diff --git a/.github/fork-manifest.txt b/.github/fork-manifest.txt
index d1559ee5b916d..098566b4a47ca 100644
--- a/.github/fork-manifest.txt
+++ b/.github/fork-manifest.txt
@@ -337,6 +337,8 @@ apps/mobile/src/native/NativeScrollViewMarker.tsx export function renderNativeSc
# Fork: legacy iPad navigation preserves sidebar destinations and native pop state.
apps/mobile/src/native/createV5StackNavigator.ios.tsx Fork:
apps/mobile/src/native/createV5StackNavigator.ios.tsx deviceType === "pad",
+apps/mobile/src/native/createV5StackNavigator.ios.test.tsx Fork:
+apps/mobile/src/native/createV5StackNavigator.ios.test.tsx vi.mock("./native-layout-metrics"
# Fork: preserve iPad Settings detail projection and native Back reconciliation.
apps/mobile/src/native/workspace-stack-projection.test.ts Fork:
@@ -745,7 +747,7 @@ packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts Effect.pr
# Fork: Use the project account credential for forge requests instead of the machine login; preserve account-scoped authorization and commit identity.
packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts Fork:
-packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts Effect.flatMap(Effect.service(SourceControlHost.AccountCredential), (account) =>
+packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts const account = yield* Effect.service(SourceControlHost.AccountCredential);
# Fork: Use the project account credential for forge requests instead of the machine login; preserve account-scoped authorization and commit identity.
packages/source-control-bitbucket/src/server/BitbucketApi.test.ts Fork:
diff --git a/.github/scripts/pr-limits.cjs b/.github/scripts/pr-limits.cjs
index 77c09785e4104..f3eb528a08042 100644
--- a/.github/scripts/pr-limits.cjs
+++ b/.github/scripts/pr-limits.cjs
@@ -100,14 +100,22 @@ function parseExemptions(text) {
}
// VOUCHED.td: one `github:login` per line, `#` comments, and `-github:login reason` to denounce.
-function vouchedLogins(text) {
- const logins = new Set();
+// A login listed both ways is an error: pr-vouch.yml's action reads its first line and
+// issue-vouch.yml its last, so no answer here would agree with both labels.
+function parseVouchList(text) {
+ const vouched = new Set();
+ const denounced = new Set();
for (const raw of text.split("\n")) {
- const entry = raw.trim().split(/\s+/)[0];
- if (entry.startsWith("github:")) logins.add(entry.slice("github:".length).toLowerCase());
+ const match = /^(-?)github:(\S+)/.exec(raw.trim());
+ if (!match) continue;
+ const login = match[2].toLowerCase();
+ const [listed, other] = match[1] ? [denounced, vouched] : [vouched, denounced];
+ if (other.has(login))
+ throw new Error(`${VOUCHED_PATH}: ${login} is both vouched and denounced`);
+ listed.add(login);
}
- if (logins.size === 0) throw new Error(`${VOUCHED_PATH}: no entries`);
- return logins;
+ if (vouched.size === 0) throw new Error(`${VOUCHED_PATH}: no entries`);
+ return { vouched, denounced };
}
function labeledAt(pr, name) {
@@ -278,7 +286,8 @@ async function enforceOpenLimit({ github, context, core, dryRun }) {
// lookups as "not vouched". Every read below throws on failure, and a throw closes nothing.
if (pr.user.type === "Bot") return;
if (parseExemptions(fs.readFileSync(EXEMPTIONS_PATH, "utf8")).has(author.toLowerCase())) return;
- if (vouchedLogins(fs.readFileSync(VOUCHED_PATH, "utf8")).has(author.toLowerCase())) return;
+ const { vouched, denounced } = parseVouchList(fs.readFileSync(VOUCHED_PATH, "utf8"));
+ if (vouched.has(author.toLowerCase())) return;
const { data: access } = await github.rest.repos.getCollaboratorPermissionLevel({
...context.repo,
username: author,
@@ -289,6 +298,21 @@ async function enforceOpenLimit({ github, context, core, dryRun }) {
const reopened = context.payload.action === "reopened";
if (reopened && context.payload.sender.login.toLowerCase() !== author.toLowerCase()) return;
+ if (denounced.has(author.toLowerCase())) {
+ if (dryRun) {
+ core.notice(`Dry run. PR #${pr.number} would close: ${author} is denounced.`);
+ return;
+ }
+ await closeWithComment(
+ github,
+ context,
+ pr.number,
+ `Closing: ${author} is banned from contributing here, so this PR will not be reviewed. See [bans](${guideLink(context, "bans")}).`,
+ );
+ core.info(`PR #${pr.number}: closed, ${author} is denounced.`);
+ return;
+ }
+
const q = `repo:${context.repo.owner}/${context.repo.repo} is:pr is:open author:${author} sort:created-asc`;
const { search } = await read(github, AUTHOR_OPEN_PRS_QUERY, { q });
// A new PR counts only the older ones, so two opened together cannot close each other.
diff --git a/.github/workflows/issue-vouch.yml b/.github/workflows/issue-vouch.yml
index bbb6e95c9ec60..d65882593c649 100644
--- a/.github/workflows/issue-vouch.yml
+++ b/.github/workflows/issue-vouch.yml
@@ -40,9 +40,14 @@ jobs:
ref: context.payload.repository.default_branch,
});
const statusByUser = new Map();
+ const listedBothWays = new Set();
for (const raw of Buffer.from(file.content, "base64").toString("utf8").split("\n")) {
const match = /^(-?)github:(\S+)/.exec(raw.trim());
- if (match) statusByUser.set(match[2].toLowerCase(), match[1] ? "denounced" : "vouched");
+ if (!match) continue;
+ const login = match[2].toLowerCase();
+ const status = match[1] ? "denounced" : "vouched";
+ if (statusByUser.has(login) && statusByUser.get(login) !== status) listedBothWays.add(login);
+ statusByUser.set(login, status);
}
const issues =
@@ -74,4 +79,32 @@ jobs:
await github.rest.issues.addLabels({ owner, repo, issue_number: issue.number, labels: [next] });
core.info(`Issue #${issue.number} (${issue.user.login}): ${status} -> ${next}`);
}
+
+ // Only a newly opened issue is closed. One filed before its author was denounced
+ // may already have a fix on the way, so the sweep leaves those to maintainers.
+ // Someone else reopening it is a maintainer keeping it open.
+ const reopenedByOther =
+ context.payload.action === "reopened" &&
+ context.payload.sender.login.toLowerCase() !== issue.user.login.toLowerCase();
+ // The PR rules refuse a list that names a login both ways, so nothing closes for one here.
+ const trusted =
+ issue.user.type === "Bot" ||
+ ["OWNER", "MEMBER", "COLLABORATOR"].includes(issue.author_association) ||
+ listedBothWays.has(issue.user.login.toLowerCase());
+ if (status === "denounced" && context.eventName === "issues" && !reopenedByOther && !trusted) {
+ await github.rest.issues.createComment({
+ owner,
+ repo,
+ issue_number: issue.number,
+ body: `Closing: ${issue.user.login} is banned from contributing here, so this issue will not be triaged. See [bans](https://github.com/${owner}/${repo}/blob/main/CONTRIBUTING.md#bans).`,
+ });
+ await github.rest.issues.update({
+ owner,
+ repo,
+ issue_number: issue.number,
+ state: "closed",
+ state_reason: "not_planned",
+ });
+ core.info(`Issue #${issue.number}: closed, ${issue.user.login} is denounced.`);
+ }
}
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 63e71dc1e250c..0c886bd493389 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -115,6 +115,9 @@ the open PR limit.
- If you make our lives harder as reviewers and maintainers, you will be banned. Examples are repeated
pings, a fight over a closure, and a second account to get around a limit.
+A banned account is denounced in [.github/VOUCHED.td](.github/VOUCHED.td). Any issue or PR it opens
+is closed when it is opened.
+
## When your PR is closed
diff --git a/apps/desktop/src/app/CodexAuthCallback.test.ts b/apps/desktop/src/app/CodexAuthCallback.test.ts
index 6d8a905885aca..e8f1ca0b80bd8 100644
--- a/apps/desktop/src/app/CodexAuthCallback.test.ts
+++ b/apps/desktop/src/app/CodexAuthCallback.test.ts
@@ -37,18 +37,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,34 +70,52 @@ 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));
diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts
index 0e7f949bc042c..f69bf965d0058 100644
--- a/apps/desktop/src/app/DesktopApp.ts
+++ b/apps/desktop/src/app/DesktopApp.ts
@@ -308,11 +308,9 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool
}
const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
- // WSL-only fallback can change the primary endpoint before readiness.
const config = yield* primaryBackend.currentConfig;
if (
!environment.isDevelopment &&
- !settings.wslOnly &&
Option.isSome(config) &&
Option.isNone(config.value.preflightFailure)
) {
diff --git a/apps/desktop/src/app/DesktopClerk.ts b/apps/desktop/src/app/DesktopClerk.ts
index 206a143128a8e..207aa17739e59 100644
--- a/apps/desktop/src/app/DesktopClerk.ts
+++ b/apps/desktop/src/app/DesktopClerk.ts
@@ -178,11 +178,12 @@ export const make = Effect.gen(function* () {
Effect.gen(function* () {
yield* electronApp.whenReady;
yield* Effect.tryPromise({
- try: () =>
+ try: (signal) =>
receiveCodexAuthCallback(
request.authorizationUrl,
(url) => runPromise(shell.openExternal(url)),
(callbackUrl) => codexAuthDeliveryUrl(request, callbackUrl),
+ signal,
),
catch: () =>
new CodexAuthCallbackError({
diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts
index 5dfde9103f152..b58b583fd6cd5 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 3240df3636e38..5db49e5f9504c 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 3a9b75b1e6c08..00497d7c0df53 100644
--- a/apps/desktop/src/app/DesktopStartupRecovery.ts
+++ b/apps/desktop/src/app/DesktopStartupRecovery.ts
@@ -219,7 +219,6 @@ export const listen: Effect.Effect<
const download = yield* updates.download;
if (!download.completed) return;
}
- // Waits for a running background check; plain install would refuse.
yield* updates.installPrepared(current.version);
return;
}
diff --git a/apps/desktop/src/app/stdioErrors.test.ts b/apps/desktop/src/app/stdioErrors.test.ts
new file mode 100644
index 0000000000000..ccfa3ed951178
--- /dev/null
+++ b/apps/desktop/src/app/stdioErrors.test.ts
@@ -0,0 +1,22 @@
+import * as NodeOS from "node:os";
+import { assert, it } from "vite-plus/test";
+
+import { handleStdioError } from "./stdioErrors.ts";
+
+const errorWithCode = (code: string, errno?: number) =>
+ Object.assign(new Error(code), { code, errno });
+const EDQUOT_ERRNO = NodeOS.constants.errno.EDQUOT;
+
+it.each(["EPIPE", "ENOSPC"])("ignores %s on console output", (code) => {
+ assert.doesNotThrow(() => handleStdioError(errorWithCode(code)));
+});
+
+// Node reports EDQUOT as UNKNOWN because libuv has no name for it.
+it.skipIf(EDQUOT_ERRNO === undefined)("ignores EDQUOT on console output", () => {
+ assert.doesNotThrow(() => handleStdioError(errorWithCode("UNKNOWN", -(EDQUOT_ERRNO ?? 0))));
+});
+
+it("rethrows other console output errors", () => {
+ assert.throws(() => handleStdioError(errorWithCode("EIO")), "EIO");
+ assert.throws(() => handleStdioError(errorWithCode("UNKNOWN", -5)), "UNKNOWN");
+});
diff --git a/apps/desktop/src/app/stdioErrors.ts b/apps/desktop/src/app/stdioErrors.ts
new file mode 100644
index 0000000000000..b23c0e89e79a8
--- /dev/null
+++ b/apps/desktop/src/app/stdioErrors.ts
@@ -0,0 +1,13 @@
+import * as NodeOS from "node:os";
+
+// libuv has no name for EDQUOT, so Node reports it as code "UNKNOWN" with the raw errno.
+const EDQUOT_ERRNO = NodeOS.constants.errno.EDQUOT;
+
+// Redirected console output can fail when its log volume is full.
+export function handleStdioError(error: unknown): void {
+ if (typeof error === "object" && error !== null) {
+ if ("code" in error && (error.code === "EPIPE" || error.code === "ENOSPC")) return;
+ if (EDQUOT_ERRNO !== undefined && "errno" in error && error.errno === -EDQUOT_ERRNO) return;
+ }
+ throw error;
+}
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
index 70f7ed87d2214..ab57d5db32372 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
@@ -385,7 +385,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";
@@ -406,8 +406,8 @@ describe("DesktopBackendConfiguration", () => {
});
return { ok: true, linuxAppRoot };
},
- probeRuntime: (_distro, root) => {
- observedProbeRoots.push(root);
+ probeRuntime: () => {
+ probeCount += 1;
return { ok: true, resolvedPath };
},
ensureNodePty: () => {
@@ -428,7 +428,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"),
@@ -523,10 +523,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(
@@ -538,9 +538,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);
@@ -553,7 +553,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`);
@@ -578,7 +578,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 5f499e6f4ee37..82f0a30a40cd9 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
@@ -424,7 +424,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f
const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive);
if (runtime.ok) {
// Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them.
- const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot);
+ const stagedProbe = yield* wslEnv.probeRuntime(runningDistro);
if (stagedProbe.ok) {
yield* wslServerTree.cleanupLegacy;
return {
@@ -437,7 +437,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f
} as const;
}
yield* Effect.logWarning(
- "The staged WSL runtime did not start; retrying from the mounted server tree.",
+ "The staged WSL runtime probe failed; retrying from the mounted server tree.",
{ reason: stagedProbe.reason },
);
stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason };
diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts
index 06a1f768f4bd4..ff5b7b8c08e4b 100644
--- a/apps/desktop/src/backend/DesktopBackendManager.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts
@@ -11,6 +11,7 @@ import {
DATABASE_MIGRATIONS_STARTED_MESSAGE,
} from "@t3tools/shared/databaseMigrationLog";
import { assert, describe, it } from "@effect/vitest";
+import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -239,6 +240,43 @@ describe("DesktopBackendManager", () => {
}),
);
+ it.effect("notices a WSL backend soon after it listens despite slow refused connects", () =>
+ Effect.gen(function* () {
+ const ready = yield* Deferred.make();
+ const exit = yield* Deferred.make();
+ const instance = yield* makeTestInstance({
+ config: { ...baseConfig, httpBaseUrl: new URL("http://172.20.84.98:3773") },
+ onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
+ spawnerLayer: Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.acquireRelease(
+ Effect.succeed(makeProcess({ exitCode: Deferred.await(exit) })),
+ () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
+ ),
+ ),
+ ),
+ // Before the server listens at 300 ms, each refused connect takes a second to fail.
+ httpClientLayer: layerHttpClient((request) =>
+ Clock.currentTimeMillis.pipe(
+ Effect.flatMap((now) =>
+ now < 300
+ ? Effect.sleep(Duration.seconds(1)).pipe(
+ Effect.as(responseForRequest(request, 503)),
+ )
+ : Effect.succeed(responseForRequest(request, 200)),
+ ),
+ ),
+ ),
+ });
+ yield* instance.start;
+ yield* TestClock.adjust(Duration.millis(600));
+
+ assert.isTrue(yield* Deferred.isDone(ready));
+ yield* instance.stop();
+ }),
+ );
+
it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined;
diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts
index 4acaa8a3c18b8..8b4f154b5d4de 100644
--- a/apps/desktop/src/backend/DesktopBackendManager.ts
+++ b/apps/desktop/src/backend/DesktopBackendManager.ts
@@ -344,8 +344,26 @@ const closeRun = (
);
};
+const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
+// Windows takes about a second to fail a refused connection to a non-loopback address such as a
+// WSL distro IP, so one sequential poller notices readiness up to a second late.
+const STAGGERED_READINESS_POLLERS = 4;
+const READINESS_POLLER_STAGGER = Duration.millis(250);
+
const waitForHttpReady = (
options: BackendProcessContext & { readonly timeout: Duration.Duration },
+): Effect.Effect => {
+ const poll = pollHttpReady(options);
+ if (LOOPBACK_HOSTNAMES.has(options.httpBaseUrl.hostname)) return poll;
+ return Effect.raceAll(
+ Array.from({ length: STAGGERED_READINESS_POLLERS }, (_, index) =>
+ Effect.sleep(Duration.times(READINESS_POLLER_STAGGER, index)).pipe(Effect.andThen(poll)),
+ ),
+ );
+};
+
+const pollHttpReady = (
+ options: BackendProcessContext & { readonly timeout: Duration.Duration },
): Effect.Effect => {
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
return waitForHttpReadyShared({
diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts
index 8e9f4320c08c7..005a1cde1224a 100644
--- a/apps/desktop/src/backend/DesktopBackendPool.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts
@@ -112,6 +112,10 @@ function layerPool(
labelRef: Ref.Ref,
options: {
readonly config?: DesktopBackendStartConfig;
+ readonly resolvePrimary?: Effect.Effect;
+ readonly onMainContentsCommand?: (
+ command: DesktopWindow.MainWindowContentsCommand,
+ ) => Effect.Effect;
readonly fileSystem?: Partial;
readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
readonly httpClient?: HttpClient.HttpClient;
@@ -180,9 +184,11 @@ function layerPool(
}),
DesktopBrowserHost.layer,
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
- resolvePrimary: options.config
- ? Effect.succeed(options.config)
- : Effect.die("unexpected primary config resolve"),
+ resolvePrimary:
+ options.resolvePrimary ??
+ (options.config
+ ? Effect.succeed(options.config)
+ : Effect.die("unexpected primary config resolve")),
resolvePrimaryLabel: Ref.get(labelRef),
resolveWsl: () => Effect.die("unexpected WSL config resolve"),
currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
@@ -190,7 +196,12 @@ function layerPool(
DesktopAppSettings.layerTest(),
DesktopState.layer,
DesktopWslEnvironment.layerTest(),
- ElectronDialog.layer,
+ Layer.succeed(ElectronDialog.ElectronDialog, {
+ pickFolder: () => Effect.die("unexpected folder picker"),
+ pickFiles: () => Effect.die("unexpected file picker"),
+ showMessageBox: () => Effect.die("unexpected message box"),
+ showErrorBox: () => Effect.void,
+ } satisfies ElectronDialog.ElectronDialog["Service"]),
ElectronApp.layer,
Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected window create"),
@@ -206,7 +217,8 @@ function layerPool(
dispatchMenuAction: () => Effect.die("unexpected menu action"),
dispatchSnapShotEvent: () => Effect.void,
zoomMain: () => Effect.die("unexpected zoom"),
- runMainContentsCommand: () => Effect.die("unexpected main contents command"),
+ runMainContentsCommand:
+ options.onMainContentsCommand ?? (() => Effect.die("unexpected main contents command")),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
@@ -478,4 +490,70 @@ describe("DesktopBackendPool", () => {
assert.equal(Option.isNone(yield* pool.get(id)), true);
}).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))),
);
+
+ it.effect("reloads a main window that read the WSL endpoint before the Windows fallback", () =>
+ Effect.gen(function* () {
+ const events: string[] = [];
+ let resolves = 0;
+ const resolvePrimary = Effect.sync(() =>
+ resolves++ === 0
+ ? {
+ ...runningConfig,
+ preflightFailure: Option.some({
+ reason: "WSL still unavailable",
+ fatal: false,
+ retryLimit: 1,
+ }),
+ }
+ : runningConfig,
+ );
+ const ready = yield* Deferred.make();
+ yield* Effect.gen(function* () {
+ const primary = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
+ yield* primary.start;
+ yield* TestClock.adjust(Duration.seconds(1));
+ yield* Deferred.await(ready);
+
+ assert.deepEqual(events, ["reload", "ready"]);
+ }).pipe(
+ Effect.provide(
+ layerPool(Ref.makeUnsafe("WSL"), {
+ resolvePrimary,
+ spawner: ChildProcessSpawner.make(() =>
+ Effect.gen(function* () {
+ const exited = yield* Deferred.make();
+ const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
+ Effect.asVoid,
+ );
+ yield* Effect.addFinalizer(() => exit);
+ return ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(123),
+ stdout: Stream.empty,
+ stderr: Stream.empty,
+ all: Stream.empty,
+ exitCode: Deferred.await(exited),
+ isRunning: Effect.succeed(true),
+ kill: () => exit,
+ stdin: Sink.drain,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ unref: Effect.succeed(Effect.void),
+ });
+ }),
+ ),
+ httpClient: HttpClient.make((request) =>
+ Effect.succeed(
+ HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
+ ),
+ ),
+ onMainContentsCommand: (command) => Effect.sync(() => void events.push(command)),
+ onReady: Effect.sync(() => void events.push("ready")).pipe(
+ Effect.andThen(Deferred.succeed(ready, undefined)),
+ Effect.asVoid,
+ ),
+ }),
+ ),
+ );
+ }),
+ );
});
diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts
index d69e1ce1427fe..62c811996b1a0 100644
--- a/apps/desktop/src/backend/DesktopBackendPool.ts
+++ b/apps/desktop/src/backend/DesktopBackendPool.ts
@@ -167,10 +167,22 @@ export const layer = Layer.effect(
// One wait at a time: each run's shutdown or readiness ends the previous run's wait.
const updateMarkerWait = yield* FiberHandle.make();
+ // The main window loads during startup and reads the primary endpoint once; a Windows fallback
+ // before the first readiness replaces the WSL endpoint it read.
+ let primaryWasReady = false;
+ let reloadMainOnReady = false;
+ const reloadStaleMain = Effect.suspend(() => {
+ primaryWasReady = true;
+ if (!reloadMainOnReady) return Effect.void;
+ reloadMainOnReady = false;
+ return desktopWindow.runMainContentsCommand("reload");
+ });
+
// Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference.
const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
function* (failure: DesktopBackendManager.PreflightFailure) {
const { reason, fatal } = failure;
+ if (!primaryWasReady) reloadMainOnReady = true;
if (!fatal) {
yield* logBackendPoolWarning(
"primary WSL preflight retry window exhausted; using Windows for this launch",
@@ -215,6 +227,7 @@ export const layer = Layer.effect(
// Absorb window errors so readiness can reset restartAttempt.
onReady: (httpBaseUrl, pid) =>
FiberHandle.run(updateMarkerWait, releaseUpdateMarker(httpBaseUrl, pid)).pipe(
+ Effect.andThen(reloadStaleMain),
Effect.andThen(desktopWindow.handleBackendReady(httpBaseUrl)),
// Only once the main window exists, so the recovery window never closes into nothing.
Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })),
diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
index e82e3afea7303..c15ce3932bb80 100644
--- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
+++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
@@ -1,11 +1,13 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { assert, describe, it } from "@effect/vitest";
+import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
+import * as Result from "effect/Result";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientRequest from "effect/http/HttpClientRequest";
import * as HttpClientResponse from "effect/http/HttpClientResponse";
@@ -238,4 +240,34 @@ describe("DesktopLocalEnvironmentAuth", () => {
assert.strictEqual(yield* Ref.get(requestCount), 1);
}).pipe(Effect.provide(TestClock.layer())),
);
+
+ it.effect("waits through a backend that stalls for 30 seconds after it is ready", () =>
+ Effect.gen(function* () {
+ const requestCount = yield* Ref.make(0);
+ const layerHttpClient = Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make((request) =>
+ Effect.gen(function* () {
+ yield* Ref.update(requestCount, (count) => count + 1);
+ const now = yield* Clock.currentTimeMillis;
+ return now < 30_000 ? yield* Effect.never : tokenResponse(request);
+ }),
+ ),
+ );
+ const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe(
+ Effect.provide(
+ DesktopLocalEnvironmentAuth.layer.pipe(
+ Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)),
+ ),
+ ),
+ );
+
+ const fiber = yield* auth.getBearerToken.pipe(Effect.result, Effect.forkChild);
+ yield* TestClock.adjust(Duration.seconds(45));
+ const result = yield* Fiber.join(fiber);
+
+ assert.isTrue(Result.isSuccess(result));
+ assert.strictEqual(yield* Ref.get(requestCount), 4);
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
});
diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
index 6c7d24623d40f..89aa3cd2a678c 100644
--- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
+++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
@@ -17,7 +17,8 @@ import * as HttpClient from "effect/http/HttpClient";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
-const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(15);
+// Each /oauth/token attempt may take 10 s, so a backend busy after ready needs several attempts.
+const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(60);
const BOOTSTRAP_TRANSIENT_RETRY_INTERVAL = Duration.millis(500);
const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
diff --git a/apps/desktop/src/electron/ElectronAudio.test.ts b/apps/desktop/src/electron/ElectronAudio.test.ts
new file mode 100644
index 0000000000000..b38d7bbb3ae47
--- /dev/null
+++ b/apps/desktop/src/electron/ElectronAudio.test.ts
@@ -0,0 +1,60 @@
+import * as Effect from "effect/Effect";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import { app } from "electron";
+import { expect, vi } from "vite-plus/test";
+import { it } from "@effect/vitest";
+import * as Fiber from "effect/Fiber";
+
+const { getAppMetrics, kill } = vi.hoisted(() => ({ getAppMetrics: vi.fn(), kill: vi.fn() }));
+vi.mock("node:process", () => ({ kill }));
+vi.mock("electron", async () => {
+ const { EventEmitter } = await import("node:events");
+ return { app: Object.assign(new EventEmitter(), { getAppMetrics }) };
+});
+
+import { restart } from "./ElectronAudio.ts";
+
+const audio = { pid: 42, type: "Utility", serviceName: "audio.mojom.AudioService" };
+
+it.effect("coalesces recovery and waits for its own audio utility to exit", () =>
+ Effect.gen(function* () {
+ getAppMetrics.mockReturnValue([
+ { pid: 1, type: "Utility", serviceName: "network.mojom.NetworkService" },
+ { pid: 2, type: "Browser", serviceName: audio.serviceName },
+ audio,
+ ]);
+ const started = Promise.withResolvers();
+ kill.mockReset().mockImplementation(() => {
+ started.resolve();
+ });
+ const pending = yield* Effect.forkChild(
+ Effect.all([restart(), restart()], { concurrency: "unbounded" }),
+ );
+ yield* Effect.promise(() => started.promise);
+ app.emit(
+ "child-process-gone",
+ {},
+ { type: "Utility", serviceName: "network.mojom.NetworkService" },
+ );
+ expect(app.listenerCount("child-process-gone")).toBe(1);
+ app.emit("child-process-gone", {}, audio);
+ expect(yield* Fiber.join(pending)).toEqual([true, true]);
+ expect(kill.mock.calls).toEqual([[42, "SIGTERM"]]);
+ expect(app.listenerCount("child-process-gone")).toBe(0);
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
+);
+
+it.effect.each(["linux", "darwin", "win32"] as const)(
+ "leaves other processes alone on %s",
+ (platform) =>
+ Effect.gen(function* () {
+ getAppMetrics.mockReturnValue([
+ { pid: 1, type: "Utility", serviceName: "network.mojom.NetworkService" },
+ ]);
+ kill.mockReset();
+ expect(yield* restart().pipe(Effect.provideService(HostProcess.Platform, platform))).toBe(
+ false,
+ );
+ expect(kill).not.toHaveBeenCalled();
+ }),
+);
diff --git a/apps/desktop/src/electron/ElectronAudio.ts b/apps/desktop/src/electron/ElectronAudio.ts
new file mode 100644
index 0000000000000..6a7f290d6fd83
--- /dev/null
+++ b/apps/desktop/src/electron/ElectronAudio.ts
@@ -0,0 +1,62 @@
+// @effect-diagnostics globalTimers:off -- The shared native restart deadline must outlive individual IPC callers.
+// @effect-diagnostics nodeBuiltinImport:off -- Only Electron's main process can restart its Chromium audio utility.
+import * as NodeProcess from "node:process";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import { app, type Details, type Event } from "electron";
+
+class AudioServiceRestartError extends Schema.TaggedError()(
+ "AudioServiceRestartError",
+ { cause: Schema.Defect() },
+) {}
+
+let pendingRestart: Promise | undefined;
+
+export const restart = Effect.fn("ElectronAudio.restart")(function* () {
+ if ((yield* HostProcess.Platform) !== "linux") return false;
+ return yield* Effect.tryPromise({
+ try: () => {
+ if (pendingRestart) return pendingRestart;
+ const audio = app
+ .getAppMetrics()
+ .find(
+ (metric) =>
+ metric.type === "Utility" && metric.serviceName === "audio.mojom.AudioService",
+ );
+ if (!audio) return Promise.resolve(false);
+ // A failed PulseAudio context survives new getUserMedia calls; Chromium reconnects when its utility exits.
+ pendingRestart = new Promise((resolve, reject) => {
+ const cleanup = () => {
+ clearTimeout(timer);
+ app.removeListener("child-process-gone", onGone);
+ };
+ const onGone = (_event: Event, details: Details) => {
+ if (details.type === "Utility" && details.serviceName === audio.serviceName) {
+ cleanup();
+ resolve(true);
+ }
+ };
+ const timer = setTimeout(() => {
+ cleanup();
+ resolve(false);
+ }, 5_000);
+ app.on("child-process-gone", onGone);
+ try {
+ NodeProcess.kill(audio.pid, "SIGTERM");
+ } catch (cause) {
+ cleanup();
+ reject(cause);
+ }
+ }).finally(() => {
+ pendingRestart = undefined;
+ });
+ return pendingRestart;
+ },
+ catch: (cause) => new AudioServiceRestartError({ cause }),
+ }).pipe(
+ Effect.catch((cause) =>
+ Effect.logWarning("Could not restart the audio service", cause).pipe(Effect.as(false)),
+ ),
+ );
+});
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
index 57d7101cf9ec7..60b72deb293a5 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -44,6 +44,7 @@ import {
getWindowFullscreenState,
openExternal,
readMedia,
+ restartAudioService,
openSystemSettings,
checkSystemPermission,
pasteAsText,
@@ -109,6 +110,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(getHostEnvironmentId);
yield* ipc.handle(getLocalEnvironmentBearerToken);
+ yield* ipc.handle(restartAudioService);
yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings);
yield* ipc.handle(getConnectionCatalog);
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
index b7bb5e579572f..9e5c7296a3a03 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -101,6 +101,7 @@ export const PREVIEW_SET_AUDIO_MUTED_CHANNEL = "desktop:preview-set-audio-muted"
export const PREVIEW_FIND_IN_PAGE_CHANNEL = "desktop:preview-find-in-page";
export const PREVIEW_STOP_FIND_IN_PAGE_CHANNEL = "desktop:preview-stop-find-in-page";
export const PREVIEW_SET_SHOWN_CHANNEL = "desktop:preview-set-shown";
+export const PREVIEW_SET_CAPTURE_DRAWN_CHANNEL = "desktop:preview-set-capture-drawn";
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
@@ -139,3 +140,5 @@ export const RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:receive-provider-
export const CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:cancel-provider-auth-callback";
export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-storage";
export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage";
+
+export const RESTART_AUDIO_SERVICE_CHANNEL = "desktop:restart-audio-service";
diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts
index cc810fee072ad..757e1e463f538 100644
--- a/apps/desktop/src/ipc/methods/preview.ts
+++ b/apps/desktop/src/ipc/methods/preview.ts
@@ -13,6 +13,7 @@ import {
DesktopPreviewScreenshotArtifactSchema,
DesktopPreviewSetAudioMutedInputSchema,
DesktopPreviewSetShownInputSchema,
+ DesktopPreviewSetCaptureDrawnInputSchema,
DesktopPreviewSetColorSchemeInputSchema,
DesktopPreviewSetZoomFactorInputSchema,
BrowserImportResult,
@@ -234,6 +235,15 @@ const setShown = DesktopIpc.makeIpcMethod({
yield* manager.setShown(tabId, shown);
}),
});
+const setCaptureDrawn = DesktopIpc.makeIpcMethod({
+ channel: IpcChannels.PREVIEW_SET_CAPTURE_DRAWN_CHANNEL,
+ payload: DesktopPreviewSetCaptureDrawnInputSchema,
+ result: Schema.Void,
+ handler: Effect.fn("desktop.ipc.preview.setCaptureDrawn")(function* ({ tabId, drawn }) {
+ const manager = yield* PreviewManager.PreviewManager;
+ yield* manager.setCaptureDrawn(tabId, drawn);
+ }),
+});
const openDevTools = tabMethod(
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
"desktop.ipc.preview.openDevTools",
@@ -488,6 +498,7 @@ export const methods = [
setZoomFactor,
setAudioMuted,
setShown,
+ setCaptureDrawn,
openDevTools,
clearCookies,
clearCache,
diff --git a/apps/desktop/src/ipc/methods/providerAuth.ts b/apps/desktop/src/ipc/methods/providerAuth.ts
index fbde6a409f3f2..d7f432815d2ae 100644
--- a/apps/desktop/src/ipc/methods/providerAuth.ts
+++ b/apps/desktop/src/ipc/methods/providerAuth.ts
@@ -23,8 +23,13 @@ export const receiveProviderAuthCallback = DesktopIpc.makeIpcMethod({
const context = yield* Effect.context();
const runPromise = Effect.runPromiseWith(context);
const callbackUrl = yield* Effect.tryPromise({
- try: () =>
- receiveCodexAuthCallback(authorizationUrl, (url) => runPromise(shell.openExternal(url))),
+ try: (signal) =>
+ receiveCodexAuthCallback(
+ authorizationUrl,
+ (url) => runPromise(shell.openExternal(url)),
+ undefined,
+ signal,
+ ),
catch: () =>
new CodexAuthCallbackError({
detail:
diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts
index fbeda6d2f2dcd..de202529c4113 100644
--- a/apps/desktop/src/ipc/methods/window.test.ts
+++ b/apps/desktop/src/ipc/methods/window.test.ts
@@ -1,6 +1,8 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import type { ManagedPolicyLimits } from "@t3tools/contracts";
+import { EDITORS, REMOTE_CAPABLE_EDITOR_IDS } from "@t3tools/contracts";
+import { resolveEditorCommand } from "@t3tools/shared/editor";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
import * as FileSystem from "effect/FileSystem";
@@ -517,3 +519,108 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
assert.include(editors, "webstorm");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
+
+describe("probeRemoteEditors PATH scan", () => {
+ const platform = HostProcess.Platform.defaultValue();
+ const launcherName = (command: string) => (platform === "win32" ? `${command}.cmd` : command);
+
+ const makeFakePath = Effect.fnUntraced(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-probe-path-" });
+ const dirs = ["a", "b", "c", "d"].map((name) => path.join(root, name));
+ for (const dir of dirs) yield* fs.makeDirectory(dir, { recursive: true });
+ // Launchers in different PATH directories, deliberately not in REMOTE_CAPABLE_EDITOR_IDS order.
+ for (const [dir, command] of [
+ [dirs[2]!, "webstorm"],
+ [dirs[0]!, "cursor"],
+ [dirs[3]!, "code"],
+ [dirs[1]!, "zeditor"],
+ ] as const) {
+ const file = path.join(dir, launcherName(command));
+ yield* fs.writeFileString(file, "#!/bin/sh\n");
+ if (platform !== "win32") yield* fs.chmod(file, 0o755);
+ }
+ return {
+ root,
+ env: {
+ HOME: root,
+ USERPROFILE: root,
+ PATH: dirs.join(platform === "win32" ? ";" : ":"),
+ PATHEXT: ".COM;.EXE;.BAT;.CMD",
+ },
+ };
+ });
+
+ const countingFileSystem = (counter: { stat: number; reads: Map }) =>
+ Layer.effect(
+ FileSystem.FileSystem,
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ return FileSystem.FileSystem.of({
+ ...fs,
+ stat: (target) => {
+ counter.stat += 1;
+ return fs.stat(target);
+ },
+ readDirectory: (target, options) => {
+ counter.reads.set(target, (counter.reads.get(target) ?? 0) + 1);
+ return fs.readDirectory(target, options);
+ },
+ });
+ }),
+ ).pipe(Layer.provideMerge(NodeServices.layer));
+
+ const serialReference = (env: Record) =>
+ Effect.gen(function* () {
+ const available: Array = [];
+ for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
+ const editor = EDITORS.find((candidate) => candidate.id === editorId);
+ if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) {
+ available.push(editorId);
+ }
+ }
+ return available;
+ });
+
+ it.effect("reads each PATH directory once instead of stat-ing every candidate per editor", () =>
+ Effect.gen(function* () {
+ const { env: baseEnv } = yield* makeFakePath();
+ const delimiter = platform === "win32" ? ";" : ":";
+ const uncachedCounter = { stat: 0, reads: new Map() };
+ const cachedCounter = { stat: 0, reads: new Map() };
+ const uncachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` };
+ const cachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` };
+ const uncached = yield* serialReference(uncachedEnv).pipe(
+ Effect.provide(countingFileSystem(uncachedCounter)),
+ );
+ const cached = yield* probeRemoteEditors
+ .handler(undefined)
+ .pipe(
+ Effect.provideService(HostProcess.Environment, cachedEnv),
+ Effect.provideService(HostProcess.Platform, platform),
+ Effect.provide(countingFileSystem(cachedCounter)),
+ );
+ // The host can add editors from app folders the fixture can't redirect (e.g. /Applications).
+ const fixtureEditors = ["cursor", "vscode", "zed", "webstorm"];
+ assert.deepStrictEqual(
+ uncached.filter((id) => fixtureEditors.includes(id)),
+ fixtureEditors,
+ );
+ assert.deepStrictEqual(cached, uncached);
+ assert.isAbove(uncachedCounter.stat, 0);
+ // On every platform the probe lists each PATH directory at most once. Only PATH entries count:
+ // resolveEditorCommand also reads app folders such as /Applications on macOS.
+ const pathReads = cachedEnv.PATH.split(delimiter)
+ .filter((entry) => entry.length > 0)
+ .map((entry) => cachedCounter.reads.get(entry) ?? 0);
+ assert.isAbove(Math.max(...pathReads), 0);
+ assert.isAtMost(Math.max(...pathReads), 1);
+ // Without the listings, Windows stats every PATH entry x PATHEXT candidate for each editor;
+ // elsewhere there is no PATHEXT, so the stat count is about the same either way.
+ if (platform === "win32") {
+ assert.isBelow(cachedCounter.stat, uncachedCounter.stat / 2);
+ }
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+});
diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts
index cee92e1ead38c..38887ec71d906 100644
--- a/apps/desktop/src/ipc/methods/window.ts
+++ b/apps/desktop/src/ipc/methods/window.ts
@@ -17,6 +17,7 @@ import {
} from "@t3tools/contracts";
import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon";
import { resolveEditorCommand } from "@t3tools/shared/editor";
+import { withPathDirectoryListings } from "@t3tools/shared/shell";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment";
import * as FileSystem from "effect/FileSystem";
@@ -36,6 +37,7 @@ import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import * as ElectronApp from "../../electron/ElectronApp.ts";
+import * as ElectronAudio from "../../electron/ElectronAudio.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
import * as ElectronShell from "../../electron/ElectronShell.ts";
@@ -427,20 +429,26 @@ export const openSystemSettings = DesktopIpc.makeIpcMethod({
}),
});
+const REMOTE_EDITOR_PROBE_CONCURRENCY = 8;
+
export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
payload: Schema.Undefined,
result: Schema.Array(EditorId),
handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
- const available: Array = [];
const env = yield* HostProcess.Environment;
- for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
- const editor = EDITORS.find((editor) => editor.id === editorId);
- if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) {
- available.push(editorId);
- }
- }
- return available;
+ // Shared listings stop each editor re-stating every PATH entry x PATHEXT candidate on Windows.
+ const resolved = yield* Effect.forEach(
+ REMOTE_CAPABLE_EDITOR_IDS,
+ (editorId) => {
+ const editor = EDITORS.find((editor) => editor.id === editorId);
+ return editor
+ ? resolveEditorCommand(editor, env).pipe(Effect.map(Option.isSome))
+ : Effect.succeed(false);
+ },
+ { concurrency: REMOTE_EDITOR_PROBE_CONCURRENCY },
+ ).pipe(withPathDirectoryListings);
+ return REMOTE_CAPABLE_EDITOR_IDS.filter((_, index) => resolved[index]);
}),
});
@@ -588,3 +596,10 @@ export const checkSystemPermission = DesktopIpc.makeIpcMethod({
return yield* Effect.promise(check);
}),
});
+
+export const restartAudioService = DesktopIpc.makeIpcMethod({
+ channel: IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL,
+ payload: Schema.Void,
+ result: Schema.Boolean,
+ handler: ElectronAudio.restart,
+});
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 003009f7190fa..432577917a3ea 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -1,8 +1,8 @@
import * as MacPermissions from "./permissions/MacPermissions.ts";
+import { handleStdioError } from "./app/stdioErrors.ts";
+
for (const stream of [process.stdout, process.stderr]) {
- stream.on("error", (err: NodeJS.ErrnoException) => {
- if (err.code !== "EPIPE") throw err;
- });
+ stream.on("error", handleStdioError);
}
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index e0ac5f2161051..ba9c17aae2695 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -115,6 +115,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL) === true,
getPathForFile: (file: File) => webUtils.getPathForFile(file),
getClientPlatform: () => clientPlatform,
+ restartAudioService: () => ipcRenderer.invoke(IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL),
setNotificationBadge: (badge) =>
ipcRenderer.invoke(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, badge),
onNotificationBadgeClear: (listener) => {
@@ -414,6 +415,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(IpcChannels.PREVIEW_STOP_FIND_IN_PAGE_CHANNEL, { tabId }),
setShown: (tabId, shown) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_SHOWN_CHANNEL, { tabId, shown }),
+ setCaptureDrawn: (tabId, drawn) =>
+ ipcRenderer.invoke(IpcChannels.PREVIEW_SET_CAPTURE_DRAWN_CHANNEL, { tabId, drawn }),
openDevTools: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
listBrowserImportSources: () => ipcRenderer.invoke(IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL),
diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts
index 92ab35320dab7..eb4dd3143eefb 100644
--- a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts
+++ b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts
@@ -358,6 +358,29 @@ describe("readChromiumCookieDatabase", () => {
}).pipe(Effect.provide(NodeServices.layer)),
);
+ it.effect("reads a cookie database the browser has emptied as having no cookies", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const directory = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3code-chromium-cookies-",
+ });
+ const filename = `${directory}/Cookies`;
+ yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`create table scratch (id integer)`;
+ yield* sql`drop table scratch`;
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
+
+ const result = yield* readChromiumCookieDatabase(
+ filename,
+ { cbcV10: Buffer.from("0123456789abcdef") },
+ "darwin",
+ );
+
+ expect(result).toEqual({ cookies: [], undecryptable: 0, undecryptableHosts: [] });
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
+ );
+
it.effect("skips partitioned cookies without breaking pre-CHIPS schemas", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts
index 63fef9fb3c808..91cbfa03aac7d 100644
--- a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts
+++ b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts
@@ -181,6 +181,10 @@ export const readChromiumCookieDatabase = Effect.fn("ChromiumCookies.readChromiu
function* (snapshotPath: string, keys: ChromiumKeyMaterial, platform: NodeJS.Platform) {
const result = yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
+ // Chromium razes a damaged jar to a file with no tables and rebuilds it on its next write.
+ const tables =
+ yield* sql`select 1 from sqlite_master where type = 'table' and name = 'cookies'`;
+ if (tables.length === 0) return { rows: [], schemaVersion: 0 };
const schemaVersion = yield* sql`select value from meta where key = 'version' limit 1`.pipe(
Effect.flatMap(decodeSchemaVersion),
Effect.map(([row]) => row.value),
diff --git a/apps/desktop/src/preview/BrowserImport/Sources.ts b/apps/desktop/src/preview/BrowserImport/Sources.ts
index 20a35752ed979..6ecd546a1ad57 100644
--- a/apps/desktop/src/preview/BrowserImport/Sources.ts
+++ b/apps/desktop/src/preview/BrowserImport/Sources.ts
@@ -345,6 +345,12 @@ const countProfileCookies = Effect.fnUntraced(function* (
if (database === undefined) return undefined;
return yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
+ // readChromiumCookieDatabase imports a razed jar as empty; Firefox has no such reader guard.
+ if (definition.engine !== "firefox") {
+ const tables =
+ yield* sql`select 1 from sqlite_master where type = 'table' and name = 'cookies'`;
+ if (tables.length === 0) return 0;
+ }
const rows =
definition.engine === "firefox"
? yield* sql`select count(*) as count from moz_cookies where originAttributes = ''`
diff --git a/apps/desktop/src/preview/CdpRelay.test.ts b/apps/desktop/src/preview/CdpRelay.test.ts
index ccc2b868720b4..564b4dc57d6f4 100644
--- a/apps/desktop/src/preview/CdpRelay.test.ts
+++ b/apps/desktop/src/preview/CdpRelay.test.ts
@@ -9,6 +9,7 @@ import {
const makeTarget = (
send: CdpRelayTarget["send"],
setDownloadDirectory: CdpRelayTarget["setDownloadDirectory"] = () => {},
+ ackScreencastFrame: CdpRelayTarget["ackScreencastFrame"] = () => {},
): CdpRelayTarget => ({
send,
targetId: async () => "GUEST-TARGET",
@@ -17,6 +18,7 @@ const makeTarget = (
userAgent: () => "Electron",
setDownloadDirectory,
receivesScreencast: () => true,
+ ackScreencastFrame,
});
const makeRelay = (target: CdpRelayTarget, write: (raw: string) => void) =>
@@ -138,9 +140,13 @@ describe("CDP relay", () => {
describe("CDP relay extra sessions", () => {
it("gives a second page session the page's commands and events", async () => {
- const send = vi.fn(async () => ({}));
+ const send = vi.fn(async () => ({}));
const written: Array> = [];
- const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
+ const nativeAcks: Array = [];
+ const relay = makeRelay(
+ makeTarget(send, undefined, (frameId) => nativeAcks.push(frameId)),
+ (raw) => written.push(JSON.parse(raw)),
+ );
relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
await settle();
@@ -170,8 +176,63 @@ describe("CDP relay extra sessions", () => {
await settle();
expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined, extra);
written.length = 0;
- relay.event("Page.screencastFrame", { data: "x" }, undefined);
- expect(written.map((m) => m["sessionId"])).toEqual(["t3-preview-page", extra]);
+ const frame = (frameId: number) =>
+ relay.event("Page.screencastFrame", { data: "x", sessionId: frameId }, undefined);
+ const ack = (sessionId: string, frameId: number) =>
+ relay.receive(
+ JSON.stringify({
+ id: 6,
+ method: "Page.screencastFrameAck",
+ params: { sessionId: frameId },
+ sessionId,
+ }),
+ );
+ const delivered = () => {
+ const frames = written
+ .filter((m) => m["method"])
+ .map((m) => [m["sessionId"], (m["params"] as { sessionId?: number }).sessionId]);
+ written.length = 0;
+ return frames;
+ };
+ frame(1);
+ expect(delivered()).toEqual([
+ ["t3-preview-page", 1],
+ [extra, 1],
+ ]);
+ // A session that has not acknowledged its frame gets only the newest one, on its ack.
+ for (let i = 2; i < 100; i++) frame(i);
+ expect(delivered()).toEqual([]);
+ // Frames every session is busy for stay unacknowledged, so Chromium pauses at its in-flight limit.
+ expect(nativeAcks).toEqual([1]);
+ ack(extra, 1);
+ await settle();
+ expect(delivered()).toEqual([[extra, 99]]);
+ // Each consumer ack lets Chromium send one more frame.
+ expect(nativeAcks).toEqual([1, 2]);
+ ack(extra, 99);
+ await settle();
+ expect(delivered()).toEqual([]);
+ expect(nativeAcks).toEqual([1, 2, 3]);
+ frame(100);
+ expect(delivered()).toEqual([[extra, 100]]);
+ ack(extra, 99);
+ await settle();
+ frame(101);
+ expect(delivered()).toEqual([]);
+ expect(send.mock.calls.some(([method]) => method === "Page.screencastFrameAck")).toBe(false);
+ // A restart keeps the unacknowledged frame's slot until its own acknowledgement.
+ relay.receive(JSON.stringify({ id: 7, method: "Page.stopScreencast", sessionId: extra }));
+ relay.receive(JSON.stringify({ id: 8, method: "Page.startScreencast", sessionId: extra }));
+ await settle();
+ delivered();
+ frame(102);
+ expect(delivered()).toEqual([]);
+ ack(extra, 100);
+ await settle();
+ expect(delivered()).toEqual([[extra, 102]]);
+ // Other events still reach a session while its frame is unacknowledged.
+ relay.event("Page.loadEventFired", { timestamp: 1 }, undefined);
+ expect(delivered().map(([session]) => session)).toEqual(["t3-preview-page", extra]);
});
});
diff --git a/apps/desktop/src/preview/CdpRelay.ts b/apps/desktop/src/preview/CdpRelay.ts
index 658e1cf70623d..e9f3cf509b446 100644
--- a/apps/desktop/src/preview/CdpRelay.ts
+++ b/apps/desktop/src/preview/CdpRelay.ts
@@ -11,6 +11,8 @@ export interface CdpRelayTarget {
readonly sessionDetached?: (owner: string) => void;
/** Whether a page session, by owner as `send` names it, gets the page's screencast frames. */
readonly receivesScreencast: (owner: string | undefined) => boolean;
+ /** Acknowledges a native screencast frame, letting Chromium send the next one. */
+ readonly ackScreencastFrame: (frameId: number) => void;
/** The page's own CDP target id; Playwright keys the main frame by it. */
readonly targetId: () => Promise;
readonly url: () => string;
@@ -103,6 +105,20 @@ export function createCdpRelayConnection(
let downloadEventsEnabled = false;
/** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */
const sessions = new Map([[PAGE_SESSION_ID, "page"]]);
+ // Each page session holds one unacknowledged frame and keeps the newest one skipped meanwhile.
+ const unackedFrames = new Map();
+ const skippedFrames = new Map>();
+ // Chromium keeps a few frames in flight and reuses one frame id per run, so pacing it means
+ // leaving frames every session is busy for unacknowledged and releasing one per consumer ack.
+ const heldNativeFrames: Array = [];
+ const releaseHeldFramesWithoutHolders = () => {
+ if (skippedFrames.size === 0)
+ for (const frameId of heldNativeFrames.splice(0)) target.ackScreencastFrame(frameId);
+ };
+ const sendFrame = (sessionId: string, params: Record) => {
+ unackedFrames.set(sessionId, params["sessionId"] as number);
+ send({ method: "Page.screencastFrame", params, sessionId });
+ };
let sessionSequence = 0;
const newSession = (kind: "browser" | "page") => {
const sessionId = `t3-preview-${kind}-${++sessionSequence}`;
@@ -170,6 +186,9 @@ export function createCdpRelayConnection(
const sessionId = command.params?.["sessionId"];
if (typeof sessionId === "string" && sessionId !== PAGE_SESSION_ID) {
sessions.delete(sessionId);
+ unackedFrames.delete(sessionId);
+ skippedFrames.delete(sessionId);
+ releaseHeldFramesWithoutHolders();
target.sessionDetached?.(sessionId);
}
return {};
@@ -202,6 +221,27 @@ export function createCdpRelayConnection(
}
// Playwright asks for this on every page; the host emulates focus only while it is in use.
if (command.method === "Emulation.setFocusEmulationEnabled") return Promise.resolve({});
+ if (command.method === "Page.screencastFrameAck" && child === undefined) {
+ // A restart keeps the slot too, or restarting would let frames past an unacknowledged one.
+ const sessionId = command.sessionId!;
+ if (unackedFrames.get(sessionId) === command.params?.["sessionId"]) {
+ unackedFrames.delete(sessionId);
+ const skipped = skippedFrames.get(sessionId);
+ skippedFrames.delete(sessionId);
+ if (
+ skipped !== undefined &&
+ target.receivesScreencast(sessionId === PAGE_SESSION_ID ? undefined : sessionId)
+ )
+ sendFrame(sessionId, skipped);
+ const released = heldNativeFrames.shift();
+ if (released !== undefined) target.ackScreencastFrame(released);
+ }
+ return Promise.resolve({});
+ }
+ if (command.method === "Page.stopScreencast" && child === undefined) {
+ skippedFrames.delete(command.sessionId!);
+ releaseHeldFramesWithoutHolders();
+ }
// The shared debugger keeps Runtime enabled after an earlier connection, and a repeated
// enable reports no existing contexts; Playwright waits for them, so reset once per connection.
if (command.method === "Runtime.enable" && child === undefined) {
@@ -262,15 +302,29 @@ export function createCdpRelayConnection(
send({ method, params, sessionId });
return;
}
- for (const [id, kind] of sessions) {
- if (kind !== "page") continue;
- if (
- method === "Page.screencastFrame" &&
- !target.receivesScreencast(id === PAGE_SESSION_ID ? undefined : id)
- )
- continue;
- send({ method, params, sessionId: id });
+ if (method === "Page.screencastFrame") {
+ const frame = (params ?? {}) as Record;
+ const frameId = frame["sessionId"];
+ if (typeof frameId !== "number") return;
+ let held = false;
+ let delivered = false;
+ for (const [id, kind] of sessions) {
+ if (kind !== "page") continue;
+ if (!target.receivesScreencast(id === PAGE_SESSION_ID ? undefined : id)) continue;
+ if (unackedFrames.has(id)) {
+ skippedFrames.set(id, frame);
+ held = true;
+ } else {
+ sendFrame(id, frame);
+ delivered = true;
+ }
+ }
+ if (held && !delivered) heldNativeFrames.push(frameId);
+ else target.ackScreencastFrame(frameId);
+ return;
}
+ for (const [id, kind] of sessions)
+ if (kind === "page") send({ method, params, sessionId: id });
},
};
}
diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts
index d6f25d66aa810..8e96129293fc8 100644
--- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts
+++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts
@@ -26,6 +26,11 @@ const decodeCdpMessage = Schema.decodeUnknownSync(
),
);
const key = { threadId: "thread-1", tabId: "tab-1" };
+
+/** A host whose client already draws `key` at full detail, so its screenshots go out at once. */
+const makeDrawnHost = Effect.tap(DesktopBrowserHost.make, (host) =>
+ Effect.sync(() => host.setCaptureDrawn(key, true)),
+);
/** Sends a page command whose id the fake debugger records as it receives it. */
const command = (
host: DesktopBrowserHost.DesktopBrowserHost["Service"],
@@ -172,7 +177,7 @@ const watchPainting = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) =
describe("DesktopBrowserHost", () => {
it.effect("announces tabs already attached to a backend that starts later", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
host.attach(key, makeDebuggee().tab);
expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]);
@@ -182,7 +187,7 @@ describe("DesktopBrowserHost", () => {
it.effect("announces a guest still loading its first page only once that page is up", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const loading = makeDebuggee({ loading: true });
const other = { ...key, tabId: "tab-2" };
const reader = yield* takeEvents(host, 3).pipe(Effect.forkScoped);
@@ -205,7 +210,7 @@ describe("DesktopBrowserHost", () => {
"keeps a loading guest unannounced across a replaced navigation and a new backend",
() =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const loading = makeDebuggee({ loading: true });
const other = { ...key, tabId: "tab-2" };
host.attach(key, loading.tab);
@@ -227,7 +232,7 @@ describe("DesktopBrowserHost", () => {
"announces a first page that never comes up, but never a tab closed or destroyed first",
() =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const closed = { ...key, tabId: "tab-2" };
const destroyed = { ...key, tabId: "tab-3" };
const destroyedGuest = makeDebuggee({ loading: true });
@@ -247,7 +252,7 @@ describe("DesktopBrowserHost", () => {
it.effect("re-sends shown to a backend that starts later and when a tab attaches again", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
host.attach(key, makeDebuggee().tab);
host.setShown(key, true);
const reader = yield* takeEvents(host, 5).pipe(Effect.forkScoped);
@@ -268,7 +273,7 @@ describe("DesktopBrowserHost", () => {
it.effect("replays an explicit hidden report before announcing another tab", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const other = { ...key, tabId: "tab-2" };
host.setShown(key, false);
host.attach(key, makeDebuggee().tab);
@@ -285,7 +290,7 @@ describe("DesktopBrowserHost", () => {
it.effect("drops replies from a relay the server released", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const reader = yield* takeEvents(host, 2).pipe(Effect.forkScoped);
@@ -313,7 +318,7 @@ describe("DesktopBrowserHost", () => {
it.effect("sends a page one screenshot at a time", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -330,9 +335,38 @@ describe("DesktopBrowserHost", () => {
}),
);
+ it.effect(
+ "sends a screenshot once the client draws the guest at full detail, or soon after",
+ () =>
+ Effect.gen(function* () {
+ const host = yield* DesktopBrowserHost.make;
+ const debuggee = makeDebuggee();
+ host.attach(key, debuggee.tab);
+ const replies = yield* watchReplies(host);
+
+ yield* command(host, 1, "Page.captureScreenshot");
+ yield* settle;
+ expect(debuggee.sent).toEqual([]);
+ host.setCaptureDrawn(key, true);
+ yield* settle;
+ expect(debuggee.sent).toEqual([1]);
+ debuggee.releaseFirst();
+ expect(yield* Queue.take(replies)).toBe(1);
+
+ // A client that never draws, such as a hidden window, only delays the capture.
+ host.setCaptureDrawn(key, false);
+ yield* command(host, 2, "Page.captureScreenshot");
+ yield* settle;
+ expect(debuggee.sent).toEqual([1]);
+ yield* TestClock.adjust("1 second");
+ yield* settle;
+ expect(debuggee.sent).toEqual([1, 2]);
+ }).pipe(Effect.scoped),
+ );
+
it.effect("stops waiting on a screenshot the page navigated away from", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -357,7 +391,7 @@ describe("DesktopBrowserHost", () => {
it.effect("drops screenshots a released relay left waiting", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -377,7 +411,7 @@ describe("DesktopBrowserHost", () => {
it.effect("emulates focus while the server drives a guest, then lets a hidden one throttle", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -408,7 +442,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a guest focused while a command it is running is still pending", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -429,7 +463,7 @@ describe("DesktopBrowserHost", () => {
it.effect("lets a guest throttle once Chromium can no longer answer its pending command", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -451,7 +485,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a guest focused for the screenshot a navigation lets start", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -467,7 +501,7 @@ describe("DesktopBrowserHost", () => {
it.effect("never sends a screenshot a navigation superseded while focus was changing", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee({ deferFocus: true });
host.attach(key, debuggee.tab);
@@ -484,7 +518,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a guest focused when its turn starts after the agent's first command", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const turn = (active: boolean) =>
@@ -506,7 +540,7 @@ describe("DesktopBrowserHost", () => {
it.effect("lets a guest throttle through a turn that only sent it housekeeping", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
yield* host.handleCommandLine(
@@ -535,7 +569,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a guest the agent used focused through its turn's pauses", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const turn = (active: boolean) =>
@@ -563,7 +597,7 @@ describe("DesktopBrowserHost", () => {
"ends a command's hold with the turn that sent it, even if Chromium never answers",
() =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
yield* host.handleCommandLine(
@@ -584,7 +618,7 @@ describe("DesktopBrowserHost", () => {
it.effect("ends the agent's own session's holds with its turn, but not a viewer's stream", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -617,7 +651,7 @@ describe("DesktopBrowserHost", () => {
it.effect("paints for a screenshot queued behind one its viewer abandoned mid-capture", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -655,7 +689,7 @@ describe("DesktopBrowserHost", () => {
it.effect("stops painting for a queued screenshot once its session detaches", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -694,7 +728,7 @@ describe("DesktopBrowserHost", () => {
it.effect("never sends a screenshot whose session detached while focus was changing", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee({ deferFocus: true });
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -718,7 +752,7 @@ describe("DesktopBrowserHost", () => {
it.effect("holds no focus for a screenshot still queued when the agent's turn ends", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const painting = yield* watchPainting(host);
@@ -748,7 +782,7 @@ describe("DesktopBrowserHost", () => {
it.effect("lets a guest throttle when Chromium refuses a viewer's screencast", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee({ refuse: (method) => method === "Page.startScreencast" });
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -769,7 +803,7 @@ describe("DesktopBrowserHost", () => {
it.effect("lets a guest throttle after a person's input through a viewer that then closed", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -798,7 +832,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a page's screencast when a child session's screencast is refused", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee({
refuse: (method, sessionId) => method === "Page.startScreencast" && sessionId !== undefined,
});
@@ -820,7 +854,7 @@ describe("DesktopBrowserHost", () => {
it.effect("ignores a screencast that arrives on a session after it detached", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -846,7 +880,7 @@ describe("DesktopBrowserHost", () => {
it.effect("lets a guest throttle once the session waiting on its command detaches", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -873,7 +907,7 @@ describe("DesktopBrowserHost", () => {
it.effect("never sends a screenshot queued by a session that has since detached", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -904,7 +938,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a streamed guest focused until its screencast ends", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -933,7 +967,7 @@ describe("DesktopBrowserHost", () => {
it.effect("keeps a guest focused while any of its screencasts runs", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -965,7 +999,7 @@ describe("DesktopBrowserHost", () => {
it.effect("paints a hidden guest only while the screenshot it is taking is pending", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const painting = yield* watchPainting(host);
@@ -991,7 +1025,7 @@ describe("DesktopBrowserHost", () => {
it.effect("stops painting for a screenshot Chromium never answers once its document goes", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const painting = yield* watchPainting(host);
@@ -1036,7 +1070,7 @@ describe("DesktopBrowserHost", () => {
it.effect("paints a streamed guest until its last screencast ends", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -1157,6 +1191,13 @@ describe("DesktopBrowserHost", () => {
debuggee.refuse(6);
debuggee.release();
expect([yield* Queue.take(replies), yield* Queue.take(replies)].toSorted()).toEqual([5, 6]);
+ yield* raw({
+ id: 7,
+ method: "Page.screencastFrameAck",
+ params: { sessionId: 1 },
+ sessionId: "t3-preview-page-1",
+ });
+ expect(yield* Queue.take(replies)).toBe(7);
yield* settle;
frames.length = 0;
debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 2 });
@@ -1236,7 +1277,7 @@ describe("DesktopBrowserHost", () => {
it.effect("saves a server tab's download under its CDP guid where the server asked", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const replies = yield* watchReplies(host);
@@ -1271,7 +1312,7 @@ describe("DesktopBrowserHost", () => {
it.effect("tells a download the person clicked from one the agent's input started", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
@@ -1335,7 +1376,7 @@ describe("DesktopBrowserHost", () => {
it.effect("detaches only the tab whose CDP event is too large to relay", () =>
Effect.gen(function* () {
- const host = yield* DesktopBrowserHost.make;
+ const host = yield* makeDrawnHost;
const tabs = [makeDebuggee({ deferFocus: true }), makeDebuggee()];
const send = vi.spyOn(tabs[0]!.tab.debugger, "sendCommand");
const keys = [key, { threadId: "thread-2", tabId: "tab-2" }];
diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts
index 296be2fa6709f..ce5d7074a786c 100644
--- a/apps/desktop/src/preview/DesktopBrowserHost.ts
+++ b/apps/desktop/src/preview/DesktopBrowserHost.ts
@@ -30,6 +30,8 @@ const AGENT_INPUT_WINDOW_MS = 5_000;
/** A viewer's pointer travelling over the stream activates nothing on the page. */
const POINTER_TRAVEL = new Set(["mouseMoved", "mouseWheel"]);
const FOCUS_IDLE = "5 seconds";
+/** How long a screenshot waits for the client to draw its guest at full detail. */
+const CAPTURE_DRAW_WAIT = "1 second";
/** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */
const FIRST_PAGE_TIMEOUT = "5 seconds";
const ERR_ABORTED = -3;
@@ -101,6 +103,8 @@ export class DesktopBrowserHost extends Context.Service<
readonly detach: (key: DesktopBrowserTabKey) => void;
readonly loadFailed: (key: DesktopBrowserTabKey, failure: PreviewAutomationLoadError) => void;
readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void;
+ /** Whether the client draws the guest at full detail while it is captured. */
+ readonly setCaptureDrawn: (key: DesktopBrowserTabKey, drawn: boolean | undefined) => void;
readonly humanStartedDownload: (source: Electron.WebContents) => boolean;
/** Whether what the page does now follows the agent's input, not a viewer's. */
readonly agentLedPage: (source: Electron.WebContents) => boolean;
@@ -138,6 +142,8 @@ export const make = Effect.gen(function* () {
// Kept apart from attachment: the renderer can show a webview before its debugger attaches,
// and the server forgets `shown` on detach, for example while DevTools holds the debugger.
const shownTabs = new Map();
+ const drawnTabs = new Set();
+ const drawWaiters = new Map void>>();
const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event));
const nextScreenshot = (tab: AttachedTab) => {
@@ -266,12 +272,32 @@ export const make = Effect.gen(function* () {
});
};
+ /**
+ * A scaled guest rasters at its on-screen size until the client draws it at full detail,
+ * and a screenshot taken before that copies the blurred frame. A client that cannot draw
+ * (a hidden window, say) only delays the capture.
+ */
+ const whenDrawn = (tab: AttachedTab) =>
+ new Promise((resolve) => {
+ const id = keyOf(tab.key);
+ const waiters = drawWaiters.get(id) ?? new Set();
+ drawWaiters.set(id, waiters);
+ const done = () => {
+ waiters.delete(done);
+ if (waiters.size === 0 && drawWaiters.get(id) === waiters) drawWaiters.delete(id);
+ resolve();
+ };
+ waiters.add(done);
+ runFork(Effect.sleep(CAPTURE_DRAW_WAIT).pipe(Effect.andThen(Effect.sync(done))));
+ });
+
/** Chromium answers a capture, and frees its wake lock, only once the guest paints a frame. */
const paintUntilAnswered = (tab: AttachedTab, send: () => Promise) => {
const sent = {};
tab.capturing.add(sent);
syncPainting(tab);
- return send().finally(() => {
+ // Sent at once when already drawn, so it keeps its place among the commands after it.
+ return (drawnTabs.has(keyOf(tab.key)) ? send() : whenDrawn(tab).then(send)).finally(() => {
tab.capturing.delete(sent);
syncPainting(tab);
});
@@ -368,12 +394,15 @@ export const make = Effect.gen(function* () {
// Waits for focus emulation; insertText and other non-CDP input would not queue behind it.
const forward = (current?: () => boolean) => {
const change = tab.focusChange;
- const run = () =>
- tab.relay !== relay || (current !== undefined && !current())
+ const stale = () => tab.relay !== relay || (current !== undefined && !current());
+ const sendUnlessStale = () =>
+ stale()
? Promise.reject(new Error("The page this screenshot was for has moved on."))
- : current === undefined
- ? send(method, params, sessionId)
- : paintUntilAnswered(tab, () => send(method, params, sessionId));
+ : send(method, params, sessionId);
+ const run = () =>
+ current === undefined || stale()
+ ? sendUnlessStale()
+ : paintUntilAnswered(tab, sendUnlessStale);
return change === null ? run() : change.then(run);
};
return method === "Page.captureScreenshot"
@@ -421,6 +450,10 @@ export const make = Effect.gen(function* () {
dropSessionHolds(tab, owner);
},
receivesScreencast: (owner) => tab.screencasts.has(owner),
+ ackScreencastFrame: (frameId) =>
+ void debuggee
+ .sendCommand("Page.screencastFrameAck", { sessionId: frameId })
+ .catch(() => {}),
targetId: () =>
debuggee
.sendCommand("Target.getTargetInfo")
@@ -583,6 +616,17 @@ export const make = Effect.gen(function* () {
if (tabs.get(id)?.stopWaiting === null) emit({ type: "shown", ...key, shown });
};
+ const setCaptureDrawn = (key: DesktopBrowserTabKey, drawn: boolean | undefined) => {
+ const id = keyOf(key);
+ if (!drawn) {
+ drawnTabs.delete(id);
+ return;
+ }
+ drawnTabs.add(id);
+ for (const done of drawWaiters.get(id) ?? []) done();
+ drawWaiters.delete(id);
+ };
+
const loadFailed: DesktopBrowserHost["Service"]["loadFailed"] = (key, failure) => {
if (tabs.has(keyOf(key))) emit({ type: "loadFailed", ...key, ...failure });
};
@@ -659,6 +703,7 @@ export const make = Effect.gen(function* () {
detach,
loadFailed,
setShown,
+ setCaptureDrawn,
placeDownload,
humanStartedDownload,
agentLedPage,
diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts
index b6387a06c22d8..2091ff3c7f8f2 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())),
@@ -2756,6 +2784,116 @@ describe("PreviewManager", () => {
),
);
+ effectIt.effect(
+ "publishes human ownership only on transitions while retaining every recording press",
+ () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ let humanInput: ((input: unknown) => void) | undefined;
+ const contents = makeTestPreviewWebContents(async () => ({
+ toJPEG: () => Buffer.from("frame"),
+ getSize: () => ({ width: 800, height: 600 }),
+ }));
+ contents.ipc.on = (channel, callback) => {
+ if (channel === "preview:human-input")
+ humanInput = (input) => callback({} as Electron.IpcMainEvent, input);
+ return contents.ipc;
+ };
+ fromId.mockReturnValue(contents);
+ yield* manager.createTab("tab_human");
+ yield* manager.registerWebview("tab_human", 42);
+ yield* manager.startRecording("tab_human", {
+ showKeyPresses: true,
+ showMousePresses: true,
+ });
+ const controllers: string[] = [];
+ const feedback = yield* Queue.unbounded();
+ webviewSend.mockImplementation((channel) => {
+ if (channel === "preview:recording-controller") Queue.offerUnsafe(feedback, undefined);
+ });
+ yield* manager.subscribeStateChanges((_tabId, state) =>
+ Effect.sync(() => {
+ controllers.push(state.controller);
+ }),
+ );
+ for (const press of [
+ { kind: "pointer", x: 10, y: 20, button: 0 },
+ { kind: "pointer", x: 30, y: 40, button: 0 },
+ { kind: "key", key: "a", code: "KeyA" },
+ ]) {
+ humanInput?.(press);
+ yield* Queue.take(feedback);
+ }
+ expect(controllers).toEqual(["human"]);
+ expect(
+ webviewSend.mock.calls.filter(
+ ([channel]) => channel === "preview:recording-controller",
+ ),
+ ).toEqual([
+ ["preview:recording-controller", "human", { x: 10, y: 20 }],
+ ["preview:recording-controller", "human", { x: 30, y: 40 }],
+ ["preview:recording-controller", "human", undefined],
+ ]);
+ yield* TestClock.adjust(750);
+ expect(controllers).toEqual(["human", "none"]);
+ }),
+ ),
+ );
+
+ effectIt.effect("keeps human ownership until the last input's idle deadline", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ let humanInput: ((input: unknown) => void) | undefined;
+ const contents = makeTestPreviewWebContents(async () => ({
+ toJPEG: () => Buffer.from("frame"),
+ getSize: () => ({ width: 800, height: 600 }),
+ }));
+ contents.ipc.on = (channel, callback) => {
+ if (channel === "preview:human-input")
+ humanInput = (input) => callback({} as Electron.IpcMainEvent, input);
+ return contents.ipc;
+ };
+ fromId.mockReturnValue(contents);
+ yield* manager.createTab("tab_idle");
+ yield* manager.registerWebview("tab_idle", 42);
+ const controllers: string[] = [];
+ yield* manager.subscribeStateChanges((_tabId, state) =>
+ Effect.sync(() => {
+ controllers.push(state.controller);
+ }),
+ );
+ const press = () => humanInput?.({ kind: "key", key: "a", code: "KeyA" });
+ press();
+ yield* TestClock.adjust(500);
+ press();
+ yield* TestClock.adjust(749);
+ expect(controllers).toEqual(["human"]);
+ yield* TestClock.adjust(1);
+ expect(controllers).toEqual(["human", "none"]);
+
+ press();
+ yield* TestClock.adjust(500);
+ const staleInput = humanInput;
+ const replacement = makeTestPreviewWebContents(
+ async () => ({
+ toJPEG: () => Buffer.from("frame"),
+ getSize: () => ({ width: 800, height: 600 }),
+ }),
+ 43,
+ );
+ replacement.ipc.on = contents.ipc.on;
+ contents.isDestroyed = () => true;
+ fromId.mockImplementation((id) => (id === 43 ? replacement : null));
+ yield* manager.registerWebview("tab_idle", 43);
+ expect(controllers.at(-1)).toBe("none");
+ const count = controllers.length;
+ staleInput?.({ kind: "key", key: "b", code: "KeyB" });
+ yield* TestClock.adjust(750);
+ expect(controllers).toHaveLength(count);
+ }),
+ ),
+ );
+
effectIt.effect("gates recording decorations and isolates failed subscribers", () =>
withManager((manager) =>
Effect.gen(function* () {
diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts
index 2c199e358fa5b..32ac876996c81 100644
--- a/apps/desktop/src/preview/Manager.ts
+++ b/apps/desktop/src/preview/Manager.ts
@@ -889,7 +889,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const update = Effect.fn("PreviewManager.update")(function* (
tabId: string,
patch: Partial,
- humanPoint?: { readonly x: number; readonly y: number },
) {
const updatedAt = yield* currentIso;
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
@@ -905,17 +904,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
// syncTabAudible can commit after this update; emitIfCurrent prevents publishing a stale snapshot.
if (Option.isSome(next)) {
- if (patch.controller !== undefined && next.value.webContentsId != null) {
- const capture = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId);
- const webContentsId = next.value.webContentsId;
- if (capture?.consumers.has("recording")) {
- yield* attempt({ operation: "recording.controller", tabId }, () => {
- const contents = webContents.fromId(webContentsId);
- if (contents && !contents.isDestroyed())
- contents.send(RECORDING_CONTROLLER_CHANNEL, patch.controller, humanPoint);
- }).pipe(Effect.ignore);
- }
- }
yield* emitIfCurrent(tabId, next.value);
}
});
@@ -1108,28 +1096,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
),
scope,
);
- const handleDebuggerMessage = Effect.fnUntraced(function* (
- method: string,
- params: Record,
- ) {
- if (method === "Page.screencastFrame") {
- const sessionId = params["sessionId"];
- if (typeof sessionId === "number") {
- yield* attemptPromise(
- {
- operation: "ackScreencastFrame",
- webContentsId: wc.id,
- },
- () => wcDebugger.sendCommand("Page.screencastFrameAck", { sessionId }),
- ).pipe(Effect.ignore);
- }
- }
+ const handleDebuggerMessage = Effect.fnUntraced(function* (method: string) {
if (method === "Runtime.consoleAPICalled" || method === "Runtime.exceptionThrown") {
yield* Queue.offer(consoleReleases, undefined);
}
});
- const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
- runFork(handleDebuggerMessage(method, params));
+ const onMessage: BrowserControlSession["onMessage"] = (_event, method) => {
+ runFork(handleDebuggerMessage(method));
};
const control: BrowserControlSession = {
webContentsId: wc.id,
@@ -1444,21 +1417,75 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}),
);
};
+ let humanInputWorker = false;
+ let humanInputDeadline = 0;
+ let listening = true;
+ const publishHumanController = Effect.fn("PreviewManager.publishHumanController")(function* (
+ controller: "human" | "none",
+ humanPoint?: { readonly x: number; readonly y: number },
+ ) {
+ const now = yield* currentMillis;
+ const updatedAt = yield* currentIso;
+ const result = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
+ const current = tabs.get(tabId);
+ if (
+ !current ||
+ current.webContentsId !== wc.id ||
+ (controller === "human"
+ ? !listening || webContents.fromId(wc.id) !== wc
+ : current.controller !== "human" || humanInputDeadline > now)
+ )
+ return [undefined, tabs] as const;
+ const changed = current.controller !== controller;
+ const state = changed ? { ...current, controller, updatedAt } : current;
+ return [
+ { state, changed },
+ changed
+ ? replaceMap(tabs, (copy) => {
+ copy.set(tabId, state);
+ })
+ : tabs,
+ ] as const;
+ });
+ if (!result) return;
+ const capture = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId);
+ if (capture?.consumers.has("recording")) {
+ yield* attempt({ operation: "recording.controller", tabId }, () => {
+ if (!wc.isDestroyed()) wc.send(RECORDING_CONTROLLER_CHANNEL, controller, humanPoint);
+ }).pipe(Effect.ignore);
+ }
+ if (result.changed) yield* emitIfCurrent(tabId, result.state);
+ });
+ yield* Scope.addFinalizer(
+ scope,
+ Effect.gen(function* () {
+ listening = false;
+ humanInputDeadline = 0;
+ yield* publishHumanController("none");
+ }),
+ );
const handleHumanInput = Effect.fn("PreviewManager.handleHumanInput")(function* (
rawSignal?: unknown,
) {
- yield* update(
- tabId,
- { controller: "human" },
+ if (!listening) return;
+ humanInputDeadline = (yield* currentMillis) + 750;
+ if (!humanInputWorker) {
+ humanInputWorker = true;
+ yield* Effect.gen(function* () {
+ let remaining: number;
+ while ((remaining = humanInputDeadline - (yield* currentMillis)) > 0) {
+ yield* Effect.sleep(remaining);
+ }
+ humanInputWorker = false;
+ yield* publishHumanController("none");
+ }).pipe(Effect.forkIn(scope));
+ }
+ yield* publishHumanController(
+ "human",
isPreviewInputSignal(rawSignal) && rawSignal.kind === "pointer"
? { x: rawSignal.x, y: rawSignal.y }
: undefined,
);
- yield* Effect.sleep(750);
- const tabs = yield* SynchronizedRef.get(tabsRef);
- if (tabs.get(tabId)?.controller === "human") {
- yield* update(tabId, { controller: "none" });
- }
});
const recordingInput = (_event: unknown, input: unknown) => {
if (!isRecordingInput(input)) return;
@@ -1800,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(
[
@@ -2608,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);
}
}
});
@@ -3476,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(
@@ -3490,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({
@@ -3688,6 +3728,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
setAnnotationSendEnabled,
setAudioMuted,
setShown,
+ setCaptureDrawn,
setColorScheme,
setMainWindow,
setForwardedShortcuts: (shortcuts: ReadonlyArray) =>
@@ -3904,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,
@@ -4066,6 +4108,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
setZoomFactor: operations.setZoomFactor,
setAudioMuted: operations.setAudioMuted,
setShown: operations.setShown,
+ setCaptureDrawn: operations.setCaptureDrawn,
openDevTools: operations.openDevTools,
clearCookies: Effect.fn("PreviewManager.clearCookies")(function* (partitions) {
yield* browserSession
diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
index 88c45f37cc467..7808682dfd82b 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
@@ -2,6 +2,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Deferred from "effect/Deferred";
@@ -62,6 +63,26 @@ function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildPro
});
}
+function makeSlowProcess(
+ output: string,
+ delay: Duration.Input,
+): ChildProcessSpawner.ChildProcessHandle {
+ const stdout = Stream.fromEffect(Effect.as(Effect.sleep(delay), textEncoder.encode(output)));
+ return ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(125),
+ stdout,
+ stderr: Stream.empty,
+ all: stdout,
+ exitCode: Effect.as(Effect.sleep(delay), ChildProcessSpawner.ExitCode(0)),
+ isRunning: Effect.succeed(true),
+ kill: () => Effect.void,
+ stdin: Sink.drain,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ unref: Effect.succeed(Effect.void),
+ });
+}
+
function makeHungProcess(): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(124),
@@ -486,7 +507,7 @@ describe("DesktopShellEnvironment", () => {
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
- PATH: "/Users/test/.local/bin:/usr/bin",
+ PATH: " /Users/test/.local/bin:/usr/bin",
};
const commands: ChildProcess.Command[] = [];
@@ -496,7 +517,7 @@ describe("DesktopShellEnvironment", () => {
handler: (command) => {
commands.push(command);
return envOutput({
- PATH: "/opt/homebrew/bin:/usr/bin",
+ PATH: "/opt/homebrew/bin:/usr/bin:/opt/bin ",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
HOMEBREW_PREFIX: "/opt/homebrew",
});
@@ -505,7 +526,7 @@ describe("DesktopShellEnvironment", () => {
assert.equal(commands.length, 1);
assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh");
- assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
+ assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/opt/bin : /Users/test/.local/bin");
assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew");
assert.isTrue(prepared);
@@ -670,6 +691,129 @@ describe("DesktopShellEnvironment", () => {
}),
);
+ it.effect("retries the user's shell when only the fallback shell answered", () =>
+ Effect.gen(function* () {
+ const env: NodeJS.ProcessEnv = { SHELL: "/usr/bin/fish", PATH: "/usr/bin" };
+ const commands: string[] = [];
+ let fishReady = false;
+ yield* runShellEnvironment({
+ env,
+ platform: "linux",
+ handler: (command) => {
+ if (command._tag !== "StandardCommand") return "";
+ commands.push(command.command);
+ if (command.command !== "/usr/bin/fish") return envOutput({ PATH: "/usr/bin" });
+ return fishReady
+ ? envOutput({ PATH: "/fish/bin:/usr/bin" })
+ : { output: "", exitCode: 7 };
+ },
+ use: (service) =>
+ Effect.gen(function* () {
+ assert.isTrue(yield* service.awaitDiscovery);
+ assert.equal(env.PATH, "/usr/bin");
+ // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await.
+ const published = yield* service.updates.pipe(
+ Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"),
+ Stream.runHead,
+ Effect.forkChild({ startImmediately: true }),
+ );
+
+ fishReady = true;
+ yield* TestClock.adjust("30 seconds");
+ assert.isTrue(Option.isSome(yield* Fiber.join(published)));
+ assert.equal(env.PATH, "/fish/bin:/usr/bin");
+ return true;
+ }),
+ }).pipe(Effect.provide(Logger.layer([])));
+ assert.deepEqual(commands, ["/usr/bin/fish", "/bin/bash", "/usr/bin/fish"]);
+
+ // With no user shell to wait for, the fallback's answer is final.
+ commands.length = 0;
+ yield* runShellEnvironment({
+ env: { PATH: "/usr/bin" },
+ platform: "linux",
+ handler: (command) => {
+ if (command._tag === "StandardCommand") commands.push(command.command);
+ return envOutput({ PATH: "/usr/bin" });
+ },
+ use: (service) =>
+ Effect.gen(function* () {
+ assert.isTrue(yield* service.awaitDiscovery);
+ yield* TestClock.adjust("5 minutes");
+ return true;
+ }),
+ }).pipe(Effect.provide(Logger.layer([])));
+ assert.deepEqual(commands, ["/bin/bash"]);
+ }),
+ );
+
+ it.effect("gives background retries time for a locked or slow shell, then publishes", () =>
+ Effect.gen(function* () {
+ const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
+ // Startup fails fast, the first retry meets a shell blocked on a lock, the second a slow one.
+ const spawned = yield* Effect.forEach([0, 1, 2], () => Deferred.make());
+ const stopped = yield* Deferred.make();
+ let attempts = 0;
+ yield* runShellEnvironment({
+ env,
+ platform: "darwin",
+ handler: () => "",
+ processSpawner: ChildProcessSpawner.make((command) => {
+ if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
+ return Effect.succeed(makeProcess(""));
+ }
+ const attempt = attempts++;
+ const spawn = Deferred.succeed(spawned[attempt]!, undefined);
+ if (attempt === 0) return spawn.pipe(Effect.as(makeProcess("")));
+ if (attempt === 1) {
+ return spawn.pipe(
+ Effect.andThen(
+ Effect.acquireRelease(Effect.succeed(makeHungProcess()), () =>
+ Deferred.succeed(stopped, command.options),
+ ),
+ ),
+ );
+ }
+ return spawn.pipe(
+ Effect.as(makeSlowProcess(envOutput({ PATH: "/fresh/bin" }), "20 seconds")),
+ );
+ }),
+ use: (service) =>
+ Effect.gen(function* () {
+ assert.isFalse(yield* service.awaitDiscovery);
+ const published = yield* service.updates.pipe(
+ Stream.drop(1),
+ Stream.runHead,
+ Effect.forkChild({ startImmediately: true }),
+ );
+
+ yield* TestClock.adjust("30 seconds");
+ yield* Deferred.await(spawned[1]!);
+ // pyenv waits up to 60 s on its rehash lock before the shell continues.
+ yield* TestClock.adjust("1 minute");
+ assert.isFalse(yield* Deferred.isDone(stopped));
+ yield* TestClock.adjust("1 minute");
+ const stop = yield* Deferred.await(stopped);
+ // pyenv releases that lock in an EXIT trap, which SIGTERM runs and SIGKILL skips.
+ assert.equal(stop.killSignal, "SIGTERM");
+ assert.isAtLeast(Duration.toMillis(stop.forceKillAfter ?? 0), 5_000);
+
+ yield* TestClock.adjust("30 seconds");
+ yield* Deferred.await(spawned[2]!);
+ yield* TestClock.adjust("20 seconds");
+ const snapshot = yield* Fiber.join(published);
+ assert.equal(env.PATH, "/fresh/bin:/usr/bin");
+ assert.isTrue(Option.isSome(snapshot) && snapshot.value.discovered);
+ assert.equal(
+ Option.isSome(snapshot) ? snapshot.value.environment.PATH : undefined,
+ "/fresh/bin:/usr/bin",
+ );
+ return true;
+ }),
+ });
+ }),
+ );
+
it.effect("recovers the login-shell PATH when the first probe outlasts the timeout", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" };
diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts
index 299b0902b57a5..351150aa4b987 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts
@@ -3,6 +3,7 @@ import {
applyShellEnvironment,
buildEnvironmentCaptureCommand,
listLoginShellCandidates,
+ mergePathValues,
readUserLoginShell,
setWindowsPath,
} from "@t3tools/shared/shell";
@@ -14,6 +15,7 @@ import * as Deferred from "effect/Deferred";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
+import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -27,9 +29,17 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
type EnvironmentPatch = Record;
+interface ProbeBudget {
+ readonly timeout: Duration.Duration;
+ // One longer wait for the first login shell that times out.
+ readonly slowTimeout?: Duration.Duration;
+ readonly terminateGrace: Duration.Duration;
+}
+
interface ShellEnvironmentConfig {
readonly env: NodeJS.ProcessEnv;
readonly platform: NodeJS.Platform;
+ readonly budget: ProbeBudget;
}
interface WindowsProbeOptions {
@@ -124,6 +134,20 @@ const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
const SLOW_LOGIN_SHELL_TIMEOUT = Duration.seconds(20);
const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
+const STARTUP_PROBE: ProbeBudget = {
+ timeout: LOGIN_SHELL_TIMEOUT,
+ slowTimeout: SLOW_LOGIN_SHELL_TIMEOUT,
+ terminateGrace: PROCESS_TERMINATE_GRACE,
+};
+// Retries block nothing, so they outlast pyenv's 60 s wait on its rehash lock, and SIGTERM gets
+// time to run the exit trap that releases it. A SIGKILL leaves the lock for two minutes.
+const RETRY_PROBE: ProbeBudget = {
+ timeout: Duration.minutes(2),
+ terminateGrace: Duration.seconds(10),
+};
+// A Mac asleep at launch fails the first probe on wake, and nothing else would probe again.
+const DISCOVERY_RETRY_DELAY = Duration.seconds(30);
+const DISCOVERY_RETRIES = 10;
const trimNonEmpty = (value: string | null | undefined): Option.Option =>
Option.fromNullishOr(value).pipe(
@@ -131,10 +155,12 @@ const trimNonEmpty = (value: string | null | undefined): Option.Option =
Option.filter((entry) => entry.length > 0),
);
-const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";" : ":");
+// POSIX directory names may begin or end with whitespace; mergePathValues trims only on Windows.
+const nonEmptyPath = (value: string | null | undefined): Option.Option =>
+ Option.fromNullishOr(value).pipe(Option.filter((entry) => entry.length > 0));
const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option =>
- trimNonEmpty(env.PATH ?? env.Path ?? env.path);
+ nonEmptyPath(env.PATH ?? env.Path ?? env.path);
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
@@ -153,39 +179,16 @@ const linuxRuntimeDirCandidates = (
return candidates.filter((candidate) => candidate.length > 0);
};
-const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
- const normalized = entry.trim().replace(/^"+|"+$/g, "");
- return platform === "win32" ? normalized.toLowerCase() : normalized;
-};
-
-const sanitizePathEntry = (entry: string, platform: NodeJS.Platform) =>
- platform === "win32" ? entry.replaceAll('"', "") : entry;
-
const mergePaths = (
platform: NodeJS.Platform,
values: ReadonlyArray>,
-): Option.Option => {
- const delimiter = pathDelimiter(platform);
- const entries: string[] = [];
- const seen = new Set();
-
- for (const value of values) {
- if (Option.isNone(value)) continue;
-
- for (const entry of value.value.split(delimiter)) {
- const sanitized = sanitizePathEntry(entry.trim(), platform);
- if (sanitized.length === 0) continue;
-
- const key = pathComparisonKey(sanitized, platform);
- if (key.length === 0 || seen.has(key)) continue;
-
- seen.add(key);
- entries.push(sanitized);
- }
- }
-
- return entries.length > 0 ? Option.some(entries.join(delimiter)) : Option.none();
-};
+): Option.Option =>
+ Option.fromNullishOr(
+ values.reduce(
+ (merged, value) => mergePathValues(merged, Option.getOrUndefined(value), platform),
+ undefined,
+ ),
+ );
const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray => [
...trimNonEmpty(env.APPDATA).pipe(
@@ -265,6 +268,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
readonly args: ReadonlyArray;
readonly env: NodeJS.ProcessEnv;
readonly timeout: Duration.Duration;
+ readonly terminateGrace?: Duration.Duration;
readonly shell?: boolean;
}): Effect.fn.Return<
string,
@@ -283,7 +287,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
stdout: "pipe",
stderr: "ignore",
killSignal: "SIGTERM",
- forceKillAfter: PROCESS_TERMINATE_GRACE,
+ forceKillAfter: input.terminateGrace ?? PROCESS_TERMINATE_GRACE,
}),
);
return yield* Effect.all([Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode], {
@@ -349,6 +353,7 @@ const readLoginShellEnvironment = (
names: ReadonlyArray,
env: NodeJS.ProcessEnv,
timeout: Duration.Duration,
+ terminateGrace: Duration.Duration,
): Effect.Effect<
EnvironmentPatch,
DesktopShellEnvironmentCommandTimeoutError,
@@ -362,6 +367,7 @@ const readLoginShellEnvironment = (
args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)],
env,
timeout,
+ terminateGrace,
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
const readLaunchctlPath = (env: NodeJS.ProcessEnv) =>
@@ -378,6 +384,7 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
names: ReadonlyArray,
options: WindowsProbeOptions,
env: NodeJS.ProcessEnv,
+ budget: ProbeBudget,
): Effect.fn.Return {
if (names.length === 0) return {};
@@ -395,7 +402,8 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
command,
args,
env,
- timeout: LOGIN_SHELL_TIMEOUT,
+ timeout: budget.timeout,
+ terminateGrace: budget.terminateGrace,
}).pipe(orEmptyOnTimeout);
const environment = extractEnvironment(output, names);
if (Object.keys(environment).length > 0) {
@@ -413,8 +421,13 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
): Effect.fn.Return {
const [noProfile, profile] = yield* Effect.all(
[
- readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env),
- readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }, config.env),
+ readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env, config.budget),
+ readWindowsEnvironment(
+ WINDOWS_PROFILE_ENV_NAMES,
+ { loadProfile: true },
+ config.env,
+ config.budget,
+ ),
],
{ concurrency: 2 },
);
@@ -438,6 +451,9 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
},
);
+const listUserShells = (env: NodeJS.ProcessEnv): ReadonlyArray =>
+ [env.SHELL?.trim(), readUserLoginShell()].filter((shell): shell is string => Boolean(shell));
+
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
function* (
config: ShellEnvironmentConfig,
@@ -448,22 +464,28 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
> {
const fileSystem = yield* FileSystem.FileSystem;
const shellEnvironment: EnvironmentPatch = {};
- const userShells = [config.env.SHELL?.trim(), readUserLoginShell()];
+ const userShells = listUserShells(config.env);
let answeredBy: string | undefined;
let waitedForSlowShell = false;
for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
const read = (timeout: Duration.Duration) =>
- readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES, config.env, timeout);
+ readLoginShellEnvironment(
+ shell,
+ LOGIN_SHELL_ENV_NAMES,
+ config.env,
+ timeout,
+ config.budget.terminateGrace,
+ );
Object.assign(
shellEnvironment,
- yield* read(LOGIN_SHELL_TIMEOUT).pipe(
+ yield* read(config.budget.timeout).pipe(
Effect.catchTags({
DesktopShellEnvironmentCommandTimeoutError: (error) => {
- const retry = !waitedForSlowShell;
+ const slowTimeout = waitedForSlowShell ? undefined : config.budget.slowTimeout;
waitedForSlowShell = true;
return logShellEnvironmentCommandError(error).pipe(
- Effect.andThen(retry ? read(SLOW_LOGIN_SHELL_TIMEOUT) : Effect.succeed({})),
+ Effect.andThen(slowTimeout ? read(slowTimeout) : Effect.succeed({})),
);
},
}),
@@ -484,7 +506,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
? yield* readLaunchctlPath(config.env)
: Option.none();
const mergedPath = mergePaths(config.platform, [
- trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
+ nonEmptyPath(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
readEnvPath(config.env),
]);
@@ -577,7 +599,10 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
}
const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH));
- return { prepared, fromUserShell: prepared && userShells.includes(answeredBy) };
+ return {
+ prepared,
+ fromUserShell: prepared && answeredBy !== undefined && userShells.includes(answeredBy),
+ };
},
);
@@ -661,38 +686,60 @@ export const make = Effect.gen(function* () {
yield* Ref.set(latest, Option.some(message));
yield* PubSub.publish(changes, message);
});
- const refresh = Effect.gen(function* () {
- // Refresh from the inherited baseline so removed cached paths and values do not survive.
- const fresh = { ...inherited };
- const discovery = yield* installShellEnvironment({
- env: fresh,
- platform: environment.platform,
- });
- const { prepared } = discovery;
- const patch = Object.fromEntries(
- Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
- );
- if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
- if (prepared) {
- const cached = Object.fromEntries(
- CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
- );
- const persist = Effect.gen(function* () {
- const encoded = yield* encodeCache({ version: 1, key, environment: cached });
- yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
- yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
- yield* fileSystem.rename(cachePath + ".tmp", cachePath);
+ const probe = Effect.fn("desktop.shellEnvironment.refresh")(
+ function* (budget: ProbeBudget) {
+ // Refresh from the inherited baseline so removed cached paths and values do not survive.
+ const fresh = { ...inherited };
+ const discovery = yield* installShellEnvironment({
+ env: fresh,
+ platform: environment.platform,
+ budget,
});
- yield* persist.pipe(
- Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
+ const { prepared } = discovery;
+ const patch = Object.fromEntries(
+ Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
);
- }
- return discovery;
- }).pipe(
+ if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
+ if (prepared) {
+ const cached = Object.fromEntries(
+ CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
+ );
+ const persist = Effect.gen(function* () {
+ const encoded = yield* encodeCache({ version: 1, key, environment: cached });
+ yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
+ yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
+ yield* fileSystem.rename(cachePath + ".tmp", cachePath);
+ });
+ yield* persist.pipe(
+ Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
+ );
+ }
+ return discovery;
+ },
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
- Effect.withSpan("desktop.shellEnvironment.refresh"),
+ );
+ // A fallback shell's PATH can miss folders the user's own shell adds, so keep asking that shell.
+ const awaitsUserShell = listUserShells(inherited).length > 0;
+ const settled = ({ prepared, fromUserShell }: ShellDiscovery) =>
+ fromUserShell || (prepared && !awaitsUserShell);
+ const refresh = probe(STARTUP_PROBE).pipe(
Effect.onExit((exit) => Deferred.done(discovered, exit)),
+ Effect.flatMap((discovery) =>
+ settled(discovery)
+ ? Effect.void
+ : Effect.sleep(DISCOVERY_RETRY_DELAY).pipe(
+ Effect.andThen(
+ probe(RETRY_PROBE).pipe(
+ Effect.repeat({
+ until: settled,
+ schedule: Schedule.spaced(DISCOVERY_RETRY_DELAY),
+ times: DISCOVERY_RETRIES - 1,
+ }),
+ ),
+ ),
+ ),
+ ),
);
const installIntoProcess = yield* Effect.cached(
Effect.gen(function* () {
diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts
index 1f5321148b77b..fdac65f86a595 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 560e2e78d4bb1..ce2f23ab3e781 100644
--- a/apps/desktop/src/updates/DesktopRemoteUpdates.ts
+++ b/apps/desktop/src/updates/DesktopRemoteUpdates.ts
@@ -32,6 +32,8 @@ const PREPARED_UPDATE_TTL = Duration.minutes(5);
interface PreparedUpdate {
readonly requestId: string;
+ readonly channel: DesktopTelemetryRequestDesktopUpdate["channel"];
+ readonly targetVersion: DesktopTelemetryRequestDesktopUpdate["targetVersion"];
readonly downloadedVersion: string;
readonly status: "prepared" | "committing" | "failed";
readonly failureReason?: string;
@@ -67,7 +69,11 @@ export const listen: Effect.Effect<
const publishReport = (
state: DesktopUpdateState,
- terminal?: { readonly outcome: DesktopUpdateRemoteOutcome; readonly reason?: string },
+ terminal?: {
+ readonly outcome: DesktopUpdateRemoteOutcome;
+ readonly reason?: string;
+ readonly preparedRequestId?: string;
+ },
explicitRequestId?: string,
): Effect.Effect => {
const reason = normalizeRemoteUpdateReason(terminal?.reason);
@@ -82,6 +88,9 @@ export const listen: Effect.Effect<
? { requestId: requestId.value }
: {}),
...(terminal === undefined ? {} : { outcome: terminal.outcome }),
+ ...(terminal?.preparedRequestId === undefined
+ ? {}
+ : { preparedRequestId: terminal.preparedRequestId }),
...(reason ? { reason } : {}),
state,
}),
@@ -167,8 +176,22 @@ export const listen: Effect.Effect<
: ([current, current] as const),
);
if (Option.isSome(prepared) && prepared.value.status !== "failed") {
+ const state = yield* updates.getState;
+ if (
+ prepared.value.status === "prepared" &&
+ prepared.value.channel === request.channel &&
+ prepared.value.targetVersion === request.targetVersion &&
+ state.downloadedVersion === prepared.value.downloadedVersion
+ ) {
+ yield* publishReport(
+ state,
+ { outcome: "ready-to-install", preparedRequestId: prepared.value.requestId },
+ request.requestId,
+ );
+ return;
+ }
yield* publishReport(
- yield* updates.getState,
+ state,
{
outcome: "failed",
reason: "A prepared desktop update is already in progress.",
@@ -301,6 +324,8 @@ export const listen: Effect.Effect<
preparedUpdateRef,
Option.some({
requestId: request.requestId,
+ channel: request.channel,
+ targetVersion: request.targetVersion,
downloadedVersion: state.downloadedVersion,
status: "prepared",
expiresAt:
diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts
index 7ee2ff5dd51c1..53bd956ca6da7 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 db31e0bc112ba..055c6574391a6 100644
--- a/apps/desktop/src/updates/DesktopUpdates.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.ts
@@ -63,7 +63,7 @@ const CHANNEL_CHANGE_RETRY_DELAY = Duration.seconds(1);
const CHANNEL_CHANGE_RETRIES = 30;
const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
const AUTO_UPDATE_POLL_INTERVAL = "4 hours";
-const PREPARED_INSTALL_CHECK_WAIT = Duration.seconds(90);
+const UPDATE_CHECK_WAIT = Duration.seconds(90);
type UpdateAction = "check" | "download" | "install" | "install-recovery" | "channel";
@@ -318,6 +318,10 @@ function getCanRetryFromState(state: DesktopUpdateState): boolean {
return state.availableVersion !== null || state.downloadedVersion !== null;
}
+function isOffered(state: DesktopUpdateState): boolean {
+ return state.status === "available" || state.status === "downloaded";
+}
+
function shouldBroadcastDownloadProgress(
currentState: DesktopUpdateState,
nextPercent: number,
@@ -518,6 +522,23 @@ export const make = Effect.gen(function* () {
),
);
+ // Re-runs admit after each finished action, so a caller waiting on a check decides on its result.
+ const admitAfterCheck = Effect.fn("desktop.updates.admitAfterCheck")(function* (
+ admit: Effect.Effect<"admitted" | "refused" | "wait-for-check">,
+ ) {
+ const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
+ let admission = yield* stateMutex.withPermits(1)(admit);
+ while (admission === "wait-for-check") {
+ const finishedAction = yield* PubSub.take(actionCompletions).pipe(
+ Effect.timeoutOption(UPDATE_CHECK_WAIT),
+ );
+ admission = Option.isNone(finishedAction)
+ ? "refused"
+ : yield* stateMutex.withPermits(1)(admit);
+ }
+ return admission;
+ });
+
const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
channel: DesktopUpdateChannel,
) {
@@ -559,8 +580,10 @@ export const make = Effect.gen(function* () {
if (actionReservation === "acquire" && !(yield* tryStartUpdateAction("check"))) return false;
const check = Effect.gen(function* () {
- const checkedAt = yield* currentIsoTimestamp;
- yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt));
+ // An offer stays on screen while re-checking, so finding it again changes nothing.
+ if (!isOffered(state)) {
+ yield* setState(reduceDesktopUpdateStateOnCheckStart(state, yield* currentIsoTimestamp));
+ }
yield* logUpdaterInfo("checking for updates", { reason });
// The flag is shared updater state, so it flips only while this check holds the reservation.
@@ -597,15 +620,30 @@ export const make = Effect.gen(function* () {
});
const downloadAvailableUpdate = Effect.gen(function* () {
- const state = yield* Ref.get(updateStateRef);
- if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") {
- return { accepted: false, completed: false };
- }
-
- if (!(yield* tryStartUpdateAction("download"))) {
+ const admission = yield* Effect.scoped(
+ admitAfterCheck(
+ Effect.gen(function* () {
+ const state = yield* Ref.get(updateStateRef);
+ if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") {
+ return "refused" as const;
+ }
+ const activeAction = yield* Ref.get(activeUpdateActionRef);
+ if (Option.isSome(activeAction)) {
+ return activeAction.value === "check"
+ ? ("wait-for-check" as const)
+ : ("refused" as const);
+ }
+ return (yield* tryStartUpdateAction("download"))
+ ? ("admitted" as const)
+ : ("refused" as const);
+ }),
+ ),
+ );
+ if (admission === "refused") {
return { accepted: false, completed: false };
}
+ const state = yield* Ref.get(updateStateRef);
return yield* Effect.gen(function* () {
yield* setState(reduceDesktopUpdateStateOnDownloadStart(state));
yield* electronUpdater.setDisableDifferentialDownload(
@@ -798,47 +836,35 @@ export const make = Effect.gen(function* () {
const installDownloadedUpdate = (expectedVersion?: string) =>
Effect.scoped(
Effect.gen(function* () {
- const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
- let admission: "admitted" | "refused" | "wait-for-check" = "wait-for-check";
- while (admission === "wait-for-check") {
- admission = yield* stateMutex.withPermits(1)(
- Effect.gen(function* () {
- const state = yield* Ref.get(updateStateRef);
- const activeAction = yield* Ref.get(activeUpdateActionRef);
- const hasExpectedDownload =
- state.downloadedVersion !== null &&
- (expectedVersion === undefined || state.downloadedVersion === expectedVersion);
- if (
- (yield* Ref.get(desktopState.quitting)) ||
- !(yield* Ref.get(updaterConfiguredRef)) ||
- !hasExpectedDownload
- ) {
- return "refused" as const;
- }
- if (Option.isSome(activeAction)) {
- return activeAction.value === "check" && expectedVersion !== undefined
- ? ("wait-for-check" as const)
- : ("refused" as const);
- }
- const hasInstallableDownload =
- state.status === "downloaded" ||
- (state.status === "error" &&
- (state.errorContext === null || state.errorContext === "install"));
- if (!hasInstallableDownload) return "refused" as const;
- return (yield* tryStartUpdateAction("install"))
- ? ("admitted" as const)
+ const admission = yield* admitAfterCheck(
+ Effect.gen(function* () {
+ const state = yield* Ref.get(updateStateRef);
+ const activeAction = yield* Ref.get(activeUpdateActionRef);
+ const hasExpectedDownload =
+ state.downloadedVersion !== null &&
+ (expectedVersion === undefined || state.downloadedVersion === expectedVersion);
+ if (
+ (yield* Ref.get(desktopState.quitting)) ||
+ !(yield* Ref.get(updaterConfiguredRef)) ||
+ !hasExpectedDownload
+ ) {
+ return "refused" as const;
+ }
+ if (Option.isSome(activeAction)) {
+ return activeAction.value === "check"
+ ? ("wait-for-check" as const)
: ("refused" as const);
- }),
- );
- if (admission === "wait-for-check") {
- const finishedAction = yield* PubSub.take(actionCompletions).pipe(
- Effect.timeoutOption(PREPARED_INSTALL_CHECK_WAIT),
- );
- if (Option.isNone(finishedAction)) {
- admission = "refused";
}
- }
- }
+ const hasInstallableDownload =
+ state.status === "downloaded" ||
+ (state.status === "error" &&
+ (state.errorContext === null || state.errorContext === "install"));
+ if (!hasInstallableDownload) return "refused" as const;
+ return (yield* tryStartUpdateAction("install"))
+ ? ("admitted" as const)
+ : ("refused" as const);
+ }),
+ );
if (admission === "refused") {
return { accepted: false, completed: false, failed: false };
}
@@ -982,6 +1008,7 @@ export const make = Effect.gen(function* () {
yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
return;
}
+ if (isOffered(state) && state.availableVersion === info.version) return;
const checkedAt = yield* currentIsoTimestamp;
const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes(
@@ -1161,6 +1188,8 @@ export const make = Effect.gen(function* () {
),
configure: Effect.gen(function* () {
const context = yield* Effect.context();
+ // Runs synchronously up to the first await, so a check's outcome is applied before the
+ // check's promise resolves and wakes the actions waiting on it.
const runEffect = (effect: Effect.Effect) => {
void Effect.runPromiseWith(context)(effect);
};
diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts
index 612ec441ba99b..46004ca302295 100644
--- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts
+++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts
@@ -3,7 +3,9 @@ import { assert, describe, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import type { DesktopUpdateCheckResult, DesktopUpdateState } from "@t3tools/contracts";
import * as Electron from "electron";
import { vi } from "vite-plus/test";
@@ -18,6 +20,7 @@ import * as DesktopApplicationMenu from "./DesktopApplicationMenu.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
+import { createInitialDesktopUpdateState } from "../updates/updateMachine.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
const environmentInput = {
@@ -56,27 +59,37 @@ const layerElectronApp = Layer.succeed(ElectronApp.ElectronApp, {
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
-const layerElectronDialog = Layer.succeed(ElectronDialog.ElectronDialog, {
- pickFolder: () => Effect.succeedNone,
- pickFiles: () => Effect.succeed([]),
- showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
- showErrorBox: () => Effect.void,
-} satisfies ElectronDialog.ElectronDialog["Service"]);
-
-const layerDesktopUpdates = Layer.succeed(DesktopUpdates.DesktopUpdates, {
- getState: Effect.die("unexpected getState"),
- isActionActive: Effect.succeed(false),
- isInstallActive: Effect.succeed(false),
- subscribe: Effect.die("unexpected subscribe"),
- emitState: Effect.void,
- disabledReason: Effect.succeedNone,
- configure: Effect.void,
- setChannel: () => Effect.die("unexpected setChannel"),
- check: () => Effect.die("unexpected check"),
- download: Effect.die("unexpected download"),
- install: Effect.die("unexpected install"),
- installPrepared: () => Effect.die("unexpected installPrepared"),
-} satisfies DesktopUpdates.DesktopUpdates["Service"]);
+interface MenuServices {
+ readonly checkResult?: DesktopUpdateCheckResult;
+ readonly shownMessageBox?: Deferred.Deferred;
+}
+
+const layerElectronDialog = ({ shownMessageBox }: MenuServices) =>
+ Layer.succeed(ElectronDialog.ElectronDialog, {
+ pickFolder: () => Effect.succeedNone,
+ pickFiles: () => Effect.succeed([]),
+ showMessageBox: (options) =>
+ (shownMessageBox ? Deferred.succeed(shownMessageBox, options) : Effect.void).pipe(
+ Effect.as({ response: options.cancelId ?? 0, checkboxChecked: false }),
+ ),
+ showErrorBox: () => Effect.void,
+ } satisfies ElectronDialog.ElectronDialog["Service"]);
+
+const layerDesktopUpdates = ({ checkResult }: MenuServices) =>
+ Layer.succeed(DesktopUpdates.DesktopUpdates, {
+ getState: Effect.die("unexpected getState"),
+ isActionActive: Effect.succeed(false),
+ isInstallActive: Effect.succeed(false),
+ subscribe: Effect.die("unexpected subscribe"),
+ emitState: Effect.void,
+ disabledReason: Effect.succeedNone,
+ configure: Effect.void,
+ setChannel: () => Effect.die("unexpected setChannel"),
+ check: () => (checkResult ? Effect.succeed(checkResult) : Effect.die("unexpected check")),
+ download: Effect.die("unexpected download"),
+ install: Effect.die("unexpected install"),
+ installPrepared: () => Effect.die("unexpected installPrepared"),
+ } satisfies DesktopUpdates.DesktopUpdates["Service"]);
const layerDesktopWindow = (selectedAction: Deferred.Deferred) =>
Layer.succeed(DesktopWindow.DesktopWindow, {
@@ -113,6 +126,7 @@ const configureMenu = (
selectedAction: Deferred.Deferred,
applicationMenuTemplate: Deferred.Deferred,
environment: Partial = {},
+ services: MenuServices = {},
) =>
Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
@@ -122,8 +136,8 @@ const configureMenu = (
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(layerElectronMenu(applicationMenuTemplate)),
Layer.provideMerge(layerDesktopWindow(selectedAction)),
- Layer.provideMerge(layerDesktopUpdates),
- Layer.provideMerge(layerElectronDialog),
+ Layer.provideMerge(layerDesktopUpdates(services)),
+ Layer.provideMerge(layerElectronDialog(services)),
Layer.provideMerge(layerElectronApp),
Layer.provideMerge(
DesktopEnvironment.layer({ ...environmentInput, ...environment }).pipe(
@@ -134,6 +148,54 @@ const configureMenu = (
),
);
+const checkForUpdatesFromMacMenu = (state: Partial) =>
+ Effect.gen(function* () {
+ const applicationMenuTemplate =
+ yield* Deferred.make();
+ const shownMessageBox = yield* Deferred.make();
+ yield* configureMenu(
+ yield* Deferred.make(),
+ applicationMenuTemplate,
+ { platform: "darwin" },
+ {
+ checkResult: {
+ checked: true,
+ state: {
+ ...createInitialDesktopUpdateState(
+ "0.1.5",
+ { hostArch: "arm64", appArch: "arm64", runningUnderArm64Translation: false },
+ "latest",
+ ),
+ enabled: true,
+ ...state,
+ },
+ },
+ shownMessageBox,
+ },
+ );
+
+ const appMenu = (yield* Deferred.await(applicationMenuTemplate))[0];
+ if (!Array.isArray(appMenu?.submenu)) {
+ throw new Error("Expected the macOS app menu submenu to be an array.");
+ }
+ const checkForUpdates = appMenu.submenu.find((item) => item.label === "Check for Updates...");
+ if (typeof checkForUpdates?.click !== "function") {
+ throw new Error("Expected Check for Updates... menu item to have a click handler.");
+ }
+
+ // Every stub completes synchronously, so the menu action has finished when click returns.
+ checkForUpdates.click(
+ {} as Electron.MenuItem,
+ {} as Electron.BrowserWindow,
+ {} as KeyboardEvent,
+ );
+ const dialog = yield* Deferred.poll(shownMessageBox);
+ if (Option.isNone(dialog)) {
+ throw new Error("Check for Updates... finished without showing any dialog.");
+ }
+ return yield* dialog.value;
+ });
+
describe("DesktopApplicationMenu", () => {
it.effect("leaves the accelerator to Chromium instead of injecting a paste", () =>
Effect.gen(function* () {
@@ -285,4 +347,25 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "main-reload");
}),
);
+ it.effect("tells the user which update the menu check found", () =>
+ Effect.gen(function* () {
+ const dialog = yield* checkForUpdatesFromMacMenu({
+ status: "available",
+ availableVersion: "0.1.7",
+ });
+ assert.include(`${dialog.title ?? ""} ${dialog.message} ${dialog.detail ?? ""}`, "0.1.7");
+ }),
+ );
+
+ it.effect("tells the user a downloaded update is ready when the menu check runs", () =>
+ Effect.gen(function* () {
+ const dialog = yield* checkForUpdatesFromMacMenu({
+ status: "downloaded",
+ availableVersion: "0.1.7",
+ downloadedVersion: "0.1.7",
+ downloadPercent: 100,
+ });
+ assert.include(`${dialog.title ?? ""} ${dialog.message} ${dialog.detail ?? ""}`, "0.1.7");
+ }),
+ );
});
diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts
index 44d2c234f8358..b4025ebfde8ef 100644
--- a/apps/desktop/src/window/DesktopApplicationMenu.ts
+++ b/apps/desktop/src/window/DesktopApplicationMenu.ts
@@ -64,6 +64,9 @@ const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")(
yield* desktopWindow.runMainContentsCommand(command);
});
+const describeUpdate = (version: string | null) =>
+ version === null ? "A new version of T3 Code" : `T3 Code ${version}`;
+
const checkForUpdatesFromMenu = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
@@ -77,6 +80,35 @@ const checkForUpdatesFromMenu = Effect.gen(function* () {
message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
buttons: ["OK"],
});
+ } else if (updateState.status === "available") {
+ const { response } = yield* electronDialog.showMessageBox({
+ type: "info",
+ title: "Update available",
+ message: `${describeUpdate(updateState.availableVersion)} is available.`,
+ detail: `You're running T3 Code ${updateState.currentVersion}.`,
+ buttons: ["Download", "Later"],
+ defaultId: 0,
+ cancelId: 1,
+ });
+ if (response === 0) yield* updates.download;
+ } else if (updateState.status === "downloading") {
+ yield* electronDialog.showMessageBox({
+ type: "info",
+ title: "Update downloading",
+ message: `${describeUpdate(updateState.availableVersion)} is already downloading.`,
+ buttons: ["OK"],
+ });
+ } else if (updateState.status === "downloaded") {
+ const { response } = yield* electronDialog.showMessageBox({
+ type: "info",
+ title: "Update ready",
+ message: `${describeUpdate(updateState.downloadedVersion ?? updateState.availableVersion)} is ready to install.`,
+ detail: "T3 Code will restart to install it. Any running tasks will be interrupted.",
+ buttons: ["Restart", "Later"],
+ defaultId: 0,
+ cancelId: 1,
+ });
+ if (response === 0) yield* updates.install;
} else if (updateState.status === "error") {
yield* electronDialog.showMessageBox({
type: "warning",
diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts
index 0ddcc7946d32b..f66586503e24d 100644
--- a/apps/desktop/src/window/DesktopWindow.test.ts
+++ b/apps/desktop/src/window/DesktopWindow.test.ts
@@ -246,6 +246,7 @@ function layerTest(input: {
readonly previewZoomReapplies?: number[];
readonly onReveal?: (window: Electron.BrowserWindow) => void;
readonly focusedWindow?: Electron.BrowserWindow;
+ readonly fallbackWindow?: Electron.BrowserWindow;
readonly platform?: NodeJS.Platform;
readonly appearanceWindows?: ReadonlyArray<{
readonly window: Electron.BrowserWindow;
@@ -299,7 +300,9 @@ function layerTest(input: {
Effect.as(input.window),
),
main: Ref.get(input.mainWindow),
- currentMainOrFirst: Ref.get(input.mainWindow),
+ currentMainOrFirst: Ref.get(input.mainWindow).pipe(
+ Effect.map(Option.orElse(() => Option.fromNullishOr(input.fallbackWindow ?? null))),
+ ),
focusedMainOrFirst:
input.focusedWindow === undefined
? Ref.get(input.mainWindow)
@@ -844,7 +847,7 @@ describe("DesktopWindow", () => {
}),
);
- it.effect("reloads and inspects the main window even when a popup has focus", () =>
+ it.effect("routes menu commands to the main window even when a popup has focus", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const popup = makeFakeBrowserWindow();
@@ -864,7 +867,10 @@ describe("DesktopWindow", () => {
yield* desktopWindow.runMainContentsCommand("reload");
yield* desktopWindow.runMainContentsCommand("forceReload");
yield* desktopWindow.runMainContentsCommand("toggleDevTools");
+ yield* desktopWindow.dispatchMenuAction("open-settings");
+ assert.deepEqual(fakeWindow.send.mock.calls, [["desktop:menu-action", "open-settings"]]);
+ assert.equal(popup.send.mock.calls.length, 0);
assert.equal(fakeWindow.reload.mock.calls.length, 1);
assert.equal(fakeWindow.reloadIgnoringCache.mock.calls.length, 1);
assert.equal(fakeWindow.toggleDevTools.mock.calls.length, 1);
@@ -875,6 +881,38 @@ describe("DesktopWindow", () => {
}),
);
+ it.effect("recreates main for Settings when only an unregistered popup survives", () =>
+ Effect.gen(function* () {
+ const main = makeFakeBrowserWindow();
+ const auxiliary = makeFakeBrowserWindow();
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make>(Option.none());
+
+ yield* Effect.gen(function* () {
+ const windows = yield* DesktopWindow.DesktopWindow;
+ yield* windows.dispatchMenuAction("open-settings");
+ assert.deepEqual(main.send.mock.calls, [["desktop:menu-action", "open-settings"]]);
+ assert.equal(auxiliary.send.mock.calls.length, 0);
+ assert.equal(yield* Ref.get(createCount), 1);
+ assert.strictEqual(yield* windows.ensureMain, main.window);
+ assert.equal(yield* Ref.get(createCount), 1);
+ }).pipe(
+ Effect.provide(
+ layerTest({
+ window: main.window,
+ createCount,
+ mainWindow,
+ fallbackWindow: auxiliary.window,
+ desktopSettings: {
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ localEnvironmentEnabled: false,
+ },
+ }),
+ ),
+ );
+ }),
+ );
+
it.effect("does not open main or splash windows once quitting has started", () =>
Effect.gen(function* () {
const fake = makeFakeBrowserWindow();
diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts
index 93b35eb9b1a32..7be14bc720838 100644
--- a/apps/desktop/src/window/DesktopWindow.ts
+++ b/apps/desktop/src/window/DesktopWindow.ts
@@ -425,7 +425,6 @@ export const make = Effect.gen(function* () {
);
const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
- const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
const zoomWindow = Effect.fn("desktop.window.zoomWindow")(function* (
window: Electron.BrowserWindow,
@@ -1019,7 +1018,7 @@ export const make = Effect.gen(function* () {
const ensureMain = Effect.gen(function* () {
if (yield* Ref.get(desktopState.quitting)) return Option.none();
- const existingWindow = yield* currentMainWindow;
+ const existingWindow = yield* electronWindow.main;
if (Option.isSome(existingWindow)) {
return existingWindow;
}
@@ -1106,7 +1105,8 @@ export const make = Effect.gen(function* () {
{ reveal = true }: { readonly reveal?: boolean } = {},
) {
if (yield* Ref.get(desktopState.quitting)) return;
- const existingWindow = yield* reveal ? focusedMainWindow : electronWindow.main;
+ // Only the main renderer loads the app preload that listens on these channels.
+ const existingWindow = yield* electronWindow.main;
if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return;
const window = Option.isSome(existingWindow) ? existingWindow : yield* ensureMain;
if (Option.isNone(window) || window.value.isDestroyed()) return;
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
index 0787956a72b76..7f4a2507a736e 100644
--- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
@@ -172,7 +172,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
" }",
' eval "$2"',
"); }",
- buildWslRuntimeProbeScript(fixture.runtimeRoot),
+ buildWslRuntimeProbeScript(),
].join("\n"),
);
@@ -207,7 +207,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
[
"bash() { return 127; }",
'export PATH="/fixture/bin:/usr/bin:/bin"',
- buildWslRuntimeProbeScript(fixture.runtimeRoot),
+ buildWslRuntimeProbeScript(),
].join("\n"),
);
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
index 4e5e5b423f20e..5ba7d3794fad1 100644
--- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
@@ -110,10 +110,7 @@ export class DesktopWslEnvironment extends Context.Service<
) => Effect.Effect;
readonly pruneRuntimes: (distro: string | null, runtimeId: string) => Effect.Effect;
readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect;
- readonly probeRuntime: (
- distro: string | null,
- linuxAppRoot: string,
- ) => Effect.Effect;
+ readonly probeRuntime: (distro: string | null) => Effect.Effect;
readonly ensureNodePty: (
distro: string | null,
linuxAppRoot: string,
@@ -483,11 +480,9 @@ require("node-pty");
NODE`;
// Resolve version-managed Node for providers without making runtime readiness depend on it.
-export const buildWslRuntimeProbeScript = (linuxAppRoot: string) =>
- [
- `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`,
- `${shellQuote(`${linuxAppRoot}/t3`)} --version >/dev/null 2>&1`,
- ].join("\n");
+// The install script already ran the staged t3, so running it again here only adds a second startup.
+export const buildWslRuntimeProbeScript = () =>
+ `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`;
const TOOLCHAIN_CHECK_SCRIPT = [
"for tool in node make g++ python3; do",
@@ -601,30 +596,17 @@ const formatMissingToolsReason = (
const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl")(function* (
distro: string | null,
- linuxAppRoot: string,
): Effect.fn.Return {
- const probe = yield* runWslShell(
- distro,
- buildWslRuntimeProbeScript(linuxAppRoot),
- PROBE_TIMEOUT,
- {
- resolveNode: false,
- },
- );
+ const probe = yield* runWslShell(distro, buildWslRuntimeProbeScript(), PROBE_TIMEOUT, {
+ resolveNode: false,
+ });
const transportFailureReason = formatWslShellTransportFailureReason(
probe.transportFailure,
- "the staged runtime",
+ "the login-shell PATH",
);
if (transportFailureReason !== null) {
return { ok: false, reason: transportFailureReason } as const;
}
- if (probe.exitCode !== 0) {
- const trimmedTail = probe.stderr.trim().slice(-500);
- return {
- ok: false,
- reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,
- } as const;
- }
const resolvedPath = parseResolvedPath(probe.stdout);
if (resolvedPath === null) {
return {
@@ -1175,7 +1157,7 @@ export interface DesktopWslEnvironmentTestStub {
) => PrepareWslRuntimeResult;
readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect;
readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect;
- readonly probeRuntime?: (distro: string | null, linuxAppRoot: string) => ProbeWslRuntimeResult;
+ readonly probeRuntime?: (distro: string | null) => ProbeWslRuntimeResult;
readonly ensureNodePty?: (
distro: string | null,
linuxAppRoot: string,
@@ -1222,16 +1204,14 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void;
},
),
- probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(
- function (distro, linuxAppRoot) {
- return Effect.succeed(
- stub.probeRuntime?.(distro, linuxAppRoot) ?? {
- ok: true,
- resolvedPath: "/usr/bin:/bin",
- },
- );
- },
- ),
+ probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(function (distro) {
+ return Effect.succeed(
+ stub.probeRuntime?.(distro) ?? {
+ ok: true,
+ resolvedPath: "/usr/bin:/bin",
+ },
+ );
+ }),
ensureNodePty: Effect.fn("DesktopWslEnvironment.ensureNodePty")(
function (distro, linuxAppRoot, options) {
return Effect.succeed(
@@ -1321,8 +1301,8 @@ export const layer = Layer.effect(
invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) {
return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId));
}),
- probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro, linuxAppRoot) {
- return provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot));
+ probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro) {
+ return provideSpawner(probeWslRuntimeImpl(distro));
}),
ensureNodePty: Effect.fn("desktop.wsl.ensureNodePty")(
function (distro, linuxAppRoot, options) {
diff --git a/apps/marketing/src/lib/releases.test.ts b/apps/marketing/src/lib/releases.test.ts
new file mode 100644
index 0000000000000..6527342d674e5
--- /dev/null
+++ b/apps/marketing/src/lib/releases.test.ts
@@ -0,0 +1,18 @@
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+
+import { fetchLatestRelease } from "./releases";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("fetchLatestRelease", () => {
+ it("rejects a GitHub API error response instead of returning it as a release", async () => {
+ vi.stubGlobal("sessionStorage", { getItem: () => null });
+ vi.stubGlobal("fetch", async () =>
+ Response.json({ message: "API rate limit exceeded" }, { status: 403 }),
+ );
+
+ await expect(fetchLatestRelease("stable")).rejects.toThrow("403");
+ });
+});
diff --git a/apps/marketing/src/lib/releases.ts b/apps/marketing/src/lib/releases.ts
index 7dc63bdaed859..f50103972cdd8 100644
--- a/apps/marketing/src/lib/releases.ts
+++ b/apps/marketing/src/lib/releases.ts
@@ -25,12 +25,18 @@ function cacheKey(channel: ReleaseChannel) {
return `t3code-${channel}-release`;
}
+async function fetchJson(url: string): Promise {
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`GitHub API responded ${response.status}`);
+ return response.json();
+}
+
async function fetchStable(): Promise {
- return fetch(LATEST_API_URL).then((r) => r.json());
+ return fetchJson(LATEST_API_URL);
}
async function fetchNightly(): Promise {
- const list: Release[] = await fetch(LIST_API_URL).then((r) => r.json());
+ const list = await fetchJson(LIST_API_URL);
const nightly = Array.isArray(list)
? list.find((release) => release.tag_name?.includes("-nightly."))
: undefined;
diff --git a/apps/marketing/src/pages/[...locale]/index.astro b/apps/marketing/src/pages/[...locale]/index.astro
index 3d8d44568d448..e8f4b5f1b5fa5 100644
--- a/apps/marketing/src/pages/[...locale]/index.astro
+++ b/apps/marketing/src/pages/[...locale]/index.astro
@@ -1234,6 +1234,8 @@ const mobileEndorsementRows = [
section { padding: 56px 0; }
.sec-cta { padding: 80px 0; }
.container { padding-left: 20px; padding-right: 20px; }
+ /* A nowrap tag widens its column past the grid, which then clips the other column. */
+ .harness-tag { white-space: normal; }
.endorsements-head {
margin-bottom: 40px;
}
@@ -1265,4 +1267,8 @@ const mobileEndorsementRows = [
font-size: 11px;
}
}
+
+ @media (max-width: 360px) {
+ .harness { padding-left: 12px; padding-right: 12px; }
+ }
diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
index 96551d05bbb55..7bc50b694df5f 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 {
@@ -301,18 +310,28 @@ private final class ComposerTextView: UITextView {
func loadImages(from providers: [NSItemProvider]) {
let group = DispatchGroup()
let lock = NSLock()
- var images = [UIImage?](repeating: nil, count: providers.count)
+ var images = [(data: Data, fileExtension: String)?](repeating: nil, count: providers.count)
for (index, provider) in providers.enumerated() {
group.enter()
- provider.loadObject(ofClass: UIImage.self) { object, _ in
- defer { group.leave() }
- guard let image = object as? UIImage else {
- return
- }
+ let store = { (image: (data: Data, fileExtension: String)?) in
lock.lock()
images[index] = image
lock.unlock()
+ group.leave()
+ }
+ let loadPNG = {
+ _ = provider.loadObject(ofClass: UIImage.self) { object, _ in
+ store((object as? UIImage)?.pngData().map { ($0, "png") })
+ }
+ }
+ // Decoding a GIF to UIImage keeps only its first frame, so pass its bytes through.
+ if provider.hasItemConformingToTypeIdentifier(UTType.gif.identifier) {
+ _ = provider.loadDataRepresentation(forTypeIdentifier: UTType.gif.identifier) { data, _ in
+ if let data { store((data, "gif")) } else { loadPNG() }
+ }
+ } else {
+ loadPNG()
}
}
@@ -320,7 +339,9 @@ private final class ComposerTextView: UITextView {
guard let self, !self.isReadOnly else {
return
}
- let urls = images.compactMap { $0 }.compactMap(Self.writeTemporaryImage)
+ let urls = images.compactMap { $0 }.compactMap {
+ Self.writeTemporaryImage($0.data, fileExtension: $0.fileExtension)
+ }
if !urls.isEmpty {
self.onPasteImages?(urls)
}
@@ -400,9 +421,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 +433,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 {
@@ -714,8 +736,10 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
hasControlledDocument = true
if tokensJson != document.tokensJson {
tokensJson = document.tokensJson
- tokens = decode([ComposerTokenPayload].self, from: document.tokensJson) ?? []
- tokensNeedRebuild = true
+ let nextTokens = decode([ComposerTokenPayload].self, from: document.tokensJson) ?? []
+ // Typing before a chip only moves its offsets; rebuilding then makes iOS autocorrect behind the caret.
+ tokensNeedRebuild = tokensNeedRebuild || !nextTokens.elementsEqual(tokens, by: { $0.rendersLike($1) })
+ tokens = nextTokens
}
let previousSelection = sourceSelection()
value = document.value
@@ -739,6 +763,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
func setPlaceholder(_ placeholder: String) {
placeholderLabel.text = placeholder
+ textView.accessibilityLabel = placeholder
setNeedsLayout()
}
@@ -1330,7 +1355,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
private func documentMatchesExpectedTokens() -> Bool {
let source = value as NSString
- let expectedSources = tokens.compactMap { token -> String? in
+ let expectedChips = tokens.compactMap { token -> (Int, String)? in
guard token.start >= 0,
token.end > token.start,
token.end <= source.length,
@@ -1339,18 +1364,22 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
) == token.source else {
return nil
}
- return token.source
+ return (token.start, token.source)
}
- var renderedSources: [String] = []
+ var renderedChips: [(Int, String)] = []
+ var sourceOffset = 0
textView.attributedText.enumerateAttribute(
.attachment,
in: NSRange(location: 0, length: textView.attributedText.length)
- ) { value, _, _ in
+ ) { value, range, _ in
if let attachment = value as? ComposerTextAttachment {
- renderedSources.append(attachment.source)
+ renderedChips.append((sourceOffset, attachment.source))
+ sourceOffset += (attachment.source as NSString).length
+ } else {
+ sourceOffset += range.length
}
}
- return renderedSources == expectedSources
+ return renderedChips.elementsEqual(expectedChips, by: ==)
}
}
diff --git a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift
index 4435b1022161d..e9751eec843ac 100644
--- a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift
+++ b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift
@@ -11,13 +11,16 @@ func check(_ passed: Bool, _ message: String) {
extension T3ComposerEditorView {
var editor: UITextView { textView }
var text: String { textView.serializedText() }
+ func chip(at location: Int) -> NSTextAttachment? {
+ textView.textStorage.attribute(.attachment, at: location, effectiveRange: nil) as? NSTextAttachment
+ }
}
-func document(_ value: String, revision: Int, resetGeneration: Int = 0, isNativeEcho: Bool = false) -> String {
+func document(_ value: String, revision: Int, resetGeneration: Int = 0, isNativeEcho: Bool = false, tokensJson: String = "[]") -> String {
let payload: [String: Any] = [
"value": value,
"selection": NSNull(),
- "tokensJson": "[]",
+ "tokensJson": tokensJson,
"mostRecentEventCount": revision,
"isNativeEcho": isNativeEcho,
"resetGeneration": resetGeneration,
@@ -33,10 +36,14 @@ func replace(_ view: T3ComposerEditorView, _ target: String, with replacement: S
editor.replace(editor.textRange(from: start, to: end)!, withText: replacement)
}
-func makeEditor(_ value: String) -> T3ComposerEditorView {
+func mention(_ label: String, at start: Int, source: String = "@README.md") -> String {
+ #"[{"type":"mention","source":"\#(source)","label":"\#(label)","start":\#(start),"end":\#(start + source.utf16.count)}]"#
+}
+
+func makeEditor(_ value: String, tokensJson: String = "[]") -> T3ComposerEditorView {
let view = T3ComposerEditorView()
view.frame = CGRect(x: 0, y: 0, width: 320, height: 200)
- view.setControlledDocumentJson(document(value, revision: 0))
+ view.setControlledDocumentJson(document(value, revision: 0, tokensJson: tokensJson))
check(view.text == value, "Initial controlled value was not applied")
return view
}
@@ -108,6 +115,37 @@ do {
)
}
+// An echo that only shifts a chip keeps the rendered text; moving or relabeling the chip redraws it.
+do {
+ let draft = "hi! @README.md @README.md"
+ let view = makeEditor("hi @README.md @README.md", tokensJson: mention("README.md", at: 3))
+ let rendered = view.chip(at: 3)
+ check(rendered != nil, "Harness could not render the chip")
+ view.editor.selectedRange = NSRange(location: 2, length: 0)
+ view.editor.insertText("!")
+ let revision = view.onComposerChange.payloads.last?["eventCount"] as? Int ?? 0
+ view.setControlledDocumentJson(document(draft, revision: revision, isNativeEcho: true, tokensJson: mention("README.md", at: 4)))
+ check(view.chip(at: 4) === rendered, "An echo that only moved a chip replaced the text")
+ view.setControlledDocumentJson(document(draft, revision: revision, tokensJson: mention("Readme", at: 4)))
+ check((view.chip(at: 4) as? ComposerTextAttachment)?.label == "Readme", "A relabeled chip was not redrawn")
+ view.setControlledDocumentJson(document(draft, revision: revision, tokensJson: mention("Readme", at: 15)))
+ check(view.chip(at: 4) == nil && view.chip(at: 15) != nil, "A chip moved to another copy of its source stayed on the old one")
+}
+
+// A chip source that changes only in Unicode normalization is rebuilt from the new text.
+do {
+ let view = makeEditor("@\u{00E9}", tokensJson: mention("e", at: 0, source: "@\u{00E9}"))
+ view.setControlledDocumentJson(document("@e\u{0301}", revision: 0, tokensJson: mention("e", at: 0, source: "@e\u{0301}")))
+ check(view.text.utf16.elementsEqual("@e\u{0301}".utf16), "A renormalized chip source kept the old text")
+}
+
+// The placeholder label is hidden from VoiceOver, so the text view must carry it.
+do {
+ let view = makeEditor("")
+ view.setPlaceholder("Ask anything")
+ check(view.editor.accessibilityLabel == "Ask anything", "VoiceOver label: \(String(describing: view.editor.accessibilityLabel))")
+}
+
print("composer editor tests passed")
private let dropEditor = ComposerTextView()
@@ -174,6 +212,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 +247,7 @@ DispatchQueue.main.async {
"The attachment must contain the pasted image's pixels")
check(pasteEditor.text == "Keep this draft", "Image paste must preserve the draft text")
print("Composer provider-paste checks passed")
- exit(0)
+ check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path")
+ gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)])
}
dispatchMain()
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
index af67e80afebb4..5b3d84aedcee3 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
@@ -10,6 +10,9 @@ public final class T3NativeControlsModule: Module {
private let presentationSources = T3PresentationSources()
private var videoPresentation: T3NativeVideoPresentation?
private var filePresentation: T3NativeFilePresentation?
+ /// The last file preview that closed. Written on main, read synchronously from JS.
+ private let filePreviewActivity = NSLock()
+ private var finishedFilePreview: String?
public func definition() -> ModuleDefinition {
Events("videoPlaybackChange")
@@ -94,6 +97,12 @@ public final class T3NativeControlsModule: Module {
file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter)
}.runOnQueue(.main)
+ // A tap can reach JS before the old viewer's close does; this tells it whether that viewer is gone.
+ // A presentation main has not started yet reads as still open.
+ Function("isFilePreviewFinished") { (identifier: String) -> Bool in
+ self.filePreviewActivity.withLock { self.finishedFilePreview == identifier }
+ }
+
// A nil URL marks the item as one that could not be resolved.
AsyncFunction("updateFile") { (identifier: String, index: Int, url: URL?) in
if self.filePresentation?.identifier == identifier { self.filePresentation?.update(index: index, url: url) }
@@ -294,15 +303,22 @@ public final class T3NativeControlsModule: Module {
guard filePresentation == nil, videoPresentation == nil,
appContext?.utilities?.currentViewController() != nil
else { throw URLError(.cannotLoadFromNetwork) }
- let file = T3NativeFilePresentation(identifier: identifier, sources: presentationSources,
- sourceIdentifiers: sourceIdentifiers) { [weak self] error in
- self?.filePresentation = nil
- if let error { promise.reject(error) } else { promise.resolve(nil) }
- }
+ let file = T3NativeFilePresentation(
+ identifier: identifier, sources: presentationSources, sourceIdentifiers: sourceIdentifiers,
+ onFinish: { [weak self] in self?.setFinishedFilePreview(identifier) },
+ completion: { [weak self] error in
+ self?.filePresentation = nil
+ if let error { promise.reject(error) } else { promise.resolve(nil) }
+ }
+ )
filePresentation = file
return file
}
+ private func setFinishedFilePreview(_ identifier: String) {
+ filePreviewActivity.withLock { finishedFilePreview = identifier }
+ }
+
private func presentFile(url: URL, title: String, sourceIdentifier: String,
identifier: String, promise: Promise) throws {
let file = try makeFilePresentation(sourceIdentifiers: [sourceIdentifier], identifier: identifier, promise: promise)
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
index 791e39b2840c0..979e87edc1b0e 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
@@ -8,232 +8,217 @@ private final class FilePreviewItem: NSObject, QLPreviewItem {
var previewItemTitle: String?
}
-private enum FilePreviewState { case loading, ready, failed }
-
private final class FilePreviewController: QLPreviewController {
var onAppear: (() -> Void)?
- // Quick Look shows a blank page for an item without a file, so loading and failure are ours to show.
- private let spinner = UIActivityIndicatorView(style: .large)
- private let failure = UILabel()
- var state = FilePreviewState.ready {
- didSet { if isViewLoaded { showState() } }
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
- failure.text = "This image could not be loaded."
- failure.textColor = .secondaryLabel
- failure.textAlignment = .center
- failure.numberOfLines = 0
- for status in [spinner, failure] as [UIView] {
- status.isUserInteractionEnabled = false
- status.translatesAutoresizingMaskIntoConstraints = false
- view.addSubview(status)
- NSLayoutConstraint.activate([
- status.centerXAnchor.constraint(equalTo: view.centerXAnchor),
- status.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 64),
- status.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, constant: -48),
- ])
- }
- showState()
- }
-
- override func viewDidLayoutSubviews() {
- super.viewDidLayoutSubviews()
- view.bringSubviewToFront(spinner)
- view.bringSubviewToFront(failure)
- }
+ var onDismiss: (() -> Void)?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
onAppear?()
}
- private func showState() {
- if state == .loading { spinner.startAnimating() } else { spinner.stopAnimating() }
- failure.isHidden = state != .failed
+ // Quick Look's own didDismiss callback can lag well behind the screen being tappable again,
+ // so a tap on the thumbnail in that gap would land while JS still thinks the viewer is open.
+ override func viewDidDisappear(_ animated: Bool) {
+ super.viewDidDisappear(animated)
+ if isBeingDismissed { onDismiss?() }
}
}
+/// How long the gallery waits for siblings once the selected file is ready; later ones are left out.
+private let siblingGraceNanoseconds: UInt64 = 1_000_000_000
+/// A load faster than this zooms straight from the thumbnail without a spinner.
+private let spinnerDelayNanoseconds: UInt64 = 250_000_000
+
+/// Quick Look only ever receives pages whose file is on disk: a page refreshed after it first
+/// rendered blank keeps a stale scroll offset, so drags scroll the image instead of paging or dismissing.
final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate {
let identifier: String
private var controller: FilePreviewController?
private let completion: (Error?) -> Void
+ private let onFinish: () -> Void
private weak var sources: T3PresentationSources?
private let sourceIdentifiers: [String]
- private var items: [FilePreviewItem] = []
+ private var titles: [String] = []
private var urls: [URL?] = []
- private var states: [FilePreviewState] = []
+ /// A prepared file, or nil while loading or after failing; `settled` tells those apart.
+ private var files: [URL?] = []
+ private var settled: [Bool] = []
+ private var downloads: [Int: Task] = [:]
private var selectedIndex = 0
+ /// The pages Quick Look shows, as indices into `files`.
+ private var pages: [Int] = []
+ private var items: [FilePreviewItem] = []
private weak var presenter: UIViewController?
- /// Files that arrived while their page was off screen; Quick Look may still hold the blank page.
- private var staleIndices = Set()
- private var currentIndexObservation: NSKeyValueObservation?
- private var download: (index: Int, task: Task)?
- private var placeholder: Task?
+ private var grace: Task?
+ private var spinnerDelay: Task?
+ private var spinner: UIView?
private var openError: Error?
private var dismissRequested = false
private var finished = false
init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String],
- completion: @escaping (Error?) -> Void) {
+ onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) {
self.identifier = identifier
self.sources = sources
self.sourceIdentifiers = sourceIdentifiers
+ self.onFinish = onFinish
self.completion = completion
super.init()
}
/// Downloads the file before presenting so Quick Look can refuse a format the caller should share instead.
func present(url: URL, title: String, from presenter: UIViewController) {
- load(urls: [url], titles: [title], selectedIndex: 0, from: presenter, opensWhileLoading: false)
+ present(urls: [url], titles: [title], selectedIndex: 0, from: presenter)
}
- /// Opens the selected image once it is ready, or a loading page if it is slow, and loads the rest
- /// of the gallery behind it so a slow or broken sibling never holds the viewer back.
+ /// Loads the gallery in parallel and opens once the selected file is ready, with whichever
+ /// siblings are ready by the end of a short grace, so a slow or broken one never holds it back.
func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) {
- load(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter, opensWhileLoading: true)
+ self.titles = titles
+ self.urls = urls
+ self.selectedIndex = selectedIndex
+ self.presenter = presenter
+ files = Array(repeating: nil, count: urls.count)
+ settled = Array(repeating: false, count: urls.count)
+ spinnerDelay = Task { @MainActor [self] in
+ try? await Task.sleep(nanoseconds: spinnerDelayNanoseconds)
+ guard !Task.isCancelled else { return }
+ showSpinner()
+ }
+ for index in urls.indices { download(index) }
}
/// Delivers a URL that was still resolving when the gallery opened, or nil when it never will.
func update(index: Int, url: URL?) {
- guard !finished, urls.indices.contains(index), urls[index] == nil, states[index] == .loading else { return }
+ guard !finished, controller == nil, urls.indices.contains(index), urls[index] == nil,
+ !settled[index]
+ else { return }
guard let url else {
- failed(index, error: URLError(.resourceUnavailable))
+ settle(index, result: .failure(URLError(.resourceUnavailable)))
return
}
urls[index] = url
- loadNext()
- }
-
- private func load(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController,
- opensWhileLoading: Bool) {
- items = titles.map { title in
- let item = FilePreviewItem()
- item.previewItemTitle = title
- return item
- }
- self.urls = urls
- self.selectedIndex = selectedIndex
- self.presenter = presenter
- states = Array(repeating: .loading, count: urls.count)
- if opensWhileLoading {
- // A short grace keeps the zoom from the thumbnail into a loaded image when the file is quick.
- placeholder = Task { @MainActor [self] in
- try? await Task.sleep(nanoseconds: 250_000_000)
- guard !Task.isCancelled, !finished, controller == nil else { return }
- show()
- }
- }
- loadNext()
+ download(index)
}
- /// Downloads one file at a time, nearest the page on screen first. The page on screen takes over
- /// from a background download, which restarts later.
- private func loadNext() {
- guard !finished, !dismissRequested else { return }
- let current = controller?.currentPreviewItemIndex ?? selectedIndex
- guard let next = urls.indices
- .filter({ urls[$0] != nil && states[$0] == .loading })
- .min(by: { abs($0 - current) < abs($1 - current) })
- else { return }
- if let download {
- guard next == current, download.index != current else { return }
- download.task.cancel()
- }
- guard let url = urls[next] else { return }
- let title = items[next].previewItemTitle ?? ""
- let task = Task { @MainActor [self] in
+ private func download(_ index: Int) {
+ guard let url = urls[index], downloads[index] == nil else { return }
+ let title = titles[index]
+ downloads[index] = Task { @MainActor [self] in
let result: Result
do {
result = .success(try await Self.prepareFile(url: url, title: title))
} catch {
result = .failure(error)
}
- guard !finished, !Task.isCancelled else {
- if case .success(let file) = result {
- try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
- }
- return
- }
- download = nil
- switch result {
- case .success(let file): loaded(next, file: file)
- case .failure(let error): failed(next, error: error)
- }
- loadNext()
+ downloads[index] = nil
+ settle(index, result: result)
}
- download = (next, task)
}
- private func loaded(_ index: Int, file: URL) {
- // Quick Look knows which formats it renders; refuse before presenting so the caller
- // can fall back instead of showing an "unsupported format" page.
- guard QLPreviewController.canPreview(file as NSURL) else {
- try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
- failed(index, error: NSError(
- domain: "T3NativePresentation",
- code: 3,
- userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
- ))
+ private func settle(_ index: Int, result: Result) {
+ guard !finished, controller == nil, !dismissRequested else {
+ if case .success(let file) = result { Self.remove(file) }
return
}
- items[index].previewItemURL = file
- states[index] = .ready
- if controller != nil { refresh(index) } else if index == selectedIndex { show() }
- }
-
- private func failed(_ index: Int, error: Error) {
- guard index != selectedIndex else {
+ settled[index] = true
+ if let error = store(index, result: result), index == selectedIndex {
openError = error
dismiss()
return
}
- states[index] = .failed
- refresh(index)
+ guard files[selectedIndex] != nil else { return }
+ if settled.allSatisfy({ $0 }) {
+ show()
+ } else if grace == nil {
+ grace = Task { @MainActor [self] in
+ try? await Task.sleep(nanoseconds: siblingGraceNanoseconds)
+ guard !Task.isCancelled else { return }
+ show()
+ }
+ }
+ }
+
+ private func store(_ index: Int, result: Result) -> Error? {
+ switch result {
+ case .success(let file):
+ // Quick Look knows which formats it renders; refuse before presenting so the caller
+ // can fall back instead of showing an "unsupported format" page.
+ guard QLPreviewController.canPreview(file as NSURL) else {
+ Self.remove(file)
+ return NSError(
+ domain: "T3NativePresentation",
+ code: 3,
+ userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
+ )
+ }
+ files[index] = file
+ return nil
+ case .failure(let error):
+ return error
+ }
}
private func show() {
+ guard !finished, controller == nil, !dismissRequested else { return }
guard let presenter else { finish(); return }
- placeholder?.cancel()
+ cancelLoading()
+ pages = files.indices.filter { files[$0] != nil }
+ items = pages.map { index in
+ let item = FilePreviewItem()
+ item.previewItemURL = files[index]
+ item.previewItemTitle = titles[index]
+ return item
+ }
let preview = FilePreviewController()
preview.delegate = self
preview.dataSource = self
- preview.currentPreviewItemIndex = selectedIndex
+ preview.currentPreviewItemIndex = pages.firstIndex(of: selectedIndex) ?? 0
preview.onAppear = { [weak self] in self?.resumePendingDismissal() }
+ preview.onDismiss = { [weak self] in self?.finish() }
controller = preview
- preview.state = states[selectedIndex]
- currentIndexObservation = preview.observe(\.currentPreviewItemIndex) { [weak self] _, _ in
- DispatchQueue.main.async { self?.currentItemChanged() }
- }
presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in
resumePendingDismissal()
}
preview.presentationController?.delegate = self
}
- private func refresh(_ index: Int) {
- guard let controller else { return }
- guard controller.currentPreviewItemIndex == index else {
- if states[index] == .ready { staleIndices.insert(index) }
- return
- }
- if states[index] == .ready { controller.refreshCurrentPreviewItem() }
- controller.state = states[index]
+ /// Shows over the tapped thumbnail that a slow open is on its way.
+ private func showSpinner() {
+ guard !finished, controller == nil, spinner == nil,
+ sourceIdentifiers.indices.contains(selectedIndex),
+ let source = sources?.view(for: sourceIdentifiers[selectedIndex]),
+ let window = source.window
+ else { return }
+ let backing = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
+ backing.backgroundColor = UIColor.black.withAlphaComponent(0.55)
+ backing.layer.cornerRadius = 22
+ backing.isUserInteractionEnabled = false
+ let indicator = UIActivityIndicatorView(style: .medium)
+ indicator.color = .white
+ indicator.center = CGPoint(x: 22, y: 22)
+ indicator.startAnimating()
+ backing.addSubview(indicator)
+ backing.center = source.convert(CGPoint(x: source.bounds.midX, y: source.bounds.midY), to: window)
+ window.addSubview(backing)
+ spinner = backing
}
- private func currentItemChanged() {
- guard !finished, let controller, states.indices.contains(controller.currentPreviewItemIndex) else { return }
- let index = controller.currentPreviewItemIndex
- if staleIndices.remove(index) != nil { controller.refreshCurrentPreviewItem() }
- controller.state = states[index]
- loadNext()
+ private func cancelLoading() {
+ for task in downloads.values { task.cancel() }
+ downloads.removeAll()
+ grace?.cancel()
+ grace = nil
+ spinnerDelay?.cancel()
+ spinnerDelay = nil
+ spinner?.removeFromSuperview()
+ spinner = nil
}
func dismiss() {
dismissRequested = true
- download?.task.cancel()
guard !finished else { return }
guard let controller else { finish(); return }
// Drain Close from viewDidAppear after opening or cancelling an interactive dismissal.
@@ -257,10 +242,10 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
private func sourceView(for item: QLPreviewItem) -> UIView? {
guard !UIAccessibility.isReduceMotionEnabled,
- let index = items.firstIndex(where: { $0 === item }),
- sourceIdentifiers.indices.contains(index)
+ let page = items.firstIndex(where: { $0 === item }),
+ sourceIdentifiers.indices.contains(pages[page])
else { return nil }
- return sources?.view(for: sourceIdentifiers[index])
+ return sources?.view(for: sourceIdentifiers[pages[page]])
}
func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? {
@@ -278,24 +263,20 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish() }
- private func finish(error: Error? = nil) {
+ private func finish() {
guard !finished else { return }
finished = true
- download?.task.cancel()
- download = nil
- placeholder?.cancel()
- placeholder = nil
- currentIndexObservation = nil
- for item in items {
- if let file = item.previewItemURL {
- try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
- }
- }
+ cancelLoading()
+ for file in files.compactMap({ $0 }) { Self.remove(file) }
+ files.removeAll()
items.removeAll()
- urls.removeAll()
- states.removeAll()
- let result = error ?? openError
- DispatchQueue.main.async { [completion] in completion(result) }
+ DispatchQueue.main.async { [completion, openError] in completion(openError) }
+ // After queueing the completion, so a new presentation JS starts on seeing this lands behind it.
+ onFinish()
+ }
+
+ private static func remove(_ file: URL) {
+ try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
}
/// Copy original bytes so preview and sharing do not mutate a draft or workspace file.
@@ -305,6 +286,7 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
do {
let download = directory.appendingPathComponent("original")
+ var mimeType: String?
if url.isFileURL {
try FileManager.default.copyItem(at: url, to: download)
} else if url.scheme == "data" {
@@ -317,6 +299,7 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
throw URLError(.badServerResponse)
}
+ mimeType = response.mimeType
try FileManager.default.moveItem(at: temporaryFile, to: download)
}
try Task.checkCancellation()
@@ -330,7 +313,8 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
type = detectedType
} else if CGPDFDocument(download as CFURL) != nil {
type = .pdf
- } else if originalExtension.lowercased() == "svg" {
+ } else if originalExtension.lowercased() == "svg" || mimeType == "image/svg+xml" {
+ // ImageIO cannot read SVG, and served images such as QR codes often have no extension.
type = .svg
}
let fileExtension: String
diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt
index 7a1225cd392bf..2f1e4d9fd4a43 100644
--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt
+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt
@@ -402,7 +402,7 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
@Suppress("LongParameterList")
fun drawCode(
canvas: Canvas,
- content: String,
+ row: DiffRow,
tokens: List?,
codeX: Float,
baseline: Float,
@@ -417,12 +417,16 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
canvas.restore()
return
}
- val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(content, null, 0)) else tokens
+ val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(row.content, null, 0)) else tokens
var line = 0
var x = codeX
var column = 0
- runs.forEach { run ->
- configureCodePaint(run.color ?: theme.text, run.fontStyle, style)
+ splitAtNote(runs, row.noteStart).forEach { (run, note) ->
+ configureCodePaint(
+ if (note) theme.warningText else run.color ?: theme.text,
+ run.fontStyle,
+ style,
+ )
var start = 0
while (start < run.content.length) {
while (line + 1 < lines.starts.size && lines.starts[line + 1] <= column + start) {
@@ -434,8 +438,10 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
if (lineBaseline + textPaint.fontMetrics.descent >= canvas.clipBounds.top &&
lineBaseline + textPaint.fontMetrics.ascent <= canvas.clipBounds.bottom
) {
+ val segmentWidth = textPaint.measureText(run.content, start, end)
+ fillNote(canvas, note, x, x + segmentWidth, lineBaseline)
canvas.drawText(run.content, start, end, x, lineBaseline, textPaint)
- x += textPaint.measureText(run.content, start, end)
+ x += segmentWidth
}
start = end
}
@@ -443,6 +449,21 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
}
}
+ fun noticeColor(row: DiffRow): Int =
+ if (row.tone == "warning") theme.warningText else theme.mutedText
+
+ fun noticeFill(row: DiffRow): Int =
+ if (row.tone == "warning") theme.warningBackground else theme.background
+
+ /** Fills behind a segment of a cut line's note; other segments are left alone. */
+ private fun fillNote(canvas: Canvas, note: Boolean, left: Float, right: Float, baseline: Float) {
+ if (!note) return
+ backgroundPaint.color = theme.warningBackground
+ val metrics = textPaint.fontMetrics
+ val top = baseline + metrics.ascent
+ canvas.drawRect(left, top, right, baseline + metrics.descent, backgroundPaint)
+ }
+
fun drawFileHeaderPathScrollFades(
canvas: Canvas,
pathRect: RectF,
@@ -532,3 +553,24 @@ private object ReviewDiffTypefaces {
else -> regular
}
}
+
+/** Splits color runs where a cut line's note starts; the flag marks the note's runs. */
+private fun splitAtNote(runs: List, noteStart: Int?): List> {
+ if (noteStart == null) return runs.map { it to false }
+ return buildList {
+ var offset = 0
+ for (run in runs) {
+ val end = offset + run.content.length
+ when {
+ end <= noteStart -> add(run to false)
+ offset >= noteStart -> add(run to true)
+ else -> {
+ val cut = noteStart - offset
+ add(run.copy(content = run.content.substring(0, cut)) to false)
+ add(run.copy(content = run.content.substring(cut)) to true)
+ }
+ }
+ offset = end
+ }
+ }
+}
diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt
index 770bc656de569..83f32788e8ab8 100644
--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt
+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt
@@ -182,6 +182,20 @@ internal class CodeLayoutCache {
}
}
}
+ row.noteStart?.takeIf { it in 0 until text.length }?.let { start ->
+ text.setSpan(
+ ForegroundColorSpan(theme.warningText),
+ start,
+ text.length,
+ Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
+ )
+ text.setSpan(
+ BackgroundColorSpan(theme.warningBackground),
+ start,
+ text.length,
+ Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
+ )
+ }
return text
}
}
diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt
index 63ab13dde3d12..03609e3658e84 100644
--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt
+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt
@@ -4,6 +4,16 @@ import expo.modules.kotlin.Promise
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
+private val REVIEW_DIFF_EVENTS = arrayOf(
+ "onDebug",
+ "onVisibleFileChange",
+ "onToggleFile",
+ "onToggleViewedFile",
+ "onPressLine",
+ "onToggleComment",
+ "onPressNotice",
+)
+
class T3ReviewDiffModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3ReviewDiffSurface")
@@ -54,14 +64,7 @@ class T3ReviewDiffModule : Module() {
view.setInitialFileId(fileId)
}
- Events(
- "onDebug",
- "onVisibleFileChange",
- "onToggleFile",
- "onToggleViewedFile",
- "onPressLine",
- "onToggleComment",
- )
+ Events(REVIEW_DIFF_EVENTS)
AsyncFunction("scrollToFile") { view: T3ReviewDiffView, fileId: String, animated: Boolean ->
view.scrollToFile(fileId, animated)
diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
index 54ff86c611a8e..91bb6719ed8fa 100644
--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
@@ -31,6 +31,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
private val onToggleViewedFile by EventDispatcher()
private val onPressLine by EventDispatcher()
private val onToggleComment by EventDispatcher()
+ private val onPressNotice by EventDispatcher()
private var rows: List = emptyList()
private var visibleRows: List = emptyList()
private var visibleRowIndices = IntArray(0)
@@ -432,6 +433,9 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
}
}
"comment" -> onToggleComment(mapOf("commentId" to row.id))
+ "notice" -> if (gesture == "tap" && row.actionable) {
+ onPressNotice(mapOf("rowId" to row.id, "fileId" to row.resolvedFileId))
+ }
"line" -> {
val payload = mutableMapOf(
"rowId" to row.id,
@@ -534,7 +538,13 @@ internal data class DiffRow(
val wordDiffRanges: List,
val commentText: String,
val commentRangeLabel: String,
- val commentSectionTitle: String
+ val commentSectionTitle: String,
+ /** A notice drawn in the warning colors. */
+ val tone: String = "",
+ /** A notice that reports taps through `onPressNotice`. */
+ val actionable: Boolean = false,
+ /** Where a cut line's note starts in `content`. */
+ val noteStart: Int? = null
) {
val resolvedFileId: String get() = fileId.ifEmpty { id }
val isPlainAscii: Boolean = content.all { it in ' '..'~' }
@@ -564,7 +574,9 @@ internal data class DiffTheme(
val addBar: Int,
val deleteBar: Int,
val addText: Int,
- val deleteText: Int
+ val deleteText: Int,
+ val warningText: Int,
+ val warningBackground: Int
) {
companion object {
fun fallback(scheme: String): DiffTheme = if (scheme == "dark") {
@@ -582,6 +594,8 @@ internal data class DiffTheme(
deleteBar = Color.rgb(255, 46, 63),
addText = Color.rgb(94, 204, 113),
deleteText = Color.rgb(255, 103, 98),
+ warningText = Color.rgb(250, 204, 102),
+ warningBackground = Color.rgb(51, 38, 13),
)
} else {
DiffTheme(
@@ -598,6 +612,8 @@ internal data class DiffTheme(
deleteBar = Color.rgb(213, 44, 54),
addText = Color.rgb(25, 130, 67),
deleteText = Color.rgb(190, 38, 48),
+ warningText = Color.rgb(140, 92, 0),
+ warningBackground = Color.rgb(255, 245, 214),
)
}
@@ -617,6 +633,8 @@ internal data class DiffTheme(
deleteBar = color(json, "deleteBar", fallback.deleteBar),
addText = color(json, "addText", fallback.addText),
deleteText = color(json, "deleteText", fallback.deleteText),
+ warningText = color(json, "warningText", fallback.warningText),
+ warningBackground = color(json, "warningBackground", fallback.warningBackground),
)
} catch (_: Exception) {
fallback
@@ -1189,7 +1207,7 @@ private class DiffCanvasView(context: Context) : View(context) {
}
private fun drawNoticeRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
- fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
+ fill(canvas, drawing.noticeFill(row), 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
val iconSize = 16f * density
val iconRect = RectF(
style.fileHeaderHorizontalPaddingPx + 2f * density,
@@ -1197,10 +1215,10 @@ private class DiffCanvasView(context: Context) : View(context) {
style.fileHeaderHorizontalPaddingPx + 2f * density + iconSize,
(top + bottom + iconSize) / 2f,
)
- drawing.drawNoticeIcon(canvas, iconRect, theme.mutedText)
+ drawing.drawNoticeIcon(canvas, iconRect, drawing.noticeColor(row))
drawing.configureUiPaint(
paint = textPaint,
- color = theme.mutedText,
+ color = drawing.noticeColor(row),
size = style.fileHeaderSubtextFontSizePx,
weight = style.fileHeaderSubtextFontWeight,
)
@@ -1313,7 +1331,7 @@ private class DiffCanvasView(context: Context) : View(context) {
drawing.configureCodePaint(theme.text, 0, style)
drawing.drawWordDiffRanges(canvas, row, codeX, top, firstLineBottom, lines)
val baseline = lines.baseline(top, firstLineBottom, textPaint)
- drawing.drawCode(canvas, row.content, tokensByRowId[row.id], codeX, baseline, style, lines)
+ drawing.drawCode(canvas, row, tokensByRowId[row.id], codeX, baseline, style, lines)
}
drawLineNumber(canvas, row, top, firstLineBottom)
@@ -1488,6 +1506,9 @@ private fun parseRows(value: String, isCancelled: () -> Boolean): List
commentText = row.optString("commentText"),
commentRangeLabel = row.optString("commentRangeLabel"),
commentSectionTitle = row.optString("commentSectionTitle"),
+ tone = row.optString("tone"),
+ actionable = row.optBoolean("actionable"),
+ noteStart = row.optNullableInt("noteStart"),
)
}
} catch (_: Exception) {
diff --git a/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift b/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift
index 7f96dc17a25e6..4c60b20c1add5 100644
--- a/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift
+++ b/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift
@@ -16,6 +16,13 @@ struct ReviewDiffCodeLineStarts: RandomAccessCollection {
/// ASCII uses fixed-pitch columns. TextKit handles shaping, tabs, and Unicode highlights.
/// Pass `unboundedWidth` to lay a row out on one line for horizontal scrolling.
+/** A cut line's note, drawn in its own colors. */
+struct ReviewDiffCodeNote {
+ let range: NSRange
+ let color: UIColor
+ let background: UIColor
+}
+
final class ReviewDiffCodeLayout: NSObject {
static let unboundedWidth = CGFloat.greatestFiniteMagnitude
@@ -84,7 +91,14 @@ final class ReviewDiffCodeLayout: NSObject {
return layout
}
- func decorate(text: NSAttributedString, highlights: [NSRange], color: UIColor, version: Int) {
+ // A cut line's note is not code, so it takes the warning colors over any token color.
+ func decorate(
+ text: NSAttributedString,
+ highlights: [NSRange],
+ color: UIColor,
+ note: ReviewDiffCodeNote? = nil,
+ version: Int
+ ) {
guard usesNativeLayout else { return }
let layout = nativeLayout()
guard layout.decorationVersion != version else { return }
@@ -105,6 +119,13 @@ final class ReviewDiffCodeLayout: NSObject {
storage.addAttribute(.backgroundColor, value: color, range: intersection)
}
}
+ if let note {
+ let intersection = NSIntersectionRange(note.range, fullRange)
+ if intersection.length > 0 {
+ storage.addAttribute(.foregroundColor, value: note.color, range: intersection)
+ storage.addAttribute(.backgroundColor, value: note.background, range: intersection)
+ }
+ }
storage.endEditing()
layout.decorationVersion = version
}
diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift
index 2fcb8a4801809..d1be707b0d9d6 100644
--- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift
+++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift
@@ -88,6 +88,7 @@ public class T3ReviewDiffModule: Module {
"onToggleViewedFile",
"onPressLine",
"onToggleComment",
+ "onPressNotice",
"onPullToRefresh"
)
diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
index cc51c40a7e77f..b427c535d6f4c 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)
)
}
}
@@ -354,6 +371,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()
@@ -387,6 +405,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)
}
@@ -1232,6 +1253,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 {
@@ -1573,6 +1595,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
@@ -2218,7 +2245,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
@@ -2232,7 +2260,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 ?? "",
@@ -2242,7 +2271,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
)
}
@@ -2572,6 +2601,13 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
NSRange(location: $0.start, length: $0.end - $0.start)
},
color: (change == "add" ? theme.addBar : theme.deleteBar).withAlphaComponent(0.28),
+ note: row.noteStart.map {
+ ReviewDiffCodeNote(
+ range: NSRange(location: $0, length: max(0, text.length - $0)),
+ color: theme.warningText,
+ background: theme.warningBackground
+ )
+ },
version: codeDecorationVersion
)
layout.draw(
diff --git a/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md b/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md
index 0f8a18d50cbd0..91e74e697bab0 100644
--- a/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md
+++ b/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md
@@ -21,7 +21,7 @@ The Android terminal renderer vendors upstream `libghostty-vt` shared libraries
The web terminal vendors a WebAssembly build from the same revision and uses the same C ABI.
- Upstream project: https://github.com/ghostty-org/ghostty
-- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
+- Vendored revision: `3ff6d08fad56f2d6b81420a27bdc56ee707b453e`
- License: MIT
Ghostty's MIT license applies to the vendored Android and web libraries. Keep this notice and both
diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so
index e086ca8315565..9e3ed70cf88ad 100755
Binary files a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so differ
diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so
index 5592142ffce8c..9174c0be80f44 100755
Binary files a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so differ
diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so
index bacab7908336a..db7667ea3559b 100755
Binary files a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so differ
diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so
index f6e0b646a2fb2..0a1f011f8c133 100755
Binary files a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so differ
diff --git a/apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh b/apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
index 55d994d3b363c..b9e225eff4bcd 100755
--- a/apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
+++ b/apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
@@ -7,7 +7,7 @@ MODULE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
VENDOR_DIR="${MODULE_DIR}/../../../../native/libghostty-vt"
PATCH_DIR="${SCRIPT_DIR}/libghostty-android-patches"
-GHOSTTY_REVISION="${GHOSTTY_REVISION:-9f62873bf195e4d8a762d768a1405a5f2f7b1697}"
+GHOSTTY_REVISION="${GHOSTTY_REVISION:-3ff6d08fad56f2d6b81420a27bdc56ee707b453e}"
GHOSTTY_SOURCE_DIR="${GHOSTTY_SOURCE_DIR:-${HOME}/.cache/t3code/ghostty-${GHOSTTY_REVISION:0:8}}"
GHOSTTY_ZIG_VERSION="${GHOSTTY_ZIG_VERSION:-0.15.2}"
GHOSTTY_ZIG="${GHOSTTY_ZIG:-}"
diff --git a/apps/mobile/src/components/ComposerEditor.ios.test.tsx b/apps/mobile/src/components/ComposerEditor.ios.test.tsx
index f7ce1f9918d85..029f454b902f7 100644
--- a/apps/mobile/src/components/ComposerEditor.ios.test.tsx
+++ b/apps/mobile/src/components/ComposerEditor.ios.test.tsx
@@ -128,7 +128,7 @@ vi.mock("../lib/useUniwindTheme", () => ({ useUniwindTheme: () => ({}) }));
vi.mock("../lib/nativeComposerTheme", () => ({ createNativeComposerTheme: () => ({}) }));
vi.mock("../lib/contextChipIconSource", () => ({ contextChipIconUri: () => "" }));
vi.mock("../features/settings/appearance/useScaledTextRole", () => ({
- useScaledTextRole: () => ({ fontSize: 16, lineHeight: 22 }),
+ useComposerTextRole: () => ({ fontSize: 16, lineHeight: 22 }),
}));
vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "0000" }));
vi.mock("../state/assets", () => ({ assetEnvironment: {} }));
diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx
index f7118b95b425f..bae452bad7c48 100644
--- a/apps/mobile/src/components/ComposerEditor.tsx
+++ b/apps/mobile/src/components/ComposerEditor.tsx
@@ -76,7 +76,7 @@ export function ComposerEditor({
props.onChangeText(text);
if (draftKey) {
setComposerDraftContext(draftKey, restored.context);
- appendComposerDraftAttachments(draftKey, restored.attachments, { allowOverflow: true });
+ appendComposerDraftAttachments(draftKey, restored.attachments, { restore: true });
}
};
const [selected, setSelected] = useState<{ source: string; start: number; end: number } | null>(
diff --git a/apps/mobile/src/components/ComposerToolbar.tsx b/apps/mobile/src/components/ComposerToolbar.tsx
index 4fd54085c45f1..fdbf27b6f2c25 100644
--- a/apps/mobile/src/components/ComposerToolbar.tsx
+++ b/apps/mobile/src/components/ComposerToolbar.tsx
@@ -285,6 +285,7 @@ export function ComposerActionButton(props: {
}) {
const { scale, smallIconSize } = useAndroidControlSizing();
const circleSize = Math.round((props.size === "large" ? 44 : 30) * scale);
+ const fadeIcon = props.disabled === true && props.variant !== "danger";
return (
-
+ {/* Fade the icon as one layer: a translucent tint, or opacity on a Tabler icon (which
+ copies it onto every path), stacks where the SVG strokes overlap. */}
+
+
+
);
diff --git a/apps/mobile/src/components/VideoThumbnailImage.tsx b/apps/mobile/src/components/VideoThumbnailImage.tsx
index 6f6fea83063ca..f4ddb25a276fb 100644
--- a/apps/mobile/src/components/VideoThumbnailImage.tsx
+++ b/apps/mobile/src/components/VideoThumbnailImage.tsx
@@ -41,7 +41,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,
diff --git a/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx b/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx
index a17e48c2604c7..f9e3b2ac01249 100644
--- a/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx
+++ b/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx
@@ -61,6 +61,10 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
setPath([]);
setOverlay(null);
};
+ // The in-window menu is pinned to the trigger's spot above the keyboard, which is stale once it hides.
+ if (anchor?.keyboardWasVisible === true && !keyboardVisible) {
+ close();
+ }
const open = () => {
anchorNode?.measureInWindow((x, y, width, height) => {
diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx
index 7aaeac554417a..b34c27bd471f3 100644
--- a/apps/mobile/src/components/ui/AppSymbol.android.tsx
+++ b/apps/mobile/src/components/ui/AppSymbol.android.tsx
@@ -140,6 +140,7 @@ import IconWifiOff from "@tabler/icons-react-native/IconWifiOff";
import IconWorld from "@tabler/icons-react-native/IconWorld";
import IconX from "@tabler/icons-react-native/IconX";
import type { AndroidSymbol, SFSymbol, SymbolViewProps } from "expo-symbols";
+import { StyleSheet, View } from "react-native";
import { withUniwind } from "uniwind";
const ANDROID_ICON_BY_SF_SYMBOL = {
@@ -371,16 +372,20 @@ function AppSymbolView(props: AppSymbolViewProps) {
return props.fallback ?? null;
}
- return (
+ // react-native-svg applies style.transform to its inner path around (0,0), so a
+ // rotated icon draws outside its box. Transform a wrapping View instead.
+ const transformed = StyleSheet.flatten(props.style)?.transform !== undefined;
+ const icon = (
);
+ return transformed ? {icon} : icon;
}
export const SymbolView = withUniwind(AppSymbolView);
diff --git a/apps/mobile/src/components/ui/FilePreviewModal.tsx b/apps/mobile/src/components/ui/FilePreviewModal.tsx
index aff82eae479cd..eba89cdb28c9b 100644
--- a/apps/mobile/src/components/ui/FilePreviewModal.tsx
+++ b/apps/mobile/src/components/ui/FilePreviewModal.tsx
@@ -31,6 +31,7 @@ const NativeControls = requireNativeModule<{
): Promise;
updateFile(identifier: string, index: number, uri: string | null): Promise;
dismissFile(identifier: string): Promise;
+ isFilePreviewFinished(identifier: string): boolean;
}>("T3NativeControls");
// Null tells the viewer an image failed; undefined means its URL has not arrived yet.
@@ -38,10 +39,11 @@ const nativeUri = (image: FilePreviewImage) => (image.failed ? null : image.uri)
function NativeFilePreview(props: FilePreviewViewerProps) {
const identifier = useId();
- // Later URLs reach the open viewer through updateFile instead of presenting again.
+ // Later URLs reach the native presentation through updateFile instead of presenting again.
const [presented] = useState(props.source);
const delivered = useRef<(string | null | undefined)[]>([]);
const onRequestClose = useEffectEvent(props.onRequestClose);
+ const onPresent = useEffectEvent((isFinished: () => boolean) => props.onPresent?.(isFinished));
const onOpenError = useEffectEvent((error: unknown) => {
if (props.onOpenError) props.onOpenError(error);
else Dialog.alert("Could not open preview", "The file could not be loaded. Please try again.");
@@ -51,7 +53,7 @@ function NativeFilePreview(props: FilePreviewViewerProps) {
useEffect(() => {
let canceled = false;
let presentation: Promise;
- // Images open while still loading; other files must download first so Quick Look can refuse them.
+ // Images hand over before every URL resolves; other files must download first so Quick Look can refuse them.
if (presented.kind === "image") {
const { images, selectedIndex } = presented;
delivered.current = images.map((image) => image.uri);
@@ -71,6 +73,7 @@ function NativeFilePreview(props: FilePreviewViewerProps) {
identifier,
);
}
+ onPresent(() => NativeControls.isFilePreviewFinished(identifier));
void presentation
.catch((error: unknown) => {
if (!canceled) onOpenError(error);
diff --git a/apps/mobile/src/components/ui/FilePreviewModal.types.ts b/apps/mobile/src/components/ui/FilePreviewModal.types.ts
index 37dd9ea9e16b0..4311776b0ad9e 100644
--- a/apps/mobile/src/components/ui/FilePreviewModal.types.ts
+++ b/apps/mobile/src/components/ui/FilePreviewModal.types.ts
@@ -54,4 +54,6 @@ export interface FilePreviewViewerProps {
readonly source: ResolvedFilePreviewSource;
readonly onRequestClose: () => void;
readonly onOpenError?: (error: unknown) => void;
+ /** Called once the viewer hands its file to a native presentation, with a check for its close. */
+ readonly onPresent?: (isFinished: () => boolean) => void;
}
diff --git a/apps/mobile/src/components/ui/FilePreviewSession.test.tsx b/apps/mobile/src/components/ui/FilePreviewSession.test.tsx
index a5b51aa5cf4b3..8a38a70605cd6 100644
--- a/apps/mobile/src/components/ui/FilePreviewSession.test.tsx
+++ b/apps/mobile/src/components/ui/FilePreviewSession.test.tsx
@@ -1,4 +1,4 @@
-import { act, useState } from "react";
+import { act, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { expect, it, vi } from "vite-plus/test";
import {
@@ -14,6 +14,7 @@ const harness = vi.hoisted(() => ({
alert: vi.fn(),
previews: [] as unknown[],
mounts: 0,
+ presentationFinished: false,
}));
vi.mock("../../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl }));
@@ -32,6 +33,9 @@ import { FilePreviewSession } from "./FilePreviewSession";
function Viewer(props: FilePreviewViewerProps) {
useState(() => harness.mounts++);
harness.previews.push(props.source);
+ const { onPresent } = props;
+ // Stands in for the native presentation starting.
+ useEffect(() => onPresent?.(() => harness.presentationFinished), [onPresent]);
return null;
}
@@ -171,3 +175,70 @@ it("names the checked path when the server cannot find the file", async () => {
);
expect(harness.alert.mock.calls[0]?.[1]).not.toMatch(/reconnect/i);
});
+
+it.each([
+ // Handed to native but not yet started there, or still on screen.
+ ["image", false, 1],
+ ["image", true, 2],
+ // A PDF is still resolving here, so its viewer never presented and a re-render must not restart it.
+ ["pdf", true, 1],
+] as const)(
+ "a re-tap of the open %s restarts the preview only once its native viewer closed (closed: %s)",
+ async (kind, finished, starts) => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ harness.presentationFinished = finished;
+ harness.mounts = 0;
+ harness.refreshAssetUrl.mockReset();
+ if (kind === "image") harness.refreshAssetUrl.mockResolvedValue("https://signed.test/a.png");
+ else harness.refreshAssetUrl.mockReturnValue(new Promise(() => {}));
+ const selected: FilePreviewItem = { ...image("https://github.com/a.png"), kind };
+ const root = createRoot(document.createElement("div"));
+ await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
+ const render = () =>
+ act(async () =>
+ root.render(
+ {}}
+ progressiveGallery
+ Viewer={Viewer}
+ />,
+ ),
+ );
+ await render();
+ await render();
+ expect(harness.refreshAssetUrl).toHaveBeenCalledTimes(starts);
+ },
+);
+
+it("does not carry a presented viewer over to a different item that is still resolving", async () => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ harness.presentationFinished = true;
+ harness.refreshAssetUrl.mockReset();
+ harness.refreshAssetUrl.mockImplementation((_environmentId, resource) =>
+ resource.url.endsWith("a.png")
+ ? Promise.resolve("https://signed.test/a.png")
+ : new Promise(() => {}),
+ );
+ const shown = image("https://github.com/a.png");
+ const resolving: FilePreviewItem = { ...image("https://github.com/b.pdf"), kind: "pdf" };
+ const root = createRoot(document.createElement("div"));
+ await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
+ const render = (item: FilePreviewItem) =>
+ act(async () =>
+ root.render(
+ {}}
+ progressiveGallery
+ Viewer={Viewer}
+ />,
+ ),
+ );
+ await render(shown);
+ await render(resolving);
+ await render(resolving);
+ expect(
+ harness.refreshAssetUrl.mock.calls.filter(([, r]) => r.url.endsWith("b.pdf")),
+ ).toHaveLength(1);
+});
diff --git a/apps/mobile/src/components/ui/FilePreviewSession.tsx b/apps/mobile/src/components/ui/FilePreviewSession.tsx
index 5df8acf001e03..a7a60ce5555b4 100644
--- a/apps/mobile/src/components/ui/FilePreviewSession.tsx
+++ b/apps/mobile/src/components/ui/FilePreviewSession.tsx
@@ -97,6 +97,7 @@ function ResolvedFilePreview(
readonly source: FilePreviewSource;
readonly onRequestClose: () => void;
readonly onOpenError?: (error: unknown) => void;
+ readonly onPresent: (isFinished: () => boolean) => void;
},
) {
const { progressiveGallery, Viewer } = props;
@@ -161,6 +162,7 @@ function ResolvedFilePreview(
);
@@ -205,6 +207,7 @@ function ResolvedFilePreview(
}}
onRequestClose={props.onRequestClose}
onOpenError={onOpenError}
+ onPresent={props.onPresent}
/>
);
}
@@ -220,15 +223,43 @@ export function FilePreviewSession(props: FilePreviewModalProps & FilePreviewSes
? null
: { ...props.source, gallery: filePreviewGallery(props.source, group) };
usePreviewPresentation(source && filePreviewKey(source), props.onRequestClose);
+ // A tap can land after the native viewer closed but before its close reached the caller, which
+ // still holds the same item; that tap only opens a new viewer under a new key.
+ // Only a viewer that presented and has since closed reopens; one still resolving never does.
+ const [opening, setOpening] = useState<{
+ readonly source: FilePreviewModalProps["source"];
+ readonly count: number;
+ readonly presented: { readonly isFinished: () => boolean } | null;
+ }>({ source: props.source, count: 0, presented: null });
+ if (opening.source !== props.source) {
+ const sameItem =
+ opening.source !== null &&
+ props.source !== null &&
+ filePreviewKey(opening.source) === filePreviewKey(props.source);
+ const reopened = sameItem && opening.presented?.isFinished() === true;
+ setOpening({
+ source: props.source,
+ count: opening.count + (reopened ? 1 : 0),
+ presented: sameItem && !reopened ? opening.presented : null,
+ });
+ }
+ const { count } = opening;
+ const onPresent = (isFinished: () => boolean) =>
+ setOpening((current) =>
+ current.count === count && current.presented === null
+ ? { ...current, presented: { isFinished } }
+ : current,
+ );
if (!source) return null;
return (
);
diff --git a/apps/mobile/src/connection/environment-owned-data-cleanup.test.ts b/apps/mobile/src/connection/environment-owned-data-cleanup.test.ts
new file mode 100644
index 0000000000000..efe489b0fde35
--- /dev/null
+++ b/apps/mobile/src/connection/environment-owned-data-cleanup.test.ts
@@ -0,0 +1,74 @@
+import { Persistence } from "@t3tools/client-runtime/platform";
+import { EnvironmentId } from "@t3tools/contracts";
+import { describe, expect, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Logger from "effect/Logger";
+import { vi } from "vite-plus/test";
+
+const harness = vi.hoisted(() => ({
+ clearOutbox: vi.fn<(environmentId: string) => Promise>(),
+ clearDrafts: vi.fn<(environmentId: string) => Promise>(),
+ clearComposerErrors: vi.fn(),
+}));
+
+vi.mock("../state/thread-outbox-removal", () => ({
+ clearThreadOutboxEnvironment: harness.clearOutbox,
+}));
+vi.mock("../state/use-composer-drafts", () => ({
+ clearComposerDraftsEnvironment: harness.clearDrafts,
+}));
+vi.mock("../state/thread-composer-error", () => ({
+ clearThreadComposerErrorsForEnvironment: harness.clearComposerErrors,
+}));
+
+import * as EnvironmentOwnedDataCleanup from "./environment-owned-data-cleanup";
+
+const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
+
+describe("EnvironmentOwnedDataCleanup", () => {
+ it.effect("waits for the other clears and logs a bounded warning when one rejects", () => {
+ const warnings: Array = [];
+ let releaseDrafts = () => {};
+ let draftsCleared = false;
+ // The drafts clear finishes only after the outbox failure is logged.
+ const logger = Logger.make(({ message }) => {
+ warnings.push(message);
+ releaseDrafts();
+ });
+ return Effect.gen(function* () {
+ harness.clearOutbox.mockRejectedValue(new Error("Some queued messages could not be read."));
+ harness.clearDrafts.mockImplementation(() =>
+ new Promise((resolve) => {
+ releaseDrafts = resolve;
+ }).then(() => {
+ draftsCleared = true;
+ }),
+ );
+
+ const cleanup = yield* Persistence.EnvironmentOwnedDataCleanup;
+ yield* cleanup.clear(ENVIRONMENT_ID);
+
+ expect(draftsCleared).toBe(true);
+ expect(warnings).toEqual([
+ [
+ "Could not clear mobile environment-owned data.",
+ {
+ environmentId: ENVIRONMENT_ID,
+ operation: "outbox",
+ errorType: "error",
+ errorName: "Error",
+ stack: expect.any(String),
+ },
+ ],
+ ]);
+ }).pipe(
+ Effect.provide(
+ Layer.merge(
+ EnvironmentOwnedDataCleanup.layer,
+ Logger.layer([logger], { mergeWithExisting: false }),
+ ),
+ ),
+ );
+ });
+});
diff --git a/apps/mobile/src/connection/environment-owned-data-cleanup.ts b/apps/mobile/src/connection/environment-owned-data-cleanup.ts
new file mode 100644
index 0000000000000..28c6cda29a4d3
--- /dev/null
+++ b/apps/mobile/src/connection/environment-owned-data-cleanup.ts
@@ -0,0 +1,48 @@
+import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
+import { Persistence } from "@t3tools/client-runtime/platform";
+import type { EnvironmentId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Schema from "effect/Schema";
+
+import { clearThreadComposerErrorsForEnvironment } from "../state/thread-composer-error";
+import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal";
+import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
+
+class EnvironmentOwnedDataClearError extends Schema.TaggedError()(
+ "EnvironmentOwnedDataClearError",
+ { cause: Schema.Defect() },
+) {}
+
+export const layer = Layer.succeed(
+ Persistence.EnvironmentOwnedDataCleanup,
+ Persistence.EnvironmentOwnedDataCleanup.of({
+ clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")(function (environmentId) {
+ // Each clear settles on its own: a failure must not interrupt a clear that is still running.
+ const settle = (
+ operation: "outbox" | "drafts",
+ clear: (environmentId: EnvironmentId) => Promise,
+ ) =>
+ Effect.tryPromise({
+ try: () => clear(environmentId),
+ catch: (cause) => new EnvironmentOwnedDataClearError({ cause }),
+ }).pipe(
+ Effect.catch((error) =>
+ Effect.logWarning("Could not clear mobile environment-owned data.", {
+ environmentId,
+ operation,
+ ...safeErrorLogAttributes(error.cause),
+ }),
+ ),
+ );
+ return Effect.all(
+ [
+ settle("outbox", clearThreadOutboxEnvironment),
+ settle("drafts", clearComposerDraftsEnvironment),
+ Effect.sync(() => clearThreadComposerErrorsForEnvironment(environmentId)),
+ ],
+ { concurrency: "unbounded", discard: true },
+ );
+ }),
+ }),
+);
diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts
index 407016ab484d9..de461f35ab104 100644
--- a/apps/mobile/src/connection/platform.ts
+++ b/apps/mobile/src/connection/platform.ts
@@ -1,8 +1,4 @@
-import {
- ClientCapabilities,
- PlatformConnectionSource,
- Persistence,
-} from "@t3tools/client-runtime/platform";
+import { ClientCapabilities, PlatformConnectionSource } from "@t3tools/client-runtime/platform";
import {
ConnectionBlockedError,
ConnectionTransientError,
@@ -25,10 +21,8 @@ import { authClientMetadata } from "../lib/authClientMetadata";
import * as Runtime from "../lib/runtime";
import * as MobileStorage from "../persistence/mobile-storage";
import { appAtomRegistry } from "../state/atom-registry";
-import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal";
-import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
-import { clearThreadComposerErrorsForEnvironment } from "../state/thread-composer-error";
import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
+import * as EnvironmentOwnedDataCleanup from "./environment-owned-data-cleanup";
import * as ConnectionStorage from "./storage";
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
@@ -255,22 +249,6 @@ const layerPlatformConnectionSource = Layer.succeed(
const layerProvidedConnectionStorage = ConnectionStorage.layer.pipe(Layer.provide(Runtime.layer));
const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.layer));
-const layerEnvironmentOwnedDataCleanup = Layer.succeed(
- Persistence.EnvironmentOwnedDataCleanup,
- Persistence.EnvironmentOwnedDataCleanup.of({
- clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")((environmentId) =>
- Effect.all(
- [
- Effect.promise(() => clearThreadOutboxEnvironment(environmentId)),
- Effect.promise(() => clearComposerDraftsEnvironment(environmentId)),
- Effect.sync(() => clearThreadComposerErrorsForEnvironment(environmentId)),
- ],
- { concurrency: "unbounded", discard: true },
- ),
- ),
- }),
-);
-
type ConnectionPlatformLayerSource =
| typeof layerProvidedConnectionStorage
| typeof Runtime.layer
@@ -278,7 +256,7 @@ type ConnectionPlatformLayerSource =
| typeof layerWakeups
| typeof layerProvidedCapabilities
| typeof layerPlatformConnectionSource
- | typeof layerEnvironmentOwnedDataCleanup;
+ | typeof EnvironmentOwnedDataCleanup.layer;
export const layer: Layer.Layer<
Layer.Success,
@@ -291,5 +269,5 @@ export const layer: Layer.Layer<
layerWakeups,
layerProvidedCapabilities,
layerPlatformConnectionSource,
- layerEnvironmentOwnedDataCleanup,
+ EnvironmentOwnedDataCleanup.layer,
);
diff --git a/apps/mobile/src/features/connection/LinkedEnvironmentsSection.test.tsx b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.test.tsx
new file mode 100644
index 0000000000000..964d499fd30c4
--- /dev/null
+++ b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.test.tsx
@@ -0,0 +1,169 @@
+import { RegistryContext } from "@effect/atom-react";
+import {
+ NavigationContext,
+ type NavigationProp,
+ type ParamListBase,
+} from "@react-navigation/native";
+import { EnvironmentId } from "@t3tools/contracts";
+import { AtomRegistry } from "effect/reactivity";
+import { act, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vite-plus/test";
+
+// Each listing probes every linked machine, so the test counts the fetches it starts and cuts.
+const fetches = vi.hoisted(() => ({
+ started: 0,
+ interrupted: 0,
+ gate: Promise.resolve(),
+ open: () => {},
+}));
+
+vi.mock("@react-navigation/native", async () => {
+ const { createRequire } = await import("node:module");
+ const { realpathSync } = await import("node:fs");
+ const require = createRequire(import.meta.url);
+ const nativeRequire = createRequire(
+ realpathSync(require.resolve("@react-navigation/native/package.json")),
+ );
+ // Use the shipped focus hook without importing the React Native view layer.
+ const { NavigationContext, useFocusEffect }: typeof import("@react-navigation/native") =
+ nativeRequire("@react-navigation/core");
+ return { NavigationContext, useFocusEffect };
+});
+const appState = vi.hoisted(() => ({ listeners: new Set<(state: string) => void>() }));
+
+vi.mock("react-native", () => ({
+ AppState: {
+ addEventListener: (_event: "change", listener: (state: string) => void) => {
+ appState.listeners.add(listener);
+ return { remove: () => appState.listeners.delete(listener) };
+ },
+ },
+ View: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("../../components/ui/AppText", () => ({
+ AppText: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("../settings/components/SettingsSection", () => ({
+ SettingsSection: ({ children }: { children?: ReactNode }) => children,
+}));
+vi.mock("../../state/entities", () => ({
+ useEnvironmentServerConfig: () => ({
+ environment: { capabilities: { peerLinks: true } },
+ settings: { linkedEnvironmentsEnabled: true },
+ }),
+}));
+vi.mock("../../state/session", () => ({ useEnvironmentScope: () => true }));
+vi.mock("../../state/peerLinks", async () => {
+ const { Atom } = await import("effect/reactivity");
+ const EffectModule = await import("effect/Effect");
+ // Waits for the gate, as a list waits on its slowest linked machine.
+ const list = Atom.make(
+ EffectModule.gen(function* () {
+ fetches.started += 1;
+ yield* EffectModule.promise(() => fetches.gate);
+ return { links: [] };
+ }).pipe(
+ EffectModule.onInterrupt(() =>
+ EffectModule.sync(() => {
+ fetches.interrupted += 1;
+ }),
+ ),
+ ),
+ );
+ return { peerLinkEnvironment: { list: () => list } };
+});
+
+import { LinkedEnvironmentsSection } from "./LinkedEnvironmentsSection";
+
+function createNavigation() {
+ const listeners = { focus: new Set<() => void>(), blur: new Set<() => void>() };
+ let focused = true;
+ return {
+ value: {
+ isFocused: () => focused,
+ addListener: (event: keyof typeof listeners, listener: () => void) => {
+ listeners[event].add(listener);
+ return () => listeners[event].delete(listener);
+ },
+ } as unknown as NavigationProp,
+ focus(next: boolean) {
+ focused = next;
+ act(() => {
+ for (const listener of listeners[next ? "focus" : "blur"]) listener();
+ });
+ },
+ };
+}
+
+function setup() {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ fetches.started = 0;
+ fetches.interrupted = 0;
+ fetches.gate = new Promise((resolve) => {
+ fetches.open = resolve;
+ });
+ const registry = AtomRegistry.make();
+ const root = createRoot(document.createElement("div"));
+ const navigation = createNavigation();
+ act(() =>
+ root.render(
+
+
+
+
+ ,
+ ),
+ );
+ return {
+ focus: navigation.focus,
+ moveApp: (state: "active" | "background") =>
+ act(() => {
+ for (const listener of appState.listeners) listener(state);
+ }),
+ settle: () =>
+ act(async () => {
+ fetches.open();
+ await fetches.gate;
+ }),
+ [Symbol.dispose]() {
+ act(() => root.unmount());
+ registry.dispose();
+ },
+ };
+}
+
+it("asks again on focus only once the list it is waiting for has answered", async () => {
+ using screen = setup();
+ // The first focus comes while the first fetch runs, which must not be cut and restarted.
+ expect(fetches).toMatchObject({ started: 1, interrupted: 0 });
+ screen.focus(false);
+ screen.focus(true);
+ expect(fetches).toMatchObject({ started: 1, interrupted: 0 });
+
+ await screen.settle();
+ screen.focus(false);
+ screen.focus(true);
+ expect(fetches).toMatchObject({ started: 2, interrupted: 0 });
+});
+
+it("asks again when the app comes back to the front on this screen", async () => {
+ using screen = setup();
+ await screen.settle();
+ expect(fetches).toMatchObject({ started: 1, interrupted: 0 });
+ fetches.gate = new Promise((resolve) => {
+ fetches.open = resolve;
+ });
+
+ screen.moveApp("background");
+ screen.moveApp("active");
+ expect(fetches).toMatchObject({ started: 2, interrupted: 0 });
+
+ // Coming back while that answer is still out must not cut it and start again.
+ screen.moveApp("background");
+ screen.moveApp("active");
+ expect(fetches).toMatchObject({ started: 2, interrupted: 0 });
+});
diff --git a/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx
index 9153c9fa6a1c8..f447e2760277e 100644
--- a/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx
+++ b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx
@@ -1,9 +1,10 @@
+import { RegistryContext } from "@effect/atom-react";
import { offersLinkedEnvironments } from "@t3tools/client-runtime/link-request";
import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";
import { useFocusEffect } from "@react-navigation/native";
import { AuthAccessReadScope, type EnvironmentId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
-import { useCallback, useState } from "react";
+import { useCallback, useContext, useState } from "react";
import { AppState, View } from "react-native";
import { AppText as Text } from "../../components/ui/AppText";
@@ -20,8 +21,25 @@ export function LinkedEnvironmentsSection(props: {
const config = useEnvironmentServerConfig(props.environmentId);
const canRead = useEnvironmentScope(props.environmentId, AuthAccessReadScope);
const supported = canRead && offersLinkedEnvironments(config);
- const links = useEnvironmentQuery(
- supported ? peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} }) : null,
+ const listAtom = supported
+ ? peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} })
+ : null;
+ const links = useEnvironmentQuery(listAtom);
+ const registry = useContext(RegistryContext);
+ // Links change outside this client, and the shared list only revalidates when built, so
+ // showing the screen and bringing the app back ask again.
+ useFocusEffect(
+ useCallback(() => {
+ if (listAtom === null) return;
+ const askAgain = () => {
+ if (!registry.get(listAtom).waiting) registry.refresh(listAtom);
+ };
+ askAgain();
+ const subscription = AppState.addEventListener("change", (state) => {
+ if (state === "active") askAgain();
+ });
+ return () => subscription.remove();
+ }, [listAtom, registry]),
);
const [nowMs, setNowMs] = useState(Date.now);
const hasLinks = supported && (links.data?.links.length ?? 0) > 0;
diff --git a/apps/mobile/src/features/connection/useConnectionController.ts b/apps/mobile/src/features/connection/useConnectionController.ts
index 626892d447569..64deaaf8d1e72 100644
--- a/apps/mobile/src/features/connection/useConnectionController.ts
+++ b/apps/mobile/src/features/connection/useConnectionController.ts
@@ -38,7 +38,6 @@ export function useConnectionController() {
const updateBearer = useAtomCommand(updateBearerConnection, { reportFailure: false });
const registerEnvironment = useAtomCommand(environmentCatalog.register, "environment register");
const removeEnvironmentMutation = useAtomCommand(environmentCatalog.remove, "environment remove");
- const retryEnvironmentMutation = useAtomCommand(environmentCatalog.retryNow, "environment retry");
const setEnvironmentEnabledMutation = useAtomCommand(
environmentCatalog.setEnabled,
"environment toggle",
@@ -84,8 +83,6 @@ export function useConnectionController() {
);
const removeEnvironment = (environmentId: EnvironmentId) =>
removeEnvironmentMutation(environmentId);
- const retryEnvironment = (environmentId: EnvironmentId) =>
- retryEnvironmentMutation(environmentId);
const setEnvironmentEnabled = (environmentId: EnvironmentId, enabled: boolean) =>
setEnvironmentEnabledMutation({ environmentId, enabled });
const updateEnvironment = (
@@ -111,7 +108,6 @@ export function useConnectionController() {
connectPairingUrl,
connectRelayEnvironment,
removeEnvironment,
- retryEnvironment,
setEnvironmentEnabled,
updateEnvironment,
refreshRelayEnvironments,
diff --git a/apps/mobile/src/features/connection/useRetryEnvironment.test.tsx b/apps/mobile/src/features/connection/useRetryEnvironment.test.tsx
new file mode 100644
index 0000000000000..da94dedf2e78a
--- /dev/null
+++ b/apps/mobile/src/features/connection/useRetryEnvironment.test.tsx
@@ -0,0 +1,108 @@
+import { RegistryContext } from "@effect/atom-react";
+import { EnvironmentId } from "@t3tools/contracts";
+import {
+ EnvironmentRegistry,
+ PrimaryConnectionTarget,
+ type ConnectionCatalogEntry,
+} from "@t3tools/client-runtime/connection";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import * as SubscriptionRef from "effect/SubscriptionRef";
+import { AtomRegistry } from "effect/reactivity";
+import { act, useLayoutEffect } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it } from "@effect/vitest";
+import { vi } from "vite-plus/test";
+
+const fixture = vi.hoisted(() => ({
+ environment: undefined as
+ | Pick<
+ EnvironmentRegistry.EnvironmentRegistry["Service"],
+ "entries" | "retryNow" | "setEnabled"
+ >
+ | undefined,
+}));
+
+vi.mock("../../connection/runtime", async () => {
+ const { Atom } = await import("effect/reactivity");
+ const Layer = await import("effect/Layer");
+ const { EnvironmentRegistry } = await import("@t3tools/client-runtime/connection");
+ return {
+ connectionAtomRuntime: Atom.runtime(
+ Layer.suspend(() =>
+ Layer.succeed(
+ EnvironmentRegistry.EnvironmentRegistry,
+ fixture.environment as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"],
+ ),
+ ),
+ ),
+ };
+});
+
+import { useRetryEnvironment } from "./useRetryEnvironment";
+
+const environmentId = EnvironmentId.make("retry-environment");
+
+describe("useRetryEnvironment", () => {
+ it.effect.each([
+ { enabled: false, retries: 0 },
+ { enabled: true, retries: 1 },
+ ])("Retry now with the environment enabled: $enabled", ({ enabled, retries }) =>
+ Effect.gen(function* () {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const target = new PrimaryConnectionTarget({
+ environmentId,
+ label: "Retry",
+ httpBaseUrl: "https://retry.test",
+ wsBaseUrl: "wss://retry.test",
+ });
+ const entries = yield* SubscriptionRef.make<
+ ReadonlyMap
+ >(new Map([[environmentId, { target, profile: Option.none(), enabled }]]));
+ let retryCount = 0;
+ fixture.environment = {
+ entries,
+ retryNow: () =>
+ Effect.sync(() => {
+ retryCount += 1;
+ }),
+ setEnabled: (id, next) =>
+ SubscriptionRef.update(entries, (current) =>
+ new Map(current).set(id, { ...current.get(id)!, enabled: next }),
+ ),
+ };
+
+ const registry = AtomRegistry.make();
+ const root = createRoot(document.createElement("div"));
+ using _mounted = {
+ [Symbol.dispose]() {
+ act(() => root.unmount());
+ registry.dispose();
+ },
+ };
+ let retryEnvironment!: ReturnType;
+ function Probe() {
+ const value = useRetryEnvironment();
+ useLayoutEffect(() => {
+ retryEnvironment = value;
+ });
+ return null;
+ }
+ yield* Effect.promise(async () => {
+ await act(async () =>
+ root.render(
+
+
+ ,
+ ),
+ );
+ await act(async () => {
+ await retryEnvironment(environmentId);
+ });
+ });
+
+ const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
+ expect({ enabled: entry?.enabled, retries: retryCount }).toEqual({ enabled: true, retries });
+ }),
+ );
+});
diff --git a/apps/mobile/src/features/connection/useRetryEnvironment.ts b/apps/mobile/src/features/connection/useRetryEnvironment.ts
new file mode 100644
index 0000000000000..b5d8edc749230
--- /dev/null
+++ b/apps/mobile/src/features/connection/useRetryEnvironment.ts
@@ -0,0 +1,17 @@
+import { useAtomValue } from "@effect/atom-react";
+import type { EnvironmentId } from "@t3tools/contracts";
+
+import { environmentCatalog } from "../../connection/catalog";
+import { useAtomCommand } from "../../state/use-atom-command";
+
+export function useRetryEnvironment() {
+ const catalog = useAtomValue(environmentCatalog.catalogValueAtom);
+ const retryNow = useAtomCommand(environmentCatalog.retryNow, "environment retry");
+ const setEnabled = useAtomCommand(environmentCatalog.setEnabled, "environment toggle");
+
+ return (environmentId: EnvironmentId) =>
+ // A retry does nothing while the environment is switched off.
+ catalog.entries.get(environmentId)?.enabled === false
+ ? setEnabled({ environmentId, enabled: true })
+ : retryNow(environmentId);
+}
diff --git a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
index 528a18541eb46..448fd929e42e8 100644
--- a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
+++ b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
@@ -96,10 +96,10 @@ export function SettingsDiagnosticsRouteScreen() {
{crashReportingAvailable ? : null}
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
index 7f503239c21d2..4d73a7cda5c3c 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
@@ -19,6 +19,7 @@ function permanentSourceFailureReason(error: unknown): string | undefined {
if (name === "GitHubDiffFileContentsUnavailableError") return "github-source-unavailable";
for (const permanent of [
"provider-unsupported",
+ "repository-without-project",
"unsupported",
"oversized",
"binary",
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts
index bf8c6e8e311ca..2699bb995406c 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts
@@ -47,6 +47,12 @@ export interface NativeReviewDiffRow {
readonly commentText?: string;
readonly commentRangeLabel?: string;
readonly commentSectionTitle?: string;
+ /** A notice drawn in the warning colors. */
+ readonly tone?: "warning";
+ /** A notice that reports taps through `onPressNotice`. */
+ readonly actionable?: boolean;
+ /** Where a cut line's note starts in `content`. */
+ readonly noteStart?: number;
}
export interface NativeReviewDiffWordDiffRange {
@@ -74,6 +80,8 @@ export interface NativeReviewDiffTheme {
readonly deleteBar: string;
readonly addText: string;
readonly deleteText: string;
+ readonly warningText: string;
+ readonly warningBackground: string;
}
export interface NativeReviewDiffStyle {
@@ -151,6 +159,9 @@ export interface NativeReviewDiffViewProps extends ViewProps {
}>,
) => void;
readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void;
+ readonly onPressNotice?: (
+ event: NativeSyntheticEvent<{ readonly rowId?: string; readonly fileId?: string }>,
+ ) => void;
}
export interface NativeReviewDiffViewHandle {
diff --git a/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx b/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx
index 63c3e7be0c65e..eccac90d9abea 100644
--- a/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx
+++ b/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx
@@ -2,11 +2,10 @@ import type { EnvironmentId } from "@t3tools/contracts";
import { View } from "react-native";
import { EmptyState } from "../../components/ui/EmptyState";
-import { environmentCatalog } from "../../connection/catalog";
import type { AssetUrlFailureReason } from "../../state/asset-url-state";
-import { useAtomCommand } from "../../state/use-atom-command";
import { useEnvironmentPresentation } from "../../state/presentation";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
+import { useRetryEnvironment } from "../connection/useRetryEnvironment";
export function WorkspaceFilePreviewError(props: {
readonly environmentId: EnvironmentId | null;
@@ -15,7 +14,7 @@ export function WorkspaceFilePreviewError(props: {
}) {
const { environmentId, onRetry } = props;
const environment = useEnvironmentPresentation(environmentId);
- const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
+ const retryEnvironment = useRetryEnvironment();
const retryConnection = () => {
if (environmentId !== null) void retryEnvironment(environmentId);
onRetry();
diff --git a/apps/mobile/src/features/files/filePath.test.ts b/apps/mobile/src/features/files/filePath.test.ts
index 0acf3d5877ef0..17bf3383d42ca 100644
--- a/apps/mobile/src/features/files/filePath.test.ts
+++ b/apps/mobile/src/features/files/filePath.test.ts
@@ -72,11 +72,18 @@ describe("needsWorkspaceFileContents", () => {
});
describe("workspace preview classifiers", () => {
- it("treat # and ? as literal filename characters", () => {
+ it("recognize preview extensions and treat # and ? as literal filename characters", () => {
for (const path of ["notes/clip#1.wav", "notes/clip?1.wav", "notes#old/clip.wav"]) {
expect(isAudioPreviewFile(path)).toBe(true);
}
- for (const path of ["docs/draft#1.md", "docs/draft?1.md", "docs#old/draft.md"]) {
+ for (const path of [
+ "docs/draft#1.md",
+ "docs/draft?1.md",
+ "docs#old/draft.md",
+ "CHANGELOG.markdown",
+ "notes.MDOWN",
+ "todo.mkd",
+ ]) {
expect(isMarkdownPreviewFile(path)).toBe(true);
}
});
diff --git a/apps/mobile/src/features/files/filePath.ts b/apps/mobile/src/features/files/filePath.ts
index be063da994f8d..9c9d16a6021c1 100644
--- a/apps/mobile/src/features/files/filePath.ts
+++ b/apps/mobile/src/features/files/filePath.ts
@@ -109,7 +109,7 @@ export function isSvgImagePreviewFile(path: string): boolean {
}
export function isMarkdownPreviewFile(path: string): boolean {
- return /\.(?:md|mdx)$/i.test(path);
+ return /\.(?:md|mdx|markdown|mdown|mkd)$/i.test(path);
}
// Fork: Installers and archives download as bytes until upstream supports download-only workspace files.
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
index 8110cca26793d..6f5db6a52f59c 100644
--- a/apps/mobile/src/features/home/HomeScreen.tsx
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -469,7 +469,6 @@ export function HomeScreen(props: HomeScreenProps) {
selectedThreadKey)
}
project={projectByKey.get(pendingScopeKey) ?? null}
- projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
environmentLabel={
Object.keys(props.savedConnectionsById).length > 1
? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??
diff --git a/apps/mobile/src/features/home/ThreadUndoNotice.tsx b/apps/mobile/src/features/home/ThreadUndoNotice.tsx
index caeb47a3c2195..544a2909124ea 100644
--- a/apps/mobile/src/features/home/ThreadUndoNotice.tsx
+++ b/apps/mobile/src/features/home/ThreadUndoNotice.tsx
@@ -51,7 +51,11 @@ export function ThreadUndoNotice(props: { readonly visible: boolean }) {
const bottom =
Platform.OS === "ios"
? foldedResting
- ? Math.max(rootMetrics.safeArea.bottom, keyboardHeight) + 8
+ ? // Sit level with the rail's tab pill, which floats inside the bottom safe area.
+ Math.max(
+ rootMetrics.bottomBarInset ?? rootMetrics.safeArea.bottom + 8,
+ keyboardHeight + 8,
+ )
: rootMetrics?.hasHinge && rootMetrics.verticalBarEdge !== "none"
? // The column's safe area already includes UIKit's search toolbar in this posture.
workspaceSearchBottomClearance({
diff --git a/apps/mobile/src/features/home/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx
index 532badd9b35cb..5a0305ca23a86 100644
--- a/apps/mobile/src/features/home/thread-swipe-actions.tsx
+++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx
@@ -512,7 +512,9 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) {
overshootRight
renderRightActions={renderRightActions}
rightThreshold={actionsWidth * 0.42}
- simultaneousWith={props.simultaneousWith}
+ // Only iPad trackpad pans need rows to swipe while the list scrolls; on Android touch it
+ // lets a diagonal swipe scroll the list, which the scroll gate turns into a closed row.
+ simultaneousWith={Platform.OS === "ios" ? props.simultaneousWith : undefined}
>
{
/* oxlint-disable react/refs -- The render callback receives a close/open handler; only invoking that handler accesses the ref. */
diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts
index 0bea39e419e21..135cf4e1d85a7 100644
--- a/apps/mobile/src/features/home/useThreadListActions.test.ts
+++ b/apps/mobile/src/features/home/useThreadListActions.test.ts
@@ -21,6 +21,7 @@ const state = vi.hoisted(() => ({
failedAction: null as string | null,
titleOutcome: null as ThreadTitleRegenerationOutcome | null,
archivedRefreshes: [] as string[],
+ onArchivedRefresh: undefined as (() => void) | undefined,
scopes: new Map>(),
shells: [] as EnvironmentThreadShell[],
requests: [] as {
@@ -59,6 +60,7 @@ vi.mock("../../components/ui/Dialog", () => ({
vi.mock("../archive/useArchivedThreadSnapshots", () => ({
refreshArchivedThreadsForEnvironment: (environmentId: string) => {
state.archivedRefreshes.push(environmentId);
+ state.onArchivedRefresh?.();
},
}));
vi.mock("../../state/session", () => ({
@@ -71,8 +73,9 @@ vi.mock("../../state/presentation", () => ({
vi.mock("../../state/server", () => ({
environmentServerConfigsAtom: "server-configs",
}));
-vi.mock("../../state/atom-registry", () => ({
- appAtomRegistry: {
+vi.mock("../../state/atom-registry", async () => {
+ const registry = (await import("effect/reactivity")).AtomRegistry.make();
+ const stub = {
set: (_atom: string, value: boolean) => {
state.dropBusy = value;
},
@@ -103,8 +106,21 @@ vi.mock("../../state/atom-registry", () => ({
},
]),
),
- },
-}));
+ };
+ // Real atoms such as composerDraftsAtom go to a real registry; strings are stubbed state.
+ return {
+ appAtomRegistry: {
+ get: (atom: unknown) =>
+ typeof atom === "string"
+ ? stub.get(atom)
+ : registry.get(atom as Parameters[0]),
+ set: (atom: unknown, value: unknown) =>
+ typeof atom === "string"
+ ? stub.set(atom, value as boolean)
+ : registry.set(atom as Parameters[0], value),
+ },
+ };
+});
vi.mock("../../state/use-atom-command", () => ({
useAtomCommand: (command: unknown) => command,
}));
@@ -164,6 +180,8 @@ vi.mock("../../state/threads", () => ({
),
}));
+import { appAtomRegistry } from "../../state/atom-registry";
+import { composerDraftsAtom } from "../../state/use-composer-drafts";
import { dismissThreadUndoNotice, readThreadUndoNotice } from "./thread-undo-notice";
import { useThreadListActions } from "./useThreadListActions";
@@ -197,6 +215,7 @@ beforeEach(() => {
state.failedAction = null;
state.titleOutcome = null;
state.archivedRefreshes = [];
+ state.onArchivedRefresh = undefined;
state.pendingOrder = null;
state.dropBusy = false;
state.holdingRows = false;
@@ -250,7 +269,9 @@ describe("thread list operation permissions", () => {
expect(state.requests).toEqual([]);
});
- it("rechecks permission after a retained delete confirmation", async () => {
+ it("rechecks permission after a retained delete confirmation, then clears the draft", async () => {
+ const draft = { text: "unsent", attachments: [] };
+ appAtomRegistry.set(composerDraftsAtom, { "primary:thread": draft, "primary:other": draft });
useThreadListActions().confirmDeleteThread(makeThread());
const confirm = state.dialogs[0]?.onConfirm;
expect(confirm).toBeTypeOf("function");
@@ -259,6 +280,15 @@ describe("thread list operation permissions", () => {
await confirm!();
expect(state.requests).toEqual([]);
+ expect(Object.keys(appAtomRegistry.get(composerDraftsAtom))).toContain("primary:thread");
+
+ state.scopes.get(primaryEnvironmentId)!.add(AuthOrchestrationOperateScope);
+ const deleted = new Promise((resolve) => (state.onArchivedRefresh = resolve));
+ confirm!();
+ await deleted;
+
+ expect(state.requests).toEqual([expect.objectContaining({ action: "delete" })]);
+ expect(Object.keys(appAtomRegistry.get(composerDraftsAtom))).toEqual(["primary:other"]);
});
});
@@ -594,6 +624,19 @@ describe("thread action undo", () => {
await undo();
expect(state.requests.map(({ action }) => action)).toEqual(["unpin"]);
});
+
+ it("keeps the earlier Undo until archiving succeeds", async () => {
+ const actions = useThreadListActions();
+ const thread = makeThread();
+ await actions.settleThread(thread);
+ state.failedAction = "archive";
+ expect(await actions.archiveThread(thread)).toBe(false);
+ expect(readThreadUndoNotice()?.action).toBe("Settled");
+
+ state.failedAction = null;
+ expect(await actions.archiveThread(thread)).toBe(true);
+ expect(readThreadUndoNotice()).toBeNull();
+ });
});
describe("thread archive guard", () => {
diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts
index 3cd180db6273f..b100b6aa5e6da 100644
--- a/apps/mobile/src/features/home/useThreadListActions.ts
+++ b/apps/mobile/src/features/home/useThreadListActions.ts
@@ -17,6 +17,7 @@ import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import { connectedEnvironmentIdsAtom } from "../../state/presentation";
import { readEnvironmentScope } from "../../state/session";
+import { clearComposerDraft } from "../../state/use-composer-drafts";
import {
environmentThreadShells,
steadyNavigationThreadShellsAtom,
@@ -115,6 +116,7 @@ function useThreadActionExecutor(
action: ThreadListAction,
thread: EnvironmentThreadShell,
onStarted?: () => void,
+ restoreUnsettledAt?: string | null,
) => {
if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false;
const key = scopedThreadKey(thread.environmentId, thread.id);
@@ -145,9 +147,6 @@ function useThreadActionExecutor(
return false;
}
if (action === "unsettle") ThreadUndo.invalidate("settle", key);
- if (action === "archive" || action === "delete") {
- for (const kind of ["settle", "snooze", "pin"]) ThreadUndo.invalidate(kind, key);
- }
onStarted?.();
const result = await withThreadDismissal(
key,
@@ -157,7 +156,11 @@ function useThreadActionExecutor(
// suppressed until real activity clears the pin server-side.
await unsettleMutation({
environmentId: thread.environmentId,
- input: { threadId: thread.id, reason: "user" },
+ input: {
+ threadId: thread.id,
+ reason: "user",
+ ...(restoreUnsettledAt === undefined ? {} : { restoreUnsettledAt }),
+ },
})
: await (
action === "settle"
@@ -177,9 +180,13 @@ function useThreadActionExecutor(
Dialog.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
return false;
}
+ if (action === "archive" || action === "delete") {
+ for (const kind of ["settle", "snooze", "pin"]) ThreadUndo.invalidate(kind, key);
+ }
if (action === "archive" || action === "unarchive" || action === "delete") {
refreshArchivedThreadsForEnvironment(thread.environmentId);
}
+ if (action === "delete") clearComposerDraft(key);
onCompleted?.(action, thread);
return true;
})();
@@ -263,11 +270,19 @@ export function useThreadListActions(): {
async (step) => {
switch (step.action) {
case "unsettle":
- return unsettleThread(thread);
+ return unsettleThread(thread, step.restoreUnsettledAt);
case "unsnooze":
return unsnoozeThread(thread);
case "pin":
return pinThread(thread, step.orderKey);
+ case "reorderActive": {
+ const result = await reorderActiveMutation({
+ environmentId: thread.environmentId,
+ input: { threadId: thread.id, orderKey: step.orderKey },
+ });
+ if (result._tag === "Failure") throw Cause.squash(result.cause);
+ return true;
+ }
case "snooze": {
const failureTitle =
action === "Unpinned" ? "Could not undo unpin" : "Could not undo settle";
@@ -411,8 +426,10 @@ export function useThreadListActions(): {
snoozeInFlightThreadKeys.current.delete(key);
return succeeded;
};
- const unsettleThread = async (thread: EnvironmentThreadShell) =>
- (await executeAction("unsettle", thread)) === true;
+ const unsettleThread = async (
+ thread: EnvironmentThreadShell,
+ restoreUnsettledAt?: string | null,
+ ) => (await executeAction("unsettle", thread, undefined, restoreUnsettledAt)) === true;
const pinThread = async (thread: EnvironmentThreadShell, restoreOrderKey?: string) => {
if (!checkThreadOperationPermission(thread, "Could not pin thread")) return false;
if (!environmentConfigLoaded(thread.environmentId)) {
diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
index cad7dbcdd572c..afdf5748e38fd 100644
--- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
+++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
@@ -110,7 +110,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;
@@ -155,9 +158,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 } });
+ }}
>
@@ -328,7 +332,7 @@ function WorkspaceColumns(
}
};
const followCollapsedSplit = (
- type: "willAppear" | "didAppear" | "willDisappear",
+ type: "willAppear" | "didAppear" | "willDisappear" | "didDisappear",
key: string,
) => {
if (!collapsed.current || layout.usesSplitView) return;
@@ -558,7 +562,6 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean
props.nativeColumns && layout.usesSplitView && !workspacePage && deviceType === "pad"
}
hidden={
- !workspacePage &&
projection.detail.length > 0 &&
// Fork: Keep compact iPad destination navigation visible until upstream makes sidebar utilities width-aware.
!(deviceType === "pad" && projection.detail.length === 1) &&
diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx
index d27f423b1d2d7..3fa34bf2dff8f 100644
--- a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx
+++ b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx
@@ -102,8 +102,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/PullRequestDiscussionScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
index e92debeea0f1d..9d59324c1e4a6 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
@@ -21,7 +21,7 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/
import { AppBar } from "../../components/ui/AppBar";
import { Button } from "../../components/ui/Button";
import { GlassSurface } from "../../components/ui/GlassSurface";
-import { relativeTime } from "../../lib/time";
+import { compareTimestamps, relativeTime } from "../../lib/time";
import { composerPullRequests } from "../../state/pull-requests";
import { useAtomCommand } from "../../state/use-atom-command";
import { useEnvironmentQuery } from "../../state/query";
@@ -147,7 +147,7 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
...new Map(
[...extra, ...(thread?.comments ?? [])].map((comment) => [comment.id, comment]),
).values(),
- ].sort((left, right) => left.createdAt.localeCompare(right.createdAt));
+ ].sort((left, right) => compareTimestamps(left.createdAt, right.createdAt));
const scrollRef = useRef(null);
const pendingTop = useRef(null);
const positionedComment = useRef(null);
diff --git a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx
index fbcb62406b7a7..5bec031fb735f 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx
@@ -41,12 +41,18 @@ function choices(field: string, options: Readonly>, selec
}));
}
-type ProjectOrder = readonly { readonly memberProjectRefs: readonly ScopedProjectRef[] }[];
+type ProjectOrder = readonly {
+ readonly memberProjectRefs: readonly ScopedProjectRef[];
+ readonly pinned: boolean;
+ readonly archived: boolean;
+}[];
const sameProjectOrder = (previous: ProjectOrder, next: ProjectOrder) =>
previous.length === next.length &&
previous.every((group, index) => {
const members = next[index]!.memberProjectRefs;
return (
+ group.pinned === next[index]!.pinned &&
+ group.archived === next[index]!.archived &&
group.memberProjectRefs.length === members.length &&
group.memberProjectRefs.every(
(ref, member) =>
@@ -69,7 +75,11 @@ const sidebarProjectOrderFamily = Atom.family((mode: SidebarProjectGroupingMode)
threads: get(environmentThreadShells.threadShellsAtom),
pendingTasks: [],
projectSortOrder: "updated_at",
- }).map((scope) => ({ memberProjectRefs: scope.projectRefs })),
+ }).map((scope) => ({
+ memberProjectRefs: scope.projectRefs,
+ pinned: scope.pinned,
+ archived: scope.archived,
+ })),
).pipe(Atom.withEquality(sameProjectOrder)),
);
diff --git a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
index 2d0414b503653..3889dd87ed2f4 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
@@ -3,12 +3,14 @@ import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import type { PullRequestDetail, PullRequestMergeMethod } from "@t3tools/contracts";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { AsyncResult } from "effect/reactivity";
import { useRef, useState } from "react";
import { View } from "react-native";
import { AppText as Text } from "../../components/ui/AppText";
import { Button } from "../../components/ui/Button";
import { SplitButton } from "../../components/ui/SplitButton";
+import { useEnvironmentServerConfig } from "../../state/entities";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { composerPullRequests } from "../../state/pull-requests";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -19,6 +21,7 @@ import {
MERGE_METHODS,
PR_ACTION_ICONS,
pullRequestActionLabel,
+ resolveMergeMethod,
} from "./pullRequestActions";
import { pullRequestStackMerge, singlePullRequestMergeAllowed } from "./pullRequestStack";
import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
@@ -39,6 +42,7 @@ export function PullRequestMergeControls(props: {
const permissions = usePullRequestPermissions(props.params, pr);
const stateAction = usePullRequestAction(props.params, pr);
const preferences = useAtomValue(mobilePreferencesAtom);
+ const serverSettings = useEnvironmentServerConfig(target.environmentId)?.settings;
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const runAction = useAtomCommand(composerPullRequests.runAction, { reportFailure: false });
const refreshDetail = useAtomRefresh(composerPullRequests.detail(target));
@@ -47,15 +51,15 @@ export function PullRequestMergeControls(props: {
const [busy, setBusy] = useState(false);
const pending = useRef(false);
const methods = allowedMergeMethods(pr);
- const preferred =
- selectedMethod ??
- (AsyncResult.isSuccess(preferences) ? preferences.value.pullRequestMergeMethod : undefined) ??
- "squash";
- const method = methods.includes(preferred)
- ? preferred
- : methods.includes("squash")
- ? "squash"
- : methods[0];
+ const method = resolveMergeMethod(
+ pr,
+ selectedMethod,
+ serverSettings
+ ? resolveProjectSettings(serverSettings, target.input.projectId).settings
+ .pullRequestMergeMethod
+ : null,
+ AsyncResult.isSuccess(preferences) ? preferences.value.pullRequestMergeMethod : undefined,
+ );
const scope = stack.stack ? pullRequestStackMerge(stack.stack, pr.number, terminology) : null;
const canMergeSingle = singlePullRequestMergeAllowed({
supportsStackActions: stack.supportsStackActions,
diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
index e742f607c2c90..929474897af73 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
@@ -4,6 +4,7 @@ import {
pullRequestAnchorMatchesUrl,
pullRequestDiffPathMatches,
pullRequestLinkCommit,
+ resolvePullRequestAnchorRange,
resolvePullRequestReviewAnchor,
} from "@t3tools/shared/pullRequestAnchor";
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
@@ -12,12 +13,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";
@@ -143,15 +141,13 @@ function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityF
const filtered = result.data ? filterPullRequestActivity(result.data, filter) : null;
const rows = (() => {
if (!filtered) return [];
- const rows = pullRequestTimelineRows(filtered.activity, params, navigation, {
- permissions,
- onChanged: result.refresh,
- });
- if (filter.newestFirst) {
- const notice = rows.at(-1)?.key === "truncated" ? rows.pop() : undefined;
- rows.reverse();
- if (notice) rows.push(notice);
- }
+ const rows = pullRequestTimelineRows(
+ filtered.activity,
+ params,
+ navigation,
+ { permissions, onChanged: result.refresh },
+ filter.newestFirst,
+ );
if (!rows.length)
rows.push({
key: "empty",
@@ -385,14 +381,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
@@ -444,10 +434,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.
@@ -833,7 +823,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps
) : null}
@@ -1013,6 +1003,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]);
@@ -1075,7 +1066,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
@@ -1332,6 +1331,10 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {
});
else void viewed.toggle(file.path);
}}
+ onPressNotice={(event) => {
+ const file = data.files.find((file) => file.id === event.nativeEvent.fileId);
+ if (file) result.loadWithheldFile(file.path);
+ }}
onToggleComment={(event) => {
const id = event.nativeEvent.commentId;
if (id?.startsWith("discussion:"))
diff --git a/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx b/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx
index 03ba26f2247cf..805d61c928378 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx
@@ -27,6 +27,7 @@ import {
} from "./pullRequestActions";
import {
checkStatus,
+ isFailingCheck,
pullRequestBranchSummary,
pullRequestChecksSummary,
pullRequestReviewSummary,
@@ -132,8 +133,7 @@ export function PullRequestChecksRow(props: RowProps) {
exiting={PR_ROW_EXIT}
className="pl-8"
>
- {props.pr.state === "open" &&
- props.pr.checks.some((check) => check.status === "failure") ? (
+ {props.pr.state === "open" && props.pr.checks.some(isFailingCheck) ? (
) : null}
{action.available("approve-workflows") ? (
diff --git a/apps/mobile/src/features/pull-requests/PullRequestTimeline.tsx b/apps/mobile/src/features/pull-requests/PullRequestTimeline.tsx
index 4b7ba3a968187..586d9947510f3 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestTimeline.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestTimeline.tsx
@@ -17,7 +17,7 @@ import { Pressable, StyleSheet, View } from "react-native";
import { parseMarkdownDocument } from "../../lib/markdownDocument";
import { AppText as Text } from "../../components/ui/AppText";
import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
-import { relativeTime } from "../../lib/time";
+import { byTimestamp, relativeTime } from "../../lib/time";
import { PullRequestAvatar } from "./PullRequestPresentation";
import { PullRequestMarkdown } from "./PullRequestMarkdown";
import { PullRequestCommentFooter } from "./PullRequestReactions";
@@ -218,6 +218,7 @@ export function pullRequestTimelineRows(
params: PullRequestParams,
navigation: Pick, "navigate" | "dispatch">,
actions: CommentActions,
+ newestFirst: boolean,
) {
const linkTarget = parsePullRequestAnchor(params.navigationUrl);
const threads = pullRequestConversationThreads(activity);
@@ -320,7 +321,7 @@ export function pullRequestTimelineRows(
),
})),
- ].sort((a, b) => a.date.localeCompare(b.date));
+ ].sort(byTimestamp(newestFirst));
if (activity.commentsTruncated || activity.reviewThreadsTruncated)
events.push({
key: "truncated",
diff --git a/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts b/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts
index 2234a31081802..6862b5b31b2fb 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts
@@ -5,6 +5,7 @@ import {
canPerformPullRequestAction,
mergeUnavailableReason,
pullRequestActionLabel,
+ resolveMergeMethod,
} from "./pullRequestActions";
const GITHUB = sourceControlClients.get("github").changeRequest;
@@ -65,6 +66,22 @@ describe("mobile pull request actions", () => {
expect(mergeUnavailableReason(pr, true, GITHUB)).toContain("conflicts");
});
+ it("picks the chosen, project default, then last used merge method the repository allows", () => {
+ const pr = detail();
+ expect(resolveMergeMethod(pr, null, "merge", "squash")).toBe("merge");
+ expect(resolveMergeMethod(pr, "squash", "merge", "merge")).toBe("squash");
+ expect(resolveMergeMethod(pr, null, "rebase", "merge")).toBe("merge");
+ expect(resolveMergeMethod(pr, null, null, undefined)).toBe("squash");
+ expect(
+ resolveMergeMethod(
+ detail({ mergeCapabilities: { merge: true, squash: false, rebase: false } }),
+ null,
+ null,
+ "rebase",
+ ),
+ ).toBe("merge");
+ });
+
it("names the change request with its host's term", () => {
expect(pullRequestActionLabel("close", GITHUB)).toBe("Close pull request");
expect(pullRequestActionLabel("close", GITLAB)).toBe("Close merge request");
diff --git a/apps/mobile/src/features/pull-requests/pullRequestActions.ts b/apps/mobile/src/features/pull-requests/pullRequestActions.ts
index 132501b60a240..967689b57d84e 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestActions.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestActions.ts
@@ -87,6 +87,20 @@ export function allowedMergeMethods(pr: ActionDetail) {
return pr.capabilities.mergeMethods.filter((method) => pr.mergeCapabilities[method]);
}
+export function resolveMergeMethod(
+ pr: ActionDetail,
+ selected: PullRequestMergeMethod | null,
+ projectDefault: PullRequestMergeMethod | null,
+ lastUsed: PullRequestMergeMethod | undefined,
+) {
+ const methods = allowedMergeMethods(pr);
+ return (
+ [selected, projectDefault, lastUsed, "squash" as const].find(
+ (method) => method != null && methods.includes(method),
+ ) ?? methods[0]
+ );
+}
+
export function allowedUpdateMethods(pr: ActionDetail) {
return (pr.capabilities.updateMethods ?? []).filter((method) =>
pr.viewerPermissions.updateMethods?.includes(method),
diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts
index 82027addc72cc..b0c91ab3ada9e 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts
@@ -7,6 +7,8 @@ import {
combinePullRequestDiffPages,
getCachedPullRequestDiffPages,
retainPullRequestDiffPage,
+ withWithheldFiles,
+ type WithheldFileLoad,
} from "./pullRequestDiffPages";
const GITHUB = sourceControlClients.get("github").changeRequest;
@@ -156,4 +158,41 @@ describe("paged mobile pull request diffs", () => {
expect(refreshed).toHaveLength(1);
expect(refreshed[0]?.result.patch).toContain("changed.ts");
});
+
+ it("swaps a loaded withheld file in under its id and says what a tap does for the rest", () => {
+ const pages = [{ cursor: null, result: withheldDiff() }];
+ const parsed = combinePullRequestDiffPages(pages, new WeakMap(), "pr", GITHUB);
+ if (parsed.kind !== "files") throw new Error("Expected structured diff");
+ const placeholder = parsed.files[0];
+ let merged: ReviewParsedDiff = parsed;
+ const fileWith = (load: WithheldFileLoad | undefined, canLoad = true) => {
+ merged = withWithheldFiles(
+ parsed,
+ new Map(load === undefined ? [] : [["large.ts", load]]),
+ canLoad,
+ "pr",
+ );
+ return merged.kind === "files" ? merged.files[0] : undefined;
+ };
+ expect(fileWith(undefined)).toMatchObject({
+ notice: "Diff too large to display. Tap to load it.",
+ noticeTone: "warning",
+ noticeActionable: true,
+ });
+ expect(fileWith(undefined, false)).toMatchObject({
+ notice: "Diff too large to display here.",
+ noticeActionable: false,
+ });
+ expect(fileWith({ status: "loading" })).toMatchObject({ noticeActionable: false });
+ expect(fileWith({ status: "error" })).toMatchObject({
+ notice: "Couldn't load this diff. Tap to try again.",
+ noticeActionable: true,
+ });
+ const loaded = fileWith({ status: "loaded", result: diff("large.ts") });
+ expect(loaded).toMatchObject({ id: placeholder?.id, path: "large.ts" });
+ expect(loaded?.notice).toBeUndefined();
+ expect(loaded?.rows.length).toBeGreaterThan(0);
+ // The totals follow the loaded file, which may have changed since the page was read.
+ expect(merged).toMatchObject({ additions: 1, deletions: 1 });
+ });
});
diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts
index 9abf7cfc0c074..8ec7cea70bf32 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts
@@ -1,6 +1,10 @@
import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
import type { PullRequestDiffResult } from "@t3tools/contracts";
-import { buildReviewParsedDiff, type ReviewParsedDiff } from "../review/reviewModel";
+import {
+ buildReviewParsedDiff,
+ type ReviewParsedDiff,
+ type ReviewRenderableFile,
+} from "../review/reviewModel";
export interface PullRequestDiffPage {
readonly cursor: string | null;
@@ -61,6 +65,7 @@ export function retainPullRequestDiffPage(
(previous?.patch === result.patch &&
previous.truncated === result.truncated &&
previous.nextCursor === result.nextCursor &&
+ previous.withheldFilesReadable === result.withheldFilesReadable &&
JSON.stringify(previous.omittedFileStats ?? []) ===
JSON.stringify(result.omittedFileStats ?? []))
)
@@ -84,7 +89,13 @@ export function combinePullRequestDiffPages(
);
const files = value.files.map((file) => {
const stat = omittedFileStats.get(file.path);
- return stat ? { ...file, additions: stat.additions, deletions: stat.deletions } : file;
+ if (!stat) return file;
+ return {
+ ...file,
+ additions: stat.additions,
+ deletions: stat.deletions,
+ ...(file.rows.length === 0 ? { withheld: true } : {}),
+ };
});
value = {
...value,
@@ -111,3 +122,63 @@ export function combinePullRequestDiffPages(
: null,
};
}
+
+export type WithheldFileLoad =
+ | { readonly status: "loading" | "error" }
+ | { readonly status: "loaded"; readonly result: PullRequestDiffResult };
+
+const withheldFileParses = new WeakMap();
+
+function parseWithheldFile(result: PullRequestDiffResult, scope: string) {
+ if (withheldFileParses.has(result)) return withheldFileParses.get(result) ?? null;
+ const parsed = buildReviewParsedDiff(result.patch, scope);
+ const file =
+ parsed.kind === "files" ? (parsed.files.find((entry) => entry.rows.length > 0) ?? null) : null;
+ withheldFileParses.set(result, file);
+ return file;
+}
+
+function withheldFileNotice(load: WithheldFileLoad | undefined, canLoad: boolean): string {
+ if (load === undefined) {
+ return canLoad
+ ? "Diff too large to display. Tap to load it."
+ : "Diff too large to display here.";
+ }
+ if (load.status === "loading") return "Loading diff…";
+ if (load.status === "error") return "Couldn't load this diff. Tap to try again.";
+ return "No text diff for this file.";
+}
+
+/**
+ * Puts each loaded withheld file in place of its empty one, under the same id so folds and
+ * targets hold, and gives the rest a notice saying what a tap does.
+ */
+export function withWithheldFiles(
+ parsed: ReviewParsedDiff,
+ loads: ReadonlyMap,
+ canLoad: boolean,
+ scope: string,
+): ReviewParsedDiff {
+ if (parsed.kind !== "files" || !parsed.files.some((file) => file.withheld)) return parsed;
+ const files = parsed.files.map((file): ReviewRenderableFile => {
+ if (!file.withheld) return file;
+ const load = loads.get(file.path);
+ const loaded =
+ load?.status === "loaded"
+ ? parseWithheldFile(load.result, `${scope}:withheld:${file.path}`)
+ : null;
+ if (loaded !== null) return { ...loaded, id: file.id };
+ return {
+ ...file,
+ notice: withheldFileNotice(load, canLoad),
+ noticeTone: "warning",
+ noticeActionable: canLoad && (load === undefined || load.status === "error"),
+ };
+ });
+ return {
+ ...parsed,
+ files,
+ additions: files.reduce((total, file) => total + file.additions, 0),
+ deletions: files.reduce((total, file) => total + file.deletions, 0),
+ };
+}
diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.ts b/apps/mobile/src/features/pull-requests/pullRequestList.ts
index 674d3b0e24fe3..5a4572dbde803 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestList.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestList.ts
@@ -11,6 +11,7 @@ import {
type PullRequestListStatsInput,
} from "@t3tools/contracts";
import type { PullRequestListControls } from "../../persistence/mobile-preferences";
+import { compareTimestamps } from "../../lib/time";
export const PR_LIST_PAGE_SIZE = 30;
export type { PullRequestListControls } from "../../persistence/mobile-preferences";
@@ -242,7 +243,7 @@ export function mergePullRequestListEntries(
const held = entries.get(key);
if (!held || (entry.observedAt ?? 0) >= (held.observedAt ?? 0)) entries.set(key, entry);
}
- return [...entries.values()].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
+ return [...entries.values()].sort((a, b) => compareTimestamps(b.updatedAt, a.updatedAt));
}
export interface PullRequestListPages {
@@ -455,10 +456,10 @@ export function filterPullRequestList<
}
return [...unique.values()].sort((a, b) =>
controls.sort === "created"
- ? b.createdAt.localeCompare(a.createdAt)
+ ? compareTimestamps(b.createdAt, a.createdAt)
: controls.sort === "oldest"
- ? a.updatedAt.localeCompare(b.updatedAt)
- : b.updatedAt.localeCompare(a.updatedAt),
+ ? compareTimestamps(a.updatedAt, b.updatedAt)
+ : compareTimestamps(b.updatedAt, a.updatedAt),
);
}
diff --git a/apps/mobile/src/features/pull-requests/pullRequestStatus.test.ts b/apps/mobile/src/features/pull-requests/pullRequestStatus.test.ts
index aef40179ded64..e5cb4551db56b 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestStatus.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestStatus.test.ts
@@ -97,5 +97,8 @@ describe("mobile overview check status", () => {
expect(
pullRequestChecksSummary({ checks: [check("success"), check("pending"), check("failure")] }),
).toMatchObject({ title: "1 check failing", count: "1 of 3" });
+ expect(
+ pullRequestChecksSummary({ checks: [check("success"), check("cancelled")] }),
+ ).toMatchObject({ title: "1 check failing", tint: "accent-danger-foreground" });
});
});
diff --git a/apps/mobile/src/features/pull-requests/pullRequestStatus.ts b/apps/mobile/src/features/pull-requests/pullRequestStatus.ts
index 5426266dc6893..d664aef1fc015 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestStatus.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestStatus.ts
@@ -88,8 +88,12 @@ export function checkStatus(check: PullRequestCheck) {
}
}
+export function isFailingCheck(check: PullRequestCheck) {
+ return check.status === "failure" || check.status === "cancelled";
+}
+
export function pullRequestChecksSummary(pr: Pick) {
- const failed = pr.checks.filter((check) => check.status === "failure").length;
+ const failed = pr.checks.filter(isFailingCheck).length;
const required = pr.checks.filter((check) => check.status === "action-required").length;
const pending = pr.checks.filter((check) => check.status === "pending").length;
const passed = pr.checks.filter((check) => check.status === "success").length;
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts b/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts
new file mode 100644
index 0000000000000..1f2d0d8582de1
--- /dev/null
+++ b/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts
@@ -0,0 +1,52 @@
+import { useAtomSet, useAtomValue } from "@effect/atom-react";
+import { AsyncResult } from "effect/reactivity";
+import { useState } from "react";
+import type { PullRequestActivityVisibility } from "../../persistence/mobile-preferences";
+import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
+import { DEFAULT_ACTIVITY_FILTER, type ActivityFilter } from "./pullRequestActivityFilter";
+
+const SHOW_EVERYTHING: PullRequestActivityVisibility = { bots: true, resolved: true };
+
+/**
+ * Bot and resolved visibility is a saved preference. A timeline link shows everything for this
+ * screen only, until the user picks visibility themselves.
+ */
+export function usePullRequestActivityFilter(link: string | undefined) {
+ const preferences = useAtomValue(mobilePreferencesAtom);
+ const savePreferences = useAtomSet(updateMobilePreferencesAtom);
+ const [view, setView] = useState(() => ({
+ kind: link === "commits" ? ("commits" as const) : DEFAULT_ACTIVITY_FILTER.kind,
+ newestFirst: DEFAULT_ACTIVITY_FILTER.newestFirst,
+ linkVisibility: link === "timeline" ? SHOW_EVERYTHING : null,
+ }));
+ const saved = AsyncResult.isSuccess(preferences)
+ ? preferences.value.pullRequestActivityVisibility
+ : undefined;
+ const visibility = view.linkVisibility ?? saved ?? DEFAULT_ACTIVITY_FILTER;
+ const filter: ActivityFilter = {
+ kind: view.kind,
+ newestFirst: view.newestFirst,
+ bots: visibility.bots,
+ resolved: visibility.resolved,
+ };
+ const visibilityChanged = (next: ActivityFilter) =>
+ next.bots !== filter.bots || next.resolved !== filter.resolved;
+ return {
+ filter,
+ setFilter: (next: ActivityFilter) => {
+ if (visibilityChanged(next)) {
+ savePreferences({
+ pullRequestActivityVisibility: { bots: next.bots, resolved: next.resolved },
+ });
+ }
+ setView((current) => ({
+ kind: next.kind,
+ newestFirst: next.newestFirst,
+ linkVisibility: visibilityChanged(next) ? null : current.linkVisibility,
+ }));
+ },
+ showTimeline: () =>
+ setView((current) => ({ ...current, kind: "all", linkVisibility: SHOW_EVERYTHING })),
+ showCommits: () => setView((current) => ({ ...current, kind: "commits" })),
+ };
+}
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
index 6e49993a137f3..f091e5b6847d6 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
@@ -5,8 +5,9 @@ import {
type PullRequestListEntry,
type PullRequestSummary,
} from "@t3tools/contracts";
-import { useAtomRefresh } from "@effect/atom-react";
-import { useLayoutEffect, useMemo, useState } from "react";
+import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
+import { Atom } from "effect/reactivity";
+import { useContext, useLayoutEffect, useMemo, useState } from "react";
import { composerPullRequests } from "../../state/pull-requests";
import { useEnvironmentQuery } from "../../state/query";
@@ -14,7 +15,9 @@ import { usePullToRefresh } from "../../state/use-pull-to-refresh";
import {
getCachedPullRequestDiffPages,
retainPullRequestDiffPage,
+ withWithheldFiles,
type PullRequestDiffPage,
+ type WithheldFileLoad,
} from "./pullRequestDiffPages";
export type PullRequestParams = {
@@ -43,6 +46,26 @@ export function pullRequestTarget(params: PullRequestParams) {
}
const NO_PAGES: readonly PullRequestDiffPage[] = [];
+const NO_PATHS: readonly string[] = [];
+
+type PullRequestDiffTarget = Parameters[0];
+
+// Keyed by the diff's serialized target, which the hook already holds as its scope.
+const withheldFileDiff = (targetKey: string, path: string) => {
+ const target = JSON.parse(targetKey) as PullRequestDiffTarget;
+ return composerPullRequests.diff({ ...target, input: { ...target.input, path } });
+};
+
+// One read per withheld file the reader asked for, so only that file's diff crosses the wire.
+const withheldFileDiffsAtom = Atom.family((key: string) => {
+ const { targetKey, paths } = JSON.parse(key) as {
+ readonly targetKey: string;
+ readonly paths: readonly string[];
+ };
+ return Atom.make((get) => paths.map((path) => get(withheldFileDiff(targetKey, path)))).pipe(
+ Atom.withLabel(`mobile:pull-request-withheld-file-diffs:${key}`),
+ );
+});
export function usePullRequestDiffEntry(navigation: {
readonly addListener: (
@@ -116,10 +139,46 @@ export function usePullRequestDiff(
}, [cursor, key, query.data, state.key, state.pages]);
if (state.key !== key || state.pages !== pages) setState({ key, cursor, pages });
- const parsed = useMemo(
+ const [withheldLoads, setWithheldLoads] = useState<{
+ readonly key: string;
+ readonly paths: readonly string[];
+ }>({ key: "", paths: NO_PATHS });
+ const withheldPaths = withheldLoads.key === key ? withheldLoads.paths : NO_PATHS;
+ const withheldResults = useAtomValue(
+ withheldFileDiffsAtom(JSON.stringify({ targetKey: key, paths: withheldPaths })),
+ );
+ const registry = useContext(RegistryContext);
+ const refreshWithheldFiles = () => {
+ for (const path of withheldPaths) registry.refresh(withheldFileDiff(key, path));
+ };
+ const loadWithheldFile = (path: string) => {
+ // The read is keyed without the head, so even a first load must not reuse an older one.
+ registry.refresh(withheldFileDiff(key, path));
+ if (!withheldPaths.includes(path)) setWithheldLoads({ key, paths: [...withheldPaths, path] });
+ };
+ // A refetch keeps showing the last patch, whose lines may not exist at the new head.
+ const withheldRefetching = withheldResults.some((result) => result.waiting);
+ const loads = new Map();
+ withheldPaths.forEach((path, index) => {
+ const result = withheldResults[index];
+ if (result === undefined) return;
+ // A failed refetch still carries the last patch; show the failure instead.
+ loads.set(
+ path,
+ result._tag === "Failure"
+ ? { status: "error" }
+ : result._tag === "Success"
+ ? { status: "loaded", result: result.value }
+ : { status: "loading" },
+ );
+ });
+ const pagesParsed = useMemo(
() => getCachedPullRequestDiffPages(pages, key, terminology),
[key, pages, terminology],
);
+ // The server says whether a withheld file can be read alone; GitHub may refuse the whole diff.
+ const withheldFilesReadable = pages[0]?.result.withheldFilesReadable === true;
+ const parsed = withWithheldFiles(pagesParsed, loads, withheldFilesReadable, key);
const patch = useMemo(() => pages.map((page) => page.result.patch).join("\n"), [pages]);
const nextCursor = pages.at(-1)?.result.nextCursor ?? null;
const canLoadMore =
@@ -136,15 +195,19 @@ export function usePullRequestDiff(
}
setState({ key, cursor: null, pages: NO_PAGES });
refreshFirstPage();
+ refreshWithheldFiles();
};
const onPullRefresh = () => {
setState({ key, cursor: null, pages: NO_PAGES });
onRefresh();
+ refreshWithheldFiles();
};
return {
...query,
refresh,
parsed,
+ loadWithheldFile,
+ withheldRefetching,
patch,
nextCursor,
canLoadMore,
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestList.ts b/apps/mobile/src/features/pull-requests/usePullRequestList.ts
index d4fe1ab3461bd..8ba0721fd7fb5 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestList.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestList.ts
@@ -1,3 +1,8 @@
+import {
+ editHeldPullRequestListEntries,
+ pullRequestHostAnswer,
+ pullRequestPendingEditsFor,
+} from "@t3tools/client-runtime/state/pull-requests";
import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
@@ -31,7 +36,10 @@ type Read = (atom: Atom.Atom) => A;
/** The head the list query holds now, cached or answered. */
function currentHead(read: Read, target: ListTarget) {
- return AsyncResult.getOrElse(read(composerPullRequests.list(target)), () => null);
+ return AsyncResult.getOrElse(
+ read(pullRequestHostAnswer(composerPullRequests.list(target))),
+ () => null,
+ );
}
function currentPages(read: Read, target: ListTarget): PullRequestListPages | null {
@@ -44,12 +52,23 @@ function currentPages(read: Read, target: ListTarget): PullRequestListPages | nu
const sourcesFamily = Atom.family((key: string) => {
const targets: readonly ListTarget[] = JSON.parse(key);
return Atom.make((get) =>
- targets.map((target) => ({
- target,
- result: get(composerPullRequests.list(target)),
- pages: currentPages(get, target),
- stats: get(pullRequestListStatsFamily(target.environmentId)),
- })),
+ targets.map((target) => {
+ const pages = currentPages(get, target);
+ return {
+ target,
+ result: get(composerPullRequests.list(target)),
+ pages:
+ pages === null
+ ? null
+ : {
+ ...pages,
+ entries: editHeldPullRequestListEntries(target.input, pages.entries, (entry) =>
+ get(pullRequestPendingEditsFor(target.environmentId, entry)),
+ ),
+ },
+ stats: get(pullRequestListStatsFamily(target.environmentId)),
+ };
+ }),
);
});
@@ -71,7 +90,7 @@ async function loadNextPages(
continuations(registry, targets).map(async ({ target, pages, input }) => {
const response = await executeAtomQuery(
registry,
- composerPullRequests.list({ ...target, input }),
+ pullRequestHostAnswer(composerPullRequests.list({ ...target, input })),
{
signal,
refresh: retry,
@@ -113,11 +132,15 @@ async function refreshHeads(
input: {},
});
if (signal.aborted) return;
- const response = await executeAtomQuery(registry, composerPullRequests.list(target), {
- refresh: true,
- signal,
- reportFailure: false,
- });
+ const response = await executeAtomQuery(
+ registry,
+ pullRequestHostAnswer(composerPullRequests.list(target)),
+ {
+ refresh: true,
+ signal,
+ reportFailure: false,
+ },
+ );
if (signal.aborted) return;
if (response._tag === "Failure") throw squashAtomCommandFailure(response);
registry.set(
diff --git a/apps/mobile/src/features/review/ReviewCommentCard.tsx b/apps/mobile/src/features/review/ReviewCommentCard.tsx
index a65bd83e9a66d..3e2cdc9ddfb6c 100644
--- a/apps/mobile/src/features/review/ReviewCommentCard.tsx
+++ b/apps/mobile/src/features/review/ReviewCommentCard.tsx
@@ -12,8 +12,10 @@ import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";
import {
buildNativeReviewDiffData,
buildNativeReviewSnippetRows,
+ buildReviewCommentPatch,
createNativeReviewDiffTheme,
NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
+ reviewCommentDiffText,
} from "./nativeReviewDiffAdapter";
import { buildReviewParsedDiff } from "./reviewModel";
import { REVIEW_MONO_FONT_FAMILY } from "./reviewDiffRendering";
@@ -86,7 +88,7 @@ export const ReviewCommentCard = memo(function ReviewCommentCard(props: {
theme: appearanceScheme,
});
const snippetTokens = useMarkdownCodeHighlight({
- code: props.comment.diff.trim(),
+ code: reviewCommentDiffText(props.comment.diff),
language: props.comment.fenceLanguage ?? language,
enabled: compactNativeRows.length === 0,
theme: appearanceScheme,
@@ -234,32 +236,10 @@ export const ReviewCommentCard = memo(function ReviewCommentCard(props: {
) /* oxlint-enable react/no-array-index-key */,
)
- : props.comment.diff.trim()}
+ : reviewCommentDiffText(props.comment.diff)}
) : null}
);
});
-
-function buildReviewCommentPatch(comment: ReviewInlineComment): string {
- if ((comment.fenceLanguage ?? "diff") !== "diff") {
- return "";
- }
- const diff = comment.diff.trim();
- if (!diff) {
- return "";
- }
-
- if (diff.startsWith("diff --git ")) {
- return diff;
- }
-
- const normalizedPath = comment.filePath.replaceAll("\\", "/");
- return [
- `diff --git a/${normalizedPath} b/${normalizedPath}`,
- `--- a/${normalizedPath}`,
- `+++ b/${normalizedPath}`,
- diff,
- ].join("\n");
-}
diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx
index 21bf033b761be..7cf0716277b80 100644
--- a/apps/mobile/src/features/review/ReviewSheet.tsx
+++ b/apps/mobile/src/features/review/ReviewSheet.tsx
@@ -26,11 +26,10 @@ import {
import { PaneListItem } from "../../components/ui/PaneListItem";
import { ScreenContent } from "../../components/ui/ScreenContent";
import { SheetPane } from "../../components/ui/SheetPane";
-import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
-import { useAtomCommand } from "../../state/use-atom-command";
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
+import { useRetryEnvironment } from "../connection/useRetryEnvironment";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import {
Inspector,
@@ -351,7 +350,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
const { themeAppearance: selectedTheme } = useAppearancePreferences();
const { environmentId, threadId } = props.route.params;
const environment = useEnvironmentPresentation(environmentId);
- const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
+ const retryEnvironment = useRetryEnvironment();
const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
const { draftMessage, draftContext } = useThreadDraftForThread({ environmentId, threadId });
const reviewCache = useReviewCacheForThread({ environmentId, threadId });
diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts
index 7e620836baccd..06c577df1bda0 100644
--- a/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts
+++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts
@@ -8,7 +8,9 @@ import { combinePullRequestDiffPages } from "../pull-requests/pullRequestDiffPag
import { createPullRequestDiffHighlightFiles } from "../pull-requests/pullRequestDiffHighlightFiles";
import {
buildNativeReviewDiffData,
+ buildReviewCommentPatch,
getCachedNativeReviewDiffData,
+ reviewCommentDiffText,
} from "./nativeReviewDiffAdapter";
import type { ReviewInlineComment } from "./reviewCommentSelection";
import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";
@@ -46,6 +48,27 @@ function filesPatch(paths: ReadonlyArray) {
.join("\n");
}
+describe("buildReviewCommentPatch", () => {
+ it("keeps a selection's trailing blank line and whitespace", () => {
+ const rows = (diff: string) =>
+ buildNativeReviewDiffData(
+ buildReviewParsedDiff(
+ buildReviewCommentPatch({ ...makeComment("Insert here."), diff }),
+ "review-comment-trailing-blank",
+ ),
+ ).rows.filter((row) => row.kind === "line");
+
+ expect(rows("@@ -3,1 +2,2 @@\n+two\t\n ")).toMatchObject([
+ { content: "two\t", change: "add" },
+ { content: "", change: "context" },
+ ]);
+ expect(rows("@@ -4,1 +4,1 @@\n ")).toMatchObject([{ content: "", change: "context" }]);
+ expect(reviewCommentDiffText("\n@@ -3,1 +2,2 @@\n+two\t\n \n")).toBe(
+ "@@ -3,1 +2,2 @@\n+two\t\n ",
+ );
+ });
+});
+
describe("buildNativeReviewDiffData languages", () => {
it.each([
["js", "javascript"],
diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
index d55aa97e305c9..63372efb661bc 100644
--- a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
+++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
@@ -1,3 +1,4 @@
+import { cutLineNoteStart } from "@t3tools/shared/diffCutLines";
import type { NativeReviewDiffRow, NativeReviewDiffTheme } from "../diffs/nativeReviewDiffSurface";
import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
import * as Arr from "effect/Array";
@@ -44,6 +45,32 @@ export function buildNativeReviewSnippetRows(
}));
}
+export function reviewCommentDiffText(diff: string): string {
+ return diff.trimStart().replace(/\n+$/, "");
+}
+
+export function buildReviewCommentPatch(comment: ReviewInlineComment): string {
+ if ((comment.fenceLanguage ?? "diff") !== "diff") {
+ return "";
+ }
+ if (!comment.diff.trim()) {
+ return "";
+ }
+ const diff = reviewCommentDiffText(comment.diff);
+
+ if (diff.startsWith("diff --git ")) {
+ return diff;
+ }
+
+ const normalizedPath = comment.filePath.replaceAll("\\", "/");
+ return [
+ `diff --git a/${normalizedPath} b/${normalizedPath}`,
+ `--- a/${normalizedPath}`,
+ `+++ b/${normalizedPath}`,
+ diff,
+ ].join("\n");
+}
+
function opaqueNativeHexColor(color: string, background: string): string {
const hex = NATIVE_HEX_COLOR.exec(color);
if (hex && !hex[4]) return color;
@@ -200,6 +227,8 @@ export function createNativeReviewDiffTheme(
deleteBar: terminalRed ?? "#ff2e3f",
addText: "#5ECC71",
deleteText: "#FF6762",
+ warningText: nativeColor(appTheme["--color-warning-foreground"]),
+ warningBackground: nativeColor(appTheme["--color-warning"]),
};
}
@@ -217,6 +246,8 @@ export function createNativeReviewDiffTheme(
deleteBar: terminalRed ?? "#ff2e3f",
addText: "#199F43",
deleteText: "#D52C36",
+ warningText: nativeColor(appTheme["--color-warning-foreground"]),
+ warningBackground: nativeColor(appTheme["--color-warning"]),
};
}
@@ -244,7 +275,15 @@ function createNoticeRow(fileId: string, suffix: string, text: string): NativeRe
}
function noticeRowsForFile(file: ReviewRenderableFile): ReadonlyArray {
- if (file.notice) return [createNoticeRow(file.id, "loading", file.notice)];
+ if (file.notice) {
+ return [
+ {
+ ...createNoticeRow(file.id, "loading", file.notice),
+ ...(file.noticeTone === undefined ? {} : { tone: file.noticeTone }),
+ ...(file.noticeActionable ? { actionable: true } : {}),
+ },
+ ];
+ }
if (file.rows.length > 0) {
return [];
}
@@ -362,6 +401,7 @@ function mapLineRow(
row: ReviewRenderableLineRow,
rowIndex: number,
): NativeReviewDiffRow {
+ const noteStart = cutLineNoteStart(row.content);
return {
kind: "line",
id: `${file.id}:line:${rowIndex}:${row.id}`,
@@ -370,6 +410,7 @@ function mapLineRow(
change: row.change,
oldLineNumber: row.oldLineNumber,
newLineNumber: row.newLineNumber,
+ ...(noteStart === null ? {} : { noteStart }),
};
}
diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts
index df3c7c51324b4..3a1028dbb1730 100644
--- a/apps/mobile/src/features/review/reviewModel.ts
+++ b/apps/mobile/src/features/review/reviewModel.ts
@@ -56,6 +56,11 @@ export interface ReviewRenderableFile {
readonly id: string;
readonly cacheKey: string;
readonly notice?: string;
+ readonly noticeTone?: "warning";
+ /** The notice row reports taps, as for loading a withheld file's diff. */
+ readonly noticeActionable?: boolean;
+ /** The host left out this file's hunks as too large; it can be loaded on its own. */
+ readonly withheld?: boolean;
readonly path: string;
readonly previousPath: string | null;
readonly changeType: ChangeTypes;
diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts
index d9ec656cbc773..8368c1ec63aa3 100644
--- a/apps/mobile/src/features/review/useReviewDiffData.ts
+++ b/apps/mobile/src/features/review/useReviewDiffData.ts
@@ -55,7 +55,7 @@ function getCachedReviewFile(
...(loaded ?? {
path: stat.path,
previousPath: stat.previousPath,
- changeType: "change" as const,
+ changeType: stat.changeType ?? ("change" as const),
languageHint: null,
additionLines: [],
deletionLines: [],
@@ -142,13 +142,7 @@ export function useReviewDiffData(input: {
});
const registry = useContext(RegistryContext);
const { environmentId, cwd } = input;
- const scope = JSON.stringify([
- environmentId,
- cwd,
- source?.kind,
- source?.baseRef,
- source?.diffHash,
- ]);
+ const scope = JSON.stringify([environmentId, cwd, lazySource?.kind, source?.baseRef]);
const [requested, setRequested] = useState({ scope, indices: [0, 1, 2] });
const indices = useMemo(
() => new Set(requested.scope === scope ? requested.indices : [0, 1, 2]),
diff --git a/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx
index c0f93d2ee324d..1b34022d4cae5 100644
--- a/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx
@@ -72,10 +72,10 @@ export function SettingsClientStorageRouteScreen() {
{AsyncResult.isFailure(summaryResult) ? (
diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.test.tsx
new file mode 100644
index 0000000000000..b92c1ec725b47
--- /dev/null
+++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.test.tsx
@@ -0,0 +1,264 @@
+import { RegistryContext } from "@effect/atom-react";
+import {
+ EnvironmentId,
+ ProjectId,
+ ProviderInstanceId,
+ ScheduledTaskId,
+ type ScheduledTask,
+} from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
+import { act, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const { Children, mocks } = vi.hoisted(() => ({
+ Children: ({ children }: { children?: ReactNode }) => children,
+ mocks: { upsert: vi.fn(), alert: vi.fn(), tasks: [] as ScheduledTask[] },
+}));
+vi.mock("react-native", () => ({
+ Platform: { OS: "ios" },
+ View: Children,
+ TextInput: () => null,
+ Pressable: ({ children, onPress }: { children?: ReactNode; onPress: () => void }) => (
+
+ ),
+}));
+vi.mock("@react-navigation/native", () => ({
+ useNavigation: () => ({ isFocused: () => false }),
+ usePreventRemove: () => {},
+}));
+vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) }));
+vi.mock("@expo/ui/community/datetime-picker", () => ({ DateTimePicker: () => null }));
+vi.mock("../../components/ui/Dialog", () => ({ alert: mocks.alert }));
+vi.mock("../../components/ui/AppText", () => ({ AppText: Children }));
+vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
+vi.mock("../../components/EnvironmentMachineSymbol", () => ({
+ EnvironmentMachineSymbol: () => null,
+ ENVIRONMENT_MACHINE_SYMBOLS: {},
+}));
+vi.mock("../../components/ui/Menu", () => ({
+ Menu: ({
+ actions,
+ onPressAction,
+ }: {
+ actions: readonly { id: string; title: string }[];
+ onPressAction: (event: { nativeEvent: { event: string } }) => void;
+ }) =>
+ actions.map(({ id, title }) => (
+
+ )),
+}));
+vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children }));
+vi.mock("./components/SettingsScreen", () => ({ SettingsScreen: Children }));
+vi.mock("./components/SettingsSection", () => ({ SettingsSection: Children }));
+vi.mock("./components/SettingsEnvironmentFilterHeader", () => ({
+ useSettingsEnvironmentMenu: () => null,
+}));
+vi.mock("./components/ScheduledTaskPromptField", () => ({ ScheduledTaskPromptField: () => null }));
+vi.mock("../layout/workspace/useSelectWorkspaceDetail", () => ({
+ useSelectWorkspaceDetail: () => vi.fn(),
+}));
+vi.mock("../../state/threads", () => ({ threadFamilies: {} }));
+vi.mock("../../lib/copyTextWithHaptic", () => ({ tryCopyTextWithHaptic: vi.fn() }));
+vi.mock("../voice-input/useVoiceInputController", () => ({
+ useVoiceInputController: () => ({ blocksSubmission: false }),
+}));
+vi.mock("../../components/ui/Button", () => ({
+ Button: ({ label, onPress }: { label: string; onPress: () => void }) => (
+
+ ),
+}));
+vi.mock("../../components/ui/SegmentedControl", () => ({
+ SegmentedControl: ({
+ options,
+ onSelect,
+ }: {
+ options: readonly { value: string; label: string }[];
+ onSelect: (value: string) => void;
+ }) =>
+ options.map(({ value, label }) => (
+
+ )),
+}));
+vi.mock("../../components/ui/ThemedSwitch", () => ({
+ ThemedSwitch: ({
+ value,
+ onValueChange,
+ }: {
+ value: boolean;
+ onValueChange: (value: boolean) => void;
+ }) => ,
+}));
+vi.mock("../../state/entities", () => ({
+ useProjects: () => [
+ { environmentId: "environment", id: "project", title: "Project" },
+ { environmentId: "target", id: "target-project", title: "Target project" },
+ ],
+ useServerConfigs: () => new Map(),
+ useEnvironmentServerConfig: () => null,
+ useThreadShell: () => null,
+}));
+vi.mock("./settings-environment-filter", () => ({
+ useSettingsEnvironmentFilter: () => ({
+ selectedTargets: [{ environmentId: "environment", label: "Environment" }],
+ availableTargets: [
+ { environmentId: "environment", label: "Environment" },
+ { environmentId: "target", label: "Target" },
+ ],
+ selectedProjectKey: null,
+ projectGroups: [],
+ }),
+}));
+vi.mock("../../lib/modelOptions", () => ({
+ buildModelOptions: () => [],
+ resolveDefaultableModelSelection: () => null,
+ resolveNewTaskModelSelection: () => null,
+}));
+vi.mock("../../state/session", () => ({
+ readEnvironmentScope: () => true,
+ usePreparedConnection: () => ({ _tag: "None" }),
+}));
+vi.mock("../../state/server", () => ({
+ serverEnvironment: {
+ scheduledTasksLive: () => ({}),
+ upsertScheduledTask: { permissionAtom: () => Atom.make(true) },
+ },
+}));
+vi.mock("../../state/query", () => ({
+ useEnvironmentQuery: () => ({ data: { tasks: mocks.tasks, threads: [] } }),
+}));
+vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => mocks.upsert }));
+
+import { appAtomRegistry } from "../../state/atom-registry";
+import { editDraft } from "./scheduledTaskDraft";
+import {
+ scheduledTaskEditorSessionAtom,
+ startScheduledTaskEditor,
+} from "./scheduled-task-editor-state";
+import { SettingsScheduledTaskEditRouteScreen } from "./SettingsScheduledTasksRouteScreen";
+
+let root: Root;
+let container: HTMLDivElement;
+beforeEach(() => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ container = document.createElement("div");
+ root = createRoot(container);
+ mocks.alert.mockReset();
+ mocks.upsert.mockReset();
+ mocks.upsert.mockResolvedValue({ _tag: "Success" });
+ const task: ScheduledTask = {
+ id: ScheduledTaskId.make("task"),
+ title: "Task",
+ prompt: "Prompt",
+ enabled: true,
+ schedule: { type: "fixed_time", timeOfDay: "05:00" },
+ projectId: ProjectId.make("project"),
+ threadId: null,
+ workspaceStrategy: { type: "root" },
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("codex"),
+ model: "model",
+ },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ createdBy: "user",
+ creationSource: "mobile",
+ createdAt: "2026-10-22T00:00:00.000Z",
+ updatedAt: "2026-10-22T00:00:00.000Z",
+ nextRunAt: null,
+ lastRunAt: null,
+ lastRunStatus: "never",
+ lastRunError: null,
+ runCount: 0,
+ };
+ mocks.tasks = [task];
+ const draft = editDraft(task);
+ startScheduledTaskEditor({
+ environmentId: EnvironmentId.make("environment"),
+ environmentLabel: "Environment",
+ draft: { ...draft, schedule: { ...draft.schedule, intervalMinutes: "60" } },
+ });
+ act(() =>
+ root.render(
+
+
+ ,
+ ),
+ );
+});
+afterEach(() => {
+ act(() => root.unmount());
+ appAtomRegistry.set(scheduledTaskEditorSessionAtom, null);
+});
+function button(label: string) {
+ const element = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === label,
+ );
+ if (!element) throw new Error(`Missing button: ${label}`);
+ return element;
+}
+describe("scheduled task batched edits", () => {
+ it("submits the selected interval when saved before React commits", async () => {
+ await act(async () => {
+ button("Interval").click();
+ button("Save changes").click();
+ });
+ expect(mocks.alert).not.toHaveBeenCalled();
+ expect(mocks.upsert).toHaveBeenCalledExactlyOnceWith({
+ environmentId: "environment",
+ input: expect.objectContaining({
+ id: "task",
+ requireExisting: true,
+ schedule: { type: "interval", everyMs: 3_600_000 },
+ }),
+ });
+ });
+ it("retains the interval when enabled changes before React commits", async () => {
+ act(() => {
+ button("Interval").click();
+ button("Toggle enabled").click();
+ });
+ expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current?.draft.schedule.mode).toBe(
+ "interval",
+ );
+ await act(async () => button("Save changes").click());
+ expect(mocks.alert).not.toHaveBeenCalled();
+ expect(mocks.upsert).toHaveBeenCalledExactlyOnceWith({
+ environmentId: "environment",
+ input: expect.objectContaining({
+ id: "task",
+ requireExisting: true,
+ enabled: false,
+ schedule: { type: "interval", everyMs: 3_600_000 },
+ }),
+ });
+ });
+ it("keeps every webhook filter added before React commits", () => {
+ act(() => button("On webhook").click());
+ act(() => {
+ button("Add filter").click();
+ button("Add filter").click();
+ });
+ expect(
+ appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current?.draft.schedule.filters,
+ ).toHaveLength(2);
+ });
+ it("keeps the target project when an old picker fires after changing environments", () => {
+ const editor = appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current;
+ if (!editor) throw new Error("Missing editor");
+ act(() => startScheduledTaskEditor({ ...editor, draft: { ...editor.draft, task: null } }));
+ act(() => {
+ button("Select Target").click();
+ button("Interval").click();
+ button("Select Project").click();
+ });
+ expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current).toMatchObject({
+ environmentId: "target",
+ draft: { projectId: "target-project", schedule: { mode: "interval" } },
+ });
+ });
+});
diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
index 3f552c1f0c46c..d71fbc8fd9d24 100644
--- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
@@ -83,7 +83,11 @@ import {
type ScheduledTaskDraft as Draft,
} from "./scheduledTaskDraft";
import { settingsTargetsForProject } from "./settings-environment-filter.logic";
-import { useScheduledTaskDestinationLabel, useScheduledTaskEditor } from "./scheduled-task-editor";
+import {
+ useScheduledTaskDestinationLabel,
+ useScheduledTaskEditor,
+ useScheduledTaskThread,
+} from "./scheduled-task-editor";
import {
discardScheduledTaskEditor,
markScheduledTaskEditorSaved,
@@ -267,11 +271,13 @@ function SelectRow(props: {
function WebhookFilterRows(props: {
readonly filters: ReadonlyArray;
readonly disabled: boolean;
- readonly onChange: (filters: ReadonlyArray) => void;
+ readonly onChange: (
+ update: (filters: ReadonlyArray) => ReadonlyArray,
+ ) => void;
}) {
- const update = (index: number, patch: Partial) =>
- props.onChange(
- props.filters.map((filter, at) => (at === index ? { ...filter, ...patch } : filter)),
+ const update = (id: WebhookFilterDraft["id"], patch: Partial) =>
+ props.onChange((filters) =>
+ filters.map((filter) => (filter.id === id ? { ...filter, ...patch } : filter)),
);
return (
<>
@@ -284,7 +290,9 @@ function WebhookFilterRows(props: {
accessibilityLabel={`Remove filter ${index + 1}`}
disabled={props.disabled}
hitSlop={8}
- onPress={() => props.onChange(removeWebhookFilterDraft(props.filters, filter.id))}
+ onPress={() =>
+ props.onChange((filters) => removeWebhookFilterDraft(filters, filter.id))
+ }
className="active:opacity-70"
>
@@ -295,7 +303,7 @@ function WebhookFilterRows(props: {
value={filter.path}
placeholder="body.action"
disabled={props.disabled}
- onChange={(path) => update(index, { path })}
+ onChange={(path) => update(filter.id, { path })}
/>
{
const known = WEBHOOK_FILTER_OPS.find((option) => option.op === id);
- if (known) update(index, { op: known.op });
+ if (known) update(filter.id, { op: known.op });
}}
/>
{filter.op === "exists" ? null : (
@@ -316,7 +324,7 @@ function WebhookFilterRows(props: {
value={filter.value}
placeholder={filter.op === "in" ? "opened, reopened" : "opened"}
disabled={props.disabled}
- onChange={(value) => update(index, { value })}
+ onChange={(value) => update(filter.id, { value })}
/>
)}
@@ -325,7 +333,13 @@ function WebhookFilterRows(props: {
props.onChange([...props.filters, emptyWebhookFilterDraft()])}
+ onPress={() =>
+ props.onChange((filters) =>
+ filters.length < MAX_WEBHOOK_FILTERS
+ ? [...filters, emptyWebhookFilterDraft()]
+ : filters,
+ )
+ }
className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
>
@@ -590,8 +604,19 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }
voiceInput={voiceInput}
/>
}
- setDraft={(draft) => {
- if (!saving) setEditor({ ...editor, draft });
+ setDraft={(update) => {
+ if (!saving)
+ setEditor((current) =>
+ current ? { ...current, draft: update(current.draft) } : current,
+ );
+ }}
+ setEnvironmentDraft={(update) => {
+ if (!saving)
+ setEditor((current) =>
+ current && current.environmentId === editor.environmentId
+ ? { ...current, draft: update(current.draft) }
+ : current,
+ );
}}
onSaved={() => {
saved.current = true;
@@ -599,18 +624,21 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }
if (navigation.isFocused()) navigation.goBack();
}}
onChangeEnvironment={(target) => {
- if (target.environmentId === editor.environmentId) return;
- setEditor({
- environmentId: target.environmentId,
- environmentLabel: target.label,
- draft: {
- ...draftForEnvironment(target.environmentId),
- title: editor.draft.title,
- prompt: editor.draft.prompt,
- schedule: editor.draft.schedule,
- enabled: editor.draft.enabled,
- },
- });
+ setEditor((current) =>
+ !current || target.environmentId === current.environmentId
+ ? current
+ : {
+ environmentId: target.environmentId,
+ environmentLabel: target.label,
+ draft: {
+ ...draftForEnvironment(target.environmentId),
+ title: current.draft.title,
+ prompt: current.draft.prompt,
+ schedule: current.draft.schedule,
+ enabled: current.draft.enabled,
+ },
+ },
+ );
}}
/>
) : (
@@ -635,6 +663,7 @@ function TaskForm({
dictationPending,
promptField,
setDraft,
+ setEnvironmentDraft,
onSaved,
onChangeEnvironment,
}: {
@@ -646,10 +675,12 @@ function TaskForm({
readonly setSaving: (saving: boolean) => void;
readonly dictationPending: boolean;
readonly promptField: ReactNode;
- readonly setDraft: (draft: Draft) => void;
+ readonly setDraft: (update: (current: Draft) => Draft) => void;
+ readonly setEnvironmentDraft: (update: (current: Draft) => Draft) => void;
readonly onSaved: () => void;
readonly onChangeEnvironment: (target: SettingsTarget) => void;
}) {
+ const { readEditor } = useScheduledTaskEditor();
const navigation = useNavigation>();
const tasks = useEnvironmentQuery(
serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
@@ -666,6 +697,10 @@ function TaskForm({
.sort((left, right) => Number(right.pinnedAt != null) - Number(left.pinnedAt != null));
const config = useEnvironmentServerConfig(environmentId);
const destinationLabel = useScheduledTaskDestinationLabel(environmentId, draft.threadId);
+ const boundThread = useScheduledTaskThread(environmentId, draft.threadId);
+ // Bound runs use the thread's current model, so the locked row shows that one.
+ const shownSelection =
+ draft.threadId === null ? draft.modelSelection : (boundThread?.modelSelection ?? null);
const modelOptions = buildModelOptions(config, null, undefined, draft.projectId);
// Existing webhook tasks keep the option so they can still switch to a timer.
const webhookDenial = managedCapabilityDenial(config?.managedPolicy, "webhookTasks");
@@ -699,6 +734,9 @@ function TaskForm({
draft.task?.schedule.type === "once";
const offersThreadModes = config?.environment.capabilities.scheduledTaskThreadModes === true;
const save = async () => {
+ const current = readEditor();
+ if (!current || current.environmentId !== environmentId) return;
+ const draft = current.draft;
if (
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
submissionPending.current ||
@@ -853,7 +891,7 @@ function TaskForm({
disabled={saving}
value={draft.title}
placeholder="Check for issues"
- onChange={(title) => setDraft({ ...draft, title })}
+ onChange={(title) => setDraft((current) => ({ ...current, title }))}
/>
{promptField}
@@ -873,21 +911,23 @@ function TaskForm({
onSelect={(id) => {
const project = projects.find((item) => item.id === id);
if (!project) return;
- const keepsExplicitModel =
- draft.modelSelectionIsExplicit &&
- (draft.modelSelection === null ||
- !config?.settings ||
- resolveProjectProviderInstanceEnabled(
- config.settings,
- project.id,
- draft.modelSelection.instanceId,
- ));
- setDraft({
- ...changeDraftProject(draft, project.id),
- modelSelection: keepsExplicitModel
- ? draft.modelSelection
- : scheduledTaskDefaultModel(config, project),
- modelSelectionIsExplicit: keepsExplicitModel,
+ setEnvironmentDraft((current) => {
+ const keepsExplicitModel =
+ current.modelSelectionIsExplicit &&
+ (current.modelSelection === null ||
+ !config?.settings ||
+ resolveProjectProviderInstanceEnabled(
+ config.settings,
+ project.id,
+ current.modelSelection.instanceId,
+ ));
+ return {
+ ...changeDraftProject(current, project.id),
+ modelSelection: keepsExplicitModel
+ ? current.modelSelection
+ : scheduledTaskDefaultModel(config, project),
+ modelSelectionIsExplicit: keepsExplicitModel,
+ };
});
}}
/>
@@ -897,14 +937,17 @@ function TaskForm({
value={
modelOptions.find(
(option) =>
- option.selection.instanceId === draft.modelSelection?.instanceId &&
- option.selection.model === draft.modelSelection?.model,
+ option.selection.instanceId === shownSelection?.instanceId &&
+ option.selection.model === shownSelection?.model,
)?.label ??
- draft.modelSelection?.model ??
+ shownSelection?.model ??
(modelOptions.length ? "Choose model" : "No models available")
}
onPress={() => navigation.navigate("SettingsScheduledTaskModel")}
- disabled={saving || dictationPending || environmentUnavailable}
+ // The saved selection only seeds new threads; bound runs ignore it.
+ disabled={
+ saving || dictationPending || environmentUnavailable || draft.threadId !== null
+ }
/>
@@ -935,9 +978,9 @@ function TaskForm({
)}
onSelect={(id) => {
if (id === "new_thread")
- setDraft({ ...unbindDraftFromThread(draft), threadMode: id });
+ setDraft((current) => ({ ...unbindDraftFromThread(current), threadMode: id }));
else if (id === "continue" || id === "fresh_session")
- setDraft({ ...draft, threadMode: id });
+ setDraft((current) => ({ ...current, threadMode: id }));
}}
/>
) : null}
@@ -985,7 +1028,7 @@ function TaskForm({
]}
onSelect={(id) => {
if (id === "worktree" || id === "root" || id === "existing_worktree")
- setDraft({ ...draft, workspace: id });
+ setDraft((current) => ({ ...current, workspace: id }));
}}
/>
{draft.workspace === "worktree" ? (
@@ -1008,10 +1051,10 @@ function TaskForm({
value={draft.checkoutPath}
borderTop
onChange={(checkoutPath) =>
- setDraft({
- ...draft,
- checkoutPath: resolvePastedPath(draft.checkoutPath, checkoutPath),
- })
+ setEnvironmentDraft((current) => ({
+ ...current,
+ checkoutPath: resolvePastedPath(current.checkoutPath, checkoutPath),
+ }))
}
/>
) : null}
@@ -1036,21 +1079,21 @@ function TaskForm({
onSelect={(mode) => {
setTimePickerOpen(false);
setRunAtPicker(null);
- setDraft({
- ...draft,
+ setDraft((current) => ({
+ ...current,
prompt:
- mode === "webhook" && !draft.prompt.trim()
+ mode === "webhook" && !current.prompt.trim()
? DEFAULT_WEBHOOK_PROMPT
- : draft.prompt,
+ : current.prompt,
schedule: {
- ...draft.schedule,
+ ...current.schedule,
mode,
runAt:
- mode === "once" && !draft.schedule.runAt
+ mode === "once" && !current.schedule.runAt
? new Date(Math.ceil(Date.now() / 3_600_000) * 3_600_000).toISOString()
- : draft.schedule.runAt,
+ : current.schedule.runAt,
},
- });
+ }));
}}
/>
@@ -1089,7 +1132,10 @@ function TaskForm({
onDismiss={() => setTimePickerOpen(false)}
onValueChange={(_, selected) => {
const timeOfDay = `${String(selected.getHours()).padStart(2, "0")}:${String(selected.getMinutes()).padStart(2, "0")}`;
- setDraft({ ...draft, schedule: { ...draft.schedule, timeOfDay } });
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, timeOfDay },
+ }));
}}
/>
) : null}
@@ -1118,19 +1164,21 @@ function TaskForm({
})),
]}
onSelect={(id) => {
- const weekdays =
- id === "every_day"
- ? DAYS.map((day) => day.index)
- : id === "weekdays"
- ? [1, 2, 3, 4, 5]
- : (() => {
- const day = DAYS.find((item) => String(item.index) === id);
- if (!day) return draft.schedule.weekdays;
- return draft.schedule.weekdays.includes(day.index)
- ? draft.schedule.weekdays.filter((index) => index !== day.index)
- : [...draft.schedule.weekdays, day.index];
- })();
- setDraft({ ...draft, schedule: { ...draft.schedule, weekdays } });
+ setDraft((current) => {
+ const weekdays =
+ id === "every_day"
+ ? DAYS.map((day) => day.index)
+ : id === "weekdays"
+ ? [1, 2, 3, 4, 5]
+ : (() => {
+ const day = DAYS.find((item) => String(item.index) === id);
+ if (!day) return current.schedule.weekdays;
+ return current.schedule.weekdays.includes(day.index)
+ ? current.schedule.weekdays.filter((index) => index !== day.index)
+ : [...current.schedule.weekdays, day.index];
+ })();
+ return { ...current, schedule: { ...current.schedule, weekdays } };
+ });
}}
/>
>
@@ -1175,10 +1223,10 @@ function TaskForm({
onValueChange={(_, selected) => {
// Android shows a dialog that closes on pick; iOS stays inline.
if (Platform.OS === "android") setRunAtPicker(null);
- setDraft({
- ...draft,
- schedule: { ...draft.schedule, runAt: selected.toISOString() },
- });
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, runAt: selected.toISOString() },
+ }));
}}
/>
) : null}
@@ -1206,14 +1254,20 @@ function TaskForm({
disabled={saving}
borderTop
onChange={(maxDeliveryAgeMinutes) =>
- setDraft({ ...draft, schedule: { ...draft.schedule, maxDeliveryAgeMinutes } })
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, maxDeliveryAgeMinutes },
+ }))
}
/>
- setDraft({ ...draft, schedule: { ...draft.schedule, filters } })
+ onChange={(update) =>
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, filters: update(current.schedule.filters) },
+ }))
}
/>
- setDraft({ ...draft, schedule: { ...draft.schedule, replayKey } })
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, replayKey },
+ }))
}
/>
@@ -1236,7 +1293,10 @@ function TaskForm({
disabled={saving}
borderTop
onChange={(coalesceKey) =>
- setDraft({ ...draft, schedule: { ...draft.schedule, coalesceKey } })
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, coalesceKey },
+ }))
}
/>
- setDraft({ ...draft, schedule: { ...draft.schedule, coalesceWindowSeconds } })
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, coalesceWindowSeconds },
+ }))
}
/>
@@ -1264,7 +1327,10 @@ function TaskForm({
disabled={saving}
borderTop
onChange={(intervalMinutes) =>
- setDraft({ ...draft, schedule: { ...draft.schedule, intervalMinutes } })
+ setDraft((current) => ({
+ ...current,
+ schedule: { ...current.schedule, intervalMinutes },
+ }))
}
/>
{!(parseIntervalMinutes(draft.schedule.intervalMinutes) >= 1) ? (
@@ -1287,7 +1353,7 @@ function TaskForm({
setDraft({ ...draft, enabled })}
+ onValueChange={(enabled) => setDraft((current) => ({ ...current, enabled }))}
/>
diff --git a/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts b/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts
index ffeb6114c17a5..c71298a89822a 100644
--- a/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts
+++ b/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts
@@ -1,4 +1,6 @@
-import { resolveScaledTextRole } from "../../../lib/appearancePreferences";
+import { Platform, useWindowDimensions } from "react-native";
+
+import { resolveComposerTextRole, resolveScaledTextRole } from "../../../lib/appearancePreferences";
import { MOBILE_TYPOGRAPHY } from "../../../lib/typography";
import { useAppearancePreferences } from "./AppearancePreferencesProvider";
@@ -12,3 +14,9 @@ export function useScaledTextRole(role: keyof typeof MOBILE_TYPOGRAPHY): ScaledT
const { appearance } = useAppearancePreferences();
return resolveScaledTextRole(role, appearance.baseFontSize);
}
+
+export function useComposerTextRole(): ScaledTextRole {
+ const body = useScaledTextRole("body");
+ const { fontScale } = useWindowDimensions();
+ return resolveComposerTextRole(body, fontScale, Platform.OS);
+}
diff --git a/apps/mobile/src/features/settings/scheduled-task-editor.tsx b/apps/mobile/src/features/settings/scheduled-task-editor.tsx
index e99600ae533b8..d79ef40896e87 100644
--- a/apps/mobile/src/features/settings/scheduled-task-editor.tsx
+++ b/apps/mobile/src/features/settings/scheduled-task-editor.tsx
@@ -21,22 +21,29 @@ import {
export const NEW_THREAD_DESTINATION_LABEL = "New thread each run";
-export function useScheduledTaskDestinationLabel(
+export function useScheduledTaskThread(
environmentId: EnvironmentId | null,
threadId: ThreadId | null,
-): string {
+) {
const ref =
environmentId === null || threadId === null ? null : scopeThreadRef(environmentId, threadId);
const shell = useThreadShell(ref);
- // The shell can omit older settled threads; their family read still carries the title.
+ // The shell can omit older settled threads; their family read still carries the row.
const family = useEnvironmentQuery(
ref !== null && shell === null
? threadFamilies.familyAtom(ref.environmentId, ref.threadId)
: null,
);
- const thread = shell ?? family.data?.threads.find((row) => row.id === threadId);
- if (ref === null) return NEW_THREAD_DESTINATION_LABEL;
- return thread?.title.trim() || `Thread ${ref.threadId}`;
+ return shell ?? family.data?.threads.find((row) => row.id === threadId) ?? null;
+}
+
+export function useScheduledTaskDestinationLabel(
+ environmentId: EnvironmentId | null,
+ threadId: ThreadId | null,
+): string {
+ const thread = useScheduledTaskThread(environmentId, threadId);
+ if (environmentId === null || threadId === null) return NEW_THREAD_DESTINATION_LABEL;
+ return thread?.title.trim() || `Thread ${threadId}`;
}
/** The form draft lives in an atom, so it survives while its native picker routes are on top. */
diff --git a/apps/mobile/src/features/settings/scheduledTaskPresentation.test.ts b/apps/mobile/src/features/settings/scheduledTaskPresentation.test.ts
new file mode 100644
index 0000000000000..02ca0a2d11c78
--- /dev/null
+++ b/apps/mobile/src/features/settings/scheduledTaskPresentation.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { formatNextScheduledTaskRun } from "./scheduledTaskPresentation";
+
+describe("formatNextScheduledTaskRun", () => {
+ it("names the rounded unit for a run later today", () => {
+ const now = new Date(2026, 10, 3, 10, 0, 0).getTime();
+ const at = (minutes: number) => new Date(now + minutes * 60_000).toISOString();
+ expect(formatNextScheduledTaskRun(at(59), now)).toBe("Next run in 59 minutes");
+ expect(formatNextScheduledTaskRun(at(59.5), now)).toBe("Next run in 1 hour");
+ expect(formatNextScheduledTaskRun(at(150), now)).toBe("Next run in 3 hours");
+ });
+});
diff --git a/apps/mobile/src/features/settings/scheduledTaskPresentation.ts b/apps/mobile/src/features/settings/scheduledTaskPresentation.ts
index 0fbc2626f1fbb..7ebdcfc2d3b3c 100644
--- a/apps/mobile/src/features/settings/scheduledTaskPresentation.ts
+++ b/apps/mobile/src/features/settings/scheduledTaskPresentation.ts
@@ -38,8 +38,9 @@ export function formatNextScheduledTaskRun(nextRunAt: string, now: number): stri
const days = localCalendarDay(next) - localCalendarDay(current);
if (days === 0) {
if (remaining < MINUTE) return "Next run in less than a minute";
- const unit = remaining < HOUR ? "minute" : "hour";
- const count = Math.round(remaining / (remaining < HOUR ? MINUTE : HOUR));
+ const minutes = Math.round(remaining / MINUTE);
+ const unit = minutes < 60 ? "minute" : "hour";
+ const count = minutes < 60 ? minutes : Math.round(remaining / HOUR);
return `Next run in ${count} ${unit}${count === 1 ? "" : "s"}`;
}
diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts
index 3e798975d743c..1dea547de53b4 100644
--- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts
+++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts
@@ -54,7 +54,7 @@ describe("incoming native shares", () => {
text: "Please explain this error\n\nhttps://example.com/issue/1",
attachments: [
{
- id: "share-1:image:3",
+ id: "share-1-image-3",
type: "image",
name: "Screenshot.png",
mimeType: "image/png",
@@ -131,7 +131,7 @@ describe("incoming native shares", () => {
expect(result.attachments).toEqual([
{
- id: "share-report:file:0",
+ id: "share-report-file-0",
type: "file",
name: "report.pdf",
mimeType: "application/pdf",
@@ -165,7 +165,7 @@ describe("incoming native shares", () => {
expect(result.warnings).toEqual([]);
expect(result.attachments).toEqual([
{
- id: "share-video:file:0",
+ id: "share-video-file-0",
type: "file",
name: video.originalName,
mimeType: video.mimeType,
@@ -239,7 +239,7 @@ describe("incoming native shares", () => {
expect(result.attachments).toEqual([
{
- id: "share-android-report:file:0",
+ id: "share-android-report-file-0",
type: "file",
name: "report",
mimeType: "application/pdf",
diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts
index aa097713923b6..aa97294e15466 100644
--- a/apps/mobile/src/features/sharing/incoming-share-model.ts
+++ b/apps/mobile/src/features/sharing/incoming-share-model.ts
@@ -332,7 +332,7 @@ export async function buildIncomingShareDraft(input: {
}
}
attachments.push({
- id: `${input.id}:file:${index}`,
+ id: `${input.id}-file-${index}`,
type: "file",
name,
mimeType,
@@ -397,7 +397,7 @@ export async function buildIncomingShareDraft(input: {
}
const dataUrl = `data:${mimeType};base64,${base64}`;
attachments.push({
- id: `${input.id}:image:${index}`,
+ id: `${input.id}-image-${index}`,
type: "image",
name: resolved?.originalName ?? fallbackName(uri, index, mimeType),
mimeType,
diff --git a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts
index c985506480b76..961c0f42fa538 100644
--- a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts
+++ b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vite-plus/test";
vi.mock("expo-quick-actions", () => ({}));
vi.mock("react-native", () => ({ Platform: { OS: "android" } }));
+vi.mock("../../connection/catalog", () => ({}));
vi.mock("../../persistence/imperative", () => ({}));
vi.mock("../../state/atom-registry", () => ({}));
vi.mock("../../state/threads", () => ({ environmentThreadShells: {} }));
@@ -54,6 +55,23 @@ describe("createRecentThreadShortcuts", () => {
expect(save).toHaveBeenLastCalledWith([thread("a")]);
});
+ it("drops threads of environments that are no longer saved", async () => {
+ const gone = { environmentId: "gone", threadId: "b", title: "b" };
+ const kept = { environmentId: "kept", threadId: "c", title: "c" };
+ const { save, publish, recents } = setup(() => Promise.resolve([thread("a"), gone, kept]));
+ recents.retainEnvironments(new Set(["env", "kept"]));
+ await recents.loaded;
+ expect(publish).toHaveBeenLastCalledWith([thread("a"), kept]);
+
+ recents.retainEnvironments(new Set(["kept"]));
+ await recents.saved();
+ expect(publish).toHaveBeenLastCalledWith([kept]);
+ expect(save).toHaveBeenLastCalledWith([kept]);
+
+ recents.recordActiveThread(thread("a"));
+ expect(publish).toHaveBeenLastCalledWith([kept]);
+ });
+
it("records title changes of the open thread and ignores repeats", async () => {
const { publish, recents } = setup(() => Promise.resolve([]));
await recents.loaded;
diff --git a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts
index b182c33b07866..a8c3d7b964776 100644
--- a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts
+++ b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts
@@ -4,6 +4,7 @@ import type { NavigationState } from "@react-navigation/native";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
+import { environmentCatalog } from "../../connection/catalog";
import {
loadRecentThreadShortcuts,
saveRecentThreadShortcuts,
@@ -34,6 +35,7 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD
let recents: ReadonlyArray | null = null;
let persistable = false;
let active: RecentThreadShortcut | null = null;
+ let savedEnvironmentIds: ReadonlySet | null = null;
// Serialize saves so older lists cannot overwrite newer ones.
let saveQueue: Promise = Promise.resolve();
@@ -53,8 +55,11 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD
});
};
+ const isSaved = (thread: RecentThreadShortcut) =>
+ savedEnvironmentIds?.has(thread.environmentId) ?? true;
+
const withActive = (list: ReadonlyArray) => {
- if (active === null) return list;
+ if (active === null || !isSaved(active)) return list;
const next = withRecentThreadShortcut(list, active);
if (next !== list) persistable = true;
return next;
@@ -63,7 +68,7 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD
const loaded = dependencies.load().then(
(threads) => {
persistable = true;
- commit(withActive(threads));
+ commit(withActive(threads.filter(isSaved)));
},
(error: unknown) => {
console.warn("[app-shortcuts] failed to load recent threads", error);
@@ -81,6 +86,12 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD
const updated = withActive(recents);
if (updated !== recents) commit(updated);
},
+ retainEnvironments(next: ReadonlySet): void {
+ savedEnvironmentIds = next;
+ if (recents === null) return;
+ const kept = recents.filter(isSaved);
+ if (kept.length !== recents.length) commit(kept);
+ },
};
}
@@ -142,8 +153,16 @@ export function installAppShortcuts(navigate: (href: string) => void): () => voi
(active) => recents.recordActiveThread(active),
{ immediate: true },
);
+ const unsubscribeCatalog = appAtomRegistry.subscribe(
+ environmentCatalog.catalogValueAtom,
+ (catalog) => {
+ if (catalog.isReady) recents.retainEnvironments(new Set(catalog.entries.keys()));
+ },
+ { immediate: true },
+ );
return () => {
subscription.remove();
unsubscribe();
+ unsubscribeCatalog();
};
}
diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
index 4b84006352162..d66ff4192ecc5 100644
--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
@@ -4,6 +4,7 @@ import * as Dialog from "../../components/ui/Dialog";
import {
AuthTerminalReadScope,
AuthTerminalOperateScope,
+ chunkTerminalWrite,
DEFAULT_TERMINAL_ID,
EnvironmentId,
ThreadId,
@@ -42,7 +43,6 @@ import { LoadingScreen } from "../../components/LoadingScreen";
import { ScreenContent } from "../../components/ui/ScreenContent";
import { Button } from "../../components/ui/Button";
import { IconButton } from "../../components/ui/IconButton";
-import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
import { terminalEnvironment } from "../../state/terminal";
import { environmentSession, readEnvironmentScope } from "../../state/session";
@@ -66,6 +66,7 @@ import {
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
+import { useRetryEnvironment } from "../connection/useRetryEnvironment";
import { TerminalSurface, type TerminalSurfaceHandle } from "./NativeTerminalSurface";
import { getMobileTerminalTheme } from "./terminalTheme";
import { useTerminalExitNavigation } from "./useTerminalExitNavigation";
@@ -383,7 +384,7 @@ function ThreadTerminal(props: {
const navigation = useNavigation();
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
- const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
+ const retryEnvironment = useRetryEnvironment();
const selectedThreadDetail = useSelectedThreadProjection();
const selectedThreadDetailWorktreePath =
selectedThreadDetail?.projection.thread.worktreePath ?? null;
@@ -622,15 +623,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) => {
@@ -908,7 +915,7 @@ function ThreadTerminal(props: {
title="No terminal sessions"
detail="Existing terminals will appear here when another client opens one."
/>
- ) : !canOperateTerminal && terminal.error !== null ? (
+ ) : terminal.error !== null && (!canOperateTerminal || terminal.status === "error") ? (
) : (
<>
diff --git a/apps/mobile/src/features/terminal/terminalInput.test.ts b/apps/mobile/src/features/terminal/terminalInput.test.ts
index 17fabe588115c..6e5046dab35c4 100644
--- a/apps/mobile/src/features/terminal/terminalInput.test.ts
+++ b/apps/mobile/src/features/terminal/terminalInput.test.ts
@@ -1,11 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import {
- chunkTerminalWrite,
- encodeTerminalPaste,
- resolveModifiedTerminalInput,
- TERMINAL_WRITE_MAX_LENGTH,
-} from "./terminalInput";
+import { encodeTerminalPaste, resolveModifiedTerminalInput } from "./terminalInput";
const byte = (code: number) => String.fromCharCode(code);
const ESC = byte(0x1b);
@@ -78,23 +73,3 @@ describe("encodeTerminalPaste", () => {
expect(encodeTerminalPaste(`safe${ESC}[201~; rm -rf /\n`)).toBe("safe [201~; rm -rf /\r");
});
});
-
-describe("chunkTerminalWrite", () => {
- it("splits oversized writes so every chunk fits the contract", () => {
- const chunks = chunkTerminalWrite("y".repeat(TERMINAL_WRITE_MAX_LENGTH * 2 + 5));
- expect(chunks.map((chunk) => chunk.length)).toEqual([
- TERMINAL_WRITE_MAX_LENGTH,
- TERMINAL_WRITE_MAX_LENGTH,
- 5,
- ]);
- expect(chunks.join("")).toHaveLength(TERMINAL_WRITE_MAX_LENGTH * 2 + 5);
- });
-
- it("does not cut a surrogate pair in half at the boundary", () => {
- const data = `${"z".repeat(TERMINAL_WRITE_MAX_LENGTH - 1)}😀tail`;
- const chunks = chunkTerminalWrite(data);
- expect(chunks[0]).toHaveLength(TERMINAL_WRITE_MAX_LENGTH - 1);
- expect(chunks[1]).toBe("😀tail");
- expect(chunks.join("")).toBe(data);
- });
-});
diff --git a/apps/mobile/src/features/terminal/terminalInput.ts b/apps/mobile/src/features/terminal/terminalInput.ts
index 9c5e05dcc24f0..0f09d109e3634 100644
--- a/apps/mobile/src/features/terminal/terminalInput.ts
+++ b/apps/mobile/src/features/terminal/terminalInput.ts
@@ -3,9 +3,6 @@ import type { ExecutionEnvironmentPlatformOs } from "@t3tools/contracts";
export type PendingModifier = "ctrl" | "meta";
export type HostPlatform = "mac" | "linux" | "windows" | "unknown";
-/** Upper bound of `TerminalWriteInput.data`; longer writes are rejected by the server. */
-export const TERMINAL_WRITE_MAX_LENGTH = 65_536;
-
export type ModifiedTerminalInput =
| { readonly kind: "write"; readonly data: string }
| { readonly kind: "paste" };
@@ -64,21 +61,6 @@ export function encodeTerminalPaste(text: string): string {
return text.replace(UNSAFE_PASTE_BYTES, " ").replace(/\r\n|\n/g, "\r");
}
-export function chunkTerminalWrite(data: string): ReadonlyArray {
- const chunks: string[] = [];
- let start = 0;
- while (start < data.length) {
- let end = Math.min(start + TERMINAL_WRITE_MAX_LENGTH, data.length);
- const last = data.charCodeAt(end - 1);
- if (end < data.length && last >= 0xd800 && last <= 0xdbff) {
- end -= 1;
- }
- chunks.push(data.slice(start, end));
- start = end;
- }
- return chunks;
-}
-
/** Returns null for unknown OSes so callers can try weaker signals. */
export function hostPlatformFromOs(os: ExecutionEnvironmentPlatformOs | null): HostPlatform | null {
if (os === "darwin") return "mac";
diff --git a/apps/mobile/src/features/terminal/terminalPaste.test.ts b/apps/mobile/src/features/terminal/terminalPaste.test.ts
index ec9bd9d74d933..2545085137916 100644
--- a/apps/mobile/src/features/terminal/terminalPaste.test.ts
+++ b/apps/mobile/src/features/terminal/terminalPaste.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import { TERMINAL_WRITE_MAX_LENGTH } from "./terminalInput";
+import { TERMINAL_WRITE_MAX_LENGTH } from "@t3tools/contracts";
import { createTerminalPasteSession } from "./terminalPaste";
function deferred() {
@@ -34,6 +34,15 @@ describe("terminal paste session", () => {
expect(writes).toEqual([]);
});
+ it("reports a liveness change after capture, including a restart in place", () => {
+ const session = createTerminalPasteSession();
+ session.reset(true);
+ const isSameShell = session.liveness();
+ expect(isSameShell()).toBe(true);
+ session.reset(true);
+ expect(isSameShell()).toBe(false);
+ });
+
it("never overlaps writes from rapid paste requests", async () => {
const session = createTerminalPasteSession();
session.reset(true);
diff --git a/apps/mobile/src/features/terminal/terminalPaste.ts b/apps/mobile/src/features/terminal/terminalPaste.ts
index d070bdc168826..b09e365587d57 100644
--- a/apps/mobile/src/features/terminal/terminalPaste.ts
+++ b/apps/mobile/src/features/terminal/terminalPaste.ts
@@ -1,4 +1,6 @@
-import { chunkTerminalWrite, encodeTerminalPaste } from "./terminalInput";
+import { chunkTerminalWrite } from "@t3tools/contracts";
+
+import { encodeTerminalPaste } from "./terminalInput";
interface TerminalPasteInput {
readonly readText: () => Promise;
@@ -8,6 +10,8 @@ interface TerminalPasteInput {
export interface TerminalPasteSession {
readonly reset: (active: boolean) => void;
+ /** True until the terminal's liveness changes (stop, start or restart) after this call. */
+ readonly liveness: () => () => boolean;
readonly paste: (input: TerminalPasteInput) => Promise;
}
@@ -21,6 +25,11 @@ export function createTerminalPasteSession(): TerminalPasteSession {
liveTarget = active ? {} : null;
},
+ liveness() {
+ const target = liveTarget;
+ return () => liveTarget === target;
+ },
+
async paste({ readText, write, onReadError }) {
const target = liveTarget;
if (target === null) {
diff --git a/apps/mobile/src/features/threads/McpAppWebView.tsx b/apps/mobile/src/features/threads/McpAppWebView.tsx
index cf03775b7c7fc..203343eb5a680 100644
--- a/apps/mobile/src/features/threads/McpAppWebView.tsx
+++ b/apps/mobile/src/features/threads/McpAppWebView.tsx
@@ -264,6 +264,8 @@ export function ThreadMcpApp(props: {
);
}, [host, detailAtom]);
const userActive = useRef(false);
+ // Teardown completions check this so a replaced document's late callback is ignored.
+ const currentHost = useRef(null);
// Each WebView document gets its own host: the view is keyed by document,
// restart generation and URL, and a changed app re-attaches this callback.
@@ -399,6 +401,8 @@ export function ThreadMcpApp(props: {
}
if (mode === "fullscreen" && current.displayMode !== "fullscreen") {
await documentHost.teardown();
+ // A crash restart or reload during the wait already replaced this document.
+ if (currentHost.current !== documentHost) return "inline";
// Approval arrival or navigation during the wait requires reloading inline.
const navigation = latest.current.navigation;
if (latest.current.awaitingUser || !navigation.isFocused()) {
@@ -417,7 +421,7 @@ export function ThreadMcpApp(props: {
}
if (mode === "inline" && current.displayMode === "fullscreen") {
await documentHost.teardown();
- current.onExitFullscreen?.();
+ if (currentHost.current === documentHost) current.onExitFullscreen?.();
return "inline";
}
return current.displayMode ?? "inline";
@@ -460,11 +464,11 @@ export function ThreadMcpApp(props: {
},
onRequestTeardown: () => {
const current = latest.current.props;
- if (current.displayMode === "fullscreen") {
- void documentHost.teardown().then(() => current.onExitFullscreen?.());
- } else {
- void documentHost.teardown().then(() => setClosed(true));
- }
+ void documentHost.teardown().then(() => {
+ if (currentHost.current !== documentHost) return;
+ if (current.displayMode === "fullscreen") current.onExitFullscreen?.();
+ else setClosed(true);
+ });
},
onSizeChanged: (size) => {
if (latest.current.props.displayMode === "fullscreen") return;
@@ -473,7 +477,9 @@ export function ThreadMcpApp(props: {
},
});
setHost(documentHost);
+ currentHost.current = documentHost;
return () => {
+ if (currentHost.current === documentHost) currentHost.current = null;
// An unmount cannot wait: the request goes out before the view does.
void documentHost.teardown();
setHost((current) => (current === documentHost ? null : current));
diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
index ac9e2ce813636..8027e1572a073 100644
--- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
@@ -523,7 +523,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps
}
@@ -548,7 +548,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps
diff --git a/apps/mobile/src/features/threads/QuestionAttachments.tsx b/apps/mobile/src/features/threads/QuestionAttachments.tsx
index b8fa753188608..3cc26c42fd7fc 100644
--- a/apps/mobile/src/features/threads/QuestionAttachments.tsx
+++ b/apps/mobile/src/features/threads/QuestionAttachments.tsx
@@ -105,10 +105,7 @@ export function QuestionAttachments(props: {
props.question.id,
);
changeQuestionAttachmentPreparation(key, 1);
- void convertPastedImagesToAttachments({
- uris,
- existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0,
- })
+ void convertPastedImagesToAttachments({ uris })
.then(async (result) => {
if (
scope.active &&
diff --git a/apps/mobile/src/features/threads/SubagentRow.tsx b/apps/mobile/src/features/threads/SubagentRow.tsx
index 7c71ac2680de1..96f6f659aa5a1 100644
--- a/apps/mobile/src/features/threads/SubagentRow.tsx
+++ b/apps/mobile/src/features/threads/SubagentRow.tsx
@@ -4,7 +4,10 @@ import {
resolveProviderInstanceDisplayName,
shouldShowInstanceBadge,
} from "@t3tools/client-runtime/state/provider-instance-display";
-import { resolveSubagentMetadata } from "@t3tools/client-runtime/state/subagent-display";
+import {
+ resolveSubagentMetadata,
+ subagentCardDetail,
+} from "@t3tools/client-runtime/state/subagent-display";
import { formatSubagentEffort } from "@t3tools/client-runtime/state/thread-execution";
import type { EnvironmentId, OrchestrationV2Subagent } from "@t3tools/contracts";
import type { ReactNode } from "react";
@@ -15,7 +18,6 @@ import { SymbolView } from "../../components/ui/AppSymbol";
import { ProviderIcon, ProviderInstanceIcon } from "../../components/ProviderIcon";
import { cn } from "../../lib/cn";
import { useEnvironmentServerConfig, useProject, useThreadShell } from "../../state/entities";
-import { subagentCardDetail } from "./subagent-card-presentation";
import { SUBAGENT_TONE_TEXT_CLASS, SubagentStatusDot } from "./SubagentStatusDot";
import { resolveSubagentRowPresentation } from "./threadAgentsPresentation";
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index 3b1b927ef8a9b..ce4e4b7fb0e4b 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -15,6 +15,7 @@ import { useAtomValue } from "@effect/atom-react";
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
import { pastedTextDisposition, replaceTextSelection } from "@t3tools/client-runtime/text-paste";
import {
+ AuthOrchestrationOperateScope,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
type ChatAttachment,
@@ -29,6 +30,7 @@ import {
hasProviderUsageLimits,
isUsageLimitsCommand,
} from "@t3tools/shared/usageLimits";
+import { parseSideChatCommand } from "@t3tools/shared/composerTrigger";
import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
import type { ReactNode } from "react";
import { useEffect, useEffectEvent, useRef, useState, type RefObject } from "react";
@@ -66,6 +68,7 @@ import type { ComposerDocumentAttachment } from "../../lib/composerContext";
import { useProject, useVisibleThreadShells } from "../../state/entities";
import { useMentionableEnvironments } from "../../state/environments";
import { useLinkedEnvironments } from "../../state/peerLinks";
+import { useEnvironmentScopeDenied } from "../../state/session";
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { AppText as Text } from "../../components/ui/AppText";
@@ -78,7 +81,12 @@ import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/
import { GlassSurface } from "../../components/ui/GlassSurface";
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import { fileRoutePathSegments } from "../files/filePath";
-import { ComposerActionButton, ComposerToolbarRow } from "../../components/ComposerToolbar";
+import {
+ ComposerActionButton,
+ ComposerInlineControl,
+ ComposerToolbarRow,
+} from "../../components/ComposerToolbar";
+import { formatTokens } from "@t3tools/shared/usageFormat";
import { ComposerModelControl } from "../../components/ComposerModelControl";
import {
composerStripAttachments,
@@ -89,7 +97,7 @@ import {
isModelSelectionUnavailable,
serverConfigForCwd,
} from "../../lib/modelOptions";
-import { useScaledTextRole, type ScaledTextRole } from "../settings/appearance/useScaledTextRole";
+import { useComposerTextRole, type ScaledTextRole } from "../settings/appearance/useScaledTextRole";
import type { RemoteClientConnectionState } from "../../lib/connection";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { Menu } from "../../components/ui/Menu";
@@ -217,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;
@@ -419,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);
@@ -471,6 +487,10 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
setResumingQueue(false);
};
+ const operateDenied = useEnvironmentScopeDenied(
+ props.environmentId,
+ AuthOrchestrationOperateScope,
+ );
const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
const attachmentsUploading =
props.connectionState === "connected" &&
@@ -482,7 +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:
@@ -568,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 }),
@@ -813,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)}
@@ -1093,6 +1143,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined
}
>
+ {compactControl}
{modelControl}
- {props.connectionState === "connected" && !props.canOperateThread ? (
+ {props.connectionState === "connected" && operateDenied ? (
This connection cannot control this task. You can still edit your draft.
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index f94efcabbcfb1..ad3f8cb083e95 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -33,7 +33,6 @@ import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-e
import {
childThreadInputsTitle,
type CodexFeedbackSubmission,
- type EnvironmentThreadStatus,
} from "@t3tools/client-runtime/state/threads";
import { useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
@@ -183,8 +182,6 @@ import { PendingApprovalCard } from "./PendingApprovalCard";
import { ComposerErrorNotice } from "./ComposerErrorNotice";
import { ManagedRuntimeModeNotice } from "./ManagedRuntimeModeNotice";
import { FreshSessionNotice } from "./FreshSessionNotice";
-import { Notice } from "../../components/ui/Notice";
-import { formatTokens } from "@t3tools/shared/usageFormat";
import { ComposerFeedback } from "./ComposerFeedback";
import { ComposerUsageLimits } from "./ComposerUsageLimits";
import { PendingUserInputCard } from "./PendingUserInputCard";
@@ -204,6 +201,7 @@ import {
COMPOSER_COLLAPSED_CHROME,
THREAD_COMPOSER_BOTTOM_GUTTER,
ThreadComposer,
+ type ThreadComposerProps,
} from "./ThreadComposer";
import { ComposerPopoverHost } from "./ComposerPopoverHost";
import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
@@ -254,11 +252,7 @@ export interface ThreadDetailScreenProps {
readonly extensionStatuses?: NonNullable;
readonly isCompacting: boolean;
/** Set while the next send compacts the thread first. */
- readonly compactBeforeSend?: {
- readonly tokens: number;
- readonly keepFullHistory: boolean;
- readonly toggleKeepFullHistory: () => void;
- } | null;
+ readonly compactBeforeSend?: ThreadComposerProps["compactBeforeSend"];
readonly creationState:
| {
readonly kind: "preparing";
@@ -276,7 +270,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;
@@ -575,20 +568,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;
@@ -811,18 +790,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 {
@@ -1507,6 +1481,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;
@@ -1715,25 +1694,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 80292dc03fd25..3025861f143ab 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -27,6 +27,7 @@ import { LinkRequestCard } from "./LinkRequestCard";
import { SecretRequestCard } from "./SecretRequestCard";
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import {
+ WorktreePreparingHeader,
WorktreeWorkingHeader,
WorktreeSetupCard,
type WorktreeSetupCardProps,
@@ -97,6 +98,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";
@@ -290,7 +292,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.
@@ -323,6 +325,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;
@@ -1092,7 +1095,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;
@@ -1127,8 +1134,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),
@@ -1671,6 +1685,7 @@ function renderFeedEntry(
| "threadId"
| "workspaceRoot"
> & {
+ readonly formatMessageTime: (input: string) => string;
readonly copiedRowId: string | null;
readonly expandedWorkRows: Record;
readonly workRowSizing: ReturnType;
@@ -1916,7 +1931,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;
@@ -3047,7 +3068,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;
@@ -3122,7 +3145,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);
@@ -3350,8 +3373,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,
@@ -3436,7 +3461,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) => {
@@ -3760,6 +3787,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,
@@ -3805,6 +3833,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
) : props.setupWorkingStartedAt && info.index === setupAnchorIndex ? (
+ ) : props.preparingWorktree && info.index === setupAnchorIndex ? (
+
) : null}
@@ -3901,6 +3931,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 2302f2229aca3..c273446a67ebf 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
@@ -393,7 +393,6 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
) === props.selectedThreadKey)
}
project={projectByKey.get(pendingScopeKey) ?? null}
- projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
environmentLabel={
Object.keys(savedConnectionsById).length > 1
? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
index d3b3ba6006291..c251283ef8839 100644
--- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx
+++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
@@ -25,6 +25,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Button } from "../../components/ui/Button";
import * as Dialog from "../../components/ui/Dialog";
+import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
import { SheetHeader } from "../../components/ui/SheetHeader";
import { AppText as Text } from "../../components/ui/AppText";
import { SymbolView } from "../../components/ui/AppSymbol";
@@ -143,6 +144,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) {
});
const [resuming, setResuming] = useState(false);
const [busyRunId, setBusyRunId] = useState(null);
+ const [previewFile, setPreviewFile] = useState(null);
const busyRef = useRef(false);
const queuedRuns = workflow?.queuedRuns ?? [];
@@ -321,6 +323,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) {
{message ? (
@@ -384,6 +387,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) {
navigation.goBack()} />
{content}
+ setPreviewFile(null)} />
);
}
@@ -436,8 +440,10 @@ function QueueRowSwipeable(props: {
function QueueAttachmentThumbnails(props: {
readonly environmentId: EnvironmentId;
readonly attachments: ReadonlyArray;
+ readonly onPressPreview: (source: FilePreviewSource) => void;
}) {
const images = props.attachments.filter((attachment) => attachment.mimeType.startsWith("image/"));
+ const gallery = images.map((attachment) => queueImagePreview(props.environmentId, attachment));
const shown = images.slice(0, THUMBNAIL_LIMIT);
const overflow = props.attachments.length - shown.length;
if (props.attachments.length === 0) return null;
@@ -448,6 +454,12 @@ function QueueAttachmentThumbnails(props: {
key={attachment.id}
environmentId={props.environmentId}
attachment={attachment}
+ onPress={() =>
+ props.onPressPreview({
+ ...queueImagePreview(props.environmentId, attachment),
+ gallery,
+ })
+ }
/>
))}
{overflow > 0 ? (
@@ -461,28 +473,60 @@ function QueueAttachmentThumbnails(props: {
);
}
+function queueAttachmentResource(attachment: ChatAttachment) {
+ return {
+ _tag: "attachment",
+ attachmentId: attachment.id,
+ fileName: attachment.name,
+ mimeType: attachment.mimeType,
+ disposition: "inline",
+ } as const;
+}
+
+function queueImagePreview(environmentId: EnvironmentId, attachment: ChatAttachment) {
+ const resource = queueAttachmentResource(attachment);
+ return {
+ kind: "image",
+ environmentId,
+ resource,
+ name: attachment.name,
+ mimeType: attachment.mimeType,
+ actionsSource: {
+ name: attachment.name,
+ mimeType: attachment.mimeType,
+ environmentId,
+ resource,
+ },
+ } as const;
+}
+
function QueueAttachmentThumbnail(props: {
readonly environmentId: EnvironmentId;
readonly attachment: ChatAttachment;
+ readonly onPress: () => void;
}) {
- const resource = {
- _tag: "attachment",
- attachmentId: props.attachment.id,
- fileName: props.attachment.name,
- mimeType: props.attachment.mimeType,
- disposition: "inline",
- } as const;
+ const resource = queueAttachmentResource(props.attachment);
const url = useAssetUrl(props.environmentId, resource);
- if (url === null) {
- return ;
- }
return (
-
+ // Its own press target, so tapping an image previews it instead of editing the message.
+
+ {url === null ? (
+
+ ) : (
+
+ )}
+
);
}
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 0bed5a25f0271..b60991731e0d7 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,27 @@ 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),
+ threadSyncStatusLabel(selectedThreadDetailState.status, contentPresentation.kind),
+ );
+ const inspectorHeader = props.inspectorPresentation ? (
+
+ ) : null;
+ if (!environmentId || !threadId || !selectedThread) {
+ return (
+ <>
+ {inspectorHeader}
+
+ >
+ );
+ }
+
const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
const renderThreadRouteBody = () => (
<>
@@ -977,7 +997,7 @@ function ThreadRouteContent(
props.inspectorPresentation ? null : (
+ {inspectorHeader}
{!props.inspectorPresentation && inspectorContent ? (
setComposerDraftText(draftKey, text)}
reportedModelSelection={reportedModelSelection}
- onSelectModel={(option) => updateModelSelection(withRememberedModelOptions(option.selection))}
+ onSelectModel={(option) =>
+ updateModelSelection(
+ withStoredThreadModelOptions(
+ withRememberedModelOptions(option.selection),
+ selectedThread.modelSelection,
+ ),
+ )
+ }
restoreSelection={withRememberedModelOptions}
optionDescriptors={resolveProviderOptionDescriptors({
capabilities: currentModelOption?.capabilities,
diff --git a/apps/mobile/src/features/threads/checkout-new-task-branch.test.ts b/apps/mobile/src/features/threads/checkout-new-task-branch.test.ts
index bee63a9775a05..328f56bcf0066 100644
--- a/apps/mobile/src/features/threads/checkout-new-task-branch.test.ts
+++ b/apps/mobile/src/features/threads/checkout-new-task-branch.test.ts
@@ -135,12 +135,12 @@ async function addRemote(remoteName: string, sourceRef = branch.name) {
}
describe("new-task branch checkout", () => {
- it("switches to a free branch and clears its historical worktree path", async () => {
+ it("switches to a free branch despite stale current and worktree metadata", async () => {
const previousWorktree = NodePath.join(directory, "previous-worktree");
await git("worktree", "add", previousWorktree, branch.name);
await exec("git", ["-C", previousWorktree, "checkout", "-b", "other-branch"]);
const result = await checkoutNewTaskBranch({
- branch: { ...branch, worktreePath: previousWorktree },
+ branch: { ...branch, current: true, worktreePath: previousWorktree },
project: { environmentId, workspaceRoot: cwd },
workspaceMode: "local",
readRefs,
diff --git a/apps/mobile/src/features/threads/checkout-new-task-branch.ts b/apps/mobile/src/features/threads/checkout-new-task-branch.ts
index fb7920dcdd5f6..a4f3a306b2eb0 100644
--- a/apps/mobile/src/features/threads/checkout-new-task-branch.ts
+++ b/apps/mobile/src/features/threads/checkout-new-task-branch.ts
@@ -34,13 +34,10 @@ export async function checkoutNewTaskBranch(input: {
Cause.fail(new Error("The selected project is unavailable. Reconnect and try again.")),
);
}
- if (input.workspaceMode === "worktree" || input.branch.current) {
- return AsyncResult.success(
- input.branch.current ? { ...input.branch, worktreePath: null } : input.branch,
- );
- }
+ if (input.workspaceMode === "worktree") return AsyncResult.success(input.branch);
- // Remote refs omit local worktrees, and historical thread metadata can be stale.
+ // The picked ref's current flag, remote refs' missing worktrees and historical
+ // thread metadata can all be stale, so Git is asked again before choosing.
const localName = localBranchName(input.branch);
let cursor: number | undefined;
for (;;) {
diff --git a/apps/mobile/src/features/threads/floating-working-control.tsx b/apps/mobile/src/features/threads/floating-working-control.tsx
index 55028a58b7df2..0f83743f99d31 100644
--- a/apps/mobile/src/features/threads/floating-working-control.tsx
+++ b/apps/mobile/src/features/threads/floating-working-control.tsx
@@ -427,21 +427,6 @@ function FloatingStatusLabel(props: {
);
}
- if (props.status.kind === "syncing") {
- return (
-
-
-
- {props.status.label}
-
-
- );
- }
if (props.status.kind === "compacting") {
return ;
}
diff --git a/apps/mobile/src/features/threads/floating-working-status.ts b/apps/mobile/src/features/threads/floating-working-status.ts
index 6beb9cb6cb01a..941a875c9500c 100644
--- a/apps/mobile/src/features/threads/floating-working-status.ts
+++ b/apps/mobile/src/features/threads/floating-working-status.ts
@@ -10,7 +10,6 @@ export interface FloatingStatusAction {
export type FloatingWorkingStatus =
| { readonly kind: "working"; readonly environmentId: EnvironmentId; readonly startedAt: string }
- | { readonly kind: "syncing"; readonly label: string }
| { readonly kind: "compacting" }
| {
readonly kind: "child-input";
diff --git a/apps/mobile/src/features/threads/messageTimestamp.test.ts b/apps/mobile/src/features/threads/messageTimestamp.test.ts
index 94f6010acd4a1..fa1ab4be779b3 100644
--- a/apps/mobile/src/features/threads/messageTimestamp.test.ts
+++ b/apps/mobile/src/features/threads/messageTimestamp.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import { formatMessageTimestamp } from "./messageTimestamp";
+import { createMessageTimeFormatter, formatMessageTimestamp } from "./messageTimestamp";
describe("formatMessageTimestamp", () => {
const now = new Date(2026, 10, 8, 20, 0).getTime();
@@ -20,3 +20,15 @@ describe("formatMessageTimestamp", () => {
);
});
});
+
+describe("createMessageTimeFormatter", () => {
+ const now = new Date(2026, 0, 1, 20, 0).getTime();
+
+ it("follows the system clock preference over the locale's hour cycle", () => {
+ const format24 = createMessageTimeFormatter(true, "en-US");
+ expect(format24(new Date(2026, 0, 1, 15, 7).toISOString(), now)).toBe("15:07");
+ expect(format24(new Date(2026, 0, 1, 0, 7).toISOString(), now)).toBe("00:07");
+ const format12 = createMessageTimeFormatter(false, "en-GB");
+ expect(format12(new Date(2026, 0, 1, 15, 7).toISOString(), now)).toMatch(/^3:07\spm$/i);
+ });
+});
diff --git a/apps/mobile/src/features/threads/messageTimestamp.ts b/apps/mobile/src/features/threads/messageTimestamp.ts
index 5624b71c0c917..cfae85e092666 100644
--- a/apps/mobile/src/features/threads/messageTimestamp.ts
+++ b/apps/mobile/src/features/threads/messageTimestamp.ts
@@ -7,13 +7,28 @@ const DATE_WITH_YEAR_FORMATTER = new Intl.DateTimeFormat(undefined, {
});
/** Time only for today's messages; older ones lead with the day and month. */
-export function formatMessageTimestamp(input: string, nowMs: number = Date.now()): string {
+export function formatMessageTimestamp(
+ input: string,
+ nowMs: number = Date.now(),
+ timeFormatter: Intl.DateTimeFormat = TIME_FORMATTER,
+): string {
const timestamp = Date.parse(input);
if (Number.isNaN(timestamp)) return "";
const date = new Date(timestamp);
const now = new Date(nowMs);
- const time = TIME_FORMATTER.format(date);
+ const time = timeFormatter.format(date);
if (date.toDateString() === now.toDateString()) return time;
const sameYear = date.getFullYear() === now.getFullYear();
return `${(sameYear ? DATE_FORMATTER : DATE_WITH_YEAR_FORMATTER).format(date)} ${time}`;
}
+
+/** `is24Hour` overrides the locale's hour cycle with the system clock preference when known. */
+export function createMessageTimeFormatter(is24Hour: boolean | undefined, locale?: string) {
+ const timeFormatter = new Intl.DateTimeFormat(locale, {
+ hour: "numeric",
+ minute: "2-digit",
+ ...(is24Hour === undefined ? {} : { hourCycle: is24Hour ? "h23" : "h12" }),
+ });
+ return (input: string, nowMs?: number): string =>
+ formatMessageTimestamp(input, nowMs, timeFormatter);
+}
diff --git a/apps/mobile/src/features/threads/subagent-card-presentation.test.ts b/apps/mobile/src/features/threads/subagent-card-presentation.test.ts
index 2b32f84fcb9cc..14a8e6ce99dfe 100644
--- a/apps/mobile/src/features/threads/subagent-card-presentation.test.ts
+++ b/apps/mobile/src/features/threads/subagent-card-presentation.test.ts
@@ -1,17 +1,8 @@
import * as DateTime from "effect/DateTime";
import { describe, expect, it } from "vite-plus/test";
-import { subagentCardDetail, subagentCardElapsed } from "./subagent-card-presentation";
+import { subagentCardElapsed } from "./subagent-card-presentation";
describe("subagent card", () => {
- it.each([
- [" Verified", "screenshot Verified"],
- ["[docs](https://en.wikipedia.org/wiki/T3_(protocol))", "docs"],
- ["[report](outputs/report%20(final).md)", "report"],
- ["[report](outputs/report\\(final.md)", "report"],
- ])("strips image and link markup from %s", (detail, expected) => {
- expect(subagentCardDetail(detail)).toBe(expected);
- });
-
const start = DateTime.makeUnsafe("2026-09-21T12:00:00Z");
const end = DateTime.makeUnsafe("2026-09-21T12:01:00Z");
const later = DateTime.makeUnsafe("2026-09-21T12:02:00Z");
diff --git a/apps/mobile/src/features/threads/subagent-card-presentation.ts b/apps/mobile/src/features/threads/subagent-card-presentation.ts
index 42e75c5cf214e..239f48cf441cc 100644
--- a/apps/mobile/src/features/threads/subagent-card-presentation.ts
+++ b/apps/mobile/src/features/threads/subagent-card-presentation.ts
@@ -3,18 +3,6 @@ import type { OrchestrationV2Subagent } from "@t3tools/contracts";
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import * as DateTime from "effect/DateTime";
-export function subagentCardDetail(detail: string | null): string | null {
- if (!detail || /^Child task ended with status\b/i.test(detail)) return null;
- return (
- detail
- .replace(/!?\[([^\]]+)\]\((?:\\.|[^\\()]|\((?:\\.|[^\\()])*\))*\)/g, "$1")
- .replace(/`/g, "")
- .replace(/^[ \t]*[-*][ \t]+/gm, "")
- .replace(/\s+/g, " ")
- .trim() || null
- );
-}
-
export function subagentCardElapsed(
agents: ReadonlyArray>,
nowMs: number,
diff --git a/apps/mobile/src/features/threads/thread-inspector-preview.tsx b/apps/mobile/src/features/threads/thread-inspector-preview.tsx
index 9f434051144d9..813233d59714c 100644
--- a/apps/mobile/src/features/threads/thread-inspector-preview.tsx
+++ b/apps/mobile/src/features/threads/thread-inspector-preview.tsx
@@ -45,12 +45,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 2697321cd7155..66bf2cdf1bc62 100644
--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx
+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
@@ -80,10 +80,12 @@ import {
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozePresets,
threadHasUnseenCompletion,
+ resolveThreadListV2RowStatus,
resolveThreadListV2Status,
resolveThreadListV2ProviderDrivers,
resolveThreadListV2SwipeActions,
layoutThreadListV2RowMenuActions,
+ threadListV2RowAccessibilityLabel,
type ThreadListV2Status,
} from "./threadListV2";
import { QueuedMessageIcon } from "./queued-message-icon";
@@ -379,7 +381,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 +427,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 +468,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}
/>
@@ -773,7 +773,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const selected = props.selected === true;
const rowAppearance = getThreadListV2RowAppearance(theme, sidebarPane, selected);
- const status = resolveThreadListV2Status(thread);
+ const rawStatus = resolveThreadListV2Status(thread);
+ const status = resolveThreadListV2RowStatus(thread);
const isUnread = status === "ready" && threadHasUnseenCompletion(thread);
const workingLabel = STATUS_LABEL_BY_STATUS[status];
const showsWoke = status === "ready" && props.wokeAt !== null;
@@ -783,17 +784,24 @@ 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,
- props.hasQueuedMessages ? "messages queued to send" : null,
- isRegeneratingTitle ? "regenerating title" : null,
- showsWoke ? "Woke" : statusLabel?.label,
- props.environmentLabel,
- ]
- .filter(Boolean)
- .join(", ");
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,
+ });
+ // Fork: screen readers also hear the environment the row shows.
+ const rowAccessibilityLabelWithEnvironment = props.environmentLabel
+ ? `${rowAccessibilityLabel}, ${props.environmentLabel}`
+ : rowAccessibilityLabel;
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
const handleAcknowledgeWoke = useCallback(() => {
@@ -1308,7 +1316,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
) : null}
- {(status === "failed" || status === "limited") && thread.runtime?.lastError ? (
+ {(rawStatus === "failed" || rawStatus === "limited") && thread.runtime?.lastError ? (
(