Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21ef91a087 | ||
|
|
28966761e1 | ||
|
|
d58dba29c7 | ||
|
|
f2fd69d8d7 | ||
|
|
33ce2d2869 | ||
|
|
9f812dd83d | ||
|
|
34e6f78fe7 | ||
|
|
d2cb3d016f | ||
|
|
e71933771d | ||
|
|
4e4cb07265 | ||
|
|
41ebf22eea | ||
|
|
3d429662c9 | ||
|
|
7b38fb5c6b | ||
|
|
7537adc30f | ||
|
|
94696b0f54 | ||
|
|
fff6a5b028 | ||
|
|
da6e1a9678 | ||
|
|
8eca20005b | ||
|
|
2fa1fec8d8 | ||
|
|
9bd2a4c688 | ||
|
|
4fb03aff0b | ||
|
|
d7950ac153 | ||
|
|
36caf34c68 | ||
|
|
90e3778660 | ||
|
|
94331c58ec | ||
|
|
c30a6d9b99 | ||
|
|
37ae1abbe9 | ||
|
|
82b76e2138 | ||
|
|
8a16cadbaf | ||
|
|
2b1d4fecb8 | ||
|
|
cec1bb9de3 | ||
|
|
25ec0b9d13 | ||
|
|
966cc05a90 | ||
|
|
1cbd88aba0 | ||
|
|
553867262c | ||
|
|
11639bf439 | ||
|
|
a261a6440a | ||
|
|
6f04a5cffb | ||
|
|
30c9622806 | ||
|
|
69dfb7f09a | ||
|
|
e60821f0e0 | ||
|
|
64bf016191 | ||
|
|
5192f777fe | ||
|
|
283c7ac4ba | ||
|
|
78eb3ecae9 | ||
|
|
d3037064e6 |
No files matched your search
@@ -9,6 +9,7 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
@@ -17,7 +18,9 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
@@ -220,20 +223,49 @@ const startup = Effect.gen(function* () {
|
||||
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
|
||||
yield* shellEnvironment.installIntoProcess;
|
||||
const hasCommandLinePasswordStore =
|
||||
preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
|
||||
const linuxElectronOptions =
|
||||
environment.platform === "linux" && !hasCommandLinePasswordStore
|
||||
? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess()
|
||||
: preReadyElectronOptions.linux;
|
||||
if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
|
||||
if (
|
||||
linuxElectronOptions.passwordStore !== null ||
|
||||
preReadyElectronOptions.linux?.passwordStore !== null
|
||||
) {
|
||||
yield* electronApp.removeCommandLineSwitch("password-store");
|
||||
}
|
||||
if (linuxElectronOptions.passwordStore !== null) {
|
||||
yield* electronApp.appendCommandLineSwitch(
|
||||
"password-store",
|
||||
linuxElectronOptions.passwordStore,
|
||||
);
|
||||
}
|
||||
}
|
||||
const userDataPath = yield* appIdentity.resolveUserDataPath;
|
||||
yield* electronApp.setPath("userData", userDataPath);
|
||||
yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
|
||||
yield* desktopSettings.load;
|
||||
|
||||
if (environment.platform === "linux") {
|
||||
yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
|
||||
if (linuxElectronOptions !== null) {
|
||||
yield* logStartupInfo("linux password store configured", {
|
||||
passwordStore: hasCommandLinePasswordStore
|
||||
? "command-line"
|
||||
: (linuxElectronOptions.passwordStore ?? "electron-default"),
|
||||
xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null,
|
||||
xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
yield* appIdentity.configure;
|
||||
@@ -245,9 +277,16 @@ const startup = Effect.gen(function* () {
|
||||
Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
|
||||
);
|
||||
yield* logStartupInfo("app ready");
|
||||
if (environment.platform === "linux") {
|
||||
const selectedBackend = yield* safeStorage.selectedStorageBackend;
|
||||
yield* logStartupInfo("safe storage ready", {
|
||||
backend: Option.getOrElse(selectedBackend, () => "unknown"),
|
||||
});
|
||||
}
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* updates.configure;
|
||||
yield* linuxUrlHandler.register;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
|
||||
|
||||
@@ -64,6 +64,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ const compactEnv = (env: Readonly<Record<string, string | undefined>>): Record<s
|
||||
export const DesktopConfig = Config.all({
|
||||
appDataDirectory: trimmedString("APPDATA"),
|
||||
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
|
||||
xdgDataHome: trimmedString("XDG_DATA_HOME"),
|
||||
t3Home: trimmedString("T3CODE_HOME"),
|
||||
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
|
||||
appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"),
|
||||
|
||||
@@ -39,6 +39,7 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
|
||||
return decoded.slice("encrypted:".length);
|
||||
});
|
||||
},
|
||||
selectedStorageBackend: Effect.succeed(Option.none()),
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - tests use POSIX path joining to match the Linux startup boundary.
|
||||
import * as NodePath from "node:path";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
resolveEarlyLinuxElectronOptions,
|
||||
resolveEarlyLinuxPasswordStorePreference,
|
||||
} from "./DesktopEarlyElectronStartup.ts";
|
||||
|
||||
describe("DesktopEarlyElectronStartup", () => {
|
||||
const joinPath = NodePath.posix.join;
|
||||
|
||||
it("reads the persisted linux password-store preference before Electron is ready", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/home/user/.t3-test" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet6");
|
||||
});
|
||||
|
||||
it("accepts JSONC in the early desktop settings file", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/home/user/.t3-test" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: () => `{
|
||||
// manually edited setting
|
||||
"linuxPasswordStore": "gnome-libsecret",
|
||||
}`,
|
||||
});
|
||||
|
||||
assert.equal(preference, "gnome-libsecret");
|
||||
});
|
||||
|
||||
it("falls back to auto when the early settings document is missing or invalid", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: () => {
|
||||
throw new Error("missing");
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "auto");
|
||||
});
|
||||
|
||||
it("preserves absolute root paths when resolving early settings", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet6");
|
||||
});
|
||||
|
||||
it("resolves the early linux Electron switches", () => {
|
||||
const options = resolveEarlyLinuxElectronOptions({
|
||||
env: {
|
||||
T3CODE_HOME: "/home/user/.t3-test",
|
||||
XDG_CURRENT_DESKTOP: "niri",
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "auto" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(options, {
|
||||
linuxWmClass: "t3code-dev",
|
||||
passwordStore: "gnome-libsecret",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps implicit development state under ~/.t3/dev when T3CODE_HOME is unset", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet");
|
||||
});
|
||||
|
||||
it("treats whitespace-only T3CODE_HOME as unconfigured in development", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {
|
||||
T3CODE_HOME: " ",
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "gnome-libsecret" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "gnome-libsecret");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
DEFAULT_LINUX_PASSWORD_STORE,
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
resolveLinuxPasswordStoreSwitch,
|
||||
type LinuxPasswordStoreSwitch,
|
||||
type LinuxPasswordStorePreference,
|
||||
} from "../linuxSecretStorage.ts";
|
||||
import {
|
||||
resolveDesktopBaseDir,
|
||||
resolveDesktopStateDir,
|
||||
type JoinPath,
|
||||
} from "./DesktopStatePaths.ts";
|
||||
|
||||
interface EarlyDesktopSettingsInput {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly readFileString: (path: string) => string;
|
||||
}
|
||||
|
||||
type EarlyLinuxElectronOptionsInput = EarlyDesktopSettingsInput;
|
||||
|
||||
export interface EarlyLinuxElectronOptions {
|
||||
readonly linuxWmClass: string;
|
||||
readonly passwordStore: LinuxPasswordStoreSwitch | null;
|
||||
}
|
||||
|
||||
const trimNonEmpty = (value: string | undefined): string | null => {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed && trimmed.length > 0 ? trimmed : null;
|
||||
};
|
||||
|
||||
const EarlyDesktopSettingsJson = fromLenientJson(
|
||||
Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
|
||||
}),
|
||||
);
|
||||
const decodeEarlyDesktopSettingsJson = Schema.decodeSync(EarlyDesktopSettingsJson);
|
||||
|
||||
const isDevelopmentEnvironment = (env: NodeJS.ProcessEnv): boolean =>
|
||||
trimNonEmpty(env.VITE_DEV_SERVER_URL) !== null;
|
||||
|
||||
function resolveEarlyDesktopSettingsPath(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
}): string {
|
||||
const t3Home = Option.fromUndefinedOr(input.env.T3CODE_HOME);
|
||||
const baseDir = resolveDesktopBaseDir({
|
||||
homeDirectory: input.homeDirectory,
|
||||
joinPath: input.joinPath,
|
||||
t3Home,
|
||||
});
|
||||
const stateDir = resolveDesktopStateDir({
|
||||
baseDir,
|
||||
isDevelopment: isDevelopmentEnvironment(input.env),
|
||||
joinPath: input.joinPath,
|
||||
t3Home,
|
||||
});
|
||||
return input.joinPath(stateDir, "desktop-settings.json");
|
||||
}
|
||||
|
||||
export function resolveEarlyLinuxPasswordStorePreference(
|
||||
input: EarlyDesktopSettingsInput,
|
||||
): LinuxPasswordStorePreference {
|
||||
const settingsPath = resolveEarlyDesktopSettingsPath(input);
|
||||
try {
|
||||
const parsed = decodeEarlyDesktopSettingsJson(input.readFileString(settingsPath));
|
||||
return normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore);
|
||||
} catch {
|
||||
return DEFAULT_LINUX_PASSWORD_STORE;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveEarlyLinuxElectronOptions(
|
||||
input: EarlyLinuxElectronOptionsInput,
|
||||
): EarlyLinuxElectronOptions {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference(input);
|
||||
return {
|
||||
linuxWmClass: isDevelopmentEnvironment(input.env) ? "t3code-dev" : "t3code",
|
||||
passwordStore: resolveLinuxPasswordStoreSwitch({
|
||||
preference,
|
||||
env: input.env,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import * as Path from "effect/Path";
|
||||
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
|
||||
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
|
||||
|
||||
export interface MakeDesktopEnvironmentInput {
|
||||
@@ -66,6 +67,8 @@ export class DesktopEnvironment extends Context.Service<
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly linuxApplicationsDir: string;
|
||||
readonly appImagePath: Option.Option<string>;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
|
||||
@@ -147,8 +150,11 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
: input.platform === "darwin"
|
||||
? path.join(homeDirectory, "Library", "Application Support")
|
||||
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
|
||||
const configuredBaseDir = config.t3Home;
|
||||
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
|
||||
const baseDir = resolveDesktopBaseDir({
|
||||
homeDirectory,
|
||||
joinPath: path.join,
|
||||
t3Home: config.t3Home,
|
||||
});
|
||||
const rootDir = path.resolve(input.dirname, "../../..");
|
||||
const appRoot = input.isPackaged ? input.appPath : rootDir;
|
||||
const branding = resolveDesktopAppBranding({
|
||||
@@ -156,12 +162,18 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
appVersion: input.appVersion,
|
||||
});
|
||||
const displayName = branding.displayName;
|
||||
const stateDir = path.join(
|
||||
const stateDir = resolveDesktopStateDir({
|
||||
baseDir,
|
||||
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
|
||||
);
|
||||
isDevelopment,
|
||||
joinPath: path.join,
|
||||
t3Home: config.t3Home,
|
||||
});
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const linuxApplicationsDir = path.join(
|
||||
Option.getOrElse(config.xdgDataHome, () => path.join(homeDirectory, ".local", "share")),
|
||||
"applications",
|
||||
);
|
||||
const resourcesPath = input.resourcesPath;
|
||||
|
||||
return DesktopEnvironment.of({
|
||||
@@ -205,6 +217,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
),
|
||||
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
|
||||
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
|
||||
linuxApplicationsDir,
|
||||
appImagePath: config.appImagePath,
|
||||
userDataDirName,
|
||||
legacyUserDataDirName,
|
||||
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
|
||||
|
||||
@@ -35,6 +35,7 @@ describe("DesktopLifecycle", () => {
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
|
||||
|
||||
interface RecordedRegistration {
|
||||
readonly directories: string[];
|
||||
readonly files: Array<{ readonly path: string; readonly content: string }>;
|
||||
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
|
||||
}
|
||||
|
||||
const makeEnvironment = (overrides: Record<string, unknown> = {}) =>
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
platform: "linux",
|
||||
isPackaged: true,
|
||||
isDevelopment: false,
|
||||
displayName: "T3 Code (Alpha)",
|
||||
linuxWmClass: "t3code",
|
||||
linuxApplicationsDir: "/home/alice/.local/share/applications",
|
||||
appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
|
||||
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
|
||||
...overrides,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
const mockProcess = (exitCode: number) =>
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
|
||||
const makeHandlerLayer = (
|
||||
recorded: RecordedRegistration,
|
||||
input: {
|
||||
readonly environment?: Record<string, unknown>;
|
||||
readonly xdgMimeExitCode?: number;
|
||||
readonly writeError?: PlatformError.PlatformError;
|
||||
} = {},
|
||||
) =>
|
||||
DesktopLinuxUrlHandler.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(DesktopEnvironment.DesktopEnvironment, makeEnvironment(input.environment)),
|
||||
FileSystem.layerNoop({
|
||||
makeDirectory: (path) =>
|
||||
Effect.sync(() => {
|
||||
recorded.directories.push(path);
|
||||
}),
|
||||
writeFileString: (path, content) =>
|
||||
input.writeError
|
||||
? Effect.fail(input.writeError)
|
||||
: Effect.sync(() => {
|
||||
recorded.files.push({ path, content });
|
||||
}),
|
||||
}),
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
recorded.commands.push({
|
||||
command: childProcess.command,
|
||||
args: childProcess.args,
|
||||
});
|
||||
return Effect.succeed(mockProcess(input.xdgMimeExitCode ?? 0));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const runRegister = (
|
||||
recorded: RecordedRegistration,
|
||||
input: Parameters<typeof makeHandlerLayer>[1] = {},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
|
||||
yield* handler.register;
|
||||
}).pipe(Effect.provide(makeHandlerLayer(recorded, input)));
|
||||
|
||||
const emptyRecording = (): RecordedRegistration => ({
|
||||
directories: [],
|
||||
files: [],
|
||||
commands: [],
|
||||
});
|
||||
|
||||
describe("DesktopLinuxUrlHandler", () => {
|
||||
it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
|
||||
const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
|
||||
displayName: "T3 Code (Nightly)",
|
||||
execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
|
||||
scheme: "t3code",
|
||||
});
|
||||
|
||||
assert.include(entry, "[Desktop Entry]");
|
||||
assert.include(entry, "Name=T3 Code (Nightly)");
|
||||
// Exec composes both escaping layers: a literal backslash becomes four
|
||||
// backslashes in the file, a quote three characters, a dollar sign two
|
||||
// backslashes plus the sign.
|
||||
assert.include(
|
||||
entry,
|
||||
'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
|
||||
);
|
||||
assert.include(entry, "NoDisplay=true");
|
||||
assert.notInclude(entry, "StartupWMClass=");
|
||||
assert.include(entry, "MimeType=x-scheme-handler/t3code;");
|
||||
});
|
||||
|
||||
it("carries structured context on registration errors", () => {
|
||||
const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "write-desktop-entry",
|
||||
scheme: "t3code",
|
||||
desktopEntryPath: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
cause: new Error("boom"),
|
||||
});
|
||||
assert.equal(
|
||||
writeError.message,
|
||||
"Failed to register the t3code:// URL handler (step: write-desktop-entry).",
|
||||
);
|
||||
assert.equal(
|
||||
writeError.desktopEntryPath,
|
||||
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
);
|
||||
|
||||
const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme: "t3code",
|
||||
exitCode: 4,
|
||||
});
|
||||
assert.equal(
|
||||
exitError.message,
|
||||
"Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).",
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("writes the handler entry and claims the scheme default via xdg-mime", () => {
|
||||
const recorded = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(recorded);
|
||||
|
||||
assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
|
||||
assert.equal(recorded.files.length, 1);
|
||||
assert.equal(
|
||||
recorded.files[0]?.path,
|
||||
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
);
|
||||
assert.include(
|
||||
recorded.files[0]?.content,
|
||||
'Exec="/home/alice/Applications/T3-Code.AppImage" %U',
|
||||
);
|
||||
assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
|
||||
assert.deepEqual(recorded.commands, [
|
||||
{
|
||||
command: "xdg-mime",
|
||||
args: ["default", "t3code-url-handler.desktop", "x-scheme-handler/t3code"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("falls back to the process executable outside an AppImage", () => {
|
||||
const recorded = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
|
||||
|
||||
assert.include(
|
||||
recorded.files[0]?.content,
|
||||
`Exec=${DesktopLinuxUrlHandler.escapeDesktopEntryExecArgument(process.execPath)} %U`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("does nothing on other platforms or unpackaged builds", () => {
|
||||
const nonLinux = emptyRecording();
|
||||
const unpackaged = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
|
||||
yield* runRegister(unpackaged, { environment: { isPackaged: false } });
|
||||
|
||||
for (const recorded of [nonLinux, unpackaged]) {
|
||||
assert.deepEqual(recorded.directories, []);
|
||||
assert.deepEqual(recorded.files, []);
|
||||
assert.deepEqual(recorded.commands, []);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("never fails startup when registration cannot complete", () => {
|
||||
const xdgMimeFailed = emptyRecording();
|
||||
const writeFailed = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
|
||||
yield* runRegister(writeFailed, {
|
||||
writeError: PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "writeFileString",
|
||||
description: "read-only filesystem",
|
||||
pathOrDescriptor: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(xdgMimeFailed.files.length, 1);
|
||||
assert.deepEqual(writeFailed.commands, []);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "./DesktopObservability.ts";
|
||||
|
||||
// Linux ships as an AppImage, so the .desktop entry users end up with is
|
||||
// created by whatever integration tool they use (AppImageLauncher names it
|
||||
// appimagekit_<hash>-….desktop) and its filename is not under our control.
|
||||
// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
|
||||
// setDesktopName, which cannot match those files — so the browser keeps
|
||||
// prompting "Choose an application" for every OAuth callback. Instead, write
|
||||
// our own handler entry pointing at the current AppImage and claim the
|
||||
// scheme default via xdg-mime, exactly what the file manager's "set as
|
||||
// default" checkbox would record in mimeapps.list.
|
||||
export const URL_HANDLER_DESKTOP_ENTRY_NAME = "t3code-url-handler.desktop";
|
||||
|
||||
const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
|
||||
|
||||
export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedErrorClass<DesktopLinuxUrlHandlerRegistrationError>()(
|
||||
"DesktopLinuxUrlHandlerRegistrationError",
|
||||
{
|
||||
step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
|
||||
scheme: Schema.String,
|
||||
desktopEntryPath: Schema.optionalKey(Schema.String),
|
||||
exitCode: Schema.optionalKey(Schema.Number),
|
||||
cause: Schema.optionalKey(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
|
||||
return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
|
||||
}
|
||||
}
|
||||
|
||||
const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
|
||||
|
||||
const escapeDesktopEntryString = (value: string): string =>
|
||||
value
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll("\n", "\\n")
|
||||
.replaceAll("\r", "\\r")
|
||||
.replaceAll("\t", "\\t");
|
||||
|
||||
// Exec values are unescaped twice by implementations: first the general
|
||||
// string-value rules, then the Exec quoting rules — so writing composes the
|
||||
// layers in reverse. The argument is double-quoted with reserved characters
|
||||
// backslash-escaped and literal percent signs doubled (field codes), and the
|
||||
// general string escaping is applied on top: a literal backslash ends up as
|
||||
// four backslashes in the file, a quote as \\", a dollar sign as \\$.
|
||||
export function escapeDesktopEntryExecArgument(value: string): string {
|
||||
const quoted = value
|
||||
.replaceAll("\\", () => "\\\\")
|
||||
.replaceAll("`", () => "\\`")
|
||||
.replaceAll("$", () => "\\$")
|
||||
.replaceAll('"', () => '\\"')
|
||||
.replaceAll("%", () => "%%");
|
||||
return escapeDesktopEntryString(`"${quoted}"`);
|
||||
}
|
||||
|
||||
// The AppImage integration entry owns the window identity and icon. This
|
||||
// hidden URL-only entry must not compete with it for StartupWMClass matching.
|
||||
export function renderUrlHandlerDesktopEntry(input: {
|
||||
readonly displayName: string;
|
||||
readonly execTarget: string;
|
||||
readonly scheme: string;
|
||||
}): string {
|
||||
return [
|
||||
"[Desktop Entry]",
|
||||
"Type=Application",
|
||||
`Name=${escapeDesktopEntryString(input.displayName)}`,
|
||||
`Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
|
||||
"Terminal=false",
|
||||
"NoDisplay=true",
|
||||
"StartupNotify=false",
|
||||
`MimeType=x-scheme-handler/${input.scheme};`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export class DesktopLinuxUrlHandler extends Context.Service<
|
||||
DesktopLinuxUrlHandler,
|
||||
{
|
||||
readonly register: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
|
||||
const desktopEntryPath = environment.path.join(
|
||||
environment.linuxApplicationsDir,
|
||||
URL_HANDLER_DESKTOP_ENTRY_NAME,
|
||||
);
|
||||
|
||||
const writeDesktopEntry = Effect.gen(function* () {
|
||||
// Inside the mounted AppImage, process.execPath points at a transient
|
||||
// /tmp/.mount_* path — the handler must launch the AppImage itself.
|
||||
const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
|
||||
yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
desktopEntryPath,
|
||||
renderUrlHandlerDesktopEntry({
|
||||
displayName: environment.displayName,
|
||||
execTarget,
|
||||
scheme,
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "write-desktop-entry",
|
||||
scheme,
|
||||
desktopEntryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const setDefaultHandler = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
"xdg-mime",
|
||||
["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) {
|
||||
return yield* new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme,
|
||||
exitCode: Number(exitCode),
|
||||
});
|
||||
}
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((error) =>
|
||||
isRegistrationError(error)
|
||||
? error
|
||||
: new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const register = Effect.gen(function* () {
|
||||
if (environment.platform !== "linux" || !environment.isPackaged) {
|
||||
return;
|
||||
}
|
||||
yield* writeDesktopEntry;
|
||||
yield* setDefaultHandler;
|
||||
yield* logInfo("registered URL scheme handler", { scheme });
|
||||
}).pipe(
|
||||
// Registration is best-effort: a missing xdg-mime or read-only home must
|
||||
// never block startup — the OS chooser remains as fallback.
|
||||
Effect.catch((error) =>
|
||||
logWarning("URL scheme handler registration failed", {
|
||||
scheme,
|
||||
step: error.step,
|
||||
message: error.message,
|
||||
...(error.desktopEntryPath === undefined
|
||||
? {}
|
||||
: { desktopEntryPath: error.desktopEntryPath }),
|
||||
...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.linuxUrlHandler.register"),
|
||||
);
|
||||
|
||||
return DesktopLinuxUrlHandler.of({ register });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopLinuxUrlHandler, make);
|
||||
@@ -0,0 +1,130 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { appendSwitchMock, getSwitchValueMock, hasSwitchMock, registerSchemesMock } = vi.hoisted(
|
||||
() => ({
|
||||
appendSwitchMock: vi.fn(),
|
||||
getSwitchValueMock: vi.fn(),
|
||||
hasSwitchMock: vi.fn(),
|
||||
registerSchemesMock: vi.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
getSwitchValue: getSwitchValueMock,
|
||||
hasSwitch: hasSwitchMock,
|
||||
},
|
||||
},
|
||||
protocol: {
|
||||
registerSchemesAsPrivileged: registerSchemesMock,
|
||||
},
|
||||
}));
|
||||
|
||||
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
|
||||
|
||||
describe("DesktopPreReadyPlatform", () => {
|
||||
beforeEach(() => {
|
||||
appendSwitchMock.mockReset();
|
||||
getSwitchValueMock.mockReset();
|
||||
hasSwitchMock.mockReset();
|
||||
registerSchemesMock.mockReset();
|
||||
});
|
||||
|
||||
it("reads an explicit Electron command-line switch value", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: (switchName) => switchName === "password-store",
|
||||
getSwitchValue: (switchName) => {
|
||||
assert.equal(switchName, "password-store");
|
||||
return "basic";
|
||||
},
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.equal(value, "basic");
|
||||
});
|
||||
|
||||
it("treats valueless Electron command-line switches as absent", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: () => true,
|
||||
getSwitchValue: () => "",
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.isNull(value);
|
||||
});
|
||||
|
||||
it("returns null for missing Electron command-line switches", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: () => false,
|
||||
getSwitchValue: () => {
|
||||
throw new Error("Unexpected switch value read.");
|
||||
},
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.isNull(value);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"acquires a synchronous pre-ready layer before an asynchronous Clerk-shaped layer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
class ClerkShaped extends Context.Service<ClerkShaped, { readonly ready: true }>()(
|
||||
"@t3tools/desktop/app/DesktopPreReadyPlatform.test/ClerkShaped",
|
||||
) {}
|
||||
|
||||
const events: Array<string> = [];
|
||||
registerSchemesMock.mockImplementation(() => {
|
||||
events.push("pre-ready");
|
||||
});
|
||||
|
||||
const preReadyLayer = DesktopPreReadyPlatform.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "darwin")),
|
||||
);
|
||||
|
||||
const clerkShapedLayer = Layer.effect(
|
||||
ClerkShaped,
|
||||
Effect.promise(() => Promise.resolve()).pipe(
|
||||
Effect.map(() => {
|
||||
events.push("clerk");
|
||||
return { ready: true as const };
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const runtimeLayer = clerkShapedLayer.pipe(
|
||||
Layer.flatMap((clerkContext) => Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(preReadyLayer),
|
||||
);
|
||||
|
||||
const result = yield* Effect.all({
|
||||
clerk: ClerkShaped,
|
||||
preReady: DesktopPreReadyPlatform.DesktopPreReadyElectronOptions,
|
||||
}).pipe(Effect.provide(runtimeLayer));
|
||||
|
||||
assert.deepEqual(result, {
|
||||
clerk: { ready: true },
|
||||
preReady: {
|
||||
linux: null,
|
||||
linuxPasswordStoreCommandLine: null,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(events, ["pre-ready", "clerk"]);
|
||||
assert.equal(registerSchemesMock.mock.calls.length, 1);
|
||||
assert.equal(appendSwitchMock.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads persisted settings synchronously before app services are available.
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
|
||||
export interface DesktopPreReadyCommandLineReader {
|
||||
readonly hasSwitch: (switchName: string) => boolean;
|
||||
readonly getSwitchValue: (switchName: string) => string;
|
||||
}
|
||||
|
||||
export function readCommandLineSwitchValue(
|
||||
commandLine: DesktopPreReadyCommandLineReader,
|
||||
switchName: string,
|
||||
): string | null {
|
||||
if (!commandLine.hasSwitch(switchName)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const value = commandLine.getSwitchValue(switchName).trim();
|
||||
return value.length > 0 ? value : null;
|
||||
}
|
||||
|
||||
export const resolveEarlyLinuxElectronOptionsFromProcess =
|
||||
(): DesktopEarlyElectronStartup.EarlyLinuxElectronOptions =>
|
||||
DesktopEarlyElectronStartup.resolveEarlyLinuxElectronOptions({
|
||||
env: process.env,
|
||||
homeDirectory: NodeOS.homedir(),
|
||||
joinPath: NodePath.posix.join,
|
||||
readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
|
||||
});
|
||||
|
||||
export class DesktopPreReadyElectronOptions extends Context.Service<
|
||||
DesktopPreReadyElectronOptions,
|
||||
{
|
||||
readonly linux: DesktopEarlyElectronStartup.EarlyLinuxElectronOptions | null;
|
||||
readonly linuxPasswordStoreCommandLine: string | null;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
|
||||
const linuxPasswordStoreCommandLine =
|
||||
platform === "linux"
|
||||
? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
|
||||
: null;
|
||||
const linux = platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess() : null;
|
||||
|
||||
if (linux !== null) {
|
||||
Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass);
|
||||
if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
|
||||
Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
|
||||
}
|
||||
}
|
||||
|
||||
return { linux, linuxPasswordStoreCommandLine };
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.electron.configureBeforeReady"));
|
||||
|
||||
// Keep Electron's strict pre-ready setup isolated so later runtime layers cannot
|
||||
// observe app readiness before scheme privileges and command-line switches exist.
|
||||
export const layer = Layer.mergeAll(
|
||||
ElectronProtocol.layerSchemePrivileges,
|
||||
Layer.effect(DesktopPreReadyElectronOptions, make),
|
||||
);
|
||||
@@ -0,0 +1,32 @@
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
export type JoinPath = (first: string, ...segments: string[]) => string;
|
||||
|
||||
function normalizeConfiguredBaseDir(t3Home: Option.Option<string>): Option.Option<string> {
|
||||
if (Option.isNone(t3Home)) {
|
||||
return Option.none();
|
||||
}
|
||||
const trimmed = t3Home.value.trim();
|
||||
return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
|
||||
}
|
||||
|
||||
export function resolveDesktopBaseDir(input: {
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
}): string {
|
||||
return Option.getOrElse(normalizeConfiguredBaseDir(input.t3Home), () =>
|
||||
input.joinPath(input.homeDirectory, ".t3"),
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveDesktopStateDir(input: {
|
||||
readonly baseDir: string;
|
||||
readonly isDevelopment: boolean;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
}): string {
|
||||
const useDevSubdir =
|
||||
input.isDevelopment && Option.isNone(normalizeConfiguredBaseDir(input.t3Home));
|
||||
return input.joinPath(input.baseDir, useDevSubdir ? "dev" : "userdata");
|
||||
}
|
||||
@@ -14,6 +14,7 @@ const {
|
||||
quitMock,
|
||||
relaunchMock,
|
||||
removeListenerMock,
|
||||
removeSwitchMock,
|
||||
setAboutPanelOptionsMock,
|
||||
setAppUserModelIdMock,
|
||||
setAsDefaultProtocolClientMock,
|
||||
@@ -34,6 +35,7 @@ const {
|
||||
quitMock: vi.fn(),
|
||||
relaunchMock: vi.fn(),
|
||||
removeListenerMock: vi.fn(),
|
||||
removeSwitchMock: vi.fn(),
|
||||
setAboutPanelOptionsMock: vi.fn(),
|
||||
setAppUserModelIdMock: vi.fn(),
|
||||
setAsDefaultProtocolClientMock: vi.fn(() => true),
|
||||
@@ -52,6 +54,7 @@ vi.mock("electron", () => ({
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
removeSwitch: removeSwitchMock,
|
||||
},
|
||||
dock: {
|
||||
setIcon: setDockIconMock,
|
||||
@@ -89,6 +92,7 @@ describe("ElectronApp", () => {
|
||||
quitMock.mockClear();
|
||||
relaunchMock.mockClear();
|
||||
removeListenerMock.mockClear();
|
||||
removeSwitchMock.mockClear();
|
||||
setPathMock.mockClear();
|
||||
});
|
||||
|
||||
@@ -178,4 +182,13 @@ describe("ElectronApp", () => {
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("removes command-line switches through the service", () =>
|
||||
Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
yield* electronApp.removeCommandLineSwitch("password-store");
|
||||
|
||||
assert.deepEqual(removeSwitchMock.mock.calls, [["password-store"]]);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
});
|
||||
@@ -69,6 +69,7 @@ export class ElectronApp extends Context.Service<
|
||||
readonly onBeforeQuitForUpdate: (
|
||||
listener: () => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly removeCommandLineSwitch: (switchName: string) => Effect.Effect<void>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
@@ -191,6 +192,10 @@ export const make = ElectronApp.of({
|
||||
Electron.autoUpdater.removeListener("before-quit-for-update", listener);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
removeCommandLineSwitch: (switchName) =>
|
||||
Effect.sync(() => {
|
||||
Electron.app.commandLine.removeSwitch(switchName);
|
||||
}),
|
||||
on: addScopedAppListener,
|
||||
});
|
||||
|
||||
|
||||
@@ -105,6 +105,38 @@ function withContentSecurityPolicy(response: Response, policy: string): Response
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Must run synchronously during process bootstrap, before Electron emits `ready`.
|
||||
*/
|
||||
export function registerDesktopSchemePrivilegesSync(): void {
|
||||
Electron.protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_PRODUCTION_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
scheme: DESKTOP_DEVELOPMENT_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
|
||||
Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
|
||||
);
|
||||
|
||||
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
|
||||
|
||||
async function proxyRequest(
|
||||
request: Request,
|
||||
targetOrigin: URL,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
const electronSafeStorageErrorFields = {
|
||||
cause: Schema.Defect(),
|
||||
@@ -60,24 +62,39 @@ export class ElectronSafeStorage extends Context.Service<
|
||||
readonly decryptString: (
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
|
||||
readonly selectedStorageBackend: Effect.Effect<Option.Option<string>>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
|
||||
|
||||
export const make = ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
try: () => Electron.safeStorage.isEncryptionAvailable(),
|
||||
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
|
||||
}),
|
||||
encryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.encryptString(value),
|
||||
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
|
||||
return ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
try: () => Electron.safeStorage.isEncryptionAvailable(),
|
||||
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
|
||||
}),
|
||||
decryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
|
||||
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
|
||||
encryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.encryptString(value),
|
||||
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
|
||||
}),
|
||||
decryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
|
||||
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
|
||||
}),
|
||||
selectedStorageBackend: Effect.sync(() => {
|
||||
if (platform !== "linux") {
|
||||
return Option.none();
|
||||
}
|
||||
try {
|
||||
return Option.fromNullishOr(Electron.safeStorage.getSelectedStorageBackend());
|
||||
} catch {
|
||||
return Option.none();
|
||||
}
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronSafeStorage, make);
|
||||
export const layer = Layer.effect(ElectronSafeStorage, make);
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
DesktopPreviewSetColorSchemeInputSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
PreviewAnnotationSubmissionResultSchema,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -227,7 +227,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
|
||||
export const pickElement = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
|
||||
result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema),
|
||||
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.pickElement(tabId);
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
resolveLinuxPasswordStoreSwitch,
|
||||
resolveLinuxSecretStorageUnavailableMessage,
|
||||
} from "./linuxSecretStorage.ts";
|
||||
|
||||
const autoSwitch = (env: NodeJS.ProcessEnv) =>
|
||||
resolveLinuxPasswordStoreSwitch({ preference: "auto", env });
|
||||
|
||||
describe("linuxSecretStorage", () => {
|
||||
it("preserves explicit supported password-store preferences", () => {
|
||||
expect(normalizeLinuxPasswordStorePreference("gnome-libsecret")).toBe("gnome-libsecret");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet")).toBe("kwallet");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet5")).toBe("kwallet5");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet6")).toBe("kwallet6");
|
||||
});
|
||||
|
||||
it("falls back to auto for missing or unsupported preferences", () => {
|
||||
expect(normalizeLinuxPasswordStorePreference(undefined)).toBe("auto");
|
||||
expect(normalizeLinuxPasswordStorePreference("basic")).toBe("auto");
|
||||
});
|
||||
|
||||
it("uses explicit preferences instead of the auto heuristic", () => {
|
||||
for (const preference of ["gnome-libsecret", "kwallet", "kwallet5", "kwallet6"] as const) {
|
||||
expect(
|
||||
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "niri" } }),
|
||||
).toBe(preference);
|
||||
// An explicit preference also wins where auto would have stayed out of the way.
|
||||
expect(
|
||||
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "KDE" } }),
|
||||
).toBe(preference);
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves canonical KDE sessions to Electron's own wallet selection", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "5" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE:plasma" })).toBeNull();
|
||||
});
|
||||
|
||||
it("does not force a password-store for desktops Electron already recognizes", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "GNOME" })).toBeNull();
|
||||
for (const desktop of ["Deepin", "Pantheon", "UKUI", "Unity", "X-Cinnamon", "XFCE"]) {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: desktop })).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("recognizes a known desktop later in a colon-separated XDG_CURRENT_DESKTOP list", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:GNOME" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBeNull();
|
||||
});
|
||||
|
||||
it("forces gnome-libsecret for unrecognized Linux desktop sessions", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "Hyprland" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({})).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("forces gnome-libsecret for desktops Electron recognizes but leaves on basic text", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt" })).toBe("gnome-libsecret");
|
||||
// Chromium stops at the first recognized value, so a later name cannot rescue the session.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:GNOME" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:KDE" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:plasma" })).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("does not treat lowercase desktop names as ones Electron recognizes", () => {
|
||||
// Chromium matches these case-sensitively, so lowercase spellings reach basic text.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "gnome" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "xfce" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "kde", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
});
|
||||
|
||||
it("overrides KDE sessions identified only by legacy variables", () => {
|
||||
// Chromium reaches KWallet4 for some of these, such as DESKTOP_SESSION=kde with a version, and
|
||||
// basic text for the rest. Either way these are the variables a previous session leaves behind,
|
||||
// so they are treated as unproven and forced to a real keyring rather than a guessed wallet.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "plasma" })).toBe("gnome-libsecret");
|
||||
for (const session of [
|
||||
"kde",
|
||||
"kde-plasma",
|
||||
"kde4",
|
||||
"plasma",
|
||||
"plasmawayland",
|
||||
"plasmawayland-dev",
|
||||
"plasmax11",
|
||||
"plasmax11-dev",
|
||||
]) {
|
||||
expect(autoSwitch({ DESKTOP_SESSION: session })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_SESSION_DESKTOP: session })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ GDMSESSION: session })).toBe("gnome-libsecret");
|
||||
}
|
||||
expect(autoSwitch({ DESKTOP_SESSION: "kde", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ KDE_SESSION_VERSION: "6" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ KDE_FULL_SESSION: "true", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores stale session hints when XDG_CURRENT_DESKTOP is authoritative", () => {
|
||||
expect(
|
||||
autoSwitch({ XDG_CURRENT_DESKTOP: "niri", DESKTOP_SESSION: "gnome", GDMSESSION: "gnome" }),
|
||||
).toBe("gnome-libsecret");
|
||||
// A previous KDE session left these behind; the compositor running now is not KDE.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", XDG_SESSION_DESKTOP: "GNOME" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:plasma" })).toBe("gnome-libsecret");
|
||||
expect(
|
||||
autoSwitch({
|
||||
XDG_CURRENT_DESKTOP: "Hyprland",
|
||||
XDG_SESSION_DESKTOP: "KDE",
|
||||
KDE_SESSION_VERSION: "6",
|
||||
}),
|
||||
).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("uses GNOME Keyring remediation for libsecret and unknown backends", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "niri" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
|
||||
it("prefers explicit libsecret selection over KDE desktop heuristics", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "gnome-libsecret",
|
||||
selectedBackend: "unknown",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
|
||||
it("prefers explicit KWallet preference over selected gnome-libsecret backend", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "kwallet6",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "niri" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "kwallet",
|
||||
selectedBackend: "gnome-libsecret",
|
||||
env: {},
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
});
|
||||
|
||||
it("uses KWallet remediation wording for KDE-looking sessions", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "kwallet6",
|
||||
env: {},
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { DESKTOP_SESSION: "plasmawayland" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
// A desktop name outranks a bare KDE marker when choosing the wording.
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { GDMSESSION: "gnome", KDE_FULL_SESSION: "true" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
export type LinuxPasswordStorePreference =
|
||||
| "auto"
|
||||
| "gnome-libsecret"
|
||||
| "kwallet"
|
||||
| "kwallet5"
|
||||
| "kwallet6";
|
||||
export type LinuxPasswordStoreSwitch = Exclude<LinuxPasswordStorePreference, "auto">;
|
||||
|
||||
export const DEFAULT_LINUX_PASSWORD_STORE: LinuxPasswordStorePreference = "auto";
|
||||
|
||||
// Chromium matches XDG_CURRENT_DESKTOP values case-sensitively and returns on the first value it
|
||||
// recognizes, so these stay exact literals and are scanned in order. Omitting a real desktop fails
|
||||
// safe: we force gnome-libsecret, which is the backend Chromium selects for all of these anyway.
|
||||
const ELECTRON_LIBSECRET_DESKTOPS = new Set([
|
||||
"Deepin",
|
||||
"GNOME",
|
||||
"Pantheon",
|
||||
"UKUI",
|
||||
"Unity",
|
||||
"X-Cinnamon",
|
||||
"XFCE",
|
||||
]);
|
||||
// Chromium selects a KWallet generation for KDE from KDE_SESSION_VERSION, so it needs no help.
|
||||
const ELECTRON_KDE_DESKTOP = "KDE";
|
||||
// Chromium recognizes LXQt and still selects basic text for it, so it does need a forced backend.
|
||||
const ELECTRON_UNPROTECTED_DESKTOPS = new Set(["LXQt"]);
|
||||
|
||||
const KDE_NAME_PREFIXES = ["kde", "plasma"];
|
||||
const NEGATIVE_FLAG_VALUES = new Set(["0", "false", "no", "off"]);
|
||||
|
||||
export function normalizeLinuxPasswordStorePreference(
|
||||
value: unknown,
|
||||
): LinuxPasswordStorePreference {
|
||||
return value === "gnome-libsecret" ||
|
||||
value === "kwallet" ||
|
||||
value === "kwallet5" ||
|
||||
value === "kwallet6"
|
||||
? value
|
||||
: DEFAULT_LINUX_PASSWORD_STORE;
|
||||
}
|
||||
|
||||
// Auto mode asks one question: will Electron select a real keyring on its own? If so, stay out of
|
||||
// the way, which is how canonical KDE sessions keep the KWallet generation Chromium picks for them.
|
||||
// Otherwise force gnome-libsecret, because the alternative is basic text, which is barely
|
||||
// encryption at all. Forcing never guesses a KWallet generation; a KDE session that needs a
|
||||
// specific one sets linuxPasswordStore explicitly.
|
||||
export function resolveLinuxPasswordStoreSwitch(input: {
|
||||
readonly preference: LinuxPasswordStorePreference;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
}): LinuxPasswordStoreSwitch | null {
|
||||
if (input.preference !== "auto") {
|
||||
return input.preference;
|
||||
}
|
||||
|
||||
return electronSelectsProtectedBackend(input.env) ? null : "gnome-libsecret";
|
||||
}
|
||||
|
||||
// Only an exact XDG_CURRENT_DESKTOP literal proves Electron will protect the session. Chromium can
|
||||
// also reach a real backend through DESKTOP_SESSION and the legacy KDE markers, but those are the
|
||||
// variables a previous session leaves behind, and trusting them is what let stale hints suppress
|
||||
// the forced backend before. Forcing where Chromium would have chosen libsecret is harmless, since
|
||||
// it lands on the same backend.
|
||||
function electronSelectsProtectedBackend(env: NodeJS.ProcessEnv): boolean {
|
||||
for (const name of splitDesktopNameList(env.XDG_CURRENT_DESKTOP)) {
|
||||
const trimmed = name.trim();
|
||||
if (trimmed.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (trimmed === ELECTRON_KDE_DESKTOP || ELECTRON_LIBSECRET_DESKTOPS.has(trimmed)) {
|
||||
return true;
|
||||
}
|
||||
if (ELECTRON_UNPROTECTED_DESKTOPS.has(trimmed)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveLinuxSecretStorageUnavailableMessage(input: {
|
||||
readonly configuredPreference: LinuxPasswordStorePreference;
|
||||
readonly selectedBackend: string | null;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
}): string {
|
||||
if (input.configuredPreference === "gnome-libsecret") {
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
if (
|
||||
input.configuredPreference === "kwallet" ||
|
||||
input.configuredPreference === "kwallet5" ||
|
||||
input.configuredPreference === "kwallet6"
|
||||
) {
|
||||
return getKWalletRemediationMessage();
|
||||
}
|
||||
|
||||
const backend = normalizeSelectedStorageBackend(input.selectedBackend);
|
||||
if (backend === "gnome-libsecret") {
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
if (
|
||||
backend === "kwallet" ||
|
||||
backend === "kwallet5" ||
|
||||
backend === "kwallet6" ||
|
||||
looksLikeKdeSession(input.env)
|
||||
) {
|
||||
return getKWalletRemediationMessage();
|
||||
}
|
||||
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
function getGnomeKeyringRemediationMessage(): string {
|
||||
return "T3 Code could not access GNOME Keyring to save this environment credential. Install and start GNOME Keyring, then restart T3 Code.";
|
||||
}
|
||||
|
||||
function getKWalletRemediationMessage(): string {
|
||||
return "T3 Code could not access KWallet to save this environment credential. Enable the KDE wallet subsystem in System Settings, then restart T3 Code.";
|
||||
}
|
||||
|
||||
// Advisory only: this picks between the GNOME Keyring and KWallet wording in the failure notice. It
|
||||
// never decides which backend to select, so a loose match costs a user slightly wrong instructions
|
||||
// rather than an unprotected credential store.
|
||||
function looksLikeKdeSession(env: NodeJS.ProcessEnv): boolean {
|
||||
const currentDesktopNames = nonEmptyDesktopNames(env.XDG_CURRENT_DESKTOP);
|
||||
if (currentDesktopNames.length > 0) {
|
||||
return currentDesktopNames.some(isKdeDesktopName);
|
||||
}
|
||||
|
||||
const legacyNames = legacyDesktopNames(env);
|
||||
if (legacyNames.length > 0) {
|
||||
return legacyNames.some(isKdeDesktopName);
|
||||
}
|
||||
|
||||
return isSet(env.KDE_SESSION_VERSION) || isAffirmativeFlag(env.KDE_FULL_SESSION);
|
||||
}
|
||||
|
||||
function isKdeDesktopName(name: string): boolean {
|
||||
return KDE_NAME_PREFIXES.some((prefix) => name.startsWith(prefix));
|
||||
}
|
||||
|
||||
function legacyDesktopNames(env: NodeJS.ProcessEnv): string[] {
|
||||
return [env.XDG_SESSION_DESKTOP, env.DESKTOP_SESSION, env.GDMSESSION].flatMap((entry) => {
|
||||
const normalized = normalizeDesktopName(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function nonEmptyDesktopNames(value: string | undefined): string[] {
|
||||
return splitDesktopNameList(value).flatMap((entry) => {
|
||||
const normalized = normalizeDesktopName(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function isSet(value: string | undefined): boolean {
|
||||
return Boolean(value?.trim());
|
||||
}
|
||||
|
||||
function isAffirmativeFlag(value: string | undefined): boolean {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
return normalized ? !NEGATIVE_FLAG_VALUES.has(normalized) : false;
|
||||
}
|
||||
|
||||
function splitDesktopNameList(value: string | undefined): string[] {
|
||||
return value?.split(":") ?? [];
|
||||
}
|
||||
|
||||
function normalizeDesktopName(value: string | undefined): string | null {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
return normalized && normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
function normalizeSelectedStorageBackend(value: string | null): string | null {
|
||||
const normalized = value?.trim().toLowerCase().replace(/_/gu, "-");
|
||||
return normalized && normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
@@ -43,12 +43,14 @@ import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentA
|
||||
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./app/DesktopLinuxUrlHandler.ts";
|
||||
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
|
||||
import * as DesktopObservability from "./app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
|
||||
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
|
||||
import * as DesktopSavedEnvironments from "./settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts";
|
||||
import * as DesktopPreReadyPlatform from "./app/DesktopPreReadyPlatform.ts";
|
||||
import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
@@ -181,6 +183,7 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layer,
|
||||
DesktopApplicationMenu.layer,
|
||||
DesktopLinuxUrlHandler.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
desktopSshLayer,
|
||||
).pipe(
|
||||
@@ -195,16 +198,20 @@ const desktopClerkLayer = DesktopClerk.layer.pipe(
|
||||
Layer.provideMerge(ElectronApp.layer),
|
||||
);
|
||||
|
||||
const desktopApplicationRuntimeLayer = desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(electronLayer),
|
||||
);
|
||||
|
||||
// Acquire strict pre-ready setup before Clerk, whose userData resolution can
|
||||
// yield and let Electron emit ready.
|
||||
const desktopRuntimeLayer = desktopClerkLayer.pipe(
|
||||
Layer.flatMap((clerkContext) =>
|
||||
desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(electronLayer),
|
||||
),
|
||||
desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))),
|
||||
),
|
||||
Layer.provideMerge(DesktopPreReadyPlatform.layer),
|
||||
);
|
||||
|
||||
DesktopApp.program.pipe(Effect.provide(desktopRuntimeLayer), NodeRuntime.runMain);
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
|
||||
|
||||
const keyboardEvent = (
|
||||
overrides: Partial<Parameters<typeof resolveAnnotationSubmission>[0]> = {},
|
||||
) => ({
|
||||
key: "Enter",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
isComposing: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("resolveAnnotationSubmission", () => {
|
||||
it("attaches on Enter and sends on Cmd/Ctrl+Enter", () => {
|
||||
expect(resolveAnnotationSubmission(keyboardEvent())).toBe("attach");
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }))).toBe("send");
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }))).toBe("send");
|
||||
});
|
||||
|
||||
it("leaves Shift+Enter and composition events available for editing", () => {
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }))).toBeNull();
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }))).toBeNull();
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { PreviewAnnotationSubmission } from "@t3tools/contracts";
|
||||
|
||||
interface AnnotationKeyboardEvent {
|
||||
readonly key: string;
|
||||
readonly metaKey: boolean;
|
||||
readonly ctrlKey: boolean;
|
||||
readonly shiftKey: boolean;
|
||||
readonly isComposing: boolean;
|
||||
}
|
||||
|
||||
export function resolveAnnotationSubmission(
|
||||
event: AnnotationKeyboardEvent,
|
||||
): PreviewAnnotationSubmission | null {
|
||||
if (event.key !== "Enter" || event.shiftKey || event.isComposing) return null;
|
||||
return event.metaKey || event.ctrlKey ? "send" : "attach";
|
||||
}
|
||||
@@ -23,6 +23,10 @@ const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
|
||||
"clipboard-sanitized-write",
|
||||
"notifications",
|
||||
"geolocation",
|
||||
// Deliberately NOT local-fonts: preview sessions run untrusted web content,
|
||||
// and silently granting it would hand every page the user's installed-font
|
||||
// fingerprint (and font file bytes via FontData.blob()). The app's own font
|
||||
// picker runs in the main window session, which is unaffected by this list.
|
||||
]);
|
||||
|
||||
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
|
||||
|
||||
@@ -36,6 +36,28 @@ describe("fitPictureInPictureContentSize", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPreviewRefreshShortcut", () => {
|
||||
const input = (overrides: Partial<Electron.Input> = {}) =>
|
||||
({
|
||||
type: "keyDown",
|
||||
key: "r",
|
||||
meta: true,
|
||||
control: false,
|
||||
shift: false,
|
||||
alt: false,
|
||||
...overrides,
|
||||
}) as Electron.Input;
|
||||
|
||||
it("recognizes the platform refresh chord without matching modified variants", () => {
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input())).toBe(true);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ meta: false, control: true }))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ shift: true }))).toBe(false);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ type: "keyUp" }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const {
|
||||
browserWindowConstructor,
|
||||
createFromPath,
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
PreviewAnnotationSubmissionResult,
|
||||
DesktopPreviewRecordingArtifact,
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewScreenshotArtifact,
|
||||
@@ -109,7 +110,7 @@ const DIAGNOSTIC_BUFFER_LIMIT = 200;
|
||||
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
|
||||
const AGENT_CURSOR_MOVE_MS = 160;
|
||||
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
|
||||
const DEFAULT_ANNOTATION_THEME: DesktopPreviewAnnotationTheme = {
|
||||
colorScheme: "light",
|
||||
radius: "0.625rem",
|
||||
@@ -406,6 +407,13 @@ const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
|
||||
{ key: "w", meta: true, shift: false, control: false },
|
||||
]);
|
||||
|
||||
export const isPreviewRefreshShortcut = (input: Electron.Input): boolean =>
|
||||
input.type === "keyDown" &&
|
||||
input.key.toLowerCase() === "r" &&
|
||||
(input.meta || input.control) &&
|
||||
!input.shift &&
|
||||
!input.alt;
|
||||
|
||||
const isPreviewInputSignal = (value: unknown): value is PreviewInputSignal => {
|
||||
if (typeof value !== "object" || value === null || !("kind" in value)) return false;
|
||||
if (value.kind === "pointer") {
|
||||
@@ -1365,6 +1373,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
});
|
||||
const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
|
||||
if (isPreviewRefreshShortcut(input)) {
|
||||
event.preventDefault();
|
||||
runFork(
|
||||
attempt({ operation: "shortcut.refresh", tabId, webContentsId: wc.id }, () =>
|
||||
wc.reload(),
|
||||
).pipe(Effect.ignore),
|
||||
);
|
||||
return;
|
||||
}
|
||||
runFork(forwardShortcut(event, input));
|
||||
};
|
||||
yield* Scope.addFinalizer(
|
||||
@@ -1792,7 +1809,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
yield* cancelPickElement(tabId);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
return yield* Effect.callback<PreviewAnnotationPayload | null, PreviewManagerError>(
|
||||
return yield* Effect.callback<PreviewAnnotationSubmissionResult | null, PreviewManagerError>(
|
||||
(resume) => {
|
||||
const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () {
|
||||
yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => {
|
||||
@@ -1807,14 +1824,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
|
||||
payload: PreviewAnnotationPayload | null,
|
||||
payload: PreviewAnnotationSubmissionResult | null,
|
||||
) {
|
||||
const active = (yield* Ref.get(pickSessionsRef)).get(tabId);
|
||||
if (!active || active.cancel !== cancel) return;
|
||||
yield* cleanup();
|
||||
resume(Effect.succeed(payload));
|
||||
});
|
||||
const settle = (payload: PreviewAnnotationPayload | null) => {
|
||||
const settle = (payload: PreviewAnnotationSubmissionResult | null) => {
|
||||
runFork(settlePick(payload));
|
||||
};
|
||||
const cancelPickSession = Effect.fn("PreviewManager.cancelPickSession")(function* () {
|
||||
@@ -1844,11 +1861,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return;
|
||||
}
|
||||
const cropRect = normalizeCaptureRect(args[1]);
|
||||
const submission = args[2] === "send" ? "send" : "attach";
|
||||
runFork(
|
||||
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: () => Effect.sync(() => settle(payload)),
|
||||
onSuccess: (screenshot) => Effect.sync(() => settle({ ...payload, screenshot })),
|
||||
onFailure: () => Effect.sync(() => settle({ annotation: payload, submission })),
|
||||
onSuccess: (screenshot) =>
|
||||
Effect.sync(() => settle({ annotation: { ...payload, screenshot }, submission })),
|
||||
}),
|
||||
Effect.ensuring(
|
||||
attempt(
|
||||
@@ -3586,7 +3605,7 @@ export class PreviewManager extends Context.Service<
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly pickElement: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
|
||||
) => Effect.Effect<PreviewAnnotationSubmissionResult | null, PreviewManagerError>;
|
||||
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly captureScreenshot: (
|
||||
tabId: string,
|
||||
|
||||
@@ -11,8 +11,10 @@ import type {
|
||||
PreviewAnnotationRegionTarget,
|
||||
PreviewAnnotationStrokeTarget,
|
||||
PreviewAnnotationStyleChange,
|
||||
PreviewAnnotationSubmission,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
|
||||
import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts";
|
||||
import {
|
||||
ANNOTATION_CAPTURED_CHANNEL,
|
||||
@@ -426,7 +428,7 @@ function startAnnotation(): void {
|
||||
"hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
|
||||
composerRow.appendChild(dragHandle);
|
||||
|
||||
const submit = createButton("Attach", "Attach annotation and screenshot");
|
||||
const submit = createButton("Attach", "Attach annotation and screenshot (Enter)");
|
||||
submit.className +=
|
||||
" h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
|
||||
composerRow.appendChild(submit);
|
||||
@@ -1182,7 +1184,7 @@ function startAnnotation(): void {
|
||||
refreshToolButtons();
|
||||
};
|
||||
|
||||
submit.addEventListener("click", () => {
|
||||
const submitAnnotation = (submission: PreviewAnnotationSubmission): void => {
|
||||
if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
|
||||
return;
|
||||
pendingCapture = true;
|
||||
@@ -1223,13 +1225,18 @@ function startAnnotation(): void {
|
||||
...regions.map((region) => region.rect),
|
||||
...strokes.map((stroke) => stroke.bounds),
|
||||
]);
|
||||
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect);
|
||||
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
|
||||
});
|
||||
});
|
||||
comment.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) return;
|
||||
};
|
||||
submit.addEventListener("click", () => submitAnnotation("attach"));
|
||||
root.addEventListener("keydown", (event) => {
|
||||
const submission = event.target === comment ? resolveAnnotationSubmission(event) : null;
|
||||
// Keep this in the bubble phase so editor inputs receive the event before
|
||||
// it is isolated from listeners installed by the inspected page.
|
||||
event.stopImmediatePropagation();
|
||||
if (!submission) return;
|
||||
event.preventDefault();
|
||||
submit.click();
|
||||
submitAnnotation(submission);
|
||||
});
|
||||
|
||||
window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
|
||||
|
||||
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
|
||||
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
|
||||
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
|
||||
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
|
||||
|
||||
@@ -11,6 +11,9 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
|
||||
|
||||
const DesktopSettingsPatch = Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(
|
||||
Schema.Literals(["auto", "gnome-libsecret", "kwallet", "kwallet5", "kwallet6"]),
|
||||
),
|
||||
mainWindowBounds: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
@@ -102,6 +105,7 @@ describe("DesktopSettings", () => {
|
||||
assert.deepEqual(
|
||||
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
|
||||
{
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -121,6 +125,7 @@ describe("DesktopSettings", () => {
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
linuxPasswordStore: "gnome-libsecret",
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
@@ -129,6 +134,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "gnome-libsecret",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
@@ -235,6 +241,7 @@ describe("DesktopSettings", () => {
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
@@ -268,6 +275,44 @@ describe("DesktopSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"normalizes unsupported linux password-store values without dropping other settings",
|
||||
() =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
environment.desktopSettingsPath,
|
||||
`{
|
||||
"linuxPasswordStore": "unsupported-store",
|
||||
"serverExposureMode": "network-accessible",
|
||||
"tailscaleServeEnabled": true,
|
||||
"tailscaleServePort": 8443,
|
||||
"updateChannel": "nightly",
|
||||
"updateChannelConfiguredByUser": true
|
||||
}\n`,
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists sparse desktop settings documents", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
@@ -300,6 +345,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -327,6 +373,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -353,6 +400,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
|
||||
@@ -16,10 +16,16 @@ import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import {
|
||||
DEFAULT_LINUX_PASSWORD_STORE,
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
type LinuxPasswordStorePreference,
|
||||
} from "../linuxSecretStorage.ts";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
|
||||
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly linuxPasswordStore: LinuxPasswordStorePreference;
|
||||
readonly mainWindowBounds: DesktopWindowBounds | null;
|
||||
readonly mainWindowMaximized: boolean;
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
@@ -67,6 +73,7 @@ export const DEFAULT_MAIN_WINDOW_SIZE = {
|
||||
} as const;
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE,
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -87,6 +94,7 @@ const DesktopWindowBoundsDocument = Schema.Struct({
|
||||
});
|
||||
|
||||
const DesktopSettingsDocument = Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
|
||||
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
|
||||
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
|
||||
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
|
||||
@@ -216,6 +224,7 @@ function normalizeDesktopSettingsDocument(
|
||||
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
|
||||
|
||||
return {
|
||||
linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore),
|
||||
mainWindowBounds,
|
||||
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
|
||||
serverExposureMode:
|
||||
@@ -238,6 +247,9 @@ function toDesktopSettingsDocument(
|
||||
): DesktopSettingsDocument {
|
||||
const document: Mutable<DesktopSettingsDocument> = {};
|
||||
|
||||
if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) {
|
||||
document.linuxPasswordStore = settings.linuxPasswordStore;
|
||||
}
|
||||
if (settings.mainWindowBounds !== null) {
|
||||
document.mainWindowBounds = settings.mainWindowBounds;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,15 @@ const clientSettings: ClientSettings = {
|
||||
diffIgnoreWhitespace: true,
|
||||
environmentIdentificationMode: "artwork",
|
||||
favorites: [],
|
||||
fontFamilyCode: "",
|
||||
fontFamilyComposer: "",
|
||||
fontFamilySans: "",
|
||||
fontFamilyTerminal: "",
|
||||
fontSizeCode: 13,
|
||||
fontSizeInterface: 16,
|
||||
fontSizePrompt: 14,
|
||||
fontSizeTerminal: 12,
|
||||
fontSmoothing: true,
|
||||
glassOpacity: 80,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
|
||||
@@ -86,6 +86,7 @@ function makeSafeStorageLayer(input: {
|
||||
}
|
||||
return Effect.succeed(decoded.slice("enc:".length));
|
||||
},
|
||||
selectedStorageBackend: Effect.succeed(Option.none()),
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -90,7 +91,7 @@ function runShellEnvironment(input: {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopShellEnvironment.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(environmentLayer, spawnerLayer)),
|
||||
Layer.provide(Layer.mergeAll(environmentLayer, NodeServices.layer, spawnerLayer)),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -243,6 +244,65 @@ describe("DesktopShellEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
XDG_CURRENT_DESKTOP: "wrong-launcher",
|
||||
XDG_SESSION_DESKTOP: "wrong-launcher",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "linux",
|
||||
handler: () =>
|
||||
envOutput({
|
||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
||||
XDG_CURRENT_DESKTOP: "KDE",
|
||||
XDG_SESSION_DESKTOP: "KDE",
|
||||
XDG_SESSION_TYPE: "wayland",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
|
||||
assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
|
||||
assert.equal(env.XDG_SESSION_TYPE, "wayland");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("overrides stale dbus session addresses from the login shell", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "linux",
|
||||
handler: () =>
|
||||
envOutput({
|
||||
PATH: "/usr/bin",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
|
||||
}),
|
||||
);
|
||||
|
||||
it("resolves dbus runtime dir candidates with existence checks", () => {
|
||||
const busPath = DesktopShellEnvironment.resolveDefaultLinuxDbusSessionBusAddress({
|
||||
env: { XDG_RUNTIME_DIR: "/tmp/stale-runtime" },
|
||||
uid: 1000,
|
||||
exists: (path) => path === "/run/user/1000/bus",
|
||||
});
|
||||
|
||||
assert.equal(busPath, "unix:path=/run/user/1000/bus");
|
||||
});
|
||||
|
||||
it.effect("logs command failures with safe probe context and the exact cause", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/bash",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -68,12 +69,19 @@ export class DesktopShellEnvironment extends Context.Service<
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"DISPLAY",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_CURRENT_DESKTOP",
|
||||
"XDG_DATA_HOME",
|
||||
"XDG_RUNTIME_DIR",
|
||||
"XDG_SESSION_DESKTOP",
|
||||
"XDG_SESSION_TYPE",
|
||||
"WAYLAND_DISPLAY",
|
||||
] as const;
|
||||
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
|
||||
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
|
||||
@@ -92,6 +100,47 @@ const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";"
|
||||
const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
|
||||
trimNonEmpty(env.PATH ?? env.Path ?? env.path);
|
||||
|
||||
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
|
||||
|
||||
const linuxRuntimeDirCandidates = (
|
||||
env: NodeJS.ProcessEnv,
|
||||
uid: number | undefined,
|
||||
): ReadonlyArray<string> => {
|
||||
const candidates: string[] = [];
|
||||
const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
|
||||
if (Option.isSome(fromEnv)) {
|
||||
candidates.push(normalizeRuntimeDir(fromEnv.value));
|
||||
}
|
||||
if (uid !== undefined) {
|
||||
candidates.push(`/run/user/${uid}`);
|
||||
}
|
||||
return candidates.filter((candidate) => candidate.length > 0);
|
||||
};
|
||||
|
||||
function resolveDefaultLinuxDbusSessionBusPath(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly uid: number | undefined;
|
||||
readonly exists?: (path: string) => boolean;
|
||||
}): string | null {
|
||||
for (const runtimeDir of linuxRuntimeDirCandidates(input.env, input.uid)) {
|
||||
const busPath = `${runtimeDir}/bus`;
|
||||
if (input.exists === undefined || input.exists(busPath)) {
|
||||
return busPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveDefaultLinuxDbusSessionBusAddress(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly exists: (path: string) => boolean;
|
||||
readonly uid: number | undefined;
|
||||
}): string | null {
|
||||
const busPath = resolveDefaultLinuxDbusSessionBusPath(input);
|
||||
return busPath !== null && input.exists(busPath) ? `unix:path=${busPath}` : null;
|
||||
}
|
||||
|
||||
const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
|
||||
const normalized = entry.trim().replace(/^"+|"+$/g, "");
|
||||
return platform === "win32" ? normalized.toLowerCase() : normalized;
|
||||
@@ -356,7 +405,12 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
|
||||
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
|
||||
function* (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const shellEnvironment: EnvironmentPatch = {};
|
||||
|
||||
for (const shell of listLoginShellCandidates(config)) {
|
||||
@@ -383,23 +437,54 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
|
||||
config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
|
||||
const shellPreferredEnvNames = [
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"XDG_CURRENT_DESKTOP",
|
||||
"XDG_SESSION_DESKTOP",
|
||||
"XDG_SESSION_TYPE",
|
||||
] as const;
|
||||
for (const name of shellPreferredEnvNames) {
|
||||
if (shellEnvironment[name]) {
|
||||
config.env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
|
||||
for (const name of [
|
||||
"DISPLAY",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
"XDG_RUNTIME_DIR",
|
||||
"WAYLAND_DISPLAY",
|
||||
] as const) {
|
||||
if (!config.env[name] && shellEnvironment[name]) {
|
||||
config.env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
config.platform === "linux" &&
|
||||
Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
|
||||
) {
|
||||
for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
|
||||
const dbusSessionBusPath = `${runtimeDir}/bus`;
|
||||
const busExists = yield* fileSystem
|
||||
.exists(dbusSessionBusPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (busExists) {
|
||||
config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const installShellEnvironment = (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
|
||||
if (config.platform === "win32") {
|
||||
return installWindowsEnvironment(config);
|
||||
}
|
||||
@@ -411,6 +496,7 @@ const installShellEnvironment = (
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
|
||||
installShellEnvironment({
|
||||
@@ -418,6 +504,7 @@ export const make = Effect.gen(function* () {
|
||||
platform: environment.platform,
|
||||
userShell: Option.none(),
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
|
||||
);
|
||||
|
||||
@@ -43,6 +43,7 @@ function makeElectronAppLayer(
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
@@ -46,6 +46,7 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
|
||||
@@ -438,6 +438,51 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const beforeInput = fakeWindow.webContentsListeners.get("before-input-event");
|
||||
if (!beforeInput) {
|
||||
return yield* Effect.die("before-input-event listener was not registered");
|
||||
}
|
||||
|
||||
let prevented = false;
|
||||
const event = { preventDefault: () => (prevented = true) };
|
||||
const input = {
|
||||
type: "keyDown",
|
||||
isAutoRepeat: true,
|
||||
key: "W",
|
||||
meta: true,
|
||||
control: false,
|
||||
alt: false,
|
||||
shift: false,
|
||||
};
|
||||
beforeInput(event, input);
|
||||
assert.isTrue(prevented);
|
||||
|
||||
prevented = false;
|
||||
beforeInput(event, { ...input, isAutoRepeat: false });
|
||||
assert.isFalse(prevented);
|
||||
|
||||
prevented = false;
|
||||
beforeInput(event, { ...input, meta: false });
|
||||
assert.isFalse(prevented);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the persisted main window bounds when opening the window", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
@@ -25,6 +26,12 @@ const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
|
||||
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
|
||||
// Renderer crash (usually V8 OOM on long sessions) recovery: reload after a
|
||||
// short delay, at most MAX_ATTEMPTS times per rolling WINDOW so a renderer
|
||||
// that dies on boot cannot reload-loop forever.
|
||||
const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500;
|
||||
const RENDERER_RECOVERY_MAX_ATTEMPTS = 3;
|
||||
const RENDERER_RECOVERY_WINDOW_MS = 60_000;
|
||||
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
|
||||
-2, // ERR_FAILED
|
||||
-7, // ERR_TIMED_OUT
|
||||
@@ -514,6 +521,18 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
// Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
|
||||
// close-terminal shortcut can outlive the terminal that handled its first
|
||||
// press, so reject repeats before they reach the native window accelerator.
|
||||
// Deliberate presses still flow through the renderer or native menu.
|
||||
window.webContents.on("before-input-event", (event, input) => {
|
||||
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
|
||||
const modifier = environment.platform === "darwin" ? input.meta : input.control;
|
||||
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
window.on("page-title-updated", (event) => {
|
||||
event.preventDefault();
|
||||
window.setTitle(environment.displayName);
|
||||
@@ -537,6 +556,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
let rendererRecoveryTimestamps: number[] = [];
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber === undefined) {
|
||||
return;
|
||||
@@ -618,10 +638,39 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
window.webContents.on("render-process-gone", (_event, details) => {
|
||||
void runPromise(
|
||||
logWindowWarning("main window render process gone", {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
const recoverable =
|
||||
details.reason === "crashed" ||
|
||||
details.reason === "oom" ||
|
||||
details.reason === "abnormal-exit";
|
||||
// Long sessions can OOM the renderer (V8 heap exhaustion from
|
||||
// accumulated thread state). Without a reload the user is left staring
|
||||
// at a dead white window while agents keep running invisibly, so
|
||||
// recover by reloading — the renderer rehydrates from the backend,
|
||||
// which is unaffected. Recovery attempts are bounded so a renderer
|
||||
// that dies immediately on boot cannot reload-loop forever.
|
||||
runFork(
|
||||
Effect.gen(function* () {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
|
||||
(timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
|
||||
);
|
||||
const shouldRecover =
|
||||
recoverable &&
|
||||
!window.isDestroyed() &&
|
||||
rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
|
||||
yield* logWindowWarning("main window render process gone", {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
recovering: shouldRecover,
|
||||
});
|
||||
if (!shouldRecover) {
|
||||
return;
|
||||
}
|
||||
rendererRecoveryTimestamps.push(now);
|
||||
yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
|
||||
if (!window.isDestroyed()) {
|
||||
loadApplication();
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -50,6 +50,8 @@ import {
|
||||
IconMinus,
|
||||
IconNetwork,
|
||||
IconPalette,
|
||||
IconPin,
|
||||
IconPinnedOff,
|
||||
IconPlayerPlay,
|
||||
IconPlayerStopFilled,
|
||||
IconPlus,
|
||||
@@ -121,6 +123,8 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
magnifyingglass: IconSearch,
|
||||
paintbrush: IconPalette,
|
||||
"person.crop.circle": IconUserCircle,
|
||||
pin: IconPin,
|
||||
"pin.slash": IconPinnedOff,
|
||||
play: IconPlayerPlay,
|
||||
plus: IconPlus,
|
||||
"qrcode.viewfinder": IconQrcode,
|
||||
|
||||
@@ -9,6 +9,7 @@ type ProviderIconProps = {
|
||||
export function ProviderIcon(props: ProviderIconProps) {
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const size = props.size ?? 16;
|
||||
const mono = isDarkMode ? "#e5e5e5" : "#171717";
|
||||
|
||||
if (props.provider === "claudeAgent") {
|
||||
return (
|
||||
@@ -21,10 +22,47 @@ export function ProviderIcon(props: ProviderIconProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "grok") {
|
||||
const fill = isDarkMode ? "#F5F5F5" : "#0F0F0F";
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<Path
|
||||
fill={fill}
|
||||
d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861"
|
||||
/>
|
||||
<Path
|
||||
fill={fill}
|
||||
d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257"
|
||||
/>
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "cursor") {
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 466.73 532.09" fill="none">
|
||||
<Path
|
||||
fill={isDarkMode ? "#EDECEC" : "#26251E"}
|
||||
d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"
|
||||
/>
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "opencode") {
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 32 40" fill="none">
|
||||
<Path d="M24 32H8V16H24V32Z" fill={isDarkMode ? "#4B4646" : "#CFCECD"} />
|
||||
<Path d="M24 8H8V32H24V8ZM32 40H0V0H32V40Z" fill={isDarkMode ? "#F1ECEC" : "#211E1E"} />
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
// codex (and unknown drivers)
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 256 260" fill="none">
|
||||
<Path
|
||||
fill={isDarkMode ? "#e5e5e5" : "#171717"}
|
||||
fill={mono}
|
||||
d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"
|
||||
/>
|
||||
</Svg>
|
||||
|
||||
@@ -42,6 +42,8 @@ export function HomeRouteScreen() {
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -155,6 +157,8 @@ export function HomeRouteScreen() {
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
|
||||
@@ -111,6 +111,8 @@ interface HomeScreenProps {
|
||||
) => Promise<boolean>;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -516,6 +518,18 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onUnsnoozeThread],
|
||||
);
|
||||
const handlePinThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onPinThread(thread);
|
||||
},
|
||||
[props.onPinThread],
|
||||
);
|
||||
const handleUnpinThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onUnpinThread(thread);
|
||||
},
|
||||
[props.onUnpinThread],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
@@ -575,6 +589,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinningEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinning === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return {
|
||||
@@ -718,6 +741,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
snoozed={item.item.snoozed}
|
||||
pinned={item.item.pinned}
|
||||
snoozePresetMinute={nowMinute}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
project={
|
||||
@@ -753,9 +777,12 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
|
||||
onSnoozeThread={handleSnoozeThread}
|
||||
onUnsnoozeThread={handleUnsnoozeThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onPinThread={handlePinThread}
|
||||
onUnpinThread={handleUnpinThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
@@ -768,12 +795,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
handlePinThread,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnpinThread,
|
||||
handleUnsnoozeThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
pinningEnvironmentIds,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
|
||||
@@ -29,6 +29,13 @@ function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["enviro
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsPinning(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadPinning === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -202,10 +209,14 @@ export function useThreadListActions(): {
|
||||
readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
|
||||
readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly pinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
|
||||
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
|
||||
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
|
||||
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
|
||||
const snoozeInFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const archiveThread = useCallback(
|
||||
@@ -310,6 +321,62 @@ export function useThreadListActions(): {
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
const pinThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
if (!environmentSupportsPinning(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not pin thread",
|
||||
"This environment's server does not support pinning yet. Update the server to use Pin.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
selectionHaptic();
|
||||
const result = await pinMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not pin thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be pinned.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[pinMutation],
|
||||
);
|
||||
const unpinThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
if (!environmentSupportsPinning(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not unpin thread",
|
||||
"This environment's server does not support pinning yet. Update the server to use Pin.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
selectionHaptic();
|
||||
const result = await unpinMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not unpin thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be unpinned.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[unpinMutation],
|
||||
);
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
@@ -320,6 +387,8 @@ export function useThreadListActions(): {
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ import {
|
||||
type ComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
|
||||
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
@@ -543,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(
|
||||
|
||||
@@ -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],
|
||||
);
|
||||
|
||||
|
||||
@@ -205,6 +205,8 @@ function ThreadNavigationSidebarPane(
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -481,6 +483,15 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinningEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinning === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return {
|
||||
@@ -792,6 +803,7 @@ function ThreadNavigationSidebarPane(
|
||||
previous.item.thread === item.item.thread &&
|
||||
previous.item.variant === item.item.variant &&
|
||||
previous.item.snoozed === item.item.snoozed &&
|
||||
previous.item.pinned === item.item.pinned &&
|
||||
previous.snoozeWakeLabelText === item.snoozeWakeLabelText
|
||||
);
|
||||
}
|
||||
@@ -879,6 +891,7 @@ function ThreadNavigationSidebarPane(
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
snoozed={item.item.snoozed}
|
||||
pinned={item.item.pinned}
|
||||
snoozePresetMinute={nowMinute}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
@@ -915,9 +928,12 @@ function ThreadNavigationSidebarPane(
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={settleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
@@ -1045,6 +1061,8 @@ function ThreadNavigationSidebarPane(
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
openPendingTask,
|
||||
pinThread,
|
||||
pinningEnvironmentIds,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
@@ -1064,6 +1082,7 @@ function ThreadNavigationSidebarPane(
|
||||
nowMinute,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
unpinThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
updateGroupDisplay,
|
||||
|
||||
@@ -305,6 +305,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly variant: "card" | "slim";
|
||||
/** Snoozed-shelf row: shows its wake time and offers Wake. */
|
||||
readonly snoozed?: boolean;
|
||||
/** Pinned-block row: shows the pin glyph and offers Unpin. */
|
||||
readonly pinned?: boolean;
|
||||
/** Preformatted against the parent minute tick so this memoized row's
|
||||
countdown keeps moving. */
|
||||
readonly snoozeWakeLabelText?: string;
|
||||
@@ -337,11 +339,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onPinThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnpinThread: (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;
|
||||
/** False on servers that predate thread.pin/unpin. */
|
||||
readonly pinningSupported: 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
|
||||
@@ -368,9 +374,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onUnsnoozeThread,
|
||||
onUnsettleThread,
|
||||
onArchiveThread,
|
||||
onPinThread,
|
||||
onUnpinThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
const snoozedRow = props.snoozed === true;
|
||||
const pinnedRow = props.pinned === true;
|
||||
|
||||
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
|
||||
const prState = pr?.state ?? null;
|
||||
@@ -383,6 +392,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const drawerColor = useThemeColor("--color-drawer");
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
|
||||
const pinTintColor = useThemeColor("--color-foreground-muted");
|
||||
const sidebarPane = props.pane === "sidebar";
|
||||
const selected = props.selected === true;
|
||||
|
||||
@@ -398,6 +408,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
);
|
||||
const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
|
||||
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
|
||||
const handlePin = useCallback(() => onPinThread(thread), [onPinThread, thread]);
|
||||
const handleUnpin = useCallback(() => onUnpinThread(thread), [onUnpinThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Every settled
|
||||
@@ -434,6 +446,20 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
})),
|
||||
[snoozePresets],
|
||||
);
|
||||
// Pinned cards keep the full lifecycle menu; only the pin item flips to
|
||||
// Unpin. (Settling a pinned thread clears the pin server-side; snoozing
|
||||
// hides the card until wake with the pin intact.)
|
||||
const pinMenuItem = useMemo<MenuAction[]>(
|
||||
() =>
|
||||
props.pinningSupported
|
||||
? [
|
||||
pinnedRow
|
||||
? { id: "unpin", title: "Unpin", image: "pin.slash" }
|
||||
: { id: "pin", title: "Pin", image: "pin" },
|
||||
]
|
||||
: [],
|
||||
[pinnedRow, props.pinningSupported],
|
||||
);
|
||||
const snoozableCardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
@@ -443,15 +469,22 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
image: "clock",
|
||||
subactions: snoozePresetActions,
|
||||
},
|
||||
...pinMenuItem,
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
],
|
||||
[snoozePresetActions],
|
||||
[pinMenuItem, snoozePresetActions],
|
||||
);
|
||||
const cardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
|
||||
[pinMenuItem],
|
||||
);
|
||||
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 === "pin") handlePin();
|
||||
if (nativeEvent.event === "unpin") handleUnpin();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
|
||||
@@ -468,8 +501,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handlePin,
|
||||
handleSettle,
|
||||
handleSnooze,
|
||||
handleUnpin,
|
||||
handleUnsettle,
|
||||
handleUnsnooze,
|
||||
snoozePresets,
|
||||
@@ -560,6 +595,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
>
|
||||
{props.projectTitle ?? props.project?.title ?? ""}
|
||||
</Text>
|
||||
{pinnedRow ? (
|
||||
<SymbolView name="pin" size={11} tintColor={pinTintColor} type="monochrome" />
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs tabular-nums",
|
||||
@@ -805,7 +843,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
? SLIM_MENU_ACTIONS
|
||||
: swipeActions.secondary === "snooze"
|
||||
? snoozableCardMenuActions
|
||||
: CARD_MENU_ACTIONS
|
||||
: cardMenuActions
|
||||
}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
|
||||
@@ -288,6 +288,57 @@ describe("buildThreadListV2Items", () => {
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("renders pinned threads first and exempts them from auto-settle — parity with web", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("pinned-settled"),
|
||||
title: "Pinned while settled",
|
||||
pinnedAt: "2026-06-01T12:00:00.000Z",
|
||||
// Stale settled state (the decider clears it on pin): the pin wins.
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["pinned-settled", "active"]);
|
||||
expect(layout.items.map((item) => item.pinned)).toEqual([true, false]);
|
||||
expect(layout.settledCount).toBe(0);
|
||||
});
|
||||
|
||||
it("snooze hides a pinned thread and wake restores it to the pinned block", () => {
|
||||
const snoozedInput = {
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("pinned-snoozed"),
|
||||
title: "Pinned and snoozed",
|
||||
pinnedAt: "2026-06-01T12:00:00.000Z",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T11:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
};
|
||||
|
||||
// Before the wake time: the snooze wins; the pin holds underneath.
|
||||
const whileSnoozed = buildThreadListV2Items({ ...snoozedInput, now: NOW });
|
||||
expect(whileSnoozed.items.map((item) => item.thread.id)).toEqual(["active"]);
|
||||
expect(whileSnoozed.snoozedCount).toBe(1);
|
||||
|
||||
// After the wake time: the thread returns pinned, back on top.
|
||||
const afterWake = buildThreadListV2Items({ ...snoozedInput, now: "2026-06-03T10:00:00.000Z" });
|
||||
expect(afterWake.items.map((item) => item.thread.id)).toEqual(["pinned-snoozed", "active"]);
|
||||
expect(afterWake.items[0]?.pinned).toBe(true);
|
||||
expect(afterWake.snoozedCount).toBe(0);
|
||||
});
|
||||
|
||||
it("classifies snooze with the second-precise clock and reports the next wake", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
|
||||
@@ -180,6 +180,8 @@ export interface ThreadListV2Item {
|
||||
readonly variant: "card" | "slim";
|
||||
/** Snoozed-shelf row: shows the wake countdown and offers Wake. */
|
||||
readonly snoozed: boolean;
|
||||
/** Pinned-block row: renders the pin glyph and offers Unpin. */
|
||||
readonly pinned: boolean;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
@@ -351,6 +353,7 @@ export function buildThreadListV2Items(input: {
|
||||
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
|
||||
: null;
|
||||
|
||||
const pinned: EnvironmentThreadShell[] = [];
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
const snoozed: EnvironmentThreadShell[] = [];
|
||||
@@ -378,9 +381,10 @@ export function buildThreadListV2Items(input: {
|
||||
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const changeRequestState =
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
// Visibility parity with web: a snoozed thread leaves the list until it
|
||||
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
|
||||
// work). Snooze outranks settled classification, same as web.
|
||||
// Visibility parity with web: snooze outranks everything, including a
|
||||
// pin — a snoozed thread leaves the list until it wakes (or raises its
|
||||
// hand). The pin survives underneath, so a woken thread reappears at
|
||||
// its original spot in the creation-ordered pinned block.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozed.push(thread);
|
||||
if (
|
||||
@@ -392,6 +396,12 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A pin otherwise overrides the lifecycle: pinned threads render above
|
||||
// the inbox and never auto-settle out of sight.
|
||||
if (thread.pinnedAt != null) {
|
||||
pinned.push(thread);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
@@ -434,11 +444,21 @@ export function buildThreadListV2Items(input: {
|
||||
);
|
||||
|
||||
const items: ThreadListV2Item[] = [];
|
||||
for (const thread of sortThreadsForListV2(pinned)) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "card",
|
||||
snoozed: false,
|
||||
pinned: true,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
for (const thread of orderedActive) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "card",
|
||||
snoozed: false,
|
||||
pinned: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
@@ -448,6 +468,7 @@ export function buildThreadListV2Items(input: {
|
||||
thread,
|
||||
variant: "slim",
|
||||
snoozed: true,
|
||||
pinned: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
@@ -457,6 +478,7 @@ export function buildThreadListV2Items(input: {
|
||||
thread,
|
||||
variant: "slim",
|
||||
snoozed: false,
|
||||
pinned: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,9 +2,92 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
|
||||
|
||||
import { buildModelOptions, resolveSelectableModelSelection } 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: [
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
@@ -105,6 +107,7 @@ export function buildModelOptions(
|
||||
providerLabel,
|
||||
providerDriver: provider.driver,
|
||||
isDefault: model.isDefault === true,
|
||||
isLegacy: model.isLegacy === true,
|
||||
capabilities: model.capabilities,
|
||||
selection: normalizeSelectionOptions(
|
||||
{
|
||||
@@ -135,6 +138,7 @@ export function buildModelOptions(
|
||||
providerLabel,
|
||||
providerDriver: fallbackModelSelection.instanceId,
|
||||
isDefault: false,
|
||||
isLegacy: false,
|
||||
capabilities: null,
|
||||
selection: fallbackModelSelection,
|
||||
});
|
||||
@@ -164,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)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -75,6 +75,7 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.vcsSwitchRef]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.vcsInit]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.reviewGetDiffPreview]: AuthReviewWriteScope,
|
||||
[WS_METHODS.reviewGetDiffFileContents]: AuthReviewWriteScope,
|
||||
[WS_METHODS.terminalOpen]: AuthTerminalOperateScope,
|
||||
[WS_METHODS.terminalAttach]: AuthTerminalOperateScope,
|
||||
[WS_METHODS.terminalWrite]: AuthTerminalOperateScope,
|
||||
|
||||
@@ -15,6 +15,7 @@ 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);
|
||||
|
||||
@@ -53,6 +54,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
|
||||
authCommand,
|
||||
projectCommand,
|
||||
serviceCommand,
|
||||
servicePreflightCommand,
|
||||
cloudEnabled ? connectCommand : connectUnavailableCommand,
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import { assert, expect, it } from "@effect/vitest";
|
||||
@@ -56,8 +58,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
const encoded = yield* encodeDesktopBootstrap(payload);
|
||||
yield* fs.writeFileString(filePath, `${encoded}\n`);
|
||||
const { fd } = yield* fs.open(filePath, { flag: "r" });
|
||||
return fd;
|
||||
return yield* Effect.acquireRelease(
|
||||
Effect.sync(() => NodeFS.openSync(filePath, "r")),
|
||||
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("falls back to effect/config values when flags are omitted", () =>
|
||||
|
||||
@@ -466,7 +466,7 @@ export const DurationFromString = Schema.String.pipe(
|
||||
return Effect.succeed(duration);
|
||||
}
|
||||
return Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(value), {
|
||||
new SchemaIssue.InvalidValue({
|
||||
message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -10,6 +10,7 @@ import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
import {
|
||||
acquireRelayClientForLink,
|
||||
formatHeadlessAuthorizationPrompt,
|
||||
@@ -63,6 +64,15 @@ it.effect("treats cancelling optional background setup as a successful skip", ()
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a successful connection when a remote service update is pending", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* recoverServiceOnboardingOffer(
|
||||
Effect.fail(new BootService.BootServiceUpdatePendingError()),
|
||||
);
|
||||
assert.isFalse(result);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not install the relay client when the user declines the managed download", () =>
|
||||
Effect.gen(function* () {
|
||||
let installCalls = 0;
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { TailscaleCommandExitError } from "@t3tools/tailscale";
|
||||
import { assert, describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
DevServerNotProxiableError,
|
||||
resolveDirectPairingBaseUrl,
|
||||
resolveTailscaleLocalTarget,
|
||||
tailscaleServeFailedError,
|
||||
} from "./pair.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
@@ -50,6 +52,45 @@ describe("pair base URL selection", () => {
|
||||
});
|
||||
|
||||
describe("pair tailscale local target", () => {
|
||||
it("surfaces the operator fix from safe structural error fields", () => {
|
||||
const cause = new TailscaleCommandExitError({
|
||||
executable: "tailscale",
|
||||
subcommand: "serve",
|
||||
argumentCount: 4,
|
||||
exitCode: 1,
|
||||
stderrLength: 24,
|
||||
stderrDiagnostic: "permission-denied",
|
||||
});
|
||||
|
||||
const failure = tailscaleServeFailedError(443, cause);
|
||||
|
||||
expect(failure).toMatchObject({
|
||||
exitCode: 1,
|
||||
stderrDiagnostic: "permission-denied",
|
||||
cause,
|
||||
});
|
||||
expect(failure.message).toBe(
|
||||
"tailscale serve failed with code 1 for HTTPS port 443: access denied. Run `sudo tailscale set --operator=$USER`, then retry.",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps Windows permission guidance free of Unix-only commands", () => {
|
||||
const cause = new TailscaleCommandExitError({
|
||||
executable: "tailscale.exe",
|
||||
subcommand: "serve",
|
||||
argumentCount: 4,
|
||||
exitCode: 1,
|
||||
stderrLength: 24,
|
||||
stderrDiagnostic: "permission-denied",
|
||||
});
|
||||
|
||||
const failure = tailscaleServeFailedError(443, cause);
|
||||
|
||||
expect(failure).toMatchObject({ executable: "tailscale.exe", cause });
|
||||
expect(failure.message).toContain("Grant this Windows user permission");
|
||||
expect(failure.message).not.toContain("sudo");
|
||||
});
|
||||
|
||||
it("proxies the dev web port for dev servers", () => {
|
||||
expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
|
||||
{ localPort: 5_733 },
|
||||
@@ -205,7 +246,8 @@ describe("t3 pair", () => {
|
||||
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, "No usable T3 Code server runtime state found.");
|
||||
assert.include(rendered, "--base-dir");
|
||||
assert.include(rendered, "npx t3 serve");
|
||||
assert.include(rendered, "npx t3 connect");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
@@ -236,7 +278,7 @@ describe("t3 pair", () => {
|
||||
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, "No usable T3 Code server runtime state found.");
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
@@ -262,7 +304,7 @@ describe("t3 pair", () => {
|
||||
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, "No usable T3 Code server runtime state found.");
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
ensureTailscaleServe,
|
||||
readTailscaleStatus,
|
||||
TailscaleCommandExitError,
|
||||
TailscaleStderrDiagnostic,
|
||||
} from "@t3tools/tailscale";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Console from "effect/Console";
|
||||
@@ -76,9 +78,10 @@ export class NoRunningServerError extends Schema.TaggedErrorClass<NoRunningServe
|
||||
) {
|
||||
override get message(): string {
|
||||
return [
|
||||
"No running T3 Code server found.",
|
||||
"No usable T3 Code server runtime state found.",
|
||||
...this.checkedStatePaths.map((statePath) => ` checked ${statePath}`),
|
||||
"Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
|
||||
"If a server is running, pass its T3 home with `--base-dir`; its runtime state may be missing or stale.",
|
||||
"Otherwise start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
|
||||
].join("\n");
|
||||
}
|
||||
}
|
||||
@@ -114,13 +117,44 @@ export class ServesOtherEnvironmentError extends Schema.TaggedErrorClass<ServesO
|
||||
|
||||
export class TailscaleServeFailedError extends Schema.TaggedErrorClass<TailscaleServeFailedError>()(
|
||||
"TailscaleServeFailedError",
|
||||
{ servePort: Schema.Number, cause: Schema.Defect() },
|
||||
{
|
||||
servePort: Schema.Number,
|
||||
executable: Schema.optional(Schema.Literals(["tailscale", "tailscale.exe"])),
|
||||
exitCode: Schema.optional(Schema.Number),
|
||||
stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
if (this.stderrDiagnostic === "permission-denied") {
|
||||
const exitDetail = this.exitCode === undefined ? "" : ` with code ${String(this.exitCode)}`;
|
||||
if (this.executable === "tailscale.exe") {
|
||||
return `tailscale serve failed${exitDetail} for HTTPS port ${String(this.servePort)}: access denied. Grant this Windows user permission to manage Tailscale, then retry.`;
|
||||
}
|
||||
return `tailscale serve failed${exitDetail} for HTTPS port ${String(this.servePort)}: access denied. Run \`sudo tailscale set --operator=$USER\`, then retry.`;
|
||||
}
|
||||
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.`;
|
||||
}
|
||||
}
|
||||
|
||||
const isTailscaleCommandExitError = Schema.is(TailscaleCommandExitError);
|
||||
|
||||
export function tailscaleServeFailedError(
|
||||
servePort: number,
|
||||
cause: unknown,
|
||||
): TailscaleServeFailedError {
|
||||
const exitDetails = isTailscaleCommandExitError(cause)
|
||||
? {
|
||||
executable: cause.executable,
|
||||
exitCode: cause.exitCode,
|
||||
...(cause.stderrDiagnostic === undefined
|
||||
? {}
|
||||
: { stderrDiagnostic: cause.stderrDiagnostic }),
|
||||
}
|
||||
: {};
|
||||
return new TailscaleServeFailedError({ servePort, cause, ...exitDetails });
|
||||
}
|
||||
|
||||
export class ServePortOccupiedError extends Schema.TaggedErrorClass<ServePortOccupiedError>()(
|
||||
"ServePortOccupiedError",
|
||||
{ servePort: Schema.Number },
|
||||
@@ -409,11 +443,7 @@ const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase"
|
||||
localPort: localTarget.localPort,
|
||||
servePort: input.servePort,
|
||||
...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.mapError((cause) => tailscaleServeFailedError(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\`.`,
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { formatServiceStatus } from "./service.ts";
|
||||
import { formatServiceStatus, serviceDowngradeRefusal } from "./service.ts";
|
||||
|
||||
const status = {
|
||||
supported: true,
|
||||
@@ -8,6 +8,7 @@ const status = {
|
||||
current: true,
|
||||
unitPath: "/home/me/.config/systemd/user/t3code.service",
|
||||
logPath: "/home/me/.t3/userdata/logs/boot-service.log",
|
||||
installedVersion: "0.0.29",
|
||||
} as const;
|
||||
|
||||
it("reports the installed service version and host paths", () => {
|
||||
@@ -35,3 +36,42 @@ it("explains service availability without systemd", () => {
|
||||
"Supported on: Linux with systemd",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports a newer installed service without recommending latest", () => {
|
||||
const output = formatServiceStatus(
|
||||
{ ...status, current: false, installedVersion: "0.0.32-nightly.1" },
|
||||
"0.0.31",
|
||||
);
|
||||
|
||||
assert.include(output, "[email protected] (newer than this [email protected] CLI)");
|
||||
assert.include(output, "npx [email protected] service update");
|
||||
assert.notInclude(output, "npx t3@latest service update");
|
||||
});
|
||||
|
||||
it("refuses service downgrades unless explicitly allowed", () => {
|
||||
const refusal = serviceDowngradeRefusal({
|
||||
installedVersion: "0.0.32-nightly.1",
|
||||
targetVersion: "0.0.31",
|
||||
allowDowngrade: false,
|
||||
});
|
||||
assert.instanceOf(refusal, Error);
|
||||
assert.deepInclude(refusal, {
|
||||
_tag: "ServiceDowngradeRefusedError",
|
||||
installedVersion: "0.0.32-nightly.1",
|
||||
targetVersion: "0.0.31",
|
||||
});
|
||||
assert.isNull(
|
||||
serviceDowngradeRefusal({
|
||||
installedVersion: "0.0.32-nightly.1",
|
||||
targetVersion: "0.0.31",
|
||||
allowDowngrade: true,
|
||||
}),
|
||||
);
|
||||
assert.isNull(
|
||||
serviceDowngradeRefusal({
|
||||
installedVersion: undefined,
|
||||
targetVersion: "0.0.31",
|
||||
allowDowngrade: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,11 +1,13 @@
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { Command, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
|
||||
import type * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
@@ -28,13 +30,50 @@ export type ServiceReconcileResult =
|
||||
readonly plan: BootService.BootServicePlan;
|
||||
};
|
||||
|
||||
export class ServiceDowngradeRefusedError extends Schema.TaggedErrorClass<ServiceDowngradeRefusedError>()(
|
||||
"ServiceDowngradeRefusedError",
|
||||
{
|
||||
installedVersion: Schema.String,
|
||||
targetVersion: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Re-run with --allow-downgrade to continue.`;
|
||||
}
|
||||
}
|
||||
|
||||
export function serviceDowngradeRefusal(input: {
|
||||
readonly installedVersion: string | undefined;
|
||||
readonly targetVersion: string;
|
||||
readonly allowDowngrade: boolean;
|
||||
}): ServiceDowngradeRefusedError | null {
|
||||
return input.installedVersion !== undefined &&
|
||||
!input.allowDowngrade &&
|
||||
compareExactServiceVersions(input.targetVersion, input.installedVersion) < 0
|
||||
? new ServiceDowngradeRefusedError({
|
||||
installedVersion: input.installedVersion,
|
||||
targetVersion: input.targetVersion,
|
||||
})
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Install, update, or repair the service using the CLI version running this command. */
|
||||
export const reconcileService = Effect.fn("cli.service.reconcile")(function* () {
|
||||
export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
|
||||
readonly allowDowngrade?: boolean;
|
||||
}) {
|
||||
const service = yield* BootService.BootService;
|
||||
const status = yield* service.status;
|
||||
if (status.installed && status.current) {
|
||||
return { changed: false, status } satisfies ServiceReconcileResult;
|
||||
}
|
||||
const downgradeRefusal = serviceDowngradeRefusal({
|
||||
installedVersion: status.installedVersion,
|
||||
targetVersion: packageJson.version,
|
||||
allowDowngrade: options?.allowDowngrade === true,
|
||||
});
|
||||
if (downgradeRefusal !== null) {
|
||||
return yield* downgradeRefusal;
|
||||
}
|
||||
const plan = yield* service.install;
|
||||
return {
|
||||
changed: true,
|
||||
@@ -53,9 +92,23 @@ export function formatServiceStatus(
|
||||
if (!status.installed) {
|
||||
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
|
||||
}
|
||||
const installedVersion = status.installedVersion ?? cliVersion;
|
||||
if (
|
||||
!status.current &&
|
||||
status.installedVersion !== undefined &&
|
||||
compareExactServiceVersions(status.installedVersion, cliVersion) > 0
|
||||
) {
|
||||
return [
|
||||
"T3 Code service",
|
||||
` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
|
||||
` Unit: ${status.unitPath}`,
|
||||
` Logs: ${status.logPath}`,
|
||||
` Next: Use \`npx t3@${installedVersion} service update\` to repair it, or pass \`--allow-downgrade\` explicitly.`,
|
||||
].join("\n");
|
||||
}
|
||||
return [
|
||||
"T3 Code service",
|
||||
` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,
|
||||
` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
|
||||
` Unit: ${status.unitPath}`,
|
||||
` Logs: ${status.logPath}`,
|
||||
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
|
||||
@@ -71,13 +124,21 @@ const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(
|
||||
return yield* run.pipe(Effect.provide(bootServiceLayer(config)));
|
||||
});
|
||||
|
||||
const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe(
|
||||
const serviceReconcileFlags = {
|
||||
...projectLocationFlags,
|
||||
allowDowngrade: Flag.boolean("allow-downgrade").pipe(
|
||||
Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
};
|
||||
|
||||
const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
|
||||
Command.withDescription("Install T3 Code as a background service for this user."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const result = yield* reconcileService();
|
||||
const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
|
||||
if (!result.changed) {
|
||||
yield* Console.log(
|
||||
`T3 Code service is already installed with t3@${packageJson.version}.`,
|
||||
@@ -92,7 +153,7 @@ const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe
|
||||
),
|
||||
);
|
||||
|
||||
const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
|
||||
const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
|
||||
Command.withDescription(
|
||||
"Update or repair the background service using this CLI version. Use `npx t3@latest service update` for the latest release.",
|
||||
),
|
||||
@@ -100,7 +161,7 @@ const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const result = yield* reconcileService();
|
||||
const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
|
||||
if (!result.changed) {
|
||||
yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
|
||||
return;
|
||||
@@ -144,7 +205,8 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
|
||||
|
||||
export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const { supported, installed, current } = yield* service.status;
|
||||
const status = yield* service.status;
|
||||
const { supported, installed, current } = status;
|
||||
if (!supported) {
|
||||
return false;
|
||||
}
|
||||
@@ -152,6 +214,18 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
installed &&
|
||||
status.installedVersion !== undefined &&
|
||||
compareExactServiceVersions(status.installedVersion, packageJson.version) > 0
|
||||
) {
|
||||
yield* Console.log(
|
||||
`A newer t3@${status.installedVersion} background service is installed; leaving it unchanged.`,
|
||||
);
|
||||
// This CLI cannot verify that the newer unit is healthy, so keep the
|
||||
// manual `serve` fallback visible instead of claiming background readiness.
|
||||
return false;
|
||||
}
|
||||
const wanted = yield* Prompt.run(
|
||||
Prompt.confirm({
|
||||
message: installed
|
||||
@@ -174,7 +248,11 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
export const recoverServiceOnboardingOffer = <R>(
|
||||
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
|
||||
offer: Effect.Effect<
|
||||
boolean,
|
||||
BootService.BootServiceError | ServiceDowngradeRefusedError | Terminal.QuitError,
|
||||
R
|
||||
>,
|
||||
) =>
|
||||
offer.pipe(
|
||||
Effect.catchTags({
|
||||
@@ -185,6 +263,10 @@ export const recoverServiceOnboardingOffer = <R>(
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceInstallError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceUpdatePendingError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
ServiceDowngradeRefusedError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,558 +1,210 @@
|
||||
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,
|
||||
SERVICE_LAUNCHER_PROTOCOL,
|
||||
serviceStateHasPendingUpdate,
|
||||
} 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: SERVICE_LAUNCHER_PROTOCOL,
|
||||
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")));
|
||||
expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
|
||||
expect(yield* service.status).toMatchObject({
|
||||
current: true,
|
||||
installedVersion: "1.2.3",
|
||||
});
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
|
||||
const pendingState = JSON.stringify({
|
||||
protocol: SERVICE_LAUNCHER_PROTOCOL,
|
||||
activeVersion: "1.2.3",
|
||||
update: {
|
||||
id: "u",
|
||||
fromVersion: "1.2.3",
|
||||
targetVersion: "1.2.4",
|
||||
dbPath: "/tmp/state.sqlite",
|
||||
status: "pending",
|
||||
},
|
||||
});
|
||||
yield* fs.writeFileString(statePath, pendingState);
|
||||
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("reinstalls a pinned runtime when its entry point is missing", () =>
|
||||
it.effect("copies the launcher from the prepared pinned runtime", () =>
|
||||
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 { service, fs } = yield* makeHarness("linux", true);
|
||||
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);
|
||||
|
||||
expect(yield* fs.readFileString(plan.launcherPath)).toBe(
|
||||
"export const source = 'pinned runtime';\n",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports the installed version across launcher protocol revisions", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, fs, statePath } = yield* makeHarness();
|
||||
yield* service.install;
|
||||
yield* fs.writeFileString(
|
||||
statePath,
|
||||
`{"protocol":${String(SERVICE_LAUNCHER_PROTOCOL + 1)},"activeVersion":"9.9.9"}`,
|
||||
);
|
||||
|
||||
expect(yield* service.status).toMatchObject({
|
||||
current: false,
|
||||
installedVersion: "9.9.9",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restarts an installed service when repair fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, commands, control } = yield* makeHarness();
|
||||
yield* service.install;
|
||||
commands.length = 0;
|
||||
control.failCommand = "systemctl --user daemon-reload";
|
||||
|
||||
const error = yield* service.install.pipe(Effect.flip);
|
||||
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("restarts without overwriting a pending remote update", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, fs, statePath, commands } = yield* makeHarness();
|
||||
yield* service.install;
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
|
||||
const pendingState = JSON.stringify({
|
||||
protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
|
||||
activeVersion: "1.2.3",
|
||||
update: {
|
||||
id: "remote-update",
|
||||
fromVersion: "1.2.3",
|
||||
targetVersion: "1.2.4",
|
||||
status: "pending",
|
||||
},
|
||||
});
|
||||
yield* fs.writeFileString(statePath, pendingState);
|
||||
commands.length = 0;
|
||||
|
||||
yield* service.install;
|
||||
|
||||
assert.isTrue(commands.some(({ command }) => command === "npm"));
|
||||
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
|
||||
expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
|
||||
expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
|
||||
"systemctl --user stop t3code.service",
|
||||
"systemctl --user restart t3code.service",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads executable metadata from host process references", () =>
|
||||
it.effect("fails closed off Linux", () =>
|
||||
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 });
|
||||
yield* fs.writeFileString(
|
||||
path.join(unitDir, "t3code.service"),
|
||||
"[Service]\nExecStart=/old/node /old/t3 serve\n",
|
||||
);
|
||||
|
||||
const status = yield* service.status;
|
||||
assert.isTrue(status.supported);
|
||||
assert.isTrue(status.installed);
|
||||
assert.isFalse(status.current);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a current unit as stale when its entry point is gone", () =>
|
||||
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));
|
||||
|
||||
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"),
|
||||
);
|
||||
|
||||
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);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("removes the unit file when an activation step 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("/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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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,31 @@ 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,
|
||||
serviceStateActiveVersion,
|
||||
serviceStateHasPendingUpdate,
|
||||
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 +43,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 +64,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)}`,
|
||||
@@ -149,16 +112,26 @@ export class BootServiceInstallError extends Schema.TaggedErrorClass<BootService
|
||||
}
|
||||
}
|
||||
|
||||
export class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootServiceUpdatePendingError>()(
|
||||
"BootServiceUpdatePendingError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "A remote server update is still pending. Wait for it to finish, then retry.";
|
||||
}
|
||||
}
|
||||
|
||||
export type BootServiceError =
|
||||
| BootServiceUnsupportedError
|
||||
| BootServiceCommandError
|
||||
| BootServiceInstallError;
|
||||
| BootServiceInstallError
|
||||
| BootServiceUpdatePendingError;
|
||||
|
||||
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 installedVersion?: string;
|
||||
readonly unitPath: string;
|
||||
readonly logPath: string;
|
||||
}
|
||||
@@ -166,12 +139,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 +147,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 +157,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 +230,139 @@ 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* () {
|
||||
if (installed) {
|
||||
const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
|
||||
if (
|
||||
Option.isSome(previousStateText) &&
|
||||
serviceStateHasPendingUpdate(previousStateText.value)
|
||||
) {
|
||||
return yield* new BootServiceUpdatePendingError();
|
||||
}
|
||||
}
|
||||
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 +380,36 @@ 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;
|
||||
const installedVersion = Option.isSome(stateText)
|
||||
? serviceStateActiveVersion(stateText.value)
|
||||
: undefined;
|
||||
return {
|
||||
supported: true,
|
||||
installed: true,
|
||||
...(installedVersion === undefined ? {} : { installedVersion }),
|
||||
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"),
|
||||
|
||||
@@ -19,12 +19,19 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
import type { RelayLinkProofRequest } from "@t3tools/contracts/relay";
|
||||
import { CLOUD_ENDPOINT_RUNTIME_CONFIG, RELAY_URL_SECRET } from "./config.ts";
|
||||
import {
|
||||
CLOUD_ENDPOINT_RUNTIME_CONFIG,
|
||||
CLOUD_LINKED_USER_ID,
|
||||
decodeRuntimeConfig,
|
||||
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
|
||||
RELAY_URL_SECRET,
|
||||
} from "./config.ts";
|
||||
import {
|
||||
consumeCloudReplayGuards,
|
||||
isSupportedLinkProviderKind,
|
||||
linkProofScopes,
|
||||
reconcileDesiredCloudLink,
|
||||
managedEndpointOriginsEqual,
|
||||
reconcileCloudLinkOnStartup,
|
||||
releaseManagedTunnelOnShutdown,
|
||||
} from "./http.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
@@ -79,6 +86,18 @@ it("preserves messages surfaced by cloud 500 responses", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("compares managed endpoint origins without hostname formatting drift", () => {
|
||||
const desired = { localHttpHost: "127.0.0.1", localHttpPort: 7331 } as const;
|
||||
|
||||
expect(managedEndpointOriginsEqual(undefined, desired)).toBe(false);
|
||||
expect(
|
||||
managedEndpointOriginsEqual({ localHttpHost: "[127.0.0.1]", localHttpPort: 7331 }, desired),
|
||||
).toBe(true);
|
||||
expect(
|
||||
managedEndpointOriginsEqual({ localHttpHost: "127.0.0.1", localHttpPort: 7332 }, desired),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
describe("consumeCloudReplayGuards", () => {
|
||||
it.effect("reports already-created guards as replay conflicts", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -172,20 +191,25 @@ describe("relay request tracing", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("reconcileDesiredCloudLink", () => {
|
||||
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
|
||||
describe("reconcileCloudLinkOnStartup", () => {
|
||||
it.effect("restores a desired CLI link before attempting origin repair", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
|
||||
const error = yield* Effect.flip(reconcileCloudLinkOnStartup("http://127.0.0.1:3774"));
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
ServerSecretStore.ServerSecretStore,
|
||||
makeSecretStore(unusedSecretStoreOperation),
|
||||
),
|
||||
Effect.provideService(ServerSecretStore.ServerSecretStore, {
|
||||
...makeSecretStore(unusedSecretStoreOperation),
|
||||
get: (name) =>
|
||||
Effect.succeed(
|
||||
name === CLOUD_CLI_DESIRED_LINK_SECRET
|
||||
? Option.some(new TextEncoder().encode("managed"))
|
||||
: Option.none(),
|
||||
),
|
||||
}),
|
||||
Effect.provideService(
|
||||
ServerEnvironment.ServerEnvironment,
|
||||
ServerEnvironment.ServerEnvironment.of({
|
||||
@@ -222,6 +246,122 @@ describe("reconcileDesiredCloudLink", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("reconcileManagedEndpointOrigin", () => {
|
||||
it.effect("uses the environment credential and persists the reconciled origin", () => {
|
||||
const initialSecrets: ReadonlyArray<readonly [string, string]> = [
|
||||
[
|
||||
CLOUD_ENDPOINT_RUNTIME_CONFIG,
|
||||
JSON.stringify({
|
||||
providerKind: "cloudflare_tunnel",
|
||||
connectorToken: "old-connector-token",
|
||||
}),
|
||||
],
|
||||
[RELAY_URL_SECRET, "https://relay.example.test"],
|
||||
[RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
|
||||
[CLOUD_LINKED_USER_ID, "user_123"],
|
||||
];
|
||||
const values = new Map<string, Uint8Array>(
|
||||
initialSecrets.map(([name, value]) => [name, new TextEncoder().encode(value)] as const),
|
||||
);
|
||||
const store: ServerSecretStore.ServerSecretStore["Service"] = {
|
||||
get: (name) => Effect.sync(() => Option.fromNullishOr(values.get(name))),
|
||||
set: (name, value) =>
|
||||
Effect.sync(() => {
|
||||
values.set(name, value);
|
||||
}),
|
||||
create: unusedSecretStoreOperation,
|
||||
getOrCreateRandom: unusedSecretStoreOperation,
|
||||
remove: unusedSecretStoreOperation,
|
||||
};
|
||||
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
|
||||
const applied: Array<unknown> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
expect(yield* reconcileCloudLinkOnStartup("http://127.0.0.1:4555")).toBe(true);
|
||||
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0]?.url).toBe(
|
||||
"https://relay.example.test/v1/environments/env_123/managed-endpoint/reconcile",
|
||||
);
|
||||
expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential");
|
||||
expect(applied).toEqual([
|
||||
{
|
||||
providerKind: "cloudflare_tunnel",
|
||||
connectorToken: "fresh-connector-token",
|
||||
tunnelId: "tunnel-123",
|
||||
tunnelName: "tunnel-name",
|
||||
origin: { localHttpHost: "127.0.0.1", localHttpPort: 4555 },
|
||||
},
|
||||
]);
|
||||
const persisted = decodeRuntimeConfig(
|
||||
new TextDecoder().decode(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)),
|
||||
);
|
||||
expect(Option.getOrNull(persisted)?.origin).toEqual({
|
||||
localHttpHost: "127.0.0.1",
|
||||
localHttpPort: 4555,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(ServerSecretStore.ServerSecretStore, store),
|
||||
Effect.provideService(
|
||||
ServerEnvironment.ServerEnvironment,
|
||||
ServerEnvironment.ServerEnvironment.of({
|
||||
getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")),
|
||||
getDescriptor: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
|
||||
applyConfig: (config) =>
|
||||
Effect.sync(() => {
|
||||
applied.push(config);
|
||||
return {
|
||||
status: "running",
|
||||
providerKind: "cloudflare_tunnel",
|
||||
pid: 123,
|
||||
} as const;
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
EnvironmentAuth.EnvironmentAuth,
|
||||
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
CliTokenManager.CloudCliTokenManager,
|
||||
CliTokenManager.CloudCliTokenManager.of({
|
||||
get: unusedSecretStoreOperation(),
|
||||
getExisting: unusedSecretStoreOperation(),
|
||||
hasCredential: unusedSecretStoreOperation(),
|
||||
store: unusedSecretStoreOperation,
|
||||
clear: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.sync(() => {
|
||||
requests.push(request);
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({
|
||||
endpointRuntime: {
|
||||
providerKind: "cloudflare_tunnel",
|
||||
connectorToken: "fresh-connector-token",
|
||||
tunnelId: "tunnel-123",
|
||||
tunnelName: "tunnel-name",
|
||||
origin: { localHttpHost: "127.0.0.1", localHttpPort: 4555 },
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("releaseManagedTunnelOnShutdown", () => {
|
||||
const cliToken: CliTokenManager.PersistedToken = {
|
||||
accessToken: "cli-access-token",
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
RelayEnvironmentConfigRequest,
|
||||
RelayEnvironmentLinkChallengeResponse,
|
||||
RelayEnvironmentLinkResponse,
|
||||
RelayManagedEndpointReconcileResponse,
|
||||
RelayEnvironmentMintResponseProofPayload,
|
||||
type RelayEnvironmentMintResponse as RelayEnvironmentMintResponseShape,
|
||||
RelayEnvironmentLinkProof,
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
CLOUD_ENDPOINT_RUNTIME_CONFIG,
|
||||
CLOUD_LINKED_USER_ID,
|
||||
CLOUD_MINT_PUBLIC_KEY,
|
||||
decodeRuntimeConfig,
|
||||
encodeEndpointRuntimeConfigJson,
|
||||
PUBLISH_AGENT_ACTIVITY_SECRET,
|
||||
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
|
||||
@@ -627,6 +629,115 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
|
||||
},
|
||||
);
|
||||
|
||||
function managedEndpointOriginFromLocalUrl(localUrl: URL): RelayManagedEndpointOrigin {
|
||||
return {
|
||||
localHttpHost: localUrl.hostname,
|
||||
localHttpPort: endpointRequestPort(localUrl),
|
||||
};
|
||||
}
|
||||
|
||||
export function managedEndpointOriginsEqual(
|
||||
left: RelayManagedEndpointOrigin | undefined,
|
||||
right: RelayManagedEndpointOrigin,
|
||||
): boolean {
|
||||
return (
|
||||
left !== undefined &&
|
||||
normalizeHostname(left.localHttpHost) === normalizeHostname(right.localHttpHost) &&
|
||||
left.localHttpPort === right.localHttpPort
|
||||
);
|
||||
}
|
||||
|
||||
const reconcileManagedEndpointOriginWith = Effect.fn(
|
||||
"environment.cloud.reconcileManagedEndpointOriginWith",
|
||||
)(function* (dependencies: CloudHttpDependencies, localOrigin: string) {
|
||||
const localUrl = yield* Effect.try({
|
||||
try: () => new URL(localOrigin),
|
||||
catch: () =>
|
||||
new EnvironmentHttpBadRequestError({
|
||||
message: "Could not resolve local environment origin.",
|
||||
}),
|
||||
});
|
||||
if (localUrl.origin !== localOrigin) {
|
||||
return yield* new EnvironmentHttpBadRequestError({
|
||||
message: "Could not resolve local environment origin.",
|
||||
});
|
||||
}
|
||||
const desiredOrigin = managedEndpointOriginFromLocalUrl(localUrl);
|
||||
const storedConfigBytes = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
|
||||
const storedConfig = Option.isSome(storedConfigBytes)
|
||||
? decodeRuntimeConfig(bytesToString(storedConfigBytes.value))
|
||||
: Option.none();
|
||||
if (Option.isSome(storedConfigBytes) && Option.isNone(storedConfig)) {
|
||||
return yield* new EnvironmentHttpInternalServerError({
|
||||
message: "Stored managed endpoint runtime configuration is invalid.",
|
||||
});
|
||||
}
|
||||
const config = Option.getOrNull(storedConfig);
|
||||
const desiredManagedLink =
|
||||
(yield* readCliDesiredCloudLink) && (yield* readCliDesiredLinkMode) === "managed";
|
||||
if (config?.providerKind !== "cloudflare_tunnel" && !desiredManagedLink) {
|
||||
return false;
|
||||
}
|
||||
if (managedEndpointOriginsEqual(config?.origin, desiredOrigin)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const relayUrl = yield* dependencies.secrets.get(RELAY_URL_SECRET);
|
||||
const environmentCredential = yield* dependencies.secrets.get(
|
||||
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
|
||||
);
|
||||
const cloudUserId = yield* dependencies.secrets.get(CLOUD_LINKED_USER_ID);
|
||||
if (
|
||||
Option.isNone(relayUrl) ||
|
||||
Option.isNone(environmentCredential) ||
|
||||
Option.isNone(cloudUserId)
|
||||
) {
|
||||
return yield* new EnvironmentHttpUnauthorizedError({
|
||||
message: "This managed environment is missing its T3 Connect credentials. Link it again.",
|
||||
});
|
||||
}
|
||||
|
||||
const environmentId = yield* dependencies.environment.getEnvironmentId;
|
||||
const response = yield* relayClientRequest(dependencies, {
|
||||
url: `${bytesToString(relayUrl.value)}/v1/environments/${encodeURIComponent(environmentId)}/managed-endpoint/reconcile`,
|
||||
token: bytesToString(environmentCredential.value),
|
||||
payload: {
|
||||
cloudUserId: bytesToString(cloudUserId.value),
|
||||
origin: desiredOrigin,
|
||||
},
|
||||
schema: RelayManagedEndpointReconcileResponse,
|
||||
});
|
||||
const status = yield* dependencies.endpointRuntime.applyConfig(response.endpointRuntime);
|
||||
if (status.status !== "running") {
|
||||
return yield* new EnvironmentCloudEndpointUnavailableError({
|
||||
message: "Managed endpoint runtime could not be started after origin reconciliation.",
|
||||
endpointRuntimeStatus: status,
|
||||
});
|
||||
}
|
||||
const encoded = yield* encodeEndpointRuntimeConfigJson(response.endpointRuntime);
|
||||
yield* dependencies.secrets.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, stringToBytes(encoded));
|
||||
return true;
|
||||
});
|
||||
|
||||
export const reconcileManagedEndpointOrigin = Effect.fn(
|
||||
"environment.cloud.reconcileManagedEndpointOrigin",
|
||||
)(function* (localOrigin: string) {
|
||||
return yield* reconcileManagedEndpointOriginWith(yield* cloudHttpDependencies, localOrigin);
|
||||
});
|
||||
|
||||
/** Restores CLI-desired links first, then repairs origin drift for links that
|
||||
are owned by web or mobile and therefore have no CLI desired-link marker. */
|
||||
export const reconcileCloudLinkOnStartup = Effect.fn(
|
||||
"environment.cloud.reconcileCloudLinkOnStartup",
|
||||
)(function* (localOrigin: string) {
|
||||
const dependencies = yield* cloudHttpDependencies;
|
||||
if (yield* readCliDesiredCloudLink) {
|
||||
yield* reconcileDesiredCloudLinkWith(dependencies, localOrigin);
|
||||
return true;
|
||||
}
|
||||
return yield* reconcileManagedEndpointOriginWith(dependencies, localOrigin);
|
||||
});
|
||||
|
||||
// Cloudflare bills per provisioned tunnel, so an environment that goes offline
|
||||
// must not leave its tunnel behind. Releasing deletes only the tunnel — the
|
||||
// relay keeps the link and its hostname reservation, and the next startup's
|
||||
@@ -641,11 +752,11 @@ export const releaseManagedTunnelOnShutdown = Effect.fn(
|
||||
if (Option.isNone(runtimeConfig)) {
|
||||
return false;
|
||||
}
|
||||
// Only CLI-desired managed links release on shutdown, because the startup
|
||||
// reconcile that provisions the replacement tunnel only runs for them. A
|
||||
// link installed by a web/mobile client comes back after a restart by
|
||||
// reapplying the stored connector token — it has no boot-time re-provision
|
||||
// path — so its tunnel must survive the restart. (Unlink still deletes it.)
|
||||
// Only CLI-desired managed links release on shutdown. Their desired-link
|
||||
// marker lets startup re-provision after this function removes the dead
|
||||
// runtime config. Web/mobile links have no equivalent marker, so they keep
|
||||
// the tunnel and stored connector token across restarts. (Unlink still
|
||||
// deletes it.)
|
||||
if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -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), []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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));
|
||||
@@ -4,7 +4,6 @@ import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
import * as Config from "effect/Config";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
|
||||
@@ -24,7 +23,7 @@ function validateRelayUrl(value: string) {
|
||||
? Effect.fail(
|
||||
new Config.ConfigError(
|
||||
new Schema.SchemaError(
|
||||
new SchemaIssue.InvalidValue(Option.some(value), {
|
||||
new SchemaIssue.InvalidValue({
|
||||
message: "Relay URL must be a secure absolute HTTPS origin.",
|
||||
}),
|
||||
),
|
||||
@@ -130,7 +129,7 @@ function validateHostedAppUrl(value: string) {
|
||||
return Effect.fail(
|
||||
new Config.ConfigError(
|
||||
new Schema.SchemaError(
|
||||
new SchemaIssue.InvalidValue(Option.some(value), {
|
||||
new SchemaIssue.InvalidValue({
|
||||
message: "Hosted app URL must be an absolute HTTPS origin (or HTTP loopback origin).",
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -1,632 +1,148 @@
|
||||
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 { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.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: SERVICE_LAUNCHER_PROTOCOL,
|
||||
};
|
||||
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,
|
||||
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", "--no-block", "t3code.service"],
|
||||
});
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
// systemd replaces the process; the server must not exit itself.
|
||||
assert.equal(context.exitCount(), 0);
|
||||
|
||||
// The queued restart returns while this process is still shutting
|
||||
// down; the lock must stay held so a second update cannot rewrite the
|
||||
// unit mid-teardown.
|
||||
const concurrentError = yield* context.service
|
||||
.update({ targetVersion: "0.0.30" })
|
||||
.pipe(Effect.flip);
|
||||
assert.include(concurrentError.reason, "already in progress");
|
||||
}).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", "--no-block", 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
-364
@@ -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,208 +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, dbPath: serverConfig.dbPath })
|
||||
.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. --no-block queues the restart job and exits before systemd
|
||||
// stops this unit: a blocking restart's SIGTERM reaches the systemctl
|
||||
// child (it shares this service's cgroup), which read as a restart
|
||||
// failure and rolled the new unit back while the old server finished
|
||||
// shutting down. With the handoff race gone, a non-zero exit or spawn
|
||||
// error means systemd genuinely rejected the job while this process is
|
||||
// still alive, so restoring the previous unit below stays correct.
|
||||
yield* scheduleRestart(
|
||||
Effect.gen(function* () {
|
||||
const restart = yield* runner
|
||||
.run({
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", "--no-block", 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 }),
|
||||
// Permit a retry only after the failed handoff was rolled
|
||||
// back. A queued restart returns while this process is still
|
||||
// shutting down; releasing the lock then would let a second
|
||||
// update rewrite the unit mid-teardown.
|
||||
Effect.andThen(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,138 @@
|
||||
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,
|
||||
SERVICE_LAUNCHER_PROTOCOL,
|
||||
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",
|
||||
dbPath: "/tmp/state.sqlite",
|
||||
status: "pending" as const,
|
||||
};
|
||||
const host = new FakeLauncherProcess({
|
||||
protocol: SERVICE_LAUNCHER_PROTOCOL,
|
||||
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: SERVICE_LAUNCHER_PROTOCOL,
|
||||
childVersion: "1.0.0",
|
||||
});
|
||||
const client = yield* makeClient(host, "1.0.0");
|
||||
const requested = yield* Effect.forkChild(
|
||||
client.requestUpdate({ targetVersion: "1.1.0", dbPath: "/tmp/state.sqlite" }),
|
||||
{ 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: SERVICE_LAUNCHER_PROTOCOL,
|
||||
childVersion: "1.0.0",
|
||||
});
|
||||
const client = yield* makeClient(host, "1.0.0");
|
||||
const requested = yield* Effect.forkChild(
|
||||
client.requestUpdate({ targetVersion: "1.1.0", dbPath: "/tmp/state.sqlite" }),
|
||||
{ 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: SERVICE_LAUNCHER_PROTOCOL,
|
||||
childVersion: "1.1.0",
|
||||
update: {
|
||||
id: "update-1",
|
||||
fromVersion: "1.0.0",
|
||||
targetVersion: "1.2.0",
|
||||
dbPath: "/tmp/state.sqlite",
|
||||
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,253 @@
|
||||
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 requestUpdate: (input: {
|
||||
readonly targetVersion: string;
|
||||
readonly dbPath: 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 { managed } = yield* resolveStartup();
|
||||
return { managed };
|
||||
},
|
||||
);
|
||||
|
||||
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; readonly dbPath: 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({
|
||||
id: pending.id,
|
||||
fromVersion: pending.fromVersion,
|
||||
targetVersion: pending.targetVersion,
|
||||
status: "committed" as const,
|
||||
});
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(outcome);
|
||||
|
||||
return ServiceLauncherClient.of({
|
||||
managed,
|
||||
requestUpdate,
|
||||
prepareTrial,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ServiceLauncherClient, make());
|
||||
@@ -0,0 +1,26 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
|
||||
import { runServicePreflight } from "./servicePreflight.ts";
|
||||
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
|
||||
|
||||
it("requires the database-snapshot launcher protocol", () => {
|
||||
expect(
|
||||
runServicePreflight({
|
||||
databasePath: "/missing/state.sqlite",
|
||||
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL - 1,
|
||||
version: "1.2.3",
|
||||
}),
|
||||
).toMatchObject({ status: "blocked", version: "1.2.3" });
|
||||
|
||||
expect(
|
||||
runServicePreflight({
|
||||
databasePath: "/missing/state.sqlite",
|
||||
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
|
||||
version: "1.2.3",
|
||||
}),
|
||||
).toEqual({
|
||||
status: "ready",
|
||||
version: "1.2.3",
|
||||
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
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;
|
||||
};
|
||||
|
||||
export function runServicePreflight(input: {
|
||||
/** Older servers always pass this flag when invoking a staged preflight. */
|
||||
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.",
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
|
||||
|
||||
/** Protocol 2 snapshots SQLite before trials so migrations can be rolled back safely. */
|
||||
export const SERVICE_LAUNCHER_PROTOCOL = 2 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 dbPath: 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 dbPath: 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 typeof value.dbPath === "string" && value.dbPath.trim() !== ""
|
||||
? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }
|
||||
: undefined;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/** Detects an in-flight update across launcher protocol versions before replacing its state. */
|
||||
export function serviceStateHasPendingUpdate(value: string): boolean {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === "pending";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads the active version across launcher protocol revisions for downgrade protection. */
|
||||
export function serviceStateActiveVersion(value: string): string | undefined {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
return isRecord(parsed) &&
|
||||
typeof parsed.activeVersion === "string" &&
|
||||
isExactServiceVersion(parsed.activeVersion)
|
||||
? parsed.activeVersion
|
||||
: undefined;
|
||||
} 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" &&
|
||||
typeof value.dbPath === "string"
|
||||
) {
|
||||
return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
|
||||
}
|
||||
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 = {
|
||||
@@ -142,11 +145,10 @@ export const make = Effect.gen(function* () {
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
threadPinning: true,
|
||||
threadTitleRegeneration: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
...(serverSelfUpdate === "boot-service" || serverSelfUpdate === "respawn"
|
||||
? { serverSelfUpdateProgress: true }
|
||||
: {}),
|
||||
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
+3
-68
@@ -14,10 +14,10 @@ import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import { cast } from "effect/Function";
|
||||
import {
|
||||
Headers,
|
||||
HttpBody,
|
||||
HttpClient,
|
||||
HttpClientResponse,
|
||||
HttpMiddleware,
|
||||
HttpRouter,
|
||||
HttpServerResponse,
|
||||
HttpServerRequest,
|
||||
@@ -30,7 +30,6 @@ import * as ServerConfig from "./config.ts";
|
||||
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
|
||||
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts";
|
||||
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
|
||||
import {
|
||||
annotateEnvironmentRequest,
|
||||
@@ -44,74 +43,10 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
|
||||
const GZIP_MIN_BYTES = 1024;
|
||||
|
||||
function acceptsGzip(value: string | undefined): boolean {
|
||||
if (!value) return false;
|
||||
|
||||
const accepted = new Map(
|
||||
value.split(",").map((entry) => {
|
||||
const [coding = "", ...parameters] = entry.trim().toLowerCase().split(";");
|
||||
const quality = parameters
|
||||
.map((parameter) => parameter.trim().match(/^q=(.+)$/)?.[1])
|
||||
.find((parameter) => parameter !== undefined);
|
||||
return [coding, quality === undefined ? 1 : Number(quality)] as const;
|
||||
}),
|
||||
);
|
||||
return (accepted.get("gzip") ?? accepted.get("*") ?? 0) > 0;
|
||||
}
|
||||
|
||||
function varyByAcceptEncoding(value: string | undefined): string {
|
||||
if (!value) return "Accept-Encoding";
|
||||
const values = new Set(value.split(",").map((entry) => entry.trim().toLowerCase()));
|
||||
return values.has("*") || values.has("accept-encoding") ? value : `${value}, Accept-Encoding`;
|
||||
}
|
||||
|
||||
const compressHttpResponse = Effect.fnUntraced(function* (
|
||||
response: HttpServerResponse.HttpServerResponse,
|
||||
acceptEncoding: string | undefined,
|
||||
) {
|
||||
const body = response.body;
|
||||
if (
|
||||
body._tag !== "Uint8Array" ||
|
||||
body.contentLength < GZIP_MIN_BYTES ||
|
||||
!body.contentType.startsWith("application/json") ||
|
||||
response.headers["content-encoding"]
|
||||
) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const variedResponse = HttpServerResponse.setHeader(
|
||||
response,
|
||||
"vary",
|
||||
varyByAcceptEncoding(response.headers.vary),
|
||||
);
|
||||
if (!acceptsGzip(acceptEncoding)) return variedResponse;
|
||||
|
||||
const compression = yield* HttpResponseCompression.HttpResponseCompression;
|
||||
const headers = Headers.set(
|
||||
Headers.remove(variedResponse.headers, "content-length"),
|
||||
"content-encoding",
|
||||
"gzip",
|
||||
);
|
||||
return compression.gzip(body.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers,
|
||||
cookies: response.cookies,
|
||||
contentType: body.contentType,
|
||||
});
|
||||
export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
|
||||
global: true,
|
||||
});
|
||||
|
||||
export const httpCompressionLayer = HttpRouter.middleware(
|
||||
(httpEffect) =>
|
||||
Effect.flatMap(
|
||||
Effect.all([httpEffect, HttpServerRequest.HttpServerRequest]),
|
||||
([response, request]) => compressHttpResponse(response, request.headers["accept-encoding"]),
|
||||
),
|
||||
{ global: true },
|
||||
);
|
||||
|
||||
export const browserApiCorsLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as NodeStream from "node:stream";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as HttpResponseCompression from "./HttpResponseCompression.ts";
|
||||
|
||||
it.effect("uses a native Node stream", () =>
|
||||
Effect.gen(function* () {
|
||||
const compression = yield* HttpResponseCompression.HttpResponseCompression;
|
||||
const response = compression.gzip(new Uint8Array(), {});
|
||||
|
||||
expect(response.body._tag).toBe("Raw");
|
||||
if (response.body._tag === "Raw") {
|
||||
expect(response.body.body).toBeInstanceOf(NodeStream.Readable);
|
||||
}
|
||||
}).pipe(Effect.provide(HttpResponseCompression.layerNode)),
|
||||
);
|
||||
|
||||
it.effect("uses a native Web stream for Bun", () =>
|
||||
Effect.gen(function* () {
|
||||
const compression = yield* HttpResponseCompression.HttpResponseCompression;
|
||||
const response = compression.gzip(new Uint8Array(), {});
|
||||
|
||||
expect(response.body._tag).toBe("Raw");
|
||||
if (response.body._tag === "Raw") {
|
||||
expect(response.body.body).toBeInstanceOf(ReadableStream);
|
||||
}
|
||||
}).pipe(Effect.provide(HttpResponseCompression.layerBun)),
|
||||
);
|
||||
@@ -1,36 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
|
||||
export class HttpResponseCompression extends Context.Service<
|
||||
HttpResponseCompression,
|
||||
{
|
||||
readonly gzip: (
|
||||
body: Uint8Array,
|
||||
options: HttpServerResponse.Options,
|
||||
) => HttpServerResponse.HttpServerResponse;
|
||||
}
|
||||
>()("t3/httpCompression/HttpResponseCompression") {}
|
||||
|
||||
export const layerNode = Layer.effect(
|
||||
HttpResponseCompression,
|
||||
Effect.gen(function* () {
|
||||
const NodeZlib = yield* Effect.promise(() => import("node:zlib"));
|
||||
return {
|
||||
gzip: (body, options) => {
|
||||
const stream = NodeZlib.createGzip();
|
||||
stream.end(body);
|
||||
return HttpServerResponse.raw(stream, options);
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
export const layerBun = Layer.succeed(HttpResponseCompression, {
|
||||
gzip: (body, options) =>
|
||||
HttpServerResponse.raw(
|
||||
new Response(body).body!.pipeThrough(new CompressionStream("gzip")),
|
||||
options,
|
||||
),
|
||||
});
|
||||
@@ -29,7 +29,6 @@ import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Predicate from "effect/Predicate";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Result from "effect/Result";
|
||||
@@ -68,7 +67,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
|
||||
Effect.filterOrFail(
|
||||
Predicate.isNotNull,
|
||||
() =>
|
||||
new SchemaIssue.InvalidValue(Option.some(rule), {
|
||||
new SchemaIssue.InvalidValue({
|
||||
message: "Invalid keybinding rule",
|
||||
}),
|
||||
),
|
||||
@@ -80,7 +79,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
|
||||
const key = encodeShortcut(resolved.shortcut);
|
||||
if (!key) {
|
||||
return yield* Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(resolved), {
|
||||
new SchemaIssue.InvalidValue({
|
||||
message: "Resolved shortcut cannot be encoded to key string",
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -5,7 +5,7 @@ import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3to
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { McpSchema, McpServer } from "effect/unstable/ai";
|
||||
import { McpProtocol, McpSchema, McpServer } from "effect/unstable/ai";
|
||||
import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import * as McpHttpServer from "./McpHttpServer.ts";
|
||||
@@ -26,8 +26,9 @@ const invocation = {
|
||||
};
|
||||
const client = McpSchema.McpServerClient.of({
|
||||
clientId: 1,
|
||||
protocolVersion: "2025-06-18",
|
||||
initializePayload: {
|
||||
protocolVersion: "2025-03-26",
|
||||
protocolVersion: "2025-06-18",
|
||||
capabilities: {},
|
||||
clientInfo: { name: "mcp-test", version: "1.0.0" },
|
||||
},
|
||||
@@ -103,6 +104,7 @@ it.effect("terminates HTTP MCP sessions with DELETE", () =>
|
||||
name: "MCP termination test",
|
||||
version: "1.0.0",
|
||||
path: "/mcp",
|
||||
protocols: [McpProtocol.v2025_06_18],
|
||||
});
|
||||
yield* HttpRouter.serve(serverLayer, {
|
||||
disableListenLog: true,
|
||||
@@ -239,8 +241,9 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
Effect.flip,
|
||||
);
|
||||
expect(malformed.isError).toBe(true);
|
||||
expect(malformed._tag).toBe("InvalidParams");
|
||||
|
||||
const snapshot = yield* server
|
||||
.callTool({ name: "preview_snapshot", arguments: { tabId: alternateTabId } })
|
||||
|
||||
@@ -6,7 +6,7 @@ import * as Option from "effect/Option";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import type * as Types from "effect/Types";
|
||||
import { McpSchema, McpServer, Tool } from "effect/unstable/ai";
|
||||
import { McpProtocol, McpSchema, McpServer, Tool } from "effect/unstable/ai";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
@@ -220,6 +220,7 @@ const McpTransportLive = McpServer.layerHttp({
|
||||
name: "T3 Code",
|
||||
version: packageJson.version,
|
||||
path: "/mcp",
|
||||
protocols: [McpProtocol.v2025_06_18],
|
||||
}).pipe(Layer.provide(McpAuthMiddlewareLive));
|
||||
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
|
||||
@@ -12,6 +12,19 @@ const schemaHasDescription = (schema: unknown): boolean => {
|
||||
.some((members) => members.some(schemaHasDescription));
|
||||
};
|
||||
|
||||
const schemaHasMultipleAllOfDescriptions = (schema: unknown): boolean => {
|
||||
if (!schema || typeof schema !== "object") return false;
|
||||
const record = schema as Record<string, unknown>;
|
||||
const allOf = Array.isArray(record.allOf) ? record.allOf : [];
|
||||
const descriptionCount = allOf.filter(
|
||||
(member) =>
|
||||
member !== null &&
|
||||
typeof member === "object" &&
|
||||
typeof (member as Record<string, unknown>).description === "string",
|
||||
).length;
|
||||
return descriptionCount > 1 || Object.values(record).some(schemaHasMultipleAllOfDescriptions);
|
||||
};
|
||||
|
||||
it("exports provider-compatible object schemas with described parameters", () => {
|
||||
for (const tool of Object.values(PreviewToolkit.tools)) {
|
||||
const schema = Tool.getJsonSchema(tool) as {
|
||||
@@ -27,6 +40,9 @@ it("exports provider-compatible object schemas with described parameters", () =>
|
||||
expect(schema.type, `${tool.name} must export a top-level object schema`).toBe("object");
|
||||
expect(schema.anyOf, `${tool.name} must not export a root anyOf`).toBeUndefined();
|
||||
expect(schema.oneOf, `${tool.name} must not export a root oneOf`).toBeUndefined();
|
||||
if (tool.name === "preview_navigate") {
|
||||
expect(schemaHasMultipleAllOfDescriptions(schema)).toBe(false);
|
||||
}
|
||||
expect(
|
||||
schema.properties?.tabId,
|
||||
`${tool.name} must allow an explicit collaborative browser tab target`,
|
||||
|
||||
@@ -29,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";
|
||||
@@ -912,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" &&
|
||||
@@ -926,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;
|
||||
|
||||
@@ -611,6 +611,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
pinnedAt: null,
|
||||
titleRegenerationRequestId: null,
|
||||
titleRegenerationStartedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
@@ -717,6 +718,36 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.pinned": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
pinnedAt: event.payload.pinnedAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.unpinned": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
pinnedAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -312,6 +312,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
pinnedAt: null,
|
||||
titleRegeneration: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
@@ -427,6 +428,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
pinnedAt: null,
|
||||
titleRegeneration: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
|
||||
@@ -384,6 +384,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
pinned_at AS "pinnedAt",
|
||||
title_regeneration_request_id AS "titleRegenerationRequestId",
|
||||
title_regeneration_started_at AS "titleRegenerationStartedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
@@ -418,6 +419,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
pinned_at AS "pinnedAt",
|
||||
title_regeneration_request_id AS "titleRegenerationRequestId",
|
||||
title_regeneration_started_at AS "titleRegenerationStartedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
@@ -454,6 +456,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
pinned_at AS "pinnedAt",
|
||||
title_regeneration_request_id AS "titleRegenerationRequestId",
|
||||
title_regeneration_started_at AS "titleRegenerationStartedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
@@ -890,6 +893,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
pinned_at AS "pinnedAt",
|
||||
title_regeneration_request_id AS "titleRegenerationRequestId",
|
||||
title_regeneration_started_at AS "titleRegenerationStartedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
@@ -1328,6 +1332,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
pinnedAt: row.pinnedAt,
|
||||
titleRegeneration: mapTitleRegeneration(row),
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
@@ -1531,6 +1536,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
pinnedAt: row.pinnedAt,
|
||||
titleRegeneration: mapTitleRegeneration(row),
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
@@ -1665,6 +1671,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
pinnedAt: row.pinnedAt,
|
||||
titleRegeneration: mapTitleRegeneration(row),
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
@@ -1804,6 +1811,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
pinnedAt: row.pinnedAt,
|
||||
titleRegeneration: mapTitleRegeneration(row),
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
@@ -2075,6 +2083,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
pinnedAt: threadRow.value.pinnedAt,
|
||||
titleRegeneration: mapTitleRegeneration(threadRow.value),
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
@@ -2174,6 +2183,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
pinnedAt: threadRow.value.pinnedAt,
|
||||
titleRegeneration: mapTitleRegeneration(threadRow.value),
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
|
||||
@@ -785,6 +785,123 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.titleRegeneration).toBeNull();
|
||||
});
|
||||
|
||||
it("pins the first user message when regeneration context is truncated", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const firstUserMessage = `Review subagent monitoring risks. ${"Opening context. ".repeat(200)}`;
|
||||
const recentUserMessage = `LATEST FINDING: ${"implementation detail ".repeat(320)}`;
|
||||
harness.generateThreadTitle.mockReturnValue(
|
||||
Effect.succeed({ title: "Review subagent monitoring risks" }),
|
||||
);
|
||||
|
||||
await harness.runEffect(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-thread-title-existing-long"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
title: "Generic PR review",
|
||||
}),
|
||||
);
|
||||
await harness.runEffect(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-before-long-title-regeneration"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-before-long-title-regeneration"),
|
||||
role: "user",
|
||||
text: firstUserMessage,
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "opening-context-image",
|
||||
name: "image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
await harness.runEffect(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-middle-turn-before-long-title-regeneration"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("middle-message-before-long-title-regeneration"),
|
||||
role: "user",
|
||||
text: "Temporary handoff details.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "middle-context-image",
|
||||
name: "image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
}),
|
||||
);
|
||||
await harness.runEffect(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-recent-turn-before-long-title-regeneration"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("recent-message-before-long-title-regeneration"),
|
||||
role: "user",
|
||||
text: recentUserMessage,
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "recent-context-image",
|
||||
name: "image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
}),
|
||||
);
|
||||
await harness.runEffect(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-thread-title-regenerate-long"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
regenerateTitle: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await harness.drain();
|
||||
|
||||
expect(harness.generateThreadTitle).toHaveBeenCalledTimes(1);
|
||||
const input = harness.generateThreadTitle.mock.calls[0]?.[0];
|
||||
if (!input) {
|
||||
throw new Error("Expected a title generation input");
|
||||
}
|
||||
const message = input.message;
|
||||
expect(message.startsWith("USER:\nReview subagent monitoring risks.")).toBe(true);
|
||||
expect(message).toContain("[First user message truncated]");
|
||||
expect(message).toContain("[Earlier content truncated]");
|
||||
expect(message).toContain("image.png");
|
||||
expect(message).toHaveLength(8_000);
|
||||
expect(input.attachments?.map((attachment) => attachment.id)).toEqual([
|
||||
"opening-context-image",
|
||||
"recent-context-image",
|
||||
]);
|
||||
});
|
||||
|
||||
it("clears title regeneration state left pending across reactor startup", async () => {
|
||||
const harness = await createHarness({
|
||||
titleRegenerationBeforeStart: "one",
|
||||
@@ -972,10 +1089,14 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.titleRegeneration).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the full retained context and excludes attachments outside it", async () => {
|
||||
it("pins the first user context and attachment before the retained tail", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const retainedContext = "x".repeat(8_000);
|
||||
const firstUserContext = "USER:\nOld visual issue\n[Attachments: old-issue.png]";
|
||||
const truncationMarker = "[Earlier content truncated]\n\n";
|
||||
const retainedContext = "x".repeat(
|
||||
8_000 - firstUserContext.length - "\n\n".length - truncationMarker.length,
|
||||
);
|
||||
|
||||
await harness.runEffect(
|
||||
harness.engine.dispatch({
|
||||
@@ -1040,9 +1161,14 @@ describe("ProviderCommandReactor", () => {
|
||||
await harness.drain();
|
||||
|
||||
expect(harness.generateThreadTitle.mock.calls[0]?.[0].message).toBe(
|
||||
`[Earlier content truncated]\n\n${retainedContext}`,
|
||||
`${firstUserContext}\n\n${truncationMarker}${retainedContext}`,
|
||||
);
|
||||
expect(harness.generateThreadTitle.mock.calls[0]?.[0].attachments).toBeUndefined();
|
||||
expect(harness.generateThreadTitle.mock.calls[0]?.[0].attachments).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "old-title-context-image",
|
||||
name: "old-issue.png",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not overwrite a manual rename while title regeneration is running", async () => {
|
||||
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { forkParked, ServerActivation } from "../../serverActivation.ts";
|
||||
import {
|
||||
resolveSourceControlWriterModelSelection,
|
||||
ServerSettingsService,
|
||||
@@ -93,41 +94,61 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
const DEFAULT_THREAD_TITLE = "New thread";
|
||||
const MAX_REGENERATION_ATTACHMENTS = 4;
|
||||
const MAX_THREAD_TITLE_CONTEXT_CHARS = 8_000;
|
||||
const MAX_FIRST_USER_TITLE_CONTEXT_CHARS = 2_000;
|
||||
const THREAD_TITLE_CONTEXT_TRUNCATION_MARKER = "[Earlier content truncated]\n\n";
|
||||
const FIRST_USER_CONTEXT_TRUNCATION_MARKER = "\n[First user message truncated]";
|
||||
|
||||
function formatThreadTitleContext(
|
||||
messages: ReadonlyArray<{
|
||||
readonly role: "user" | "assistant" | "system";
|
||||
readonly text: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
}>,
|
||||
type ThreadTitleMessage = {
|
||||
readonly role: "user" | "assistant" | "system";
|
||||
readonly text: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
};
|
||||
|
||||
function formatThreadTitleSection(message: ThreadTitleMessage): string | undefined {
|
||||
if (message.role === "system") {
|
||||
return undefined;
|
||||
}
|
||||
const text = message.text.trim();
|
||||
const attachmentSummary = (message.attachments ?? [])
|
||||
.map((attachment) => attachment.name)
|
||||
.join(", ");
|
||||
const contents = [
|
||||
...(text.length > 0 ? [text] : []),
|
||||
...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []),
|
||||
].join("\n");
|
||||
return contents.length > 0 ? `${message.role.toUpperCase()}:\n${contents}` : undefined;
|
||||
}
|
||||
|
||||
function limitFirstUserSection(section: string): string {
|
||||
if (section.length <= MAX_FIRST_USER_TITLE_CONTEXT_CHARS) {
|
||||
return section;
|
||||
}
|
||||
return `${section.slice(
|
||||
0,
|
||||
MAX_FIRST_USER_TITLE_CONTEXT_CHARS - FIRST_USER_CONTEXT_TRUNCATION_MARKER.length,
|
||||
)}${FIRST_USER_CONTEXT_TRUNCATION_MARKER}`;
|
||||
}
|
||||
|
||||
function collectRecentThreadTitleContext(
|
||||
messages: ReadonlyArray<ThreadTitleMessage>,
|
||||
maxChars: number,
|
||||
): {
|
||||
readonly message: string;
|
||||
readonly context: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
readonly truncated: boolean;
|
||||
} {
|
||||
let context = "";
|
||||
let truncated = false;
|
||||
const retainedAttachments: Array<ChatAttachment> = [];
|
||||
|
||||
for (const message of messages.toReversed()) {
|
||||
if (message.role === "system") {
|
||||
continue;
|
||||
}
|
||||
const text = message.text.trim();
|
||||
const attachmentSummary = (message.attachments ?? [])
|
||||
.map((attachment) => attachment.name)
|
||||
.join(", ");
|
||||
const contents = [
|
||||
...(text.length > 0 ? [text] : []),
|
||||
...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []),
|
||||
].join("\n");
|
||||
if (contents.length === 0) {
|
||||
const section = formatThreadTitleSection(message);
|
||||
if (section === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const section = `${message.role.toUpperCase()}:\n${contents}`;
|
||||
const separator = context.length > 0 ? "\n\n" : "";
|
||||
const available = MAX_THREAD_TITLE_CONTEXT_CHARS - context.length - separator.length;
|
||||
const available = maxChars - context.length - separator.length;
|
||||
if (section.length > available) {
|
||||
if (available > 0) {
|
||||
context = `${section.slice(-available)}${separator}${context}`;
|
||||
@@ -140,9 +161,54 @@ function formatThreadTitleContext(
|
||||
retainedAttachments.unshift(...(message.attachments ?? []));
|
||||
}
|
||||
|
||||
return { context, attachments: retainedAttachments, truncated };
|
||||
}
|
||||
|
||||
function formatThreadTitleContext(messages: ReadonlyArray<ThreadTitleMessage>): {
|
||||
readonly message: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
} {
|
||||
const recent = collectRecentThreadTitleContext(messages, MAX_THREAD_TITLE_CONTEXT_CHARS);
|
||||
if (!recent.truncated) {
|
||||
return {
|
||||
message: recent.context,
|
||||
attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),
|
||||
};
|
||||
}
|
||||
|
||||
const firstUserMessage = messages.find(
|
||||
(message) => message.role === "user" && formatThreadTitleSection(message),
|
||||
);
|
||||
const firstUserSection = firstUserMessage
|
||||
? formatThreadTitleSection(firstUserMessage)
|
||||
: undefined;
|
||||
if (!firstUserMessage || !firstUserSection) {
|
||||
return {
|
||||
message: `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${recent.context}`,
|
||||
attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),
|
||||
};
|
||||
}
|
||||
|
||||
const pinnedSection = limitFirstUserSection(firstUserSection);
|
||||
const recentContextBudget =
|
||||
MAX_THREAD_TITLE_CONTEXT_CHARS -
|
||||
pinnedSection.length -
|
||||
"\n\n".length -
|
||||
THREAD_TITLE_CONTEXT_TRUNCATION_MARKER.length;
|
||||
const retainedRecent = collectRecentThreadTitleContext(messages, recentContextBudget);
|
||||
const pinnedAttachment = firstUserMessage.attachments?.[0];
|
||||
const recentAttachments = retainedRecent.attachments.filter(
|
||||
(attachment) => attachment.id !== pinnedAttachment?.id,
|
||||
);
|
||||
|
||||
return {
|
||||
message: truncated ? `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${context}` : context,
|
||||
attachments: retainedAttachments.slice(-MAX_REGENERATION_ATTACHMENTS),
|
||||
message: `${pinnedSection}\n\n${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${retainedRecent.context}`,
|
||||
attachments: [
|
||||
...(pinnedAttachment ? [pinnedAttachment] : []),
|
||||
...recentAttachments.slice(
|
||||
-(MAX_REGENERATION_ATTACHMENTS - (pinnedAttachment === undefined ? 0 : 1)),
|
||||
),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -899,19 +965,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 +993,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 +1376,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 +1388,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 +1413,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 +1433,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;
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
|
||||
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
|
||||
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
|
||||
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
|
||||
ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -42,6 +44,8 @@ export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
|
||||
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
|
||||
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
|
||||
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
|
||||
export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import {
|
||||
CommandId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
const NOW = "2026-01-01T00:00:00.000Z";
|
||||
const PINNED_AT = "1969-12-30T00:00:00.000Z";
|
||||
|
||||
function makeReadModel(input: {
|
||||
readonly pinnedAt?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
readonly settledOverride?: "settled" | "active" | null;
|
||||
readonly settledAt?: string | null;
|
||||
readonly snoozedUntil?: string | null;
|
||||
readonly snoozedAt?: string | null;
|
||||
}): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: input.archivedAt ?? null,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? (input.settledOverride === "settled" ? NOW : null),
|
||||
snoozedUntil: input.snoozedUntil ?? null,
|
||||
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? PINNED_AT : null),
|
||||
pinnedAt: input.pinnedAt ?? null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
],
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("pinned thread decider", (it) => {
|
||||
it.effect("pins a thread, stamping pinnedAt and updatedAt together", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.pin",
|
||||
commandId: CommandId.make("cmd-pin"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.type).toBe("thread.pinned");
|
||||
if (events[0]?.type === "thread.pinned") {
|
||||
expect(events[0].payload.pinnedAt).toBe(events[0].payload.updatedAt);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-pinning preserves the original pinnedAt and updatedAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.pin",
|
||||
commandId: CommandId.make("cmd-pin-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events[0]?.type).toBe("thread.pinned");
|
||||
if (events[0]?.type === "thread.pinned") {
|
||||
expect(events[0].payload.pinnedAt).toBe(PINNED_AT);
|
||||
expect(events[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unpins a pinned thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unpin",
|
||||
commandId: CommandId.make("cmd-unpin"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events[0]?.type).toBe("thread.unpinned");
|
||||
if (events[0]?.type === "thread.unpinned") {
|
||||
expect(events[0].payload.updatedAt).not.toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unpinning an unpinned thread preserves updatedAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unpin",
|
||||
commandId: CommandId.make("cmd-unpin-noop"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events[0]?.type).toBe("thread.unpinned");
|
||||
if (events[0]?.type === "thread.unpinned") {
|
||||
expect(events[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pinning a settled thread also un-settles it", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.pin",
|
||||
commandId: CommandId.make("cmd-pin-settled"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel({ settledOverride: "settled" }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned", "thread.unsettled"]);
|
||||
const unsettled = events.find((entry) => entry.type === "thread.unsettled");
|
||||
if (unsettled?.type === "thread.unsettled") {
|
||||
expect(unsettled.payload.reason).toBe("user");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pinning a snoozed thread also wakes it", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.pin",
|
||||
commandId: CommandId.make("cmd-pin-snoozed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel({ snoozedUntil: "1970-01-02T09:00:00.000Z" }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned", "thread.unsnoozed"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pinning an unparked thread emits only thread.pinned", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.pin",
|
||||
commandId: CommandId.make("cmd-pin-plain"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settling a pinned thread also unpins it", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-pinned"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events.map((entry) => entry.type)).toEqual(["thread.settled", "thread.unpinned"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settling an unpinned thread emits no unpin event", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-unpinned"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events.map((entry) => entry.type)).toEqual(["thread.settled"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects pinning an archived thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.pin",
|
||||
commandId: CommandId.make("cmd-pin-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel({ archivedAt: NOW }),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -487,14 +487,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
// settledAt: the engine rejects zero-event commands, and bulk-settle /
|
||||
// double-click must stay silent no-ops rather than surface errors.
|
||||
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
|
||||
return {
|
||||
const settledEvent = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.settled",
|
||||
type: "thread.settled" as const,
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
settledAt: alreadySettled ? thread.settledAt : occurredAt,
|
||||
@@ -504,6 +504,29 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
// Settling is "I'm done with this": it clears a pin the same way it
|
||||
// parks the thread. Without this, settling a pinned thread would only
|
||||
// stamp invisible state — the pin would hold the card in place until
|
||||
// a separate unpin.
|
||||
if (thread.pinnedAt == null) {
|
||||
return settledEvent;
|
||||
}
|
||||
return [
|
||||
settledEvent,
|
||||
{
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unpinned" as const,
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "thread.unsettle": {
|
||||
@@ -630,6 +653,98 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.pin": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
// Re-pinning an already-pinned thread is a duplicate (double-click,
|
||||
// raced clients): re-emit with the original timestamps so the
|
||||
// projection is a no-op. Pinning has no lifecycle invariants — a pin
|
||||
// only ever promotes visibility, so it can never hide pending work.
|
||||
const existingPinnedAt = thread.pinnedAt ?? null;
|
||||
const pinnedEvent = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.pinned" as const,
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
pinnedAt: existingPinnedAt ?? occurredAt,
|
||||
updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
// Pinning is a promotion: it clears the parked states rather than
|
||||
// silently outranking them. An explicit settle un-settles (reason
|
||||
// "user", same override the un-settle button stamps), and a snooze's
|
||||
// return ticket is spent — the thread is on top NOW, not on Tuesday.
|
||||
const promotionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
if (thread.settledOverride === "settled") {
|
||||
promotionEvents.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "user",
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (thread.snoozedUntil != null) {
|
||||
promotionEvents.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsnoozed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "user",
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
return promotionEvents.length > 0 ? [pinnedEvent, ...promotionEvents] : pinnedEvent;
|
||||
}
|
||||
|
||||
case "thread.unpin": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Idempotent by re-emission (see thread.settle): unpinning a thread
|
||||
// that is not pinned lands on the same null state without churning
|
||||
// updatedAt.
|
||||
const alreadyUnpinned = thread.pinnedAt == null;
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unpinned",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
updatedAt: alreadyUnpinned ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.meta.update": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
function makeEvent(input: {
|
||||
readonly sequence: number;
|
||||
readonly type: OrchestrationEvent["type"];
|
||||
readonly payload: unknown;
|
||||
}): OrchestrationEvent {
|
||||
return {
|
||||
sequence: input.sequence,
|
||||
eventId: EventId.make(`event-${input.sequence}`),
|
||||
type: input.type,
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
occurredAt: "2026-01-01T00:00:00.000Z",
|
||||
commandId: CommandId.make(`command-${input.sequence}`),
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
payload: input.payload as never,
|
||||
} as OrchestrationEvent;
|
||||
}
|
||||
|
||||
it.effect("projects pin lifecycle events", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const created = yield* projectEvent(
|
||||
createEmptyReadModel(now),
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(created.threads[0]?.pinnedAt ?? null).toBeNull();
|
||||
|
||||
const pinned = yield* projectEvent(
|
||||
created,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.pinned",
|
||||
payload: { threadId: ThreadId.make("thread-1"), pinnedAt: now, updatedAt: now },
|
||||
}),
|
||||
);
|
||||
expect(pinned.threads[0]?.pinnedAt).toBe(now);
|
||||
|
||||
const unpinned = yield* projectEvent(
|
||||
pinned,
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.unpinned",
|
||||
payload: { threadId: ThreadId.make("thread-1"), updatedAt: now },
|
||||
}),
|
||||
);
|
||||
expect(unpinned.threads[0]?.pinnedAt).toBeNull();
|
||||
}),
|
||||
);
|
||||
@@ -23,7 +23,9 @@ import {
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
ThreadPinnedPayload,
|
||||
ThreadSnoozedPayload,
|
||||
ThreadUnpinnedPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadUnsnoozedPayload,
|
||||
@@ -394,6 +396,28 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.pinned":
|
||||
return decodeForEvent(ThreadPinnedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
pinnedAt: payload.pinnedAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.unpinned":
|
||||
return decodeForEvent(ThreadUnpinnedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
pinnedAt: null,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.meta-updated":
|
||||
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
|
||||
Loaded 100 of 297 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user