Compare commits

...
Author SHA1 Message Date
t3-code[bot] 8ac9c0321d fix(web): isolate browser chrome sync 2026-08-03 07:01:14 +00:00
t3-code[bot] f0e4ec40ed fix(web): keep custom palettes readable 2026-08-03 06:53:48 +00:00
t3-code[bot] d3c4644759 feat(web): showcase palette controls 2026-08-03 06:45:06 +00:00
t3-code[bot] b8f0110d4c feat(web): add two-color appearance palette 2026-08-03 06:13:27 +00: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
253 changed files with 15414 additions and 4006 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: |
+3
View File
@@ -17,6 +17,7 @@ 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 DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
@@ -220,6 +221,7 @@ 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;
@@ -248,6 +250,7 @@ const startup = Effect.gen(function* () {
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),
+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"),
@@ -66,6 +66,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;
@@ -162,6 +164,10 @@ const make = Effect.fn("desktop.environment.make")(function* (
);
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 +211,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,7 +29,6 @@ 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),
@@ -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);
@@ -14,7 +14,6 @@ const {
quitMock,
relaunchMock,
removeListenerMock,
requestSingleInstanceLockMock,
setAboutPanelOptionsMock,
setAppUserModelIdMock,
setAsDefaultProtocolClientMock,
@@ -35,7 +34,6 @@ const {
quitMock: vi.fn(),
relaunchMock: vi.fn(),
removeListenerMock: vi.fn(),
requestSingleInstanceLockMock: vi.fn(() => true),
setAboutPanelOptionsMock: vi.fn(),
setAppUserModelIdMock: vi.fn(),
setAsDefaultProtocolClientMock: vi.fn(() => true),
@@ -67,7 +65,6 @@ vi.mock("electron", () => ({
quit: quitMock,
relaunch: relaunchMock,
removeListener: removeListenerMock,
requestSingleInstanceLock: requestSingleInstanceLockMock,
runningUnderARM64Translation: false,
setAboutPanelOptions: setAboutPanelOptionsMock,
setAsDefaultProtocolClient: setAsDefaultProtocolClientMock,
-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: (
@@ -153,7 +152,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)),
@@ -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",
];
+2
View File
@@ -43,6 +43,7 @@ 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";
@@ -181,6 +182,7 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer,
DesktopApplicationMenu.layer,
DesktopLinuxUrlHandler.layer,
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(
@@ -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;
@@ -39,7 +39,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
+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",
};
}
@@ -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,
]),
);
+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));
+108 -588
View File
@@ -1,624 +1,144 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import { expect, it } from "@effect/vitest";
import { HostProcessExecutablePath } from "@t3tools/shared/hostProcess";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Fiber from "effect/Fiber";
import * as Path from "effect/Path";
import * as TestClock from "effect/testing/TestClock";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import {
HostProcessArguments,
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
BOOT_SERVICE_UNIT_ENV,
BOOT_SERVICE_UNIT_FILE,
renderBootServiceUnit,
} from "./bootService.ts";
import * as SelfUpdate from "./selfUpdate.ts";
import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
import * as ServerSelfUpdate from "./selfUpdate.ts";
const NODE_PATH = "/usr/local/bin/node";
const eventuallyFileString = Effect.fn("test.eventuallyFileString")(function* (
filePath: string,
expected: string,
) {
const fs = yield* FileSystem.FileSystem;
for (let iteration = 0; iteration < 1_000; iteration += 1) {
const contents = yield* fs.readFileString(filePath);
if (contents === expected) {
return;
}
// The rollback performs real filesystem I/O on a detached fiber, which
// advancing TestClock does not await.
yield* Effect.yieldNow;
}
return yield* Effect.die(new Error(`Expected file contents were not observed at ${filePath}.`));
});
const eventuallyTrue = Effect.fn("test.eventuallyTrue")(function* (predicate: () => boolean) {
for (let iteration = 0; iteration < 1_000; iteration += 1) {
if (predicate()) {
return;
}
yield* Effect.yieldNow;
}
return yield* Effect.die(new Error("Expected condition was not observed."));
});
interface RecordedCommand {
readonly command: string;
readonly args: ReadonlyArray<string>;
interface HarnessOptions {
readonly mode?: "web" | "desktop";
readonly managed?: boolean;
readonly preflight?: "ready" | "blocked";
readonly requestUpdate?: ServiceLauncherClient.ServiceLauncherClient["Service"]["requestUpdate"];
}
const makeRecordingRunnerLayer = (
commands: Array<RecordedCommand>,
options?: {
readonly failWhen?: ((command: string, args: ReadonlyArray<string>) => boolean) | undefined;
readonly stdoutFor?:
| ((command: string, args: ReadonlyArray<string>) => string | undefined)
| undefined;
},
) =>
Layer.succeed(
ProcessRunner.ProcessRunner,
ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.sync(() => {
commands.push({ command: input.command, args: input.args });
const failed = options?.failWhen?.(input.command, input.args) === true;
const versionFromPath =
input.command === NODE_PATH && input.args[1] === "--version"
? /[/\\]runtime[/\\]versions[/\\]([^/\\]+)/.exec(input.args[0] ?? "")?.[1]
: undefined;
const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
options: HarnessOptions = {},
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
const order: string[] = [];
const runner = ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.gen(function* () {
if (input.command === "npm") {
order.push("install");
const prefix = input.args[input.args.indexOf("--prefix") + 1];
if (prefix === undefined) return yield* Effect.die("missing npm prefix");
const entry = path.join(prefix, "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:
options?.stdoutFor?.(input.command, input.args) ??
(versionFromPath === undefined ? "" : `t3 v${versionFromPath}\n`),
stderr: failed ? `${input.command} exploded` : "",
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
stdout: "",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
}),
);
const provideHostRefs = (input: {
readonly platform: NodeJS.Platform;
readonly env: NodeJS.ProcessEnv;
readonly entryPath: string;
}) =>
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, input.platform),
Layer.succeed(HostProcessEnvironment, input.env),
Layer.succeed(HostProcessExecutablePath, NODE_PATH),
Layer.succeed(HostProcessArguments, [NODE_PATH, input.entryPath, "serve"]),
),
);
it("recognizes published npm artifacts as swappable entry points", () => {
assert.isTrue(SelfUpdate.isPublishedCliEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
assert.isTrue(
SelfUpdate.isPublishedCliEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
);
assert.isTrue(
SelfUpdate.isPublishedCliEntry(
"C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
),
);
// Dev checkouts and the desktop bundle run apps/server/dist directly.
assert.isFalse(SelfUpdate.isPublishedCliEntry("/home/theo/dev/t3/apps/server/dist/bin.mjs"));
assert.isFalse(SelfUpdate.isPublishedCliEntry(""));
});
it.layer(NodeServices.layer)("resolveServerSelfUpdateCapability", (it) => {
const makeHome = Effect.fn("test.makeHome")(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
return { fs, path, home };
});
const writeUnitReferencing = Effect.fn("test.writeUnitReferencing")(function* (
home: string,
entryPath: string,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const unitDir = path.join(home, ".config", "systemd", "user");
yield* fs.makeDirectory(unitDir, { recursive: true });
yield* fs.writeFileString(
path.join(unitDir, "t3code.service"),
renderBootServiceUnit({
nodePath: NODE_PATH,
t3EntryPath: entryPath,
baseDir: path.join(home, ".t3"),
logPath: path.join(home, ".t3", "userdata", "logs", "boot-service.log"),
unitPath: path.join(unitDir, "t3code.service"),
}
order.push("preflight");
const result =
options.preflight === "blocked"
? { status: "blocked", version: "1.1.0", reason: "local update required" }
: { status: "ready", version: "1.1.0", launcherProtocol: 1 };
return {
// @effect-diagnostics-next-line preferSchemaOverJson:off - fake child-process stdout.
stdout: JSON.stringify(result),
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
);
});
const launcher = ServiceLauncherClient.ServiceLauncherClient.of({
managed: options.managed ?? true,
trial: false,
requestUpdate:
options.requestUpdate ??
(() =>
Effect.sync(() => {
order.push("accept");
return "launcher-id";
})),
prepareTrial: Effect.sync((): undefined => undefined),
});
const config = yield* ServerConfig.ServerConfig.pipe(
Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
);
const selfUpdate = yield* ServerSelfUpdate.make().pipe(
Effect.provideService(ProcessRunner.ProcessRunner, runner),
Effect.provideService(ServiceLauncherClient.ServiceLauncherClient, launcher),
Effect.provideService(HostProcessExecutablePath, "/usr/bin/node"),
Effect.provide(ServerConfig.layer({ ...config, mode: options.mode ?? "web" })),
);
return { selfUpdate, order };
});
it.effect("reports boot-service for the systemd-spawned unit process", () =>
it.layer(NodeServices.layer)("server self update", (it) => {
it.effect("stages and preflights before asking the launcher for an update ID", () =>
Effect.gen(function* () {
const { home, path } = yield* makeHome();
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
yield* writeUnitReferencing(home, entryPath);
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(
provideHostRefs({
platform: "linux",
env: {
HOME: home,
INVOCATION_ID: "abc123",
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
},
entryPath,
}),
);
assert.equal(method, "boot-service");
const { selfUpdate, order } = yield* makeHarness();
expect(yield* selfUpdate.update({ targetVersion: "1.1.0" })).toEqual({
targetVersion: "1.1.0",
method: "boot-service",
updateId: "launcher-id",
});
expect(order).toEqual(["install", "preflight", "accept"]);
}),
);
it.effect("does not claim a systemd process owned by another unit", () =>
it.effect("rejects invalid versions and desktop-managed servers before staging", () =>
Effect.gen(function* () {
const { home, path } = yield* makeHome();
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
yield* writeUnitReferencing(home, entryPath);
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(
provideHostRefs({
platform: "linux",
env: { HOME: home, INVOCATION_ID: "abc123" },
entryPath,
}),
);
assert.isNull(method);
const web = yield* makeHarness();
expect(
(yield* web.selfUpdate.update({ targetVersion: "latest" }).pipe(Effect.flip)).reason,
).toBe("'latest' is not an exact t3 version.");
const desktop = yield* makeHarness({ mode: "desktop" });
expect(
(yield* desktop.selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason,
).toContain("desktop app");
expect([...web.order, ...desktop.order]).toEqual([]);
}),
);
it.effect("reports respawn for a manual run of the pinned artifact", () =>
it.effect("preserves the preflight refusal reason", () =>
Effect.gen(function* () {
const { home, path } = yield* makeHome();
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
yield* writeUnitReferencing(home, entryPath);
// Same unit on disk, but no INVOCATION_ID: restarting the unit would
// not replace this process, so it must respawn itself instead.
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(provideHostRefs({ platform: "linux", env: { HOME: home }, entryPath }));
assert.equal(method, "respawn");
const { selfUpdate } = yield* makeHarness({ preflight: "blocked" });
expect((yield* selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason).toBe(
"local update required",
);
}),
);
it.effect("reports respawn for a foreground npx artifact on darwin", () =>
it.effect("allows only one update at a time", () =>
Effect.gen(function* () {
const { home } = yield* makeHome();
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(
provideHostRefs({
platform: "darwin",
env: { HOME: home },
entryPath: `${home}/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs`,
}),
const requested = yield* Deferred.make<void>();
const accepted = yield* Deferred.make<string>();
const { selfUpdate } = yield* makeHarness({
requestUpdate: () =>
Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(accepted))),
});
const first = yield* Effect.forkChild(selfUpdate.update({ targetVersion: "1.1.0" }), {
startImmediately: true,
});
yield* Deferred.await(requested);
expect((yield* selfUpdate.update({ targetVersion: "1.1.1" }).pipe(Effect.flip)).reason).toBe(
"A server update is already in progress.",
);
assert.equal(method, "respawn");
}),
);
it.effect("reports desktop-managed for desktop-supervised backends", () =>
Effect.gen(function* () {
const { home, path } = yield* makeHome();
// Desktop ownership wins over every process-shape heuristic: even a
// systemd-looking pinned artifact belongs to the app that spawned it.
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
yield* writeUnitReferencing(home, entryPath);
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: true,
}).pipe(
provideHostRefs({
platform: "linux",
env: {
HOME: home,
INVOCATION_ID: "abc123",
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
},
entryPath,
}),
);
assert.equal(method, "desktop-managed");
}),
);
it.effect("reports no method for dev checkouts and Windows", () =>
Effect.gen(function* () {
const { home } = yield* makeHome();
const devMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(
provideHostRefs({
platform: "darwin",
env: { HOME: home },
entryPath: `${home}/dev/t3/apps/server/dist/bin.mjs`,
}),
);
assert.isNull(devMethod);
const windowsMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(
provideHostRefs({
platform: "win32",
env: { HOME: home },
entryPath: "C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
}),
);
assert.isNull(windowsMethod);
yield* Deferred.succeed(accepted, "launcher-id");
expect((yield* Fiber.join(first)).updateId).toBe("launcher-id");
}),
);
});
it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
interface RecordedSpawn {
readonly command: string;
readonly args: ReadonlyArray<string>;
}
const makeContext = Effect.fn("test.makeContext")(function* (options?: {
readonly platform?: NodeJS.Platform;
readonly bootService?: boolean;
readonly desktopManaged?: boolean;
readonly entryPath?: string;
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
readonly stdoutFor?: (command: string, args: ReadonlyArray<string>) => string | undefined;
readonly failSpawn?: boolean;
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
const baseDir = path.join(home, ".t3");
const entryPath =
options?.entryPath ??
path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
const env: NodeJS.ProcessEnv =
options?.bootService === true
? {
HOME: home,
INVOCATION_ID: "abc123",
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
}
: { HOME: home };
if (options?.bootService === true) {
const unitDir = path.join(home, ".config", "systemd", "user");
yield* fs.makeDirectory(unitDir, { recursive: true });
yield* fs.writeFileString(
path.join(unitDir, "t3code.service"),
renderBootServiceUnit({
nodePath: NODE_PATH,
t3EntryPath: entryPath,
baseDir,
logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
unitPath: path.join(unitDir, "t3code.service"),
}),
);
}
const commands: Array<RecordedCommand> = [];
const spawns: Array<RecordedSpawn> = [];
let exited = 0;
// layerTest always reports mode "web"; desktop-managed contexts overlay
// the mode the desktop app's bootstrap envelope would set.
const configLayer =
options?.desktopManaged === true
? Layer.effect(
ServerConfig.ServerConfig,
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
return { ...config, mode: "desktop" as const };
}),
).pipe(Layer.provide(ServerConfig.layerTest(home, baseDir)))
: ServerConfig.layerTest(home, baseDir);
const service = yield* SelfUpdate.make({
host: {
spawnDetached: (command, args) =>
Effect.sync(() => spawns.push({ command, args })).pipe(
Effect.andThen(
options?.failSpawn === true
? Effect.fail(
new ProcessRunner.ProcessSpawnError({
command,
argumentCount: args.length,
cause: new Error("detached spawn failed"),
}),
)
: Effect.void,
),
),
exitProcess: () => {
exited += 1;
},
},
}).pipe(
Effect.provide(
Layer.mergeAll(
makeRecordingRunnerLayer(commands, {
failWhen: options?.failWhen,
stdoutFor: options?.stdoutFor,
}),
configLayer,
),
),
provideHostRefs({ platform: options?.platform ?? "linux", env, entryPath }),
);
return {
fs,
path,
home,
baseDir,
entryPath,
commands,
spawns,
exitCount: () => exited,
service,
};
});
it.effect("rejects dist-tags and other non-exact versions", () =>
Effect.gen(function* () {
const context = yield* makeContext();
const error = yield* context.service.update({ targetVersion: "latest" }).pipe(Effect.flip);
assert.include(error.reason, "not an exact t3 version");
assert.lengthOf(context.commands, 0);
}),
);
it.effect("refuses to update a desktop-managed backend and points at the app", () =>
Effect.gen(function* () {
const context = yield* makeContext({ desktopManaged: true, bootService: true });
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(error.reason, "desktop app");
assert.lengthOf(context.commands, 0);
assert.lengthOf(context.spawns, 0);
}),
);
it.effect("fails without touching anything when no update method applies", () =>
Effect.gen(function* () {
const context = yield* makeContext({
entryPath: "/home/theo/dev/t3/apps/server/dist/bin.mjs",
});
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(error.reason, "cannot update itself");
assert.lengthOf(context.commands, 0);
}),
);
it.effect("surfaces a failed npm install and never schedules a restart", () =>
Effect.gen(function* () {
const context = yield* makeContext({ failWhen: (command) => command === "npm" });
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.equal(error.reason, "Could not install the requested t3 version.");
yield* TestClock.adjust(Duration.seconds(10));
assert.lengthOf(context.spawns, 0);
assert.equal(context.exitCount(), 0);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("reinstalls the same version after a failed preflight", () =>
Effect.gen(function* () {
let preflightAttempts = 0;
const context = yield* makeContext({
failWhen: (command) => {
if (command !== NODE_PATH) return false;
preflightAttempts += 1;
return preflightAttempts === 1;
},
});
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
const entryPath = context.path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
yield* context.fs.makeDirectory(context.path.dirname(entryPath), { recursive: true });
yield* context.fs.writeFileString(entryPath, "export {};\n");
yield* context.fs.writeFileString(
context.path.join(versionDir, ".install-complete"),
"0.0.29\n",
);
const firstError = yield* context.service
.update({ targetVersion: "0.0.29" })
.pipe(Effect.flip);
assert.include(firstError.reason, "failed its version check");
assert.isFalse(yield* context.fs.exists(versionDir));
const result = yield* context.service.update({ targetVersion: "0.0.29" });
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
assert.deepEqual(
context.commands.map((entry) => entry.command),
[NODE_PATH, "npm", NODE_PATH],
);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("rejects and removes an installed runtime that reports the wrong version", () =>
Effect.gen(function* () {
const context = yield* makeContext({
stdoutFor: (command, args) =>
command === NODE_PATH && args[1] === "--version" ? "t3 v0.0.28\n" : undefined,
});
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(error.reason, "did not report the requested");
assert.isFalse(yield* context.fs.exists(versionDir));
assert.lengthOf(context.spawns, 0);
}),
);
it.effect("reports a detached replacement spawn failure and leaves updates retryable", () =>
Effect.gen(function* () {
const context = yield* makeContext({ failSpawn: true });
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(first.reason, "Could not start the replacement");
const second = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(second.reason, "Could not start the replacement");
assert.notInclude(second.reason, "already in progress");
assert.lengthOf(context.spawns, 2);
assert.equal(context.exitCount(), 0);
}),
);
it.effect("installs, preflights, and respawns a foreground server", () =>
Effect.gen(function* () {
const context = yield* makeContext();
const progress: Array<string> = [];
const result = yield* context.service.update({ targetVersion: "0.0.29" }, (stage) =>
Effect.sync(() => progress.push(stage)),
);
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
assert.deepEqual(progress, ["downloading", "installing"]);
assert.lengthOf(context.spawns, 1);
const concurrentError = yield* context.service
.update({ targetVersion: "0.0.30" })
.pipe(Effect.flip);
assert.include(concurrentError.reason, "already in progress");
const pinnedEntry = context.path.join(
context.baseDir,
"runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
);
assert.deepEqual(
context.commands.map((entry) => [entry.command, ...entry.args].join(" ")),
[
`npm install --prefix ${context.path.join(context.baseDir, "runtime/versions/0.0.29")} --no-fund --no-audit [email protected]`,
`${NODE_PATH} ${pinnedEntry} --version`,
],
);
// The restart is deferred so the RPC acknowledgement flushes first.
yield* TestClock.adjust(Duration.seconds(10));
assert.lengthOf(context.spawns, 1);
const spawn = context.spawns[0];
assert.equal(spawn?.command, "/bin/sh");
assert.include(spawn?.args ?? [], pinnedEntry);
// The replacement replays the original CLI arguments.
assert.include(spawn?.args ?? [], "serve");
assert.equal(context.exitCount(), 1);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("rewrites the systemd unit and restarts the boot service", () =>
Effect.gen(function* () {
const context = yield* makeContext({ bootService: true });
const result = yield* context.service.update({ targetVersion: "0.0.29" });
assert.deepEqual(result, { targetVersion: "0.0.29", method: "boot-service" });
const pinnedEntry = context.path.join(
context.baseDir,
"runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
);
const unit = yield* context.fs.readFileString(
context.path.join(context.home, ".config", "systemd", "user", "t3code.service"),
);
assert.include(unit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
assert.deepEqual(
context.commands.map((entry) => entry.command),
["npm", NODE_PATH, "systemctl"],
);
assert.deepEqual(context.commands[2]?.args, ["--user", "daemon-reload"]);
// Restart waits until after the update acknowledgement can flush.
yield* TestClock.adjust(Duration.seconds(10));
assert.deepEqual(context.commands[3], {
command: "systemctl",
args: ["--user", "restart", "t3code.service"],
});
assert.lengthOf(context.spawns, 0);
// systemd replaces the process; the server must not exit itself.
assert.equal(context.exitCount(), 0);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
Effect.gen(function* () {
let failRestart = true;
const context = yield* makeContext({
bootService: true,
failWhen: (command, args) => {
if (command !== "systemctl" || args[1] !== "restart" || !failRestart) {
return false;
}
failRestart = false;
return true;
},
});
const unitPath = context.path.join(
context.home,
".config",
"systemd",
"user",
BOOT_SERVICE_UNIT_FILE,
);
const previousUnit = yield* context.fs.readFileString(unitPath);
const first = yield* context.service.update({ targetVersion: "0.0.29" });
assert.deepEqual(first, { targetVersion: "0.0.29", method: "boot-service" });
yield* TestClock.adjust(Duration.seconds(10));
yield* eventuallyFileString(unitPath, previousUnit);
yield* eventuallyTrue(() => context.commands.at(-1)?.args[1] === "daemon-reload");
assert.deepEqual(
context.commands.slice(-2).map((entry) => entry.args),
[
["--user", "restart", BOOT_SERVICE_UNIT_FILE],
["--user", "daemon-reload"],
],
);
const retry = yield* context.service.update({ targetVersion: "0.0.30" });
assert.deepEqual(retry, { targetVersion: "0.0.30", method: "boot-service" });
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("restores the previous systemd unit when daemon-reload fails", () =>
Effect.gen(function* () {
const context = yield* makeContext({
bootService: true,
failWhen: (command) => command === "systemctl",
});
const unitPath = context.path.join(
context.home,
".config",
"systemd",
"user",
BOOT_SERVICE_UNIT_FILE,
);
const previousUnit = yield* context.fs.readFileString(unitPath);
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(error.reason, "Reloading systemd units failed");
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
assert.deepEqual(
context.commands.map((entry) => entry.command),
["npm", NODE_PATH, "systemctl", "systemctl"],
);
yield* TestClock.adjust(Duration.seconds(10));
assert.lengthOf(context.spawns, 0);
assert.equal(context.exitCount(), 0);
}).pipe(Effect.provide(TestClock.layer())),
);
});
+113 -355
View File
@@ -1,7 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
// node:child_process directly: the foreground-server replacement must be a
// detached fire-and-forget child that outlives this process, while Effect's
// ChildProcessSpawner ties every child to a scope that kills it.
import {
ServerSelfUpdateError,
type ServerSelfUpdateCapability,
@@ -9,13 +5,7 @@ import {
type ServerSelfUpdateProgressStage,
type ServerSelfUpdateResult,
} from "@t3tools/contracts";
import {
HostProcessArguments,
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as NodeChildProcess from "node:child_process";
import { HostProcessExecutablePath } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -25,208 +15,52 @@ import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as ServerConfig from "../config.ts";
import { writeFileStringAtomically } from "../atomicWrite.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
BOOT_SERVICE_UNIT_ENV,
BOOT_SERVICE_UNIT_FILE,
quoteSystemdValue,
renderBootServiceUnit,
} from "./bootService.ts";
import { ensurePinnedRuntimeInstalled, removePinnedRuntimeInstallation } from "./pinnedRuntime.ts";
/**
* Lets a connected client replace this server with another published `t3`
* version over RPC — the only update path that works when the user is not at
* the machine (phone against a home server, relay-managed box). The target
* version is npm-installed into the pinned runtime and verified before
* anything restarts, so a failed install leaves the running server untouched.
*/
ensurePinnedRuntimeInstalled,
PinnedRuntimeInstallError,
PinnedRuntimePreflightBlockedError,
} from "./pinnedRuntime.ts";
import { decodeServicePreflightResult } from "./servicePreflight.ts";
import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
import { isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
const PREFLIGHT_TIMEOUT = Duration.seconds(30);
/** Grace between acknowledging the RPC and killing the process, so the
response (and its relay hop) flushes before the socket drops. */
const RESTART_DELAY = Duration.seconds(2);
/** Exact npm versions only — never dist-tags — so the acknowledgement names
the version that was actually installed. Also keeps the value safe to
pass to npm and embed in filesystem paths. */
const EXACT_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
export interface ServerSelfUpdateHost {
readonly execPath: string;
readonly cliEntryPath: string;
/** Original CLI arguments after the entry path, replayed on respawn. */
readonly cliArgs: ReadonlyArray<string>;
/** Resolves once the foreground replacement process has actually spawned. */
readonly spawnDetached: (
command: string,
args: ReadonlyArray<string>,
) => Effect.Effect<void, ProcessRunner.ProcessSpawnError>;
readonly exitProcess: () => void;
}
function normalizeEntryPath(entryPath: string): string {
return entryPath.replaceAll("\\", "/");
}
/**
* Only a published npm artifact can be swapped for another version: dev
* checkouts (apps/server/dist) and the desktop app's bundled backend have no
* npm identity, and the desktop manages its own updates.
*/
export function isPublishedCliEntry(entryPath: string): boolean {
return normalizeEntryPath(entryPath).includes("/node_modules/t3/dist/");
}
/**
* The update path this process can offer, or null when only a manual
* relaunch works. "desktop-managed" — the T3 Code desktop app spawned this
* backend and owns its version; only updating the app updates it.
* "boot-service" — this is the systemd-supervised process from
* bootService.ts: rewrite the unit and let systemd swap it. "respawn" — a
* foreground POSIX process running a published artifact: replace it with a
* detached child. Windows foreground runs are unsupported for now (no
* equivalent of the detach-and-exec handoff below).
*/
export const resolveServerSelfUpdateCapability = Effect.fn(
"cloud.server_self_update.resolve_capability",
)(function* (input: {
/** True when the desktop app supervises this backend (mode "desktop"). */
export function resolveServerSelfUpdateCapability(input: {
readonly desktopManaged: boolean;
}) {
if (input.desktopManaged) {
return "desktop-managed" as const;
}
const platform = yield* HostProcessPlatform;
const env = yield* HostProcessEnvironment;
const hostArguments = yield* HostProcessArguments;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const entryPath = hostArguments[1] ?? "";
if (entryPath === "") {
return null;
}
const homeDir = env.HOME ?? "";
if (platform === "linux" && homeDir !== "") {
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
const unitReferencesEntry = yield* fs.readFileString(unitPath).pipe(
Effect.map((unit) => unit.includes(quoteSystemdValue(entryPath))),
Effect.orElseSucceed(() => false),
);
// INVOCATION_ID only proves that some systemd unit launched us. The
// explicit marker written into t3code.service identifies this unit as the
// supervisor that will replace the current process when restarted.
if (
unitReferencesEntry &&
(env.INVOCATION_ID ?? "") !== "" &&
env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_UNIT_FILE
) {
return "boot-service" as const;
}
// A process owned by another (or a legacy unmarked) systemd unit must not
// use the foreground respawn path: Restart=always could otherwise launch
// the old unit beside the detached replacement.
if ((env.INVOCATION_ID ?? "") !== "") {
return null;
}
}
if ((platform === "linux" || platform === "darwin") && isPublishedCliEntry(entryPath)) {
return "respawn" as const;
}
return null;
});
readonly launcherManaged: boolean;
}): ServerSelfUpdateCapability | null {
if (input.desktopManaged) return "desktop-managed" as const;
return input.launcherManaged ? ("boot-service" as const) : null;
}
export class ServerSelfUpdate extends Context.Service<
ServerSelfUpdate,
{
readonly update: (
input: ServerSelfUpdateInput,
reportProgress?: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void, never, never>,
reportProgress?: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void>,
) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
}
>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
export const make = Effect.fn("cloud.server_self_update.make")(function* (options?: {
readonly host?: Partial<ServerSelfUpdateHost>;
}) {
export const make = Effect.fn("cloud.server_self_update.make")(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
const runner = yield* ProcessRunner.ProcessRunner;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const env = yield* HostProcessEnvironment;
const hostExecPath = yield* HostProcessExecutablePath;
const hostArguments = yield* HostProcessArguments;
const capability: ServerSelfUpdateCapability | null = yield* resolveServerSelfUpdateCapability({
desktopManaged: serverConfig.mode === "desktop",
});
const host: ServerSelfUpdateHost = {
execPath: options?.host?.execPath ?? hostExecPath,
cliEntryPath: options?.host?.cliEntryPath ?? hostArguments[1] ?? "",
cliArgs: options?.host?.cliArgs ?? hostArguments.slice(2),
spawnDetached:
options?.host?.spawnDetached ??
((command, args) =>
Effect.callback<void, ProcessRunner.ProcessSpawnError>((resume) => {
const spawnError = (cause: unknown) =>
new ProcessRunner.ProcessSpawnError({
command,
argumentCount: args.length,
cause,
});
let child: NodeChildProcess.ChildProcess;
try {
child = NodeChildProcess.spawn(command, [...args], {
detached: true,
stdio: "ignore",
});
} catch (cause) {
resume(Effect.fail(spawnError(cause)));
return;
}
const onSpawnError = (cause: Error) => resume(Effect.fail(spawnError(cause)));
child.once("error", onSpawnError);
child.once("spawn", () => {
child.removeListener("error", onSpawnError);
// Keep asynchronous child errors from becoming uncaught after the
// successful spawn handoff has already been acknowledged.
child.on("error", () => undefined);
child.unref();
resume(Effect.void);
});
})),
exitProcess: options?.host?.exitProcess ?? (() => process.exit(0)),
};
const execPath = yield* HostProcessExecutablePath;
const inFlight = yield* Ref.make(false);
const capability: ServerSelfUpdateCapability | null =
serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
const failWith = (reason: string, cause?: unknown) =>
cause === undefined
? new ServerSelfUpdateError({ reason })
: new ServerSelfUpdateError({ reason, cause });
/** Deferred so the RPC acknowledgement flushes before the process dies.
Detached from the request scope: the triggering connection is exactly
what the restart tears down. */
const scheduleRestart = (restart: Effect.Effect<void>) =>
Effect.sleep(RESTART_DELAY).pipe(
Effect.andThen(restart),
Effect.forkDetach({ startImmediately: true }),
);
const writeUnitAtomically = (filePath: string, contents: string) =>
writeFileStringAtomically({ filePath, contents }).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
);
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
"cloud.server_self_update.update",
)(function* (input, reportProgress = () => Effect.void) {
@@ -237,199 +71,123 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
}
if (capability === null) {
return yield* failWith(
"This server cannot update itself; relaunch it manually with the new version.",
"Remote updates require the T3 Code background service. Run `t3 service install` on the server machine.",
);
}
const activeMethod = capability;
const targetVersion = input.targetVersion.trim();
if (!EXACT_VERSION_PATTERN.test(targetVersion)) {
if (!isExactServiceVersion(targetVersion)) {
return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
}
const alreadyRunning = yield* Ref.getAndSet(inFlight, true);
if (alreadyRunning) {
if (yield* Ref.getAndSet(inFlight, true)) {
return yield* failWith("A server update is already in progress.");
}
return yield* Effect.gen(function* () {
yield* reportProgress("downloading");
const runtimePaths = yield* ensurePinnedRuntimeInstalled({
const paths = yield* ensurePinnedRuntimeInstalled({
baseDir: serverConfig.baseDir,
version: targetVersion,
fs,
path,
runner,
validate: (runtime) =>
runner
.run({
command: execPath,
args: [
runtime.entryPath,
"__service-preflight",
"--database-path",
serverConfig.dbPath,
"--launcher-protocol",
String(SERVICE_LAUNCHER_PROTOCOL),
],
timeout: PREFLIGHT_TIMEOUT,
})
.pipe(
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({
step: "running the staged service preflight",
cause,
}),
),
Effect.flatMap(
(
result,
): Effect.Effect<
void,
PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError
> => {
if (result.code !== 0) {
return Effect.fail(
new PinnedRuntimeInstallError({
step: "running the staged service preflight",
exitCode: Number(result.code),
stdoutLength: result.stdout.length,
stderrLength: result.stderr.length,
}),
);
}
let parsed: unknown;
try {
parsed = JSON.parse(result.stdout.trim());
} catch (cause) {
return Effect.fail(
new PinnedRuntimeInstallError({
step: "decoding the staged service preflight",
cause,
}),
);
}
const preflight = decodeServicePreflightResult(parsed);
if (preflight === undefined || preflight.version !== targetVersion) {
return Effect.fail(
new PinnedRuntimeInstallError({
step: "verifying the staged service preflight",
}),
);
}
return preflight.status === "ready"
? Effect.void
: Effect.fail(
new PinnedRuntimePreflightBlockedError({
version: targetVersion,
reason: preflight.reason,
}),
);
},
),
),
}).pipe(
Effect.mapError((error) => failWith("Could not install the requested t3 version.", error)),
Effect.mapError((error) =>
error._tag === "PinnedRuntimePreflightBlockedError"
? failWith(error.reason, error)
: failWith(`Could not prepare t3@${targetVersion}.`, error),
),
);
yield* reportProgress("installing");
// A broken artifact (failed native build, incompatible node) must be
// caught while the current server is still alive to report it.
const preflight = yield* runner
.run({
command: host.execPath,
args: [runtimePaths.entryPath, "--version"],
timeout: PREFLIGHT_TIMEOUT,
})
const updateId = yield* launcher
.requestUpdate({ targetVersion })
.pipe(
Effect.mapError((cause) =>
failWith(`Could not verify the installed t3@${targetVersion}.`, cause),
),
);
// Effect CLI's unstable formatVersion currently emits `${name} v${version}`.
// Extract the version token so surrounding presentation changes do not break updates.
const reportedVersion = /\bv(\S+)\s*$/.exec(preflight.stdout)?.[1];
if (preflight.code !== 0 || reportedVersion !== targetVersion) {
// A completed npm install can still be unusable under this Node or on
// this machine. Remove its sentinel and tree so a retry of the same
// version performs a clean install instead of reusing a known-bad one.
yield* removePinnedRuntimeInstallation({
baseDir: serverConfig.baseDir,
version: targetVersion,
fs,
path,
}).pipe(
Effect.mapError((error) =>
failWith(`Could not remove the failed t3@${targetVersion} installation.`, error),
),
);
return yield* failWith(
preflight.code !== 0
? `The installed t3@${targetVersion} failed its version check (exit code ${String(preflight.code)}).`
: `The installed runtime did not report the requested t3@${targetVersion} version.`,
);
}
if (activeMethod === "boot-service") {
const homeDir = env.HOME ?? "";
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
const previousUnit = yield* fs
.readFileString(unitPath)
.pipe(
Effect.mapError((cause) => failWith("Could not read the current systemd unit.", cause)),
);
// Same shape bootService.install writes, so host lifecycle commands
// still recognize the unit as current.
const unit = renderBootServiceUnit({
nodePath: host.execPath,
t3EntryPath: runtimePaths.entryPath,
baseDir: serverConfig.baseDir,
logPath: path.join(serverConfig.logsDir, "boot-service.log"),
unitPath,
});
yield* writeUnitAtomically(unitPath, unit).pipe(
Effect.mapError((cause) => failWith("Could not update the systemd unit.", cause)),
);
const reloadSystemd = Effect.fn("cloud.server_self_update.reload_systemd")(function* () {
const reload = yield* runner
.run({ command: "systemctl", args: ["--user", "daemon-reload"] })
.pipe(Effect.mapError((cause) => failWith("Could not reload systemd units.", cause)));
if (reload.code !== 0) {
return yield* failWith(
`Reloading systemd units failed (exit code ${String(reload.code)}).`,
);
}
});
yield* reloadSystemd().pipe(
Effect.catch((reloadError) =>
writeUnitAtomically(unitPath, previousUnit).pipe(
Effect.mapError((rollbackCause) =>
failWith("Could not restore the previous systemd unit.", {
reloadError,
rollbackCause,
}),
),
// Systemd should still have the old unit in memory after the
// failed reload, but retry after restoring in case it applied a
// partial update before returning an error.
Effect.andThen(reloadSystemd().pipe(Effect.ignore)),
Effect.andThen(Effect.fail(reloadError)),
failWith(
error._tag === "ServiceLauncherRejectedError"
? error.reason
: "Could not ask the service launcher to activate the prepared update.",
error,
),
),
);
yield* Effect.logInfo("Server self-update installed; restarting boot service.", {
targetVersion,
});
// Restart after the acknowledgement has had time to cross any relay
// hop. If systemd rejects the handoff, restore the previous unit while
// this process is still alive and log the failure for diagnostics.
yield* scheduleRestart(
Effect.gen(function* () {
const restart = yield* runner
.run({
command: "systemctl",
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
})
.pipe(
Effect.mapError((cause) =>
failWith("Could not restart the systemd boot service.", cause),
),
);
if (restart.code !== 0) {
return yield* failWith(
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
);
}
}).pipe(
Effect.catch((restartError) =>
writeUnitAtomically(unitPath, previousUnit).pipe(
Effect.andThen(reloadSystemd()),
Effect.mapError((rollbackError) =>
failWith("Could not restore the previous systemd unit.", {
restartError,
rollbackError,
}),
),
Effect.andThen(Effect.fail(restartError)),
),
),
Effect.catch((error) =>
Effect.logError("Server self-update could not restart the boot service.").pipe(
Effect.annotateLogs({ targetVersion, error: error.reason }),
),
),
Effect.ensuring(Ref.set(inFlight, false)),
),
);
} else {
// Spawn the shim before acknowledging the RPC so ENOENT/EACCES and
// other launch failures leave this server alive and return a useful
// error. The shim itself waits until after the acknowledgement and
// deferred exit before binding the replacement server.
yield* host
.spawnDetached("/bin/sh", [
"-c",
'sleep 3; exec "$@"',
"t3-self-update",
host.execPath,
runtimePaths.entryPath,
...host.cliArgs,
])
.pipe(
Effect.mapError((cause) =>
failWith("Could not start the replacement t3 process.", cause),
),
);
yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });
yield* scheduleRestart(
Effect.try({
try: () => host.exitProcess(),
catch: (cause) => failWith("Could not exit the replaced t3 process.", cause),
}).pipe(
Effect.catch((error) =>
Effect.logError("Server self-update could not exit the replaced process.").pipe(
Effect.annotateLogs({ targetVersion, error: error.reason }),
Effect.ensuring(Ref.set(inFlight, false)),
),
),
),
);
}
return { targetVersion, method: activeMethod };
yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
updateId,
targetVersion,
runtimePath: paths.entryPath,
});
return { targetVersion, method: "boot-service" as const, updateId };
}).pipe(Effect.onError(() => Ref.set(inFlight, false)));
});
@@ -0,0 +1,130 @@
import { expect, it } from "@effect/vitest";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import {
SERVICE_LAUNCHER_CONTEXT_ENV,
type ServiceLauncherChildMessage,
type ServiceLauncherParentMessage,
} from "./serviceProtocol.ts";
import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
class FakeLauncherProcess {
readonly connected = true;
readonly env: Record<string, string | undefined>;
readonly sent: ServiceLauncherChildMessage[] = [];
readonly #listeners = new Map<string, Set<(...args: ReadonlyArray<unknown>) => void>>();
constructor(context: unknown) {
this.env = { [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) };
}
send = (message: ServiceLauncherChildMessage, callback?: (error: Error | null) => void) => {
this.sent.push(message);
callback?.(null);
return true;
};
on = (event: "message" | "disconnect", listener: (...args: ReadonlyArray<unknown>) => void) => {
const listeners = this.#listeners.get(event) ?? new Set();
listeners.add(listener);
this.#listeners.set(event, listeners);
};
off = (event: "message" | "disconnect", listener: (...args: ReadonlyArray<unknown>) => void) => {
this.#listeners.get(event)?.delete(listener);
};
emit(message: ServiceLauncherParentMessage) {
for (const listener of this.#listeners.get("message") ?? []) listener(message);
}
}
const makeClient = (host: FakeLauncherProcess, currentVersion: string) =>
ServiceLauncherClient.make({ currentVersion }).pipe(
Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, host),
Effect.provideService(HostProcessEnvironment, host.env),
);
it.effect("waits for the launcher to durably commit the trial update ID", () =>
Effect.gen(function* () {
const pending = {
id: "update-1",
fromVersion: "1.0.0",
targetVersion: "1.1.0",
status: "pending" as const,
};
const host = new FakeLauncherProcess({
protocol: 1,
childVersion: "1.1.0",
update: pending,
});
const client = yield* makeClient(host, "1.1.0");
const prepared = yield* Effect.forkChild(client.prepareTrial, { startImmediately: true });
yield* Effect.yieldNow;
expect(host.sent).toEqual([{ type: "prepared", updateId: "update-1" }]);
const committed = {
id: pending.id,
fromVersion: pending.fromVersion,
targetVersion: pending.targetVersion,
status: "committed" as const,
};
host.emit({ type: "committed", updateId: committed.id });
expect(yield* Fiber.join(prepared)).toEqual(committed);
}),
);
it.effect("returns the launcher-generated ID only after update acceptance", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({
protocol: 1,
childVersion: "1.0.0",
});
const client = yield* makeClient(host, "1.0.0");
const requested = yield* Effect.forkChild(client.requestUpdate({ targetVersion: "1.1.0" }), {
startImmediately: true,
});
yield* Effect.yieldNow;
host.emit({
type: "update-accepted",
updateId: "launcher-id",
});
expect(yield* Fiber.join(requested)).toBe("launcher-id");
}),
);
it.effect("preserves a launcher rejection as a distinct error", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({ protocol: 1, childVersion: "1.0.0" });
const client = yield* makeClient(host, "1.0.0");
const requested = yield* Effect.forkChild(client.requestUpdate({ targetVersion: "1.1.0" }), {
startImmediately: true,
});
yield* Effect.yieldNow;
host.emit({ type: "update-rejected", reason: "requires local update" });
expect(yield* Fiber.join(requested).pipe(Effect.flip)).toMatchObject({
_tag: "ServiceLauncherRejectedError",
targetVersion: "1.1.0",
reason: "requires local update",
});
}),
);
it.effect("rejects contradictory trial context instead of leaving activation closed", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({
protocol: 1,
childVersion: "1.1.0",
update: {
id: "update-1",
fromVersion: "1.0.0",
targetVersion: "1.2.0",
status: "pending",
},
});
const error = yield* makeClient(host, "1.1.0").pipe(Effect.flip);
expect(error.message).toBe("The service launcher supplied invalid startup context.");
}),
);
@@ -0,0 +1,249 @@
import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import packageJson from "../../package.json" with { type: "json" };
import {
decodeServiceLauncherContext,
decodeServiceLauncherParentMessage,
SERVICE_LAUNCHER_CONTEXT_ENV,
type ServiceLauncherChildMessage,
type ServiceLauncherParentMessage,
} from "./serviceProtocol.ts";
export class ServiceLauncherClientError extends Schema.TaggedErrorClass<ServiceLauncherClientError>()(
"ServiceLauncherClientError",
{
operation: Schema.Literals([
"decode-context",
"version-mismatch",
"ipc-unavailable",
"unmanaged",
"send",
"disconnect",
"timeout",
]),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
switch (this.operation) {
case "decode-context":
return "The service launcher supplied invalid startup context.";
case "version-mismatch":
return "The service launcher started a different t3 version.";
case "ipc-unavailable":
return "The service launcher IPC channel is unavailable.";
case "unmanaged":
return "This server is not managed by the launcher.";
case "send":
return "Could not send a request to the service launcher.";
case "disconnect":
return "The service launcher disconnected before acknowledging the request.";
case "timeout":
return "The service launcher did not respond within 30 seconds.";
}
}
}
export class ServiceLauncherRejectedError extends Schema.TaggedErrorClass<ServiceLauncherRejectedError>()(
"ServiceLauncherRejectedError",
{
targetVersion: Schema.String,
reason: Schema.String,
},
) {
override get message(): string {
return this.reason;
}
}
interface ServiceLauncherProcess {
readonly connected: boolean;
readonly send: (
message: ServiceLauncherChildMessage,
callback?: (error: Error | null) => void,
) => boolean;
readonly on: (
event: "message" | "disconnect",
listener: (...args: ReadonlyArray<unknown>) => void,
) => void;
readonly off: (
event: "message" | "disconnect",
listener: (...args: ReadonlyArray<unknown>) => void,
) => void;
}
export const ServiceLauncherHostProcess = Context.Reference<ServiceLauncherProcess>(
"t3/cloud/serviceLauncherHostProcess",
{
defaultValue: () => ({
connected: process.connected && process.send !== undefined,
send: (message, callback) => {
if (process.send === undefined) return false;
return callback === undefined ? process.send(message) : process.send(message, callback);
},
on: (event, listener) => {
process.on(event, listener);
},
off: (event, listener) => {
process.off(event, listener);
},
}),
},
);
export class ServiceLauncherClient extends Context.Service<
ServiceLauncherClient,
{
readonly managed: boolean;
readonly trial: boolean;
readonly requestUpdate: (input: {
readonly targetVersion: string;
}) => Effect.Effect<string, ServiceLauncherClientError | ServiceLauncherRejectedError>;
readonly prepareTrial: Effect.Effect<
ServerSelfUpdateOutcome | undefined,
ServiceLauncherClientError
>;
}
>()("t3/cloud/serviceLauncherClient") {}
const resolveStartup = Effect.fn("cloud.service_launcher_client.resolve_startup")(
function* (options?: { readonly currentVersion?: string }) {
const host = yield* ServiceLauncherHostProcess;
const environment = yield* HostProcessEnvironment;
const currentVersion = options?.currentVersion ?? packageJson.version;
const rawContext = environment[SERVICE_LAUNCHER_CONTEXT_ENV];
const context = rawContext === undefined ? undefined : decodeServiceLauncherContext(rawContext);
if (rawContext !== undefined && context === undefined) {
return yield* new ServiceLauncherClientError({ operation: "decode-context" });
}
if (context !== undefined && context.childVersion !== currentVersion) {
return yield* new ServiceLauncherClientError({ operation: "version-mismatch" });
}
const managed = context !== undefined && host.connected;
if (context !== undefined && !managed) {
return yield* new ServiceLauncherClientError({ operation: "ipc-unavailable" });
}
return { host, context, managed };
},
);
export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_client.resolve_mode")(
function* () {
const { context, managed } = yield* resolveStartup();
return { managed, trial: context?.update?.status === "pending" };
},
);
export const make = Effect.fn("cloud.service_launcher_client.make")(function* (options?: {
readonly currentVersion?: string;
}) {
const { host, context, managed } = yield* resolveStartup(options);
const exchange = (
message: ServiceLauncherChildMessage,
accept: (reply: ServiceLauncherParentMessage) => boolean,
) =>
Effect.callback<ServiceLauncherParentMessage, ServiceLauncherClientError>((resume) => {
if (!managed) {
resume(Effect.fail(new ServiceLauncherClientError({ operation: "unmanaged" })));
return;
}
let settled = false;
const cleanup = () => {
host.off("message", onMessage);
host.off("disconnect", onDisconnect);
};
const settle = (
effect: Effect.Effect<ServiceLauncherParentMessage, ServiceLauncherClientError>,
) => {
if (settled) return;
settled = true;
cleanup();
resume(effect);
};
const onMessage = (...args: ReadonlyArray<unknown>) => {
const reply = decodeServiceLauncherParentMessage(args[0]);
if (reply !== undefined && accept(reply)) settle(Effect.succeed(reply));
};
const onDisconnect = () =>
settle(Effect.fail(new ServiceLauncherClientError({ operation: "disconnect" })));
host.on("message", onMessage);
host.on("disconnect", onDisconnect);
try {
host.send(message, (error) => {
if (error !== null) {
settle(
Effect.fail(new ServiceLauncherClientError({ operation: "send", cause: error })),
);
}
});
} catch (cause) {
settle(Effect.fail(new ServiceLauncherClientError({ operation: "send", cause })));
}
return Effect.sync(cleanup);
}).pipe(
Effect.timeoutOrElse({
duration: "30 seconds",
orElse: () => Effect.fail(new ServiceLauncherClientError({ operation: "timeout" })),
}),
);
const requestUpdate = (input: { readonly targetVersion: string }) =>
exchange(
{ type: "request-update", ...input },
(reply) => reply.type === "update-accepted" || reply.type === "update-rejected",
).pipe(
Effect.flatMap((reply) =>
reply.type === "update-accepted"
? Effect.succeed(reply.updateId)
: reply.type === "update-rejected"
? Effect.fail(
new ServiceLauncherRejectedError({
targetVersion: input.targetVersion,
reason: reply.reason,
}),
)
: Effect.die("service launcher returned an impossible update response"),
),
);
const pending = context?.update?.status === "pending" ? context.update : undefined;
const outcome =
context?.update === undefined || context.update.status === "pending"
? undefined
: context.update;
const prepareTrial =
pending !== undefined
? exchange(
{ type: "prepared", updateId: pending.id },
(reply) => reply.type === "committed" && reply.updateId === pending.id,
).pipe(
Effect.flatMap((reply) => {
if (reply.type !== "committed") {
return Effect.die("service launcher returned an impossible prepared response");
}
return Effect.succeed({ ...pending, status: "committed" as const });
}),
)
: Effect.succeed(outcome);
return ServiceLauncherClient.of({
managed,
trial: pending !== undefined,
requestUpdate,
prepareTrial,
});
});
export const layer = Layer.effect(ServiceLauncherClient, make());
@@ -0,0 +1,47 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as NodeSqlite from "node:sqlite";
import { migrationManifest } from "../persistence/Migrations.ts";
import { runServicePreflight } from "./servicePreflight.ts";
it.layer(NodeServices.layer)("service update preflight", (it) => {
it.effect("requires exact migration-manifest equality without mutating the database", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-preflight-test-" });
const databasePath = path.join(root, "state.sqlite");
const database = new NodeSqlite.DatabaseSync(databasePath);
database.exec("CREATE TABLE effect_sql_migrations (migration_id INTEGER, name TEXT)");
const insert = database.prepare(
"INSERT INTO effect_sql_migrations (migration_id, name) VALUES (?, ?)",
);
for (const [id, name] of migrationManifest) insert.run(id, name);
database.close();
expect(runServicePreflight({ databasePath, launcherProtocol: 1, version: "1.2.3" })).toEqual({
status: "ready",
version: "1.2.3",
launcherProtocol: 1,
});
const changed = new NodeSqlite.DatabaseSync(databasePath);
changed.exec("DELETE FROM effect_sql_migrations WHERE migration_id = 35");
changed.close();
const blocked = runServicePreflight({
databasePath,
launcherProtocol: 1,
version: "1.2.3",
});
expect(blocked.status).toBe("blocked");
if (blocked.status === "blocked") {
expect(blocked.reason).toContain("npx [email protected] service update");
}
}),
);
});
+96
View File
@@ -0,0 +1,96 @@
import * as NodeSqlite from "node:sqlite";
import packageJson from "../../package.json" with { type: "json" };
import { migrationManifest } from "../persistence/Migrations.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
export type ServicePreflightResult =
| {
readonly status: "ready";
readonly version: string;
readonly launcherProtocol: typeof SERVICE_LAUNCHER_PROTOCOL;
}
| {
readonly status: "blocked";
readonly version: string;
readonly reason: string;
};
const localUpdateReason = (version: string) =>
`This version includes a database update and cannot be installed remotely. Run \`npx t3@${version} service update\` on the server machine.`;
const isMigrationRow = (
value: unknown,
): value is { readonly migration_id: number; readonly name: string } =>
typeof value === "object" &&
value !== null &&
"migration_id" in value &&
typeof value.migration_id === "number" &&
"name" in value &&
typeof value.name === "string";
export function runServicePreflight(input: {
readonly databasePath: string;
readonly launcherProtocol: number;
readonly version?: string;
}): ServicePreflightResult {
const version = input.version ?? packageJson.version;
if (input.launcherProtocol !== SERVICE_LAUNCHER_PROTOCOL) {
return {
status: "blocked",
version,
reason:
"This release requires a newer T3 Code service launcher. Update it on the server machine.",
};
}
try {
const database = new NodeSqlite.DatabaseSync(input.databasePath, { readOnly: true });
try {
const rows: ReadonlyArray<unknown> = database
.prepare("SELECT migration_id, name FROM effect_sql_migrations ORDER BY migration_id")
.all();
const exact =
rows.length === migrationManifest.length &&
rows.every((row, index) => {
const expected = migrationManifest[index];
return (
isMigrationRow(row) && row.migration_id === expected?.[0] && row.name === expected?.[1]
);
});
if (!exact) return { status: "blocked", version, reason: localUpdateReason(version) };
} finally {
database.close();
}
} catch {
return { status: "blocked", version, reason: localUpdateReason(version) };
}
return { status: "ready", version, launcherProtocol: SERVICE_LAUNCHER_PROTOCOL };
}
export function decodeServicePreflightResult(value: unknown): ServicePreflightResult | undefined {
if (typeof value !== "object" || value === null) {
return undefined;
}
const record = value as Record<string, unknown>;
if (
record.status === "ready" &&
record.launcherProtocol === SERVICE_LAUNCHER_PROTOCOL &&
typeof record.version === "string"
) {
return {
status: "ready",
version: record.version,
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
};
}
if (
record.status === "blocked" &&
typeof record.version === "string" &&
typeof record.reason === "string"
) {
return { status: "blocked", version: record.version, reason: record.reason };
}
return undefined;
}
+226
View File
@@ -0,0 +1,226 @@
import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
export const SERVICE_LAUNCHER_PROTOCOL = 1 as const;
export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
export const SERVICE_LAUNCHER_FILE = "service-launcher.mjs";
export const SERVICE_STATE_FILE = "service-state.json";
export interface PendingServiceUpdate {
readonly id: string;
readonly fromVersion: string;
readonly targetVersion: string;
readonly status: "pending";
}
export type ServiceUpdateRecord = PendingServiceUpdate | ServerSelfUpdateOutcome;
export interface ServiceState {
readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
readonly activeVersion: string;
readonly update?: ServiceUpdateRecord;
}
/** Context is copied from launcher-owned state when a child is spawned. */
export interface ServiceLauncherContext {
readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
readonly childVersion: string;
readonly update?: ServiceUpdateRecord;
}
export type ServiceLauncherChildMessage =
| {
readonly type: "request-update";
readonly targetVersion: string;
}
| {
readonly type: "prepared";
readonly updateId: string;
};
export type ServiceLauncherParentMessage =
| {
readonly type: "update-accepted";
readonly updateId: string;
}
| {
readonly type: "update-rejected";
readonly reason: string;
}
| {
readonly type: "committed";
readonly updateId: string;
};
const SEMVER_NUMBER = "(?:0|[1-9]\\d*)";
const SEMVER_PRERELEASE = `(?:${SEMVER_NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)`;
const EXACT_SERVICE_VERSION = new RegExp(
`^${SEMVER_NUMBER}\\.${SEMVER_NUMBER}\\.${SEMVER_NUMBER}(?:-${SEMVER_PRERELEASE}(?:\\.${SEMVER_PRERELEASE})*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$`,
);
/** Accepts exact SemVer only: never dist-tags or ranges passed to npm or filesystem paths. */
export const isExactServiceVersion = (version: string): boolean =>
EXACT_SERVICE_VERSION.test(version);
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
export function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undefined {
if (!isRecord(value)) return undefined;
const { id, fromVersion, targetVersion, status } = value;
if (
typeof id !== "string" ||
id.trim() === "" ||
typeof fromVersion !== "string" ||
!isExactServiceVersion(fromVersion) ||
typeof targetVersion !== "string" ||
!isExactServiceVersion(targetVersion)
) {
return undefined;
}
if (status === "pending") {
return { id, fromVersion, targetVersion, status };
}
if (
(status === "committed" || status === "rolled-back" || status === "failed") &&
(value.reason === undefined || (typeof value.reason === "string" && value.reason.trim() !== ""))
) {
return {
id,
fromVersion,
targetVersion,
status,
...(typeof value.reason === "string" ? { reason: value.reason } : {}),
};
}
return undefined;
}
/** SemVer precedence for exact versions. Build metadata is ignored. */
export function compareExactServiceVersions(left: string, right: string): number {
const parse = (version: string) => {
const withoutBuild = version.split("+", 1)[0] ?? version;
const separator = withoutBuild.indexOf("-");
const core = separator === -1 ? withoutBuild : withoutBuild.slice(0, separator);
const prerelease = separator === -1 ? undefined : withoutBuild.slice(separator + 1);
const [major = "0", minor = "0", patch = "0"] = core.split(".");
return {
core: [BigInt(major), BigInt(minor), BigInt(patch)] as const,
prerelease: prerelease?.split(".") ?? [],
};
};
const a = parse(left);
const b = parse(right);
for (let index = 0; index < 3; index += 1) {
const x = a.core[index] ?? 0n;
const y = b.core[index] ?? 0n;
if (x !== y) return x < y ? -1 : 1;
}
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
}
const count = Math.max(a.prerelease.length, b.prerelease.length);
for (let index = 0; index < count; index += 1) {
const x = a.prerelease[index];
const y = b.prerelease[index];
if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
if (x === y) continue;
const xNumeric = /^\d+$/.test(x);
const yNumeric = /^\d+$/.test(y);
if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
return x < y ? -1 : 1;
}
return 0;
}
export function decodeServiceState(value: unknown): ServiceState | undefined {
if (!isRecord(value)) return undefined;
const update = value.update === undefined ? undefined : decodeServiceUpdate(value.update);
if (
value.protocol !== SERVICE_LAUNCHER_PROTOCOL ||
typeof value.activeVersion !== "string" ||
!isExactServiceVersion(value.activeVersion) ||
(value.update !== undefined && update === undefined) ||
(update !== undefined &&
compareExactServiceVersions(update.targetVersion, update.fromVersion) <= 0) ||
(update?.status === "pending" && update.fromVersion !== value.activeVersion) ||
(update?.status === "committed" && update.targetVersion !== value.activeVersion) ||
((update?.status === "rolled-back" || update?.status === "failed") &&
update.fromVersion !== value.activeVersion)
) {
return undefined;
}
return {
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: value.activeVersion,
...(update === undefined ? {} : { update }),
};
}
export function parseServiceState(value: string): ServiceState | undefined {
try {
return decodeServiceState(JSON.parse(value) as unknown);
} catch {
return undefined;
}
}
export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
let parsed: unknown;
try {
parsed = JSON.parse(value) as unknown;
} catch {
return undefined;
}
if (
!isRecord(parsed) ||
parsed.protocol !== SERVICE_LAUNCHER_PROTOCOL ||
typeof parsed.childVersion !== "string" ||
!isExactServiceVersion(parsed.childVersion)
) {
return undefined;
}
const update = parsed.update === undefined ? undefined : decodeServiceUpdate(parsed.update);
if (parsed.update !== undefined && update === undefined) return undefined;
const selectedVersion =
update?.status === "pending" || update?.status === "committed"
? update.targetVersion
: update === undefined
? parsed.childVersion
: update.fromVersion;
if (parsed.childVersion !== selectedVersion) {
return undefined;
}
return {
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: parsed.childVersion,
...(update === undefined ? {} : { update }),
};
}
export function decodeServiceLauncherChildMessage(
value: unknown,
): ServiceLauncherChildMessage | undefined {
if (!isRecord(value)) return undefined;
if (value.type === "request-update" && typeof value.targetVersion === "string") {
return { type: value.type, targetVersion: value.targetVersion };
}
return value.type === "prepared" && typeof value.updateId === "string"
? { type: value.type, updateId: value.updateId }
: undefined;
}
export function decodeServiceLauncherParentMessage(
value: unknown,
): ServiceLauncherParentMessage | undefined {
if (!isRecord(value)) return undefined;
if (value.type === "update-rejected" && typeof value.reason === "string") {
return { type: value.type, reason: value.reason };
}
if (value.type === "update-accepted" && typeof value.updateId === "string") {
return { type: value.type, updateId: value.updateId };
}
return value.type === "committed" && typeof value.updateId === "string"
? { type: value.type, updateId: value.updateId }
: undefined;
}
@@ -10,6 +10,7 @@ import * as Schema from "effect/Schema";
import packageJson from "../../package.json" with { type: "json" };
import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
@@ -125,8 +126,10 @@ export const make = Effect.gen(function* () {
const environmentId = EnvironmentId.make(environmentIdRaw);
const cwdBaseName = path.basename(serverConfig.cwd).trim();
const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
const serverSelfUpdate = yield* resolveServerSelfUpdateCapability({
const launcher = yield* resolveServiceLauncherMode();
const serverSelfUpdate = resolveServerSelfUpdateCapability({
desktopManaged: serverConfig.mode === "desktop",
launcherManaged: launcher.managed,
});
const descriptor: ExecutionEnvironmentDescriptor = {
@@ -144,9 +147,7 @@ export const make = Effect.gen(function* () {
threadSnooze: true,
threadTitleRegeneration: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" || serverSelfUpdate === "respawn"
? { serverSelfUpdateProgress: true }
: {}),
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
},
};
@@ -277,6 +277,9 @@ describe("CheckpointReactor", () => {
readonly seedFilesystemCheckpoints?: boolean;
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly threadBranch?: string | null;
readonly secondThreadSharingWorktree?: boolean;
readonly localStatusRefName?: string | null;
readonly providerSessionCwd?: string;
readonly providerName?: ProviderDriverKind;
readonly gitStatusRefreshCalls?: Array<string>;
@@ -315,7 +318,8 @@ describe("CheckpointReactor", () => {
isRepo: true,
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
refName:
options?.localStatusRefName !== undefined ? options.localStatusRefName : "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -370,22 +374,45 @@ describe("CheckpointReactor", () => {
}),
);
await Effect.runPromise(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create"),
threadId: ThreadId.make("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: options?.threadWorktreePath ?? cwd,
createdAt,
}),
engine
.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create"),
threadId: ThreadId.make("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: options?.threadBranch ?? null,
worktreePath: options?.threadWorktreePath ?? cwd,
createdAt,
})
.pipe(
options?.secondThreadSharingWorktree
? Effect.andThen(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-2"),
threadId: ThreadId.make("thread-2"),
projectId: asProjectId("project-1"),
title: "Thread 2",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: options?.threadWorktreePath ?? cwd,
createdAt,
}),
)
: Effect.asVoid,
),
);
if (options?.seedFilesystemCheckpoints ?? true) {
@@ -518,6 +545,86 @@ describe("CheckpointReactor", () => {
expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
});
it("adopts a drifted checkout as the thread branch on a dedicated worktree", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
threadBranch: "t3code/original-branch",
localStatusRefName: "t3code/renamed-by-agent",
});
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-branch-drift"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-branch-drift"),
payload: { state: "completed" },
});
await harness.drain();
await waitForEvent(
harness.engine,
(event) =>
event.type === "thread.meta-updated" &&
(event as unknown as { payload: { branch?: string } }).payload.branch ===
"t3code/renamed-by-agent",
);
const snapshot = await harness.readModel();
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.branch).toBe("t3code/renamed-by-agent");
});
it("does not adopt a drifted checkout when the worktree is shared by another thread", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
threadBranch: "t3code/original-branch",
localStatusRefName: "t3code/renamed-by-agent",
secondThreadSharingWorktree: true,
});
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-branch-drift-shared"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-branch-drift-shared"),
payload: { state: "completed" },
});
await harness.drain();
const snapshot = await harness.readModel();
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.branch).toBe("t3code/original-branch");
});
it("does not adopt a temporary placeholder checkout as the thread branch", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
threadBranch: "t3code/original-branch",
localStatusRefName: "t3code/0a1b2c3d",
});
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-branch-drift-temp"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-branch-drift-temp"),
payload: { state: "completed" },
});
await harness.drain();
const snapshot = await harness.readModel();
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.branch).toBe("t3code/original-branch");
});
it("ignores auxiliary thread turn completion while primary turn is active", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -8,6 +8,7 @@ import {
TurnId,
type OrchestrationEvent,
type ProviderRuntimeEvent,
type VcsStatusLocalResult,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
@@ -18,6 +19,7 @@ import * as Option from "effect/Option";
import type * as PlatformError from "effect/PlatformError";
import * as Stream from "effect/Stream";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts";
import {
@@ -27,6 +29,7 @@ import {
import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
import { forkParked } from "../../serverActivation.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
@@ -534,16 +537,93 @@ const make = Effect.gen(function* () {
return;
}
yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
const local = yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to refresh local git status after turn completion", {
threadId: event.threadId,
turnId: event.turnId ?? null,
cwd: sessionRuntime.value.cwd,
detail: error.message,
}),
}).pipe(Effect.as(null)),
),
);
if (local !== null) {
yield* followWorktreeBranchDrift({
threadId: event.threadId,
cwd: sessionRuntime.value.cwd,
local,
});
}
});
// A `git checkout` run inside a thread's dedicated worktree (by an agent or
// the user) bypasses T3's commands, so the thread's recorded branch goes
// stale. Since #4460 the client only attributes PR state to a thread when
// the checked-out branch equals the recorded one, so stale metadata silently
// orphans the thread's PR. Follow the drift here: adopt the checked-out
// branch as the thread's branch, but only when the worktree belongs to
// exactly this thread — for shared cwds the strict matching is the point.
const followWorktreeBranchDrift = Effect.fn("followWorktreeBranchDrift")(function* (input: {
readonly threadId: ThreadId;
readonly cwd: string;
readonly local: VcsStatusLocalResult;
}) {
// Detached HEAD has no branch to adopt; a temporary placeholder checkout
// means the first-turn auto-rename is still in flight — don't race it.
const checkedOutBranch = input.local.refName;
if (checkedOutBranch === null || isTemporaryWorktreeBranch(checkedOutBranch)) {
return;
}
yield* Effect.gen(function* () {
const thread = yield* projectionSnapshotQuery
.getThreadShellById(input.threadId)
.pipe(Effect.map(Option.getOrUndefined));
if (
!thread ||
thread.branch === null ||
thread.branch === checkedOutBranch ||
thread.worktreePath === null ||
thread.worktreePath !== input.cwd ||
isTemporaryWorktreeBranch(thread.branch)
) {
return;
}
const shell = yield* projectionSnapshotQuery.getShellSnapshot();
const worktreeIsShared = shell.threads.some(
(other) => other.id !== thread.id && other.worktreePath === thread.worktreePath,
);
if (worktreeIsShared) {
return;
}
// expectedBranch makes this a compare-and-swap in the decider: if the
// recorded branch moved between our read and the dispatch (rename,
// concurrent drift-follow), the stale update is dropped.
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: yield* serverCommandId("worktree-branch-drift"),
threadId: thread.id,
branch: checkedOutBranch,
expectedBranch: thread.branch,
});
yield* Effect.logInfo("thread branch followed worktree checkout", {
threadId: thread.id,
previousBranch: thread.branch,
branch: checkedOutBranch,
});
}).pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
return Effect.logWarning("failed to follow worktree branch drift", {
threadId: input.threadId,
cause: Cause.pretty(cause),
});
}),
);
});
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
@@ -833,7 +913,7 @@ const make = Effect.gen(function* () {
const worker = yield* makeDrainableWorker(processInputSafely);
const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () {
yield* Effect.forkScoped(
yield* forkParked(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (
event.type !== "thread.turn-start-requested" &&
@@ -847,7 +927,7 @@ const make = Effect.gen(function* () {
}),
);
yield* Effect.forkScoped(
yield* forkParked(
Stream.runForEach(providerService.streamEvents, (event) => {
if (event.type !== "turn.started" && event.type !== "turn.completed") {
return Effect.void;
@@ -38,6 +38,7 @@ import {
ProviderCommandReactor,
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { forkParked, ServerActivation } from "../../serverActivation.ts";
import {
resolveSourceControlWriterModelSelection,
ServerSettingsService,
@@ -899,19 +900,25 @@ const make = Effect.gen(function* () {
...(input.title !== undefined ? { title: input.title } : {}),
});
});
const clearInterruptedThreadTitleRegenerations = Effect.fn(
"clearInterruptedThreadTitleRegenerations",
const findInterruptedThreadTitleRegenerations = Effect.fn(
"findInterruptedThreadTitleRegenerations",
)(function* () {
const readModel = yield* projectionSnapshotQuery.getCommandReadModel();
return readModel.threads.flatMap((thread) => {
const requestId = thread.titleRegeneration?.requestId;
return requestId === undefined ? [] : [{ threadId: thread.id, requestId }];
});
});
const clearInterruptedThreadTitleRegenerations = Effect.fn(
"clearInterruptedThreadTitleRegenerations",
)(function* (
interrupted: ReadonlyArray<{ readonly threadId: ThreadId; readonly requestId: CommandId }>,
) {
yield* Effect.forEach(
readModel.threads,
(thread) => {
const requestId = thread.titleRegeneration?.requestId;
if (requestId === undefined) {
return Effect.void;
}
interrupted,
({ threadId, requestId }) => {
return dispatchThreadTitleRegenerationCompletion({
threadId: thread.id,
threadId,
requestId,
}).pipe(
Effect.catchCause((cause) => {
@@ -921,7 +928,7 @@ const make = Effect.gen(function* () {
return Effect.logWarning(
"provider command reactor failed to clear interrupted title regeneration",
{
threadId: thread.id,
threadId,
cause: Cause.pretty(cause),
},
);
@@ -1304,7 +1311,7 @@ const make = Effect.gen(function* () {
processDomainEvent(event).pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
return Effect.interrupt;
}
return Effect.logWarning("provider command reactor failed to process event", {
eventType: event.type,
@@ -1316,6 +1323,17 @@ const make = Effect.gen(function* () {
const worker = yield* makeDrainableWorker(processDomainEventSafely);
const start: ProviderCommandReactorShape["start"] = Effect.fn("start")(function* () {
const interruptedTitleRegenerations = yield* findInterruptedThreadTitleRegenerations().pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.interrupt;
}
return Effect.logWarning(
"provider command reactor failed to find interrupted title regenerations",
{ cause: Cause.pretty(cause) },
).pipe(Effect.as([]));
}),
);
const processEvent = Effect.fn("processEvent")(function* (event: OrchestrationEvent) {
if (
(event.type === "thread.meta-updated" && event.payload.regenerateTitle === true) ||
@@ -1330,14 +1348,14 @@ const make = Effect.gen(function* () {
}
});
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent),
);
yield* forkParked(Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent));
// The domain event stream is hot, so work pending before this reactor
// starts cannot be resumed. Correlated completions only clear the request
// captured here, leaving any newer request untouched.
yield* clearInterruptedThreadTitleRegenerations().pipe(
const clearInterrupted = clearInterruptedThreadTitleRegenerations(
interruptedTitleRegenerations,
).pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.interrupt;
@@ -1350,6 +1368,12 @@ const make = Effect.gen(function* () {
);
}),
);
const activation = yield* ServerActivation;
if (activation === undefined) {
yield* clearInterrupted;
} else {
yield* forkParked(clearInterrupted);
}
});
return {
@@ -37,6 +37,7 @@ import {
ProviderRuntimeIngestionService,
type ProviderRuntimeIngestionShape,
} from "../Services/ProviderRuntimeIngestion.ts";
import { forkParked } from "../../serverActivation.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
@@ -1804,12 +1805,12 @@ const make = Effect.gen(function* () {
const start: ProviderRuntimeIngestionShape["start"] = () =>
Effect.gen(function* () {
yield* Effect.forkScoped(
yield* forkParked(
Stream.runForEach(providerService.streamEvents, (event) =>
worker.enqueue({ source: "runtime", event }),
),
);
yield* Effect.forkScoped(
yield* forkParked(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (event.type !== "thread.turn-start-requested") {
return Effect.void;
@@ -12,6 +12,7 @@ import {
ThreadDeletionReactor,
type ThreadDeletionReactorShape,
} from "../Services/ThreadDeletionReactor.ts";
import { forkParked } from "../../serverActivation.ts";
type ThreadDeletedEvent = Extract<OrchestrationEvent, { type: "thread.deleted" }>;
@@ -80,7 +81,7 @@ const make = Effect.gen(function* () {
const worker = yield* makeDrainableWorker(processThreadDeletedSafely);
const start: ThreadDeletionReactorShape["start"] = Effect.fn("start")(function* () {
yield* Effect.forkScoped(
yield* forkParked(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (event.type !== "thread.deleted") {
return Effect.void;
+6 -1
View File
@@ -32,8 +32,13 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
Effect.fn("environment.orchestration.snapshot")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
// Serve the lightweight command read model (thread bodies empty)
// instead of the fully hydrated snapshot. Hydrating every message
// and activity payload in the database has OOM-killed servers, and
// the route's only consumer (the project CLI) reads projects alone —
// UI clients load the shell and per-thread snapshots instead.
return yield* projectionSnapshotQuery
.getSnapshot()
.getCommandReadModel()
.pipe(
Effect.catch((cause) =>
failEnvironmentInternal("orchestration_snapshot_failed", cause),
+20 -11
View File
@@ -7,6 +7,7 @@ import type { SqlError } from "effect/unstable/sql/SqlError";
import { runMigrations } from "../Migrations.ts";
import { ServerConfig } from "../../config.ts";
import * as ServiceLauncherClient from "../../cloud/serviceLauncherClient.ts";
type RuntimeSqliteLayerConfig = {
readonly filename: string;
@@ -30,24 +31,28 @@ const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* (
return clientModule.layer(config);
}, Layer.unwrap);
const setup = Layer.effectDiscard(
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`PRAGMA journal_mode = WAL;`;
yield* sql`PRAGMA foreign_keys = ON;`;
yield* runMigrations();
}),
);
const setup = (trial: boolean) =>
Layer.effectDiscard(
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`PRAGMA foreign_keys = ON;`;
if (!trial) {
yield* sql`PRAGMA journal_mode = WAL;`;
yield* runMigrations();
}
}),
);
export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* (
dbPath: string,
options?: { readonly trial?: boolean },
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
return Layer.provideMerge(
setup,
setup(options?.trial === true),
makeRuntimeSqliteLayer({
filename: dbPath,
spanAttributes: {
@@ -59,10 +64,14 @@ export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(
}, Layer.unwrap);
export const SqlitePersistenceMemory = Layer.provideMerge(
setup,
setup(false),
makeRuntimeSqliteLayer({ filename: ":memory:" }),
);
export const layerConfig = Layer.unwrap(
Effect.map(Effect.service(ServerConfig), ({ dbPath }) => makeSqlitePersistenceLive(dbPath)),
Effect.gen(function* () {
const { dbPath } = yield* ServerConfig;
const launcher = yield* ServiceLauncherClient.resolveServiceLauncherMode();
return makeSqlitePersistenceLive(dbPath, { trial: launcher.trial });
}),
);
+3 -1
View File
@@ -9,8 +9,8 @@
*/
import * as Migrator from "effect/unstable/sql/Migrator";
import * as Layer from "effect/Layer";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
// Import all migrations statically
import Migration0001 from "./Migrations/001_OrchestrationEvents.ts";
@@ -97,6 +97,8 @@ export const migrationEntries = [
[35, "ProjectionThreadTitleRegeneration", Migration0035],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
export const makeMigrationLoader = (throughId?: number) =>
Migrator.fromRecord(
Object.fromEntries(
@@ -9,11 +9,27 @@ import * as Schema from "effect/Schema";
import {
buildClaudeCapabilitiesProbeQueryOptions,
CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES,
isLegacyClaudeModel,
probeClaudeCapabilities,
} from "./ClaudeProvider.ts";
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
it("keeps only the Claude 5 family out of legacy models", () => {
assert.deepStrictEqual(
["claude-fable-5", "claude-opus-5", "claude-sonnet-5", "claude-opus-4-8"].map((model) => [
model,
isLegacyClaudeModel(model),
]),
[
["claude-fable-5", false],
["claude-opus-5", false],
["claude-sonnet-5", false],
["claude-opus-4-8", true],
],
);
});
it("isolates Claude capability probes without dropping workspace setting sources", () => {
const abortController = new AbortController();
const options = buildClaudeCapabilitiesProbeQueryOptions({
@@ -56,7 +56,13 @@ const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
const CURRENT_CLAUDE_MODELS = new Set(["claude-fable-5", "claude-opus-5", "claude-sonnet-5"]);
export function isLegacyClaudeModel(model: string): boolean {
return !CURRENT_CLAUDE_MODELS.has(model);
}
const CLAUDE_MODEL_CATALOG: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-fable-5",
name: "Claude Fable 5",
@@ -309,6 +315,10 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = CLAUDE_MODEL_CATALOG.map((model) =>
isLegacyClaudeModel(model.slug) ? { ...model, isLegacy: true } : model,
);
function supportsClaudeOpus5(version: string | null | undefined): boolean {
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_5_VERSION) >= 0 : false;
}
@@ -1,6 +1,25 @@
import { assert, it } from "@effect/vitest";
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
import {
applyPreferredCodexDefaultModel,
isLegacyCodexModel,
mapCodexModelCapabilities,
} from "./CodexProvider.ts";
it("keeps only the GPT-5.6 Codex family out of legacy models", () => {
assert.deepStrictEqual(
["gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol", "gpt-5.4"].map((model) => [
model,
isLegacyCodexModel(model),
]),
[
["gpt-5.6-luna", false],
["gpt-5.6-terra", false],
["gpt-5.6-sol", false],
["gpt-5.4", true],
],
);
});
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
@@ -62,6 +62,11 @@ const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
};
const DEFAULT_SERVICE_TIER_ID = "default";
const CURRENT_CODEX_MODELS = new Set(["gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol"]);
export function isLegacyCodexModel(model: string): boolean {
return !CURRENT_CODEX_MODELS.has(model);
}
function reasoningEffortLabel(reasoningEffort: string): string {
return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
@@ -190,6 +195,7 @@ function parseCodexModelListResponse(
name: toDisplayName(model),
isCustom: false,
...(model.isDefault ? { isDefault: true } : {}),
...(isLegacyCodexModel(model.model) ? { isLegacy: true } : {}),
capabilities: mapCodexModelCapabilities(model),
}));
}
@@ -11,6 +11,7 @@ import {
ProviderSessionReaper,
type ProviderSessionReaperShape,
} from "../Services/ProviderSessionReaper.ts";
import { forkParked } from "../../serverActivation.ts";
import { ProviderService } from "../Services/ProviderService.ts";
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
@@ -105,7 +106,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
const start: ProviderSessionReaperShape["start"] = () =>
Effect.gen(function* () {
yield* Effect.forkScoped(
yield* forkParked(
sweep.pipe(
Effect.catch((error: unknown) =>
Effect.logWarning("provider.session.reaper.sweep-failed", {
+3 -2
View File
@@ -44,6 +44,7 @@ import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/environme
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import { forkParked } from "../serverActivation.ts";
export class AgentAwarenessRelay extends Context.Service<
AgentAwarenessRelay,
@@ -599,12 +600,12 @@ export const make = Effect.gen(function* () {
});
break;
}
yield* Effect.forkScoped(
yield* forkParked(
Effect.sleep("1 second").pipe(
Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
),
);
yield* Effect.forkScoped(
yield* forkParked(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
const threadId = eventThreadId(event);
if (threadId === null) {
+184 -4
View File
@@ -89,6 +89,7 @@ import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
import * as ServerSettings from "./serverSettings.ts";
import * as TerminalManager from "./terminal/Manager.ts";
import * as PreviewManager from "./preview/Manager.ts";
@@ -550,10 +551,13 @@ const buildAppUnderTest = (options?: {
),
);
const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, {
disableListenLog: true,
disableLogger: true,
}).pipe(
const servedRoutesLayer = HttpRouter.serve(
makeRoutesLayer.pipe(Layer.provide(ServiceLauncherClient.layer)),
{
disableListenLog: true,
disableLogger: true,
},
).pipe(
Layer.provide(
Layer.mock(Keybindings.Keybindings)({
loadConfigState: Effect.succeed({
@@ -1318,6 +1322,39 @@ const getWsServerUrl = (
});
it.layer(NodeServices.layer)("server router seam", (it) => {
it.effect("parks HTTP ingress until command readiness", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-gate-" });
yield* fileSystem.writeFileString(path.join(staticDir, "index.html"), "ready");
const entered = yield* Deferred.make<void>();
const ready = yield* Deferred.make<void>();
const completed = yield* Deferred.make<void>();
yield* buildAppUnderTest({
config: { staticDir },
layers: {
serverRuntimeStartup: {
awaitCommandReady: Deferred.succeed(entered, undefined).pipe(
Effect.andThen(Deferred.await(ready)),
),
},
},
});
const request = yield* HttpClient.get("/").pipe(
Effect.tap(() => Deferred.succeed(completed, undefined)),
Effect.forkChild,
);
yield* Deferred.await(entered);
assert.isFalse(yield* Deferred.isDone(completed));
yield* Deferred.succeed(ready, undefined);
assert.equal((yield* Fiber.join(request)).status, 200);
assert.isTrue(yield* Deferred.isDone(completed));
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("serves static index content for GET / when staticDir is configured", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -6005,6 +6042,149 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
);
it.effect("subscribeThread sends a fresh snapshot instead of replaying a large gap", () =>
Effect.gen(function* () {
let readEventsCalls = 0;
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
yield* buildAppUnderTest({
layers: {
orchestrationEngine: {
// Head is far ahead of the client's afterSequence (gap > 1000).
latestSequence: Effect.succeed(100_000),
readEvents: () =>
Stream.sync(() => {
readEventsCalls += 1;
return {} as OrchestrationEvent;
}),
},
projectionSnapshotQuery: {
getThreadDetailSnapshot: () =>
Effect.succeed(Option.some({ snapshotSequence: 100_000, thread })),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const items = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: defaultThreadId,
afterSequence: 5,
requestCompletionMarker: true,
}).pipe(Stream.take(2), Stream.runCollect),
),
);
const [first, second] = Array.from(items);
// Large gap => fresh thread snapshot, and the global replay never starts.
assert.equal(first?.kind, "snapshot");
if (first?.kind === "snapshot") {
assert.equal(first.snapshot.thread.id, defaultThreadId);
assert.equal(first.snapshot.snapshotSequence, 100_000);
}
assert.equal(second?.kind, "synchronized");
assert.equal(readEventsCalls, 0);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("subscribeThread replaces a cursor ahead of the authoritative head", () =>
Effect.gen(function* () {
let readEventsCalls = 0;
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
yield* buildAppUnderTest({
layers: {
orchestrationEngine: {
latestSequence: Effect.succeed(5),
readEvents: () =>
Stream.sync(() => {
readEventsCalls += 1;
return {} as OrchestrationEvent;
}),
},
projectionSnapshotQuery: {
getThreadDetailSnapshot: () =>
Effect.succeed(Option.some({ snapshotSequence: 5, thread })),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const first = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: defaultThreadId,
afterSequence: 10,
}).pipe(Stream.runHead),
),
);
assert.equal(Option.getOrThrow(first).kind, "snapshot");
assert.equal(readEventsCalls, 0);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("subscribeThread bounds catch-up replay to the captured head", () =>
Effect.gen(function* () {
let replayLimit: number | undefined;
const now = "2026-01-01T00:00:00.000Z";
const messageEvent = {
sequence: 3,
eventId: EventId.make("event-replay-message"),
aggregateKind: "thread",
aggregateId: defaultThreadId,
occurredAt: now,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.message-sent",
payload: {
threadId: defaultThreadId,
messageId: MessageId.make("message-replay"),
role: "user",
text: "Replayed message",
turnId: null,
streaming: false,
createdAt: now,
updatedAt: now,
},
} satisfies Extract<OrchestrationEvent, { type: "thread.message-sent" }>;
yield* buildAppUnderTest({
layers: {
orchestrationEngine: {
latestSequence: Effect.succeed(50),
readEvents: (_afterSequence, limit) => {
replayLimit = limit;
return Stream.make(messageEvent);
},
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const items = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: defaultThreadId,
afterSequence: 0,
requestCompletionMarker: true,
}).pipe(Stream.take(2), Stream.runCollect),
),
);
const [first, second] = Array.from(items);
assert.equal(first?.kind, "event");
assert.equal(first?.kind === "event" ? first.event.sequence : null, 3);
assert.equal(second?.kind, "synchronized");
// The replay is bounded to the head captured before the read, not
// Number.MAX_SAFE_INTEGER.
assert.equal(replayLimit, 50);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("subscribeShell sends a fresh snapshot instead of replaying a large gap", () =>
Effect.gen(function* () {
let readEventsCalls = 0;
+102 -60
View File
@@ -1,5 +1,6 @@
import { EnvironmentHttpApi } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schedule from "effect/Schedule";
@@ -91,6 +92,7 @@ import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts"
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
import * as CloudCliState from "./cloud/CliState.ts";
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
@@ -109,6 +111,7 @@ import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
import * as NetService from "@t3tools/shared/Net";
import * as RelayClient from "@t3tools/shared/relayClient";
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
import { forkParked, ServerActivation } from "./serverActivation.ts";
// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
@@ -396,8 +399,12 @@ const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
Layer.provide(NetService.layer),
);
const RuntimeServicesLive = ServerRuntimeStartup.layer.pipe(
Layer.provideMerge(RuntimeDependenciesLive),
const commandReadinessLayer = HttpRouter.middleware(
(httpEffect) =>
Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>
startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),
),
{ global: true },
);
export const makeRoutesLayer = Layer.mergeAll(
@@ -418,6 +425,7 @@ export const makeRoutesLayer = Layer.mergeAll(
).pipe(
Layer.provide(PreviewAutomationBroker.layer),
Layer.provide(ServerSelfUpdate.layer),
Layer.provide(commandReadinessLayer),
Layer.provide(browserApiCorsLayer),
Layer.provide(httpCompressionLayer),
);
@@ -425,6 +433,14 @@ export const makeRoutesLayer = Layer.mergeAll(
export const makeServerLayer = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const activation = yield* Deferred.make<void>();
const awaitActivation = Deferred.await(activation);
const activationLayer = Layer.succeed(ServerActivation, awaitActivation);
const runtimeStateParked = yield* Deferred.make<void>();
const tailscaleParked = yield* Deferred.make<void>();
const cloudLinkParked = yield* Deferred.make<void>();
const routesReady = yield* Deferred.make<void>();
const launcherLayer = ServiceLauncherClient.layer;
yield* fixPath();
@@ -438,6 +454,8 @@ export const makeServerLayer = Layer.unwrap(
const runtimeStateLayer = Layer.effectDiscard(
Effect.acquireRelease(
Effect.gen(function* () {
yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);
yield* awaitActivation;
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) {
@@ -451,15 +469,26 @@ export const makeServerLayer = Layer.unwrap(
yield* persistServerRuntimeState({
path: config.serverRuntimeStatePath,
state,
});
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Failed to persist server runtime state", { cause }),
),
);
}),
() => clearPersistedServerRuntimeState(config.serverRuntimeStatePath),
() =>
clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Failed to clear server runtime state", { cause }),
),
),
),
);
const tailscaleServeLayer = config.tailscaleServeEnabled
? Layer.effectDiscard(
Effect.acquireRelease(
Effect.gen(function* () {
yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);
yield* awaitActivation;
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) {
@@ -509,68 +538,80 @@ export const makeServerLayer = Layer.unwrap(
: Layer.empty;
const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(
Effect.gen(function* () {
if (!hasCloudPublicConfig) return;
// Idle Cloudflare tunnels are billed, so a stopping server releases its
// tunnel; the persisted desired link brings one back — same hostname,
// fresh tunnel — when the environment starts again. Registered even
// when no link is desired yet: a client can link a running server, and
// that tunnel needs the same disposal on shutdown.
yield* Effect.addFinalizer(() =>
releaseManagedTunnelOnShutdown().pipe(
Effect.timeout("10 seconds"),
Effect.tap((released) =>
released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
),
Effect.catchCause((cause) =>
Effect.logWarning(
"Failed to release the managed tunnel on shutdown; the next link reuses it",
{ cause },
),
),
Effect.asVoid,
),
);
if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) return;
yield* Effect.forkScoped(
Effect.sleep("250 millis").pipe(
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
// On reboot this races NIC/DNS bring-up, so back off exponentially
// (capped at 30s) instead of burning all retries in a second.
// Bounded overall so a permanently broken setup still surfaces the
// warning below. Bad-request/unauthorized/conflict are
// deterministic failures (malformed origin, not linked yet, linked
// to a different cloud account) that no amount of retrying
// converges.
Effect.retry({
while: (error) =>
error._tag !== "EnvironmentHttpBadRequestError" &&
error._tag !== "EnvironmentHttpUnauthorizedError" &&
error._tag !== "EnvironmentHttpConflictError",
schedule: Schedule.exponential("1 second").pipe(
Schedule.modifyDelay(({ duration }) =>
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
if (!hasCloudPublicConfig) {
yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
return;
}
yield* forkParked(
Effect.gen(function* () {
// Only an activated runtime owns the tunnel cleanup finalizer.
yield* Effect.addFinalizer(() =>
releaseManagedTunnelOnShutdown().pipe(
Effect.timeout("10 seconds"),
Effect.tap((released) =>
released
? Effect.logInfo("Released the managed tunnel on shutdown")
: Effect.void,
),
Schedule.upTo({ duration: "10 minutes" }),
Effect.catchCause((cause) =>
Effect.logWarning(
"Failed to release the managed tunnel on shutdown; the next link reuses it",
{ cause },
),
),
Effect.asVoid,
),
}),
Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
Effect.catch((cause) =>
Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
cause,
);
if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) return;
yield* Effect.sleep("250 millis").pipe(
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
Effect.retry({
while: (error) =>
error._tag !== "EnvironmentHttpBadRequestError" &&
error._tag !== "EnvironmentHttpUnauthorizedError" &&
error._tag !== "EnvironmentHttpConflictError",
schedule: Schedule.exponential("1 second").pipe(
Schedule.modifyDelay(({ duration }) =>
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
),
Schedule.upTo({ duration: "10 minutes" }),
),
}),
),
),
Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
Effect.catch((cause) =>
Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
cause,
}),
),
);
}),
);
yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
}),
);
const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({
activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),
awaitAuxiliaryParked: Effect.all(
[
Deferred.await(runtimeStateParked),
Deferred.await(cloudLinkParked),
Deferred.await(routesReady),
...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),
],
{ concurrency: "unbounded" },
).pipe(Effect.asVoid),
}).pipe(Layer.provideMerge(RuntimeDependenciesLive), Layer.provide(launcherLayer));
const routesLayer = HttpRouter.serve(makeRoutesLayer.pipe(Layer.provide(launcherLayer)), {
disableLogger: !config.logWebSocketEvents,
}).pipe(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));
const serverApplicationLayer = Layer.mergeAll(
HttpRouter.serve(makeRoutesLayer, {
disableLogger: !config.logWebSocketEvents,
}),
routesLayer,
httpListeningLayer,
runtimeStateLayer,
tailscaleServeLayer,
@@ -578,7 +619,8 @@ export const makeServerLayer = Layer.unwrap(
);
return serverApplicationLayer.pipe(
Layer.provideMerge(RuntimeServicesLive),
Layer.provideMerge(runtimeServicesLive),
Layer.provide(activationLayer),
Layer.provideMerge(serverRelayBrokerTracingLayer),
Layer.provideMerge(HttpResponseCompressionLive),
Layer.provideMerge(HttpServerLive),
@@ -590,5 +632,5 @@ export const makeServerLayer = Layer.unwrap(
}),
);
// Important: Only `ServerConfig` should be provided by the CLI layer!!! Don't let other requirements leak into the launch layer.
// The CLI supplies configuration.
export const runServer = Layer.launch(makeServerLayer);
+23
View File
@@ -0,0 +1,23 @@
import { expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import { forkParked, ServerActivation } from "./serverActivation.ts";
it.effect("proves a root is parked before returning and releases it with one gate", () =>
Effect.scoped(
Effect.gen(function* () {
const activation = yield* Deferred.make<void>();
const ran = yield* Deferred.make<void>();
yield* forkParked(Deferred.succeed(ran, undefined)).pipe(
Effect.provideService(ServerActivation, Deferred.await(activation)),
);
expect(yield* Deferred.isDone(ran)).toBe(false);
yield* Deferred.succeed(activation, undefined);
yield* Deferred.await(ran);
expect(yield* Deferred.isDone(ran)).toBe(true);
}),
),
);
+26
View File
@@ -0,0 +1,26 @@
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import type * as Scope from "effect/Scope";
export class ServerActivation extends Context.Reference<Effect.Effect<void> | undefined>(
"t3/serverActivation",
{ defaultValue: () => undefined },
) {}
/** Forks a long-running root before commit and proves it is parked at the activation boundary. */
export const forkParked = <A, E, R>(
effect: Effect.Effect<A, E, R>,
): Effect.Effect<void, never, Scope.Scope | R> =>
Effect.gen(function* () {
const activation = yield* ServerActivation;
if (activation === undefined) {
yield* Effect.forkScoped(effect);
return;
}
const parked = yield* Deferred.make<void>();
yield* Effect.forkScoped(
Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)),
);
yield* Deferred.await(parked);
});
Loaded 100 of 253 files, more files were not shown because too many files have changed in this diff. Show more