Compare commits

..
Author SHA1 Message Date
t3-code[bot] d93833fd3e fix(desktop): confirm before quitting the app 2026-08-04 21:21:41 +00:00
Theo Browne d7950ac153 fix(server): generate durable thread titles (#5357) 2026-08-04 14:02:33 -07:00
Theo BrowneandClaude Fable 5 36caf34c68 fix(desktop,web): contain renderer memory growth and recover from renderer OOM crashes (#5148)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-04 13:37:03 -07:00
Bilal Bakr 90e3778660 fix(web): stop the chat timeline reading through the provider status banner (#5353) 2026-08-04 15:41:07 -04:00
Rushikesh Gaikwad 94331c58ec fix(mobile): show correct provider icons for Grok, Cursor, and OpenCode (#4586) 2026-08-04 11:04:37 -07:00
Arham AminandClaude Opus 4.8 c30a6d9b99 fix(server): scrub AppImage XDG_DATA_DIRS and GSETTINGS_SCHEMA_DIR from terminals (#5075)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-04 09:35:10 -04:00
Yukun Shan 37ae1abbe9 fix(ssh): isolate managed tunnel processes (#4347) 2026-08-04 09:34:23 -04:00
Arham AminandClaude Opus 4.8 82b76e2138 fix(server): use a Cursor todo's title when its content is blank (#5073)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-04 09:19:12 -04:00
naMqe 8a16cadbaf fix(web): increase tooltip z-index to overlay popovers and menus (#5326) 2026-08-04 09:18:34 -04:00
Julius Marminge 2b1d4fecb8 Upgrade Effect to beta.103 (#5331) 2026-08-04 13:56:50 +02:00
t3-code[bot] cec1bb9de3 fix(web): align multiline error alert controls (#5304) 2026-08-04 13:34:22 +02:00
t3-code[bot] 25ec0b9d13 fix(web): simplify chat code blocks (#5301) 2026-08-04 13:34:10 +02:00
Rodrigo BrechardandRodrigo Brechard 966cc05a90 fix(contracts): decode ServerProviders forward-compatibly (#5327)
Co-authored-by: Rodrigo Brechard <[email protected]>
2026-08-04 13:07:22 +02:00
Wout Stiens 1cbd88aba0 fix(server): strip replayable terminal queries from history (#5319) 2026-08-04 12:52:05 +02:00
Wout Stiens 553867262c fix(terminal): protect held Ctrl/Cmd+W close shortcut (#5322) 2026-08-04 12:51:36 +02:00
Wout StiensandClaude Opus 5 11639bf439 fix(web): blink the terminal cursor again (#5314)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-04 12:50:19 +02:00
t3-code[bot] a261a6440a fix(web): match loading screen to dark theme (#5303) 2026-08-04 00:50:56 +02:00
Mike OlsonandJulius Marminge 6f04a5cffb fix(desktop): Niri/Hyprland - Linux secret storage backend (#2916)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-03 22:02:47 +02:00
maria 30c9622806 fix(web): polish interface spacing (#5252) 2026-08-02 23:35:04 -04:00
Julius Marminge 69dfb7f09a fix(desktop): claim the t3code:// scheme default on Linux at startup (#5054) 2026-08-02 21:53:37 +00:00
Theo Browne e60821f0e0 feat: fold legacy models into separate menus (#5190) 2026-08-02 00:45:05 -07:00
Theo BrowneandClaude 64bf016191 fix(server): stop npx service updates from silently leaving the old server running (#5217)
Co-authored-by: Claude <[email protected]>
2026-08-01 22:42:39 -07:00
Arham AminandClaude Opus 4.8 5192f777fe fix(server): surface cloudflared FTL/PNC relay logs as warnings, not debug (#5076)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-01 16:10:25 -04:00
t3-code[bot] 283c7ac4ba fix: normalize app icon glyph sizing (#5202)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-01 15:21:40 -04:00
Illia Panasenko 78eb3ecae9 fix(web): stop settle controls overlapping the status label (#4574) 2026-08-01 15:06:31 -04:00
Theo Browne d3037064e6 fix(server): make remote updates rollback-safe (#5181) 2026-08-01 05:48:03 -07:00
Theo BrowneandClaude Fable 5 0ad91b6e7f fix(server): follow branch drift in dedicated worktrees so PRs link to their thread (#5159)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 20:18:58 -07:00
Theo BrowneandClaude Fable 5 ca72e381c6 fix(server): bound thread catch-up replay and stop full-DB snapshot hydration (#5147)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 16:14:15 -07:00
Theo Browne 491219bf1f fix: threads with open PRs no longer auto-settle (#5151) 2026-07-31 15:46:15 -07:00
shivamandClaude Fable 5 e5c7547067 feat(web): add settings sidebar search (#4682)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 18:11:27 -04:00
shivamandClaude Fable 5 bfc31507f8 feat(web): search threads from the sidebar (#4769)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 16:52:20 -04:00
shivamandT3 Code Test 03adf215ce follow-up normalization after #4700. (#4498)
Co-authored-by: T3 Code Test <[email protected]>
2026-07-31 16:11:28 -04:00
Alex 916cff733c feat(mobile): make settled threads collapsible (#5056) 2026-07-31 14:55:29 -04:00
Gabriel De Andrade a041981276 feat(mobile): add thread snoozing (#5053) 2026-07-31 10:22:52 -04:00
Wout StiensandClaude Fable 5 964cc27901 refactor: move the canonical libghostty-vt vendor to the repository root (#5102)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 14:20:27 +02:00
Wout StiensandClaude Fable 5 acf761b2f5 feat(web): render terminals with libghostty-vt (#4860)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 13:15:25 +02:00
Julius MarmingeandClaude Fable 5 ab8182cb4e fix(ci): rotate iPad showcase captures without Simulator UI scripting (#5094)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 13:11:56 +02:00
Theo BrowneandClaude Fable 5 ef4ec2ad4b fix(server): self-update no longer rolls itself back on restart (#5095)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 03:46:47 -07:00
Theo BrowneandClaude Fable 5 61514c1294 feat(cli): npx t3 pair - generate QR code from a running server (#4955)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 03:18:55 -07:00
Mike Olson 894d6d68f5 fix(oxlint-plugin): Resolve the oxlint bin without assuming a pnpm layout (#5066) 2026-07-31 11:45:00 +02:00
Alex fccec9f097 fix(ci): capture iPad App Store screenshots in landscape (#5065) 2026-07-31 10:12:23 +02:00
Julius Marminge 50a3d6b872 fix(ci): repair the mobile showcase screenshots workflow (#5057) 2026-07-31 10:11:12 +02:00
Theo BrowneandClaude Fable 5 e259dd23c7 fix(mobile): server model, worktree, and origin preferences now apply to new tasks (#5064)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 21:21:39 -07:00
Julius MarmingeandClaude Fable 5 df78cda8bf fix(contracts): decode growing config unions forward-compatibly (#5055)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 01:11:46 +02:00
Alex 605c2bb734 fix(mobile): show the correct build channel in Android's Threads page header (#4861) 2026-07-30 22:30:46 +00:00
Aditya Vardhan Sharma cb11a71d63 fix(mobile): accept Android clipboard images in composer (#4836) 2026-07-31 00:20:33 +02:00
Simon DobaandClaude Opus 5 41124c7260 fix(desktop): link release notes from the update downloaded toast (#4771)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-07-31 00:19:34 +02:00
Max Anderson b0b275227b chore: add mobile issue template area (#4895) 2026-07-31 00:19:00 +02:00
Alex cb293fe790 fix(mobile): restore iOS Threads branding (#4862) 2026-07-31 00:17:47 +02:00
Simone 1d694dcbd8 fix(mobile): default bare IP pairing to HTTP (#4990) 2026-07-30 22:17:38 +00:00
Arham AminandClaude Opus 4.8 32407df9c5 fix(shared): lenient JSON parser deletes commas inside string values (#5025)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-07-30 22:16:22 +00:00
Elaine Lyons 162e774294 fix(mobile): remove unnecessary photo library permission (#4929) 2026-07-31 00:15:38 +02:00
Arham AminandClaude Opus 4.8 063ed7120a feat(shared): support shorthand (major-only) versions in the semver helpers (#5027)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-07-30 22:13:46 +00:00
Utkarsh Patil 34b15a9ace perf(server): cache default branch name and origin existence across status refreshes (#5008) 2026-07-31 00:08:59 +02:00
Julius MarmingeandClaude Fable 5 fbecb7365e fix(desktop): bump Clerk Electron SDK to 0.0.24 and register t3code:// scheme on Linux (#5015)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 00:06:49 +02:00
Julius MarmingeandClaude Fable 5 4029b858ea fix(ci): drop sparse-checkout from EAS workflows
actions/checkout implements sparse-checkout with --filter=blob:none, so
the runner repo is a partial clone missing the .repos/ blobs. eas-cli
archives the project via `git clone --depth 1 file://<workspace>`,
which upload-pack cannot serve from a partial clone and exits 128
(#4802 broke both EAS build workflows this way).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-30 13:15:03 -07:00
maria 5b2577f6a9 style(web): make scroll-to-end pill translucent (#5036) 2026-07-30 20:08:05 +00:00
Julius MarmingeandClaude Fable 5 bc142f84a2 chore(mobile): bump app version to 1.0.1
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-30 13:07:10 -07:00
343 changed files with 17434 additions and 4580 deletions

No files matched your search

+1 -1
View File
@@ -66,7 +66,7 @@ Use these client origins:
- Android Emulator: `http://10.0.2.2:<server-port>`
- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
Enter the complete `http://` origin to make the test transport explicit. Bare IP addresses default to HTTP, while bare hostnames default to HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
## Start or reuse Metro safely
+1
View File
@@ -30,6 +30,7 @@ body:
- apps/web
- apps/server
- apps/desktop
- apps/mobile
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
@@ -30,6 +30,7 @@ body:
- apps/web
- apps/server
- apps/desktop
- apps/mobile
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
+4 -4
View File
@@ -39,10 +39,10 @@ jobs:
uses: actions/checkout@v6
with:
fetch-depth: 0
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
# No sparse-checkout here: it makes actions/checkout fetch with
# --filter=blob:none, and eas-cli archives the project via
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
# when the partial clone can't serve the unfetched blobs.
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
+4 -4
View File
@@ -57,10 +57,10 @@ jobs:
uses: actions/checkout@v6
with:
fetch-depth: 0
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
# No sparse-checkout here: it makes actions/checkout fetch with
# --filter=blob:none, and eas-cli archives the project via
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
# when the partial clone can't serve the unfetched blobs.
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
@@ -52,6 +52,7 @@ jobs:
args:
- --filter=@t3tools/mobile...
- --filter=@t3tools/scripts...
- --filter=t3...
- name: Expose pnpm
run: |
@@ -100,6 +101,7 @@ jobs:
args:
- --filter=@t3tools/mobile...
- --filter=@t3tools/scripts...
- --filter=t3...
- name: Expose pnpm
run: |
Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 295 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 310 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.3 KiB

+41 -2
View File
@@ -9,6 +9,7 @@ import * as Crypto from "effect/Crypto";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
@@ -17,7 +18,9 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
@@ -220,20 +223,49 @@ const startup = Effect.gen(function* () {
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
const electronApp = yield* ElectronApp.ElectronApp;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
const clerk = yield* DesktopClerk.DesktopClerk;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const updates = yield* DesktopUpdates.DesktopUpdates;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* shellEnvironment.installIntoProcess;
const hasCommandLinePasswordStore =
preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
const linuxElectronOptions =
environment.platform === "linux" && !hasCommandLinePasswordStore
? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess()
: preReadyElectronOptions.linux;
if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
if (
linuxElectronOptions.passwordStore !== null ||
preReadyElectronOptions.linux?.passwordStore !== null
) {
yield* electronApp.removeCommandLineSwitch("password-store");
}
if (linuxElectronOptions.passwordStore !== null) {
yield* electronApp.appendCommandLineSwitch(
"password-store",
linuxElectronOptions.passwordStore,
);
}
}
const userDataPath = yield* appIdentity.resolveUserDataPath;
yield* electronApp.setPath("userData", userDataPath);
yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
yield* desktopSettings.load;
if (environment.platform === "linux") {
yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
if (linuxElectronOptions !== null) {
yield* logStartupInfo("linux password store configured", {
passwordStore: hasCommandLinePasswordStore
? "command-line"
: (linuxElectronOptions.passwordStore ?? "electron-default"),
xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null,
xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null,
});
}
yield* appIdentity.configure;
@@ -245,9 +277,16 @@ const startup = Effect.gen(function* () {
Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
);
yield* logStartupInfo("app ready");
if (environment.platform === "linux") {
const selectedBackend = yield* safeStorage.selectedStorageBackend;
yield* logStartupInfo("safe storage ready", {
backend: Option.getOrElse(selectedBackend, () => "unknown"),
});
}
yield* appIdentity.configure;
yield* applicationMenu.configure;
yield* updates.configure;
yield* linuxUrlHandler.register;
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
}).pipe(Effect.withSpan("desktop.startup"));
@@ -54,7 +54,6 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
calls.setAboutPanelOptions.push(options);
}),
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
@@ -65,6 +64,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
}),
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
+27 -19
View File
@@ -45,6 +45,27 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
: Option.none();
};
export const resolveUserDataPath = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const legacyPath = environment.path.join(
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
export const make = Effect.gen(function* () {
const assets = yield* DesktopAssets.DesktopAssets;
const electronApp = yield* ElectronApp.ElectronApp;
@@ -90,24 +111,11 @@ export const make = Effect.gen(function* () {
return commitHash;
});
const resolveUserDataPath = Effect.gen(function* () {
const legacyPath = environment.path.join(
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
const userDataPath = resolveUserDataPath.pipe(
Effect.provide(
yield* Effect.context<DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem>(),
),
);
const configure = Effect.gen(function* () {
const commitHash = yield* resolveAboutCommitHash;
@@ -136,7 +144,7 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.appIdentity.configure"));
return DesktopAppIdentity.of({
resolveUserDataPath,
resolveUserDataPath: userDataPath,
configure,
});
});
+90 -5
View File
@@ -22,17 +22,38 @@ vi.mock("@clerk/electron/storage", () => ({
storage: storageMock,
}));
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const makeDesktopClerkLayer = (isDevelopment = true) => {
const makeDesktopClerkLayer = (isDevelopment = true, events: string[] = []) => {
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment,
appDataDirectory: "/tmp/app-data",
userDataDirName: isDevelopment ? "t3code-dev" : "t3code",
legacyUserDataDirName: isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)",
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
const electronApp = {
setPath: (name: string, value: string) =>
Effect.sync(() => {
events.push(`setPath:${name}:${value}`);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
return DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
Layer.provide(
Layer.mergeAll(
Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
Layer.succeed(ElectronApp.ElectronApp, electronApp),
FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
),
),
);
};
@@ -55,11 +76,15 @@ describe("DesktopClerk", () => {
it.effect("acquires and releases the SDK bridge with the layer", () => {
const cleanup = vi.fn();
const events: string[] = [];
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup });
createClerkBridgeMock.mockImplementation(() => {
events.push("createClerkBridge");
return { cleanup, isPrimaryInstance: true };
});
return Effect.gen(function* () {
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer(true, events)));
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
@@ -71,6 +96,10 @@ describe("DesktopClerk", () => {
],
]);
assert.equal(cleanup.mock.calls.length, 1);
// The bridge acquires Electron's single-instance lock at creation, and
// the lock both lives in and creates the userData directory — so the
// real path must be set before the bridge exists.
assert.deepEqual(events, ["setPath:userData:/tmp/app-data/t3code-dev", "createClerkBridge"]);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
@@ -124,11 +153,67 @@ describe("DesktopClerk", () => {
});
});
it.effect("registers the second-instance handler in the primary instance", () => {
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
const quit = vi.fn();
const registeredEvents: string[] = [];
const electronApp = {
quit: Effect.sync(quit),
on: (eventName: string) =>
Effect.sync(() => {
registeredEvents.push(eventName);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
return Effect.gen(function* () {
const clerk = yield* DesktopClerk.DesktopClerk;
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
assert.isTrue(Exit.isSuccess(exit));
assert.equal(quit.mock.calls.length, 0);
assert.deepEqual(registeredEvents, ["second-instance"]);
}).pipe(
Effect.provide(makeDesktopClerkLayer()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
);
});
it.effect("quits and interrupts startup in a secondary instance", () => {
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: false });
const quit = vi.fn();
const registeredEvents: string[] = [];
const electronApp = {
quit: Effect.sync(quit),
on: (eventName: string) =>
Effect.sync(() => {
registeredEvents.push(eventName);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
return Effect.gen(function* () {
const clerk = yield* DesktopClerk.DesktopClerk;
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
assert.isTrue(Exit.hasInterrupts(exit));
assert.equal(quit.mock.calls.length, 1);
assert.deepEqual(registeredEvents, []);
}).pipe(
Effect.provide(makeDesktopClerkLayer()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
);
});
it.each([
{ isDevelopment: true, scheme: "t3code-dev" },
{ isDevelopment: false, scheme: "t3code" },
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
const bridge = { cleanup: vi.fn() };
const bridge = { cleanup: vi.fn(), isPrimaryInstance: true };
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue(bridge);
+19 -2
View File
@@ -11,6 +11,7 @@ import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/rela
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
@@ -84,7 +85,18 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.acquireRelease(
const electronApp = yield* ElectronApp.ElectronApp;
// Electron scopes the single-instance lock to the userData directory and
// creates that directory when the lock is acquired. The SDK bridge takes
// the lock at creation, so userData must already point at the real
// directory here — under the default productName-derived path, acquiring
// the lock would create "T3 Code (Alpha)" and make the legacy-install
// detection in resolveUserDataPath match on fresh installs.
const userDataPath = yield* DesktopAppIdentity.resolveUserDataPath;
yield* electronApp.setPath("userData", userDataPath);
const bridge = yield* Effect.acquireRelease(
Effect.try({
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
catch: (cause) =>
@@ -113,7 +125,12 @@ export const make = Effect.gen(function* () {
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
if (!(yield* electronApp.requestSingleInstanceLock)) {
// The SDK bridge holds Electron's single-instance lock (acquired at
// bridge creation) so OAuth deep-link callbacks on Windows/Linux are
// forwarded to the running app. In a secondary instance the bridge has
// already begun quitting the app; app.quit() is asynchronous, so stop
// bootstrap here before whenReady can fire.
if (!bridge.isPrimaryInstance) {
yield* electronApp.quit;
return yield* Effect.interrupt;
}
+1
View File
@@ -35,6 +35,7 @@ const compactEnv = (env: Readonly<Record<string, string | undefined>>): Record<s
export const DesktopConfig = Config.all({
appDataDirectory: trimmedString("APPDATA"),
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
xdgDataHome: trimmedString("XDG_DATA_HOME"),
t3Home: trimmedString("T3CODE_HOME"),
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"),
@@ -39,6 +39,7 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
return decoded.slice("encrypted:".length);
});
},
selectedStorageBackend: Effect.succeed(Option.none()),
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
@@ -0,0 +1,121 @@
// @effect-diagnostics nodeBuiltinImport:off - tests use POSIX path joining to match the Linux startup boundary.
import * as NodePath from "node:path";
import { assert, describe, it } from "@effect/vitest";
import {
resolveEarlyLinuxElectronOptions,
resolveEarlyLinuxPasswordStorePreference,
} from "./DesktopEarlyElectronStartup.ts";
describe("DesktopEarlyElectronStartup", () => {
const joinPath = NodePath.posix.join;
it("reads the persisted linux password-store preference before Electron is ready", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/home/user/.t3-test" },
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
},
});
assert.equal(preference, "kwallet6");
});
it("accepts JSONC in the early desktop settings file", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/home/user/.t3-test" },
homeDirectory: "/home/user",
joinPath,
readFileString: () => `{
// manually edited setting
"linuxPasswordStore": "gnome-libsecret",
}`,
});
assert.equal(preference, "gnome-libsecret");
});
it("falls back to auto when the early settings document is missing or invalid", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {},
homeDirectory: "/home/user",
joinPath,
readFileString: () => {
throw new Error("missing");
},
});
assert.equal(preference, "auto");
});
it("preserves absolute root paths when resolving early settings", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/" },
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
},
});
assert.equal(preference, "kwallet6");
});
it("resolves the early linux Electron switches", () => {
const options = resolveEarlyLinuxElectronOptions({
env: {
T3CODE_HOME: "/home/user/.t3-test",
XDG_CURRENT_DESKTOP: "niri",
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "auto" });
},
});
assert.deepEqual(options, {
linuxWmClass: "t3code-dev",
passwordStore: "gnome-libsecret",
});
});
it("keeps implicit development state under ~/.t3/dev when T3CODE_HOME is unset", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet" });
},
});
assert.equal(preference, "kwallet");
});
it("treats whitespace-only T3CODE_HOME as unconfigured in development", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {
T3CODE_HOME: " ",
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "gnome-libsecret" });
},
});
assert.equal(preference, "gnome-libsecret");
});
});
@@ -0,0 +1,90 @@
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
DEFAULT_LINUX_PASSWORD_STORE,
normalizeLinuxPasswordStorePreference,
resolveLinuxPasswordStoreSwitch,
type LinuxPasswordStoreSwitch,
type LinuxPasswordStorePreference,
} from "../linuxSecretStorage.ts";
import {
resolveDesktopBaseDir,
resolveDesktopStateDir,
type JoinPath,
} from "./DesktopStatePaths.ts";
interface EarlyDesktopSettingsInput {
readonly env: NodeJS.ProcessEnv;
readonly homeDirectory: string;
readonly joinPath: JoinPath;
readonly readFileString: (path: string) => string;
}
type EarlyLinuxElectronOptionsInput = EarlyDesktopSettingsInput;
export interface EarlyLinuxElectronOptions {
readonly linuxWmClass: string;
readonly passwordStore: LinuxPasswordStoreSwitch | null;
}
const trimNonEmpty = (value: string | undefined): string | null => {
const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? trimmed : null;
};
const EarlyDesktopSettingsJson = fromLenientJson(
Schema.Struct({
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
}),
);
const decodeEarlyDesktopSettingsJson = Schema.decodeSync(EarlyDesktopSettingsJson);
const isDevelopmentEnvironment = (env: NodeJS.ProcessEnv): boolean =>
trimNonEmpty(env.VITE_DEV_SERVER_URL) !== null;
function resolveEarlyDesktopSettingsPath(input: {
readonly env: NodeJS.ProcessEnv;
readonly homeDirectory: string;
readonly joinPath: JoinPath;
}): string {
const t3Home = Option.fromUndefinedOr(input.env.T3CODE_HOME);
const baseDir = resolveDesktopBaseDir({
homeDirectory: input.homeDirectory,
joinPath: input.joinPath,
t3Home,
});
const stateDir = resolveDesktopStateDir({
baseDir,
isDevelopment: isDevelopmentEnvironment(input.env),
joinPath: input.joinPath,
t3Home,
});
return input.joinPath(stateDir, "desktop-settings.json");
}
export function resolveEarlyLinuxPasswordStorePreference(
input: EarlyDesktopSettingsInput,
): LinuxPasswordStorePreference {
const settingsPath = resolveEarlyDesktopSettingsPath(input);
try {
const parsed = decodeEarlyDesktopSettingsJson(input.readFileString(settingsPath));
return normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore);
} catch {
return DEFAULT_LINUX_PASSWORD_STORE;
}
}
export function resolveEarlyLinuxElectronOptions(
input: EarlyLinuxElectronOptionsInput,
): EarlyLinuxElectronOptions {
const preference = resolveEarlyLinuxPasswordStorePreference(input);
return {
linuxWmClass: isDevelopmentEnvironment(input.env) ? "t3code-dev" : "t3code",
passwordStore: resolveLinuxPasswordStoreSwitch({
preference,
env: input.env,
}),
};
}
+19 -5
View File
@@ -13,6 +13,7 @@ import * as Path from "effect/Path";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
export interface MakeDesktopEnvironmentInput {
@@ -66,6 +67,8 @@ export class DesktopEnvironment extends Context.Service<
readonly appUserModelId: string;
readonly linuxDesktopEntryName: string;
readonly linuxWmClass: string;
readonly linuxApplicationsDir: string;
readonly appImagePath: Option.Option<string>;
readonly userDataDirName: string;
readonly legacyUserDataDirName: string;
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
@@ -147,8 +150,11 @@ const make = Effect.fn("desktop.environment.make")(function* (
: input.platform === "darwin"
? path.join(homeDirectory, "Library", "Application Support")
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
const configuredBaseDir = config.t3Home;
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
const baseDir = resolveDesktopBaseDir({
homeDirectory,
joinPath: path.join,
t3Home: config.t3Home,
});
const rootDir = path.resolve(input.dirname, "../../..");
const appRoot = input.isPackaged ? input.appPath : rootDir;
const branding = resolveDesktopAppBranding({
@@ -156,12 +162,18 @@ const make = Effect.fn("desktop.environment.make")(function* (
appVersion: input.appVersion,
});
const displayName = branding.displayName;
const stateDir = path.join(
const stateDir = resolveDesktopStateDir({
baseDir,
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
);
isDevelopment,
joinPath: path.join,
t3Home: config.t3Home,
});
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const linuxApplicationsDir = path.join(
Option.getOrElse(config.xdgDataHome, () => path.join(homeDirectory, ".local", "share")),
"applications",
);
const resourcesPath = input.resourcesPath;
return DesktopEnvironment.of({
@@ -205,6 +217,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
),
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
linuxApplicationsDir,
appImagePath: config.appImagePath,
userDataDirName,
legacyUserDataDirName,
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
@@ -29,13 +29,13 @@ describe("DesktopLifecycle", () => {
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: (listener) =>
Effect.acquireRelease(
Effect.sync(() => {
@@ -0,0 +1,229 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
interface RecordedRegistration {
readonly directories: string[];
readonly files: Array<{ readonly path: string; readonly content: string }>;
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
}
const makeEnvironment = (overrides: Record<string, unknown> = {}) =>
DesktopEnvironment.DesktopEnvironment.of({
platform: "linux",
isPackaged: true,
isDevelopment: false,
displayName: "T3 Code (Alpha)",
linuxWmClass: "t3code",
linuxApplicationsDir: "/home/alice/.local/share/applications",
appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
...overrides,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
const mockProcess = (exitCode: number) =>
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
const makeHandlerLayer = (
recorded: RecordedRegistration,
input: {
readonly environment?: Record<string, unknown>;
readonly xdgMimeExitCode?: number;
readonly writeError?: PlatformError.PlatformError;
} = {},
) =>
DesktopLinuxUrlHandler.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(DesktopEnvironment.DesktopEnvironment, makeEnvironment(input.environment)),
FileSystem.layerNoop({
makeDirectory: (path) =>
Effect.sync(() => {
recorded.directories.push(path);
}),
writeFileString: (path, content) =>
input.writeError
? Effect.fail(input.writeError)
: Effect.sync(() => {
recorded.files.push({ path, content });
}),
}),
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
recorded.commands.push({
command: childProcess.command,
args: childProcess.args,
});
return Effect.succeed(mockProcess(input.xdgMimeExitCode ?? 0));
}),
),
),
),
);
const runRegister = (
recorded: RecordedRegistration,
input: Parameters<typeof makeHandlerLayer>[1] = {},
) =>
Effect.gen(function* () {
const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
yield* handler.register;
}).pipe(Effect.provide(makeHandlerLayer(recorded, input)));
const emptyRecording = (): RecordedRegistration => ({
directories: [],
files: [],
commands: [],
});
describe("DesktopLinuxUrlHandler", () => {
it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
displayName: "T3 Code (Nightly)",
execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
scheme: "t3code",
});
assert.include(entry, "[Desktop Entry]");
assert.include(entry, "Name=T3 Code (Nightly)");
// Exec composes both escaping layers: a literal backslash becomes four
// backslashes in the file, a quote three characters, a dollar sign two
// backslashes plus the sign.
assert.include(
entry,
'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
);
assert.include(entry, "NoDisplay=true");
assert.notInclude(entry, "StartupWMClass=");
assert.include(entry, "MimeType=x-scheme-handler/t3code;");
});
it("carries structured context on registration errors", () => {
const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
step: "write-desktop-entry",
scheme: "t3code",
desktopEntryPath: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
cause: new Error("boom"),
});
assert.equal(
writeError.message,
"Failed to register the t3code:// URL handler (step: write-desktop-entry).",
);
assert.equal(
writeError.desktopEntryPath,
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
);
const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme: "t3code",
exitCode: 4,
});
assert.equal(
exitError.message,
"Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).",
);
});
it.effect("writes the handler entry and claims the scheme default via xdg-mime", () => {
const recorded = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(recorded);
assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
assert.equal(recorded.files.length, 1);
assert.equal(
recorded.files[0]?.path,
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
);
assert.include(
recorded.files[0]?.content,
'Exec="/home/alice/Applications/T3-Code.AppImage" %U',
);
assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
assert.deepEqual(recorded.commands, [
{
command: "xdg-mime",
args: ["default", "t3code-url-handler.desktop", "x-scheme-handler/t3code"],
},
]);
});
});
it.effect("falls back to the process executable outside an AppImage", () => {
const recorded = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
assert.include(
recorded.files[0]?.content,
`Exec=${DesktopLinuxUrlHandler.escapeDesktopEntryExecArgument(process.execPath)} %U`,
);
});
});
it.effect("does nothing on other platforms or unpackaged builds", () => {
const nonLinux = emptyRecording();
const unpackaged = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
yield* runRegister(unpackaged, { environment: { isPackaged: false } });
for (const recorded of [nonLinux, unpackaged]) {
assert.deepEqual(recorded.directories, []);
assert.deepEqual(recorded.files, []);
assert.deepEqual(recorded.commands, []);
}
});
});
it.effect("never fails startup when registration cannot complete", () => {
const xdgMimeFailed = emptyRecording();
const writeFailed = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
yield* runRegister(writeFailed, {
writeError: PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFileString",
description: "read-only filesystem",
pathOrDescriptor: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
}),
});
assert.equal(xdgMimeFailed.files.length, 1);
assert.deepEqual(writeFailed.commands, []);
});
});
});
@@ -0,0 +1,191 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import { makeComponentLogger } from "./DesktopObservability.ts";
// Linux ships as an AppImage, so the .desktop entry users end up with is
// created by whatever integration tool they use (AppImageLauncher names it
// appimagekit_<hash>-….desktop) and its filename is not under our control.
// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
// setDesktopName, which cannot match those files — so the browser keeps
// prompting "Choose an application" for every OAuth callback. Instead, write
// our own handler entry pointing at the current AppImage and claim the
// scheme default via xdg-mime, exactly what the file manager's "set as
// default" checkbox would record in mimeapps.list.
export const URL_HANDLER_DESKTOP_ENTRY_NAME = "t3code-url-handler.desktop";
const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedErrorClass<DesktopLinuxUrlHandlerRegistrationError>()(
"DesktopLinuxUrlHandlerRegistrationError",
{
step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
scheme: Schema.String,
desktopEntryPath: Schema.optionalKey(Schema.String),
exitCode: Schema.optionalKey(Schema.Number),
cause: Schema.optionalKey(Schema.Defect()),
},
) {
override get message(): string {
const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
}
}
const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
const escapeDesktopEntryString = (value: string): string =>
value
.replaceAll("\\", "\\\\")
.replaceAll("\n", "\\n")
.replaceAll("\r", "\\r")
.replaceAll("\t", "\\t");
// Exec values are unescaped twice by implementations: first the general
// string-value rules, then the Exec quoting rules — so writing composes the
// layers in reverse. The argument is double-quoted with reserved characters
// backslash-escaped and literal percent signs doubled (field codes), and the
// general string escaping is applied on top: a literal backslash ends up as
// four backslashes in the file, a quote as \\", a dollar sign as \\$.
export function escapeDesktopEntryExecArgument(value: string): string {
const quoted = value
.replaceAll("\\", () => "\\\\")
.replaceAll("`", () => "\\`")
.replaceAll("$", () => "\\$")
.replaceAll('"', () => '\\"')
.replaceAll("%", () => "%%");
return escapeDesktopEntryString(`"${quoted}"`);
}
// The AppImage integration entry owns the window identity and icon. This
// hidden URL-only entry must not compete with it for StartupWMClass matching.
export function renderUrlHandlerDesktopEntry(input: {
readonly displayName: string;
readonly execTarget: string;
readonly scheme: string;
}): string {
return [
"[Desktop Entry]",
"Type=Application",
`Name=${escapeDesktopEntryString(input.displayName)}`,
`Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
"Terminal=false",
"NoDisplay=true",
"StartupNotify=false",
`MimeType=x-scheme-handler/${input.scheme};`,
"",
].join("\n");
}
export class DesktopLinuxUrlHandler extends Context.Service<
DesktopLinuxUrlHandler,
{
readonly register: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
const desktopEntryPath = environment.path.join(
environment.linuxApplicationsDir,
URL_HANDLER_DESKTOP_ENTRY_NAME,
);
const writeDesktopEntry = Effect.gen(function* () {
// Inside the mounted AppImage, process.execPath points at a transient
// /tmp/.mount_* path — the handler must launch the AppImage itself.
const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
yield* fileSystem.writeFileString(
desktopEntryPath,
renderUrlHandlerDesktopEntry({
displayName: environment.displayName,
execTarget,
scheme,
}),
);
}).pipe(
Effect.mapError(
(cause) =>
new DesktopLinuxUrlHandlerRegistrationError({
step: "write-desktop-entry",
scheme,
desktopEntryPath,
cause,
}),
),
);
const setDefaultHandler = Effect.scoped(
Effect.gen(function* () {
const command = ChildProcess.make(
"xdg-mime",
["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
{
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
);
const handle = yield* spawner.spawn(command);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) {
return yield* new DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme,
exitCode: Number(exitCode),
});
}
}),
).pipe(
Effect.mapError((error) =>
isRegistrationError(error)
? error
: new DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme,
cause: error,
}),
),
);
const register = Effect.gen(function* () {
if (environment.platform !== "linux" || !environment.isPackaged) {
return;
}
yield* writeDesktopEntry;
yield* setDefaultHandler;
yield* logInfo("registered URL scheme handler", { scheme });
}).pipe(
// Registration is best-effort: a missing xdg-mime or read-only home must
// never block startup — the OS chooser remains as fallback.
Effect.catch((error) =>
logWarning("URL scheme handler registration failed", {
scheme,
step: error.step,
message: error.message,
...(error.desktopEntryPath === undefined
? {}
: { desktopEntryPath: error.desktopEntryPath }),
...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
}),
),
Effect.withSpan("desktop.linuxUrlHandler.register"),
);
return DesktopLinuxUrlHandler.of({ register });
});
export const layer = Layer.effect(DesktopLinuxUrlHandler, make);
@@ -0,0 +1,130 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
const { appendSwitchMock, getSwitchValueMock, hasSwitchMock, registerSchemesMock } = vi.hoisted(
() => ({
appendSwitchMock: vi.fn(),
getSwitchValueMock: vi.fn(),
hasSwitchMock: vi.fn(),
registerSchemesMock: vi.fn(),
}),
);
vi.mock("electron", () => ({
app: {
commandLine: {
appendSwitch: appendSwitchMock,
getSwitchValue: getSwitchValueMock,
hasSwitch: hasSwitchMock,
},
},
protocol: {
registerSchemesAsPrivileged: registerSchemesMock,
},
}));
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
describe("DesktopPreReadyPlatform", () => {
beforeEach(() => {
appendSwitchMock.mockReset();
getSwitchValueMock.mockReset();
hasSwitchMock.mockReset();
registerSchemesMock.mockReset();
});
it("reads an explicit Electron command-line switch value", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: (switchName) => switchName === "password-store",
getSwitchValue: (switchName) => {
assert.equal(switchName, "password-store");
return "basic";
},
},
"password-store",
);
assert.equal(value, "basic");
});
it("treats valueless Electron command-line switches as absent", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: () => true,
getSwitchValue: () => "",
},
"password-store",
);
assert.isNull(value);
});
it("returns null for missing Electron command-line switches", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: () => false,
getSwitchValue: () => {
throw new Error("Unexpected switch value read.");
},
},
"password-store",
);
assert.isNull(value);
});
it.effect(
"acquires a synchronous pre-ready layer before an asynchronous Clerk-shaped layer",
() =>
Effect.gen(function* () {
class ClerkShaped extends Context.Service<ClerkShaped, { readonly ready: true }>()(
"@t3tools/desktop/app/DesktopPreReadyPlatform.test/ClerkShaped",
) {}
const events: Array<string> = [];
registerSchemesMock.mockImplementation(() => {
events.push("pre-ready");
});
const preReadyLayer = DesktopPreReadyPlatform.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "darwin")),
);
const clerkShapedLayer = Layer.effect(
ClerkShaped,
Effect.promise(() => Promise.resolve()).pipe(
Effect.map(() => {
events.push("clerk");
return { ready: true as const };
}),
),
);
const runtimeLayer = clerkShapedLayer.pipe(
Layer.flatMap((clerkContext) => Layer.succeedContext(clerkContext)),
Layer.provideMerge(preReadyLayer),
);
const result = yield* Effect.all({
clerk: ClerkShaped,
preReady: DesktopPreReadyPlatform.DesktopPreReadyElectronOptions,
}).pipe(Effect.provide(runtimeLayer));
assert.deepEqual(result, {
clerk: { ready: true },
preReady: {
linux: null,
linuxPasswordStoreCommandLine: null,
},
});
assert.deepEqual(events, ["pre-ready", "clerk"]);
assert.equal(registerSchemesMock.mock.calls.length, 1);
assert.equal(appendSwitchMock.mock.calls.length, 0);
}),
);
});
@@ -0,0 +1,74 @@
// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads persisted settings synchronously before app services are available.
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
export interface DesktopPreReadyCommandLineReader {
readonly hasSwitch: (switchName: string) => boolean;
readonly getSwitchValue: (switchName: string) => string;
}
export function readCommandLineSwitchValue(
commandLine: DesktopPreReadyCommandLineReader,
switchName: string,
): string | null {
if (!commandLine.hasSwitch(switchName)) {
return null;
}
const value = commandLine.getSwitchValue(switchName).trim();
return value.length > 0 ? value : null;
}
export const resolveEarlyLinuxElectronOptionsFromProcess =
(): DesktopEarlyElectronStartup.EarlyLinuxElectronOptions =>
DesktopEarlyElectronStartup.resolveEarlyLinuxElectronOptions({
env: process.env,
homeDirectory: NodeOS.homedir(),
joinPath: NodePath.posix.join,
readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
});
export class DesktopPreReadyElectronOptions extends Context.Service<
DesktopPreReadyElectronOptions,
{
readonly linux: DesktopEarlyElectronStartup.EarlyLinuxElectronOptions | null;
readonly linuxPasswordStoreCommandLine: string | null;
}
>()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {}
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
const linuxPasswordStoreCommandLine =
platform === "linux"
? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
: null;
const linux = platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess() : null;
if (linux !== null) {
Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass);
if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
}
}
return { linux, linuxPasswordStoreCommandLine };
});
}).pipe(Effect.withSpan("desktop.electron.configureBeforeReady"));
// Keep Electron's strict pre-ready setup isolated so later runtime layers cannot
// observe app readiness before scheme privileges and command-line switches exist.
export const layer = Layer.mergeAll(
ElectronProtocol.layerSchemePrivileges,
Layer.effect(DesktopPreReadyElectronOptions, make),
);
+32
View File
@@ -0,0 +1,32 @@
import * as Option from "effect/Option";
export type JoinPath = (first: string, ...segments: string[]) => string;
function normalizeConfiguredBaseDir(t3Home: Option.Option<string>): Option.Option<string> {
if (Option.isNone(t3Home)) {
return Option.none();
}
const trimmed = t3Home.value.trim();
return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
}
export function resolveDesktopBaseDir(input: {
readonly homeDirectory: string;
readonly joinPath: JoinPath;
readonly t3Home: Option.Option<string>;
}): string {
return Option.getOrElse(normalizeConfiguredBaseDir(input.t3Home), () =>
input.joinPath(input.homeDirectory, ".t3"),
);
}
export function resolveDesktopStateDir(input: {
readonly baseDir: string;
readonly isDevelopment: boolean;
readonly joinPath: JoinPath;
readonly t3Home: Option.Option<string>;
}): string {
const useDevSubdir =
input.isDevelopment && Option.isNone(normalizeConfiguredBaseDir(input.t3Home));
return input.joinPath(input.baseDir, useDevSubdir ? "dev" : "userdata");
}
+13 -3
View File
@@ -14,7 +14,7 @@ const {
quitMock,
relaunchMock,
removeListenerMock,
requestSingleInstanceLockMock,
removeSwitchMock,
setAboutPanelOptionsMock,
setAppUserModelIdMock,
setAsDefaultProtocolClientMock,
@@ -35,7 +35,7 @@ const {
quitMock: vi.fn(),
relaunchMock: vi.fn(),
removeListenerMock: vi.fn(),
requestSingleInstanceLockMock: vi.fn(() => true),
removeSwitchMock: vi.fn(),
setAboutPanelOptionsMock: vi.fn(),
setAppUserModelIdMock: vi.fn(),
setAsDefaultProtocolClientMock: vi.fn(() => true),
@@ -54,6 +54,7 @@ vi.mock("electron", () => ({
app: {
commandLine: {
appendSwitch: appendSwitchMock,
removeSwitch: removeSwitchMock,
},
dock: {
setIcon: setDockIconMock,
@@ -67,7 +68,6 @@ vi.mock("electron", () => ({
quit: quitMock,
relaunch: relaunchMock,
removeListener: removeListenerMock,
requestSingleInstanceLock: requestSingleInstanceLockMock,
runningUnderARM64Translation: false,
setAboutPanelOptions: setAboutPanelOptionsMock,
setAsDefaultProtocolClient: setAsDefaultProtocolClientMock,
@@ -92,6 +92,7 @@ describe("ElectronApp", () => {
quitMock.mockClear();
relaunchMock.mockClear();
removeListenerMock.mockClear();
removeSwitchMock.mockClear();
setPathMock.mockClear();
});
@@ -181,4 +182,13 @@ describe("ElectronApp", () => {
]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("removes command-line switches through the service", () =>
Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
yield* electronApp.removeCommandLineSwitch("password-store");
assert.deepEqual(removeSwitchMock.mock.calls, [["password-store"]]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
});
+5 -2
View File
@@ -56,7 +56,6 @@ export class ElectronApp extends Context.Service<
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
@@ -70,6 +69,7 @@ export class ElectronApp extends Context.Service<
readonly onBeforeQuitForUpdate: (
listener: () => void,
) => Effect.Effect<void, never, Scope.Scope>;
readonly removeCommandLineSwitch: (switchName: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
@@ -153,7 +153,6 @@ export const make = ElectronApp.of({
Effect.sync(() => {
Electron.app.setAppUserModelId(id);
}),
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
isDefaultProtocolClient: (protocol) =>
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
@@ -193,6 +192,10 @@ export const make = ElectronApp.of({
Electron.autoUpdater.removeListener("before-quit-for-update", listener);
}),
).pipe(Effect.asVoid),
removeCommandLineSwitch: (switchName) =>
Effect.sync(() => {
Electron.app.commandLine.removeSwitch(switchName);
}),
on: addScopedAppListener,
});
@@ -57,7 +57,7 @@ describe("ElectronProtocol", () => {
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
@@ -212,6 +212,7 @@ describe("ElectronProtocol", () => {
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"'wasm-unsafe-eval'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
@@ -71,6 +71,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
const scriptSources = [
"'self'",
"'unsafe-inline'",
"'wasm-unsafe-eval'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
];
@@ -104,6 +105,38 @@ function withContentSecurityPolicy(response: Response, policy: string): Response
});
}
/**
* Must run synchronously during process bootstrap, before Electron emits `ready`.
*/
export function registerDesktopSchemePrivilegesSync(): void {
Electron.protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_PRODUCTION_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
{
scheme: DESKTOP_DEVELOPMENT_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
}
const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
);
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
async function proxyRequest(
request: Request,
targetOrigin: URL,
@@ -1,9 +1,11 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
const electronSafeStorageErrorFields = {
cause: Schema.Defect(),
@@ -60,24 +62,39 @@ export class ElectronSafeStorage extends Context.Service<
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
readonly selectedStorageBackend: Effect.Effect<Option.Option<string>>;
}
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
export const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
}),
encryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.encryptString(value),
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
}),
decryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
encryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.encryptString(value),
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
}),
decryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
}),
selectedStorageBackend: Effect.sync(() => {
if (platform !== "linux") {
return Option.none();
}
try {
return Option.fromNullishOr(Electron.safeStorage.getSelectedStorageBackend());
} catch {
return Option.none();
}
}),
});
});
export const layer = Layer.succeed(ElectronSafeStorage, make);
export const layer = Layer.effect(ElectronSafeStorage, make);
+203
View File
@@ -0,0 +1,203 @@
import { describe, expect, it } from "vite-plus/test";
import {
normalizeLinuxPasswordStorePreference,
resolveLinuxPasswordStoreSwitch,
resolveLinuxSecretStorageUnavailableMessage,
} from "./linuxSecretStorage.ts";
const autoSwitch = (env: NodeJS.ProcessEnv) =>
resolveLinuxPasswordStoreSwitch({ preference: "auto", env });
describe("linuxSecretStorage", () => {
it("preserves explicit supported password-store preferences", () => {
expect(normalizeLinuxPasswordStorePreference("gnome-libsecret")).toBe("gnome-libsecret");
expect(normalizeLinuxPasswordStorePreference("kwallet")).toBe("kwallet");
expect(normalizeLinuxPasswordStorePreference("kwallet5")).toBe("kwallet5");
expect(normalizeLinuxPasswordStorePreference("kwallet6")).toBe("kwallet6");
});
it("falls back to auto for missing or unsupported preferences", () => {
expect(normalizeLinuxPasswordStorePreference(undefined)).toBe("auto");
expect(normalizeLinuxPasswordStorePreference("basic")).toBe("auto");
});
it("uses explicit preferences instead of the auto heuristic", () => {
for (const preference of ["gnome-libsecret", "kwallet", "kwallet5", "kwallet6"] as const) {
expect(
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "niri" } }),
).toBe(preference);
// An explicit preference also wins where auto would have stayed out of the way.
expect(
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "KDE" } }),
).toBe(preference);
}
});
it("leaves canonical KDE sessions to Electron's own wallet selection", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "5" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE:plasma" })).toBeNull();
});
it("does not force a password-store for desktops Electron already recognizes", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "GNOME" })).toBeNull();
for (const desktop of ["Deepin", "Pantheon", "UKUI", "Unity", "X-Cinnamon", "XFCE"]) {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: desktop })).toBeNull();
}
});
it("recognizes a known desktop later in a colon-separated XDG_CURRENT_DESKTOP list", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:GNOME" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBeNull();
});
it("forces gnome-libsecret for unrecognized Linux desktop sessions", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "Hyprland" })).toBe("gnome-libsecret");
expect(autoSwitch({})).toBe("gnome-libsecret");
});
it("forces gnome-libsecret for desktops Electron recognizes but leaves on basic text", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt" })).toBe("gnome-libsecret");
// Chromium stops at the first recognized value, so a later name cannot rescue the session.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:GNOME" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:KDE" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:plasma" })).toBe("gnome-libsecret");
});
it("does not treat lowercase desktop names as ones Electron recognizes", () => {
// Chromium matches these case-sensitively, so lowercase spellings reach basic text.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "gnome" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "xfce" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "kde", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
});
it("overrides KDE sessions identified only by legacy variables", () => {
// Chromium reaches KWallet4 for some of these, such as DESKTOP_SESSION=kde with a version, and
// basic text for the rest. Either way these are the variables a previous session leaves behind,
// so they are treated as unproven and forced to a real keyring rather than a guessed wallet.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "plasma" })).toBe("gnome-libsecret");
for (const session of [
"kde",
"kde-plasma",
"kde4",
"plasma",
"plasmawayland",
"plasmawayland-dev",
"plasmax11",
"plasmax11-dev",
]) {
expect(autoSwitch({ DESKTOP_SESSION: session })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_SESSION_DESKTOP: session })).toBe("gnome-libsecret");
expect(autoSwitch({ GDMSESSION: session })).toBe("gnome-libsecret");
}
expect(autoSwitch({ DESKTOP_SESSION: "kde", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ KDE_SESSION_VERSION: "6" })).toBe("gnome-libsecret");
expect(autoSwitch({ KDE_FULL_SESSION: "true", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
});
it("ignores stale session hints when XDG_CURRENT_DESKTOP is authoritative", () => {
expect(
autoSwitch({ XDG_CURRENT_DESKTOP: "niri", DESKTOP_SESSION: "gnome", GDMSESSION: "gnome" }),
).toBe("gnome-libsecret");
// A previous KDE session left these behind; the compositor running now is not KDE.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", XDG_SESSION_DESKTOP: "GNOME" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:plasma" })).toBe("gnome-libsecret");
expect(
autoSwitch({
XDG_CURRENT_DESKTOP: "Hyprland",
XDG_SESSION_DESKTOP: "KDE",
KDE_SESSION_VERSION: "6",
}),
).toBe("gnome-libsecret");
});
it("uses GNOME Keyring remediation for libsecret and unknown backends", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "niri" },
}),
).toContain("GNOME Keyring");
});
it("prefers explicit libsecret selection over KDE desktop heuristics", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "gnome-libsecret",
selectedBackend: "unknown",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("GNOME Keyring");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("GNOME Keyring");
});
it("prefers explicit KWallet preference over selected gnome-libsecret backend", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "kwallet6",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "niri" },
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "kwallet",
selectedBackend: "gnome-libsecret",
env: {},
}),
).toContain("KWallet");
});
it("uses KWallet remediation wording for KDE-looking sessions", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "kwallet6",
env: {},
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { DESKTOP_SESSION: "plasmawayland" },
}),
).toContain("KWallet");
// A desktop name outranks a bare KDE marker when choosing the wording.
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { GDMSESSION: "gnome", KDE_FULL_SESSION: "true" },
}),
).toContain("GNOME Keyring");
});
});
+178
View File
@@ -0,0 +1,178 @@
export type LinuxPasswordStorePreference =
| "auto"
| "gnome-libsecret"
| "kwallet"
| "kwallet5"
| "kwallet6";
export type LinuxPasswordStoreSwitch = Exclude<LinuxPasswordStorePreference, "auto">;
export const DEFAULT_LINUX_PASSWORD_STORE: LinuxPasswordStorePreference = "auto";
// Chromium matches XDG_CURRENT_DESKTOP values case-sensitively and returns on the first value it
// recognizes, so these stay exact literals and are scanned in order. Omitting a real desktop fails
// safe: we force gnome-libsecret, which is the backend Chromium selects for all of these anyway.
const ELECTRON_LIBSECRET_DESKTOPS = new Set([
"Deepin",
"GNOME",
"Pantheon",
"UKUI",
"Unity",
"X-Cinnamon",
"XFCE",
]);
// Chromium selects a KWallet generation for KDE from KDE_SESSION_VERSION, so it needs no help.
const ELECTRON_KDE_DESKTOP = "KDE";
// Chromium recognizes LXQt and still selects basic text for it, so it does need a forced backend.
const ELECTRON_UNPROTECTED_DESKTOPS = new Set(["LXQt"]);
const KDE_NAME_PREFIXES = ["kde", "plasma"];
const NEGATIVE_FLAG_VALUES = new Set(["0", "false", "no", "off"]);
export function normalizeLinuxPasswordStorePreference(
value: unknown,
): LinuxPasswordStorePreference {
return value === "gnome-libsecret" ||
value === "kwallet" ||
value === "kwallet5" ||
value === "kwallet6"
? value
: DEFAULT_LINUX_PASSWORD_STORE;
}
// Auto mode asks one question: will Electron select a real keyring on its own? If so, stay out of
// the way, which is how canonical KDE sessions keep the KWallet generation Chromium picks for them.
// Otherwise force gnome-libsecret, because the alternative is basic text, which is barely
// encryption at all. Forcing never guesses a KWallet generation; a KDE session that needs a
// specific one sets linuxPasswordStore explicitly.
export function resolveLinuxPasswordStoreSwitch(input: {
readonly preference: LinuxPasswordStorePreference;
readonly env: NodeJS.ProcessEnv;
}): LinuxPasswordStoreSwitch | null {
if (input.preference !== "auto") {
return input.preference;
}
return electronSelectsProtectedBackend(input.env) ? null : "gnome-libsecret";
}
// Only an exact XDG_CURRENT_DESKTOP literal proves Electron will protect the session. Chromium can
// also reach a real backend through DESKTOP_SESSION and the legacy KDE markers, but those are the
// variables a previous session leaves behind, and trusting them is what let stale hints suppress
// the forced backend before. Forcing where Chromium would have chosen libsecret is harmless, since
// it lands on the same backend.
function electronSelectsProtectedBackend(env: NodeJS.ProcessEnv): boolean {
for (const name of splitDesktopNameList(env.XDG_CURRENT_DESKTOP)) {
const trimmed = name.trim();
if (trimmed.length === 0) {
continue;
}
if (trimmed === ELECTRON_KDE_DESKTOP || ELECTRON_LIBSECRET_DESKTOPS.has(trimmed)) {
return true;
}
if (ELECTRON_UNPROTECTED_DESKTOPS.has(trimmed)) {
return false;
}
}
return false;
}
export function resolveLinuxSecretStorageUnavailableMessage(input: {
readonly configuredPreference: LinuxPasswordStorePreference;
readonly selectedBackend: string | null;
readonly env: NodeJS.ProcessEnv;
}): string {
if (input.configuredPreference === "gnome-libsecret") {
return getGnomeKeyringRemediationMessage();
}
if (
input.configuredPreference === "kwallet" ||
input.configuredPreference === "kwallet5" ||
input.configuredPreference === "kwallet6"
) {
return getKWalletRemediationMessage();
}
const backend = normalizeSelectedStorageBackend(input.selectedBackend);
if (backend === "gnome-libsecret") {
return getGnomeKeyringRemediationMessage();
}
if (
backend === "kwallet" ||
backend === "kwallet5" ||
backend === "kwallet6" ||
looksLikeKdeSession(input.env)
) {
return getKWalletRemediationMessage();
}
return getGnomeKeyringRemediationMessage();
}
function getGnomeKeyringRemediationMessage(): string {
return "T3 Code could not access GNOME Keyring to save this environment credential. Install and start GNOME Keyring, then restart T3 Code.";
}
function getKWalletRemediationMessage(): string {
return "T3 Code could not access KWallet to save this environment credential. Enable the KDE wallet subsystem in System Settings, then restart T3 Code.";
}
// Advisory only: this picks between the GNOME Keyring and KWallet wording in the failure notice. It
// never decides which backend to select, so a loose match costs a user slightly wrong instructions
// rather than an unprotected credential store.
function looksLikeKdeSession(env: NodeJS.ProcessEnv): boolean {
const currentDesktopNames = nonEmptyDesktopNames(env.XDG_CURRENT_DESKTOP);
if (currentDesktopNames.length > 0) {
return currentDesktopNames.some(isKdeDesktopName);
}
const legacyNames = legacyDesktopNames(env);
if (legacyNames.length > 0) {
return legacyNames.some(isKdeDesktopName);
}
return isSet(env.KDE_SESSION_VERSION) || isAffirmativeFlag(env.KDE_FULL_SESSION);
}
function isKdeDesktopName(name: string): boolean {
return KDE_NAME_PREFIXES.some((prefix) => name.startsWith(prefix));
}
function legacyDesktopNames(env: NodeJS.ProcessEnv): string[] {
return [env.XDG_SESSION_DESKTOP, env.DESKTOP_SESSION, env.GDMSESSION].flatMap((entry) => {
const normalized = normalizeDesktopName(entry);
return normalized ? [normalized] : [];
});
}
function nonEmptyDesktopNames(value: string | undefined): string[] {
return splitDesktopNameList(value).flatMap((entry) => {
const normalized = normalizeDesktopName(entry);
return normalized ? [normalized] : [];
});
}
function isSet(value: string | undefined): boolean {
return Boolean(value?.trim());
}
function isAffirmativeFlag(value: string | undefined): boolean {
const normalized = value?.trim().toLowerCase();
return normalized ? !NEGATIVE_FLAG_VALUES.has(normalized) : false;
}
function splitDesktopNameList(value: string | undefined): string[] {
return value?.split(":") ?? [];
}
function normalizeDesktopName(value: string | undefined): string | null {
const normalized = value?.trim().toLowerCase();
return normalized && normalized.length > 0 ? normalized : null;
}
function normalizeSelectedStorageBackend(value: string | null): string | null {
const normalized = value?.trim().toLowerCase().replace(/_/gu, "-");
return normalized && normalized.length > 0 ? normalized : null;
}
+14 -7
View File
@@ -43,12 +43,14 @@ import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentA
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
import * as DesktopLinuxUrlHandler from "./app/DesktopLinuxUrlHandler.ts";
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
import * as DesktopObservability from "./app/DesktopObservability.ts";
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
import * as DesktopSavedEnvironments from "./settings/DesktopSavedEnvironments.ts";
import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts";
import * as DesktopPreReadyPlatform from "./app/DesktopPreReadyPlatform.ts";
import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
@@ -181,6 +183,7 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer,
DesktopApplicationMenu.layer,
DesktopLinuxUrlHandler.layer,
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(
@@ -195,16 +198,20 @@ const desktopClerkLayer = DesktopClerk.layer.pipe(
Layer.provideMerge(ElectronApp.layer),
);
const desktopApplicationRuntimeLayer = desktopApplicationLayer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(electronLayer),
);
// Acquire strict pre-ready setup before Clerk, whose userData resolution can
// yield and let Electron emit ready.
const desktopRuntimeLayer = desktopClerkLayer.pipe(
Layer.flatMap((clerkContext) =>
desktopApplicationLayer.pipe(
Layer.provideMerge(Layer.succeedContext(clerkContext)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(electronLayer),
),
desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))),
),
Layer.provideMerge(DesktopPreReadyPlatform.layer),
);
DesktopApp.program.pipe(Effect.provide(desktopRuntimeLayer), NodeRuntime.runMain);
+1 -1
View File
@@ -109,7 +109,7 @@ const DIAGNOSTIC_BUFFER_LIMIT = 200;
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
const AGENT_CURSOR_MOVE_MS = 160;
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const DEFAULT_ANNOTATION_THEME: DesktopPreviewAnnotationTheme = {
colorScheme: "light",
radius: "0.625rem",
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = NodeModule.createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
@@ -11,6 +11,9 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
const DesktopSettingsPatch = Schema.Struct({
linuxPasswordStore: Schema.optionalKey(
Schema.Literals(["auto", "gnome-libsecret", "kwallet", "kwallet5", "kwallet6"]),
),
mainWindowBounds: Schema.optionalKey(
Schema.NullOr(
Schema.Struct({
@@ -102,6 +105,7 @@ describe("DesktopSettings", () => {
assert.deepEqual(
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
{
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -121,6 +125,7 @@ describe("DesktopSettings", () => {
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
linuxPasswordStore: "gnome-libsecret",
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
@@ -129,6 +134,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "gnome-libsecret",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
@@ -235,6 +241,7 @@ describe("DesktopSettings", () => {
);
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
@@ -268,6 +275,44 @@ describe("DesktopSettings", () => {
),
);
it.effect(
"normalizes unsupported linux password-store values without dropping other settings",
() =>
withSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(
environment.desktopSettingsPath,
`{
"linuxPasswordStore": "unsupported-store",
"serverExposureMode": "network-accessible",
"tailscaleServeEnabled": true,
"tailscaleServePort": 8443,
"updateChannel": "nightly",
"updateChannelConfiguredByUser": true
}\n`,
);
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
),
);
it.effect("persists sparse desktop settings documents", () =>
withSettings(
Effect.gen(function* () {
@@ -300,6 +345,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -327,6 +373,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -353,6 +400,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -16,10 +16,16 @@ import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import {
DEFAULT_LINUX_PASSWORD_STORE,
normalizeLinuxPasswordStorePreference,
type LinuxPasswordStorePreference,
} from "../linuxSecretStorage.ts";
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
export interface DesktopSettings {
readonly linuxPasswordStore: LinuxPasswordStorePreference;
readonly mainWindowBounds: DesktopWindowBounds | null;
readonly mainWindowMaximized: boolean;
readonly serverExposureMode: DesktopServerExposureMode;
@@ -67,6 +73,7 @@ export const DEFAULT_MAIN_WINDOW_SIZE = {
} as const;
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE,
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -87,6 +94,7 @@ const DesktopWindowBoundsDocument = Schema.Struct({
});
const DesktopSettingsDocument = Schema.Struct({
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
@@ -216,6 +224,7 @@ function normalizeDesktopSettingsDocument(
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
return {
linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore),
mainWindowBounds,
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
serverExposureMode:
@@ -238,6 +247,9 @@ function toDesktopSettingsDocument(
): DesktopSettingsDocument {
const document: Mutable<DesktopSettingsDocument> = {};
if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) {
document.linuxPasswordStore = settings.linuxPasswordStore;
}
if (settings.mainWindowBounds !== null) {
document.mainWindowBounds = settings.mainWindowBounds;
}
@@ -86,6 +86,7 @@ function makeSafeStorageLayer(input: {
}
return Effect.succeed(decoded.slice("enc:".length));
},
selectedStorageBackend: Effect.succeed(Option.none()),
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
@@ -1,3 +1,4 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -90,7 +91,7 @@ function runShellEnvironment(input: {
}).pipe(
Effect.provide(
DesktopShellEnvironment.layer.pipe(
Layer.provide(Layer.mergeAll(environmentLayer, spawnerLayer)),
Layer.provide(Layer.mergeAll(environmentLayer, NodeServices.layer, spawnerLayer)),
),
),
);
@@ -243,6 +244,65 @@ describe("DesktopShellEnvironment", () => {
}),
);
it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
XDG_CURRENT_DESKTOP: "wrong-launcher",
XDG_SESSION_DESKTOP: "wrong-launcher",
};
yield* runShellEnvironment({
env,
platform: "linux",
handler: () =>
envOutput({
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
XDG_CURRENT_DESKTOP: "KDE",
XDG_SESSION_DESKTOP: "KDE",
XDG_SESSION_TYPE: "wayland",
}),
});
assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
assert.equal(env.XDG_SESSION_TYPE, "wayland");
}),
);
it.effect("overrides stale dbus session addresses from the login shell", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
};
yield* runShellEnvironment({
env,
platform: "linux",
handler: () =>
envOutput({
PATH: "/usr/bin",
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
}),
});
assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
}),
);
it("resolves dbus runtime dir candidates with existence checks", () => {
const busPath = DesktopShellEnvironment.resolveDefaultLinuxDbusSessionBusAddress({
env: { XDG_RUNTIME_DIR: "/tmp/stale-runtime" },
uid: 1000,
exists: (path) => path === "/run/user/1000/bus",
});
assert.equal(busPath, "unix:path=/run/user/1000/bus");
});
it.effect("logs command failures with safe probe context and the exact cause", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/bash",
@@ -1,6 +1,7 @@
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -68,12 +69,19 @@ export class DesktopShellEnvironment extends Context.Service<
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
"DBUS_SESSION_BUS_ADDRESS",
"DISPLAY",
"SSH_AUTH_SOCK",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_CURRENT_DESKTOP",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"XDG_SESSION_DESKTOP",
"XDG_SESSION_TYPE",
"WAYLAND_DISPLAY",
] as const;
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
@@ -92,6 +100,47 @@ const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";"
const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
trimNonEmpty(env.PATH ?? env.Path ?? env.path);
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
const linuxRuntimeDirCandidates = (
env: NodeJS.ProcessEnv,
uid: number | undefined,
): ReadonlyArray<string> => {
const candidates: string[] = [];
const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
if (Option.isSome(fromEnv)) {
candidates.push(normalizeRuntimeDir(fromEnv.value));
}
if (uid !== undefined) {
candidates.push(`/run/user/${uid}`);
}
return candidates.filter((candidate) => candidate.length > 0);
};
function resolveDefaultLinuxDbusSessionBusPath(input: {
readonly env: NodeJS.ProcessEnv;
readonly uid: number | undefined;
readonly exists?: (path: string) => boolean;
}): string | null {
for (const runtimeDir of linuxRuntimeDirCandidates(input.env, input.uid)) {
const busPath = `${runtimeDir}/bus`;
if (input.exists === undefined || input.exists(busPath)) {
return busPath;
}
}
return null;
}
export function resolveDefaultLinuxDbusSessionBusAddress(input: {
readonly env: NodeJS.ProcessEnv;
readonly exists: (path: string) => boolean;
readonly uid: number | undefined;
}): string | null {
const busPath = resolveDefaultLinuxDbusSessionBusPath(input);
return busPath !== null && input.exists(busPath) ? `unix:path=${busPath}` : null;
}
const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
const normalized = entry.trim().replace(/^"+|"+$/g, "");
return platform === "win32" ? normalized.toLowerCase() : normalized;
@@ -356,7 +405,12 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
): Effect.fn.Return<
void,
never,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
> {
const fileSystem = yield* FileSystem.FileSystem;
const shellEnvironment: EnvironmentPatch = {};
for (const shell of listLoginShellCandidates(config)) {
@@ -383,23 +437,54 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
const shellPreferredEnvNames = [
"DBUS_SESSION_BUS_ADDRESS",
"XDG_CURRENT_DESKTOP",
"XDG_SESSION_DESKTOP",
"XDG_SESSION_TYPE",
] as const;
for (const name of shellPreferredEnvNames) {
if (shellEnvironment[name]) {
config.env[name] = shellEnvironment[name];
}
}
for (const name of [
"DISPLAY",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"WAYLAND_DISPLAY",
] as const) {
if (!config.env[name] && shellEnvironment[name]) {
config.env[name] = shellEnvironment[name];
}
}
if (
config.platform === "linux" &&
Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
) {
for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
const dbusSessionBusPath = `${runtimeDir}/bus`;
const busExists = yield* fileSystem
.exists(dbusSessionBusPath)
.pipe(Effect.orElseSucceed(() => false));
if (busExists) {
config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
break;
}
}
}
},
);
const installShellEnvironment = (
config: ShellEnvironmentConfig,
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
if (config.platform === "win32") {
return installWindowsEnvironment(config);
}
@@ -411,6 +496,7 @@ const installShellEnvironment = (
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
installShellEnvironment({
@@ -418,6 +504,7 @@ export const make = Effect.gen(function* () {
platform: environment.platform,
userShell: Option.none(),
}).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
);
@@ -34,7 +34,6 @@ function makeElectronAppLayer(
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.sync(() => {
onMetricsRead();
return metrics;
@@ -44,6 +43,7 @@ function makeElectronAppLayer(
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
@@ -28,34 +28,39 @@ const environmentInput = {
runningUnderArm64Translation: false,
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
const makeElectronAppLayer = (quit: Effect.Effect<void> = Effect.void) =>
Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
confirm: () => Effect.succeed(false),
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
showErrorBox: () => Effect.void,
} satisfies ElectronDialog.ElectronDialog["Service"]);
const makeElectronDialogLayer = (
showMessageBox: ElectronDialog.ElectronDialog["Service"]["showMessageBox"] = () =>
Effect.succeed({ response: 0, checkboxChecked: false }),
) =>
Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
confirm: () => Effect.succeed(false),
showMessageBox,
showErrorBox: () => Effect.void,
} satisfies ElectronDialog.ElectronDialog["Service"]);
const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
getState: Effect.die("unexpected getState"),
@@ -109,8 +114,8 @@ describe("DesktopApplicationMenu", () => {
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(makeElectronDialogLayer()),
Layer.provideMerge(makeElectronAppLayer()),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
@@ -137,4 +142,69 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
}),
);
it.effect("confirms Cmd+Q before quitting on macOS", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
const promptOptions = yield* Deferred.make<Electron.MessageBoxOptions>();
const quitRequested = yield* Deferred.make<void>();
yield* Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(
makeElectronDialogLayer((options) =>
Deferred.succeed(promptOptions, options).pipe(
Effect.as({ response: 1, checkboxChecked: false }),
),
),
),
Layer.provideMerge(
makeElectronAppLayer(Deferred.succeed(quitRequested, undefined).pipe(Effect.asVoid)),
),
Layer.provideMerge(
DesktopEnvironment.layer({ ...environmentInput, platform: "darwin" }).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
const template = yield* Deferred.await(applicationMenuTemplate);
const appMenu = template.find((item) => item.label === "T3 Code");
assert.isDefined(appMenu);
if (!Array.isArray(appMenu.submenu)) {
throw new Error("Expected application menu submenu to be an array.");
}
const quitItem = appMenu.submenu.find((item) => item.label === "Quit T3 Code");
assert.isDefined(quitItem);
assert.equal(quitItem.accelerator, "CmdOrCtrl+Q");
if (typeof quitItem.click !== "function") {
throw new Error("Expected Quit menu item to have a click handler.");
}
quitItem.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
assert.deepEqual(yield* Deferred.await(promptOptions), {
type: "warning",
title: "Quit T3 Code?",
message: "Quit T3 Code?",
detail: "All running agents will be stopped.",
buttons: ["Cancel", "Quit"],
defaultId: 0,
cancelId: 0,
noLink: true,
});
yield* Deferred.await(quitRequested);
}),
);
});
@@ -96,6 +96,21 @@ const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
yield* checkForUpdatesFromMenu;
}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
const confirmQuit = Effect.gen(function* () {
const electronDialog = yield* ElectronDialog.ElectronDialog;
const result = yield* electronDialog.showMessageBox({
type: "warning",
title: "Quit T3 Code?",
message: "Quit T3 Code?",
detail: "All running agents will be stopped.",
buttons: ["Cancel", "Quit"],
defaultId: 0,
cancelId: 0,
noLink: true,
});
return result.response === 1;
}).pipe(Effect.withSpan("desktop.menu.confirmQuit"));
export const make = Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronMenu = yield* ElectronMenu.ElectronMenu;
@@ -127,6 +142,30 @@ export const make = Effect.gen(function* () {
const settingsClick = () => {
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
};
let quitConfirmationOpen = false;
const quitClick = () => {
if (quitConfirmationOpen) return;
quitConfirmationOpen = true;
runMenuEffect(
"quit",
Effect.gen(function* () {
if (yield* confirmQuit) {
yield* electronApp.quit;
}
}).pipe(
Effect.ensuring(
Effect.sync(() => {
quitConfirmationOpen = false;
}),
),
),
);
};
const quitMenuItem: Electron.MenuItemConstructorOptions = {
label: `Quit ${appName}`,
accelerator: "CmdOrCtrl+Q",
click: quitClick,
};
const template: Electron.MenuItemConstructorOptions[] = [];
if (environment.platform === "darwin") {
@@ -151,7 +190,7 @@ export const make = Effect.gen(function* () {
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
quitMenuItem,
],
});
}
@@ -170,7 +209,7 @@ export const make = Effect.gen(function* () {
},
{ type: "separator" as const },
]),
{ role: environment.platform === "darwin" ? "close" : "quit" },
environment.platform === "darwin" ? { role: "close" } : quitMenuItem,
],
},
{ role: "editMenu" },
@@ -438,6 +438,51 @@ describe("DesktopWindow", () => {
}),
);
it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const beforeInput = fakeWindow.webContentsListeners.get("before-input-event");
if (!beforeInput) {
return yield* Effect.die("before-input-event listener was not registered");
}
let prevented = false;
const event = { preventDefault: () => (prevented = true) };
const input = {
type: "keyDown",
isAutoRepeat: true,
key: "W",
meta: true,
control: false,
alt: false,
shift: false,
};
beforeInput(event, input);
assert.isTrue(prevented);
prevented = false;
beforeInput(event, { ...input, isAutoRepeat: false });
assert.isFalse(prevented);
prevented = false;
beforeInput(event, { ...input, meta: false });
assert.isFalse(prevented);
}).pipe(Effect.provide(layer));
}),
);
it.effect("uses the persisted main window bounds when opening the window", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
+53 -4
View File
@@ -1,3 +1,4 @@
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -25,6 +26,12 @@ const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
// Renderer crash (usually V8 OOM on long sessions) recovery: reload after a
// short delay, at most MAX_ATTEMPTS times per rolling WINDOW so a renderer
// that dies on boot cannot reload-loop forever.
const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500;
const RENDERER_RECOVERY_MAX_ATTEMPTS = 3;
const RENDERER_RECOVERY_WINDOW_MS = 60_000;
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
-2, // ERR_FAILED
-7, // ERR_TIMED_OUT
@@ -514,6 +521,18 @@ export const make = Effect.gen(function* () {
}
});
// Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
// close-terminal shortcut can outlive the terminal that handled its first
// press, so reject repeats before they reach the native window accelerator.
// Deliberate presses still flow through the renderer or native menu.
window.webContents.on("before-input-event", (event, input) => {
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
const modifier = environment.platform === "darwin" ? input.meta : input.control;
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
event.preventDefault();
}
});
window.on("page-title-updated", (event) => {
event.preventDefault();
window.setTitle(environment.displayName);
@@ -537,6 +556,7 @@ export const make = Effect.gen(function* () {
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
let rendererRecoveryTimestamps: number[] = [];
const clearDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber === undefined) {
return;
@@ -618,10 +638,39 @@ export const make = Effect.gen(function* () {
},
);
window.webContents.on("render-process-gone", (_event, details) => {
void runPromise(
logWindowWarning("main window render process gone", {
reason: details.reason,
exitCode: details.exitCode,
const recoverable =
details.reason === "crashed" ||
details.reason === "oom" ||
details.reason === "abnormal-exit";
// Long sessions can OOM the renderer (V8 heap exhaustion from
// accumulated thread state). Without a reload the user is left staring
// at a dead white window while agents keep running invisibly, so
// recover by reloading — the renderer rehydrates from the backend,
// which is unaffected. Recovery attempts are bounded so a renderer
// that dies immediately on boot cannot reload-loop forever.
runFork(
Effect.gen(function* () {
const now = yield* Clock.currentTimeMillis;
rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
(timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
);
const shouldRecover =
recoverable &&
!window.isDestroyed() &&
rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
yield* logWindowWarning("main window render process gone", {
reason: details.reason,
exitCode: details.exitCode,
recovering: shouldRecover,
});
if (!shouldRecover) {
return;
}
rendererRecoveryTimestamps.push(now);
yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
if (!window.isDestroyed()) {
loadApplication();
}
}),
);
});
+21 -1
View File
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
slug: "t3-code",
platforms: ["ios", "android"],
scheme: variant.scheme,
version: "0.1.0",
version: "1.0.1",
runtimeVersion: {
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
// project — native deps, config plugins, AND patches/ — matches the update.
@@ -181,6 +181,9 @@ const config: ExpoConfig = {
ios: {
icon: variant.assets.iosIcon,
supportsTablet: true,
// Multitasking-capable iPad apps cannot rotate programmatically, so the
// showcase capture build requires full screen (see infoPlist below).
requireFullScreen: process.env.T3_SHOWCASE_CAPTURE_BUILD === "1",
bundleIdentifier: iosBundleIdentifier,
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
// does not fall back to a personal team (which cannot sign app groups,
@@ -197,6 +200,21 @@ const config: ExpoConfig = {
NSLocalNetworkUsageDescription:
"Allow T3 Code to connect to T3 Code servers on your local network or tailnet.",
ITSAppUsesNonExemptEncryption: false,
// The App Store screenshot harness rotates the iPad interface from
// inside the app (CI denies osascript the Accessibility access that
// Simulator menu scripting needs), and iPadOS ignores programmatic
// orientation requests for multitasking-capable apps — so the capture
// build opts out of multitasking and declares landscape support.
...(process.env.T3_SHOWCASE_CAPTURE_BUILD === "1"
? {
"UISupportedInterfaceOrientations~ipad": [
"UIInterfaceOrientationPortrait",
"UIInterfaceOrientationPortraitUpsideDown",
"UIInterfaceOrientationLandscapeLeft",
"UIInterfaceOrientationLandscapeRight",
],
}
: {}),
},
},
android: {
@@ -275,10 +293,12 @@ const config: ExpoConfig = {
"expo-camera",
{
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
microphonePermission: false,
barcodeScannerEnabled: true,
recordAudioAndroid: false,
},
],
["expo-image-picker", { photosPermission: false, microphonePermission: false }],
[
"expo-splash-screen",
{
@@ -1,5 +1,6 @@
import ExpoModulesCore
import Security
import UIKit
public final class T3NativeControlsModule: Module {
public func definition() -> ModuleDefinition {
@@ -32,6 +33,50 @@ public final class T3NativeControlsModule: Module {
return arguments[flagIndex + 1]
}
Function("getShowcaseOrientation") { () -> String? in
let arguments = ProcessInfo.processInfo.arguments
guard
let flagIndex = arguments.firstIndex(of: "--showcaseOrientation"),
arguments.indices.contains(flagIndex + 1)
else {
return nil as String?
}
return arguments[flagIndex + 1]
}
// Rotates the interface without Simulator menu UI scripting, which CI
// runners cannot perform (osascript is denied Accessibility access there).
AsyncFunction("applyShowcaseOrientation") { (orientation: String) in
guard #available(iOS 16.0, *) else { return }
let mask: UIInterfaceOrientationMask = orientation == "landscape" ? .landscapeRight : .portrait
for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) { error in
NSLog("T3NativeControls applyShowcaseOrientation(\(orientation)) failed: \(error)")
}
for window in windowScene.windows {
window.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
}
}
}.runOnQueue(.main)
// The geometry request above can fail transiently (for example before the
// scene is foreground-active), so callers poll this until it settles.
// Screen bounds — not the scene's interface orientation — decide the
// answer because they match the captured framebuffer: with iPadOS
// windowing active, a floating landscape window still reports a portrait
// screen, and screenshots would come out portrait.
AsyncFunction("getInterfaceOrientation") { () -> String in
guard
let windowScene = UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene })
.first
else {
return "unknown"
}
let bounds = windowScene.screen.coordinateSpace.bounds
return bounds.width > bounds.height ? "landscape" : "portrait"
}.runOnQueue(.main)
Function("prepareShowcaseCapture") {
for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
+1 -1
View File
@@ -40,7 +40,7 @@ fails, run `xcodebuild -downloadComponent MetalToolchain`.
## Rebuilding libghostty-vt for Android
The checked-in Android shared libraries and headers are pinned to the revision recorded in
`Vendor/libghostty-vt/VERSION`. Set `ANDROID_NDK_HOME` and run:
`native/libghostty-vt/VERSION` at the repository root. Set `ANDROID_NDK_HOME` and run:
```bash
apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
@@ -18,13 +18,14 @@ Ghostty's MIT license applies to the vendored framework. Keep this notice in syn
## Ghostty / libghostty-vt
The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers.
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`
- License: MIT
Ghostty's MIT license applies to the vendored Android libraries. Keep this notice in sync when
updating `Vendor/libghostty-vt`.
Ghostty's MIT license applies to the vendored Android and web libraries. Keep this notice and both
artifacts in sync when updating the repository-root `native/libghostty-vt`.
## MesloLGS NF (Android terminal font)
@@ -13,7 +13,7 @@ add_library(t3terminal SHARED t3_terminal_jni.cpp)
target_include_directories(
t3terminal
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../Vendor/libghostty-vt/include"
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../../../native/libghostty-vt/include"
)
target_link_options(
@@ -4,7 +4,7 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
VENDOR_DIR="${MODULE_DIR}/Vendor/libghostty-vt"
VENDOR_DIR="${MODULE_DIR}/../../../../native/libghostty-vt"
PATCH_DIR="${SCRIPT_DIR}/libghostty-android-patches"
GHOSTTY_REVISION="${GHOSTTY_REVISION:-9f62873bf195e4d8a762d768a1405a5f2f7b1697}"
+1 -1
View File
@@ -11,7 +11,7 @@
"start:dev": "APP_VARIANT=development expo start",
"start:preview": "APP_VARIANT=preview expo start",
"start:prod": "APP_VARIANT=production expo start",
"showcase": "APP_VARIANT=development EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code-dev --clear",
"showcase": "APP_VARIANT=production EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code --clear",
"screenshots": "node ../../scripts/mobile-showcase.ts",
"android": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
"android:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && REACT_NATIVE_PACKAGER_HOSTNAME=localhost expo run:android",
+2 -1
View File
@@ -15,6 +15,7 @@ import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "re
import { useResolveClassNames } from "uniwind";
import { AppText as Text } from "./components/AppText";
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
@@ -392,7 +393,7 @@ export const RootStack = createNativeStackNavigator({
...GLASS_HEADER_OPTIONS,
contentStyle: { backgroundColor: "transparent" },
headerBackVisible: false,
title: "Threads",
...getCompactBrandHeaderOptions(),
},
}),
Thread: createNativeStackScreen({
+2
View File
@@ -22,6 +22,7 @@ import {
IconChevronUp,
IconCircleCheck,
IconCircleXFilled,
IconClock,
IconCopy,
IconDeviceDesktop,
IconDots,
@@ -96,6 +97,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
camera: IconCamera,
checkmark: IconCheck,
"checkmark.circle": IconCircleCheck,
clock: IconClock,
"chevron.down": IconChevronDown,
"chevron.left": IconChevronLeft,
"chevron.left.forwardslash.chevron.right": IconCode,
@@ -0,0 +1,121 @@
import Constants from "expo-constants";
import type {
NativeStackHeaderItem,
NativeStackNavigationOptions,
} from "@react-navigation/native-stack";
import { Platform, View } from "react-native";
import { AppText as Text } from "./AppText";
import { T3Wordmark } from "./T3Wordmark";
import { IPAD_HOME_TITLE_OFFSET } from "../lib/layoutMetrics";
import { resolveMobileStageLabel } from "../lib/mobileBranding";
import { useThemeColor } from "../lib/useThemeColor";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
// Native leading items inherit different UIKit margins than title views.
const IOS_NATIVE_LEADING_TITLE_OFFSET = -6;
const IPAD_NATIVE_LEADING_TITLE_OFFSET = 7;
/**
* Compact brand lockup sized for native navigation bars.
*/
export function CompactBrandTitle(
props: {
readonly nativeLeadingItem?: boolean;
} = {},
) {
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
const titleOffset =
Platform.OS !== "ios"
? 0
: props.nativeLeadingItem
? Platform.isPad
? IPAD_NATIVE_LEADING_TITLE_OFFSET
: IOS_NATIVE_LEADING_TITLE_OFFSET
: Platform.isPad
? IPAD_HOME_TITLE_OFFSET
: 0;
return (
<View
aria-level={1}
accessibilityLabel="T3 Code, Threads"
accessible
role="heading"
style={{
alignItems: "center",
flexDirection: "row",
gap: 6,
marginLeft: titleOffset,
}}
>
<T3Wordmark color={iconColor} height={15} />
<Text
style={{
color: mutedColor,
fontFamily: "DMSans-Medium",
fontSize: 21,
letterSpacing: -0.5,
}}
>
Code
</Text>
<View
style={{
backgroundColor: subtleColor,
borderRadius: 999,
paddingHorizontal: 6,
paddingVertical: 2,
}}
>
<Text
style={{
color: mutedColor,
fontFamily: "DMSans-Bold",
fontSize: 9,
letterSpacing: 0.9,
textTransform: "uppercase",
}}
>
{stageLabel}
</Text>
</View>
</View>
);
}
export function renderCompactBrandTitle() {
return <CompactBrandTitle />;
}
export function renderCompactBrandHeaderItems(): NativeStackHeaderItem[] {
return [
{
element: <CompactBrandTitle nativeLeadingItem />,
hidesSharedBackground: true,
type: "custom",
},
];
}
export function getCompactBrandHeaderOptions(
fallbackTitleStyle?: NativeStackNavigationOptions["headerTitleStyle"],
): NativeStackNavigationOptions {
if (Platform.OS === "ios" && NATIVE_LIQUID_GLASS_SUPPORTED) {
return {
headerTitle: "Threads",
headerTitleStyle: { color: "transparent", fontSize: 18, fontWeight: "800" },
title: "Threads",
unstable_headerLeftItems: renderCompactBrandHeaderItems,
};
}
return {
headerTitle: renderCompactBrandTitle,
headerTitleStyle: fallbackTitleStyle,
title: "Threads",
};
}
+39 -1
View File
@@ -9,6 +9,7 @@ type ProviderIconProps = {
export function ProviderIcon(props: ProviderIconProps) {
const isDarkMode = useColorScheme() === "dark";
const size = props.size ?? 16;
const mono = isDarkMode ? "#e5e5e5" : "#171717";
if (props.provider === "claudeAgent") {
return (
@@ -21,10 +22,47 @@ export function ProviderIcon(props: ProviderIconProps) {
);
}
if (props.provider === "grok") {
const fill = isDarkMode ? "#F5F5F5" : "#0F0F0F";
return (
<Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
<Path
fill={fill}
d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861"
/>
<Path
fill={fill}
d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257"
/>
</Svg>
);
}
if (props.provider === "cursor") {
return (
<Svg width={size} height={size} viewBox="0 0 466.73 532.09" fill="none">
<Path
fill={isDarkMode ? "#EDECEC" : "#26251E"}
d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"
/>
</Svg>
);
}
if (props.provider === "opencode") {
return (
<Svg width={size} height={size} viewBox="0 0 32 40" fill="none">
<Path d="M24 32H8V16H24V32Z" fill={isDarkMode ? "#4B4646" : "#CFCECD"} />
<Path d="M24 8H8V32H24V8ZM32 40H0V0H32V40Z" fill={isDarkMode ? "#F1ECEC" : "#211E1E"} />
</Svg>
);
}
// codex (and unknown drivers)
return (
<Svg width={size} height={size} viewBox="0 0 256 260" fill="none">
<Path
fill={isDarkMode ? "#e5e5e5" : "#171717"}
fill={mono}
d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"
/>
</Svg>
@@ -1,11 +1,32 @@
import { describe, expect, it } from "vite-plus/test";
import {
buildPairingUrl,
extractPairingUrlFromQrPayload,
PairingQrPayloadEmptyError,
parsePairingUrl,
} from "./pairing";
describe("buildPairingUrl", () => {
it("uses HTTP for a schemeless IP address", () => {
expect(buildPairingUrl("192.168.1.100:3773", "pairing-token")).toBe(
"http://192.168.1.100:3773/#token=pairing-token",
);
});
it("keeps HTTPS as the default for a schemeless hostname", () => {
expect(buildPairingUrl("remote.example.com", "pairing-token")).toBe(
"https://remote.example.com/#token=pairing-token",
);
});
it("preserves an explicit scheme for an IP address", () => {
expect(buildPairingUrl("https://192.168.1.100:3773", "pairing-token")).toBe(
"https://192.168.1.100:3773/#token=pairing-token",
);
});
});
describe("extractPairingUrlFromQrPayload", () => {
it("trims raw pairing urls from qr payloads", () => {
expect(
+16 -1
View File
@@ -3,6 +3,21 @@ import * as Schema from "effect/Schema";
const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
function isIpLiteral(host: string): boolean {
try {
const hostname = new URL(`http://${host}`).hostname.replace(/^\[|\]$/g, "");
if (hostname.includes(":")) return true;
const octets = hostname.split(".");
return (
octets.length === 4 &&
octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255)
);
} catch {
return false;
}
}
export class PairingQrPayloadEmptyError extends Schema.TaggedErrorClass<PairingQrPayloadEmptyError>()(
"PairingQrPayloadEmptyError",
{},
@@ -19,7 +34,7 @@ export function buildPairingUrl(host: string, code: string): string {
if (!c) return h;
try {
const url = new URL(h.includes("://") ? h : `https://${h}`);
const url = new URL(h.includes("://") ? h : `${isIpLiteral(h) ? "http" : "https"}://${h}`);
url.hash = new URLSearchParams([["token", c]]).toString();
return url.toString();
} catch {
+7 -2
View File
@@ -1,5 +1,6 @@
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import Constants from "expo-constants";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useCallback, useMemo, useRef } from "react";
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
@@ -9,6 +10,8 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { ControlPillMenu } from "../../components/ControlPill";
import { SymbolView } from "../../components/AppSymbol";
import { T3Wordmark } from "../../components/T3Wordmark";
import { HOME_HORIZONTAL_INSET } from "../../lib/layoutMetrics";
import { resolveMobileStageLabel } from "../../lib/mobileBranding";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
@@ -64,6 +67,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
const insets = useSafeAreaInsets();
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
// Thread List v2 lays the list out in fixed creation order, so the
// sort/group filter controls would be silently ignored — hide them and
// key the "customized" icon state off the environment filter alone.
@@ -195,8 +199,9 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<View
className="border-b border-header-border bg-header px-4 pb-3"
className="border-b border-header-border bg-header pb-3"
style={{
paddingHorizontal: HOME_HORIZONTAL_INSET,
paddingTop: Math.max(insets.top, 12),
}}
>
@@ -210,7 +215,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
</RNText>
<View className="rounded-full bg-subtle px-2 py-0.75">
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
Alpha
{stageLabel}
</RNText>
</View>
</View>
@@ -3,6 +3,7 @@ import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useEffect, useMemo, useState } from "react";
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
@@ -35,8 +36,14 @@ export function HomeRouteScreen() {
void checkForAppUpdateOnLaunch();
}, []);
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
useThreadListActions();
const {
archiveThread,
confirmDeleteThread,
settleThread,
snoozeThread,
unsnoozeThread,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(() => {
@@ -93,7 +100,9 @@ export function HomeRouteScreen() {
if (layout.usesSplitView) {
return (
<>
<NativeStackScreenOptions options={{ title: "", headerTitle: "" }} />
<NativeStackScreenOptions
options={{ title: "", headerTitle: "", unstable_headerLeftItems: () => [] }}
/>
<WorkspaceSidebarToolbar
afterSidebarButton={
<NativeHeaderToolbar.Button
@@ -115,8 +124,8 @@ export function HomeRouteScreen() {
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
>
<>
{/* Restore the compact title in case the split branch blanked it. */}
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
{/* Restore the compact title after the split branch blanks the detail header. */}
<NativeStackScreenOptions options={getCompactBrandHeaderOptions()} />
<HomeHeader
environments={environments}
projects={projectFilterOptions}
@@ -143,6 +152,8 @@ export function HomeRouteScreen() {
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onSettleThread={settleThread}
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
+86 -29
View File
@@ -41,7 +41,12 @@ import {
ThreadListRow,
ThreadListShowMoreRow,
} from "../threads/thread-list-items";
import { ThreadListV2PendingRow, ThreadListV2Row } from "../threads/thread-list-v2-items";
import {
ThreadListV2PendingRow,
ThreadListV2Row,
ThreadListV2SettledShelfHeader,
ThreadListV2SnoozedShelfHeader,
} from "../threads/thread-list-v2-items";
import {
buildThreadListV2Items,
buildThreadListV2ListItems,
@@ -100,6 +105,11 @@ interface HomeScreenProps {
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
/** Resolves true iff the settle was dispatched and succeeded. */
readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onSnoozeThread: (
thread: EnvironmentThreadShell,
snoozedUntil: string,
) => Promise<boolean>;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
@@ -494,6 +504,18 @@ export function HomeScreen(props: HomeScreenProps) {
},
[props.onSettleThread],
);
const handleSnoozeThread = useCallback(
(thread: EnvironmentThreadShell, snoozedUntil: string) => {
void props.onSnoozeThread(thread, snoozedUntil);
},
[props.onSnoozeThread],
);
const handleUnsnoozeThread = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onUnsnoozeThread(thread);
},
[props.onUnsnoozeThread],
);
const handleDeleteThread = props.onDeleteThread;
const handleUnsettleThread = props.onUnsettleThread;
// The settled tail renders in pages; expansion resets when the filter
@@ -511,6 +533,10 @@ export function HomeScreen(props: HomeScreenProps) {
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
[],
);
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
// now is quantized to the minute and ticks so the inactivity auto-settle
// boundary is actually crossed while the app stays open (mirrors web);
// without a clock dependency the partition memoizes a frozen "now".
@@ -551,7 +577,15 @@ export function HomeScreen(props: HomeScreenProps) {
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
return {
items: [],
hiddenSettledCount: 0,
snoozedCount: 0,
snoozedShelfHeaderIndex: null,
settledCount: 0,
settledShelfHeaderIndex: null,
nextSnoozeWakeAt: null,
};
// Settled threads are live shells; archived threads keep their original
// "hidden from lists" meaning.
return buildThreadListV2Items({
@@ -566,11 +600,16 @@ export function HomeScreen(props: HomeScreenProps) {
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
snoozedShelfExpanded,
settledShelfExpanded,
selectedThreadKey: null,
});
}, [
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
settledShelfExpanded,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
@@ -620,8 +659,15 @@ export function HomeScreen(props: HomeScreenProps) {
buildThreadListV2ListItems({
items: threadListV2Layout.items,
pendingTasks: v2PendingTasks,
snoozedCount: threadListV2Layout.snoozedCount,
snoozedShelfExpanded,
snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
settledCount: threadListV2Layout.settledCount,
settledShelfExpanded,
settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
snoozeLabelNow: `${nowMinute}:00.000Z`,
}),
[threadListV2Layout.items, v2PendingTasks],
[settledShelfExpanded, snoozedShelfExpanded, threadListV2Layout, v2PendingTasks],
);
const renderV2Item = useCallback(
@@ -648,12 +694,32 @@ export function HomeScreen(props: HomeScreenProps) {
/>
);
}
if (item.type === "v2-snoozed-shelf") {
return (
<ThreadListV2SnoozedShelfHeader
count={item.count}
expanded={item.expanded}
onToggle={toggleSnoozedShelf}
/>
);
}
if (item.type === "v2-settled-shelf") {
return (
<ThreadListV2SettledShelfHeader
count={item.count}
expanded={item.expanded}
onToggle={toggleSettledShelf}
/>
);
}
const thread = item.item.thread;
return (
<ThreadListV2Row
thread={thread}
variant={item.item.variant}
showSettledDivider={item.item.showSettledDivider}
snoozed={item.item.snoozed}
snoozePresetMinute={nowMinute}
snoozeWakeLabelText={item.snoozeWakeLabelText}
project={
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
}
@@ -686,6 +752,9 @@ export function HomeScreen(props: HomeScreenProps) {
onArchiveThread={props.onArchiveThread}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={handleSettleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
onSnoozeThread={handleSnoozeThread}
onUnsnoozeThread={handleUnsnoozeThread}
onUnsettleThread={handleUnsettleThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
@@ -700,6 +769,8 @@ export function HomeScreen(props: HomeScreenProps) {
handleChangeRequestState,
handleDeleteThread,
handleSettleThread,
handleSnoozeThread,
handleUnsnoozeThread,
handleSwipeableClose,
handleSwipeableWillOpen,
handleUnsettleThread,
@@ -712,9 +783,13 @@ export function HomeScreen(props: HomeScreenProps) {
props.savedConnectionsById,
serverConfigs,
settlementEnvironmentIds,
snoozeEnvironmentIds,
threadSearchMatchByKey,
toggleSettledShelf,
toggleSnoozedShelf,
v2ProjectTitleByProjectKey,
props.searchQuery,
nowMinute,
],
);
const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
@@ -730,6 +805,7 @@ export function HomeScreen(props: HomeScreenProps) {
serverConfigs,
savedConnectionsById: props.savedConnectionsById,
searchQuery: props.searchQuery,
snoozePresetMinute: nowMinute,
threadSearchMatchByKey,
}),
[
@@ -738,6 +814,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.savedConnectionsById,
serverConfigs,
nowMinute,
threadSearchMatchByKey,
v2ProjectTitleByProjectKey,
],
@@ -953,31 +1030,11 @@ export function HomeScreen(props: HomeScreenProps) {
) : null;
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
// v2 project scope, so it can be null (results elsewhere) while this list
// is empty. Search outranks the scope — "No results" names the actionable
// fact when a query is active. Snoozed threads outrank the rest: "No
// threads yet" over an inbox that is merely all-snoozed reads as data
// loss.
const v2SnoozedCount = threadListV2Layout.snoozedCount;
// is empty. Snoozed threads need no special empty state: their shelf header
// is a list row even while collapsed.
const v2ListEmpty =
hasSearchQuery && threadSearch.isPending && v2SnoozedCount === 0 ? null : hasSearchQuery ? (
v2SnoozedCount > 0 ? (
// The snoozed threads already passed this search filter: "No
// results" would claim nothing matched when matches are merely
// parked.
<EmptyState
title={
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
}
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
/>
) : (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
)
) : v2SnoozedCount > 0 ? (
<EmptyState
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
detail="Snoozed threads return when their wake time passes."
/>
hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : v2ScopedProjectGroup !== null ? (
<EmptyState
title={`No threads in ${v2ScopedProjectGroup.title}`}
@@ -998,7 +1055,7 @@ export function HomeScreen(props: HomeScreenProps) {
extraData={v2ExtraData}
ListHeaderComponent={v2ListHeader}
ListFooterComponent={
threadListV2Layout.hiddenSettledCount > 0 ? (
settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
<Pressable
accessibilityRole="button"
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
@@ -1,4 +1,6 @@
import { SymbolView } from "../../components/AppSymbol";
import { ControlPillMenu } from "../../components/ControlPill";
import type { MenuAction } from "@react-native-menu/menu";
import * as Haptics from "expo-haptics";
import {
createContext,
@@ -47,13 +49,67 @@ export const THREAD_SWIPE_SPRING = {
stiffness: 330,
};
interface ThreadSwipePrimaryAction {
interface ThreadSwipeAction {
readonly accessibilityLabel: string;
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly menu?: {
readonly actions: MenuAction[];
readonly onPressAction: NonNullable<ComponentProps<typeof ControlPillMenu>["onPressAction"]>;
readonly title?: string;
};
readonly onPress: () => void;
}
interface ThreadSwipeSecondaryAction extends ThreadSwipeAction {
readonly backgroundColor: string;
}
function swipeActionsWidth(hasSecondaryAction: boolean) {
return hasSecondaryAction ? THREAD_SWIPE_ACTIONS_WIDTH : ACTION_ITEM_WIDTH;
}
/** `undefined` keeps the v1 Delete default; `null` means one action only. */
function resolveSecondaryAction(input: {
readonly close: () => void;
readonly onDelete: () => void;
readonly secondaryAction: ThreadSwipeAction | null | undefined;
readonly threadTitle: string;
}): ThreadSwipeSecondaryAction | null {
if (input.secondaryAction === null) return null;
if (input.secondaryAction === undefined) {
return {
accessibilityLabel: `Delete ${input.threadTitle}`,
backgroundColor: "#ff2d55",
icon: "trash",
label: "Delete",
onPress: () => {
input.close();
input.onDelete();
},
};
}
const action = input.secondaryAction;
return {
...action,
backgroundColor: "#5856d6",
menu:
action.menu === undefined
? undefined
: {
...action.menu,
onPressAction: (event) => {
input.close();
action.menu?.onPressAction(event);
},
},
onPress: () => {
input.close();
action.onPress();
},
};
}
/**
* Delivers the scroll gate to swipeables via context so that flipping it does
* NOT re-render whole rows: putting the flag in list extraData/renderItem deps
@@ -173,17 +229,22 @@ export function ThreadSwipeable(props: {
readonly enabled?: boolean;
readonly enableTrackpadSwipe?: boolean;
/**
* What a full swipe commits: "delete" (default, v1 behavior — the Delete
* button stretches) or "primary" — the advertised primary action fires and
* its button stretches instead. A full swipe must always match the action
* the stretching button advertises.
* What a full swipe commits. Omitted keeps the v1 Delete behavior only when
* the built-in Delete secondary action is in use; custom or absent
* secondary actions default to the advertised primary action.
*/
readonly fullSwipeAction?: "delete" | "primary";
readonly fullSwipeWidth: number;
readonly onDelete: () => void;
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void;
readonly primaryAction: ThreadSwipePrimaryAction;
readonly primaryAction: ThreadSwipeAction;
/**
* Omitted keeps the v1 destructive Delete action. Explicit null opts out of
* a secondary action entirely so a gated Snooze can never fall back to an
* unadvertised Delete.
*/
readonly secondaryAction?: ThreadSwipeAction | null;
/**
* Identity of the content being wrapped. When a recycled list reuses this
* component for a different item, the swipeable snaps back to closed so an
@@ -197,7 +258,11 @@ export function ThreadSwipeable(props: {
}) {
const swipeableRef = useRef<SwipeableMethods | null>(null);
const fullSwipeArmedRef = useRef(false);
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, props.fullSwipeWidth * 0.58);
const hasSecondaryAction = props.secondaryAction !== null;
const actionsWidth = swipeActionsWidth(hasSecondaryAction);
const fullSwipeThreshold = Math.max(actionsWidth + 44, props.fullSwipeWidth * 0.58);
const fullSwipeAction =
props.fullSwipeAction ?? (props.secondaryAction === undefined ? "delete" : "primary");
const close = useCallback(() => swipeableRef.current?.close(), []);
const gateEnabled = use(SwipeableScrollGateContext);
const resetKey = props.resetKey;
@@ -251,7 +316,7 @@ export function ThreadSwipeable(props: {
if (fullSwipeArmedRef.current) {
fullSwipeArmedRef.current = false;
methods.close();
if (props.fullSwipeAction === "primary") {
if (fullSwipeAction === "primary") {
props.primaryAction.onPress();
} else {
props.onDelete();
@@ -264,9 +329,8 @@ export function ThreadSwipeable(props: {
<ThreadSwipeActions
backgroundColor={props.backgroundColor}
compact={props.compactActions === true}
fullSwipeAction={props.fullSwipeAction ?? "delete"}
fullSwipeAction={fullSwipeAction}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
primaryAction={{
...props.primaryAction,
@@ -275,12 +339,16 @@ export function ThreadSwipeable(props: {
props.primaryAction.onPress();
},
}}
swipeableMethods={methods}
threadTitle={props.threadTitle}
secondaryAction={resolveSecondaryAction({
close: () => methods.close(),
onDelete: props.onDelete,
secondaryAction: props.secondaryAction,
threadTitle: props.threadTitle,
})}
translation={translation}
/>
)}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
rightThreshold={actionsWidth * 0.42}
simultaneousWithExternalGesture={props.simultaneousWithExternalGesture}
>
{props.children(close)}
@@ -290,12 +358,14 @@ export function ThreadSwipeable(props: {
function SwipeActionButton(props: {
readonly accessibilityLabel: string;
readonly actionsWidth: number;
readonly backgroundColor: string;
readonly compact: boolean;
readonly entryRange: readonly [number, number];
readonly fullSwipeThreshold: number;
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly menu?: ThreadSwipeAction["menu"];
readonly onPress: () => void;
readonly stretchesOnFullSwipe: boolean;
readonly translation: SharedValue<number>;
@@ -305,10 +375,10 @@ function SwipeActionButton(props: {
const actionStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
const stretch = Math.max(reveal - props.actionsWidth, 0);
const fullSwipeProgress = interpolate(
reveal,
[THREAD_SWIPE_ACTIONS_WIDTH, props.fullSwipeThreshold + 20],
[props.actionsWidth, props.fullSwipeThreshold + 20],
[0, 1],
Extrapolation.CLAMP,
);
@@ -327,9 +397,7 @@ function SwipeActionButton(props: {
});
const circleStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const stretch = props.stretchesOnFullSwipe
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
: 0;
const stretch = props.stretchesOnFullSwipe ? Math.max(reveal - props.actionsWidth, 0) : 0;
return {
transform: [{ translateX: -stretch }],
@@ -338,9 +406,7 @@ function SwipeActionButton(props: {
});
const iconStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const stretch = props.stretchesOnFullSwipe
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
: 0;
const stretch = props.stretchesOnFullSwipe ? Math.max(reveal - props.actionsWidth, 0) : 0;
const armedProgress = interpolate(
reveal,
[props.fullSwipeThreshold, props.fullSwipeThreshold + 20],
@@ -358,7 +424,7 @@ function SwipeActionButton(props: {
}
const reveal = Math.max(-props.translation.value, 0);
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
const stretch = Math.max(reveal - props.actionsWidth, 0);
return {
opacity: interpolate(
reveal,
@@ -370,6 +436,63 @@ function SwipeActionButton(props: {
};
});
const button = (
<Pressable
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
onPress={props.menu === undefined ? props.onPress : undefined}
style={({ pressed }) => ({
alignItems: "center",
height: "100%",
justifyContent: "center",
opacity: pressed ? 0.72 : 1,
width: "100%",
})}
>
<View style={{ height: circleSize, width: circleSize }}>
<Animated.View
style={[
{
backgroundColor: props.backgroundColor,
borderRadius: 999,
height: circleSize,
left: 0,
position: "absolute",
top: 0,
},
circleStyle,
]}
/>
<Animated.View
style={[
{
alignItems: "center",
height: circleSize,
justifyContent: "center",
left: 0,
position: "absolute",
top: 0,
width: circleSize,
},
iconStyle,
]}
>
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
</Animated.View>
</View>
<Animated.View
style={[
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
labelStyle,
]}
>
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
{props.label}
</Text>
</Animated.View>
</Pressable>
);
return (
<Animated.View
style={[
@@ -383,60 +506,18 @@ function SwipeActionButton(props: {
actionStyle,
]}
>
<Pressable
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
onPress={props.onPress}
style={({ pressed }) => ({
alignItems: "center",
height: "100%",
justifyContent: "center",
opacity: pressed ? 0.72 : 1,
width: "100%",
})}
>
<View style={{ height: circleSize, width: circleSize }}>
<Animated.View
style={[
{
backgroundColor: props.backgroundColor,
borderRadius: 999,
height: circleSize,
left: 0,
position: "absolute",
top: 0,
},
circleStyle,
]}
/>
<Animated.View
style={[
{
alignItems: "center",
height: circleSize,
justifyContent: "center",
left: 0,
position: "absolute",
top: 0,
width: circleSize,
},
iconStyle,
]}
>
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
</Animated.View>
</View>
<Animated.View
style={[
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
labelStyle,
]}
{props.menu === undefined ? (
button
) : (
<ControlPillMenu
actions={props.menu.actions}
onPressAction={props.menu.onPressAction}
title={props.menu.title}
style={{ height: "100%", width: "100%" }}
>
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
{props.label}
</Text>
</Animated.View>
</Pressable>
{button}
</ControlPillMenu>
)}
</Animated.View>
);
}
@@ -446,14 +527,14 @@ export function ThreadSwipeActions(props: {
readonly compact: boolean;
readonly fullSwipeAction?: "delete" | "primary";
readonly fullSwipeThreshold: number;
readonly onDelete: () => void;
readonly onFullSwipeArmedChange: (armed: boolean) => void;
readonly primaryAction: ThreadSwipePrimaryAction;
readonly swipeableMethods: SwipeableMethods;
readonly threadTitle: string;
readonly primaryAction: ThreadSwipeAction;
readonly secondaryAction: ThreadSwipeSecondaryAction | null;
readonly translation: SharedValue<number>;
}) {
const fullSwipeIsPrimary = props.fullSwipeAction === "primary";
const secondaryAction = props.secondaryAction;
const fullSwipeIsPrimary = props.fullSwipeAction === "primary" || secondaryAction === null;
const actionsWidth = swipeActionsWidth(secondaryAction !== null);
useAnimatedReaction(
() => -props.translation.value >= props.fullSwipeThreshold,
(armed, previous) => {
@@ -470,14 +551,19 @@ export function ThreadSwipeActions(props: {
backgroundColor: props.backgroundColor,
flexDirection: "row",
height: "100%",
width: THREAD_SWIPE_ACTIONS_WIDTH,
width: actionsWidth,
}}
>
<SwipeActionButton
accessibilityLabel={props.primaryAction.accessibilityLabel}
actionsWidth={actionsWidth}
backgroundColor="#007aff"
compact={props.compact}
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
entryRange={
secondaryAction === null
? [8, ACTION_ITEM_WIDTH * 0.72]
: [ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]
}
fullSwipeThreshold={props.fullSwipeThreshold}
icon={props.primaryAction.icon}
label={props.primaryAction.label}
@@ -485,21 +571,22 @@ export function ThreadSwipeActions(props: {
stretchesOnFullSwipe={fullSwipeIsPrimary}
translation={props.translation}
/>
<SwipeActionButton
accessibilityLabel={`Delete ${props.threadTitle}`}
backgroundColor="#ff2d55"
compact={props.compact}
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
fullSwipeThreshold={props.fullSwipeThreshold}
icon="trash"
label="Delete"
onPress={() => {
props.swipeableMethods.close();
props.onDelete();
}}
stretchesOnFullSwipe={!fullSwipeIsPrimary}
translation={props.translation}
/>
{secondaryAction === null ? null : (
<SwipeActionButton
accessibilityLabel={secondaryAction.accessibilityLabel}
actionsWidth={actionsWidth}
backgroundColor={secondaryAction.backgroundColor}
compact={props.compact}
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
fullSwipeThreshold={props.fullSwipeThreshold}
icon={secondaryAction.icon}
label={secondaryAction.label}
menu={secondaryAction.menu}
onPress={secondaryAction.onPress}
stretchesOnFullSwipe={!fullSwipeIsPrimary}
translation={props.translation}
/>
)}
</View>
);
}
@@ -1,5 +1,5 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled";
import * as Cause from "effect/Cause";
import * as Haptics from "expo-haptics";
import { useCallback, useRef } from "react";
@@ -22,6 +22,13 @@ function environmentSupportsSettlement(environmentId: EnvironmentThreadShell["en
);
}
function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["environmentId"]) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadSnooze === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -192,9 +199,14 @@ export function useThreadListActions(): {
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
const snoozeInFlightThreadKeys = useRef(new Set<string>());
const archiveThread = useCallback(
(thread: EnvironmentThreadShell) => {
@@ -206,6 +218,94 @@ export function useThreadListActions(): {
async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,
[executeAction],
);
const snoozeThread = useCallback(
async (thread: EnvironmentThreadShell, snoozedUntil: string) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (snoozeInFlightThreadKeys.current.has(key)) {
return false;
}
snoozeInFlightThreadKeys.current.add(key);
try {
if (!environmentSupportsSnooze(thread.environmentId)) {
Alert.alert(
"Could not snooze thread",
"This environment's server does not support snoozing yet. Update the server to use Snooze.",
);
return false;
}
if (!canSnooze(thread, { now: new Date().toISOString() })) {
Alert.alert(
"Could not snooze thread",
thread.hasPendingApprovals || thread.hasPendingUserInput
? "This thread is waiting on you. Respond to the pending request before snoozing it."
: "This thread is still starting a turn. Try again once it's running.",
);
return false;
}
selectionHaptic();
const result = await snoozeMutation({
environmentId: thread.environmentId,
input: {
threadId: thread.id,
snoozedUntil,
},
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not snooze thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread could not be snoozed.",
);
return false;
}
return true;
} finally {
snoozeInFlightThreadKeys.current.delete(key);
}
},
[snoozeMutation],
);
const unsnoozeThread = useCallback(
async (thread: EnvironmentThreadShell) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (snoozeInFlightThreadKeys.current.has(key)) {
return false;
}
snoozeInFlightThreadKeys.current.add(key);
try {
if (!environmentSupportsSnooze(thread.environmentId)) {
Alert.alert(
"Could not wake thread",
"This environment's server does not support snoozing yet. Update the server to wake this thread.",
);
return false;
}
selectionHaptic();
const result = await unsnoozeMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id, reason: "user" },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not wake thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread could not be woken.",
);
return false;
}
return true;
} finally {
snoozeInFlightThreadKeys.current.delete(key);
}
},
[unsnoozeMutation],
);
const unsettleThread = useCallback(
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
[executeAction],
@@ -213,7 +313,14 @@ export function useThreadListActions(): {
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
return { archiveThread, confirmDeleteThread, settleThread, unsettleThread };
return {
archiveThread,
confirmDeleteThread,
settleThread,
snoozeThread,
unsnoozeThread,
unsettleThread,
};
}
export function useArchivedThreadListActions(
@@ -9,6 +9,8 @@ import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
import { holdEditingQueuedMessage } from "../../state/use-thread-outbox";
import { useWorkspaceState } from "../../state/workspace";
import {
applyNativeShowcaseOrientation,
getNativeShowcaseOrientation,
getNativeShowcasePairingUrls,
getNativeShowcaseScene,
markNativeShowcaseReady,
@@ -47,6 +49,7 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
const [pendingTasksReady, setPendingTasksReady] = useState(false);
const [requestedScene, setRequestedScene] = useState<ShowcaseScene | null>(null);
const [readyScene, setReadyScene] = useState<ShowcaseScene | null>(null);
const [orientationSettled, setOrientationSettled] = useState(false);
useEffect(() => {
if (!SHOWCASE_ENABLED || pairingUrls.length > 0) return;
@@ -60,6 +63,25 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
return () => clearInterval(interval);
}, [pairingUrls.length]);
useEffect(() => {
if (!SHOWCASE_ENABLED || orientationSettled) return;
const orientation = getNativeShowcaseOrientation();
if (orientation === null) {
setOrientationSettled(true);
return;
}
let cancelled = false;
void retryShowcaseOperation(async () => applyNativeShowcaseOrientation(orientation), {
isCancelled: () => cancelled,
}).then((applied) => {
if (!cancelled && applied) setOrientationSettled(true);
});
return () => {
cancelled = true;
};
}, [orientationSettled]);
useEffect(() => {
if (!SHOWCASE_ENABLED) return;
@@ -182,7 +204,10 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
scene === null ||
requestedScene === null ||
scene !== requestedScene ||
!hasFixture
!hasFixture ||
// Never report a scene ready while the capture orientation is still
// being applied — a screenshot taken early has the wrong dimensions.
!orientationSettled
) {
setReadyScene(null);
return;
@@ -210,7 +235,7 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
if (renderFrame !== null) cancelAnimationFrame(renderFrame);
if (readyFrame !== null) cancelAnimationFrame(readyFrame);
};
}, [hasFixture, requestedScene, scene]);
}, [hasFixture, orientationSettled, requestedScene, scene]);
if (!SHOWCASE_ENABLED || readyScene === null) return null;
@@ -3,9 +3,14 @@ import { requireOptionalNativeModule } from "expo";
export const SHOWCASE_SCENES = ["threads", "thread", "terminal", "review", "environments"] as const;
export type ShowcaseScene = (typeof SHOWCASE_SCENES)[number];
export type ShowcaseOrientation = "portrait" | "landscape";
interface NativeShowcaseControls {
readonly getShowcasePairingUrl?: () => string | null;
readonly getShowcaseScene?: () => string | null;
readonly getShowcaseOrientation?: () => string | null;
readonly applyShowcaseOrientation?: (orientation: ShowcaseOrientation) => Promise<void>;
readonly getInterfaceOrientation?: () => Promise<string>;
readonly prepareShowcaseCapture?: () => void;
readonly markShowcaseReady?: (scene: ShowcaseScene) => void;
}
@@ -59,6 +64,35 @@ export function prepareNativeShowcaseCapture(): void {
}
}
export function getNativeShowcaseOrientation(): ShowcaseOrientation | null {
try {
const orientation = nativeShowcaseControls()?.getShowcaseOrientation?.()?.trim();
return orientation === "portrait" || orientation === "landscape" ? orientation : null;
} catch {
return null;
}
}
export async function applyNativeShowcaseOrientation(
orientation: ShowcaseOrientation,
): Promise<boolean> {
const controls = nativeShowcaseControls();
if (!controls?.applyShowcaseOrientation || !controls.getInterfaceOrientation) {
// A development build that predates this helper keeps its default
// orientation; report success so callers do not retry forever.
return true;
}
try {
await controls.applyShowcaseOrientation(orientation);
// The geometry request settles asynchronously; confirm it took effect so
// callers can retry attempts made before the scene was foreground-active.
await new Promise((resolve) => setTimeout(resolve, 500));
return (await controls.getInterfaceOrientation()) === orientation;
} catch {
return false;
}
}
export function markNativeShowcaseReady(scene: ShowcaseScene): void {
try {
nativeShowcaseControls()?.markShowcaseReady?.(scene);
@@ -42,7 +42,8 @@ import {
restoreComposerDraftSnapshot,
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { useProjects } from "../../state/entities";
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
@@ -90,6 +91,9 @@ export function NewTaskDraftScreen(props: {
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
const { connectedEnvironments } = useRemoteConnectionStatus();
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
);
const environmentConnected =
selectedProject !== null &&
connectedEnvironments.find(
@@ -539,27 +543,7 @@ export function NewTaskDraftScreen(props: {
);
const modelMenuActions = useMemo(
() =>
flow.providerGroups.map((group) => ({
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: group.models.find(
(model) =>
flow.selectedModel &&
model.selection.instanceId === flow.selectedModel.instanceId &&
model.selection.model === flow.selectedModel.model,
)?.label,
subactions: group.models.map((option) => ({
id: `model:${option.key}`,
title: option.label,
state:
flow.selectedModel &&
option.selection.instanceId === flow.selectedModel.instanceId &&
option.selection.model === flow.selectedModel.model
? ("on" as const)
: undefined,
})),
})),
() => buildModelMenuActions(flow.providerGroups, flow.selectedModel),
[flow.providerGroups, flow.selectedModel],
);
const providerOptionDescriptors = useMemo(
@@ -795,7 +779,14 @@ export function NewTaskDraftScreen(props: {
return;
}
const draft = getComposerDraftSnapshot(draftKey);
const modelSelection = draft.modelSelection ?? flow.selectedModel;
// Snapshot read keeps just-typed selector state; the availability gate
// still applies so a stored selection on a disabled provider falls back
// to the flow's resolved model.
const modelSelection =
resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
draft.modelSelection ?? null,
) ?? flow.selectedModel;
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
const selectedWorktreePath =
@@ -847,7 +838,10 @@ export function NewTaskDraftScreen(props: {
if (editingPendingTask) {
flow.finishEditingPendingTask();
} else {
clearComposerDraftContent(draftKey);
// Drop the workspace selection with the content: the next task should
// re-resolve mode/branch/origin from the server's configured defaults
// instead of resurrecting this task's picks.
clearComposerDraftContent(draftKey, { clearWorkspaceSelection: true });
}
navigation.getParent()?.goBack();
return;
@@ -905,7 +899,7 @@ export function NewTaskDraftScreen(props: {
}
flow.finishEditingPendingTask();
} else {
clearComposerDraftContent(draftKey);
clearComposerDraftContent(draftKey, { clearWorkspaceSelection: true });
}
navigation.dispatch(
StackActions.replace("Thread", {
@@ -53,7 +53,7 @@ import {
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import type { RemoteClientConnectionState } from "../../lib/connection";
import {
@@ -606,25 +606,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
[providerOptionDescriptors],
);
const modelMenuActions = useMemo(
() =>
providerGroups.map((group) => ({
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: group.models.find(
(model) =>
model.selection.instanceId === currentModelSelection.instanceId &&
model.selection.model === currentModelSelection.model,
)?.label,
subactions: group.models.map((option) => ({
id: `model:${option.key}`,
title: option.label,
state:
option.selection.instanceId === currentModelSelection.instanceId &&
option.selection.model === currentModelSelection.model
? ("on" as const)
: undefined,
})),
})),
() => buildModelMenuActions(providerGroups, currentModelSelection),
[providerGroups, currentModelSelection],
);
@@ -67,7 +67,12 @@ import {
ThreadListRow,
ThreadListShowMoreRow,
} from "./thread-list-items";
import { ThreadListV2PendingRow, ThreadListV2Row } from "./thread-list-v2-items";
import {
ThreadListV2PendingRow,
ThreadListV2Row,
ThreadListV2SettledShelfHeader,
ThreadListV2SnoozedShelfHeader,
} from "./thread-list-v2-items";
import {
buildThreadListV2Items,
buildThreadListV2ListItems,
@@ -193,8 +198,14 @@ function ThreadNavigationSidebarPane(
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const headerIsOverContentRef = useRef(false);
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
useThreadListActions();
const {
archiveThread,
confirmDeleteThread,
settleThread,
snoozeThread,
unsnoozeThread,
unsettleThread,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
@@ -428,6 +439,10 @@ function ThreadNavigationSidebarPane(
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
[],
);
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
// now ticks per minute so the inactivity auto-settle boundary is actually
// crossed while the pane stays open; without a clock dependency the
// partition memoizes a frozen "now".
@@ -468,7 +483,15 @@ function ThreadNavigationSidebarPane(
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
return {
items: [],
hiddenSettledCount: 0,
snoozedCount: 0,
snoozedShelfHeaderIndex: null,
settledCount: 0,
settledShelfHeaderIndex: null,
nextSnoozeWakeAt: null,
};
return buildThreadListV2Items({
threads: threads.filter((thread) => thread.archivedAt === null),
environmentId: options.selectedEnvironmentId,
@@ -481,11 +504,17 @@ function ThreadNavigationSidebarPane(
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
snoozedShelfExpanded,
settledShelfExpanded,
selectedThreadKey: props.selectedThreadKey ?? null,
});
}, [
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
settledShelfExpanded,
props.selectedThreadKey,
options.selectedEnvironmentId,
props.searchQuery,
matchedThreadKeys,
@@ -532,8 +561,15 @@ function ThreadNavigationSidebarPane(
const items: SidebarListItem[] = buildThreadListV2ListItems({
items: threadListV2Layout.items,
pendingTasks: v2PendingTasks,
snoozedCount: threadListV2Layout.snoozedCount,
snoozedShelfExpanded,
snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
settledCount: threadListV2Layout.settledCount,
settledShelfExpanded,
settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
snoozeLabelNow: `${nowMinute}:00.000Z`,
});
if (threadListV2Layout.hiddenSettledCount > 0) {
if (settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0) {
items.push({
type: "v2-show-more",
key: "v2-show-more",
@@ -543,10 +579,13 @@ function ThreadNavigationSidebarPane(
return items;
}, [
listLayout.items,
nowMinute,
options.selectedEnvironmentId,
pendingTasks,
props.searchQuery,
selectedProjectRefs,
settledShelfExpanded,
snoozedShelfExpanded,
threadListV2Enabled,
threadListV2Layout,
]);
@@ -731,6 +770,7 @@ function ThreadNavigationSidebarPane(
projectTitleByProjectKey,
savedConnectionsById,
serverConfigs,
snoozePresetMinute: nowMinute,
threadSearchMatchByKey,
}),
[
@@ -740,6 +780,7 @@ function ThreadNavigationSidebarPane(
projectTitleByProjectKey,
savedConnectionsById,
serverConfigs,
nowMinute,
threadSearchMatchByKey,
],
);
@@ -750,7 +791,8 @@ function ThreadNavigationSidebarPane(
previous.key === item.key &&
previous.item.thread === item.item.thread &&
previous.item.variant === item.item.variant &&
previous.item.showSettledDivider === item.item.showSettledDivider
previous.item.snoozed === item.item.snoozed &&
previous.snoozeWakeLabelText === item.snoozeWakeLabelText
);
}
if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
@@ -762,13 +804,23 @@ function ThreadNavigationSidebarPane(
previous.showPendingDivider === item.showPendingDivider
);
}
if (previous.type === "v2-snoozed-shelf" && item.type === "v2-snoozed-shelf") {
return previous.count === item.count && previous.expanded === item.expanded;
}
if (previous.type === "v2-settled-shelf" && item.type === "v2-settled-shelf") {
return previous.count === item.count && previous.expanded === item.expanded;
}
if (
previous.type === "v2-thread" ||
previous.type === "v2-show-more" ||
previous.type === "v2-pending" ||
previous.type === "v2-snoozed-shelf" ||
previous.type === "v2-settled-shelf" ||
item.type === "v2-thread" ||
item.type === "v2-show-more" ||
item.type === "v2-pending"
item.type === "v2-pending" ||
item.type === "v2-snoozed-shelf" ||
item.type === "v2-settled-shelf"
) {
return false;
}
@@ -826,7 +878,9 @@ function ThreadNavigationSidebarPane(
<ThreadListV2Row
thread={thread}
variant={item.item.variant}
showSettledDivider={item.item.showSettledDivider}
snoozed={item.item.snoozed}
snoozePresetMinute={nowMinute}
snoozeWakeLabelText={item.snoozeWakeLabelText}
project={projectByKey.get(scopeKey) ?? null}
projectTitle={projectTitleByProjectKey.get(scopeKey)}
providerDriver={
@@ -860,6 +914,9 @@ function ThreadNavigationSidebarPane(
onArchiveThread={archiveThread}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={settleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
@@ -869,6 +926,24 @@ function ThreadNavigationSidebarPane(
/>
);
}
case "v2-snoozed-shelf":
return (
<ThreadListV2SnoozedShelfHeader
count={item.count}
expanded={item.expanded}
onToggle={toggleSnoozedShelf}
pane="sidebar"
/>
);
case "v2-settled-shelf":
return (
<ThreadListV2SettledShelfHeader
count={item.count}
expanded={item.expanded}
onToggle={toggleSettledShelf}
pane="sidebar"
/>
);
case "v2-show-more":
return (
<Pressable
@@ -984,7 +1059,13 @@ function ThreadNavigationSidebarPane(
settlementEnvironmentIds,
showMoreSettled,
sidebarScrollGesture,
snoozeEnvironmentIds,
snoozeThread,
nowMinute,
toggleSettledShelf,
toggleSnoozedShelf,
unsettleThread,
unsnoozeThread,
updateGroupDisplay,
],
);
@@ -1031,30 +1112,19 @@ function ThreadNavigationSidebarPane(
}),
[filterIcon, filterMenu, props.onOpenSettings],
);
// "No threads yet" over an inbox that is merely all-snoozed reads as
// data loss; name the snoozed threads instead.
const snoozedCount = threadListV2Layout.snoozedCount;
// Snoozed threads need no special case: the shelf header is a list row
// even while collapsed.
const listEmpty = (
<Text className="px-2 py-4 text-sm text-foreground-muted">
{catalogState.isLoadingConnections
? "Loading threads…"
: props.searchQuery.trim().length > 0
? threadSearch.isPending && snoozedCount === 0
? threadSearch.isPending
? "Searching thread messages…"
: snoozedCount > 0
? // Snoozed matches passed this same search filter — "No
// matching threads" would misreport them as nonexistent.
snoozedCount === 1
? "1 matching thread snoozed"
: "All matching threads snoozed"
: "No matching threads"
: snoozedCount > 0
? snoozedCount === 1
? "1 thread snoozed"
: `${snoozedCount} threads snoozed`
: selectedProjectScope !== null
? `No threads in ${selectedProjectScope.title}`
: "No threads yet"}
: "No matching threads"
: selectedProjectScope !== null
? `No threads in ${selectedProjectScope.title}`
: "No threads yet"}
</Text>
);
@@ -22,7 +22,11 @@ import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../
import type { TurnCommandMetadata } from "../../lib/commandMetadata";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import {
buildModelOptions,
groupByProvider,
resolveSelectableModelSelection,
} from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { appAtomRegistry } from "../../state/atom-registry";
@@ -347,7 +351,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
const prompt = selectedProjectDraft.text;
const attachments = selectedProjectDraft.attachments;
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
// The server's configured default decides the mode until the user picks one
// explicitly — same resolution web uses for new draft threads.
const defaultWorkspaceMode: WorkspaceMode =
selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local";
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode;
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
// Keep the user's explicit choice separate from the resolved display value:
@@ -361,22 +369,29 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
// Stored selections (draft and project default) only count while their
// provider is usable on the server; otherwise the server's default model
// wins instead of silently targeting a disabled provider.
const draftModelSelection = resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
selectedProjectDraft.modelSelection ?? null,
);
const projectDefaultModelSelection = resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection ?? null,
);
const modelOptions = useMemo(
() =>
buildModelOptions(
selectedEnvironmentServerConfig,
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
draftModelSelection ?? projectDefaultModelSelection,
),
[
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection,
selectedProjectDraft.modelSelection,
],
[selectedEnvironmentServerConfig, draftModelSelection, projectDefaultModelSelection],
);
const selectedModel =
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
draftModelSelection ??
projectDefaultModelSelection ??
modelOptions.find((option) => option.isDefault)?.selection ??
modelOptions[0]?.selection ??
null;
@@ -675,12 +690,20 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}
const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
const text = draft.text.trim();
const draftModelSelection = draft.modelSelection ?? selectedModel;
// Same availability gate the composer display applies: a stored
// selection targeting a disabled provider must not ride into the queue.
const draftModelSelection =
resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
draft.modelSelection ?? null,
) ?? selectedModel;
if (text.length === 0 || !draftModelSelection) {
return null;
}
const workspaceSelection = draft.workspaceSelection;
const mode = workspaceSelection?.mode ?? "local";
// Fall back to the resolved mode (server default) so queued tasks drain
// with the same mode the composer displayed.
const mode = workspaceSelection?.mode ?? workspaceMode;
// When the selection is the stand-in built from the queued snapshot,
// persist the original (possibly absent) snapshot values — the
// stand-in's placeholder title/workspaceRoot must never be written back
@@ -722,10 +745,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[
editingPendingProject,
editingPendingTask,
selectedEnvironmentServerConfig,
selectedModel,
selectedProject,
selectedProjectDraftKey,
startFromOrigin,
workspaceMode,
],
);
@@ -11,6 +11,7 @@ import {
import type { ReactNode } from "react";
import { Platform, useColorScheme } from "react-native";
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
@@ -35,10 +36,9 @@ const SIDEBAR_SCREEN_OPTIONS: SidebarScreenOptions = {
headerShadowVisible: false,
headerShown: true,
headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? { backgroundColor: "transparent" } : undefined,
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
...getCompactBrandHeaderOptions({ fontSize: 18, fontWeight: "800" }),
headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
scrollEdgeEffects: NATIVE_LIQUID_GLASS_SUPPORTED ? SCROLL_EDGE_EFFECTS : undefined,
title: "Threads",
unstable_navigationItemStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? "editor" : undefined,
};
@@ -15,6 +15,7 @@ import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { cn } from "../../lib/cn";
import { HOME_HORIZONTAL_INSET } from "../../lib/layoutMetrics";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
@@ -33,7 +34,7 @@ import { ThreadSearchMatchExcerpt } from "./thread-search-match";
export type ThreadListVariant = "compact" | "sidebar";
/** Left inset that aligns compact secondary rows with the title column. */
export const THREAD_LIST_COMPACT_INSET = 20;
export const THREAD_LIST_COMPACT_INSET = HOME_HORIZONTAL_INSET;
const SIDEBAR_ROW_RADIUS = 12;
function pullRequestTintColor(
@@ -3,11 +3,20 @@ import type {
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
import type { MenuAction } from "@react-native-menu/menu";
import { memo, useCallback, useEffect, useMemo, type ComponentProps } from "react";
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react";
import {
Alert,
Platform,
Pressable,
useColorScheme,
useWindowDimensions,
View,
} from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { ProjectFavicon } from "../../components/ProjectFavicon";
@@ -18,7 +27,13 @@ import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
import {
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozeGateExpiryMs,
resolveThreadListV2Status,
resolveThreadListV2SwipeActions,
type ThreadListV2Status,
} from "./threadListV2";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
/**
@@ -62,6 +77,11 @@ const SLIM_MENU_ACTIONS: MenuAction[] = [
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
const SNOOZED_MENU_ACTIONS: MenuAction[] = [
{ id: "unsnooze", title: "Wake thread", image: "clock" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
// Pre-settlement servers: no lifecycle items, archive fills the gap.
const LEGACY_MENU_ACTIONS: MenuAction[] = [
{ id: "archive", title: "Archive", image: "archivebox" },
@@ -90,6 +110,81 @@ export const ThreadListV2SectionDivider = memo(function ThreadListV2SectionDivid
);
});
const SNOOZE_ACCENT_LIGHT = "#2563eb";
const SNOOZE_ACCENT_DARK = "#60a5fa";
export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedShelfHeader(props: {
readonly count: number;
readonly expanded: boolean;
readonly onToggle: () => void;
readonly pane?: "screen" | "sidebar";
}) {
const colorScheme = useColorScheme();
return (
<Pressable
accessibilityHint={
props.expanded ? "Collapses the snoozed threads." : "Expands the snoozed threads."
}
accessibilityLabel={props.count === 1 ? "1 snoozed thread" : `${props.count} snoozed threads`}
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
className={cn(
"mb-1.5 mt-4 flex-row items-center gap-2.5",
props.pane === "sidebar" ? "px-3" : "px-5",
)}
onPress={props.onToggle}
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text className="text-xs font-t3-medium text-blue-600 dark:text-blue-400">
{props.expanded ? "Snoozed" : `Snoozed (${props.count})`}
</Text>
<View className="h-px flex-1 bg-blue-500/20 dark:bg-blue-400/15" />
<SymbolView
name={props.expanded ? "chevron.up" : "chevron.down"}
size={10}
tintColor={colorScheme === "dark" ? SNOOZE_ACCENT_DARK : SNOOZE_ACCENT_LIGHT}
type="monochrome"
/>
</Pressable>
);
});
export const ThreadListV2SettledShelfHeader = memo(function ThreadListV2SettledShelfHeader(props: {
readonly count: number;
readonly expanded: boolean;
readonly onToggle: () => void;
readonly pane?: "screen" | "sidebar";
}) {
const mutedColor = useThemeColor("--color-foreground-muted");
return (
<Pressable
accessibilityHint={
props.expanded ? "Collapses the settled threads." : "Expands the settled threads."
}
accessibilityLabel={props.count === 1 ? "1 settled thread" : `${props.count} settled threads`}
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
className={cn(
"mb-1.5 mt-4 flex-row items-center gap-2.5",
props.pane === "sidebar" ? "px-3" : "px-5",
)}
onPress={props.onToggle}
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text className="text-xs font-t3-medium text-foreground-tertiary">
{props.expanded ? "Settled" : `Settled (${props.count})`}
</Text>
<View className="h-px flex-1 bg-border" />
<SymbolView
name={props.expanded ? "chevron.up" : "chevron.down"}
size={10}
tintColor={mutedColor}
type="monochrome"
/>
</Pressable>
);
});
const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
@@ -208,7 +303,14 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly thread: EnvironmentThreadShell;
readonly variant: "card" | "slim";
readonly showSettledDivider: boolean;
/** Snoozed-shelf row: shows its wake time and offers Wake. */
readonly snoozed?: boolean;
/** Preformatted against the parent minute tick so this memoized row's
countdown keeps moving. */
readonly snoozeWakeLabelText?: string;
/** Parent minute tick passed as a prop so this memoized row refreshes its
native snooze menu while mounted. */
readonly snoozePresetMinute: string;
readonly project: EnvironmentProject | null;
readonly projectTitle?: string;
readonly providerDriver: string | null;
@@ -231,11 +333,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
/** False on environments whose server predates thread.settle/unsettle:
swipe + menu fall back to Archive instead of failing on use. */
readonly settlementSupported: boolean;
/** False on servers that predate thread.snooze/unsnooze. */
readonly snoozeSupported: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
/** Reports this row's live PR state up so the partition can auto-settle
@@ -258,10 +364,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onSelectThread,
onDeleteThread,
onSettleThread,
onSnoozeThread,
onUnsnoozeThread,
onUnsettleThread,
onArchiveThread,
onChangeRequestState,
} = props;
const snoozedRow = props.snoozed === true;
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
const prState = pr?.state ?? null;
@@ -283,27 +392,94 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
const handleSnooze = useCallback(
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
[onSnoozeThread, thread],
);
const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "settle") handleSettle();
if (nativeEvent.event === "unsettle") handleUnsettle();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "delete") handleDelete();
},
[handleArchive, handleDelete, handleSettle, handleUnsettle],
);
// Swipe: the v2 primary action is the lifecycle transition. Every settled
// row can un-settle — explicit settles clear the override, auto-settled
// rows get pinned active until real activity clears the pin.
const canUnsettle = variant === "slim";
const [snoozeGateTick, bumpSnoozeGateTick] = useState(0);
const snoozeGateExpiryMs = props.snoozeSupported
? resolveThreadListV2SnoozeGateExpiryMs(thread, { now: new Date().toISOString() })
: null;
useEffect(() => {
if (snoozeGateExpiryMs === null) return;
const delayMs = Math.min(Math.max(0, snoozeGateExpiryMs - Date.now()) + 50, 2_147_483_647);
const id = setTimeout(() => bumpSnoozeGateTick((tick) => tick + 1), delayMs);
return () => clearTimeout(id);
}, [snoozeGateExpiryMs, snoozeGateTick]);
const swipeActions = resolveThreadListV2SwipeActions({
variant,
settlementSupported: props.settlementSupported,
snoozeSupported: props.snoozeSupported,
snoozable: canSnooze(thread, { now: new Date().toISOString() }),
snoozed: snoozedRow,
});
const snoozePresets = useMemo(
() => (swipeActions.secondary === "snooze" ? resolveSnoozePresets(new Date()) : ([] as const)),
[props.snoozePresetMinute, swipeActions.secondary],
);
const snoozePresetActions = useMemo<MenuAction[]>(
() =>
snoozePresets.map((preset) => ({
id: `snooze:${preset.id}`,
title: preset.label,
subtitle: preset.whenLabel,
})),
[snoozePresets],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
{ id: "settle", title: "Settle", image: "checkmark" },
{
id: "snooze",
title: "Snooze",
image: "clock",
subactions: snoozePresetActions,
},
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[snoozePresetActions],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "settle") handleSettle();
if (nativeEvent.event === "unsettle") handleUnsettle();
if (nativeEvent.event === "unsnooze") handleUnsnooze();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
event: nativeEvent.event,
displayedPresets: snoozePresets,
now: new Date(),
});
if (snoozeSelection._tag === "selected") {
handleSnooze(snoozeSelection.preset.snoozedUntil);
} else if (snoozeSelection._tag === "expired") {
Alert.alert("Could not snooze thread", "That snooze time has passed. Choose another time.");
}
},
[
handleArchive,
handleDelete,
handleSettle,
handleSnooze,
handleUnsettle,
handleUnsnooze,
snoozePresets,
],
);
const primaryAction = useMemo(() => {
// Pre-settlement server: archive is the swipe action, as in v1. (Slim
// rows cannot occur here — unsupported environments never classify as
// settled.)
if (!props.settlementSupported) {
if (swipeActions.primary === "archive") {
return {
accessibilityLabel: `Archive ${thread.title}`,
icon: "archivebox" as const,
@@ -311,7 +487,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onPress: handleArchive,
};
}
return canUnsettle
if (swipeActions.primary === "unsnooze") {
return {
accessibilityLabel: `Wake ${thread.title} now`,
icon: "clock" as const,
label: "Wake",
onPress: handleUnsnooze,
};
}
return swipeActions.primary === "unsettle"
? {
accessibilityLabel: `Un-settle ${thread.title}`,
icon: "arrow.uturn.backward" as const,
@@ -325,13 +509,34 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onPress: handleSettle,
};
}, [
canUnsettle,
handleArchive,
handleSettle,
handleUnsettle,
props.settlementSupported,
handleUnsnooze,
swipeActions.primary,
thread.title,
]);
const secondaryAction = useMemo(
() =>
swipeActions.secondary === "snooze"
? {
accessibilityLabel: `Choose when to snooze ${thread.title}`,
icon: "clock" as const,
label: "Snooze",
menu: {
actions: snoozePresetActions,
onPressAction: handleMenuAction,
title: "Snooze until",
},
onPress: () => undefined,
}
: null,
[handleMenuAction, snoozePresetActions, swipeActions.secondary, thread.title],
);
const swipeAccessibilityHint =
secondaryAction === null
? `Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`
: `Opens the thread. Swipe left for ${primaryAction.label.toLowerCase()} and snooze actions.`;
// The sidebar pane fills selected rows with the accent color (matching the
// v1 sidebar), so every piece of row text needs a white-on-accent variant.
@@ -453,7 +658,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const rowContent = (close: () => void) =>
variant === "card" ? (
<Pressable
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
accessibilityHint={swipeAccessibilityHint}
accessibilityLabel={thread.title}
accessibilityRole="button"
accessibilityState={{ selected }}
@@ -491,7 +696,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
</Pressable>
) : (
<Pressable
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
accessibilityHint={swipeAccessibilityHint}
accessibilityLabel={thread.title}
accessibilityRole="button"
accessibilityState={{ selected }}
@@ -551,11 +756,17 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<Text
className={cn(
"text-sm tabular-nums",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
selected
? "text-user-bubble-foreground-muted"
: snoozedRow
? "text-blue-600 dark:text-blue-400"
: "text-foreground-tertiary",
)}
style={{ fontFamily: MONO_FONT }}
>
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
{snoozedRow && props.snoozeWakeLabelText !== undefined
? props.snoozeWakeLabelText
: relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
</Text>
</View>
</Pressable>
@@ -563,9 +774,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
return (
<>
{props.showSettledDivider ? (
<ThreadListV2SectionDivider label="Settled" pane={props.pane} />
) : null}
<ThreadSwipeable
backgroundColor={sidebarPane ? drawerColor : screenColor}
compactActions={variant === "slim"}
@@ -574,13 +782,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
}
enableTrackpadSwipe
// Full swipe commits the advertised lifecycle action (Settle /
// Un-settle), never the destructive delete.
// Un-settle), never the secondary snooze action.
fullSwipeAction="primary"
fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
onDelete={handleDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
primaryAction={primaryAction}
secondaryAction={secondaryAction}
resetKey={`${thread.environmentId}:${thread.id}`}
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
threadTitle={thread.title}
@@ -588,11 +797,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
{(close) => (
<ControlPillMenu
actions={
!props.settlementSupported
? LEGACY_MENU_ACTIONS
: canUnsettle
? SLIM_MENU_ACTIONS
: CARD_MENU_ACTIONS
snoozedRow
? SNOOZED_MENU_ACTIONS
: !props.settlementSupported
? LEGACY_MENU_ACTIONS
: canUnsettle
? SLIM_MENU_ACTIONS
: swipeActions.secondary === "snooze"
? snoozableCardMenuActions
: CARD_MENU_ACTIONS
}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
@@ -1,5 +1,6 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
import {
CommandId,
EnvironmentId,
@@ -16,7 +17,10 @@ import {
buildThreadListV2Items,
buildThreadListV2ListItems,
resolveThreadListV2Enabled,
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozeGateExpiryMs,
resolveThreadListV2Status,
resolveThreadListV2SwipeActions,
sortThreadsForListV2,
} from "./threadListV2";
@@ -50,6 +54,54 @@ function makeThread(
const NOW = "2026-06-02T00:00:00.000Z";
describe("resolveThreadListV2SnoozeMenuSelection", () => {
it("accepts a displayed evening preset while its wake time is still future", () => {
const menuOpenedAt = new Date(2026, 4, 8, 16, 59, 30);
const selectedAt = new Date(2026, 4, 8, 17, 0, 30);
const displayedPresets = resolveSnoozePresets(menuOpenedAt);
const selection = resolveThreadListV2SnoozeMenuSelection({
event: "snooze:evening",
displayedPresets,
now: selectedAt,
});
expect(selection).toEqual({
_tag: "selected",
preset: displayedPresets.find((preset) => preset.id === "evening"),
});
});
it("expires a displayed preset once its wake time has passed", () => {
const displayedPresets = resolveSnoozePresets(new Date(2026, 4, 8, 16, 59, 30));
expect(
resolveThreadListV2SnoozeMenuSelection({
event: "snooze:evening",
displayedPresets,
now: new Date(2026, 4, 8, 18, 0, 1),
}),
).toEqual({ _tag: "expired" });
});
it("recomputes presets that remain available instead of using old timestamps", () => {
const displayedPresets = resolveSnoozePresets(new Date(2026, 4, 8, 10));
const selectedAt = new Date(2026, 4, 8, 10, 30);
const selection = resolveThreadListV2SnoozeMenuSelection({
event: "snooze:hour",
displayedPresets,
now: selectedAt,
});
expect(selection._tag).toBe("selected");
if (selection._tag === "selected") {
expect(selection.preset.snoozedUntil).toBe(
new Date(selectedAt.getTime() + 60 * 60 * 1_000).toISOString(),
);
}
});
});
describe("resolveThreadListV2Enabled", () => {
it("defaults on when the device has never chosen", () => {
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true })).toBe(
@@ -96,6 +148,105 @@ describe("resolveThreadListV2Status", () => {
});
});
describe("resolveThreadListV2SwipeActions", () => {
it("offers settle and snooze for an active snoozable thread", () => {
expect(
resolveThreadListV2SwipeActions({
variant: "card",
settlementSupported: true,
snoozeSupported: true,
snoozable: true,
}),
).toEqual({ primary: "settle", secondary: "snooze" });
});
it("offers un-settle and snooze for settled history", () => {
expect(
resolveThreadListV2SwipeActions({
variant: "slim",
settlementSupported: true,
snoozeSupported: true,
snoozable: true,
}),
).toEqual({ primary: "unsettle", secondary: "snooze" });
});
it("omits snooze when the server or thread does not allow it", () => {
expect(
resolveThreadListV2SwipeActions({
variant: "card",
settlementSupported: true,
snoozeSupported: false,
snoozable: true,
}),
).toEqual({ primary: "settle", secondary: null });
expect(
resolveThreadListV2SwipeActions({
variant: "card",
settlementSupported: true,
snoozeSupported: true,
snoozable: false,
}),
).toEqual({ primary: "settle", secondary: null });
});
it("falls back to archive only for a pre-lifecycle server", () => {
expect(
resolveThreadListV2SwipeActions({
variant: "card",
settlementSupported: false,
snoozeSupported: false,
snoozable: true,
}),
).toEqual({ primary: "archive", secondary: null });
});
it("offers wake and no snooze on a snoozed row", () => {
expect(
resolveThreadListV2SwipeActions({
variant: "slim",
settlementSupported: true,
snoozeSupported: true,
snoozable: true,
snoozed: true,
}),
).toEqual({ primary: "unsnooze", secondary: null });
});
});
describe("resolveThreadListV2SnoozeGateExpiryMs", () => {
it("reports when an unadopted turn's grace window lapses", () => {
const thread = makeThread({
id: ThreadId.make("t"),
title: "t",
latestUserMessageAt: "2026-06-02T00:00:30.000Z",
});
expect(resolveThreadListV2SnoozeGateExpiryMs(thread, { now: "2026-06-02T00:01:00.000Z" })).toBe(
Date.parse("2026-06-02T00:02:30.000Z"),
);
});
it("returns null once the thread is snoozable or when only data can unblock it", () => {
expect(
resolveThreadListV2SnoozeGateExpiryMs(
makeThread({ id: ThreadId.make("ready"), title: "Ready" }),
{ now: NOW },
),
).toBe(null);
expect(
resolveThreadListV2SnoozeGateExpiryMs(
makeThread({
id: ThreadId.make("blocked"),
title: "Blocked",
hasPendingApprovals: true,
latestUserMessageAt: NOW,
}),
{ now: NOW },
),
).toBe(null);
});
});
describe("sortThreadsForListV2", () => {
it("orders by creation time, newest first, ignoring activity", () => {
const sorted = sortThreadsForListV2([
@@ -167,6 +318,93 @@ describe("buildThreadListV2Items", () => {
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
});
it("builds snoozed rows between active and settled when the shelf is expanded", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("settled"),
title: "Settled",
settledOverride: "settled",
settledAt: NOW,
}),
makeThread({
id: ThreadId.make("later"),
title: "Wakes later",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: ThreadId.make("sooner"),
title: "Wakes sooner",
snoozedUntil: "2026-06-02T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozedShelfExpanded: true,
});
expect(layout.items.map((item) => item.thread.id)).toEqual([
"active",
"sooner",
"later",
"settled",
]);
expect(layout.items.map((item) => item.snoozed)).toEqual([false, true, true, false]);
expect(layout.snoozedShelfHeaderIndex).toBe(1);
expect(layout.snoozedCount).toBe(2);
});
it("collapses to a header-only shelf", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("snoozed"),
title: "Snoozed",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
expect(layout.items).toEqual([]);
expect(layout.snoozedCount).toBe(1);
expect(layout.snoozedShelfHeaderIndex).toBe(0);
});
it("keeps the selected thread on a collapsed shelf", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("open"),
title: "Open",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: ThreadId.make("other"),
title: "Other",
snoozedUntil: "2026-06-03T10:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
selectedThreadKey: `${environmentId}:open`,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["open"]);
expect(layout.items[0]?.snoozed).toBe(true);
expect(layout.snoozedCount).toBe(2);
});
it("keeps snoozed threads visible on environments without the snooze capability", () => {
const layout = buildThreadListV2Items({
threads: [
@@ -187,8 +425,8 @@ describe("buildThreadListV2Items", () => {
expect(layout.snoozedCount).toBe(0);
});
it("partitions settled threads into a slim tail with one divider", () => {
const { items } = buildThreadListV2Items({
it("partitions settled threads into a slim shelf", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
@@ -209,13 +447,64 @@ describe("buildThreadListV2Items", () => {
now: NOW,
});
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
expect(layout.items.map((item) => [item.thread.id, item.variant])).toEqual([
["active", "card"],
["settled", "slim"],
["settled-2", "slim"],
]);
expect(items.map((item) => item.showSettledDivider)).toEqual([false, true, false]);
expect(items.map((item) => item.isLast)).toEqual([false, false, true]);
expect(layout.items.map((item) => item.isLast)).toEqual([false, false, true]);
expect(layout.settledCount).toBe(2);
expect(layout.settledShelfHeaderIndex).toBe(1);
});
it("collapses settled threads to a counted shelf header", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("settled"),
title: "Settled",
settledOverride: "settled",
settledAt: NOW,
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
settledShelfExpanded: false,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["active"]);
expect(layout.settledCount).toBe(1);
expect(layout.settledShelfHeaderIndex).toBe(1);
});
it("keeps the selected settled thread visible when its shelf is collapsed", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("selected"),
title: "Selected",
settledOverride: "settled",
settledAt: NOW,
}),
makeThread({
id: ThreadId.make("other"),
title: "Other",
settledOverride: "settled",
settledAt: NOW,
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
settledShelfExpanded: false,
selectedThreadKey: `${environmentId}:selected`,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["selected"]);
expect(layout.settledCount).toBe(2);
expect(layout.settledShelfHeaderIndex).toBe(0);
});
it("keeps cards in creation order while settled sorts by recency", () => {
@@ -420,13 +709,21 @@ describe("buildThreadListV2ListItems", () => {
const items = buildThreadListV2ListItems({
items: layout.items,
pendingTasks: [makePendingTask("queued-1"), makePendingTask("queued-2")],
settledCount: layout.settledCount,
settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
});
expect(
items.map((item) =>
item.type === "v2-pending" ? item.pendingTask.title : item.item.thread.id,
item.type === "v2-pending"
? item.pendingTask.title
: item.type === "v2-thread"
? item.item.thread.id
: item.type === "v2-snoozed-shelf"
? "snoozed-shelf"
: "settled-shelf",
),
).toEqual(["active", "queued-1", "queued-2", "settled"]);
).toEqual(["active", "queued-1", "queued-2", "settled-shelf", "settled"]);
// Only the leading queued row labels the section, exactly like Settled.
expect(
items.filter((item) => item.type === "v2-pending" && item.showPendingDivider),
@@ -448,12 +745,58 @@ describe("buildThreadListV2ListItems", () => {
expect(items.map((item) => item.type)).toEqual(["v2-thread", "v2-pending"]);
});
it("leaves the thread order untouched when nothing is queued", () => {
const items = buildThreadListV2ListItems({ items: layout.items, pendingTasks: [] });
it("keeps the settled shelf between active and settled rows when nothing is queued", () => {
const items = buildThreadListV2ListItems({
items: layout.items,
pendingTasks: [],
settledCount: layout.settledCount,
settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
});
expect(items.map((item) => item.key)).toEqual([
`v2-thread:${environmentId}:active`,
"v2-settled-shelf",
`v2-thread:${environmentId}:settled`,
]);
});
it("places queued tasks before a collapsed snoozed shelf", () => {
const snoozedLayout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "active" }),
makeThread({
id: ThreadId.make("snoozed"),
title: "snoozed",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: ThreadId.make("settled"),
title: "settled",
settledOverride: "settled",
settledAt: NOW,
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
const items = buildThreadListV2ListItems({
items: snoozedLayout.items,
pendingTasks: [makePendingTask("queued")],
snoozedCount: snoozedLayout.snoozedCount,
snoozedShelfExpanded: false,
snoozedShelfHeaderIndex: snoozedLayout.snoozedShelfHeaderIndex,
settledCount: snoozedLayout.settledCount,
settledShelfHeaderIndex: snoozedLayout.settledShelfHeaderIndex,
});
expect(items.map((item) => item.type)).toEqual([
"v2-thread",
"v2-pending",
"v2-snoozed-shelf",
"v2-settled-shelf",
"v2-thread",
]);
});
});
+207 -30
View File
@@ -1,10 +1,20 @@
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import {
effectiveSettled,
effectiveSnoozed,
hasQueuedTurnStart,
QUEUED_TURN_START_GRACE_MS,
resolveSnoozePresets,
snoozeWakeLabel,
} from "@t3tools/client-runtime/state/thread-settled";
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
export { snoozeWakeLabel };
/**
* Thread List v2 model, ported from the web sidebar v2
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
@@ -14,6 +24,76 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
* unlabeled resting state.
*/
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
export function resolveThreadListV2SnoozeMenuSelection(input: {
readonly event: string;
readonly displayedPresets: ReadonlyArray<SnoozePreset>;
readonly now: Date;
}):
| { readonly _tag: "selected"; readonly preset: SnoozePreset }
| { readonly _tag: "expired" }
| { readonly _tag: "not-snooze" } {
if (!input.event.startsWith("snooze:")) return { _tag: "not-snooze" };
const currentPreset = resolveSnoozePresets(input.now).find(
(candidate) => input.event === `snooze:${candidate.id}`,
);
if (currentPreset) return { _tag: "selected", preset: currentPreset };
const displayedPreset = input.displayedPresets.find(
(candidate) => input.event === `snooze:${candidate.id}`,
);
if (displayedPreset && Date.parse(displayedPreset.snoozedUntil) > input.now.getTime()) {
return { _tag: "selected", preset: displayedPreset };
}
return { _tag: "expired" };
}
export function resolveThreadListV2SwipeActions(input: {
readonly variant: "card" | "slim";
readonly settlementSupported: boolean;
readonly snoozeSupported: boolean;
readonly snoozable: boolean;
/** Row is on the snoozed shelf. */
readonly snoozed?: boolean;
}): {
readonly primary: Exclude<ThreadListV2SwipeAction, "snooze">;
readonly secondary: "snooze" | null;
} {
if (input.snoozed === true) {
return { primary: "unsnooze", secondary: null };
}
const primary = input.settlementSupported
? input.variant === "slim"
? "unsettle"
: "settle"
: "archive";
return {
primary,
secondary: input.snoozeSupported && input.snoozable ? "snooze" : null,
};
}
/**
* The point at which a queued-turn snooze guard expires on its own. Rows arm
* a one-shot timer for this boundary so Snooze appears without waiting for an
* unrelated render. User-blocked threads return null because only fresh
* server data can make them snoozable.
*/
export function resolveThreadListV2SnoozeGateExpiryMs(
thread: Pick<
EnvironmentThreadShell,
"hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
>,
options: { readonly now: string },
): number | null {
if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null;
if (!hasQueuedTurnStart(thread, options)) return null;
const messageAtMs = Date.parse(thread.latestUserMessageAt ?? "");
if (Number.isNaN(messageAtMs)) return null;
return messageAtMs + QUEUED_TURN_START_GRACE_MS;
}
// Settled-tail paging: recent history is the common lookup; the deep tail
// stays behind an explicit Show more. Shared by the compact Home list and
@@ -98,8 +178,8 @@ export function sortThreadsForListV2<T extends { readonly id: string; readonly c
export interface ThreadListV2Item {
readonly thread: EnvironmentThreadShell;
readonly variant: "card" | "slim";
/** First settled row after the card block draws the SETTLED divider. */
readonly showSettledDivider: boolean;
/** Snoozed-shelf row: shows the wake countdown and offers Wake. */
readonly snoozed: boolean;
readonly isLast: boolean;
}
@@ -107,10 +187,16 @@ export interface ThreadListV2Layout {
readonly items: ThreadListV2Item[];
/** Settled threads beyond the render limit (behind "Show more"). */
readonly hiddenSettledCount: number;
/** Snoozed threads hidden from the list (visibility parity with web's
collapsed Snoozed shelf; mobile has no shelf UI yet). */
/** Snoozed threads matching the current filters. */
readonly snoozedCount: number;
/** Soonest wake time among hidden snoozed threads, or null. Callers arm
/** Index in `items` where the Snoozed shelf header belongs. The header is
still rendered when the shelf is collapsed and no snoozed rows exist. */
readonly snoozedShelfHeaderIndex: number | null;
/** Total settled threads in scope, including rows hidden by collapse/paging. */
readonly settledCount: number;
/** Index in `items` where the Settled shelf header belongs. */
readonly settledShelfHeaderIndex: number | null;
/** Soonest wake time among snoozed threads, or null. Callers arm
a timeout at this boundary so the list re-partitions the moment a
snooze expires instead of on the next minute tick. */
readonly nextSnoozeWakeAt: string | null;
@@ -120,6 +206,8 @@ export interface ThreadListV2ThreadListItem {
readonly type: "v2-thread";
readonly key: string;
readonly item: ThreadListV2Item;
/** Precomputed so recycled-list equality can see a minute-tick change. */
readonly snoozeWakeLabelText: string | undefined;
}
export interface ThreadListV2PendingListItem {
@@ -130,28 +218,53 @@ export interface ThreadListV2PendingListItem {
readonly showPendingDivider: boolean;
}
export type ThreadListV2ListItem = ThreadListV2ThreadListItem | ThreadListV2PendingListItem;
export interface ThreadListV2SnoozedShelfListItem {
readonly type: "v2-snoozed-shelf";
readonly key: "v2-snoozed-shelf";
readonly count: number;
readonly expanded: boolean;
}
export interface ThreadListV2SettledShelfListItem {
readonly type: "v2-settled-shelf";
readonly key: "v2-settled-shelf";
readonly count: number;
readonly expanded: boolean;
}
export type ThreadListV2ListItem =
| ThreadListV2ThreadListItem
| ThreadListV2PendingListItem
| ThreadListV2SnoozedShelfListItem
| ThreadListV2SettledShelfListItem;
/**
* Splices queued tasks between the active block and the settled tail, so the
* list reads active → pending → settled. Queued work sits below the live
* threads because nothing can happen to it until its environment returns:
* it is waiting, not asking. Shared by the compact Home list and the iPad
* sidebar so both order and label the sections identically.
* Builds the shared mobile order: active → pending → snoozed shelf → settled.
* Pending tasks are waiting rather than asking, and parked work remains
* reachable without competing with either the inbox or settled history.
*/
export function buildThreadListV2ListItems(input: {
readonly items: ReadonlyArray<ThreadListV2Item>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
readonly snoozedCount?: number;
readonly snoozedShelfExpanded?: boolean;
readonly snoozedShelfHeaderIndex?: number | null;
readonly settledCount?: number;
readonly settledShelfExpanded?: boolean;
readonly settledShelfHeaderIndex?: number | null;
readonly snoozeLabelNow?: string;
}): ThreadListV2ListItem[] {
const threadItems = input.items.map(
(item): ThreadListV2ListItem => ({
type: "v2-thread",
key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
item,
snoozeWakeLabelText:
item.snoozed && item.thread.snoozedUntil != null && input.snoozeLabelNow !== undefined
? snoozeWakeLabel(item.thread.snoozedUntil, { now: input.snoozeLabelNow })
: undefined,
}),
);
if (input.pendingTasks.length === 0) return threadItems;
const pendingItems = input.pendingTasks.map(
(pendingTask, index): ThreadListV2ListItem => ({
type: "v2-pending",
@@ -160,14 +273,32 @@ export function buildThreadListV2ListItems(input: {
showPendingDivider: index === 0,
}),
);
// The settled tail begins at the row that draws the SETTLED divider; with
// no settled rows the queued block simply ends the list.
const settledStart = threadItems.findIndex(
(entry) => entry.type === "v2-thread" && entry.item.showSettledDivider,
);
return settledStart === -1
? [...threadItems, ...pendingItems]
: [...threadItems.slice(0, settledStart), ...pendingItems, ...threadItems.slice(settledStart)];
const snoozedCount = input.snoozedCount ?? 0;
const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null;
const settledCount = input.settledCount ?? 0;
const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null;
const activeEnd = snoozedShelfHeaderIndex ?? settledShelfHeaderIndex ?? threadItems.length;
const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length;
const result: ThreadListV2ListItem[] = [...threadItems.slice(0, activeEnd), ...pendingItems];
if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) {
result.push({
type: "v2-snoozed-shelf",
key: "v2-snoozed-shelf",
count: snoozedCount,
expanded: input.snoozedShelfExpanded === true,
});
result.push(...threadItems.slice(snoozedShelfHeaderIndex, snoozedEnd));
}
if (settledShelfHeaderIndex !== null && settledCount > 0) {
result.push({
type: "v2-settled-shelf",
key: "v2-settled-shelf",
count: settledCount,
expanded: input.settledShelfExpanded !== false,
});
result.push(...threadItems.slice(settledShelfHeaderIndex));
}
return result;
}
/**
@@ -204,6 +335,13 @@ export function buildThreadListV2Items(input: {
second-precise, so classifying with the floored minute would hold a
woken thread hidden for up to a minute. Defaults to `now`. */
readonly snoozeNow?: string;
/** Expands the snoozed shelf into rows. Collapsed is the default. */
readonly snoozedShelfExpanded?: boolean;
/** Expands the settled shelf into rows. Expanded is the default. */
readonly settledShelfExpanded?: boolean;
/** The selected thread remains visible on an otherwise collapsed shelf so
a split-view detail can never lose its navigation row. */
readonly selectedThreadKey?: string | null;
}): ThreadListV2Layout {
const now = input.now ?? new Date().toISOString();
const snoozeNow = input.snoozeNow ?? now;
@@ -215,7 +353,7 @@ export function buildThreadListV2Items(input: {
const active: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
let snoozedCount = 0;
const snoozed: EnvironmentThreadShell[] = [];
let nextSnoozeWakeAt: string | null = null;
for (const thread of input.threads) {
// Callers pass live (unarchived) shells; settled threads are among them
@@ -244,7 +382,7 @@ export function buildThreadListV2Items(input: {
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
// work). Snooze outranks settled classification, same as web.
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
snoozedCount += 1;
snoozed.push(thread);
if (
thread.snoozedUntil != null &&
(nextSnoozeWakeAt === null ||
@@ -265,24 +403,60 @@ export function buildThreadListV2Items(input: {
}
const orderedActive = sortThreadsForListV2(active);
const orderedSnoozed = [...snoozed].sort(
(left, right) =>
parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
);
const selectedThreadKey = input.selectedThreadKey ?? null;
const visibleSnoozed =
input.snoozedShelfExpanded === true
? orderedSnoozed
: orderedSnoozed.filter(
(thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
);
const orderedSettled = [...settled].sort(
(left, right) =>
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
);
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
const visibleSettled =
const pagedSettled =
orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
const selectedSettled = orderedSettled
.slice(pagedSettled.length)
.find((thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey);
if (selectedSettled !== undefined) pagedSettled.push(selectedSettled);
const visibleSettled =
input.settledShelfExpanded !== false
? pagedSettled
: pagedSettled.filter(
(thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
);
const items: ThreadListV2Item[] = [];
for (const thread of orderedActive) {
items.push({ thread, variant: "card", showSettledDivider: false, isLast: false });
items.push({
thread,
variant: "card",
snoozed: false,
isLast: false,
});
}
for (const [index, thread] of visibleSettled.entries()) {
const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
for (const thread of visibleSnoozed) {
items.push({
thread,
variant: "slim",
showSettledDivider: index === 0,
snoozed: true,
isLast: false,
});
}
const settledShelfHeaderIndex = orderedSettled.length > 0 ? items.length : null;
for (const thread of visibleSettled) {
items.push({
thread,
variant: "slim",
snoozed: false,
isLast: false,
});
}
@@ -292,8 +466,11 @@ export function buildThreadListV2Items(input: {
}
return {
items,
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
snoozedCount,
hiddenSettledCount: orderedSettled.length - pagedSettled.length,
snoozedCount: orderedSnoozed.length,
snoozedShelfHeaderIndex,
settledCount: orderedSettled.length,
settledShelfHeaderIndex,
nextSnoozeWakeAt,
};
}
-8
View File
@@ -65,14 +65,6 @@ export async function pickComposerImages(input: { readonly existingCount: number
};
}
const permission = await imagePicker.requestMediaLibraryPermissionsAsync();
if (!permission.granted) {
return {
images: [],
error: "Allow photo library access to attach images.",
};
}
const result = await imagePicker.launchImageLibraryAsync({
mediaTypes: ["images"],
allowsMultipleSelection: true,
+5
View File
@@ -0,0 +1,5 @@
/** Horizontal inset shared by the home header and compact thread list. */
export const HOME_HORIZONTAL_INSET = 20;
/** Compensates for the tighter native sidebar title margin on iPad. */
export const IPAD_HOME_TITLE_OFFSET = 10;
@@ -0,0 +1,14 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveMobileStageLabel } from "./mobileBranding";
describe("resolveMobileStageLabel", () => {
it.each([
["development", "Dev"],
["preview", "Nightly"],
["production", "Alpha"],
[undefined, "Alpha"],
])("maps %s builds to %s", (appVariant, expected) => {
expect(resolveMobileStageLabel(appVariant)).toBe(expected);
});
});
+7
View File
@@ -0,0 +1,7 @@
export type MobileStageLabel = "Alpha" | "Dev" | "Nightly";
export function resolveMobileStageLabel(appVariant: unknown): MobileStageLabel {
if (appVariant === "development") return "Dev";
if (appVariant === "preview") return "Nightly";
return "Alpha";
}
+126 -1
View File
@@ -2,9 +2,92 @@ import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
import { buildModelOptions } from "./modelOptions";
import {
buildModelMenuActions,
buildModelOptions,
groupByProvider,
resolveSelectableModelSelection,
} from "./modelOptions";
describe("mobile model options", () => {
it("folds legacy models into a provider-scoped menu", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
displayName: "Codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [
{
slug: "gpt-5.6-sol",
name: "GPT-5.6 Sol",
isCustom: false,
capabilities: null,
},
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
},
],
} as unknown as ServerConfig;
const actions = buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null);
expect(actions).toMatchObject([
{
title: "Codex",
subactions: [{ id: "model:codex:gpt-5.6-sol", title: "GPT-5.6 Sol" }],
},
{
id: "legacy-models:codex",
title: "Codex legacy models",
subactions: [{ id: "model:codex:gpt-5.4", title: "GPT-5.4" }],
},
]);
});
it("omits an empty provider menu when every model is legacy", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
displayName: "Codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
},
],
} as unknown as ServerConfig;
expect(
buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null),
).toMatchObject([
{
id: "legacy-models:codex",
title: "Codex legacy models",
subactions: [{ id: "model:codex:gpt-5.4" }],
},
]);
});
it("normalizes a legacy fallback selection against current capabilities", () => {
const config = {
providers: [
@@ -49,4 +132,46 @@ describe("mobile model options", () => {
expect(option?.capabilities?.optionDescriptors?.[0]?.id).toBe("serviceTier");
expect(option?.selection.options).toEqual([{ id: "serviceTier", value: "default" }]);
});
it("rejects stored selections whose provider is not usable", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [],
},
{
instanceId: "claudeAgent",
driver: "claudeAgent",
enabled: false,
installed: true,
auth: { status: "authenticated" },
models: [],
},
],
} as unknown as ServerConfig;
const usable = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.6-sol",
};
const disabled = {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-5",
};
const removed = {
instanceId: ProviderInstanceId.make("codex_personal"),
model: "gpt-5.6-sol",
};
expect(resolveSelectableModelSelection(config, usable)).toBe(usable);
expect(resolveSelectableModelSelection(config, disabled)).toBeNull();
expect(resolveSelectableModelSelection(config, removed)).toBeNull();
// No config (environment offline) — nothing to validate against.
expect(resolveSelectableModelSelection(null, disabled)).toBe(disabled);
});
});
+79
View File
@@ -3,6 +3,7 @@ import type {
ModelSelection,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import {
buildProviderOptionSelectionsFromDescriptors,
getProviderOptionDescriptors,
@@ -16,6 +17,7 @@ export type ModelOption = {
readonly providerLabel: string;
readonly providerDriver: string;
readonly isDefault: boolean;
readonly isLegacy: boolean;
readonly capabilities: ModelCapabilities | null;
readonly selection: ModelSelection;
};
@@ -58,6 +60,31 @@ function normalizeSelectionOptions(
};
}
/**
* A stored model selection is only usable when its provider instance is
* currently enabled, installed, and authenticated on the server. Returns the
* selection unchanged when usable, otherwise `null` so callers fall through to
* the server's default model. A missing config (environment offline) cannot be
* validated, so stored selections pass through untouched.
*/
export function resolveSelectableModelSelection(
config: T3ServerConfig | null | undefined,
selection: ModelSelection | null,
): ModelSelection | null {
if (!selection || !config) {
return selection;
}
const provider = config.providers.find(
(candidate) => candidate.instanceId === selection.instanceId,
);
return provider &&
provider.enabled &&
provider.installed &&
provider.auth.status !== "unauthenticated"
? selection
: null;
}
export function buildModelOptions(
config: T3ServerConfig | null | undefined,
fallbackModelSelection: ModelSelection | null,
@@ -80,6 +107,7 @@ export function buildModelOptions(
providerLabel,
providerDriver: provider.driver,
isDefault: model.isDefault === true,
isLegacy: model.isLegacy === true,
capabilities: model.capabilities,
selection: normalizeSelectionOptions(
{
@@ -110,6 +138,7 @@ export function buildModelOptions(
providerLabel,
providerDriver: fallbackModelSelection.instanceId,
isDefault: false,
isLegacy: false,
capabilities: null,
selection: fallbackModelSelection,
});
@@ -139,3 +168,53 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
models: group.models,
}));
}
function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
return {
id: `model:${option.key}`,
title: option.label,
state:
option.selection.instanceId === selectedModel?.instanceId &&
option.selection.model === selectedModel.model
? "on"
: undefined,
};
}
export function buildModelMenuActions(
groups: ReadonlyArray<ProviderGroup>,
selectedModel: ModelSelection | null,
): MenuAction[] {
return groups.flatMap((group) => {
const currentModels = group.models.filter((model) => !model.isLegacy);
const legacyModels = group.models.filter((model) => model.isLegacy);
const selected = group.models.find(
(model) =>
model.selection.instanceId === selectedModel?.instanceId &&
model.selection.model === selectedModel.model,
);
return [
...(currentModels.length > 0
? [
{
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: selected && !selected.isLegacy ? selected.label : undefined,
subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
...(legacyModels.length > 0
? [
{
id: `legacy-models:${group.providerKey}`,
title: `${group.providerLabel} legacy models`,
subtitle: selected?.isLegacy ? selected.label : undefined,
subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
];
});
}
+2 -1
View File
@@ -370,7 +370,8 @@ function NativeHeaderToolbarRoot(props: {
const navigation = useNativeStackNavigation();
const items = useMemo(() => collectToolbarItems(props.children), [props.children]);
useEffect(() => {
// Swap toolbar owners before paint so split and compact headers cannot clear each other.
useLayoutEffect(() => {
if (!navigation) {
return;
}
@@ -1,5 +1,6 @@
import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
import { requireNativeView } from "expo";
import { TextInputWrapper } from "expo-paste-input";
import {
useCallback,
useEffect,
@@ -9,12 +10,13 @@ import {
useState,
type Ref,
} from "react";
import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native";
import type { NativeSyntheticEvent, ViewProps } from "react-native";
import { Image, StyleSheet } from "react-native";
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
import { resolveMarkdownFileIcon } from "@t3tools/mobile-markdown-text/links";
import { MOBILE_TYPOGRAPHY } from "../lib/typography";
import { useNativePaste } from "../lib/useNativePaste";
import { useFontFamily } from "../lib/useFontFamily";
import { useThemeColor } from "../lib/useThemeColor";
import {
@@ -117,6 +119,7 @@ export function ComposerEditor({
const skillBorder = useThemeColor("--color-inline-skill-border");
const skillText = useThemeColor("--color-inline-skill-foreground");
const fileTint = useThemeColor("--color-icon-muted");
const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
useImperativeHandle(
ref,
@@ -221,61 +224,63 @@ export function ComposerEditor({
const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
const regularFontFamily = useFontFamily("regular");
return (
<NativeView
ref={nativeRef}
controlledDocumentJson={controlledDocumentJson}
themeJson={themeJson}
placeholder={props.placeholder ?? ""}
fontFamily={
typeof resolvedTextStyle.fontFamily === "string"
? resolvedTextStyle.fontFamily
: regularFontFamily
}
fontSize={
typeof resolvedTextStyle.fontSize === "number"
? resolvedTextStyle.fontSize
: MOBILE_TYPOGRAPHY.body.fontSize
}
lineHeight={
typeof resolvedTextStyle.lineHeight === "number"
? resolvedTextStyle.lineHeight
: MOBILE_TYPOGRAPHY.body.lineHeight
}
contentInsetVertical={contentInsetVertical}
singleLineCentered={props.singleLineCentered ?? false}
editable={props.editable ?? true}
scrollEnabled={props.scrollEnabled ?? true}
autoFocus={props.autoFocus ?? false}
autoCorrect={props.autoCorrect ?? true}
spellCheck={props.spellCheck ?? true}
style={style as StyleProp<ViewStyle>}
onComposerChange={(event) => {
const acknowledgedEventCount = acceptNativeEvent(
event.nativeEvent.eventCount,
event.nativeEvent.value,
event.nativeEvent.selection,
);
if (acknowledgedEventCount === false) return;
onChangeText(event.nativeEvent.value);
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
}}
onComposerSelectionChange={(event) => {
const acknowledgedEventCount = acceptNativeEvent(
event.nativeEvent.eventCount,
event.nativeEvent.value,
event.nativeEvent.selection,
);
if (acknowledgedEventCount === false) return;
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
}}
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
onComposerFocus={onFocus}
onComposerBlur={onBlur}
/>
<TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
<NativeView
ref={nativeRef}
controlledDocumentJson={controlledDocumentJson}
themeJson={themeJson}
placeholder={props.placeholder ?? ""}
fontFamily={
typeof resolvedTextStyle.fontFamily === "string"
? resolvedTextStyle.fontFamily
: regularFontFamily
}
fontSize={
typeof resolvedTextStyle.fontSize === "number"
? resolvedTextStyle.fontSize
: MOBILE_TYPOGRAPHY.body.fontSize
}
lineHeight={
typeof resolvedTextStyle.lineHeight === "number"
? resolvedTextStyle.lineHeight
: MOBILE_TYPOGRAPHY.body.lineHeight
}
contentInsetVertical={contentInsetVertical}
singleLineCentered={props.singleLineCentered ?? false}
editable={props.editable ?? true}
scrollEnabled={props.scrollEnabled ?? true}
autoFocus={props.autoFocus ?? false}
autoCorrect={props.autoCorrect ?? true}
spellCheck={props.spellCheck ?? true}
style={{ flex: 1, minHeight: 0 }}
onComposerChange={(event) => {
const acknowledgedEventCount = acceptNativeEvent(
event.nativeEvent.eventCount,
event.nativeEvent.value,
event.nativeEvent.selection,
);
if (acknowledgedEventCount === false) return;
onChangeText(event.nativeEvent.value);
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
}}
onComposerSelectionChange={(event) => {
const acknowledgedEventCount = acceptNativeEvent(
event.nativeEvent.eventCount,
event.nativeEvent.value,
event.nativeEvent.selection,
);
if (acknowledgedEventCount === false) return;
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
}}
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
onComposerFocus={onFocus}
onComposerBlur={onBlur}
/>
</TextInputWrapper>
);
}
@@ -119,6 +119,36 @@ describe("mobile composer drafts", () => {
});
});
it("drops the workspace selection when clearing a sent new-task draft", () => {
const draftKey = "new-task:environment-1:project-1";
const draft: ComposerDraft = {
text: "send this",
attachments: [],
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
startFromOrigin: false,
},
};
expect(
clearComposerDraftContentState({ [draftKey]: draft }, draftKey, {
clearWorkspaceSelection: true,
}),
).toEqual({
[draftKey]: {
modelSelection: draft.modelSelection,
text: "",
attachments: [],
},
});
});
it("reads the latest selector state synchronously for send", () => {
const draftKey = "environment-1:thread-1";
const selectedDraft: ComposerDraft = {
+10 -3
View File
@@ -372,14 +372,18 @@ export function updateComposerDraftSettings(
export function clearComposerDraftContentState(
current: Record<string, ComposerDraft>,
draftKey: string,
options?: { readonly clearWorkspaceSelection?: boolean },
): Record<string, ComposerDraft> {
const existing = current[draftKey];
if (!existing) {
return current;
}
const { importedShareIds: _importedShareIds, ...retained } = existing;
const { importedShareIds: _importedShareIds, workspaceSelection, ...retained } = existing;
const draft = {
...retained,
...(options?.clearWorkspaceSelection || workspaceSelection === undefined
? {}
: { workspaceSelection }),
text: "",
attachments: [],
};
@@ -526,8 +530,11 @@ export async function restoreComposerDraftSnapshot(
await persistenceQueue.run(() => writePersistedComposerDrafts(next));
}
export function clearComposerDraftContent(draftKey: string): void {
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
export function clearComposerDraftContent(
draftKey: string,
options?: { readonly clearWorkspaceSelection?: boolean },
): void {
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
}
export function clearComposerDraft(draftKey: string): void {
+1 -1
View File
@@ -16,7 +16,7 @@
"type": "module",
"scripts": {
"dev": "node --watch src/bin.ts",
"build:bundle": "vp pack",
"build:bundle": "vp pack && vp pack src/service-launcher.ts --out-dir dist --no-clean",
"start": "node dist/bin.mjs",
"typecheck": "tsgo --noEmit",
"test": "vp test run"
+5 -1
View File
@@ -223,7 +223,11 @@ const publishCmd = Command.make(
const packageJsonPath = path.join(serverDir, "package.json");
// Assert build assets exist
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
for (const relPath of [
"dist/bin.mjs",
"dist/service-launcher.mjs",
"dist/client/index.html",
]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new ServerCliBuildAssetMissingError({ assetPath: abs });
+4
View File
@@ -9,11 +9,13 @@ import * as NetService from "@t3tools/shared/Net";
import packageJson from "../package.json" with { type: "json" };
import { authCommand } from "./cli/auth.ts";
import { connectCommand } from "./cli/connect.ts";
import { pairCommand } from "./cli/pair.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
import { serviceCommand } from "./cli/service.ts";
import { servicePreflightCommand } from "./cli/servicePreflight.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -48,9 +50,11 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
Command.withSubcommands([
startCommand,
serveCommand,
pairCommand,
authCommand,
projectCommand,
serviceCommand,
servicePreflightCommand,
cloudEnabled ? connectCommand : connectUnavailableCommand,
]),
);
+6 -2
View File
@@ -1,3 +1,5 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import { assert, expect, it } from "@effect/vitest";
@@ -56,8 +58,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
const encoded = yield* encodeDesktopBootstrap(payload);
yield* fs.writeFileString(filePath, `${encoded}\n`);
const { fd } = yield* fs.open(filePath, { flag: "r" });
return fd;
return yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
});
it.effect("falls back to effect/config values when flags are omitted", () =>
+1 -1
View File
@@ -466,7 +466,7 @@ export const DurationFromString = Schema.String.pipe(
return Effect.succeed(duration);
}
return Effect.fail(
new SchemaIssue.InvalidValue(Option.some(value), {
new SchemaIssue.InvalidValue({
message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
}),
);
+268
View File
@@ -0,0 +1,268 @@
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
import * as NodeHttp from "node:http";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NetService from "@t3tools/shared/Net";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/unstable/cli";
import { cli } from "../bin.ts";
import {
makePersistedServerRuntimeState,
persistServerRuntimeState,
type PersistedServerRuntimeState,
} from "../serverRuntimeState.ts";
import {
DevServerNotProxiableError,
resolveDirectPairingBaseUrl,
resolveTailscaleLocalTarget,
} from "./pair.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
const baseState = {
version: 1,
pid: 123,
port: 3_773,
origin: "http://127.0.0.1:3773",
startedAt: "2026-06-20T00:00:00.000Z",
} as const satisfies PersistedServerRuntimeState;
describe("pair base URL selection", () => {
it("pairs through the dev web origin when the server fronts a dev server", () => {
expect(resolveDirectPairingBaseUrl({ ...baseState, devUrl: "http://localhost:5733/" })).toBe(
"http://localhost:5733/",
);
});
it("pairs through the bound host when there is no dev server", () => {
expect(resolveDirectPairingBaseUrl({ ...baseState, host: "100.64.0.7" })).toBe(
"http://100.64.0.7:3773",
);
expect(resolveDirectPairingBaseUrl(baseState)).toBe("http://localhost:3773");
});
});
describe("pair tailscale local target", () => {
it("proxies the dev web port for dev servers", () => {
expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
{ localPort: 5_733 },
);
// A dev server on a non-loopback interface must be proxied at that
// interface; tailscale serve defaults to 127.0.0.1 otherwise.
expect(
resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://192.168.1.10:5733/" }),
).toEqual({ localPort: 5_733, localHost: "192.168.1.10" });
// URL.hostname keeps IPv6 brackets, so the serve target stays valid.
expect(
resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[fd7a:115c::1]:5733/" }),
).toEqual({ localPort: 5_733, localHost: "[fd7a:115c::1]" });
});
it("rejects HTTPS dev URLs, which tailscale serve cannot proxy", () => {
expect(
resolveTailscaleLocalTarget({ ...baseState, devUrl: "https://localhost:5733/" }),
).toBeInstanceOf(DevServerNotProxiableError);
});
it("proxies the backend port directly otherwise", () => {
expect(resolveTailscaleLocalTarget(baseState)).toEqual({ localPort: 3_773 });
expect(resolveTailscaleLocalTarget({ ...baseState, host: "0.0.0.0" })).toEqual({
localPort: 3_773,
});
expect(resolveTailscaleLocalTarget({ ...baseState, host: "192.168.1.42" })).toEqual({
localPort: 3_773,
localHost: "192.168.1.42",
});
});
});
const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
const provideCliTestLayers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.provide(effect, Layer.mergeAll(CliRuntimeLayer, TestConsole.layer));
// Console output accumulates across CLI runs within a test, and each
// Console.log call is one entry — so the latest command's output is the last
// entry, even when it spans many lines.
const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
provideCliTestLayers(
Effect.gen(function* () {
yield* effect;
return (
(yield* TestConsole.logLines).findLast(
(line): line is string => typeof line === "string",
) ?? ""
);
}),
);
const testDescriptor = {
environmentId: "pair-test-environment",
label: "pair-test",
platform: { os: "linux", arch: "x64" },
serverVersion: "0.0.1",
capabilities: { repositoryIdentity: true },
};
const withDescriptorServer = <A, E, R>(run: (origin: string) => Effect.Effect<A, E, R>) =>
Effect.acquireUseRelease(
Effect.callback<NodeHttp.Server>((resume) => {
const server = NodeHttp.createServer((request, response) => {
if (request.url === "/.well-known/t3/environment") {
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify(testDescriptor));
return;
}
response.writeHead(404);
response.end();
});
server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server)));
}),
(server) => {
const address = server.address();
if (address === null || typeof address === "string") {
return Effect.die(new Error("Expected a TCP address"));
}
return run(`http://127.0.0.1:${String(address.port)}`);
},
(server) => Effect.sync(() => server.close()),
);
describe("t3 pair", () => {
it.effect("mints a token and prints a QR pairing URL for a live server", () =>
withDescriptorServer((origin) =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-test-"));
const port = Number(new URL(origin).port);
const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
yield* persistServerRuntimeState({
path: statePath,
state: yield* makePersistedServerRuntimeState({
config: { host: "127.0.0.1", devUrl: undefined },
port,
}),
});
const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
assert.include(output, `Pairing with pair-test (${origin})`);
assert.include(output, `Pairing URL: ${origin}/pair#token=`);
assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
// Loopback origins are not reachable from a phone; the output must say so.
assert.include(output, "only reachable from this machine");
const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
assert.isString(token);
// The token must be in the same store the running server reads.
const listed = yield* captureStdout(
runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const credentials = JSON.parse(listed) as ReadonlyArray<{ readonly label?: string }>;
assert.equal(credentials.length, 1);
assert.equal(credentials[0]?.label, "t3 pair");
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("pairs through the recorded dev web URL for dev servers", () =>
withDescriptorServer((origin) =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-dev-test-"));
const port = Number(new URL(origin).port);
const statePath = NodePath.join(baseDir, "dev", "server-runtime.json");
yield* persistServerRuntimeState({
path: statePath,
state: yield* makePersistedServerRuntimeState({
config: { host: undefined, devUrl: new URL("http://localhost:5733") },
port,
}),
});
const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
assert.include(output, "Pairing URL: http://localhost:5733/pair#token=");
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("directs to t3 serve or t3 connect when no server is running", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-none-test-"));
const error = yield* provideCliTestLayers(
runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
);
const rendered = String(
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
);
assert.include(rendered, "No running T3 Code server found.");
assert.include(rendered, "npx t3 serve");
assert.include(rendered, "npx t3 connect");
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
withDescriptorServer((origin) =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-pid-test-"));
const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
// The origin answers (another server reused the port), but the pid
// that wrote this state file is dead — pairing must not mint a token
// into the dead server's database.
const state = yield* makePersistedServerRuntimeState({
config: { host: "127.0.0.1", devUrl: undefined },
port: Number(new URL(origin).port),
});
yield* persistServerRuntimeState({
path: statePath,
// pid 2**22 + 1 exceeds any default Linux/macOS pid range.
state: { ...state, pid: 4_194_305 },
});
const error = yield* provideCliTestLayers(
runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
);
const rendered = String(
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
);
assert.include(rendered, "No running T3 Code server found.");
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("ignores stale runtime state pointing at a dead server", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-stale-test-"));
const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
// A port from the dynamic range with nothing listening: the probe fails
// fast with ECONNREFUSED and discovery moves on.
yield* persistServerRuntimeState({
path: statePath,
state: yield* makePersistedServerRuntimeState({
config: { host: "127.0.0.1", devUrl: undefined },
port: 1,
}),
});
const error = yield* provideCliTestLayers(
runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
);
const rendered = String(
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
);
assert.include(rendered, "No running T3 Code server found.");
}).pipe(Effect.provide(NodeServices.layer)),
);
});
+542
View File
@@ -0,0 +1,542 @@
/**
* `t3 pair` - mint a pairing token for an already-running server and print it
* as a QR code, without restarting anything.
*
* Discovery reads the `server-runtime.json` a live server persists next to its
* database, then confirms the process is actually answering by fetching its
* public environment descriptor. Inside a linked git worktree the worktree's
* own `.t3` is checked first (matching dev-runner precedence); otherwise the
* shared T3 home. `--tailscale` publishes the server over Tailscale Serve
* HTTPS and pairs through the tailnet URL instead.
*/
import {
AuthStandardClientScopes,
ExecutionEnvironmentDescriptor,
PortSchema,
} from "@t3tools/contracts";
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
import {
buildTailscaleHttpsBaseUrl,
DEFAULT_TAILSCALE_SERVE_PORT,
ensureTailscaleServe,
readTailscaleStatus,
} from "@t3tools/tailscale";
import * as Config from "effect/Config";
import * as Console from "effect/Console";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
HttpClientResponse,
} from "effect/unstable/http";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerConfig from "../config.ts";
import { resolveBaseDir } from "../os-jank.ts";
import {
type PersistedServerRuntimeState,
readPersistedServerRuntimeState,
} from "../serverRuntimeState.ts";
import {
buildPairingUrl,
formatHostForUrl,
isLoopbackHost,
isWildcardHost,
renderTerminalQrCode,
resolveHeadlessConnectionString,
} from "../startupAccess.ts";
import { baseDirFlag, DurationFromString } from "./config.ts";
const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment";
const PAIR_PROBE_TIMEOUT = Duration.millis(2_500);
// Tailscale provisions an HTTPS certificate on the first request to a fresh
// serve mapping, which can take a few seconds.
const TAILSCALE_PROBE_ATTEMPTS = 5;
const TAILSCALE_PROBE_RETRY_DELAY = Duration.seconds(1);
export type PairStateVariant = "userdata" | "dev";
// deriveServerPaths only checks devUrl for undefined-ness when picking the
// dev-vs-userdata state directory; the value itself is not used.
const DEV_VARIANT_PLACEHOLDER_URL = new URL("http://localhost");
export class NoRunningServerError extends Schema.TaggedErrorClass<NoRunningServerError>()(
"NoRunningServerError",
{
checkedStatePaths: Schema.Array(Schema.String),
},
) {
override get message(): string {
return [
"No running T3 Code server found.",
...this.checkedStatePaths.map((statePath) => ` checked ${statePath}`),
"Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
].join("\n");
}
}
// Each tailscale failure gets its own class (same reasoning as
// scripts/lib/dev-share.ts): distinct caller-visible message, distinct remedy.
export class TailscaleUnavailableError extends Schema.TaggedErrorClass<TailscaleUnavailableError>()(
"TailscaleUnavailableError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.";
}
}
export class MagicDnsNameMissingError extends Schema.TaggedErrorClass<MagicDnsNameMissingError>()(
"MagicDnsNameMissingError",
{},
) {
override get message(): string {
return "This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.";
}
}
export class ServesOtherEnvironmentError extends Schema.TaggedErrorClass<ServesOtherEnvironmentError>()(
"ServesOtherEnvironmentError",
{ servePort: Schema.Number },
) {
override get message(): string {
return `Tailscale Serve on HTTPS port ${String(this.servePort)} already fronts a different T3 Code server. Pass --tailscale-serve-port to publish this one on another port.`;
}
}
export class TailscaleServeFailedError extends Schema.TaggedErrorClass<TailscaleServeFailedError>()(
"TailscaleServeFailedError",
{ servePort: Schema.Number, cause: Schema.Defect() },
) {
override get message(): string {
return `tailscale serve failed for HTTPS port ${String(this.servePort)}. Run \`tailscale serve --https=${String(this.servePort)} --bg <local-url>\` by hand to see why.`;
}
}
export class ServePortOccupiedError extends Schema.TaggedErrorClass<ServePortOccupiedError>()(
"ServePortOccupiedError",
{ servePort: Schema.Number },
) {
override get message(): string {
return `HTTPS port ${String(this.servePort)} on the tailnet already serves something that is not a T3 Code server. Pass --tailscale-serve-port to publish this one on another port.`;
}
}
/** The URL a browser or phone should pair through, absent Tailscale. */
export const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>
state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);
export class DevServerNotProxiableError extends Schema.TaggedErrorClass<DevServerNotProxiableError>()(
"DevServerNotProxiableError",
{ devUrl: Schema.String },
) {
override get message(): string {
return `Tailscale Serve can only proxy plain-HTTP local targets, and this dev server runs at ${this.devUrl}. Pair without --tailscale instead.`;
}
}
const isDevServerNotProxiableError = Schema.is(DevServerNotProxiableError);
/**
* The local endpoint Tailscale Serve should proxy to. Dev servers are
* single-origin, so the web dev server's port is the one to publish; the
* backend rides along behind Vite's proxy. Serve targets are always plain
* HTTP, so an HTTPS dev URL cannot be proxied and is rejected.
*/
export const resolveTailscaleLocalTarget = (
state: PersistedServerRuntimeState,
): { readonly localPort: number; readonly localHost?: string } | DevServerNotProxiableError => {
if (state.devUrl !== undefined) {
const devUrl = new URL(state.devUrl);
if (devUrl.protocol !== "http:") {
return new DevServerNotProxiableError({ devUrl: state.devUrl });
}
const localPort = devUrl.port.length > 0 ? Number.parseInt(devUrl.port, 10) : 80;
return isLoopbackHost(devUrl.hostname)
? { localPort }
: { localPort, localHost: devUrl.hostname };
}
// A server bound to one specific interface does not answer on loopback, so
// the proxy has to target that interface directly.
if (state.host !== undefined && !isWildcardHost(state.host) && !isLoopbackHost(state.host)) {
return { localPort: state.port, localHost: formatHostForUrl(state.host) };
}
return { localPort: state.port };
};
export const formatPairOutput = (input: {
readonly serverLabel: string;
readonly origin: string;
readonly pairingUrl: string;
readonly token: string;
readonly expiresAt: DateTime.Utc;
readonly notes: ReadonlyArray<string>;
}): string =>
[
`Pairing with ${input.serverLabel} (${input.origin}).`,
"",
renderTerminalQrCode(input.pairingUrl),
"",
`Pairing URL: ${input.pairingUrl}`,
`Token: ${input.token}`,
`Expires: ${DateTime.formatIso(input.expiresAt)}`,
...input.notes.flatMap((note) => ["", `Note: ${note}`]),
"",
].join("\n");
/**
* Three outcomes, because they drive different decisions: a T3 descriptor
* (pair with it), nothing answering (safe to configure Tailscale Serve), or
* something answering that is not a T3 server (do NOT overwrite its mapping).
*/
type EnvironmentProbeResult =
| { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }
| { readonly _tag: "unreachable" }
| { readonly _tag: "not-a-t3-server" };
const probeEnvironmentDescriptor = (
baseUrl: string,
): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>
Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
const response = yield* client.execute(request).pipe(
Effect.timeout(PAIR_PROBE_TIMEOUT),
// Transport failure or timeout: nothing (reachable) is listening there.
Effect.mapError(() => ({ _tag: "unreachable" }) as const),
);
// Bad-gateway family means a proxy (Tailscale Serve) answered for a
// backend that is gone — a stale mapping, not a live occupant. Treating
// it as unreachable lets `t3 pair --tailscale` repair its own mapping
// after the server's port changed.
if (response.status === 502 || response.status === 503 || response.status === 504) {
return { _tag: "unreachable" } as const;
}
// Anything else that answered HTTP but not with a valid descriptor is
// some other service.
const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(
Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
);
return { _tag: "descriptor", descriptor } as const;
}).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));
// signal 0 delivers nothing; it only reports whether the pid exists. EPERM
// means it exists but belongs to another user, which still counts as alive.
const isProcessAlive = (pid: number): boolean => {
try {
process.kill(pid, 0);
return true;
} catch (error) {
return error instanceof Error && "code" in error && error.code === "EPERM";
}
};
interface DiscoveredPairTarget {
readonly baseDir: string;
readonly variant: PairStateVariant;
readonly state: PersistedServerRuntimeState;
readonly descriptor: ExecutionEnvironmentDescriptor;
}
const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* (
explicitBaseDir: string | undefined,
) {
const bases: Array<string> = [];
if (explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0) {
bases.push(yield* resolveBaseDir(explicitBaseDir));
} else {
// Same precedence as dev-runner: inside a linked worktree its own `.t3`
// outranks the shared home, so `t3 pair` in a worktree pairs with the dev
// server under test rather than the daily-driver install.
const worktreeHome = yield* resolveWorktreeT3Home(process.cwd());
if (worktreeHome !== undefined) {
bases.push(worktreeHome);
}
const envHome = yield* Config.string("T3CODE_HOME").pipe(Config.option);
bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));
}
const checkedStatePaths: Array<string> = [];
for (const baseDir of new Set(bases)) {
for (const variant of ["userdata", "dev"] as const) {
const derivedPaths = yield* ServerConfig.deriveServerPaths(
baseDir,
variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
{},
);
const statePath = derivedPaths.serverRuntimeStatePath;
checkedStatePaths.push(statePath);
const state = yield* readPersistedServerRuntimeState(statePath);
if (Option.isNone(state)) {
continue;
}
// The pid check guards against a dead server's state file whose port
// was since reused by a different server: pairing would then mint a
// token in the old database while the QR code points at the new server.
if (!isProcessAlive(state.value.pid)) {
continue;
}
const probed = yield* probeEnvironmentDescriptor(state.value.origin);
if (probed._tag !== "descriptor") {
continue;
}
return {
baseDir,
variant,
state: state.value,
descriptor: probed.descriptor,
} satisfies DiscoveredPairTarget;
}
}
return yield* new NoRunningServerError({ checkedStatePaths });
});
/**
* Server config pointed at the discovered server's state directory, so the
* minted token lands in the database the running server reads from. Built by
* hand rather than through `resolveServerConfig` to keep the dev-vs-userdata
* choice pinned to where the runtime state was actually found, independent of
* ambient environment variables.
*/
const makePairServerConfig = Effect.fn(function* (input: {
readonly target: DiscoveredPairTarget;
readonly logLevel: ServerConfig.ServerConfig["Service"]["logLevel"];
}) {
const { baseDir, variant, state } = input.target;
// The state-dir variant does not imply dev-ness: a worktree dev server uses
// an explicit home and therefore lands in `userdata`. The recorded devUrl is
// what actually marks a dev server.
const devUrl = state.devUrl !== undefined ? new URL(state.devUrl) : undefined;
const derivedPaths = yield* ServerConfig.deriveServerPaths(
baseDir,
variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
{},
);
return ServerConfig.make({
logLevel: input.logLevel,
traceMinLevel: "Info",
traceTimingEnabled: false,
traceBatchWindowMs: 1_000,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
mode: "web",
port: state.port,
host: state.host,
cwd: process.cwd(),
baseDir,
...derivedPaths,
staticDir: undefined,
devUrl,
devAllowedOrigins: [],
noBrowser: true,
startupPresentation: "headless",
desktopBootstrapToken: undefined,
desktopTelemetryFd: undefined,
desktopTelemetryControlFd: undefined,
resourceMonitorPath: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
});
});
const awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {
let last: EnvironmentProbeResult = { _tag: "unreachable" };
for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {
last = yield* probeEnvironmentDescriptor(baseUrl);
if (last._tag === "descriptor") {
return last;
}
yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);
}
return last;
});
const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase")(
function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {
const notes: Array<string> = [];
const status = yield* readTailscaleStatus.pipe(
Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),
);
if (status.magicDnsName === null) {
return yield* new MagicDnsNameMissingError();
}
const baseUrl = buildTailscaleHttpsBaseUrl({
magicDnsName: status.magicDnsName,
servePort: input.servePort,
});
// Only an unreachable port, or a mapping already fronting this exact
// environment, is safe to (re)configure. Any other responder — T3 or not
// — must not have its mapping silently replaced.
const existing = yield* probeEnvironmentDescriptor(baseUrl);
if (existing._tag === "descriptor") {
if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {
return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
}
// Matching environment id proves the mapping reaches this server, but
// not through which port: for a dev server it may front the backend
// (whose /.well-known also answers) while /pair only renders through
// the web origin. Reuse as-is for regular servers; fall through and
// repoint our own mapping at the web port for dev servers.
if (input.target.state.devUrl === undefined) {
return { baseUrl, notes };
}
}
if (existing._tag === "not-a-t3-server") {
return yield* new ServePortOccupiedError({ servePort: input.servePort });
}
const localTarget = resolveTailscaleLocalTarget(input.target.state);
if (isDevServerNotProxiableError(localTarget)) {
return yield* localTarget;
}
yield* ensureTailscaleServe({
localPort: localTarget.localPort,
servePort: input.servePort,
...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
}).pipe(
Effect.mapError(
(cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
),
);
notes.push(
`Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
);
const probed = yield* awaitEnvironmentDescriptor(baseUrl);
if (probed._tag === "descriptor") {
if (probed.descriptor.environmentId !== input.target.descriptor.environmentId) {
return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
}
} else {
notes.push(
"The HTTPS endpoint has not answered yet. First use can take a moment while Tailscale provisions certificates.",
);
}
return { baseUrl, notes };
},
);
const mintPairingLink = Effect.fn("pair.mintPairingLink")(function* (input: {
readonly config: ServerConfig.ServerConfig["Service"];
readonly ttl: Option.Option<Duration.Duration>;
readonly label: Option.Option<string>;
}) {
return yield* Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
return yield* environmentAuth.createPairingLink({
scopes: AuthStandardClientScopes,
subject: "one-time-token",
label: Option.getOrElse(input.label, () => "t3 pair"),
...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),
});
}).pipe(
Effect.provide(
EnvironmentAuth.runtimeLayer.pipe(
Layer.provide(ServerConfig.layer(input.config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),
),
),
);
});
const ttlFlag = Flag.string("ttl").pipe(
Flag.withSchema(DurationFromString),
Flag.withDescription(
"Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.",
),
Flag.optional,
);
const labelFlag = Flag.string("label").pipe(
Flag.withDescription("Optional label shown in the server's connections list."),
Flag.optional,
);
const tailscaleFlag = Flag.boolean("tailscale").pipe(
Flag.withDescription(
"Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.",
),
Flag.withDefault(false),
);
const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale is enabled."),
Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),
);
export const pairCommand = Command.make("pair", {
baseDir: baseDirFlag,
ttl: ttlFlag,
label: labelFlag,
tailscale: tailscaleFlag,
tailscaleServePort: tailscaleServePortFlag,
}).pipe(
Command.withDescription(
"Mint a pairing token for a running T3 Code server and print it as a QR code.",
),
Command.withHandler((flags) =>
Effect.gen(function* () {
const cliLogLevel = yield* GlobalFlag.LogLevel;
// Default to Warn so storage/migration chatter cannot bury the QR code;
// an explicit --log-level still wins.
const logLevel = Option.getOrElse(cliLogLevel, () => "Warn" as const);
const target = yield* discoverPairTarget(Option.getOrUndefined(flags.baseDir));
const notes: Array<string> = [];
let pairingBaseUrl: string;
if (flags.tailscale) {
const resolved = yield* resolveTailscalePairingBase({
target,
servePort: flags.tailscaleServePort,
});
pairingBaseUrl = resolved.baseUrl;
notes.push(...resolved.notes);
} else {
pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);
if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {
notes.push(
"This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
);
}
if (target.variant === "dev" && target.state.devUrl === undefined) {
notes.push(
"This dev server did not record its web URL; restart it so pairing can go through the web origin.",
);
}
}
const config = yield* makePairServerConfig({ target, logLevel });
const issued = yield* mintPairingLink({ config, ttl: flags.ttl, label: flags.label });
const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);
yield* Console.log(
formatPairOutput({
serverLabel: target.descriptor.label,
origin: target.state.origin,
pairingUrl,
token: issued.credential,
expiresAt: issued.expiresAt,
notes,
}),
);
}).pipe(Effect.provide(FetchHttpClient.layer)),
),
);
+3 -1
View File
@@ -337,7 +337,9 @@ const dispatchLiveOrchestrationCommand = (
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
return yield* projectionSnapshotQuery.getSnapshot();
// Project commands only read the project list, so use the lightweight
// command read model instead of hydrating every thread body in the database.
return yield* projectionSnapshotQuery.getCommandReadModel();
});
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
+17
View File
@@ -0,0 +1,17 @@
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import { Command, Flag } from "effect/unstable/cli";
import { runServicePreflight } from "../cloud/servicePreflight.ts";
export const servicePreflightCommand = Command.make("__service-preflight", {
databasePath: Flag.string("database-path"),
launcherProtocol: Flag.integer("launcher-protocol"),
}).pipe(
Command.withHidden,
Command.withHandler(({ databasePath, launcherProtocol }) =>
Console.log(JSON.stringify(runServicePreflight({ databasePath, launcherProtocol }))).pipe(
Effect.asVoid,
),
),
);
@@ -96,6 +96,15 @@ describe("CloudManagedEndpointRuntime", () => {
"2026-06-17T02:00:00Z INF Starting metrics server",
),
).toBe("debug");
// FTL (fatal) and PNC (panic) are more severe than ERR and must surface.
expect(
ManagedEndpointRuntime.classifyRelayClientOutput(
"2026-06-17T02:00:00Z FTL Cannot determine default origin certificate path",
),
).toBe("warning");
expect(
ManagedEndpointRuntime.classifyRelayClientOutput("2026-06-17T02:00:00Z PNC runtime panic"),
).toBe("warning");
});
it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
@@ -72,7 +72,10 @@ export function classifyRelayClientOutput(line: string): "connected" | "warning"
if (/\bRegistered tunnel connection\b/iu.test(line)) {
return "connected";
}
return /\b(?:ERR|WRN)\b/u.test(line) ? "warning" : "debug";
// cloudflared uses zerolog level tokens. FTL (fatal) and PNC (panic) are more
// severe than ERR, so they must surface at least as loudly — without them a
// fatal connector failure would be logged at debug and hidden.
return /\b(?:ERR|WRN|FTL|PNC)\b/u.test(line) ? "warning" : "debug";
}
function runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string {
+108 -515
View File
@@ -1,558 +1,151 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { expect, it } from "@effect/vitest";
import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { reconcileService } from "../cli/service.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as BootService from "./bootService.ts";
import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
import { parseServiceState } from "./serviceProtocol.ts";
const isUnsupportedError = Schema.is(BootService.BootServiceUnsupportedError);
const isCommandError = Schema.is(BootService.BootServiceCommandError);
interface RecordedCommand {
readonly command: string;
readonly args: ReadonlyArray<string>;
}
const makeRecordingRunnerLayer = (
commands: Array<RecordedCommand>,
options?: {
readonly failCommand?: string;
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
},
) =>
Layer.succeed(
ProcessRunner.ProcessRunner,
ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.sync(() => {
assert.isUndefined(input.env);
commands.push({ command: input.command, args: input.args });
const failed =
input.command === options?.failCommand ||
options?.failWhen?.(input.command, input.args) === true;
return {
stdout: "",
stderr: failed ? `${input.command} exploded` : "",
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
}),
);
const makeHost = (entry: string): BootService.BootServiceHost => ({
execPath: "/usr/local/bin/node",
cliEntryPath: entry,
});
const provideHostRefs = (home: string, platform: NodeJS.Platform = "linux") =>
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, platform),
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
),
);
const makeTestContext = Effect.fn("test.makeTestContext")(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
// A real file for the stable-entry cases so status can confirm the entry
// point exists.
const stableEntry = path.join(root, "bin.mjs");
yield* fs.writeFileString(stableEntry, "#!/usr/bin/env node\n");
return {
fs,
path,
dirs: {
home: root,
baseDir: path.join(root, ".t3"),
logsDir: path.join(root, ".t3", "userdata", "logs"),
stableEntry,
},
};
});
it("renders a systemd unit with absolute paths and append-mode logging", () => {
it("keeps systemd pinned to the stable launcher rather than a versioned server", () => {
const unit = BootService.renderBootServiceUnit({
nodePath: "/usr/local/bin/node",
t3EntryPath: "/home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs",
nodePath: "/usr/bin/node",
launcherPath: "/home/theo/.t3/runtime/service-launcher.mjs",
baseDir: "/home/theo/.t3",
logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
unitPath: "/home/theo/.config/systemd/user/t3code.service",
});
assert.equal(
unit,
[
"[Unit]",
"Description=T3 Code server",
"StartLimitIntervalSec=300",
"StartLimitBurst=5",
"",
"[Service]",
"Type=simple",
"WorkingDirectory=%h",
"Environment=T3CODE_HOME=/home/theo/.t3",
"Environment=T3_BOOT_SERVICE_UNIT=t3code.service",
"ExecStart=/usr/local/bin/node /home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs serve",
"Restart=always",
"RestartSec=5",
"StandardOutput=append:/home/theo/.t3/userdata/logs/boot-service.log",
"StandardError=append:/home/theo/.t3/userdata/logs/boot-service.log",
"",
"[Install]",
"WantedBy=default.target",
"",
].join("\n"),
);
expect(unit).toContain("ExecStart=/usr/bin/node /home/theo/.t3/runtime/service-launcher.mjs");
expect(unit).toContain("KillMode=control-group");
expect(unit).not.toContain("versions/1.2.3");
});
it("quotes systemd values containing spaces and escapes percent specifiers", () => {
assert.equal(BootService.quoteSystemdValue("/plain/path"), "/plain/path");
assert.equal(BootService.quoteSystemdValue("/home/me/T3 Data"), '"/home/me/T3 Data"');
assert.equal(BootService.quoteSystemdValue("/opt/100%cpu"), "/opt/100%%cpu");
const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
platform: NodeJS.Platform = "linux",
usePinnedLauncher = false,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
const baseDir = path.join(home, ".t3");
const sourceLauncher = path.join(home, "service-launcher.mjs");
const statePath = path.join(baseDir, "runtime", "service-state.json");
yield* fs.writeFileString(sourceLauncher, "export {};\n");
const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3");
yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
yield* fs.writeFileString(runtime.entryPath, "export {};\n");
yield* fs.writeFileString(
path.join(path.dirname(runtime.entryPath), "service-launcher.mjs"),
"export const source = 'pinned runtime';\n",
);
yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
const unit = BootService.renderBootServiceUnit({
nodePath: "/home/me/my tools/node",
t3EntryPath: "/home/me/T3 Data/bin.mjs",
baseDir: "/home/me/T3 Data",
logPath: "/home/me/100%logs/boot.log",
unitPath: "/home/me/.config/systemd/user/t3code.service",
const commands: string[] = [];
const control: { failCommand: string | undefined } = { failCommand: undefined };
const runner = ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.sync(() => {
const command = `${input.command} ${input.args.join(" ")}`;
commands.push(command);
return {
stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",
stderr: "",
code: ChildProcessSpawner.ExitCode(command === control.failCommand ? 1 : 0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
});
assert.include(unit, 'ExecStart="/home/me/my tools/node" "/home/me/T3 Data/bin.mjs" serve');
assert.include(unit, 'Environment=T3CODE_HOME="/home/me/T3 Data"');
// append: paths take the rest of the line literally (spaces are fine,
// quoting is not), but % still goes through specifier expansion.
assert.include(unit, "StandardOutput=append:/home/me/100%%logs/boot.log");
assert.include(unit, "StandardError=append:/home/me/100%%logs/boot.log");
const service = yield* BootService.make({
baseDir,
logsDir: path.join(baseDir, "userdata", "logs"),
cliVersion: "1.2.3",
host: {
execPath: "/usr/bin/node",
...(usePinnedLauncher ? {} : { launcherSourcePath: sourceLauncher }),
},
}).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, runner),
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, platform),
Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),
Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
),
),
);
return { service, fs, statePath, commands, control };
});
it("flags package-manager cache entry points as ephemeral", () => {
assert.isTrue(
BootService.isEphemeralCacheEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
);
assert.isTrue(
BootService.isEphemeralCacheEntry("C:\\Users\\theo\\AppData\\npm-cache\\_npx\\abc\\bin.mjs"),
);
assert.isTrue(
BootService.isEphemeralCacheEntry(
"/home/theo/.cache/pnpm/dlx/abc/node_modules/t3/dist/bin.mjs",
),
);
assert.isTrue(
BootService.isEphemeralCacheEntry("/home/theo/.bun/install/cache/[email protected]/dist/bin.mjs"),
);
assert.isFalse(BootService.isEphemeralCacheEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
assert.isFalse(
BootService.isEphemeralCacheEntry(
"/home/theo/dev/pnpm/dlx-tools/t3/node_modules/t3/dist/bin.mjs",
),
);
assert.isFalse(
BootService.isEphemeralCacheEntry(
"/home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs",
),
);
});
it.layer(NodeServices.layer)("BootService", (it) => {
it.effect("reconciles the standalone service once and is then idempotent", () =>
it.layer(NodeServices.layer)("boot service install", (it) => {
it.effect("installs, reports current state, and uninstalls", () =>
Effect.gen(function* () {
const { dirs } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const first = yield* reconcileService().pipe(
Effect.provideService(BootService.BootService, service),
);
assert.isTrue(first.changed);
if (!first.changed) return;
assert.isFalse(first.previouslyInstalled);
const commandCount = commands.length;
const second = yield* reconcileService().pipe(
Effect.provideService(BootService.BootService, service),
);
assert.isFalse(second.changed);
assert.lengthOf(commands, commandCount);
}),
);
it.effect("installs the unit, enables the service, and enables linger", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const { service, fs, statePath, commands } = yield* makeHarness();
const plan = yield* service.install;
// A stable entry point is reused directly — no npm install.
assert.equal(plan.t3EntryPath, dirs.stableEntry);
assert.deepEqual(
commands.map((entry) => [entry.command, ...entry.args].join(" ")),
[
"systemctl --user daemon-reload",
"systemctl --user enable t3code.service",
// restart (not enable --now) so repairing a stale unit replaces a
// running process instead of leaving the old one until reboot.
"systemctl --user restart t3code.service",
"loginctl enable-linger",
],
);
const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service");
const unit = yield* fs.readFileString(unitPath);
assert.include(unit, `ExecStart=/usr/local/bin/node ${dirs.stableEntry} serve`);
assert.include(unit, `Environment=T3CODE_HOME=${dirs.baseDir}`);
const status = yield* service.status;
assert.isTrue(status.supported);
assert.isTrue(status.installed);
assert.isTrue(status.current);
const removed = yield* service.uninstall;
assert.isTrue(removed);
assert.isFalse(yield* fs.exists(unitPath));
const statusAfter = yield* service.status;
assert.isFalse(statusAfter.installed);
const removedAgain = yield* service.uninstall;
assert.isFalse(removedAgain);
}),
);
it.effect("pins a runtime via npm install when running from the npx cache", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const plan = yield* service.install;
const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
assert.equal(
plan.t3EntryPath,
path.join(runtimeDir, "node_modules", "t3", "dist", "bin.mjs"),
);
assert.deepEqual(commands[0], {
command: "npm",
args: ["install", "--prefix", runtimeDir, "--no-fund", "--no-audit", "[email protected]"],
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
protocol: 1,
activeVersion: "1.2.3",
});
// Success is recorded via a sentinel so interrupted installs re-run.
assert.isTrue(yield* fs.exists(path.join(runtimeDir, ".install-complete")));
}),
);
it.effect("reinstalls a pinned runtime when its entry point is missing", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const plan = yield* service.install;
yield* fs.makeDirectory(path.dirname(plan.t3EntryPath), { recursive: true });
yield* fs.writeFileString(plan.t3EntryPath, "#!/usr/bin/env node\n");
yield* fs.remove(plan.t3EntryPath);
commands.length = 0;
yield* service.install;
assert.isTrue(commands.some(({ command }) => command === "npm"));
}),
);
it.effect("reads executable metadata from host process references", () =>
Effect.gen(function* () {
const { dirs } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands)),
provideHostRefs(dirs.home),
Effect.provideService(HostProcessExecutablePath, "/opt/node/bin/node"),
Effect.provideService(HostProcessArguments, ["/opt/node/bin/node", dirs.stableEntry]),
);
const plan = yield* service.install;
assert.equal(plan.nodePath, "/opt/node/bin/node");
assert.equal(plan.t3EntryPath, dirs.stableEntry);
}),
);
it.effect("cleans up and fails when the pinned runtime install fails", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "npm" })),
provideHostRefs(dirs.home),
);
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
// The half-installed tree must not be reused by the next attempt.
assert.isFalse(yield* fs.exists(runtimeDir));
assert.isFalse(yield* fs.exists(path.join(runtimeDir, ".install-complete")));
}),
);
it.effect("reports an installed-but-stale unit so the lifecycle can offer a repair", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const unitDir = path.join(dirs.home, ".config", "systemd", "user");
yield* fs.makeDirectory(unitDir, { recursive: true });
expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
expect((yield* service.status).current).toBe(true);
yield* fs.writeFileString(
path.join(unitDir, "t3code.service"),
"[Service]\nExecStart=/old/node /old/t3 serve\n",
statePath,
'{"protocol":1,"activeVersion":"1.2.3","update":{"id":"u","fromVersion":"1.2.3","targetVersion":"1.2.4","status":"pending"}}',
);
const status = yield* service.status;
assert.isTrue(status.supported);
assert.isTrue(status.installed);
assert.isFalse(status.current);
expect((yield* service.status).current).toBe(false);
expect(yield* service.uninstall).toBe(true);
expect((yield* service.status).installed).toBe(false);
expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
}),
);
it.effect("reports a current unit as stale when its entry point is gone", () =>
it.effect("copies the launcher from the prepared pinned runtime", () =>
Effect.gen(function* () {
const { dirs, fs } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const { service, fs } = yield* makeHarness("linux", true);
const plan = yield* service.install;
expect(yield* fs.readFileString(plan.launcherPath)).toBe(
"export const source = 'pinned runtime';\n",
);
}),
);
it.effect("restarts an installed service when repair fails", () =>
Effect.gen(function* () {
const { service, commands, control } = yield* makeHarness();
yield* service.install;
assert.isTrue((yield* service.status).current);
// The pinned runtime (or global bin) was deleted to reclaim space; the
// unit still matches byte-for-byte but would crashloop at boot.
yield* fs.remove(dirs.stableEntry);
const status = yield* service.status;
assert.isTrue(status.installed);
assert.isFalse(status.current);
}),
);
it.effect("fails on non-Linux platforms without touching the filesystem", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands)),
provideHostRefs(dirs.home, "darwin"),
);
commands.length = 0;
control.failCommand = "systemctl --user daemon-reload";
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isUnsupportedError(error));
assert.lengthOf(commands, 0);
assert.isFalse(
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
);
const status = yield* service.status;
assert.isFalse(status.supported);
assert.isFalse(status.installed);
expect(error._tag).toBe("BootServiceCommandError");
expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
"systemctl --user stop t3code.service",
"systemctl --user daemon-reload",
"systemctl --user restart t3code.service",
]);
}),
);
it.effect("removes the unit file when an activation step fails", () =>
it.effect("fails closed off Linux", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "loginctl" })),
provideHostRefs(dirs.home),
);
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
// A leftover unit would make status report "installed" even though
// linger never happened.
assert.isFalse(
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
);
const status = yield* service.status;
assert.isFalse(status.installed);
assert.isTrue(
commands.some(
({ command, args }) =>
command === "systemctl" && args.join(" ") === "--user disable --now t3code.service",
),
);
}),
);
it.effect("restores the previous unit when a repair cannot activate", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const initialCommands: Array<RecordedCommand> = [];
const initialService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(initialCommands)),
provideHostRefs(dirs.home),
);
yield* initialService.install;
const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service");
const previousUnit = yield* fs.readFileString(unitPath);
const replacementEntry = path.join(dirs.home, "replacement-bin.mjs");
yield* fs.writeFileString(replacementEntry, "#!/usr/bin/env node\n");
const repairCommands: Array<RecordedCommand> = [];
const repairService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.28",
host: makeHost(replacementEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(repairCommands, { failCommand: "loginctl" })),
provideHostRefs(dirs.home),
);
const error = yield* repairService.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
assert.equal(yield* fs.readFileString(unitPath), previousUnit);
assert.isTrue(
repairCommands.some(
({ command, args }) =>
command === "systemctl" && args.join(" ") === "--user restart t3code.service",
),
);
}),
);
it.effect("keeps the unit when stopping it during uninstall fails", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const installCommands: Array<RecordedCommand> = [];
const installedService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(installCommands)),
provideHostRefs(dirs.home),
);
yield* installedService.install;
const uninstallCommands: Array<RecordedCommand> = [];
const failingService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(
makeRecordingRunnerLayer(uninstallCommands, {
failWhen: (command, args) =>
command === "systemctl" && args.includes("disable") && args.includes("--now"),
}),
),
provideHostRefs(dirs.home),
);
const error = yield* failingService.uninstall.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
assert.isTrue(
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
);
}),
);
it.effect("appends failed steps to the boot-service log", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "systemctl" })),
provideHostRefs(dirs.home),
);
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
if (!isCommandError(error)) return;
assert.equal(error.exitCode, 1);
assert.equal(error.stderrLength, "systemctl exploded".length);
const logPath = path.join(dirs.logsDir, "boot-service.log");
assert.isTrue(yield* fs.exists(logPath));
assert.include(yield* fs.readFileString(logPath), "exit code 1");
const { service } = yield* makeHarness("darwin");
expect((yield* service.status).supported).toBe(false);
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
}),
);
});
+166 -199
View File
@@ -1,5 +1,6 @@
import * as Context from "effect/Context";
import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -9,58 +10,29 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as ProcessRunner from "../processRunner.ts";
import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts";
/**
* Installs T3 Code as a per-user boot service. Linux-only for now: systemd
* user unit + loginctl enable-linger. The service runs a stable or pinned
* runtime — never an ephemeral `npx t3` cache whose eviction could break
* startup.
*/
import {
ensurePinnedRuntimeInstalled,
pinnedRuntimePaths,
PinnedRuntimeInstallError,
} from "./pinnedRuntime.ts";
import {
SERVICE_LAUNCHER_FILE,
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
parseServiceState,
type ServiceState,
} from "./serviceProtocol.ts";
const BOOT_SERVICE_NAME = "t3code";
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
const EPHEMERAL_CACHE_SEGMENTS = [
"/_npx/", // npx
"\\_npx\\",
"/pnpm/dlx/", // pnpm dlx (~/.cache/pnpm/dlx and $PNPM_HOME/.pnpm/dlx)
"/.pnpm/dlx/",
"/.bun/install/cache/", // bunx
];
/**
* `npx t3` (and pnpm dlx / bunx) run out of ephemeral package-manager
* caches that can be evicted at any time — a boot service must never point
* there. Global installs, repo checkouts, and the pinned runtime below are
* all stable.
*/
export function isEphemeralCacheEntry(entryPath: string): boolean {
return EPHEMERAL_CACHE_SEGMENTS.some((segment) => entryPath.includes(segment));
}
/**
* systemd expands `%` specifiers in most directive values, including the
* `append:` file paths, which take the rest of the line literally and must
* NOT be quoted.
*/
/** systemd expands `%` specifiers, including in unquoted append-log paths. */
export function escapeSystemdSpecifiers(value: string): string {
return value.replaceAll("%", "%%");
}
/**
* systemd word-splits ExecStart and Environment values and expands `%`
* specifiers, so paths with spaces or percents must be quoted and escaped.
*/
export function quoteSystemdValue(value: string): string {
const escaped = escapeSystemdSpecifiers(value);
return /[\s"'\\]/.test(escaped)
@@ -69,31 +41,19 @@ export function quoteSystemdValue(value: string): string {
}
export interface BootServicePlan {
/** Absolute path of the node binary running this CLI. */
readonly nodePath: string;
/** Absolute path of the pinned t3 entry point the unit will run. */
readonly t3EntryPath: string;
readonly launcherPath: string;
readonly baseDir: string;
readonly logPath: string;
readonly unitPath: string;
}
/**
* Pure so it is testable byte-for-byte. systemd user units run with a
* minimal environment: every path must be absolute, and the service must
* not rely on PATH, nvm shims, or shell profiles. Failures land in
* `logPath` because `systemctl --user` failures are otherwise invisible.
*/
/** Pure renderer: service units cannot rely on the user's shell or PATH. */
export function renderBootServiceUnit(plan: BootServicePlan): string {
// No After=network-online.target: it does not exist in the systemd *user*
// manager, so ordering on it is silently ignored. The server retries its
// relay connection, and Restart=always covers early-boot failures.
// The user manager has no reliable network-online target; server networking retries itself.
return [
"[Unit]",
"Description=T3 Code server",
// Give up after 5 crashes in 5 minutes so a persistently broken install
// (deleted runtime, broken workspace) stops instead of restarting every
// 5s forever and growing the unrotated append log without bound.
"StartLimitIntervalSec=300",
"StartLimitBurst=5",
"",
@@ -102,7 +62,8 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
"WorkingDirectory=%h",
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
`Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.t3EntryPath)} serve`,
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,
"KillMode=control-group",
"Restart=always",
"RestartSec=5",
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
@@ -157,7 +118,6 @@ export type BootServiceError =
export interface BootServiceStatus {
readonly supported: boolean;
readonly installed: boolean;
/** False when the installed unit no longer matches what install would write. */
readonly current: boolean;
readonly unitPath: string;
readonly logPath: string;
@@ -166,12 +126,7 @@ export interface BootServiceStatus {
export class BootService extends Context.Service<
BootService,
{
/** Installs the pinned runtime + unit, enables linger, starts the service. */
readonly install: Effect.Effect<BootServicePlan, BootServiceError>;
/**
* Stops and removes the unit; leaves the pinned runtime for reuse.
* Returns whether a unit was actually removed.
*/
readonly uninstall: Effect.Effect<boolean, BootServiceError>;
readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
}
@@ -179,7 +134,7 @@ export class BootService extends Context.Service<
export interface BootServiceHost {
readonly execPath: string;
readonly cliEntryPath: string;
readonly launcherSourcePath?: string;
}
export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
@@ -189,23 +144,41 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
readonly host?: BootServiceHost;
}) {
const hostExecPath = yield* HostProcessExecutablePath;
const hostArguments = yield* HostProcessArguments;
const host = input.host ?? {
execPath: hostExecPath,
// When running the packed CLI this is dist/bin.mjs; when stable (global
// install, repo checkout) the boot service runs this same artifact.
cliEntryPath: hostArguments[1] ?? "",
};
const platform = yield* HostProcessPlatform;
const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const host = input.host ?? { execPath: hostExecPath };
const unitDir = path.join(homeDir, ".config", "systemd", "user");
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
const logPath = path.join(input.logsDir, "boot-service.log");
const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
const launcherSourcePath =
host.launcherSourcePath ??
path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);
const writeDurably = (filePath: string, contents: string) =>
Effect.scoped(
Effect.gen(function* () {
const directory = path.dirname(filePath);
yield* fs.makeDirectory(directory, { recursive: true });
const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
yield* (yield* fs.open(tempPath, { flag: "r" })).sync;
yield* fs.rename(tempPath, filePath);
yield* (yield* fs.open(directory, { flag: "r" })).sync;
}),
).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
const plan: BootServicePlan = {
nodePath: host.execPath,
launcherPath,
baseDir: input.baseDir,
logPath,
unitPath,
};
const requireSystemdLinux = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
@@ -244,150 +217,130 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
);
});
/**
* Ensures plannedEntryPath exists before the unit points at it. A stable
* install (global bin, repo checkout) is used as-is; an ephemeral cache
* entry is replaced by `npm install --prefix`-ing the exact running
* version into <baseDir>/runtime/versions/<v>. A real install (not a copy
* of bin.mjs) because t3 ships native deps like node-pty.
*/
const ensurePinnedRuntime = Effect.gen(function* () {
if (!isEphemeralCacheEntry(host.cliEntryPath)) {
return;
}
yield* ensurePinnedRuntimeInstalled({
baseDir: input.baseDir,
version: input.cliVersion,
fs,
path,
runner,
}).pipe(
Effect.mapError((error) =>
error.step.startsWith("installing")
? new BootServiceCommandError({
step: error.step,
exitCode: error.exitCode,
stdoutLength: error.stdoutLength,
stderrLength: error.stderrLength,
cause: error.cause,
})
: new BootServiceInstallError({ cause: error }),
),
Effect.tapError((error) =>
DateTime.now.pipe(
Effect.flatMap((now) =>
fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
flag: "a",
}),
),
Effect.ignore,
),
),
);
});
// Where the unit will point: derivable without touching the network, so
// status can compare units purely; install materializes it first.
const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
? runtimePaths.entryPath
: host.cliEntryPath;
const plan: BootServicePlan = {
nodePath: host.execPath,
t3EntryPath: plannedEntryPath,
baseDir: input.baseDir,
logPath,
unitPath,
};
const install: BootService["Service"]["install"] = Effect.gen(function* () {
yield* requireSystemdLinux;
yield* fs
.makeDirectory(input.logsDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* ensurePinnedRuntime;
const previousUnit = yield* fs.exists(unitPath).pipe(
Effect.flatMap((exists) =>
exists
? fs.readFileString(unitPath).pipe(Effect.map(Option.some))
: Effect.succeed(Option.none<string>()),
// Prepare every immutable artifact before stopping the installed unit.
yield* ensurePinnedRuntimeInstalled({
baseDir: input.baseDir,
version: input.cliVersion,
fs,
path,
runner,
validate: (runtime) =>
runner
.run({
command: host.execPath,
args: [runtime.entryPath, "--version"],
timeout: Duration.seconds(30),
})
.pipe(
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({
step: "verifying the pinned t3 runtime",
cause,
}),
),
Effect.flatMap((result) => {
const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
return result.code === 0 && reportedVersion === input.cliVersion
? Effect.void
: Effect.fail(
new PinnedRuntimeInstallError({
step: "verifying the pinned t3 runtime",
exitCode: Number(result.code),
stdoutLength: result.stdout.length,
stderrLength: result.stderr.length,
}),
);
}),
),
}).pipe(
Effect.mapError((error) =>
error._tag === "PinnedRuntimeInstallError"
? new BootServiceCommandError({
step: error.step,
exitCode: error.exitCode,
stdoutLength: error.stdoutLength,
stderrLength: error.stderrLength,
cause: error,
})
: new BootServiceInstallError({ cause: error }),
),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
const launcherSource = yield* fs
.readFileString(launcherSourcePath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* fs.makeDirectory(unitDir, { recursive: true }).pipe(
Effect.andThen(fs.writeFileString(unitPath, renderBootServiceUnit(plan))),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
const installed = yield* fs
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
if (installed) {
yield* runStep("stopping the installed service", "systemctl", [
"--user",
"stop",
BOOT_SERVICE_UNIT_FILE,
]);
}
// If any activation step fails, remove the unit again: a leftover file
// would make service status report it as installed even though it was
// never enabled or lingered.
yield* Effect.gen(function* () {
yield* fs
.makeDirectory(unitDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* writeDurably(launcherPath, launcherSource);
yield* writeDurably(
statePath,
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
`${JSON.stringify(
{
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: input.cliVersion,
} satisfies ServiceState,
null,
2,
)}\n`,
);
yield* writeDurably(unitPath, renderBootServiceUnit(plan));
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
yield* runStep("enabling the service", "systemctl", [
"--user",
"enable",
BOOT_SERVICE_UNIT_FILE,
]);
// restart rather than enable --now: --now does not replace an already
// running process, so repairing a stale unit would leave the old
// server running until reboot. restart also starts a stopped service.
yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
// Start last. No administrative state write occurs after this succeeds.
yield* runStep("starting the service", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]);
// Linger keeps the user manager (and this service) running without an
// open session — the whole point on a box reached over SSH. No
// username argument: loginctl defaults to the calling user, which is
// always right, while $USER can be stale (su without -l) or unset.
yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
}).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit)));
}).pipe(
Effect.tapError(() =>
installed
? runStep("restarting the service after a failed update", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]).pipe(Effect.ignore)
: Effect.void,
),
);
return plan;
}).pipe(Effect.withSpan("cloud.boot_service.install"));
// If activation fails partway (e.g. enable succeeds but restart/linger
// fails), leave nothing behind: disable removes the enable symlink, remove
// deletes the file, daemon-reload clears the stale definition — otherwise a
// dangling wants/ symlink logs "Failed to load unit" at every boot and the
// next lifecycle command misreports the state.
const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
previousUnit: Option.Option<string>,
) {
if (Option.isSome(previousUnit)) {
yield* fs.writeFileString(unitPath, previousUnit.value).pipe(Effect.ignore);
} else {
yield* runStep("cleaning up the service", "systemctl", [
"--user",
"disable",
"--now",
BOOT_SERVICE_UNIT_FILE,
]).pipe(Effect.ignore);
yield* fs.remove(unitPath).pipe(Effect.ignore);
}
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]).pipe(
Effect.ignore,
);
if (Option.isSome(previousUnit)) {
yield* runStep("restoring the previous service", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]).pipe(Effect.ignore);
}
});
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
yield* requireSystemdLinux;
const exists = yield* fs
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
if (!exists) {
if (
!(yield* fs
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
)
return false;
}
yield* runStep("stopping the service", "systemctl", [
"--user",
"disable",
@@ -405,18 +358,32 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
if (platform !== "linux" || homeDir === "") {
return { supported: false, installed: false, current: false, unitPath, logPath };
}
const unitExists = yield* fs.exists(unitPath);
if (!unitExists) {
if (!(yield* fs.exists(unitPath))) {
return { supported: true, installed: false, current: false, unitPath, logPath };
}
const unit = yield* fs.readFileString(unitPath);
// A unit is current only if it matches what install would write now (an
// older CLI wrote a different runtime/node path) AND the entry point it
// references still exists (a pinned runtime under ~/.t3 can be deleted to
// reclaim space). Either mismatch makes connect offer a repair.
const entryExists = yield* fs.exists(plannedEntryPath);
const current = unit === renderBootServiceUnit(plan) && entryExists;
return { supported: true, installed: true, current, unitPath, logPath };
const [unit, launcherExists, runtimeEntryExists, runtimeSentinel, stateText] =
yield* Effect.all([
fs.readFileString(unitPath),
fs.exists(launcherPath),
fs.exists(runtimePaths.entryPath),
fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
fs.readFileString(statePath).pipe(Effect.option),
]);
const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
return {
supported: true,
installed: true,
current:
unit === renderBootServiceUnit(plan) &&
launcherExists &&
runtimeEntryExists &&
Option.isSome(runtimeSentinel) &&
runtimeSentinel.value.trim() === input.cliVersion &&
state?.activeVersion === input.cliVersion &&
state?.update?.status !== "pending",
unitPath,
logPath,
};
}).pipe(
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
Effect.withSpan("cloud.boot_service.status"),
+146 -101
View File
@@ -2,8 +2,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Path from "effect/Path";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
@@ -11,119 +11,164 @@ import * as ProcessRunner from "../processRunner.ts";
import {
ensurePinnedRuntimeInstalled,
pinnedRuntimePaths,
removePinnedRuntimeInstallation,
PinnedRuntimeInstallError,
} from "./pinnedRuntime.ts";
const successfulRunner = (fs: FileSystem.FileSystem, path: Path.Path) =>
ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.gen(function* () {
const prefixIndex = input.args.indexOf("--prefix");
const stagingDir = input.args[prefixIndex + 1];
if (stagingDir === undefined) return yield* Effect.die("missing npm --prefix");
const entry = path.join(stagingDir, "node_modules", "t3", "dist", "bin.mjs");
yield* fs.makeDirectory(path.dirname(entry), { recursive: true }).pipe(Effect.orDie);
yield* fs.writeFileString(entry, "export {};\n").pipe(Effect.orDie);
return {
stdout: "",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
});
it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
it.effect("serializes concurrent installs of the same runtime", () =>
it.effect("validates a staging tree before atomically publishing it", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
const installStarted = yield* Deferred.make<void>();
const allowInstallToFinish = yield* Deferred.make<void>();
const paths = pinnedRuntimePaths(path, baseDir, "0.0.29");
let npmRuns = 0;
const finalPaths = pinnedRuntimePaths(path, baseDir, "1.2.3");
let validatedDirectory = "";
const runner = ProcessRunner.ProcessRunner.of({
run: (_input) =>
Effect.gen(function* () {
npmRuns += 1;
yield* Deferred.succeed(installStarted, undefined);
yield* Deferred.await(allowInstallToFinish);
yield* fs
.makeDirectory(path.dirname(paths.entryPath), { recursive: true })
.pipe(Effect.orDie);
yield* fs.writeFileString(paths.entryPath, "export {};\n").pipe(Effect.orDie);
return {
stdout: "",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
});
const install = ensurePinnedRuntimeInstalled({
const installed = yield* ensurePinnedRuntimeInstalled({
baseDir,
version: "0.0.29",
version: "1.2.3",
fs,
path,
runner: successfulRunner(fs, path),
validate: (staging) =>
Effect.gen(function* () {
validatedDirectory = staging.versionDir;
assert.isFalse(yield* fs.exists(finalPaths.versionDir));
assert.isTrue(yield* fs.exists(staging.entryPath));
}).pipe(Effect.orDie),
});
assert.notEqual(validatedDirectory, finalPaths.versionDir);
assert.deepEqual(installed, finalPaths);
assert.isTrue(yield* fs.exists(finalPaths.entryPath));
assert.equal(yield* fs.readFileString(finalPaths.sentinelPath), "1.2.3\n");
}),
);
it.effect("removes staging and leaves no final runtime when validation fails", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
const finalPaths = pinnedRuntimePaths(path, baseDir, "1.2.3");
yield* ensurePinnedRuntimeInstalled({
baseDir,
version: "1.2.3",
fs,
path,
runner: successfulRunner(fs, path),
validate: () =>
Effect.fail(new PinnedRuntimeInstallError({ step: "validating the staged runtime" })),
}).pipe(Effect.flip);
assert.isFalse(yield* fs.exists(finalPaths.versionDir));
assert.deepEqual(
(yield* fs.readDirectory(path.dirname(finalPaths.versionDir))).filter((entry) =>
entry.startsWith(".staging-"),
),
[],
);
}),
);
it.effect("replaces an incomplete pinned runtime", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
const finalPaths = pinnedRuntimePaths(path, baseDir, "1.2.3");
yield* fs.makeDirectory(finalPaths.versionDir, { recursive: true });
yield* fs.writeFileString(path.join(finalPaths.versionDir, "partial"), "incomplete\n");
yield* ensurePinnedRuntimeInstalled({
baseDir,
version: "1.2.3",
fs,
path,
runner: successfulRunner(fs, path),
validate: () => Effect.void,
});
assert.isFalse(yield* fs.exists(path.join(finalPaths.versionDir, "partial")));
assert.isTrue(yield* fs.exists(finalPaths.entryPath));
}),
);
it.effect("preserves a completed runtime when validation fails", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
const finalPaths = pinnedRuntimePaths(path, baseDir, "1.2.3");
yield* fs.makeDirectory(path.dirname(finalPaths.entryPath), { recursive: true });
yield* fs.writeFileString(finalPaths.entryPath, "broken\n");
yield* fs.writeFileString(finalPaths.sentinelPath, "1.2.3\n");
let validations = 0;
yield* ensurePinnedRuntimeInstalled({
baseDir,
version: "1.2.3",
fs,
path,
runner: successfulRunner(fs, path),
validate: (paths) =>
Effect.gen(function* () {
validations += 1;
const source = yield* fs.readFileString(paths.entryPath).pipe(Effect.orDie);
if (source === "broken\n") {
return yield* new PinnedRuntimeInstallError({ step: "validating the runtime" });
}
}),
}).pipe(Effect.flip);
assert.equal(validations, 1);
assert.equal(yield* fs.readFileString(finalPaths.entryPath), "broken\n");
}),
);
it.effect("removes staging when installation is interrupted", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-interrupt-" });
const started = yield* Deferred.make<void>();
const runner = ProcessRunner.ProcessRunner.of({
run: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)),
});
const install = yield* ensurePinnedRuntimeInstalled({
baseDir,
version: "1.2.3",
fs,
path,
runner,
});
validate: () => Effect.void,
}).pipe(Effect.forkScoped);
const first = yield* Effect.forkChild(install, { startImmediately: true });
yield* Deferred.await(installStarted);
const second = yield* Effect.forkChild(install, { startImmediately: true });
yield* Effect.yieldNow;
assert.equal(npmRuns, 1);
yield* Deferred.succeed(allowInstallToFinish, undefined);
yield* Fiber.join(first);
yield* Fiber.join(second);
assert.equal(npmRuns, 1);
assert.isTrue(yield* fs.exists(paths.sentinelPath));
assert.isTrue(yield* fs.exists(paths.entryPath));
}),
);
it.effect("waits for an active install before removing its runtime", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
const installStarted = yield* Deferred.make<void>();
const allowInstallToFinish = yield* Deferred.make<void>();
const paths = pinnedRuntimePaths(path, baseDir, "0.0.30");
const runner = ProcessRunner.ProcessRunner.of({
run: (_input) =>
Effect.gen(function* () {
yield* Deferred.succeed(installStarted, undefined);
yield* Deferred.await(allowInstallToFinish);
yield* fs
.makeDirectory(path.dirname(paths.entryPath), { recursive: true })
.pipe(Effect.orDie);
yield* fs.writeFileString(paths.entryPath, "export {};\n").pipe(Effect.orDie);
return {
stdout: "",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
});
const installFiber = yield* Effect.forkChild(
ensurePinnedRuntimeInstalled({
baseDir,
version: "0.0.30",
fs,
path,
runner,
}),
{ startImmediately: true },
);
yield* Deferred.await(installStarted);
const removeFiber = yield* Effect.forkChild(
removePinnedRuntimeInstallation({
baseDir,
version: "0.0.30",
fs,
path,
}),
{ startImmediately: true },
);
yield* Effect.yieldNow;
assert.isTrue(yield* fs.exists(paths.versionDir));
yield* Deferred.succeed(allowInstallToFinish, undefined);
yield* Fiber.join(installFiber);
yield* Fiber.join(removeFiber);
assert.isFalse(yield* fs.exists(paths.versionDir));
yield* Deferred.await(started);
yield* Fiber.interrupt(install);
const versionsDir = path.join(baseDir, "runtime", "versions");
assert.deepEqual(yield* fs.readDirectory(versionsDir), []);
}),
);
});
+150 -104
View File
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Option from "effect/Option";
import * as Semaphore from "effect/Semaphore";
import * as ProcessRunner from "../processRunner.ts";
@@ -11,15 +12,14 @@ import * as ProcessRunner from "../processRunner.ts";
* A pinned runtime is an exact `t3@<version>` npm-installed into
* <baseDir>/runtime/versions/<version>. The boot service points its systemd
* unit here, and server self-update installs the target version here before
* switching over — never `npx t3`, whose cache is ephemeral and whose
* switching over, never `npx t3`, whose cache is ephemeral and whose
* registry fetch at boot would make startup depend on the network.
*/
const PINNED_RUNTIME_DIR = "runtime";
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
// Boot-service setup and remote self-update share this module but can be
// constructed in separate layers. Serialize the complete check/install/
// sentinel transaction across all callers in this process.
// Boot-service setup and remote update can construct separate layers. Serialize
// the complete install transaction across every caller in this process.
const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
export interface PinnedRuntimePaths {
@@ -58,119 +58,165 @@ export class PinnedRuntimeInstallError extends Schema.TaggedErrorClass<PinnedRun
}
}
export class PinnedRuntimePreflightBlockedError extends Schema.TaggedErrorClass<PinnedRuntimePreflightBlockedError>()(
"PinnedRuntimePreflightBlockedError",
{
version: Schema.String,
reason: Schema.String,
},
) {
override get message(): string {
return this.reason;
}
}
/**
* Installs `t3@<version>` into the pinned runtime directory unless a complete
* install is already there, and returns its paths. The sentinel is written
* only after npm exits 0; checking the entry file alone is not enough — npm
* only after npm exits 0; checking the entry file alone is not enough. npm
* extracts files before running native builds (node-pty), so a killed
* install leaves a plausible-looking but broken tree behind.
*/
export const ensurePinnedRuntimeInstalled = Effect.fn("cloud.pinned_runtime.ensure_installed")(
function* (input: {
readonly baseDir: string;
readonly version: string;
readonly fs: FileSystem.FileSystem;
readonly path: Path.Path;
readonly runner: ProcessRunner.ProcessRunner["Service"];
}) {
const { fs, runner } = input;
const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
interface PinnedRuntimeInstallInput {
readonly baseDir: string;
readonly version: string;
readonly fs: FileSystem.FileSystem;
readonly path: Path.Path;
readonly runner: ProcessRunner.ProcessRunner["Service"];
readonly validate: (
paths: PinnedRuntimePaths,
) => Effect.Effect<void, PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError>;
}
return yield* pinnedRuntimeInstallLock.withPermit(
Effect.gen(function* () {
const alreadyPinned = yield* Effect.all([
fs.exists(paths.sentinelPath),
const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(function* (
input: PinnedRuntimeInstallInput,
) {
const { fs, runner } = input;
const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
const [versionDirExists, entryExists, sentinel] = yield* Effect.all([
fs.exists(paths.versionDir),
fs.exists(paths.entryPath),
fs.readFileString(paths.sentinelPath).pipe(Effect.option),
]).pipe(
Effect.mapError(
(cause) => new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
),
);
const alreadyPinned =
entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;
if (alreadyPinned) {
yield* input.validate(paths);
return paths;
}
if (versionDirExists) {
yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({
step: "removing an incomplete pinned runtime",
cause,
}),
),
);
}
const versionsDir = input.path.dirname(paths.versionDir);
yield* fs.makeDirectory(versionsDir, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({
step: "preparing the pinned runtime directory",
cause,
}),
),
);
const stagingDir = yield* fs
.makeTempDirectory({
directory: versionsDir,
prefix: ".staging-",
})
.pipe(
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({
step: "preparing the pinned runtime directory",
cause,
}),
),
);
const stagingPaths: PinnedRuntimePaths = {
versionDir: stagingDir,
entryPath: input.path.join(stagingDir, "node_modules", "t3", "dist", "bin.mjs"),
sentinelPath: input.path.join(stagingDir, ".install-complete"),
};
return yield* Effect.gen(function* () {
const installStep = "installing the pinned t3 runtime (this can take a few minutes)";
yield* runner
.run({
command: "npm",
args: ["install", "--prefix", stagingDir, "--no-fund", "--no-audit", `t3@${input.version}`],
// Native dependencies may compile from source on slower machines.
timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
})
.pipe(
Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),
Effect.filterOrFail(
(result) => result.code === 0,
(result) =>
new PinnedRuntimeInstallError({
step: installStep,
exitCode: Number(result.code),
stdoutLength: result.stdout.length,
stderrLength: result.stderr.length,
}),
),
);
yield* input.validate(stagingPaths);
yield* fs
.writeFileString(stagingPaths.sentinelPath, `${input.version}\n`)
.pipe(
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
),
);
const published = yield* fs.rename(stagingDir, paths.versionDir).pipe(
Effect.as(true),
Effect.catch((cause) =>
Effect.all([
fs.exists(paths.entryPath),
fs.readFileString(paths.sentinelPath).pipe(Effect.option),
]).pipe(
Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
),
);
if (alreadyPinned) {
return paths;
}
yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
Effect.andThen(fs.makeDirectory(paths.versionDir, { recursive: true })),
Effect.mapError(
(cause) =>
(checkCause) =>
new PinnedRuntimeInstallError({
step: "preparing the pinned runtime directory",
cause,
step: "checking a concurrently published pinned runtime",
cause: checkCause,
}),
),
);
const installStep = "installing the pinned t3 runtime (this can take a few minutes)";
yield* runner
.run({
command: "npm",
args: [
"install",
"--prefix",
paths.versionDir,
"--no-fund",
"--no-audit",
`t3@${input.version}`,
],
// Native deps (node-pty) can compile from source on slow boxes; the
// ProcessRunner default of 60s would kill a healthy install.
timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
})
.pipe(
Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),
Effect.filterOrFail(
(result) => result.code === 0,
(result) =>
new PinnedRuntimeInstallError({
step: installStep,
exitCode: Number(result.code),
stdoutLength: result.stdout.length,
stderrLength: result.stderr.length,
}),
),
Effect.tapError(() =>
fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(Effect.ignore),
),
);
yield* fs
.writeFileString(paths.sentinelPath, `${input.version}\n`)
.pipe(
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
),
);
return paths;
}),
);
},
);
/** Removes one pinned runtime while holding the same process-wide lock used
* by install/check/sentinel work, so cleanup cannot race another caller that
* is materializing or reusing the runtime tree. */
export const removePinnedRuntimeInstallation = Effect.fn("cloud.pinned_runtime.remove")(
function* (input: {
readonly baseDir: string;
readonly version: string;
readonly fs: FileSystem.FileSystem;
readonly path: Path.Path;
}) {
const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
yield* pinnedRuntimeInstallLock.withPermit(
input.fs
.remove(paths.versionDir, { recursive: true, force: true })
.pipe(
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({ step: "removing the pinned runtime", cause }),
Effect.flatMap(([publishedEntryExists, publishedSentinel]) =>
publishedEntryExists &&
Option.isSome(publishedSentinel) &&
publishedSentinel.value.trim() === input.version
? Effect.succeed(false)
: Effect.fail(
new PinnedRuntimeInstallError({
step: "publishing the pinned runtime",
cause,
}),
),
),
),
),
);
},
);
if (!published) yield* input.validate(paths);
return paths;
}).pipe(
Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
);
});
export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =>
pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));
Loaded 100 of 343 files, more files were not shown because too many files have changed in this diff. Show more