Compare commits

..
Author SHA1 Message Date
Gabriel De Andrade aadd5f0327 fix(server): tombstone deletion of missing threads
- Make thread deletion idempotent for stale client entries
- Add coverage for emitting a deletion tombstone when the thread is missing
2026-07-30 21:49:09 -04:00
292 changed files with 4354 additions and 16354 deletions

No files matched your search

@@ -52,7 +52,6 @@ jobs:
args:
- --filter=@t3tools/mobile...
- --filter=@t3tools/scripts...
- --filter=t3...
- name: Expose pnpm
run: |
@@ -101,7 +100,6 @@ jobs:
args:
- --filter=@t3tools/mobile...
- --filter=@t3tools/scripts...
- --filter=t3...
- name: Expose pnpm
run: |
+2 -41
View File
@@ -9,7 +9,6 @@ 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";
@@ -18,9 +17,7 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
@@ -223,49 +220,20 @@ 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 (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,
});
if (environment.platform === "linux") {
yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
}
yield* appIdentity.configure;
@@ -277,16 +245,9 @@ 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,7 +64,6 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
}),
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
-1
View File
@@ -35,7 +35,6 @@ 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,7 +39,6 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
return decoded.slice("encrypted:".length);
});
},
selectedStorageBackend: Effect.succeed(Option.none()),
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
@@ -1,121 +0,0 @@
// @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");
});
});
@@ -1,90 +0,0 @@
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,
}),
};
}
+5 -19
View File
@@ -13,7 +13,6 @@ 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 {
@@ -67,8 +66,6 @@ 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;
@@ -150,11 +147,8 @@ 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 baseDir = resolveDesktopBaseDir({
homeDirectory,
joinPath: path.join,
t3Home: config.t3Home,
});
const configuredBaseDir = config.t3Home;
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
const rootDir = path.resolve(input.dirname, "../../..");
const appRoot = input.isPackaged ? input.appPath : rootDir;
const branding = resolveDesktopAppBranding({
@@ -162,18 +156,12 @@ const make = Effect.fn("desktop.environment.make")(function* (
appVersion: input.appVersion,
});
const displayName = branding.displayName;
const stateDir = resolveDesktopStateDir({
const stateDir = path.join(
baseDir,
isDevelopment,
joinPath: path.join,
t3Home: config.t3Home,
});
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
);
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({
@@ -217,8 +205,6 @@ 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,7 +35,6 @@ describe("DesktopLifecycle", () => {
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: (listener) =>
Effect.acquireRelease(
Effect.sync(() => {
@@ -1,229 +0,0 @@
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, []);
});
});
});
@@ -1,191 +0,0 @@
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);
@@ -1,130 +0,0 @@
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);
}),
);
});
@@ -1,74 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads persisted settings synchronously before app services are available.
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
export interface DesktopPreReadyCommandLineReader {
readonly hasSwitch: (switchName: string) => boolean;
readonly getSwitchValue: (switchName: string) => string;
}
export function readCommandLineSwitchValue(
commandLine: DesktopPreReadyCommandLineReader,
switchName: string,
): string | null {
if (!commandLine.hasSwitch(switchName)) {
return null;
}
const value = commandLine.getSwitchValue(switchName).trim();
return value.length > 0 ? value : null;
}
export const resolveEarlyLinuxElectronOptionsFromProcess =
(): DesktopEarlyElectronStartup.EarlyLinuxElectronOptions =>
DesktopEarlyElectronStartup.resolveEarlyLinuxElectronOptions({
env: process.env,
homeDirectory: NodeOS.homedir(),
joinPath: NodePath.posix.join,
readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
});
export class DesktopPreReadyElectronOptions extends Context.Service<
DesktopPreReadyElectronOptions,
{
readonly linux: DesktopEarlyElectronStartup.EarlyLinuxElectronOptions | null;
readonly linuxPasswordStoreCommandLine: string | null;
}
>()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {}
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
const linuxPasswordStoreCommandLine =
platform === "linux"
? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
: null;
const linux = platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess() : null;
if (linux !== null) {
Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass);
if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
}
}
return { linux, linuxPasswordStoreCommandLine };
});
}).pipe(Effect.withSpan("desktop.electron.configureBeforeReady"));
// Keep Electron's strict pre-ready setup isolated so later runtime layers cannot
// observe app readiness before scheme privileges and command-line switches exist.
export const layer = Layer.mergeAll(
ElectronProtocol.layerSchemePrivileges,
Layer.effect(DesktopPreReadyElectronOptions, make),
);
-32
View File
@@ -1,32 +0,0 @@
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,7 +14,6 @@ const {
quitMock,
relaunchMock,
removeListenerMock,
removeSwitchMock,
setAboutPanelOptionsMock,
setAppUserModelIdMock,
setAsDefaultProtocolClientMock,
@@ -35,7 +34,6 @@ const {
quitMock: vi.fn(),
relaunchMock: vi.fn(),
removeListenerMock: vi.fn(),
removeSwitchMock: vi.fn(),
setAboutPanelOptionsMock: vi.fn(),
setAppUserModelIdMock: vi.fn(),
setAsDefaultProtocolClientMock: vi.fn(() => true),
@@ -54,7 +52,6 @@ vi.mock("electron", () => ({
app: {
commandLine: {
appendSwitch: appendSwitchMock,
removeSwitch: removeSwitchMock,
},
dock: {
setIcon: setDockIconMock,
@@ -92,7 +89,6 @@ describe("ElectronApp", () => {
quitMock.mockClear();
relaunchMock.mockClear();
removeListenerMock.mockClear();
removeSwitchMock.mockClear();
setPathMock.mockClear();
});
@@ -182,13 +178,4 @@ describe("ElectronApp", () => {
]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("removes command-line switches through the service", () =>
Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
yield* electronApp.removeCommandLineSwitch("password-store");
assert.deepEqual(removeSwitchMock.mock.calls, [["password-store"]]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
});
-5
View File
@@ -69,7 +69,6 @@ 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,
@@ -192,10 +191,6 @@ export const make = ElectronApp.of({
Electron.autoUpdater.removeListener("before-quit-for-update", listener);
}),
).pipe(Effect.asVoid),
removeCommandLineSwitch: (switchName) =>
Effect.sync(() => {
Electron.app.commandLine.removeSwitch(switchName);
}),
on: addScopedAppListener,
});
@@ -57,7 +57,7 @@ describe("ElectronProtocol", () => {
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
@@ -212,7 +212,6 @@ describe("ElectronProtocol", () => {
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"'wasm-unsafe-eval'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
@@ -71,7 +71,6 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
const scriptSources = [
"'self'",
"'unsafe-inline'",
"'wasm-unsafe-eval'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
];
@@ -105,38 +104,6 @@ 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,11 +1,9 @@
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(),
@@ -62,39 +60,24 @@ 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 = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
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 }),
}),
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();
}
decryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
}),
});
});
export const layer = Layer.effect(ElectronSafeStorage, make);
export const layer = Layer.succeed(ElectronSafeStorage, make);
-203
View File
@@ -1,203 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
normalizeLinuxPasswordStorePreference,
resolveLinuxPasswordStoreSwitch,
resolveLinuxSecretStorageUnavailableMessage,
} from "./linuxSecretStorage.ts";
const autoSwitch = (env: NodeJS.ProcessEnv) =>
resolveLinuxPasswordStoreSwitch({ preference: "auto", env });
describe("linuxSecretStorage", () => {
it("preserves explicit supported password-store preferences", () => {
expect(normalizeLinuxPasswordStorePreference("gnome-libsecret")).toBe("gnome-libsecret");
expect(normalizeLinuxPasswordStorePreference("kwallet")).toBe("kwallet");
expect(normalizeLinuxPasswordStorePreference("kwallet5")).toBe("kwallet5");
expect(normalizeLinuxPasswordStorePreference("kwallet6")).toBe("kwallet6");
});
it("falls back to auto for missing or unsupported preferences", () => {
expect(normalizeLinuxPasswordStorePreference(undefined)).toBe("auto");
expect(normalizeLinuxPasswordStorePreference("basic")).toBe("auto");
});
it("uses explicit preferences instead of the auto heuristic", () => {
for (const preference of ["gnome-libsecret", "kwallet", "kwallet5", "kwallet6"] as const) {
expect(
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "niri" } }),
).toBe(preference);
// An explicit preference also wins where auto would have stayed out of the way.
expect(
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "KDE" } }),
).toBe(preference);
}
});
it("leaves canonical KDE sessions to Electron's own wallet selection", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "5" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE:plasma" })).toBeNull();
});
it("does not force a password-store for desktops Electron already recognizes", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "GNOME" })).toBeNull();
for (const desktop of ["Deepin", "Pantheon", "UKUI", "Unity", "X-Cinnamon", "XFCE"]) {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: desktop })).toBeNull();
}
});
it("recognizes a known desktop later in a colon-separated XDG_CURRENT_DESKTOP list", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:GNOME" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBeNull();
});
it("forces gnome-libsecret for unrecognized Linux desktop sessions", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "Hyprland" })).toBe("gnome-libsecret");
expect(autoSwitch({})).toBe("gnome-libsecret");
});
it("forces gnome-libsecret for desktops Electron recognizes but leaves on basic text", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt" })).toBe("gnome-libsecret");
// Chromium stops at the first recognized value, so a later name cannot rescue the session.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:GNOME" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:KDE" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:plasma" })).toBe("gnome-libsecret");
});
it("does not treat lowercase desktop names as ones Electron recognizes", () => {
// Chromium matches these case-sensitively, so lowercase spellings reach basic text.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "gnome" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "xfce" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "kde", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
});
it("overrides KDE sessions identified only by legacy variables", () => {
// Chromium reaches KWallet4 for some of these, such as DESKTOP_SESSION=kde with a version, and
// basic text for the rest. Either way these are the variables a previous session leaves behind,
// so they are treated as unproven and forced to a real keyring rather than a guessed wallet.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "plasma" })).toBe("gnome-libsecret");
for (const session of [
"kde",
"kde-plasma",
"kde4",
"plasma",
"plasmawayland",
"plasmawayland-dev",
"plasmax11",
"plasmax11-dev",
]) {
expect(autoSwitch({ DESKTOP_SESSION: session })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_SESSION_DESKTOP: session })).toBe("gnome-libsecret");
expect(autoSwitch({ GDMSESSION: session })).toBe("gnome-libsecret");
}
expect(autoSwitch({ DESKTOP_SESSION: "kde", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ KDE_SESSION_VERSION: "6" })).toBe("gnome-libsecret");
expect(autoSwitch({ KDE_FULL_SESSION: "true", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
});
it("ignores stale session hints when XDG_CURRENT_DESKTOP is authoritative", () => {
expect(
autoSwitch({ XDG_CURRENT_DESKTOP: "niri", DESKTOP_SESSION: "gnome", GDMSESSION: "gnome" }),
).toBe("gnome-libsecret");
// A previous KDE session left these behind; the compositor running now is not KDE.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", XDG_SESSION_DESKTOP: "GNOME" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:plasma" })).toBe("gnome-libsecret");
expect(
autoSwitch({
XDG_CURRENT_DESKTOP: "Hyprland",
XDG_SESSION_DESKTOP: "KDE",
KDE_SESSION_VERSION: "6",
}),
).toBe("gnome-libsecret");
});
it("uses GNOME Keyring remediation for libsecret and unknown backends", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "niri" },
}),
).toContain("GNOME Keyring");
});
it("prefers explicit libsecret selection over KDE desktop heuristics", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "gnome-libsecret",
selectedBackend: "unknown",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("GNOME Keyring");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("GNOME Keyring");
});
it("prefers explicit KWallet preference over selected gnome-libsecret backend", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "kwallet6",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "niri" },
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "kwallet",
selectedBackend: "gnome-libsecret",
env: {},
}),
).toContain("KWallet");
});
it("uses KWallet remediation wording for KDE-looking sessions", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "kwallet6",
env: {},
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { DESKTOP_SESSION: "plasmawayland" },
}),
).toContain("KWallet");
// A desktop name outranks a bare KDE marker when choosing the wording.
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { GDMSESSION: "gnome", KDE_FULL_SESSION: "true" },
}),
).toContain("GNOME Keyring");
});
});
-178
View File
@@ -1,178 +0,0 @@
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;
}
+7 -14
View File
@@ -43,14 +43,12 @@ 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";
@@ -183,7 +181,6 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer,
DesktopApplicationMenu.layer,
DesktopLinuxUrlHandler.layer,
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(
@@ -198,20 +195,16 @@ 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) =>
desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))),
desktopApplicationLayer.pipe(
Layer.provideMerge(Layer.succeedContext(clerkContext)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(electronLayer),
),
),
Layer.provideMerge(DesktopPreReadyPlatform.layer),
);
DesktopApp.program.pipe(Effect.provide(desktopRuntimeLayer), NodeRuntime.runMain);
+1 -1
View File
@@ -109,7 +109,7 @@ const DIAGNOSTIC_BUFFER_LIMIT = 200;
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
const AGENT_CURSOR_MOVE_MS = 160;
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const DEFAULT_ANNOTATION_THEME: DesktopPreviewAnnotationTheme = {
colorScheme: "light",
radius: "0.625rem",
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = NodeModule.createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
@@ -11,9 +11,6 @@ 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({
@@ -105,7 +102,6 @@ describe("DesktopSettings", () => {
assert.deepEqual(
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
{
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -125,7 +121,6 @@ describe("DesktopSettings", () => {
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
linuxPasswordStore: "gnome-libsecret",
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
@@ -134,7 +129,6 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "gnome-libsecret",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
@@ -241,7 +235,6 @@ describe("DesktopSettings", () => {
);
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
@@ -275,44 +268,6 @@ 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* () {
@@ -345,7 +300,6 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -373,7 +327,6 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -400,7 +353,6 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -16,16 +16,10 @@ 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;
@@ -73,7 +67,6 @@ 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",
@@ -94,7 +87,6 @@ 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),
@@ -224,7 +216,6 @@ function normalizeDesktopSettingsDocument(
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
return {
linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore),
mainWindowBounds,
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
serverExposureMode:
@@ -247,9 +238,6 @@ function toDesktopSettingsDocument(
): DesktopSettingsDocument {
const document: Mutable<DesktopSettingsDocument> = {};
if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) {
document.linuxPasswordStore = settings.linuxPasswordStore;
}
if (settings.mainWindowBounds !== null) {
document.mainWindowBounds = settings.mainWindowBounds;
}
@@ -86,7 +86,6 @@ function makeSafeStorageLayer(input: {
}
return Effect.succeed(decoded.slice("enc:".length));
},
selectedStorageBackend: Effect.succeed(Option.none()),
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
@@ -1,4 +1,3 @@
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";
@@ -91,7 +90,7 @@ function runShellEnvironment(input: {
}).pipe(
Effect.provide(
DesktopShellEnvironment.layer.pipe(
Layer.provide(Layer.mergeAll(environmentLayer, NodeServices.layer, spawnerLayer)),
Layer.provide(Layer.mergeAll(environmentLayer, spawnerLayer)),
),
),
);
@@ -244,65 +243,6 @@ 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,7 +1,6 @@
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";
@@ -69,19 +68,12 @@ 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;
@@ -100,47 +92,6 @@ 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;
@@ -405,12 +356,7 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<
void,
never,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
> {
const fileSystem = yield* FileSystem.FileSystem;
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
const shellEnvironment: EnvironmentPatch = {};
for (const shell of listLoginShellCandidates(config)) {
@@ -437,54 +383,23 @@ 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 | FileSystem.FileSystem> => {
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
if (config.platform === "win32") {
return installWindowsEnvironment(config);
}
@@ -496,7 +411,6 @@ 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({
@@ -504,7 +418,6 @@ 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,7 +43,6 @@ function makeElectronAppLayer(
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
@@ -28,39 +28,33 @@ const environmentInput = {
runningUnderArm64Translation: false,
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
const makeElectronAppLayer = (quit: Effect.Effect<void> = Effect.void) =>
Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
const makeElectronDialogLayer = (
showMessageBox: ElectronDialog.ElectronDialog["Service"]["showMessageBox"] = () =>
Effect.succeed({ response: 0, checkboxChecked: false }),
) =>
Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
confirm: () => Effect.succeed(false),
showMessageBox,
showErrorBox: () => Effect.void,
} satisfies ElectronDialog.ElectronDialog["Service"]);
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
confirm: () => Effect.succeed(false),
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
showErrorBox: () => Effect.void,
} satisfies ElectronDialog.ElectronDialog["Service"]);
const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
getState: Effect.die("unexpected getState"),
@@ -114,8 +108,8 @@ describe("DesktopApplicationMenu", () => {
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(makeElectronDialogLayer()),
Layer.provideMerge(makeElectronAppLayer()),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
@@ -142,69 +136,4 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
}),
);
it.effect("confirms Cmd+Q before quitting on macOS", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
const promptOptions = yield* Deferred.make<Electron.MessageBoxOptions>();
const quitRequested = yield* Deferred.make<void>();
yield* Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(
makeElectronDialogLayer((options) =>
Deferred.succeed(promptOptions, options).pipe(
Effect.as({ response: 1, checkboxChecked: false }),
),
),
),
Layer.provideMerge(
makeElectronAppLayer(Deferred.succeed(quitRequested, undefined).pipe(Effect.asVoid)),
),
Layer.provideMerge(
DesktopEnvironment.layer({ ...environmentInput, platform: "darwin" }).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
const template = yield* Deferred.await(applicationMenuTemplate);
const appMenu = template.find((item) => item.label === "T3 Code");
assert.isDefined(appMenu);
if (!Array.isArray(appMenu.submenu)) {
throw new Error("Expected application menu submenu to be an array.");
}
const quitItem = appMenu.submenu.find((item) => item.label === "Quit T3 Code");
assert.isDefined(quitItem);
assert.equal(quitItem.accelerator, "CmdOrCtrl+Q");
if (typeof quitItem.click !== "function") {
throw new Error("Expected Quit menu item to have a click handler.");
}
quitItem.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
assert.deepEqual(yield* Deferred.await(promptOptions), {
type: "warning",
title: "Quit T3 Code?",
message: "Quit T3 Code?",
detail: "All running agents will be stopped.",
buttons: ["Cancel", "Quit"],
defaultId: 0,
cancelId: 0,
noLink: true,
});
yield* Deferred.await(quitRequested);
}),
);
});
@@ -96,21 +96,6 @@ const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
yield* checkForUpdatesFromMenu;
}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
const confirmQuit = Effect.gen(function* () {
const electronDialog = yield* ElectronDialog.ElectronDialog;
const result = yield* electronDialog.showMessageBox({
type: "warning",
title: "Quit T3 Code?",
message: "Quit T3 Code?",
detail: "All running agents will be stopped.",
buttons: ["Cancel", "Quit"],
defaultId: 0,
cancelId: 0,
noLink: true,
});
return result.response === 1;
}).pipe(Effect.withSpan("desktop.menu.confirmQuit"));
export const make = Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronMenu = yield* ElectronMenu.ElectronMenu;
@@ -142,30 +127,6 @@ export const make = Effect.gen(function* () {
const settingsClick = () => {
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
};
let quitConfirmationOpen = false;
const quitClick = () => {
if (quitConfirmationOpen) return;
quitConfirmationOpen = true;
runMenuEffect(
"quit",
Effect.gen(function* () {
if (yield* confirmQuit) {
yield* electronApp.quit;
}
}).pipe(
Effect.ensuring(
Effect.sync(() => {
quitConfirmationOpen = false;
}),
),
),
);
};
const quitMenuItem: Electron.MenuItemConstructorOptions = {
label: `Quit ${appName}`,
accelerator: "CmdOrCtrl+Q",
click: quitClick,
};
const template: Electron.MenuItemConstructorOptions[] = [];
if (environment.platform === "darwin") {
@@ -190,7 +151,7 @@ export const make = Effect.gen(function* () {
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
quitMenuItem,
{ role: "quit" },
],
});
}
@@ -209,7 +170,7 @@ export const make = Effect.gen(function* () {
},
{ type: "separator" as const },
]),
environment.platform === "darwin" ? { role: "close" } : quitMenuItem,
{ role: environment.platform === "darwin" ? "close" : "quit" },
],
},
{ role: "editMenu" },
@@ -438,51 +438,6 @@ 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();
+4 -53
View File
@@ -1,4 +1,3 @@
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -26,12 +25,6 @@ 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
@@ -521,18 +514,6 @@ 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);
@@ -556,7 +537,6 @@ 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;
@@ -638,39 +618,10 @@ export const make = Effect.gen(function* () {
},
);
window.webContents.on("render-process-gone", (_event, details) => {
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();
}
void runPromise(
logWindowWarning("main window render process gone", {
reason: details.reason,
exitCode: details.exitCode,
}),
);
});
-18
View File
@@ -181,9 +181,6 @@ const config: ExpoConfig = {
ios: {
icon: variant.assets.iosIcon,
supportsTablet: true,
// Multitasking-capable iPad apps cannot rotate programmatically, so the
// showcase capture build requires full screen (see infoPlist below).
requireFullScreen: process.env.T3_SHOWCASE_CAPTURE_BUILD === "1",
bundleIdentifier: iosBundleIdentifier,
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
// does not fall back to a personal team (which cannot sign app groups,
@@ -200,21 +197,6 @@ const config: ExpoConfig = {
NSLocalNetworkUsageDescription:
"Allow T3 Code to connect to T3 Code servers on your local network or tailnet.",
ITSAppUsesNonExemptEncryption: false,
// The App Store screenshot harness rotates the iPad interface from
// inside the app (CI denies osascript the Accessibility access that
// Simulator menu scripting needs), and iPadOS ignores programmatic
// orientation requests for multitasking-capable apps — so the capture
// build opts out of multitasking and declares landscape support.
...(process.env.T3_SHOWCASE_CAPTURE_BUILD === "1"
? {
"UISupportedInterfaceOrientations~ipad": [
"UIInterfaceOrientationPortrait",
"UIInterfaceOrientationPortraitUpsideDown",
"UIInterfaceOrientationLandscapeLeft",
"UIInterfaceOrientationLandscapeRight",
],
}
: {}),
},
},
android: {
@@ -1,6 +1,5 @@
import ExpoModulesCore
import Security
import UIKit
public final class T3NativeControlsModule: Module {
public func definition() -> ModuleDefinition {
@@ -33,50 +32,6 @@ public final class T3NativeControlsModule: Module {
return arguments[flagIndex + 1]
}
Function("getShowcaseOrientation") { () -> String? in
let arguments = ProcessInfo.processInfo.arguments
guard
let flagIndex = arguments.firstIndex(of: "--showcaseOrientation"),
arguments.indices.contains(flagIndex + 1)
else {
return nil as String?
}
return arguments[flagIndex + 1]
}
// Rotates the interface without Simulator menu UI scripting, which CI
// runners cannot perform (osascript is denied Accessibility access there).
AsyncFunction("applyShowcaseOrientation") { (orientation: String) in
guard #available(iOS 16.0, *) else { return }
let mask: UIInterfaceOrientationMask = orientation == "landscape" ? .landscapeRight : .portrait
for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) { error in
NSLog("T3NativeControls applyShowcaseOrientation(\(orientation)) failed: \(error)")
}
for window in windowScene.windows {
window.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
}
}
}.runOnQueue(.main)
// The geometry request above can fail transiently (for example before the
// scene is foreground-active), so callers poll this until it settles.
// Screen bounds — not the scene's interface orientation — decide the
// answer because they match the captured framebuffer: with iPadOS
// windowing active, a floating landscape window still reports a portrait
// screen, and screenshots would come out portrait.
AsyncFunction("getInterfaceOrientation") { () -> String in
guard
let windowScene = UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene })
.first
else {
return "unknown"
}
let bounds = windowScene.screen.coordinateSpace.bounds
return bounds.width > bounds.height ? "landscape" : "portrait"
}.runOnQueue(.main)
Function("prepareShowcaseCapture") {
for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
+1 -1
View File
@@ -40,7 +40,7 @@ fails, run `xcodebuild -downloadComponent MetalToolchain`.
## Rebuilding libghostty-vt for Android
The checked-in Android shared libraries and headers are pinned to the revision recorded in
`native/libghostty-vt/VERSION` at the repository root. Set `ANDROID_NDK_HOME` and run:
`Vendor/libghostty-vt/VERSION`. Set `ANDROID_NDK_HOME` and run:
```bash
apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
@@ -18,14 +18,13 @@ Ghostty's MIT license applies to the vendored framework. Keep this notice in syn
## Ghostty / libghostty-vt
The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers.
The web terminal vendors a WebAssembly build from the same revision and uses the same C ABI.
- Upstream project: https://github.com/ghostty-org/ghostty
- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
- License: MIT
Ghostty's MIT license applies to the vendored Android and web libraries. Keep this notice and both
artifacts in sync when updating the repository-root `native/libghostty-vt`.
Ghostty's MIT license applies to the vendored Android libraries. Keep this notice in sync when
updating `Vendor/libghostty-vt`.
## MesloLGS NF (Android terminal font)
File renamed without changes.
File renamed without changes.
@@ -13,7 +13,7 @@ add_library(t3terminal SHARED t3_terminal_jni.cpp)
target_include_directories(
t3terminal
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../../../native/libghostty-vt/include"
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../Vendor/libghostty-vt/include"
)
target_link_options(
@@ -4,7 +4,7 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
VENDOR_DIR="${MODULE_DIR}/../../../../native/libghostty-vt"
VENDOR_DIR="${MODULE_DIR}/Vendor/libghostty-vt"
PATCH_DIR="${SCRIPT_DIR}/libghostty-android-patches"
GHOSTTY_REVISION="${GHOSTTY_REVISION:-9f62873bf195e4d8a762d768a1405a5f2f7b1697}"
-2
View File
@@ -22,7 +22,6 @@ import {
IconChevronUp,
IconCircleCheck,
IconCircleXFilled,
IconClock,
IconCopy,
IconDeviceDesktop,
IconDots,
@@ -97,7 +96,6 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
camera: IconCamera,
checkmark: IconCheck,
"checkmark.circle": IconCircleCheck,
clock: IconClock,
"chevron.down": IconChevronDown,
"chevron.left": IconChevronLeft,
"chevron.left.forwardslash.chevron.right": IconCode,
+1 -39
View File
@@ -9,7 +9,6 @@ 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 (
@@ -22,47 +21,10 @@ 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={mono}
fill={isDarkMode ? "#e5e5e5" : "#171717"}
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>
@@ -36,14 +36,8 @@ export function HomeRouteScreen() {
void checkForAppUpdateOnLaunch();
}, []);
const {
archiveThread,
confirmDeleteThread,
settleThread,
snoozeThread,
unsnoozeThread,
unsettleThread,
} = useThreadListActions();
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
useThreadListActions();
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(() => {
@@ -152,8 +146,6 @@ export function HomeRouteScreen() {
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onSettleThread={settleThread}
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
+29 -86
View File
@@ -41,12 +41,7 @@ import {
ThreadListRow,
ThreadListShowMoreRow,
} from "../threads/thread-list-items";
import {
ThreadListV2PendingRow,
ThreadListV2Row,
ThreadListV2SettledShelfHeader,
ThreadListV2SnoozedShelfHeader,
} from "../threads/thread-list-v2-items";
import { ThreadListV2PendingRow, ThreadListV2Row } from "../threads/thread-list-v2-items";
import {
buildThreadListV2Items,
buildThreadListV2ListItems,
@@ -105,11 +100,6 @@ interface HomeScreenProps {
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
/** Resolves true iff the settle was dispatched and succeeded. */
readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onSnoozeThread: (
thread: EnvironmentThreadShell,
snoozedUntil: string,
) => Promise<boolean>;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
@@ -504,18 +494,6 @@ export function HomeScreen(props: HomeScreenProps) {
},
[props.onSettleThread],
);
const handleSnoozeThread = useCallback(
(thread: EnvironmentThreadShell, snoozedUntil: string) => {
void props.onSnoozeThread(thread, snoozedUntil);
},
[props.onSnoozeThread],
);
const handleUnsnoozeThread = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onUnsnoozeThread(thread);
},
[props.onUnsnoozeThread],
);
const handleDeleteThread = props.onDeleteThread;
const handleUnsettleThread = props.onUnsettleThread;
// The settled tail renders in pages; expansion resets when the filter
@@ -533,10 +511,6 @@ export function HomeScreen(props: HomeScreenProps) {
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
[],
);
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
// now is quantized to the minute and ticks so the inactivity auto-settle
// boundary is actually crossed while the app stays open (mirrors web);
// without a clock dependency the partition memoizes a frozen "now".
@@ -577,15 +551,7 @@ export function HomeScreen(props: HomeScreenProps) {
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
items: [],
hiddenSettledCount: 0,
snoozedCount: 0,
snoozedShelfHeaderIndex: null,
settledCount: 0,
settledShelfHeaderIndex: null,
nextSnoozeWakeAt: null,
};
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
// Settled threads are live shells; archived threads keep their original
// "hidden from lists" meaning.
return buildThreadListV2Items({
@@ -600,16 +566,11 @@ export function HomeScreen(props: HomeScreenProps) {
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
snoozedShelfExpanded,
settledShelfExpanded,
selectedThreadKey: null,
});
}, [
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
settledShelfExpanded,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
@@ -659,15 +620,8 @@ export function HomeScreen(props: HomeScreenProps) {
buildThreadListV2ListItems({
items: threadListV2Layout.items,
pendingTasks: v2PendingTasks,
snoozedCount: threadListV2Layout.snoozedCount,
snoozedShelfExpanded,
snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
settledCount: threadListV2Layout.settledCount,
settledShelfExpanded,
settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
snoozeLabelNow: `${nowMinute}:00.000Z`,
}),
[settledShelfExpanded, snoozedShelfExpanded, threadListV2Layout, v2PendingTasks],
[threadListV2Layout.items, v2PendingTasks],
);
const renderV2Item = useCallback(
@@ -694,32 +648,12 @@ export function HomeScreen(props: HomeScreenProps) {
/>
);
}
if (item.type === "v2-snoozed-shelf") {
return (
<ThreadListV2SnoozedShelfHeader
count={item.count}
expanded={item.expanded}
onToggle={toggleSnoozedShelf}
/>
);
}
if (item.type === "v2-settled-shelf") {
return (
<ThreadListV2SettledShelfHeader
count={item.count}
expanded={item.expanded}
onToggle={toggleSettledShelf}
/>
);
}
const thread = item.item.thread;
return (
<ThreadListV2Row
thread={thread}
variant={item.item.variant}
snoozed={item.item.snoozed}
snoozePresetMinute={nowMinute}
snoozeWakeLabelText={item.snoozeWakeLabelText}
showSettledDivider={item.item.showSettledDivider}
project={
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
}
@@ -752,9 +686,6 @@ export function HomeScreen(props: HomeScreenProps) {
onArchiveThread={props.onArchiveThread}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={handleSettleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
onSnoozeThread={handleSnoozeThread}
onUnsnoozeThread={handleUnsnoozeThread}
onUnsettleThread={handleUnsettleThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
@@ -769,8 +700,6 @@ export function HomeScreen(props: HomeScreenProps) {
handleChangeRequestState,
handleDeleteThread,
handleSettleThread,
handleSnoozeThread,
handleUnsnoozeThread,
handleSwipeableClose,
handleSwipeableWillOpen,
handleUnsettleThread,
@@ -783,13 +712,9 @@ export function HomeScreen(props: HomeScreenProps) {
props.savedConnectionsById,
serverConfigs,
settlementEnvironmentIds,
snoozeEnvironmentIds,
threadSearchMatchByKey,
toggleSettledShelf,
toggleSnoozedShelf,
v2ProjectTitleByProjectKey,
props.searchQuery,
nowMinute,
],
);
const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
@@ -805,7 +730,6 @@ export function HomeScreen(props: HomeScreenProps) {
serverConfigs,
savedConnectionsById: props.savedConnectionsById,
searchQuery: props.searchQuery,
snoozePresetMinute: nowMinute,
threadSearchMatchByKey,
}),
[
@@ -814,7 +738,6 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.savedConnectionsById,
serverConfigs,
nowMinute,
threadSearchMatchByKey,
v2ProjectTitleByProjectKey,
],
@@ -1030,11 +953,31 @@ export function HomeScreen(props: HomeScreenProps) {
) : null;
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
// v2 project scope, so it can be null (results elsewhere) while this list
// is empty. Snoozed threads need no special empty state: their shelf header
// is a list row even while collapsed.
// is empty. Search outranks the scope — "No results" names the actionable
// fact when a query is active. Snoozed threads outrank the rest: "No
// threads yet" over an inbox that is merely all-snoozed reads as data
// loss.
const v2SnoozedCount = threadListV2Layout.snoozedCount;
const v2ListEmpty =
hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
hasSearchQuery && threadSearch.isPending && v2SnoozedCount === 0 ? null : hasSearchQuery ? (
v2SnoozedCount > 0 ? (
// The snoozed threads already passed this search filter: "No
// results" would claim nothing matched when matches are merely
// parked.
<EmptyState
title={
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
}
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
/>
) : (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
)
) : v2SnoozedCount > 0 ? (
<EmptyState
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
detail="Snoozed threads return when their wake time passes."
/>
) : v2ScopedProjectGroup !== null ? (
<EmptyState
title={`No threads in ${v2ScopedProjectGroup.title}`}
@@ -1055,7 +998,7 @@ export function HomeScreen(props: HomeScreenProps) {
extraData={v2ExtraData}
ListHeaderComponent={v2ListHeader}
ListFooterComponent={
settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
threadListV2Layout.hiddenSettledCount > 0 ? (
<Pressable
accessibilityRole="button"
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
@@ -1,6 +1,4 @@
import { SymbolView } from "../../components/AppSymbol";
import { ControlPillMenu } from "../../components/ControlPill";
import type { MenuAction } from "@react-native-menu/menu";
import * as Haptics from "expo-haptics";
import {
createContext,
@@ -49,67 +47,13 @@ export const THREAD_SWIPE_SPRING = {
stiffness: 330,
};
interface ThreadSwipeAction {
interface ThreadSwipePrimaryAction {
readonly accessibilityLabel: string;
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly menu?: {
readonly actions: MenuAction[];
readonly onPressAction: NonNullable<ComponentProps<typeof ControlPillMenu>["onPressAction"]>;
readonly title?: string;
};
readonly onPress: () => void;
}
interface ThreadSwipeSecondaryAction extends ThreadSwipeAction {
readonly backgroundColor: string;
}
function swipeActionsWidth(hasSecondaryAction: boolean) {
return hasSecondaryAction ? THREAD_SWIPE_ACTIONS_WIDTH : ACTION_ITEM_WIDTH;
}
/** `undefined` keeps the v1 Delete default; `null` means one action only. */
function resolveSecondaryAction(input: {
readonly close: () => void;
readonly onDelete: () => void;
readonly secondaryAction: ThreadSwipeAction | null | undefined;
readonly threadTitle: string;
}): ThreadSwipeSecondaryAction | null {
if (input.secondaryAction === null) return null;
if (input.secondaryAction === undefined) {
return {
accessibilityLabel: `Delete ${input.threadTitle}`,
backgroundColor: "#ff2d55",
icon: "trash",
label: "Delete",
onPress: () => {
input.close();
input.onDelete();
},
};
}
const action = input.secondaryAction;
return {
...action,
backgroundColor: "#5856d6",
menu:
action.menu === undefined
? undefined
: {
...action.menu,
onPressAction: (event) => {
input.close();
action.menu?.onPressAction(event);
},
},
onPress: () => {
input.close();
action.onPress();
},
};
}
/**
* Delivers the scroll gate to swipeables via context so that flipping it does
* NOT re-render whole rows: putting the flag in list extraData/renderItem deps
@@ -229,22 +173,17 @@ export function ThreadSwipeable(props: {
readonly enabled?: boolean;
readonly enableTrackpadSwipe?: boolean;
/**
* What a full swipe commits. Omitted keeps the v1 Delete behavior only when
* the built-in Delete secondary action is in use; custom or absent
* secondary actions default to the advertised primary action.
* What a full swipe commits: "delete" (default, v1 behavior — the Delete
* button stretches) or "primary" — the advertised primary action fires and
* its button stretches instead. A full swipe must always match the action
* the stretching button advertises.
*/
readonly fullSwipeAction?: "delete" | "primary";
readonly fullSwipeWidth: number;
readonly onDelete: () => void;
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void;
readonly primaryAction: ThreadSwipeAction;
/**
* Omitted keeps the v1 destructive Delete action. Explicit null opts out of
* a secondary action entirely so a gated Snooze can never fall back to an
* unadvertised Delete.
*/
readonly secondaryAction?: ThreadSwipeAction | null;
readonly primaryAction: ThreadSwipePrimaryAction;
/**
* Identity of the content being wrapped. When a recycled list reuses this
* component for a different item, the swipeable snaps back to closed so an
@@ -258,11 +197,7 @@ export function ThreadSwipeable(props: {
}) {
const swipeableRef = useRef<SwipeableMethods | null>(null);
const fullSwipeArmedRef = useRef(false);
const hasSecondaryAction = props.secondaryAction !== null;
const actionsWidth = swipeActionsWidth(hasSecondaryAction);
const fullSwipeThreshold = Math.max(actionsWidth + 44, props.fullSwipeWidth * 0.58);
const fullSwipeAction =
props.fullSwipeAction ?? (props.secondaryAction === undefined ? "delete" : "primary");
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, props.fullSwipeWidth * 0.58);
const close = useCallback(() => swipeableRef.current?.close(), []);
const gateEnabled = use(SwipeableScrollGateContext);
const resetKey = props.resetKey;
@@ -316,7 +251,7 @@ export function ThreadSwipeable(props: {
if (fullSwipeArmedRef.current) {
fullSwipeArmedRef.current = false;
methods.close();
if (fullSwipeAction === "primary") {
if (props.fullSwipeAction === "primary") {
props.primaryAction.onPress();
} else {
props.onDelete();
@@ -329,8 +264,9 @@ export function ThreadSwipeable(props: {
<ThreadSwipeActions
backgroundColor={props.backgroundColor}
compact={props.compactActions === true}
fullSwipeAction={fullSwipeAction}
fullSwipeAction={props.fullSwipeAction ?? "delete"}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
primaryAction={{
...props.primaryAction,
@@ -339,16 +275,12 @@ export function ThreadSwipeable(props: {
props.primaryAction.onPress();
},
}}
secondaryAction={resolveSecondaryAction({
close: () => methods.close(),
onDelete: props.onDelete,
secondaryAction: props.secondaryAction,
threadTitle: props.threadTitle,
})}
swipeableMethods={methods}
threadTitle={props.threadTitle}
translation={translation}
/>
)}
rightThreshold={actionsWidth * 0.42}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
simultaneousWithExternalGesture={props.simultaneousWithExternalGesture}
>
{props.children(close)}
@@ -358,14 +290,12 @@ export function ThreadSwipeable(props: {
function SwipeActionButton(props: {
readonly accessibilityLabel: string;
readonly actionsWidth: number;
readonly backgroundColor: string;
readonly compact: boolean;
readonly entryRange: readonly [number, number];
readonly fullSwipeThreshold: number;
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly menu?: ThreadSwipeAction["menu"];
readonly onPress: () => void;
readonly stretchesOnFullSwipe: boolean;
readonly translation: SharedValue<number>;
@@ -375,10 +305,10 @@ function SwipeActionButton(props: {
const actionStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
const stretch = Math.max(reveal - props.actionsWidth, 0);
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
const fullSwipeProgress = interpolate(
reveal,
[props.actionsWidth, props.fullSwipeThreshold + 20],
[THREAD_SWIPE_ACTIONS_WIDTH, props.fullSwipeThreshold + 20],
[0, 1],
Extrapolation.CLAMP,
);
@@ -397,7 +327,9 @@ function SwipeActionButton(props: {
});
const circleStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const stretch = props.stretchesOnFullSwipe ? Math.max(reveal - props.actionsWidth, 0) : 0;
const stretch = props.stretchesOnFullSwipe
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
: 0;
return {
transform: [{ translateX: -stretch }],
@@ -406,7 +338,9 @@ function SwipeActionButton(props: {
});
const iconStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const stretch = props.stretchesOnFullSwipe ? Math.max(reveal - props.actionsWidth, 0) : 0;
const stretch = props.stretchesOnFullSwipe
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
: 0;
const armedProgress = interpolate(
reveal,
[props.fullSwipeThreshold, props.fullSwipeThreshold + 20],
@@ -424,7 +358,7 @@ function SwipeActionButton(props: {
}
const reveal = Math.max(-props.translation.value, 0);
const stretch = Math.max(reveal - props.actionsWidth, 0);
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
return {
opacity: interpolate(
reveal,
@@ -436,63 +370,6 @@ function SwipeActionButton(props: {
};
});
const button = (
<Pressable
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
onPress={props.menu === undefined ? props.onPress : undefined}
style={({ pressed }) => ({
alignItems: "center",
height: "100%",
justifyContent: "center",
opacity: pressed ? 0.72 : 1,
width: "100%",
})}
>
<View style={{ height: circleSize, width: circleSize }}>
<Animated.View
style={[
{
backgroundColor: props.backgroundColor,
borderRadius: 999,
height: circleSize,
left: 0,
position: "absolute",
top: 0,
},
circleStyle,
]}
/>
<Animated.View
style={[
{
alignItems: "center",
height: circleSize,
justifyContent: "center",
left: 0,
position: "absolute",
top: 0,
width: circleSize,
},
iconStyle,
]}
>
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
</Animated.View>
</View>
<Animated.View
style={[
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
labelStyle,
]}
>
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
{props.label}
</Text>
</Animated.View>
</Pressable>
);
return (
<Animated.View
style={[
@@ -506,18 +383,60 @@ function SwipeActionButton(props: {
actionStyle,
]}
>
{props.menu === undefined ? (
button
) : (
<ControlPillMenu
actions={props.menu.actions}
onPressAction={props.menu.onPressAction}
title={props.menu.title}
style={{ height: "100%", width: "100%" }}
<Pressable
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
onPress={props.onPress}
style={({ pressed }) => ({
alignItems: "center",
height: "100%",
justifyContent: "center",
opacity: pressed ? 0.72 : 1,
width: "100%",
})}
>
<View style={{ height: circleSize, width: circleSize }}>
<Animated.View
style={[
{
backgroundColor: props.backgroundColor,
borderRadius: 999,
height: circleSize,
left: 0,
position: "absolute",
top: 0,
},
circleStyle,
]}
/>
<Animated.View
style={[
{
alignItems: "center",
height: circleSize,
justifyContent: "center",
left: 0,
position: "absolute",
top: 0,
width: circleSize,
},
iconStyle,
]}
>
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
</Animated.View>
</View>
<Animated.View
style={[
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
labelStyle,
]}
>
{button}
</ControlPillMenu>
)}
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
{props.label}
</Text>
</Animated.View>
</Pressable>
</Animated.View>
);
}
@@ -527,14 +446,14 @@ export function ThreadSwipeActions(props: {
readonly compact: boolean;
readonly fullSwipeAction?: "delete" | "primary";
readonly fullSwipeThreshold: number;
readonly onDelete: () => void;
readonly onFullSwipeArmedChange: (armed: boolean) => void;
readonly primaryAction: ThreadSwipeAction;
readonly secondaryAction: ThreadSwipeSecondaryAction | null;
readonly primaryAction: ThreadSwipePrimaryAction;
readonly swipeableMethods: SwipeableMethods;
readonly threadTitle: string;
readonly translation: SharedValue<number>;
}) {
const secondaryAction = props.secondaryAction;
const fullSwipeIsPrimary = props.fullSwipeAction === "primary" || secondaryAction === null;
const actionsWidth = swipeActionsWidth(secondaryAction !== null);
const fullSwipeIsPrimary = props.fullSwipeAction === "primary";
useAnimatedReaction(
() => -props.translation.value >= props.fullSwipeThreshold,
(armed, previous) => {
@@ -551,19 +470,14 @@ export function ThreadSwipeActions(props: {
backgroundColor: props.backgroundColor,
flexDirection: "row",
height: "100%",
width: actionsWidth,
width: THREAD_SWIPE_ACTIONS_WIDTH,
}}
>
<SwipeActionButton
accessibilityLabel={props.primaryAction.accessibilityLabel}
actionsWidth={actionsWidth}
backgroundColor="#007aff"
compact={props.compact}
entryRange={
secondaryAction === null
? [8, ACTION_ITEM_WIDTH * 0.72]
: [ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]
}
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
fullSwipeThreshold={props.fullSwipeThreshold}
icon={props.primaryAction.icon}
label={props.primaryAction.label}
@@ -571,22 +485,21 @@ export function ThreadSwipeActions(props: {
stretchesOnFullSwipe={fullSwipeIsPrimary}
translation={props.translation}
/>
{secondaryAction === null ? null : (
<SwipeActionButton
accessibilityLabel={secondaryAction.accessibilityLabel}
actionsWidth={actionsWidth}
backgroundColor={secondaryAction.backgroundColor}
compact={props.compact}
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
fullSwipeThreshold={props.fullSwipeThreshold}
icon={secondaryAction.icon}
label={secondaryAction.label}
menu={secondaryAction.menu}
onPress={secondaryAction.onPress}
stretchesOnFullSwipe={!fullSwipeIsPrimary}
translation={props.translation}
/>
)}
<SwipeActionButton
accessibilityLabel={`Delete ${props.threadTitle}`}
backgroundColor="#ff2d55"
compact={props.compact}
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
fullSwipeThreshold={props.fullSwipeThreshold}
icon="trash"
label="Delete"
onPress={() => {
props.swipeableMethods.close();
props.onDelete();
}}
stretchesOnFullSwipe={!fullSwipeIsPrimary}
translation={props.translation}
/>
</View>
);
}
@@ -1,5 +1,5 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled";
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
import * as Cause from "effect/Cause";
import * as Haptics from "expo-haptics";
import { useCallback, useRef } from "react";
@@ -22,13 +22,6 @@ function environmentSupportsSettlement(environmentId: EnvironmentThreadShell["en
);
}
function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["environmentId"]) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadSnooze === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -199,14 +192,9 @@ export function useThreadListActions(): {
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
const snoozeInFlightThreadKeys = useRef(new Set<string>());
const archiveThread = useCallback(
(thread: EnvironmentThreadShell) => {
@@ -218,94 +206,6 @@ export function useThreadListActions(): {
async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,
[executeAction],
);
const snoozeThread = useCallback(
async (thread: EnvironmentThreadShell, snoozedUntil: string) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (snoozeInFlightThreadKeys.current.has(key)) {
return false;
}
snoozeInFlightThreadKeys.current.add(key);
try {
if (!environmentSupportsSnooze(thread.environmentId)) {
Alert.alert(
"Could not snooze thread",
"This environment's server does not support snoozing yet. Update the server to use Snooze.",
);
return false;
}
if (!canSnooze(thread, { now: new Date().toISOString() })) {
Alert.alert(
"Could not snooze thread",
thread.hasPendingApprovals || thread.hasPendingUserInput
? "This thread is waiting on you. Respond to the pending request before snoozing it."
: "This thread is still starting a turn. Try again once it's running.",
);
return false;
}
selectionHaptic();
const result = await snoozeMutation({
environmentId: thread.environmentId,
input: {
threadId: thread.id,
snoozedUntil,
},
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not snooze thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread could not be snoozed.",
);
return false;
}
return true;
} finally {
snoozeInFlightThreadKeys.current.delete(key);
}
},
[snoozeMutation],
);
const unsnoozeThread = useCallback(
async (thread: EnvironmentThreadShell) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (snoozeInFlightThreadKeys.current.has(key)) {
return false;
}
snoozeInFlightThreadKeys.current.add(key);
try {
if (!environmentSupportsSnooze(thread.environmentId)) {
Alert.alert(
"Could not wake thread",
"This environment's server does not support snoozing yet. Update the server to wake this thread.",
);
return false;
}
selectionHaptic();
const result = await unsnoozeMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id, reason: "user" },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not wake thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread could not be woken.",
);
return false;
}
return true;
} finally {
snoozeInFlightThreadKeys.current.delete(key);
}
},
[unsnoozeMutation],
);
const unsettleThread = useCallback(
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
[executeAction],
@@ -313,14 +213,7 @@ export function useThreadListActions(): {
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
return {
archiveThread,
confirmDeleteThread,
settleThread,
snoozeThread,
unsnoozeThread,
unsettleThread,
};
return { archiveThread, confirmDeleteThread, settleThread, unsettleThread };
}
export function useArchivedThreadListActions(
@@ -9,8 +9,6 @@ import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
import { holdEditingQueuedMessage } from "../../state/use-thread-outbox";
import { useWorkspaceState } from "../../state/workspace";
import {
applyNativeShowcaseOrientation,
getNativeShowcaseOrientation,
getNativeShowcasePairingUrls,
getNativeShowcaseScene,
markNativeShowcaseReady,
@@ -49,7 +47,6 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
const [pendingTasksReady, setPendingTasksReady] = useState(false);
const [requestedScene, setRequestedScene] = useState<ShowcaseScene | null>(null);
const [readyScene, setReadyScene] = useState<ShowcaseScene | null>(null);
const [orientationSettled, setOrientationSettled] = useState(false);
useEffect(() => {
if (!SHOWCASE_ENABLED || pairingUrls.length > 0) return;
@@ -63,25 +60,6 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
return () => clearInterval(interval);
}, [pairingUrls.length]);
useEffect(() => {
if (!SHOWCASE_ENABLED || orientationSettled) return;
const orientation = getNativeShowcaseOrientation();
if (orientation === null) {
setOrientationSettled(true);
return;
}
let cancelled = false;
void retryShowcaseOperation(async () => applyNativeShowcaseOrientation(orientation), {
isCancelled: () => cancelled,
}).then((applied) => {
if (!cancelled && applied) setOrientationSettled(true);
});
return () => {
cancelled = true;
};
}, [orientationSettled]);
useEffect(() => {
if (!SHOWCASE_ENABLED) return;
@@ -204,10 +182,7 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
scene === null ||
requestedScene === null ||
scene !== requestedScene ||
!hasFixture ||
// Never report a scene ready while the capture orientation is still
// being applied — a screenshot taken early has the wrong dimensions.
!orientationSettled
!hasFixture
) {
setReadyScene(null);
return;
@@ -235,7 +210,7 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
if (renderFrame !== null) cancelAnimationFrame(renderFrame);
if (readyFrame !== null) cancelAnimationFrame(readyFrame);
};
}, [hasFixture, orientationSettled, requestedScene, scene]);
}, [hasFixture, requestedScene, scene]);
if (!SHOWCASE_ENABLED || readyScene === null) return null;
@@ -3,14 +3,9 @@ import { requireOptionalNativeModule } from "expo";
export const SHOWCASE_SCENES = ["threads", "thread", "terminal", "review", "environments"] as const;
export type ShowcaseScene = (typeof SHOWCASE_SCENES)[number];
export type ShowcaseOrientation = "portrait" | "landscape";
interface NativeShowcaseControls {
readonly getShowcasePairingUrl?: () => string | null;
readonly getShowcaseScene?: () => string | null;
readonly getShowcaseOrientation?: () => string | null;
readonly applyShowcaseOrientation?: (orientation: ShowcaseOrientation) => Promise<void>;
readonly getInterfaceOrientation?: () => Promise<string>;
readonly prepareShowcaseCapture?: () => void;
readonly markShowcaseReady?: (scene: ShowcaseScene) => void;
}
@@ -64,35 +59,6 @@ export function prepareNativeShowcaseCapture(): void {
}
}
export function getNativeShowcaseOrientation(): ShowcaseOrientation | null {
try {
const orientation = nativeShowcaseControls()?.getShowcaseOrientation?.()?.trim();
return orientation === "portrait" || orientation === "landscape" ? orientation : null;
} catch {
return null;
}
}
export async function applyNativeShowcaseOrientation(
orientation: ShowcaseOrientation,
): Promise<boolean> {
const controls = nativeShowcaseControls();
if (!controls?.applyShowcaseOrientation || !controls.getInterfaceOrientation) {
// A development build that predates this helper keeps its default
// orientation; report success so callers do not retry forever.
return true;
}
try {
await controls.applyShowcaseOrientation(orientation);
// The geometry request settles asynchronously; confirm it took effect so
// callers can retry attempts made before the scene was foreground-active.
await new Promise((resolve) => setTimeout(resolve, 500));
return (await controls.getInterfaceOrientation()) === orientation;
} catch {
return false;
}
}
export function markNativeShowcaseReady(scene: ShowcaseScene): void {
try {
nativeShowcaseControls()?.markShowcaseReady?.(scene);
@@ -42,8 +42,7 @@ import {
restoreComposerDraftSnapshot,
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
import { useProjects } from "../../state/entities";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
@@ -91,9 +90,6 @@ export function NewTaskDraftScreen(props: {
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
const { connectedEnvironments } = useRemoteConnectionStatus();
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
);
const environmentConnected =
selectedProject !== null &&
connectedEnvironments.find(
@@ -543,7 +539,27 @@ export function NewTaskDraftScreen(props: {
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(flow.providerGroups, flow.selectedModel),
() =>
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,
})),
})),
[flow.providerGroups, flow.selectedModel],
);
const providerOptionDescriptors = useMemo(
@@ -779,14 +795,7 @@ export function NewTaskDraftScreen(props: {
return;
}
const draft = getComposerDraftSnapshot(draftKey);
// Snapshot read keeps just-typed selector state; the availability gate
// still applies so a stored selection on a disabled provider falls back
// to the flow's resolved model.
const modelSelection =
resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
draft.modelSelection ?? null,
) ?? flow.selectedModel;
const modelSelection = draft.modelSelection ?? flow.selectedModel;
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
const selectedWorktreePath =
@@ -838,10 +847,7 @@ export function NewTaskDraftScreen(props: {
if (editingPendingTask) {
flow.finishEditingPendingTask();
} else {
// Drop the workspace selection with the content: the next task should
// re-resolve mode/branch/origin from the server's configured defaults
// instead of resurrecting this task's picks.
clearComposerDraftContent(draftKey, { clearWorkspaceSelection: true });
clearComposerDraftContent(draftKey);
}
navigation.getParent()?.goBack();
return;
@@ -899,7 +905,7 @@ export function NewTaskDraftScreen(props: {
}
flow.finishEditingPendingTask();
} else {
clearComposerDraftContent(draftKey, { clearWorkspaceSelection: true });
clearComposerDraftContent(draftKey);
}
navigation.dispatch(
StackActions.replace("Thread", {
@@ -53,7 +53,7 @@ import {
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import type { RemoteClientConnectionState } from "../../lib/connection";
import {
@@ -606,7 +606,25 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
[providerOptionDescriptors],
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(providerGroups, currentModelSelection),
() =>
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,
})),
})),
[providerGroups, currentModelSelection],
);
@@ -67,12 +67,7 @@ import {
ThreadListRow,
ThreadListShowMoreRow,
} from "./thread-list-items";
import {
ThreadListV2PendingRow,
ThreadListV2Row,
ThreadListV2SettledShelfHeader,
ThreadListV2SnoozedShelfHeader,
} from "./thread-list-v2-items";
import { ThreadListV2PendingRow, ThreadListV2Row } from "./thread-list-v2-items";
import {
buildThreadListV2Items,
buildThreadListV2ListItems,
@@ -198,14 +193,8 @@ function ThreadNavigationSidebarPane(
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const headerIsOverContentRef = useRef(false);
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
const {
archiveThread,
confirmDeleteThread,
settleThread,
snoozeThread,
unsnoozeThread,
unsettleThread,
} = useThreadListActions();
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
@@ -439,10 +428,6 @@ function ThreadNavigationSidebarPane(
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
[],
);
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
// now ticks per minute so the inactivity auto-settle boundary is actually
// crossed while the pane stays open; without a clock dependency the
// partition memoizes a frozen "now".
@@ -483,15 +468,7 @@ function ThreadNavigationSidebarPane(
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
items: [],
hiddenSettledCount: 0,
snoozedCount: 0,
snoozedShelfHeaderIndex: null,
settledCount: 0,
settledShelfHeaderIndex: null,
nextSnoozeWakeAt: null,
};
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
return buildThreadListV2Items({
threads: threads.filter((thread) => thread.archivedAt === null),
environmentId: options.selectedEnvironmentId,
@@ -504,17 +481,11 @@ function ThreadNavigationSidebarPane(
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
snoozedShelfExpanded,
settledShelfExpanded,
selectedThreadKey: props.selectedThreadKey ?? null,
});
}, [
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
settledShelfExpanded,
props.selectedThreadKey,
options.selectedEnvironmentId,
props.searchQuery,
matchedThreadKeys,
@@ -561,15 +532,8 @@ function ThreadNavigationSidebarPane(
const items: SidebarListItem[] = buildThreadListV2ListItems({
items: threadListV2Layout.items,
pendingTasks: v2PendingTasks,
snoozedCount: threadListV2Layout.snoozedCount,
snoozedShelfExpanded,
snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
settledCount: threadListV2Layout.settledCount,
settledShelfExpanded,
settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
snoozeLabelNow: `${nowMinute}:00.000Z`,
});
if (settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0) {
if (threadListV2Layout.hiddenSettledCount > 0) {
items.push({
type: "v2-show-more",
key: "v2-show-more",
@@ -579,13 +543,10 @@ function ThreadNavigationSidebarPane(
return items;
}, [
listLayout.items,
nowMinute,
options.selectedEnvironmentId,
pendingTasks,
props.searchQuery,
selectedProjectRefs,
settledShelfExpanded,
snoozedShelfExpanded,
threadListV2Enabled,
threadListV2Layout,
]);
@@ -770,7 +731,6 @@ function ThreadNavigationSidebarPane(
projectTitleByProjectKey,
savedConnectionsById,
serverConfigs,
snoozePresetMinute: nowMinute,
threadSearchMatchByKey,
}),
[
@@ -780,7 +740,6 @@ function ThreadNavigationSidebarPane(
projectTitleByProjectKey,
savedConnectionsById,
serverConfigs,
nowMinute,
threadSearchMatchByKey,
],
);
@@ -791,8 +750,7 @@ function ThreadNavigationSidebarPane(
previous.key === item.key &&
previous.item.thread === item.item.thread &&
previous.item.variant === item.item.variant &&
previous.item.snoozed === item.item.snoozed &&
previous.snoozeWakeLabelText === item.snoozeWakeLabelText
previous.item.showSettledDivider === item.item.showSettledDivider
);
}
if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
@@ -804,23 +762,13 @@ function ThreadNavigationSidebarPane(
previous.showPendingDivider === item.showPendingDivider
);
}
if (previous.type === "v2-snoozed-shelf" && item.type === "v2-snoozed-shelf") {
return previous.count === item.count && previous.expanded === item.expanded;
}
if (previous.type === "v2-settled-shelf" && item.type === "v2-settled-shelf") {
return previous.count === item.count && previous.expanded === item.expanded;
}
if (
previous.type === "v2-thread" ||
previous.type === "v2-show-more" ||
previous.type === "v2-pending" ||
previous.type === "v2-snoozed-shelf" ||
previous.type === "v2-settled-shelf" ||
item.type === "v2-thread" ||
item.type === "v2-show-more" ||
item.type === "v2-pending" ||
item.type === "v2-snoozed-shelf" ||
item.type === "v2-settled-shelf"
item.type === "v2-pending"
) {
return false;
}
@@ -878,9 +826,7 @@ function ThreadNavigationSidebarPane(
<ThreadListV2Row
thread={thread}
variant={item.item.variant}
snoozed={item.item.snoozed}
snoozePresetMinute={nowMinute}
snoozeWakeLabelText={item.snoozeWakeLabelText}
showSettledDivider={item.item.showSettledDivider}
project={projectByKey.get(scopeKey) ?? null}
projectTitle={projectTitleByProjectKey.get(scopeKey)}
providerDriver={
@@ -914,9 +860,6 @@ function ThreadNavigationSidebarPane(
onArchiveThread={archiveThread}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={settleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
@@ -926,24 +869,6 @@ function ThreadNavigationSidebarPane(
/>
);
}
case "v2-snoozed-shelf":
return (
<ThreadListV2SnoozedShelfHeader
count={item.count}
expanded={item.expanded}
onToggle={toggleSnoozedShelf}
pane="sidebar"
/>
);
case "v2-settled-shelf":
return (
<ThreadListV2SettledShelfHeader
count={item.count}
expanded={item.expanded}
onToggle={toggleSettledShelf}
pane="sidebar"
/>
);
case "v2-show-more":
return (
<Pressable
@@ -1059,13 +984,7 @@ function ThreadNavigationSidebarPane(
settlementEnvironmentIds,
showMoreSettled,
sidebarScrollGesture,
snoozeEnvironmentIds,
snoozeThread,
nowMinute,
toggleSettledShelf,
toggleSnoozedShelf,
unsettleThread,
unsnoozeThread,
updateGroupDisplay,
],
);
@@ -1112,19 +1031,30 @@ function ThreadNavigationSidebarPane(
}),
[filterIcon, filterMenu, props.onOpenSettings],
);
// Snoozed threads need no special case: the shelf header is a list row
// even while collapsed.
// "No threads yet" over an inbox that is merely all-snoozed reads as
// data loss; name the snoozed threads instead.
const snoozedCount = threadListV2Layout.snoozedCount;
const listEmpty = (
<Text className="px-2 py-4 text-sm text-foreground-muted">
{catalogState.isLoadingConnections
? "Loading threads…"
: props.searchQuery.trim().length > 0
? threadSearch.isPending
? threadSearch.isPending && snoozedCount === 0
? "Searching thread messages…"
: "No matching threads"
: selectedProjectScope !== null
? `No threads in ${selectedProjectScope.title}`
: "No threads yet"}
: snoozedCount > 0
? // Snoozed matches passed this same search filter — "No
// matching threads" would misreport them as nonexistent.
snoozedCount === 1
? "1 matching thread snoozed"
: "All matching threads snoozed"
: "No matching threads"
: snoozedCount > 0
? snoozedCount === 1
? "1 thread snoozed"
: `${snoozedCount} threads snoozed`
: selectedProjectScope !== null
? `No threads in ${selectedProjectScope.title}`
: "No threads yet"}
</Text>
);
@@ -22,11 +22,7 @@ import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../
import type { TurnCommandMetadata } from "../../lib/commandMetadata";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import {
buildModelOptions,
groupByProvider,
resolveSelectableModelSelection,
} from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { appAtomRegistry } from "../../state/atom-registry";
@@ -351,11 +347,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
const prompt = selectedProjectDraft.text;
const attachments = selectedProjectDraft.attachments;
// The server's configured default decides the mode until the user picks one
// explicitly — same resolution web uses for new draft threads.
const defaultWorkspaceMode: WorkspaceMode =
selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local";
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode;
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
// Keep the user's explicit choice separate from the resolved display value:
@@ -369,29 +361,22 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
// Stored selections (draft and project default) only count while their
// provider is usable on the server; otherwise the server's default model
// wins instead of silently targeting a disabled provider.
const draftModelSelection = resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
selectedProjectDraft.modelSelection ?? null,
);
const projectDefaultModelSelection = resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection ?? null,
);
const modelOptions = useMemo(
() =>
buildModelOptions(
selectedEnvironmentServerConfig,
draftModelSelection ?? projectDefaultModelSelection,
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
),
[selectedEnvironmentServerConfig, draftModelSelection, projectDefaultModelSelection],
[
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection,
selectedProjectDraft.modelSelection,
],
);
const selectedModel =
draftModelSelection ??
projectDefaultModelSelection ??
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
modelOptions.find((option) => option.isDefault)?.selection ??
modelOptions[0]?.selection ??
null;
@@ -690,20 +675,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}
const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
const text = draft.text.trim();
// Same availability gate the composer display applies: a stored
// selection targeting a disabled provider must not ride into the queue.
const draftModelSelection =
resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
draft.modelSelection ?? null,
) ?? selectedModel;
const draftModelSelection = draft.modelSelection ?? selectedModel;
if (text.length === 0 || !draftModelSelection) {
return null;
}
const workspaceSelection = draft.workspaceSelection;
// Fall back to the resolved mode (server default) so queued tasks drain
// with the same mode the composer displayed.
const mode = workspaceSelection?.mode ?? workspaceMode;
const mode = workspaceSelection?.mode ?? "local";
// When the selection is the stand-in built from the queued snapshot,
// persist the original (possibly absent) snapshot values — the
// stand-in's placeholder title/workspaceRoot must never be written back
@@ -745,12 +722,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[
editingPendingProject,
editingPendingTask,
selectedEnvironmentServerConfig,
selectedModel,
selectedProject,
selectedProjectDraftKey,
startFromOrigin,
workspaceMode,
],
);
@@ -3,20 +3,11 @@ import type {
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
import type { MenuAction } from "@react-native-menu/menu";
import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react";
import {
Alert,
Platform,
Pressable,
useColorScheme,
useWindowDimensions,
View,
} from "react-native";
import { memo, useCallback, useEffect, useMemo, type ComponentProps } from "react";
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { ProjectFavicon } from "../../components/ProjectFavicon";
@@ -27,13 +18,7 @@ import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import {
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozeGateExpiryMs,
resolveThreadListV2Status,
resolveThreadListV2SwipeActions,
type ThreadListV2Status,
} from "./threadListV2";
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
/**
@@ -77,11 +62,6 @@ const SLIM_MENU_ACTIONS: MenuAction[] = [
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
const SNOOZED_MENU_ACTIONS: MenuAction[] = [
{ id: "unsnooze", title: "Wake thread", image: "clock" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
// Pre-settlement servers: no lifecycle items, archive fills the gap.
const LEGACY_MENU_ACTIONS: MenuAction[] = [
{ id: "archive", title: "Archive", image: "archivebox" },
@@ -110,81 +90,6 @@ export const ThreadListV2SectionDivider = memo(function ThreadListV2SectionDivid
);
});
const SNOOZE_ACCENT_LIGHT = "#2563eb";
const SNOOZE_ACCENT_DARK = "#60a5fa";
export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedShelfHeader(props: {
readonly count: number;
readonly expanded: boolean;
readonly onToggle: () => void;
readonly pane?: "screen" | "sidebar";
}) {
const colorScheme = useColorScheme();
return (
<Pressable
accessibilityHint={
props.expanded ? "Collapses the snoozed threads." : "Expands the snoozed threads."
}
accessibilityLabel={props.count === 1 ? "1 snoozed thread" : `${props.count} snoozed threads`}
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
className={cn(
"mb-1.5 mt-4 flex-row items-center gap-2.5",
props.pane === "sidebar" ? "px-3" : "px-5",
)}
onPress={props.onToggle}
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text className="text-xs font-t3-medium text-blue-600 dark:text-blue-400">
{props.expanded ? "Snoozed" : `Snoozed (${props.count})`}
</Text>
<View className="h-px flex-1 bg-blue-500/20 dark:bg-blue-400/15" />
<SymbolView
name={props.expanded ? "chevron.up" : "chevron.down"}
size={10}
tintColor={colorScheme === "dark" ? SNOOZE_ACCENT_DARK : SNOOZE_ACCENT_LIGHT}
type="monochrome"
/>
</Pressable>
);
});
export const ThreadListV2SettledShelfHeader = memo(function ThreadListV2SettledShelfHeader(props: {
readonly count: number;
readonly expanded: boolean;
readonly onToggle: () => void;
readonly pane?: "screen" | "sidebar";
}) {
const mutedColor = useThemeColor("--color-foreground-muted");
return (
<Pressable
accessibilityHint={
props.expanded ? "Collapses the settled threads." : "Expands the settled threads."
}
accessibilityLabel={props.count === 1 ? "1 settled thread" : `${props.count} settled threads`}
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
className={cn(
"mb-1.5 mt-4 flex-row items-center gap-2.5",
props.pane === "sidebar" ? "px-3" : "px-5",
)}
onPress={props.onToggle}
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text className="text-xs font-t3-medium text-foreground-tertiary">
{props.expanded ? "Settled" : `Settled (${props.count})`}
</Text>
<View className="h-px flex-1 bg-border" />
<SymbolView
name={props.expanded ? "chevron.up" : "chevron.down"}
size={10}
tintColor={mutedColor}
type="monochrome"
/>
</Pressable>
);
});
const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
@@ -303,14 +208,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly thread: EnvironmentThreadShell;
readonly variant: "card" | "slim";
/** Snoozed-shelf row: shows its wake time and offers Wake. */
readonly snoozed?: boolean;
/** Preformatted against the parent minute tick so this memoized row's
countdown keeps moving. */
readonly snoozeWakeLabelText?: string;
/** Parent minute tick passed as a prop so this memoized row refreshes its
native snooze menu while mounted. */
readonly snoozePresetMinute: string;
readonly showSettledDivider: boolean;
readonly project: EnvironmentProject | null;
readonly projectTitle?: string;
readonly providerDriver: string | null;
@@ -333,15 +231,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
/** False on environments whose server predates thread.settle/unsettle:
swipe + menu fall back to Archive instead of failing on use. */
readonly settlementSupported: boolean;
/** False on servers that predate thread.snooze/unsnooze. */
readonly snoozeSupported: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
/** Reports this row's live PR state up so the partition can auto-settle
@@ -364,13 +258,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onSelectThread,
onDeleteThread,
onSettleThread,
onSnoozeThread,
onUnsnoozeThread,
onUnsettleThread,
onArchiveThread,
onChangeRequestState,
} = props;
const snoozedRow = props.snoozed === true;
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
const prState = pr?.state ?? null;
@@ -392,94 +283,27 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
const handleSnooze = useCallback(
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
[onSnoozeThread, thread],
);
const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "settle") handleSettle();
if (nativeEvent.event === "unsettle") handleUnsettle();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "delete") handleDelete();
},
[handleArchive, handleDelete, handleSettle, handleUnsettle],
);
// Swipe: the v2 primary action is the lifecycle transition. Every settled
// row can un-settle — explicit settles clear the override, auto-settled
// rows get pinned active until real activity clears the pin.
const canUnsettle = variant === "slim";
const [snoozeGateTick, bumpSnoozeGateTick] = useState(0);
const snoozeGateExpiryMs = props.snoozeSupported
? resolveThreadListV2SnoozeGateExpiryMs(thread, { now: new Date().toISOString() })
: null;
useEffect(() => {
if (snoozeGateExpiryMs === null) return;
const delayMs = Math.min(Math.max(0, snoozeGateExpiryMs - Date.now()) + 50, 2_147_483_647);
const id = setTimeout(() => bumpSnoozeGateTick((tick) => tick + 1), delayMs);
return () => clearTimeout(id);
}, [snoozeGateExpiryMs, snoozeGateTick]);
const swipeActions = resolveThreadListV2SwipeActions({
variant,
settlementSupported: props.settlementSupported,
snoozeSupported: props.snoozeSupported,
snoozable: canSnooze(thread, { now: new Date().toISOString() }),
snoozed: snoozedRow,
});
const snoozePresets = useMemo(
() => (swipeActions.secondary === "snooze" ? resolveSnoozePresets(new Date()) : ([] as const)),
[props.snoozePresetMinute, swipeActions.secondary],
);
const snoozePresetActions = useMemo<MenuAction[]>(
() =>
snoozePresets.map((preset) => ({
id: `snooze:${preset.id}`,
title: preset.label,
subtitle: preset.whenLabel,
})),
[snoozePresets],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
{ id: "settle", title: "Settle", image: "checkmark" },
{
id: "snooze",
title: "Snooze",
image: "clock",
subactions: snoozePresetActions,
},
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[snoozePresetActions],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "settle") handleSettle();
if (nativeEvent.event === "unsettle") handleUnsettle();
if (nativeEvent.event === "unsnooze") handleUnsnooze();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
event: nativeEvent.event,
displayedPresets: snoozePresets,
now: new Date(),
});
if (snoozeSelection._tag === "selected") {
handleSnooze(snoozeSelection.preset.snoozedUntil);
} else if (snoozeSelection._tag === "expired") {
Alert.alert("Could not snooze thread", "That snooze time has passed. Choose another time.");
}
},
[
handleArchive,
handleDelete,
handleSettle,
handleSnooze,
handleUnsettle,
handleUnsnooze,
snoozePresets,
],
);
const primaryAction = useMemo(() => {
// Pre-settlement server: archive is the swipe action, as in v1. (Slim
// rows cannot occur here — unsupported environments never classify as
// settled.)
if (swipeActions.primary === "archive") {
if (!props.settlementSupported) {
return {
accessibilityLabel: `Archive ${thread.title}`,
icon: "archivebox" as const,
@@ -487,15 +311,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onPress: handleArchive,
};
}
if (swipeActions.primary === "unsnooze") {
return {
accessibilityLabel: `Wake ${thread.title} now`,
icon: "clock" as const,
label: "Wake",
onPress: handleUnsnooze,
};
}
return swipeActions.primary === "unsettle"
return canUnsettle
? {
accessibilityLabel: `Un-settle ${thread.title}`,
icon: "arrow.uturn.backward" as const,
@@ -509,34 +325,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onPress: handleSettle,
};
}, [
canUnsettle,
handleArchive,
handleSettle,
handleUnsettle,
handleUnsnooze,
swipeActions.primary,
props.settlementSupported,
thread.title,
]);
const secondaryAction = useMemo(
() =>
swipeActions.secondary === "snooze"
? {
accessibilityLabel: `Choose when to snooze ${thread.title}`,
icon: "clock" as const,
label: "Snooze",
menu: {
actions: snoozePresetActions,
onPressAction: handleMenuAction,
title: "Snooze until",
},
onPress: () => undefined,
}
: null,
[handleMenuAction, snoozePresetActions, swipeActions.secondary, thread.title],
);
const swipeAccessibilityHint =
secondaryAction === null
? `Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`
: `Opens the thread. Swipe left for ${primaryAction.label.toLowerCase()} and snooze actions.`;
// The sidebar pane fills selected rows with the accent color (matching the
// v1 sidebar), so every piece of row text needs a white-on-accent variant.
@@ -658,7 +453,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const rowContent = (close: () => void) =>
variant === "card" ? (
<Pressable
accessibilityHint={swipeAccessibilityHint}
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
accessibilityLabel={thread.title}
accessibilityRole="button"
accessibilityState={{ selected }}
@@ -696,7 +491,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
</Pressable>
) : (
<Pressable
accessibilityHint={swipeAccessibilityHint}
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
accessibilityLabel={thread.title}
accessibilityRole="button"
accessibilityState={{ selected }}
@@ -756,17 +551,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<Text
className={cn(
"text-sm tabular-nums",
selected
? "text-user-bubble-foreground-muted"
: snoozedRow
? "text-blue-600 dark:text-blue-400"
: "text-foreground-tertiary",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
)}
style={{ fontFamily: MONO_FONT }}
>
{snoozedRow && props.snoozeWakeLabelText !== undefined
? props.snoozeWakeLabelText
: relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
</Text>
</View>
</Pressable>
@@ -774,6 +563,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
return (
<>
{props.showSettledDivider ? (
<ThreadListV2SectionDivider label="Settled" pane={props.pane} />
) : null}
<ThreadSwipeable
backgroundColor={sidebarPane ? drawerColor : screenColor}
compactActions={variant === "slim"}
@@ -782,14 +574,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
}
enableTrackpadSwipe
// Full swipe commits the advertised lifecycle action (Settle /
// Un-settle), never the secondary snooze action.
// Un-settle), never the destructive delete.
fullSwipeAction="primary"
fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
onDelete={handleDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
primaryAction={primaryAction}
secondaryAction={secondaryAction}
resetKey={`${thread.environmentId}:${thread.id}`}
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
threadTitle={thread.title}
@@ -797,15 +588,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
{(close) => (
<ControlPillMenu
actions={
snoozedRow
? SNOOZED_MENU_ACTIONS
: !props.settlementSupported
? LEGACY_MENU_ACTIONS
: canUnsettle
? SLIM_MENU_ACTIONS
: swipeActions.secondary === "snooze"
? snoozableCardMenuActions
: CARD_MENU_ACTIONS
!props.settlementSupported
? LEGACY_MENU_ACTIONS
: canUnsettle
? SLIM_MENU_ACTIONS
: CARD_MENU_ACTIONS
}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
@@ -1,6 +1,5 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
import {
CommandId,
EnvironmentId,
@@ -17,10 +16,7 @@ import {
buildThreadListV2Items,
buildThreadListV2ListItems,
resolveThreadListV2Enabled,
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozeGateExpiryMs,
resolveThreadListV2Status,
resolveThreadListV2SwipeActions,
sortThreadsForListV2,
} from "./threadListV2";
@@ -54,54 +50,6 @@ function makeThread(
const NOW = "2026-06-02T00:00:00.000Z";
describe("resolveThreadListV2SnoozeMenuSelection", () => {
it("accepts a displayed evening preset while its wake time is still future", () => {
const menuOpenedAt = new Date(2026, 4, 8, 16, 59, 30);
const selectedAt = new Date(2026, 4, 8, 17, 0, 30);
const displayedPresets = resolveSnoozePresets(menuOpenedAt);
const selection = resolveThreadListV2SnoozeMenuSelection({
event: "snooze:evening",
displayedPresets,
now: selectedAt,
});
expect(selection).toEqual({
_tag: "selected",
preset: displayedPresets.find((preset) => preset.id === "evening"),
});
});
it("expires a displayed preset once its wake time has passed", () => {
const displayedPresets = resolveSnoozePresets(new Date(2026, 4, 8, 16, 59, 30));
expect(
resolveThreadListV2SnoozeMenuSelection({
event: "snooze:evening",
displayedPresets,
now: new Date(2026, 4, 8, 18, 0, 1),
}),
).toEqual({ _tag: "expired" });
});
it("recomputes presets that remain available instead of using old timestamps", () => {
const displayedPresets = resolveSnoozePresets(new Date(2026, 4, 8, 10));
const selectedAt = new Date(2026, 4, 8, 10, 30);
const selection = resolveThreadListV2SnoozeMenuSelection({
event: "snooze:hour",
displayedPresets,
now: selectedAt,
});
expect(selection._tag).toBe("selected");
if (selection._tag === "selected") {
expect(selection.preset.snoozedUntil).toBe(
new Date(selectedAt.getTime() + 60 * 60 * 1_000).toISOString(),
);
}
});
});
describe("resolveThreadListV2Enabled", () => {
it("defaults on when the device has never chosen", () => {
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true })).toBe(
@@ -148,105 +96,6 @@ describe("resolveThreadListV2Status", () => {
});
});
describe("resolveThreadListV2SwipeActions", () => {
it("offers settle and snooze for an active snoozable thread", () => {
expect(
resolveThreadListV2SwipeActions({
variant: "card",
settlementSupported: true,
snoozeSupported: true,
snoozable: true,
}),
).toEqual({ primary: "settle", secondary: "snooze" });
});
it("offers un-settle and snooze for settled history", () => {
expect(
resolveThreadListV2SwipeActions({
variant: "slim",
settlementSupported: true,
snoozeSupported: true,
snoozable: true,
}),
).toEqual({ primary: "unsettle", secondary: "snooze" });
});
it("omits snooze when the server or thread does not allow it", () => {
expect(
resolveThreadListV2SwipeActions({
variant: "card",
settlementSupported: true,
snoozeSupported: false,
snoozable: true,
}),
).toEqual({ primary: "settle", secondary: null });
expect(
resolveThreadListV2SwipeActions({
variant: "card",
settlementSupported: true,
snoozeSupported: true,
snoozable: false,
}),
).toEqual({ primary: "settle", secondary: null });
});
it("falls back to archive only for a pre-lifecycle server", () => {
expect(
resolveThreadListV2SwipeActions({
variant: "card",
settlementSupported: false,
snoozeSupported: false,
snoozable: true,
}),
).toEqual({ primary: "archive", secondary: null });
});
it("offers wake and no snooze on a snoozed row", () => {
expect(
resolveThreadListV2SwipeActions({
variant: "slim",
settlementSupported: true,
snoozeSupported: true,
snoozable: true,
snoozed: true,
}),
).toEqual({ primary: "unsnooze", secondary: null });
});
});
describe("resolveThreadListV2SnoozeGateExpiryMs", () => {
it("reports when an unadopted turn's grace window lapses", () => {
const thread = makeThread({
id: ThreadId.make("t"),
title: "t",
latestUserMessageAt: "2026-06-02T00:00:30.000Z",
});
expect(resolveThreadListV2SnoozeGateExpiryMs(thread, { now: "2026-06-02T00:01:00.000Z" })).toBe(
Date.parse("2026-06-02T00:02:30.000Z"),
);
});
it("returns null once the thread is snoozable or when only data can unblock it", () => {
expect(
resolveThreadListV2SnoozeGateExpiryMs(
makeThread({ id: ThreadId.make("ready"), title: "Ready" }),
{ now: NOW },
),
).toBe(null);
expect(
resolveThreadListV2SnoozeGateExpiryMs(
makeThread({
id: ThreadId.make("blocked"),
title: "Blocked",
hasPendingApprovals: true,
latestUserMessageAt: NOW,
}),
{ now: NOW },
),
).toBe(null);
});
});
describe("sortThreadsForListV2", () => {
it("orders by creation time, newest first, ignoring activity", () => {
const sorted = sortThreadsForListV2([
@@ -318,93 +167,6 @@ describe("buildThreadListV2Items", () => {
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
});
it("builds snoozed rows between active and settled when the shelf is expanded", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("settled"),
title: "Settled",
settledOverride: "settled",
settledAt: NOW,
}),
makeThread({
id: ThreadId.make("later"),
title: "Wakes later",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: ThreadId.make("sooner"),
title: "Wakes sooner",
snoozedUntil: "2026-06-02T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozedShelfExpanded: true,
});
expect(layout.items.map((item) => item.thread.id)).toEqual([
"active",
"sooner",
"later",
"settled",
]);
expect(layout.items.map((item) => item.snoozed)).toEqual([false, true, true, false]);
expect(layout.snoozedShelfHeaderIndex).toBe(1);
expect(layout.snoozedCount).toBe(2);
});
it("collapses to a header-only shelf", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("snoozed"),
title: "Snoozed",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
expect(layout.items).toEqual([]);
expect(layout.snoozedCount).toBe(1);
expect(layout.snoozedShelfHeaderIndex).toBe(0);
});
it("keeps the selected thread on a collapsed shelf", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("open"),
title: "Open",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: ThreadId.make("other"),
title: "Other",
snoozedUntil: "2026-06-03T10:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
selectedThreadKey: `${environmentId}:open`,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["open"]);
expect(layout.items[0]?.snoozed).toBe(true);
expect(layout.snoozedCount).toBe(2);
});
it("keeps snoozed threads visible on environments without the snooze capability", () => {
const layout = buildThreadListV2Items({
threads: [
@@ -425,8 +187,8 @@ describe("buildThreadListV2Items", () => {
expect(layout.snoozedCount).toBe(0);
});
it("partitions settled threads into a slim shelf", () => {
const layout = buildThreadListV2Items({
it("partitions settled threads into a slim tail with one divider", () => {
const { items } = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
@@ -447,64 +209,13 @@ describe("buildThreadListV2Items", () => {
now: NOW,
});
expect(layout.items.map((item) => [item.thread.id, item.variant])).toEqual([
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
["active", "card"],
["settled", "slim"],
["settled-2", "slim"],
]);
expect(layout.items.map((item) => item.isLast)).toEqual([false, false, true]);
expect(layout.settledCount).toBe(2);
expect(layout.settledShelfHeaderIndex).toBe(1);
});
it("collapses settled threads to a counted shelf header", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("settled"),
title: "Settled",
settledOverride: "settled",
settledAt: NOW,
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
settledShelfExpanded: false,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["active"]);
expect(layout.settledCount).toBe(1);
expect(layout.settledShelfHeaderIndex).toBe(1);
});
it("keeps the selected settled thread visible when its shelf is collapsed", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("selected"),
title: "Selected",
settledOverride: "settled",
settledAt: NOW,
}),
makeThread({
id: ThreadId.make("other"),
title: "Other",
settledOverride: "settled",
settledAt: NOW,
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
settledShelfExpanded: false,
selectedThreadKey: `${environmentId}:selected`,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["selected"]);
expect(layout.settledCount).toBe(2);
expect(layout.settledShelfHeaderIndex).toBe(0);
expect(items.map((item) => item.showSettledDivider)).toEqual([false, true, false]);
expect(items.map((item) => item.isLast)).toEqual([false, false, true]);
});
it("keeps cards in creation order while settled sorts by recency", () => {
@@ -709,21 +420,13 @@ describe("buildThreadListV2ListItems", () => {
const items = buildThreadListV2ListItems({
items: layout.items,
pendingTasks: [makePendingTask("queued-1"), makePendingTask("queued-2")],
settledCount: layout.settledCount,
settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
});
expect(
items.map((item) =>
item.type === "v2-pending"
? item.pendingTask.title
: item.type === "v2-thread"
? item.item.thread.id
: item.type === "v2-snoozed-shelf"
? "snoozed-shelf"
: "settled-shelf",
item.type === "v2-pending" ? item.pendingTask.title : item.item.thread.id,
),
).toEqual(["active", "queued-1", "queued-2", "settled-shelf", "settled"]);
).toEqual(["active", "queued-1", "queued-2", "settled"]);
// Only the leading queued row labels the section, exactly like Settled.
expect(
items.filter((item) => item.type === "v2-pending" && item.showPendingDivider),
@@ -745,58 +448,12 @@ describe("buildThreadListV2ListItems", () => {
expect(items.map((item) => item.type)).toEqual(["v2-thread", "v2-pending"]);
});
it("keeps the settled shelf between active and settled rows when nothing is queued", () => {
const items = buildThreadListV2ListItems({
items: layout.items,
pendingTasks: [],
settledCount: layout.settledCount,
settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
});
it("leaves the thread order untouched when nothing is queued", () => {
const items = buildThreadListV2ListItems({ items: layout.items, pendingTasks: [] });
expect(items.map((item) => item.key)).toEqual([
`v2-thread:${environmentId}:active`,
"v2-settled-shelf",
`v2-thread:${environmentId}:settled`,
]);
});
it("places queued tasks before a collapsed snoozed shelf", () => {
const snoozedLayout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "active" }),
makeThread({
id: ThreadId.make("snoozed"),
title: "snoozed",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: ThreadId.make("settled"),
title: "settled",
settledOverride: "settled",
settledAt: NOW,
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
const items = buildThreadListV2ListItems({
items: snoozedLayout.items,
pendingTasks: [makePendingTask("queued")],
snoozedCount: snoozedLayout.snoozedCount,
snoozedShelfExpanded: false,
snoozedShelfHeaderIndex: snoozedLayout.snoozedShelfHeaderIndex,
settledCount: snoozedLayout.settledCount,
settledShelfHeaderIndex: snoozedLayout.settledShelfHeaderIndex,
});
expect(items.map((item) => item.type)).toEqual([
"v2-thread",
"v2-pending",
"v2-snoozed-shelf",
"v2-settled-shelf",
"v2-thread",
]);
});
});
+30 -207
View File
@@ -1,20 +1,10 @@
import {
effectiveSettled,
effectiveSnoozed,
hasQueuedTurnStart,
QUEUED_TURN_START_GRACE_MS,
resolveSnoozePresets,
snoozeWakeLabel,
} from "@t3tools/client-runtime/state/thread-settled";
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
export { snoozeWakeLabel };
/**
* Thread List v2 model, ported from the web sidebar v2
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
@@ -24,76 +14,6 @@ export { snoozeWakeLabel };
* unlabeled resting state.
*/
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
export function resolveThreadListV2SnoozeMenuSelection(input: {
readonly event: string;
readonly displayedPresets: ReadonlyArray<SnoozePreset>;
readonly now: Date;
}):
| { readonly _tag: "selected"; readonly preset: SnoozePreset }
| { readonly _tag: "expired" }
| { readonly _tag: "not-snooze" } {
if (!input.event.startsWith("snooze:")) return { _tag: "not-snooze" };
const currentPreset = resolveSnoozePresets(input.now).find(
(candidate) => input.event === `snooze:${candidate.id}`,
);
if (currentPreset) return { _tag: "selected", preset: currentPreset };
const displayedPreset = input.displayedPresets.find(
(candidate) => input.event === `snooze:${candidate.id}`,
);
if (displayedPreset && Date.parse(displayedPreset.snoozedUntil) > input.now.getTime()) {
return { _tag: "selected", preset: displayedPreset };
}
return { _tag: "expired" };
}
export function resolveThreadListV2SwipeActions(input: {
readonly variant: "card" | "slim";
readonly settlementSupported: boolean;
readonly snoozeSupported: boolean;
readonly snoozable: boolean;
/** Row is on the snoozed shelf. */
readonly snoozed?: boolean;
}): {
readonly primary: Exclude<ThreadListV2SwipeAction, "snooze">;
readonly secondary: "snooze" | null;
} {
if (input.snoozed === true) {
return { primary: "unsnooze", secondary: null };
}
const primary = input.settlementSupported
? input.variant === "slim"
? "unsettle"
: "settle"
: "archive";
return {
primary,
secondary: input.snoozeSupported && input.snoozable ? "snooze" : null,
};
}
/**
* The point at which a queued-turn snooze guard expires on its own. Rows arm
* a one-shot timer for this boundary so Snooze appears without waiting for an
* unrelated render. User-blocked threads return null because only fresh
* server data can make them snoozable.
*/
export function resolveThreadListV2SnoozeGateExpiryMs(
thread: Pick<
EnvironmentThreadShell,
"hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
>,
options: { readonly now: string },
): number | null {
if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null;
if (!hasQueuedTurnStart(thread, options)) return null;
const messageAtMs = Date.parse(thread.latestUserMessageAt ?? "");
if (Number.isNaN(messageAtMs)) return null;
return messageAtMs + QUEUED_TURN_START_GRACE_MS;
}
// Settled-tail paging: recent history is the common lookup; the deep tail
// stays behind an explicit Show more. Shared by the compact Home list and
@@ -178,8 +98,8 @@ export function sortThreadsForListV2<T extends { readonly id: string; readonly c
export interface ThreadListV2Item {
readonly thread: EnvironmentThreadShell;
readonly variant: "card" | "slim";
/** Snoozed-shelf row: shows the wake countdown and offers Wake. */
readonly snoozed: boolean;
/** First settled row after the card block draws the SETTLED divider. */
readonly showSettledDivider: boolean;
readonly isLast: boolean;
}
@@ -187,16 +107,10 @@ export interface ThreadListV2Layout {
readonly items: ThreadListV2Item[];
/** Settled threads beyond the render limit (behind "Show more"). */
readonly hiddenSettledCount: number;
/** Snoozed threads matching the current filters. */
/** Snoozed threads hidden from the list (visibility parity with web's
collapsed Snoozed shelf; mobile has no shelf UI yet). */
readonly snoozedCount: number;
/** Index in `items` where the Snoozed shelf header belongs. The header is
still rendered when the shelf is collapsed and no snoozed rows exist. */
readonly snoozedShelfHeaderIndex: number | null;
/** Total settled threads in scope, including rows hidden by collapse/paging. */
readonly settledCount: number;
/** Index in `items` where the Settled shelf header belongs. */
readonly settledShelfHeaderIndex: number | null;
/** Soonest wake time among snoozed threads, or null. Callers arm
/** Soonest wake time among hidden snoozed threads, or null. Callers arm
a timeout at this boundary so the list re-partitions the moment a
snooze expires instead of on the next minute tick. */
readonly nextSnoozeWakeAt: string | null;
@@ -206,8 +120,6 @@ export interface ThreadListV2ThreadListItem {
readonly type: "v2-thread";
readonly key: string;
readonly item: ThreadListV2Item;
/** Precomputed so recycled-list equality can see a minute-tick change. */
readonly snoozeWakeLabelText: string | undefined;
}
export interface ThreadListV2PendingListItem {
@@ -218,53 +130,28 @@ export interface ThreadListV2PendingListItem {
readonly showPendingDivider: boolean;
}
export interface ThreadListV2SnoozedShelfListItem {
readonly type: "v2-snoozed-shelf";
readonly key: "v2-snoozed-shelf";
readonly count: number;
readonly expanded: boolean;
}
export interface ThreadListV2SettledShelfListItem {
readonly type: "v2-settled-shelf";
readonly key: "v2-settled-shelf";
readonly count: number;
readonly expanded: boolean;
}
export type ThreadListV2ListItem =
| ThreadListV2ThreadListItem
| ThreadListV2PendingListItem
| ThreadListV2SnoozedShelfListItem
| ThreadListV2SettledShelfListItem;
export type ThreadListV2ListItem = ThreadListV2ThreadListItem | ThreadListV2PendingListItem;
/**
* Builds the shared mobile order: active → pending → snoozed shelf → settled.
* Pending tasks are waiting rather than asking, and parked work remains
* reachable without competing with either the inbox or settled history.
* Splices queued tasks between the active block and the settled tail, so the
* list reads active → pending → settled. Queued work sits below the live
* threads because nothing can happen to it until its environment returns:
* it is waiting, not asking. Shared by the compact Home list and the iPad
* sidebar so both order and label the sections identically.
*/
export function buildThreadListV2ListItems(input: {
readonly items: ReadonlyArray<ThreadListV2Item>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
readonly snoozedCount?: number;
readonly snoozedShelfExpanded?: boolean;
readonly snoozedShelfHeaderIndex?: number | null;
readonly settledCount?: number;
readonly settledShelfExpanded?: boolean;
readonly settledShelfHeaderIndex?: number | null;
readonly snoozeLabelNow?: string;
}): ThreadListV2ListItem[] {
const threadItems = input.items.map(
(item): ThreadListV2ListItem => ({
type: "v2-thread",
key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
item,
snoozeWakeLabelText:
item.snoozed && item.thread.snoozedUntil != null && input.snoozeLabelNow !== undefined
? snoozeWakeLabel(item.thread.snoozedUntil, { now: input.snoozeLabelNow })
: undefined,
}),
);
if (input.pendingTasks.length === 0) return threadItems;
const pendingItems = input.pendingTasks.map(
(pendingTask, index): ThreadListV2ListItem => ({
type: "v2-pending",
@@ -273,32 +160,14 @@ export function buildThreadListV2ListItems(input: {
showPendingDivider: index === 0,
}),
);
const snoozedCount = input.snoozedCount ?? 0;
const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null;
const settledCount = input.settledCount ?? 0;
const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null;
const activeEnd = snoozedShelfHeaderIndex ?? settledShelfHeaderIndex ?? threadItems.length;
const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length;
const result: ThreadListV2ListItem[] = [...threadItems.slice(0, activeEnd), ...pendingItems];
if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) {
result.push({
type: "v2-snoozed-shelf",
key: "v2-snoozed-shelf",
count: snoozedCount,
expanded: input.snoozedShelfExpanded === true,
});
result.push(...threadItems.slice(snoozedShelfHeaderIndex, snoozedEnd));
}
if (settledShelfHeaderIndex !== null && settledCount > 0) {
result.push({
type: "v2-settled-shelf",
key: "v2-settled-shelf",
count: settledCount,
expanded: input.settledShelfExpanded !== false,
});
result.push(...threadItems.slice(settledShelfHeaderIndex));
}
return result;
// The settled tail begins at the row that draws the SETTLED divider; with
// no settled rows the queued block simply ends the list.
const settledStart = threadItems.findIndex(
(entry) => entry.type === "v2-thread" && entry.item.showSettledDivider,
);
return settledStart === -1
? [...threadItems, ...pendingItems]
: [...threadItems.slice(0, settledStart), ...pendingItems, ...threadItems.slice(settledStart)];
}
/**
@@ -335,13 +204,6 @@ export function buildThreadListV2Items(input: {
second-precise, so classifying with the floored minute would hold a
woken thread hidden for up to a minute. Defaults to `now`. */
readonly snoozeNow?: string;
/** Expands the snoozed shelf into rows. Collapsed is the default. */
readonly snoozedShelfExpanded?: boolean;
/** Expands the settled shelf into rows. Expanded is the default. */
readonly settledShelfExpanded?: boolean;
/** The selected thread remains visible on an otherwise collapsed shelf so
a split-view detail can never lose its navigation row. */
readonly selectedThreadKey?: string | null;
}): ThreadListV2Layout {
const now = input.now ?? new Date().toISOString();
const snoozeNow = input.snoozeNow ?? now;
@@ -353,7 +215,7 @@ export function buildThreadListV2Items(input: {
const active: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
const snoozed: EnvironmentThreadShell[] = [];
let snoozedCount = 0;
let nextSnoozeWakeAt: string | null = null;
for (const thread of input.threads) {
// Callers pass live (unarchived) shells; settled threads are among them
@@ -382,7 +244,7 @@ export function buildThreadListV2Items(input: {
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
// work). Snooze outranks settled classification, same as web.
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
snoozed.push(thread);
snoozedCount += 1;
if (
thread.snoozedUntil != null &&
(nextSnoozeWakeAt === null ||
@@ -403,60 +265,24 @@ export function buildThreadListV2Items(input: {
}
const orderedActive = sortThreadsForListV2(active);
const orderedSnoozed = [...snoozed].sort(
(left, right) =>
parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
);
const selectedThreadKey = input.selectedThreadKey ?? null;
const visibleSnoozed =
input.snoozedShelfExpanded === true
? orderedSnoozed
: orderedSnoozed.filter(
(thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
);
const orderedSettled = [...settled].sort(
(left, right) =>
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
);
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
const pagedSettled =
orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
const selectedSettled = orderedSettled
.slice(pagedSettled.length)
.find((thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey);
if (selectedSettled !== undefined) pagedSettled.push(selectedSettled);
const visibleSettled =
input.settledShelfExpanded !== false
? pagedSettled
: pagedSettled.filter(
(thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
);
orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
const items: ThreadListV2Item[] = [];
for (const thread of orderedActive) {
items.push({
thread,
variant: "card",
snoozed: false,
isLast: false,
});
items.push({ thread, variant: "card", showSettledDivider: false, isLast: false });
}
const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
for (const thread of visibleSnoozed) {
for (const [index, thread] of visibleSettled.entries()) {
items.push({
thread,
variant: "slim",
snoozed: true,
isLast: false,
});
}
const settledShelfHeaderIndex = orderedSettled.length > 0 ? items.length : null;
for (const thread of visibleSettled) {
items.push({
thread,
variant: "slim",
snoozed: false,
showSettledDivider: index === 0,
isLast: false,
});
}
@@ -466,11 +292,8 @@ export function buildThreadListV2Items(input: {
}
return {
items,
hiddenSettledCount: orderedSettled.length - pagedSettled.length,
snoozedCount: orderedSnoozed.length,
snoozedShelfHeaderIndex,
settledCount: orderedSettled.length,
settledShelfHeaderIndex,
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
snoozedCount,
nextSnoozeWakeAt,
};
}
+1 -126
View File
@@ -2,92 +2,9 @@ import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
import {
buildModelMenuActions,
buildModelOptions,
groupByProvider,
resolveSelectableModelSelection,
} from "./modelOptions";
import { buildModelOptions } 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: [
@@ -132,46 +49,4 @@ describe("mobile model options", () => {
expect(option?.capabilities?.optionDescriptors?.[0]?.id).toBe("serviceTier");
expect(option?.selection.options).toEqual([{ id: "serviceTier", value: "default" }]);
});
it("rejects stored selections whose provider is not usable", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [],
},
{
instanceId: "claudeAgent",
driver: "claudeAgent",
enabled: false,
installed: true,
auth: { status: "authenticated" },
models: [],
},
],
} as unknown as ServerConfig;
const usable = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.6-sol",
};
const disabled = {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-5",
};
const removed = {
instanceId: ProviderInstanceId.make("codex_personal"),
model: "gpt-5.6-sol",
};
expect(resolveSelectableModelSelection(config, usable)).toBe(usable);
expect(resolveSelectableModelSelection(config, disabled)).toBeNull();
expect(resolveSelectableModelSelection(config, removed)).toBeNull();
// No config (environment offline) — nothing to validate against.
expect(resolveSelectableModelSelection(null, disabled)).toBe(disabled);
});
});
-79
View File
@@ -3,7 +3,6 @@ import type {
ModelSelection,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import {
buildProviderOptionSelectionsFromDescriptors,
getProviderOptionDescriptors,
@@ -17,7 +16,6 @@ export type ModelOption = {
readonly providerLabel: string;
readonly providerDriver: string;
readonly isDefault: boolean;
readonly isLegacy: boolean;
readonly capabilities: ModelCapabilities | null;
readonly selection: ModelSelection;
};
@@ -60,31 +58,6 @@ function normalizeSelectionOptions(
};
}
/**
* A stored model selection is only usable when its provider instance is
* currently enabled, installed, and authenticated on the server. Returns the
* selection unchanged when usable, otherwise `null` so callers fall through to
* the server's default model. A missing config (environment offline) cannot be
* validated, so stored selections pass through untouched.
*/
export function resolveSelectableModelSelection(
config: T3ServerConfig | null | undefined,
selection: ModelSelection | null,
): ModelSelection | null {
if (!selection || !config) {
return selection;
}
const provider = config.providers.find(
(candidate) => candidate.instanceId === selection.instanceId,
);
return provider &&
provider.enabled &&
provider.installed &&
provider.auth.status !== "unauthenticated"
? selection
: null;
}
export function buildModelOptions(
config: T3ServerConfig | null | undefined,
fallbackModelSelection: ModelSelection | null,
@@ -107,7 +80,6 @@ export function buildModelOptions(
providerLabel,
providerDriver: provider.driver,
isDefault: model.isDefault === true,
isLegacy: model.isLegacy === true,
capabilities: model.capabilities,
selection: normalizeSelectionOptions(
{
@@ -138,7 +110,6 @@ export function buildModelOptions(
providerLabel,
providerDriver: fallbackModelSelection.instanceId,
isDefault: false,
isLegacy: false,
capabilities: null,
selection: fallbackModelSelection,
});
@@ -168,53 +139,3 @@ 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)),
},
]
: []),
];
});
}
@@ -119,36 +119,6 @@ describe("mobile composer drafts", () => {
});
});
it("drops the workspace selection when clearing a sent new-task draft", () => {
const draftKey = "new-task:environment-1:project-1";
const draft: ComposerDraft = {
text: "send this",
attachments: [],
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
startFromOrigin: false,
},
};
expect(
clearComposerDraftContentState({ [draftKey]: draft }, draftKey, {
clearWorkspaceSelection: true,
}),
).toEqual({
[draftKey]: {
modelSelection: draft.modelSelection,
text: "",
attachments: [],
},
});
});
it("reads the latest selector state synchronously for send", () => {
const draftKey = "environment-1:thread-1";
const selectedDraft: ComposerDraft = {
+3 -10
View File
@@ -372,18 +372,14 @@ export function updateComposerDraftSettings(
export function clearComposerDraftContentState(
current: Record<string, ComposerDraft>,
draftKey: string,
options?: { readonly clearWorkspaceSelection?: boolean },
): Record<string, ComposerDraft> {
const existing = current[draftKey];
if (!existing) {
return current;
}
const { importedShareIds: _importedShareIds, workspaceSelection, ...retained } = existing;
const { importedShareIds: _importedShareIds, ...retained } = existing;
const draft = {
...retained,
...(options?.clearWorkspaceSelection || workspaceSelection === undefined
? {}
: { workspaceSelection }),
text: "",
attachments: [],
};
@@ -530,11 +526,8 @@ export async function restoreComposerDraftSnapshot(
await persistenceQueue.run(() => writePersistedComposerDrafts(next));
}
export function clearComposerDraftContent(
draftKey: string,
options?: { readonly clearWorkspaceSelection?: boolean },
): void {
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
export function clearComposerDraftContent(draftKey: string): void {
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
}
export function clearComposerDraft(draftKey: string): void {
+1 -1
View File
@@ -16,7 +16,7 @@
"type": "module",
"scripts": {
"dev": "node --watch src/bin.ts",
"build:bundle": "vp pack && vp pack src/service-launcher.ts --out-dir dist --no-clean",
"build:bundle": "vp pack",
"start": "node dist/bin.mjs",
"typecheck": "tsgo --noEmit",
"test": "vp test run"
+1 -5
View File
@@ -223,11 +223,7 @@ const publishCmd = Command.make(
const packageJsonPath = path.join(serverDir, "package.json");
// Assert build assets exist
for (const relPath of [
"dist/bin.mjs",
"dist/service-launcher.mjs",
"dist/client/index.html",
]) {
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new ServerCliBuildAssetMissingError({ assetPath: abs });
-4
View File
@@ -9,13 +9,11 @@ import * as NetService from "@t3tools/shared/Net";
import packageJson from "../package.json" with { type: "json" };
import { authCommand } from "./cli/auth.ts";
import { connectCommand } from "./cli/connect.ts";
import { pairCommand } from "./cli/pair.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
import { serviceCommand } from "./cli/service.ts";
import { servicePreflightCommand } from "./cli/servicePreflight.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -50,11 +48,9 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
Command.withSubcommands([
startCommand,
serveCommand,
pairCommand,
authCommand,
projectCommand,
serviceCommand,
servicePreflightCommand,
cloudEnabled ? connectCommand : connectUnavailableCommand,
]),
);
+2 -6
View File
@@ -1,5 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import { assert, expect, it } from "@effect/vitest";
@@ -58,10 +56,8 @@ 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`);
return yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const { fd } = yield* fs.open(filePath, { flag: "r" });
return fd;
});
it.effect("falls back to effect/config values when flags are omitted", () =>
+1 -1
View File
@@ -466,7 +466,7 @@ export const DurationFromString = Schema.String.pipe(
return Effect.succeed(duration);
}
return Effect.fail(
new SchemaIssue.InvalidValue({
new SchemaIssue.InvalidValue(Option.some(value), {
message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
}),
);
-268
View File
@@ -1,268 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
import * as NodeHttp from "node:http";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NetService from "@t3tools/shared/Net";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/unstable/cli";
import { cli } from "../bin.ts";
import {
makePersistedServerRuntimeState,
persistServerRuntimeState,
type PersistedServerRuntimeState,
} from "../serverRuntimeState.ts";
import {
DevServerNotProxiableError,
resolveDirectPairingBaseUrl,
resolveTailscaleLocalTarget,
} from "./pair.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
const baseState = {
version: 1,
pid: 123,
port: 3_773,
origin: "http://127.0.0.1:3773",
startedAt: "2026-06-20T00:00:00.000Z",
} as const satisfies PersistedServerRuntimeState;
describe("pair base URL selection", () => {
it("pairs through the dev web origin when the server fronts a dev server", () => {
expect(resolveDirectPairingBaseUrl({ ...baseState, devUrl: "http://localhost:5733/" })).toBe(
"http://localhost:5733/",
);
});
it("pairs through the bound host when there is no dev server", () => {
expect(resolveDirectPairingBaseUrl({ ...baseState, host: "100.64.0.7" })).toBe(
"http://100.64.0.7:3773",
);
expect(resolveDirectPairingBaseUrl(baseState)).toBe("http://localhost:3773");
});
});
describe("pair tailscale local target", () => {
it("proxies the dev web port for dev servers", () => {
expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
{ localPort: 5_733 },
);
// A dev server on a non-loopback interface must be proxied at that
// interface; tailscale serve defaults to 127.0.0.1 otherwise.
expect(
resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://192.168.1.10:5733/" }),
).toEqual({ localPort: 5_733, localHost: "192.168.1.10" });
// URL.hostname keeps IPv6 brackets, so the serve target stays valid.
expect(
resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[fd7a:115c::1]:5733/" }),
).toEqual({ localPort: 5_733, localHost: "[fd7a:115c::1]" });
});
it("rejects HTTPS dev URLs, which tailscale serve cannot proxy", () => {
expect(
resolveTailscaleLocalTarget({ ...baseState, devUrl: "https://localhost:5733/" }),
).toBeInstanceOf(DevServerNotProxiableError);
});
it("proxies the backend port directly otherwise", () => {
expect(resolveTailscaleLocalTarget(baseState)).toEqual({ localPort: 3_773 });
expect(resolveTailscaleLocalTarget({ ...baseState, host: "0.0.0.0" })).toEqual({
localPort: 3_773,
});
expect(resolveTailscaleLocalTarget({ ...baseState, host: "192.168.1.42" })).toEqual({
localPort: 3_773,
localHost: "192.168.1.42",
});
});
});
const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
const provideCliTestLayers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.provide(effect, Layer.mergeAll(CliRuntimeLayer, TestConsole.layer));
// Console output accumulates across CLI runs within a test, and each
// Console.log call is one entry — so the latest command's output is the last
// entry, even when it spans many lines.
const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
provideCliTestLayers(
Effect.gen(function* () {
yield* effect;
return (
(yield* TestConsole.logLines).findLast(
(line): line is string => typeof line === "string",
) ?? ""
);
}),
);
const testDescriptor = {
environmentId: "pair-test-environment",
label: "pair-test",
platform: { os: "linux", arch: "x64" },
serverVersion: "0.0.1",
capabilities: { repositoryIdentity: true },
};
const withDescriptorServer = <A, E, R>(run: (origin: string) => Effect.Effect<A, E, R>) =>
Effect.acquireUseRelease(
Effect.callback<NodeHttp.Server>((resume) => {
const server = NodeHttp.createServer((request, response) => {
if (request.url === "/.well-known/t3/environment") {
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify(testDescriptor));
return;
}
response.writeHead(404);
response.end();
});
server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server)));
}),
(server) => {
const address = server.address();
if (address === null || typeof address === "string") {
return Effect.die(new Error("Expected a TCP address"));
}
return run(`http://127.0.0.1:${String(address.port)}`);
},
(server) => Effect.sync(() => server.close()),
);
describe("t3 pair", () => {
it.effect("mints a token and prints a QR pairing URL for a live server", () =>
withDescriptorServer((origin) =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-test-"));
const port = Number(new URL(origin).port);
const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
yield* persistServerRuntimeState({
path: statePath,
state: yield* makePersistedServerRuntimeState({
config: { host: "127.0.0.1", devUrl: undefined },
port,
}),
});
const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
assert.include(output, `Pairing with pair-test (${origin})`);
assert.include(output, `Pairing URL: ${origin}/pair#token=`);
assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
// Loopback origins are not reachable from a phone; the output must say so.
assert.include(output, "only reachable from this machine");
const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
assert.isString(token);
// The token must be in the same store the running server reads.
const listed = yield* captureStdout(
runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const credentials = JSON.parse(listed) as ReadonlyArray<{ readonly label?: string }>;
assert.equal(credentials.length, 1);
assert.equal(credentials[0]?.label, "t3 pair");
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("pairs through the recorded dev web URL for dev servers", () =>
withDescriptorServer((origin) =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-dev-test-"));
const port = Number(new URL(origin).port);
const statePath = NodePath.join(baseDir, "dev", "server-runtime.json");
yield* persistServerRuntimeState({
path: statePath,
state: yield* makePersistedServerRuntimeState({
config: { host: undefined, devUrl: new URL("http://localhost:5733") },
port,
}),
});
const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
assert.include(output, "Pairing URL: http://localhost:5733/pair#token=");
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("directs to t3 serve or t3 connect when no server is running", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-none-test-"));
const error = yield* provideCliTestLayers(
runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
);
const rendered = String(
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
);
assert.include(rendered, "No running T3 Code server found.");
assert.include(rendered, "npx t3 serve");
assert.include(rendered, "npx t3 connect");
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
withDescriptorServer((origin) =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-pid-test-"));
const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
// The origin answers (another server reused the port), but the pid
// that wrote this state file is dead — pairing must not mint a token
// into the dead server's database.
const state = yield* makePersistedServerRuntimeState({
config: { host: "127.0.0.1", devUrl: undefined },
port: Number(new URL(origin).port),
});
yield* persistServerRuntimeState({
path: statePath,
// pid 2**22 + 1 exceeds any default Linux/macOS pid range.
state: { ...state, pid: 4_194_305 },
});
const error = yield* provideCliTestLayers(
runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
);
const rendered = String(
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
);
assert.include(rendered, "No running T3 Code server found.");
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("ignores stale runtime state pointing at a dead server", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-stale-test-"));
const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
// A port from the dynamic range with nothing listening: the probe fails
// fast with ECONNREFUSED and discovery moves on.
yield* persistServerRuntimeState({
path: statePath,
state: yield* makePersistedServerRuntimeState({
config: { host: "127.0.0.1", devUrl: undefined },
port: 1,
}),
});
const error = yield* provideCliTestLayers(
runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
);
const rendered = String(
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
);
assert.include(rendered, "No running T3 Code server found.");
}).pipe(Effect.provide(NodeServices.layer)),
);
});
-542
View File
@@ -1,542 +0,0 @@
/**
* `t3 pair` - mint a pairing token for an already-running server and print it
* as a QR code, without restarting anything.
*
* Discovery reads the `server-runtime.json` a live server persists next to its
* database, then confirms the process is actually answering by fetching its
* public environment descriptor. Inside a linked git worktree the worktree's
* own `.t3` is checked first (matching dev-runner precedence); otherwise the
* shared T3 home. `--tailscale` publishes the server over Tailscale Serve
* HTTPS and pairs through the tailnet URL instead.
*/
import {
AuthStandardClientScopes,
ExecutionEnvironmentDescriptor,
PortSchema,
} from "@t3tools/contracts";
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
import {
buildTailscaleHttpsBaseUrl,
DEFAULT_TAILSCALE_SERVE_PORT,
ensureTailscaleServe,
readTailscaleStatus,
} from "@t3tools/tailscale";
import * as Config from "effect/Config";
import * as Console from "effect/Console";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
HttpClientResponse,
} from "effect/unstable/http";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerConfig from "../config.ts";
import { resolveBaseDir } from "../os-jank.ts";
import {
type PersistedServerRuntimeState,
readPersistedServerRuntimeState,
} from "../serverRuntimeState.ts";
import {
buildPairingUrl,
formatHostForUrl,
isLoopbackHost,
isWildcardHost,
renderTerminalQrCode,
resolveHeadlessConnectionString,
} from "../startupAccess.ts";
import { baseDirFlag, DurationFromString } from "./config.ts";
const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment";
const PAIR_PROBE_TIMEOUT = Duration.millis(2_500);
// Tailscale provisions an HTTPS certificate on the first request to a fresh
// serve mapping, which can take a few seconds.
const TAILSCALE_PROBE_ATTEMPTS = 5;
const TAILSCALE_PROBE_RETRY_DELAY = Duration.seconds(1);
export type PairStateVariant = "userdata" | "dev";
// deriveServerPaths only checks devUrl for undefined-ness when picking the
// dev-vs-userdata state directory; the value itself is not used.
const DEV_VARIANT_PLACEHOLDER_URL = new URL("http://localhost");
export class NoRunningServerError extends Schema.TaggedErrorClass<NoRunningServerError>()(
"NoRunningServerError",
{
checkedStatePaths: Schema.Array(Schema.String),
},
) {
override get message(): string {
return [
"No running T3 Code server found.",
...this.checkedStatePaths.map((statePath) => ` checked ${statePath}`),
"Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
].join("\n");
}
}
// Each tailscale failure gets its own class (same reasoning as
// scripts/lib/dev-share.ts): distinct caller-visible message, distinct remedy.
export class TailscaleUnavailableError extends Schema.TaggedErrorClass<TailscaleUnavailableError>()(
"TailscaleUnavailableError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.";
}
}
export class MagicDnsNameMissingError extends Schema.TaggedErrorClass<MagicDnsNameMissingError>()(
"MagicDnsNameMissingError",
{},
) {
override get message(): string {
return "This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.";
}
}
export class ServesOtherEnvironmentError extends Schema.TaggedErrorClass<ServesOtherEnvironmentError>()(
"ServesOtherEnvironmentError",
{ servePort: Schema.Number },
) {
override get message(): string {
return `Tailscale Serve on HTTPS port ${String(this.servePort)} already fronts a different T3 Code server. Pass --tailscale-serve-port to publish this one on another port.`;
}
}
export class TailscaleServeFailedError extends Schema.TaggedErrorClass<TailscaleServeFailedError>()(
"TailscaleServeFailedError",
{ servePort: Schema.Number, cause: Schema.Defect() },
) {
override get message(): string {
return `tailscale serve failed for HTTPS port ${String(this.servePort)}. Run \`tailscale serve --https=${String(this.servePort)} --bg <local-url>\` by hand to see why.`;
}
}
export class ServePortOccupiedError extends Schema.TaggedErrorClass<ServePortOccupiedError>()(
"ServePortOccupiedError",
{ servePort: Schema.Number },
) {
override get message(): string {
return `HTTPS port ${String(this.servePort)} on the tailnet already serves something that is not a T3 Code server. Pass --tailscale-serve-port to publish this one on another port.`;
}
}
/** The URL a browser or phone should pair through, absent Tailscale. */
export const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>
state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);
export class DevServerNotProxiableError extends Schema.TaggedErrorClass<DevServerNotProxiableError>()(
"DevServerNotProxiableError",
{ devUrl: Schema.String },
) {
override get message(): string {
return `Tailscale Serve can only proxy plain-HTTP local targets, and this dev server runs at ${this.devUrl}. Pair without --tailscale instead.`;
}
}
const isDevServerNotProxiableError = Schema.is(DevServerNotProxiableError);
/**
* The local endpoint Tailscale Serve should proxy to. Dev servers are
* single-origin, so the web dev server's port is the one to publish; the
* backend rides along behind Vite's proxy. Serve targets are always plain
* HTTP, so an HTTPS dev URL cannot be proxied and is rejected.
*/
export const resolveTailscaleLocalTarget = (
state: PersistedServerRuntimeState,
): { readonly localPort: number; readonly localHost?: string } | DevServerNotProxiableError => {
if (state.devUrl !== undefined) {
const devUrl = new URL(state.devUrl);
if (devUrl.protocol !== "http:") {
return new DevServerNotProxiableError({ devUrl: state.devUrl });
}
const localPort = devUrl.port.length > 0 ? Number.parseInt(devUrl.port, 10) : 80;
return isLoopbackHost(devUrl.hostname)
? { localPort }
: { localPort, localHost: devUrl.hostname };
}
// A server bound to one specific interface does not answer on loopback, so
// the proxy has to target that interface directly.
if (state.host !== undefined && !isWildcardHost(state.host) && !isLoopbackHost(state.host)) {
return { localPort: state.port, localHost: formatHostForUrl(state.host) };
}
return { localPort: state.port };
};
export const formatPairOutput = (input: {
readonly serverLabel: string;
readonly origin: string;
readonly pairingUrl: string;
readonly token: string;
readonly expiresAt: DateTime.Utc;
readonly notes: ReadonlyArray<string>;
}): string =>
[
`Pairing with ${input.serverLabel} (${input.origin}).`,
"",
renderTerminalQrCode(input.pairingUrl),
"",
`Pairing URL: ${input.pairingUrl}`,
`Token: ${input.token}`,
`Expires: ${DateTime.formatIso(input.expiresAt)}`,
...input.notes.flatMap((note) => ["", `Note: ${note}`]),
"",
].join("\n");
/**
* Three outcomes, because they drive different decisions: a T3 descriptor
* (pair with it), nothing answering (safe to configure Tailscale Serve), or
* something answering that is not a T3 server (do NOT overwrite its mapping).
*/
type EnvironmentProbeResult =
| { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }
| { readonly _tag: "unreachable" }
| { readonly _tag: "not-a-t3-server" };
const probeEnvironmentDescriptor = (
baseUrl: string,
): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>
Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
const response = yield* client.execute(request).pipe(
Effect.timeout(PAIR_PROBE_TIMEOUT),
// Transport failure or timeout: nothing (reachable) is listening there.
Effect.mapError(() => ({ _tag: "unreachable" }) as const),
);
// Bad-gateway family means a proxy (Tailscale Serve) answered for a
// backend that is gone — a stale mapping, not a live occupant. Treating
// it as unreachable lets `t3 pair --tailscale` repair its own mapping
// after the server's port changed.
if (response.status === 502 || response.status === 503 || response.status === 504) {
return { _tag: "unreachable" } as const;
}
// Anything else that answered HTTP but not with a valid descriptor is
// some other service.
const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(
Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
);
return { _tag: "descriptor", descriptor } as const;
}).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));
// signal 0 delivers nothing; it only reports whether the pid exists. EPERM
// means it exists but belongs to another user, which still counts as alive.
const isProcessAlive = (pid: number): boolean => {
try {
process.kill(pid, 0);
return true;
} catch (error) {
return error instanceof Error && "code" in error && error.code === "EPERM";
}
};
interface DiscoveredPairTarget {
readonly baseDir: string;
readonly variant: PairStateVariant;
readonly state: PersistedServerRuntimeState;
readonly descriptor: ExecutionEnvironmentDescriptor;
}
const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* (
explicitBaseDir: string | undefined,
) {
const bases: Array<string> = [];
if (explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0) {
bases.push(yield* resolveBaseDir(explicitBaseDir));
} else {
// Same precedence as dev-runner: inside a linked worktree its own `.t3`
// outranks the shared home, so `t3 pair` in a worktree pairs with the dev
// server under test rather than the daily-driver install.
const worktreeHome = yield* resolveWorktreeT3Home(process.cwd());
if (worktreeHome !== undefined) {
bases.push(worktreeHome);
}
const envHome = yield* Config.string("T3CODE_HOME").pipe(Config.option);
bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));
}
const checkedStatePaths: Array<string> = [];
for (const baseDir of new Set(bases)) {
for (const variant of ["userdata", "dev"] as const) {
const derivedPaths = yield* ServerConfig.deriveServerPaths(
baseDir,
variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
{},
);
const statePath = derivedPaths.serverRuntimeStatePath;
checkedStatePaths.push(statePath);
const state = yield* readPersistedServerRuntimeState(statePath);
if (Option.isNone(state)) {
continue;
}
// The pid check guards against a dead server's state file whose port
// was since reused by a different server: pairing would then mint a
// token in the old database while the QR code points at the new server.
if (!isProcessAlive(state.value.pid)) {
continue;
}
const probed = yield* probeEnvironmentDescriptor(state.value.origin);
if (probed._tag !== "descriptor") {
continue;
}
return {
baseDir,
variant,
state: state.value,
descriptor: probed.descriptor,
} satisfies DiscoveredPairTarget;
}
}
return yield* new NoRunningServerError({ checkedStatePaths });
});
/**
* Server config pointed at the discovered server's state directory, so the
* minted token lands in the database the running server reads from. Built by
* hand rather than through `resolveServerConfig` to keep the dev-vs-userdata
* choice pinned to where the runtime state was actually found, independent of
* ambient environment variables.
*/
const makePairServerConfig = Effect.fn(function* (input: {
readonly target: DiscoveredPairTarget;
readonly logLevel: ServerConfig.ServerConfig["Service"]["logLevel"];
}) {
const { baseDir, variant, state } = input.target;
// The state-dir variant does not imply dev-ness: a worktree dev server uses
// an explicit home and therefore lands in `userdata`. The recorded devUrl is
// what actually marks a dev server.
const devUrl = state.devUrl !== undefined ? new URL(state.devUrl) : undefined;
const derivedPaths = yield* ServerConfig.deriveServerPaths(
baseDir,
variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
{},
);
return ServerConfig.make({
logLevel: input.logLevel,
traceMinLevel: "Info",
traceTimingEnabled: false,
traceBatchWindowMs: 1_000,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
mode: "web",
port: state.port,
host: state.host,
cwd: process.cwd(),
baseDir,
...derivedPaths,
staticDir: undefined,
devUrl,
devAllowedOrigins: [],
noBrowser: true,
startupPresentation: "headless",
desktopBootstrapToken: undefined,
desktopTelemetryFd: undefined,
desktopTelemetryControlFd: undefined,
resourceMonitorPath: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
});
});
const awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {
let last: EnvironmentProbeResult = { _tag: "unreachable" };
for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {
last = yield* probeEnvironmentDescriptor(baseUrl);
if (last._tag === "descriptor") {
return last;
}
yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);
}
return last;
});
const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase")(
function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {
const notes: Array<string> = [];
const status = yield* readTailscaleStatus.pipe(
Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),
);
if (status.magicDnsName === null) {
return yield* new MagicDnsNameMissingError();
}
const baseUrl = buildTailscaleHttpsBaseUrl({
magicDnsName: status.magicDnsName,
servePort: input.servePort,
});
// Only an unreachable port, or a mapping already fronting this exact
// environment, is safe to (re)configure. Any other responder — T3 or not
// — must not have its mapping silently replaced.
const existing = yield* probeEnvironmentDescriptor(baseUrl);
if (existing._tag === "descriptor") {
if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {
return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
}
// Matching environment id proves the mapping reaches this server, but
// not through which port: for a dev server it may front the backend
// (whose /.well-known also answers) while /pair only renders through
// the web origin. Reuse as-is for regular servers; fall through and
// repoint our own mapping at the web port for dev servers.
if (input.target.state.devUrl === undefined) {
return { baseUrl, notes };
}
}
if (existing._tag === "not-a-t3-server") {
return yield* new ServePortOccupiedError({ servePort: input.servePort });
}
const localTarget = resolveTailscaleLocalTarget(input.target.state);
if (isDevServerNotProxiableError(localTarget)) {
return yield* localTarget;
}
yield* ensureTailscaleServe({
localPort: localTarget.localPort,
servePort: input.servePort,
...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
}).pipe(
Effect.mapError(
(cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
),
);
notes.push(
`Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
);
const probed = yield* awaitEnvironmentDescriptor(baseUrl);
if (probed._tag === "descriptor") {
if (probed.descriptor.environmentId !== input.target.descriptor.environmentId) {
return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
}
} else {
notes.push(
"The HTTPS endpoint has not answered yet. First use can take a moment while Tailscale provisions certificates.",
);
}
return { baseUrl, notes };
},
);
const mintPairingLink = Effect.fn("pair.mintPairingLink")(function* (input: {
readonly config: ServerConfig.ServerConfig["Service"];
readonly ttl: Option.Option<Duration.Duration>;
readonly label: Option.Option<string>;
}) {
return yield* Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
return yield* environmentAuth.createPairingLink({
scopes: AuthStandardClientScopes,
subject: "one-time-token",
label: Option.getOrElse(input.label, () => "t3 pair"),
...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),
});
}).pipe(
Effect.provide(
EnvironmentAuth.runtimeLayer.pipe(
Layer.provide(ServerConfig.layer(input.config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),
),
),
);
});
const ttlFlag = Flag.string("ttl").pipe(
Flag.withSchema(DurationFromString),
Flag.withDescription(
"Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.",
),
Flag.optional,
);
const labelFlag = Flag.string("label").pipe(
Flag.withDescription("Optional label shown in the server's connections list."),
Flag.optional,
);
const tailscaleFlag = Flag.boolean("tailscale").pipe(
Flag.withDescription(
"Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.",
),
Flag.withDefault(false),
);
const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale is enabled."),
Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),
);
export const pairCommand = Command.make("pair", {
baseDir: baseDirFlag,
ttl: ttlFlag,
label: labelFlag,
tailscale: tailscaleFlag,
tailscaleServePort: tailscaleServePortFlag,
}).pipe(
Command.withDescription(
"Mint a pairing token for a running T3 Code server and print it as a QR code.",
),
Command.withHandler((flags) =>
Effect.gen(function* () {
const cliLogLevel = yield* GlobalFlag.LogLevel;
// Default to Warn so storage/migration chatter cannot bury the QR code;
// an explicit --log-level still wins.
const logLevel = Option.getOrElse(cliLogLevel, () => "Warn" as const);
const target = yield* discoverPairTarget(Option.getOrUndefined(flags.baseDir));
const notes: Array<string> = [];
let pairingBaseUrl: string;
if (flags.tailscale) {
const resolved = yield* resolveTailscalePairingBase({
target,
servePort: flags.tailscaleServePort,
});
pairingBaseUrl = resolved.baseUrl;
notes.push(...resolved.notes);
} else {
pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);
if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {
notes.push(
"This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
);
}
if (target.variant === "dev" && target.state.devUrl === undefined) {
notes.push(
"This dev server did not record its web URL; restart it so pairing can go through the web origin.",
);
}
}
const config = yield* makePairServerConfig({ target, logLevel });
const issued = yield* mintPairingLink({ config, ttl: flags.ttl, label: flags.label });
const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);
yield* Console.log(
formatPairOutput({
serverLabel: target.descriptor.label,
origin: target.state.origin,
pairingUrl,
token: issued.credential,
expiresAt: issued.expiresAt,
notes,
}),
);
}).pipe(Effect.provide(FetchHttpClient.layer)),
),
);
+1 -3
View File
@@ -337,9 +337,7 @@ const dispatchLiveOrchestrationCommand = (
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
// Project commands only read the project list, so use the lightweight
// command read model instead of hydrating every thread body in the database.
return yield* projectionSnapshotQuery.getCommandReadModel();
return yield* projectionSnapshotQuery.getSnapshot();
});
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
-17
View File
@@ -1,17 +0,0 @@
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,
),
),
);
Loaded 100 of 292 files, more files were not shown because too many files have changed in this diff. Show more