Compare commits

..
214 changed files with 4554 additions and 4113 deletions

No files matched your search

+8
View File
@@ -46,6 +46,14 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Ensure Electron runtime is installed
run: |
if ! node -e "require('./apps/desktop/node_modules/electron')" >/dev/null 2>&1; then
rm -rf apps/desktop/node_modules/electron/dist apps/desktop/node_modules/electron/path.txt
bun apps/desktop/node_modules/electron/install.js
fi
node -e "require('./apps/desktop/node_modules/electron')"
- name: Format
run: bun run fmt:check
+8
View File
@@ -98,6 +98,14 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Ensure Electron runtime is installed
run: |
if ! node -e "require('./apps/desktop/node_modules/electron')" >/dev/null 2>&1; then
rm -rf apps/desktop/node_modules/electron/dist apps/desktop/node_modules/electron/path.txt
bun apps/desktop/node_modules/electron/install.js
fi
node -e "require('./apps/desktop/node_modules/electron')"
- id: release_meta
name: Resolve release version
shell: bash
+1 -3
View File
@@ -10,7 +10,7 @@
"dev:electron": "node scripts/dev-electron.mjs",
"build": "tsdown",
"start": "node scripts/start-electron.mjs",
"typecheck": "tsc --noEmit",
"typecheck": "tsgo --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
@@ -25,11 +25,9 @@
"electron-updater": "^6.6.2"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"productName": "T3 Code (Alpha)"
+3 -2
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as NetService from "@t3tools/shared/Net";
@@ -26,7 +26,8 @@ const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
const MAX_TCP_PORT = 65_535;
const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const;
const makeDesktopRunId = Random.nextUUIDv4.pipe(
const makeDesktopRunId = Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
);
+1 -1
View File
@@ -26,7 +26,7 @@ export interface DesktopAppIdentityShape {
export class DesktopAppIdentity extends Context.Service<
DesktopAppIdentity,
DesktopAppIdentityShape
>()("t3/desktop/AppIdentity") {}
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
const normalizeCommitHash = (value: string): Option.Option<string> => {
const trimmed = value.trim();
+1 -1
View File
@@ -18,7 +18,7 @@ export interface DesktopAssetsShape {
}
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
"t3/desktop/Assets",
"@t3tools/desktop/app/DesktopAssets",
) {}
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
@@ -32,9 +32,7 @@ const makeEnvironment = (
overrides: Partial<DesktopEnvironment.MakeDesktopEnvironmentInput> = {},
env: Record<string, string | undefined> = {},
) =>
Effect.gen(function* () {
return yield* DesktopEnvironment.DesktopEnvironment;
}).pipe(Effect.provide(makeEnvironmentLayer(overrides, env)));
DesktopEnvironment.DesktopEnvironment.pipe(Effect.provide(makeEnvironmentLayer(overrides, env)));
describe("DesktopEnvironment", () => {
it.effect("derives state paths and development identity inside Effect", () =>
+1 -1
View File
@@ -78,7 +78,7 @@ export interface DesktopEnvironmentShape {
export class DesktopEnvironment extends Context.Service<
DesktopEnvironment,
DesktopEnvironmentShape
>()("t3/desktop/Environment") {}
>()("@t3tools/desktop/app/DesktopEnvironment") {}
const APP_BASE_NAME = "T3 Code";
+5 -2
View File
@@ -24,7 +24,7 @@ export interface DesktopShutdownShape {
}
export class DesktopShutdown extends Context.Service<DesktopShutdown, DesktopShutdownShape>()(
"t3/desktop/Shutdown",
"@t3tools/desktop/app/DesktopLifecycle/DesktopShutdown",
) {}
const makeShutdown = Effect.gen(function* () {
@@ -61,8 +61,11 @@ export interface DesktopLifecycleShape {
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
}
/**
* @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
*/
export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
"t3/desktop/Lifecycle",
"@t3tools/desktop/app/DesktopLifecycle",
) {}
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
+1 -1
View File
@@ -43,7 +43,7 @@ export interface DesktopBackendOutputLogShape {
export class DesktopBackendOutputLog extends Context.Service<
DesktopBackendOutputLog,
DesktopBackendOutputLogShape
>()("t3/desktop/BackendOutputLog") {}
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLog") {}
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
+1 -1
View File
@@ -9,7 +9,7 @@ export interface DesktopStateShape {
}
export class DesktopState extends Context.Service<DesktopState, DesktopStateShape>()(
"t3/desktop/State",
"@t3tools/desktop/app/DesktopState",
) {}
export const layer = Layer.effect(
@@ -1,10 +1,12 @@
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Random from "effect/Random";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
@@ -13,13 +15,16 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
export interface DesktopBackendConfigurationShape {
readonly resolve: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
readonly resolve: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
}
export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration,
DesktopBackendConfigurationShape
>()("t3/desktop/BackendConfiguration") {}
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
interface BackendObservabilitySettings {
readonly otlpTracesUrl: Option.Option<string>;
@@ -80,23 +85,6 @@ const readPersistedBackendObservabilitySettings: Effect.Effect<
};
});
const getOrCreateBootstrapToken = Effect.fn("desktop.backendConfiguration.bootstrapToken")(
function* (tokenRef: Ref.Ref<Option.Option<string>>) {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
}
let token = "";
while (token.length < 48) {
token += (yield* Random.nextUUIDv4).replace(/-/g, "");
}
token = token.slice(0, 48);
yield* Ref.set(tokenRef, Option.some(token));
return token;
},
);
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
function* (input: {
readonly bootstrapToken: string;
@@ -148,11 +136,22 @@ export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const crypto = yield* Crypto.Crypto;
const tokenRef = yield* Ref.make(Option.none<string>());
const getOrCreateBootstrapToken = Effect.gen(function* () {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
}
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token));
return token;
});
return DesktopBackendConfiguration.of({
resolve: Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken(tokenRef);
const bootstrapToken = yield* getOrCreateBootstrapToken;
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
@@ -116,7 +116,7 @@ export interface DesktopBackendManagerShape {
export class DesktopBackendManager extends Context.Service<
DesktopBackendManager,
DesktopBackendManagerShape
>()("t3/desktop/BackendManager") {}
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
DesktopObservability.makeComponentLogger("desktop-backend-manager");
@@ -329,9 +329,19 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
}
yield* Ref.set(desktopState.backendReady, false);
const config = yield* configuration.resolve;
const config = yield* configuration.resolve.pipe(
Effect.tapError((error) =>
logBackendManagerError("failed to generate desktop backend configuration", {
cause: error.message,
}),
),
Effect.option,
);
if (Option.isNone(config)) {
return;
}
const entryExists = yield* fileSystem
.exists(config.entryPath)
.exists(config.value.entryPath)
.pipe(Effect.orElseSucceed(() => false));
yield* cancelRestart;
@@ -339,11 +349,11 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
...latest,
desiredRunning: true,
ready: false,
config: Option.some(config),
config: Option.some(config.value),
}));
if (!entryExists) {
yield* scheduleRestart(`missing server entry at ${config.entryPath}`);
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
return;
}
@@ -425,7 +435,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
});
const program = runBackendProcess({
...config,
...config.value,
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
yield* updateActiveRun(runId, (run) => ({
...run,
@@ -433,7 +443,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
}));
yield* backendOutputLog.writeSessionBoundary({
phase: "START",
details: `pid=${pid} port=${config.bootstrap.port} cwd=${config.cwd}`,
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
});
}),
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
@@ -275,7 +275,7 @@ export interface DesktopServerExposureShape {
export class DesktopServerExposure extends Context.Service<
DesktopServerExposure,
DesktopServerExposureShape
>()("t3/desktop/ServerExposure") {}
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
export interface DesktopNetworkInterfacesServiceShape {
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
@@ -284,7 +284,7 @@ export interface DesktopNetworkInterfacesServiceShape {
export class DesktopNetworkInterfacesService extends Context.Service<
DesktopNetworkInterfacesService,
DesktopNetworkInterfacesServiceShape
>()("t3/desktop/ServerExposure/NetworkInterfaces") {}
>()("@t3tools/desktop/backend/DesktopServerExposure/DesktopNetworkInterfacesService") {}
interface RuntimeState {
readonly requestedMode: DesktopServerExposureMode;
+1 -1
View File
@@ -39,7 +39,7 @@ export interface ElectronAppShape {
}
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
"t3/desktop/electron/App",
"@t3tools/desktop/electron/ElectronApp",
) {}
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
+1 -1
View File
@@ -29,7 +29,7 @@ export interface ElectronDialogShape {
}
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
"t3/desktop/electron/Dialog",
"@t3tools/desktop/electron/ElectronDialog",
) {}
const make = ElectronDialog.of({
+1 -1
View File
@@ -33,7 +33,7 @@ export interface ElectronMenuShape {
}
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
"t3/desktop/electron/Menu",
"@t3tools/desktop/electron/ElectronMenu",
) {}
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
@@ -52,7 +52,7 @@ export interface ElectronProtocolShape {
}
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
"t3/desktop/electron/Protocol",
"@t3tools/desktop/electron/ElectronProtocol",
) {}
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
@@ -48,7 +48,7 @@ export interface ElectronSafeStorageShape {
export class ElectronSafeStorage extends Context.Service<
ElectronSafeStorage,
ElectronSafeStorageShape
>()("@t3tools/desktop/ElectronSafeStorage") {}
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
+1 -1
View File
@@ -26,7 +26,7 @@ export interface ElectronShellShape {
}
export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
"t3/desktop/electron/Shell",
"@t3tools/desktop/electron/ElectronShell",
) {}
const make = ElectronShell.of({
+1 -1
View File
@@ -13,7 +13,7 @@ export interface ElectronThemeShape {
}
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
"t3/desktop/electron/Theme",
"@t3tools/desktop/electron/ElectronTheme",
) {}
const make = ElectronTheme.of({
+1 -1
View File
@@ -67,7 +67,7 @@ export interface ElectronUpdaterShape {
}
export class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
"t3/desktop/electron/Updater",
"@t3tools/desktop/electron/ElectronUpdater",
) {}
export const layer = Layer.succeed(ElectronUpdater, {
+1 -1
View File
@@ -33,7 +33,7 @@ export interface ElectronWindowShape {
}
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
"t3/desktop/electron/Window",
"@t3tools/desktop/electron/ElectronWindow",
) {}
const make = Effect.gen(function* () {
+3 -1
View File
@@ -42,7 +42,9 @@ export interface DesktopIpcShape {
) => Effect.Effect<void, never, R | Scope.Scope>;
}
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()("t3/desktop/Ipc") {}
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
"@t3tools/desktop/ipc/DesktopIpc",
) {}
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
DesktopIpc.of({
+17 -11
View File
@@ -6,6 +6,7 @@ import {
} from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -13,7 +14,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
@@ -89,7 +89,7 @@ export interface DesktopAppSettingsShape {
export class DesktopAppSettings extends Context.Service<
DesktopAppSettings,
DesktopAppSettingsShape
>()("t3/desktop/AppSettings") {}
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
return {
@@ -222,10 +222,10 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
readonly settingsPath: string;
readonly settings: DesktopSettings;
readonly defaultSettings: DesktopSettings;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath);
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
const tempPath = `${input.settingsPath}.${process.pid}.${suffix}.tmp`;
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeDesktopSettingsJson(
toDesktopSettingsDocument(input.settings, input.defaultSettings),
);
@@ -240,6 +240,7 @@ export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
const persist = (
@@ -251,13 +252,18 @@ export const layer = Layer.effect(
return Effect.succeed([settingsChange(settings, false), settings] as const);
}
return writeSettings({
fileSystem,
path,
settingsPath: environment.desktopSettingsPath,
settings: nextSettings,
defaultSettings: environment.defaultDesktopSettings,
}).pipe(
return crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeSettings({
fileSystem,
path,
settingsPath: environment.desktopSettingsPath,
settings: nextSettings,
defaultSettings: environment.defaultDesktopSettings,
suffix,
}),
),
Effect.mapError((cause) => new DesktopSettingsWriteError({ cause })),
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
);
@@ -1,6 +1,7 @@
import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -8,7 +9,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref";
@@ -49,7 +49,7 @@ export interface DesktopClientSettingsShape {
export class DesktopClientSettings extends Context.Service<
DesktopClientSettings,
DesktopClientSettingsShape
>()("t3/desktop/ClientSettings") {}
>()("@t3tools/desktop/settings/DesktopClientSettings") {}
const readClientSettings = (
fileSystem: FileSystem.FileSystem,
@@ -74,10 +74,10 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
readonly path: Path.Path;
readonly settingsPath: string;
readonly settings: ClientSettings;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath);
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
const tempPath = `${input.settingsPath}.${process.pid}.${suffix}.tmp`;
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeClientSettingsJson(input.settings);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
@@ -90,18 +90,24 @@ export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
return DesktopClientSettings.of({
get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
Effect.withSpan("desktop.clientSettings.get"),
),
set: (settings) =>
writeClientSettings({
fileSystem,
path,
settingsPath: environment.clientSettingsPath,
settings,
}).pipe(
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeClientSettings({
fileSystem,
path,
settingsPath: environment.clientSettingsPath,
settings,
suffix,
}),
),
Effect.mapError((cause) => new DesktopClientSettingsWriteError({ cause })),
Effect.withSpan("desktop.clientSettings.set"),
),
@@ -1,6 +1,7 @@
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
@@ -9,7 +10,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref";
@@ -121,7 +121,7 @@ export interface DesktopSavedEnvironmentsShape {
export class DesktopSavedEnvironments extends Context.Service<
DesktopSavedEnvironments,
DesktopSavedEnvironmentsShape
>()("t3/desktop/SavedEnvironments") {}
>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
@@ -200,10 +200,10 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
readonly path: Path.Path;
readonly registryPath: string;
readonly document: SavedEnvironmentRegistryDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.registryPath);
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
const tempPath = `${input.registryPath}.${process.pid}.${suffix}.tmp`;
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
@@ -247,14 +247,22 @@ export const layer = Layer.effect(
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
writeRegistryDocument({
fileSystem,
path,
registryPath: environment.savedEnvironmentRegistryPath,
document,
}).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeRegistryDocument({
fileSystem,
path,
registryPath: environment.savedEnvironmentRegistryPath,
document,
suffix,
}),
),
Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })),
);
return DesktopSavedEnvironments.of({
getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
@@ -26,7 +26,7 @@ export interface DesktopShellEnvironmentShape {
export class DesktopShellEnvironment extends Context.Service<
DesktopShellEnvironment,
DesktopShellEnvironmentShape
>()("t3/desktop/ShellEnvironment") {}
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
@@ -68,7 +68,7 @@ export interface DesktopSshEnvironmentShape {
export class DesktopSshEnvironment extends Context.Service<
DesktopSshEnvironment,
DesktopSshEnvironmentShape
>()("t3/desktop/SshEnvironment") {}
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}
export interface DesktopSshEnvironmentLayerOptions {
readonly resolveCliPackageSpec?: () => string;
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -86,6 +87,7 @@ function makeElectronWindowLayer(window: ReturnType<typeof makeTestWindow>["wind
function makeLayer(window: ReturnType<typeof makeTestWindow>["window"]) {
return DesktopSshPasswordPrompts.layer({ passwordPromptTimeoutMs: 1_000 }).pipe(
Layer.provide(makeElectronWindowLayer(window)),
Layer.provide(NodeServices.layer),
Layer.provideMerge(TestClock.layer()),
);
}
@@ -2,6 +2,7 @@ import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
import { DesktopSshPasswordPromptResolutionInputSchema } from "@t3tools/contracts";
import type { SshPasswordRequest } from "@t3tools/ssh/auth";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
@@ -9,7 +10,6 @@ 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 Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as IpcChannels from "../ipc/channels.ts";
@@ -129,7 +129,7 @@ export interface DesktopSshPasswordPromptsShape {
export class DesktopSshPasswordPrompts extends Context.Service<
DesktopSshPasswordPrompts,
DesktopSshPasswordPromptsShape
>()("t3/desktop/SshPasswordPrompts") {}
>()("@t3tools/desktop/ssh/DesktopSshPasswordPrompts") {}
interface PendingSshPasswordPrompt {
readonly requestId: string;
@@ -163,6 +163,7 @@ const failPending = (
const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: LayerOptions = {}) {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const crypto = yield* Crypto.Crypto;
const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>());
const passwordPromptTimeoutMs =
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
@@ -230,7 +231,11 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
});
}
const requestId = yield* Random.nextUUIDv4;
const requestId = yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
() => new DesktopSshPromptUnavailableError({ reason: "Secure randomness is unavailable." }),
),
);
const now = yield* DateTime.now;
const expiresAt = DateTime.formatIso(
DateTime.add(now, { milliseconds: passwordPromptTimeoutMs }),
+1 -1
View File
@@ -53,7 +53,7 @@ export interface DesktopSshRemoteApiShape {
export class DesktopSshRemoteApi extends Context.Service<
DesktopSshRemoteApi,
DesktopSshRemoteApiShape
>()("t3/desktop/SshRemoteApi") {}
>()("@t3tools/desktop/ssh/DesktopSshRemoteApi") {}
const decodeExecutionEnvironmentDescriptor = Schema.decodeUnknownEffect(
ExecutionEnvironmentDescriptor,
+1 -1
View File
@@ -100,7 +100,7 @@ export interface DesktopUpdatesShape {
}
export class DesktopUpdates extends Context.Service<DesktopUpdates, DesktopUpdatesShape>()(
"t3/desktop/Updates",
"@t3tools/desktop/updates/DesktopUpdates",
) {}
const {
@@ -21,7 +21,7 @@ export interface DesktopApplicationMenuShape {
export class DesktopApplicationMenu extends Context.Service<
DesktopApplicationMenu,
DesktopApplicationMenuShape
>()("t3/desktop/ApplicationMenu") {}
>()("@t3tools/desktop/window/DesktopApplicationMenu") {}
type DesktopApplicationMenuRuntimeServices =
| DesktopUpdates.DesktopUpdates
+1 -1
View File
@@ -62,7 +62,7 @@ export interface DesktopWindowShape {
}
export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowShape>()(
"t3/desktop/Window",
"@t3tools/desktop/window/DesktopWindow",
) {}
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
+8 -15
View File
@@ -49,7 +49,6 @@ function resolveAppVariant(value: string | undefined): AppVariant {
}
const variant = VARIANT_CONFIG[APP_VARIANT];
const allowsCleartextTraffic = APP_VARIANT === "development";
const config: ExpoConfig = {
name: variant.appName,
@@ -68,23 +67,16 @@ const config: ExpoConfig = {
checkAutomatically: "ON_LOAD",
fallbackToCacheTimeout: 0,
},
splash: {
image: "./assets/splash-icon.png",
resizeMode: "contain",
backgroundColor: "#ffffff",
},
ios: {
icon: variant.iosIcon,
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
infoPlist: {
...(allowsCleartextTraffic
? {
NSAppTransportSecurity: {
NSAllowsArbitraryLoads: true,
},
}
: {}),
NSAppTransportSecurity: {
NSAllowsArbitraryLoads: true,
},
NSLocalNetworkUsageDescription:
"Allow T3 Code to connect to T3 Code servers on your local network or tailnet.",
ITSAppUsesNonExemptEncryption: false,
},
},
@@ -127,13 +119,14 @@ const config: ExpoConfig = {
"expo-build-properties",
{
ios: {
deploymentTarget: "16.1",
deploymentTarget: "16.4",
},
},
],
"expo-secure-store",
"expo-router",
...(allowsCleartextTraffic ? ["./plugins/withAndroidCleartextTraffic.cjs"] : []),
"expo-font",
"./plugins/withAndroidCleartextTraffic.cjs",
],
extra: {
appVariant: APP_VARIANT,
+1
View File
@@ -0,0 +1 @@
declare module "*.css";
+30 -29
View File
@@ -38,6 +38,7 @@
"@callstack/liquid-glass": "^0.7.1",
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/ui": "~56.0.8",
"@legendapp/list": "3.0.0-beta.44",
"@pierre/diffs": "catalog:",
"@react-native-menu/menu": "^2.0.0",
@@ -53,47 +54,47 @@
"clsx": "^2.1.1",
"diff": "8.0.3",
"effect": "catalog:",
"expo": "~55.0.14",
"expo-build-properties": "~55.0.13",
"expo-camera": "~55.0.15",
"expo-clipboard": "~55.0.9",
"expo-constants": "^55.0.9",
"expo-dev-client": "~55.0.26",
"expo-file-system": "~55.0.16",
"expo-font": "^55.0.4",
"expo-glass-effect": "~55.0.8",
"expo-haptics": "^55.0.9",
"expo-image-picker": "~55.0.14",
"expo-linking": "~55.0.12",
"expo-modules-core": "~55.0.22",
"expo": "^56.0.0",
"expo-build-properties": "~56.0.15",
"expo-camera": "~56.0.7",
"expo-clipboard": "~56.0.3",
"expo-constants": "~56.0.16",
"expo-crypto": "~56.0.4",
"expo-dev-client": "~56.0.16",
"expo-file-system": "~56.0.7",
"expo-font": "~56.0.5",
"expo-glass-effect": "~56.0.4",
"expo-haptics": "~56.0.3",
"expo-image-picker": "~56.0.14",
"expo-linking": "~56.0.12",
"expo-paste-input": "^0.1.15",
"expo-router": "~55.0.12",
"expo-secure-store": "~55.0.9",
"expo-splash-screen": "~55.0.13",
"expo-symbols": "~55.0.5",
"expo-updates": "~55.0.16",
"expo-router": "~56.2.7",
"expo-secure-store": "~56.0.4",
"expo-splash-screen": "~56.0.10",
"expo-symbols": "~56.0.5",
"expo-updates": "~56.0.17",
"punycode": "^2.3.1",
"react": "19.2.5",
"react-dom": "19.2.5",
"react-native": "0.83.4",
"react-native-gesture-handler": "~2.30.0",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-native": "0.85.3",
"react-native-gesture-handler": "~2.31.1",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.20.7",
"react-native-keyboard-controller": "1.21.6",
"react-native-nitro-markdown": "^0.5.0",
"react-native-nitro-modules": "^0.35.4",
"react-native-reanimated": "4.2.1",
"react-native-safe-area-context": "~5.6.2",
"react-native-screens": "~4.23.0",
"react-native-reanimated": "4.3.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "4.25.2",
"react-native-shiki-engine": "^0.3.9",
"react-native-svg": "15.15.3",
"react-native-worklets": "0.7.2",
"react-native-svg": "15.15.4",
"react-native-worklets": "0.8.3",
"shiki": "3.23.0",
"tailwind-merge": "^3.5.0",
"uniwind": "^1.6.2"
},
"devDependencies": {
"@types/react": "~19.2.0",
"babel-preset-expo": "~55.0.8",
"babel-preset-expo": "~56.0.0",
"tailwindcss": "^4.0.0",
"typescript": "catalog:"
},
+10 -36
View File
@@ -1,38 +1,12 @@
import { Stack, useRouter } from "expo-router";
import { type ComponentProps, useState } from "react";
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
import { SymbolView } from "expo-symbols";
import { useState } from "react";
import { Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { buildThreadRoutePath } from "../lib/routes";
import { useRemoteCatalog } from "../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
import type { RemoteCatalogState } from "../state/use-remote-catalog";
function resolveHeaderStatus(state: RemoteCatalogState): {
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly color: string;
readonly label: string;
} {
if (state.isLoadingSavedConnections) {
return { icon: "hourglass", color: "#737373", label: "Loading environments" };
}
if (state.connectionError) {
return { icon: "exclamationmark.triangle.fill", color: "#ef4444", label: "Environment error" };
}
if (state.connectionState === "ready") {
return { icon: "checkmark.circle.fill", color: "#22c55e", label: "Environment online" };
}
if (state.connectionState === "connecting" || state.connectionState === "reconnecting") {
return {
icon: "arrow.triangle.2.circlepath",
color: "#f59e0b",
label: "Environment connecting",
};
}
return { icon: "wifi.slash", color: "#ef4444", label: "Environment offline" };
}
/* ─── Route screen ───────────────────────────────────────────────────── */
@@ -44,7 +18,6 @@ export default function HomeRouteScreen() {
const isDark = useColorScheme() === "dark";
const iconColor = String(useThemeColor("--color-icon"));
const status = resolveHeaderStatus(catalogState);
return (
<>
@@ -105,15 +78,16 @@ export default function HomeRouteScreen() {
</Stack.Toolbar>
<Stack.Toolbar placement="right">
<Stack.Toolbar.View hidesSharedBackground>
<Pressable
accessibilityLabel={status.label}
className="h-11 w-11 items-center justify-center rounded-full bg-card active:opacity-70"
<Stack.Toolbar.Menu icon="ellipsis.circle" separateBackground>
<Stack.Toolbar.Label>More</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
icon="desktopcomputer"
onPress={() => router.push("/connections")}
subtitle="Manage connected hosts"
>
<SymbolView name={status.icon} size={21} tintColor={status.color} type="monochrome" />
</Pressable>
</Stack.Toolbar.View>
<Stack.Toolbar.Label>Environments</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
{/* Bottom toolbar: search + compose, visually split like iMessage */}
+2 -11
View File
@@ -8,6 +8,7 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { NewTaskSheetHeader } from "../../features/threads/NewTaskSheetHeader";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { type RemoteCatalogState, useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
@@ -103,17 +104,7 @@ export default function NewTaskRoute() {
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen options={{ headerShown: false }} />
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold">Choose project</Text>
</View>
<NewTaskSheetHeader title="Choose project" />
<ScrollView
showsVerticalScrollIndicator={false}
+12 -2
View File
@@ -1,3 +1,4 @@
import type { Ref } from "react";
import {
Text as RNText,
TextInput as RNTextInput,
@@ -18,17 +19,26 @@ export function AppText({ className, ...props }: AppTextProps) {
return <RNText className={cn("font-sans text-foreground", className)} {...props} />;
}
export type AppTextInputProps = RNTextInputProps & { readonly className?: string };
export type AppTextInputProps = RNTextInputProps & {
readonly className?: string;
readonly ref?: Ref<RNTextInput>;
};
/**
* Thin wrapper around RN TextInput with default input styling.
* Uses Uniwind className — no manual style parsing.
*/
export function AppTextInput({ className, placeholderTextColor, ...props }: AppTextInputProps) {
export function AppTextInput({
className,
placeholderTextColor,
ref,
...props
}: AppTextInputProps) {
const placeholderColor = useThemeColor("--color-placeholder");
return (
<RNTextInput
ref={ref}
className={cn(
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-[15px] text-foreground",
className,
+24 -2
View File
@@ -1,5 +1,6 @@
import { MenuView } from "@react-native-menu/menu";
import type { ComponentProps, ReactNode } from "react";
import { Pressable, View } from "react-native";
import { Pressable, useColorScheme, View } from "react-native";
import { SymbolView } from "expo-symbols";
import { useThemeColor } from "../lib/useThemeColor";
@@ -10,6 +11,7 @@ export function ControlPill(props: {
readonly icon?: ComponentProps<typeof SymbolView>["name"];
readonly iconNode?: ReactNode;
readonly label?: string;
readonly accessibilityLabel?: string;
readonly onPress?: () => void;
readonly variant?: "circle" | "pill" | "primary" | "danger";
readonly disabled?: boolean;
@@ -55,7 +57,13 @@ export function ControlPill(props: {
);
return (
<Pressable onPress={props.onPress} disabled={props.disabled} className={containerClassName}>
<Pressable
accessibilityLabel={props.accessibilityLabel ?? props.label}
accessibilityRole="button"
onPress={props.onPress}
disabled={props.disabled}
className={containerClassName}
>
{props.iconNode ? (
<View className="h-4 w-4 items-center justify-center">{props.iconNode}</View>
) : props.icon ? (
@@ -65,3 +73,17 @@ export function ControlPill(props: {
</Pressable>
);
}
export function ControlPillMenu(
props: Omit<ComponentProps<typeof MenuView>, "children" | "style" | "themeVariant"> & {
readonly children: ReactNode;
},
) {
const isDarkMode = useColorScheme() === "dark";
return (
<MenuView {...props} themeVariant={isDarkMode ? "dark" : "light"}>
{props.children}
</MenuView>
);
}
@@ -1,252 +0,0 @@
import { CameraView, useCameraPermissions } from "expo-camera";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useState } from "react";
import { Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner";
import { dismissRoute } from "../../lib/routes";
import { ConnectionSheetButton } from "./ConnectionSheetButton";
import { extractPairingUrlFromQrPayload } from "./pairing";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { buildPairingUrl, parsePairingUrl } from "./pairing";
export function NewConnectionRouteScreen() {
const {
connectionPairingUrl,
onChangeConnectionPairingUrl,
onConnectPress,
pairingConnectionError,
} = useRemoteConnections();
const router = useRouter();
const params = useLocalSearchParams<{ mode?: string }>();
const insets = useSafeAreaInsets();
const [hostInput, setHostInput] = useState("");
const [codeInput, setCodeInput] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [showScanner, setShowScanner] = useState(params.mode === "scan_qr");
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
const [scannerLocked, setScannerLocked] = useState(false);
const textColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
useEffect(() => {
const { host, code } = parsePairingUrl(connectionPairingUrl);
setHostInput(host);
setCodeInput(code);
}, [connectionPairingUrl]);
useEffect(() => {
if (pairingConnectionError) {
setIsSubmitting(false);
}
}, [pairingConnectionError]);
const handleHostChange = useCallback((value: string) => {
setHostInput(value);
}, []);
const handleCodeChange = useCallback((value: string) => {
setCodeInput(value);
}, []);
const openScanner = useCallback(async () => {
if (cameraPermission?.granted) {
setScannerLocked(false);
setShowScanner(true);
return;
}
const permission = await requestCameraPermission();
if (permission.granted) {
setScannerLocked(false);
setShowScanner(true);
return;
}
Alert.alert(
"Camera access needed",
"Allow camera access to scan an environment pairing QR code.",
);
}, [cameraPermission?.granted, requestCameraPermission]);
const closeScanner = useCallback(() => {
setShowScanner(false);
setScannerLocked(false);
}, []);
const handleQrScan = useCallback(
({ data }: { readonly data: string }) => {
if (scannerLocked) {
return;
}
setScannerLocked(true);
try {
const pairingUrl = extractPairingUrlFromQrPayload(data);
const { host, code } = parsePairingUrl(pairingUrl);
setHostInput(host);
setCodeInput(code);
onChangeConnectionPairingUrl(pairingUrl);
setShowScanner(false);
} catch (error) {
Alert.alert(
"Invalid QR code",
error instanceof Error ? error.message : "Scanned QR code was not recognized.",
);
} finally {
setTimeout(() => {
setScannerLocked(false);
}, 600);
}
},
[onChangeConnectionPairingUrl, scannerLocked],
);
const handleSubmit = useCallback(async () => {
setIsSubmitting(true);
try {
const pairingUrl = buildPairingUrl(hostInput, codeInput);
onChangeConnectionPairingUrl(pairingUrl);
await onConnectPress(pairingUrl);
dismissRoute(router);
} catch {
setIsSubmitting(false);
}
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: showScanner ? "Scan QR Code" : "Add Environment",
headerRight: () => (
<Pressable
className="h-10 w-10 items-center justify-center rounded-full border border-border bg-secondary"
onPress={() => {
if (showScanner) {
closeScanner();
} else {
void openScanner();
}
}}
>
<SymbolView
name={showScanner ? "xmark" : "qrcode.viewfinder"}
size={showScanner ? 14 : 18}
tintColor={textColor}
type="monochrome"
weight="semibold"
/>
</Pressable>
),
}}
/>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 16,
}}
>
<View collapsable={false} className="gap-5">
{showScanner ? (
cameraPermission?.granted ? (
<View
className="overflow-hidden rounded-[24px]"
style={{ borderCurve: "continuous" }}
>
<CameraView
barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
onBarcodeScanned={handleQrScan}
style={{ aspectRatio: 1, width: "100%" }}
/>
</View>
) : (
<View
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
style={{ borderCurve: "continuous" }}
>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Camera permission is required to scan a QR code.
</Text>
<ConnectionSheetButton
compact
icon="camera"
label="Allow camera"
tone="secondary"
onPress={() => {
void openScanner();
}}
/>
</View>
)
) : (
<View collapsable={false} className="gap-4 rounded-[24px] bg-card p-4">
<View collapsable={false} className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Host
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={hostInput}
onChangeText={handleHostChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
/>
</View>
<View collapsable={false} className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Pairing code
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
placeholder="abc-123-xyz"
placeholderTextColor={placeholderColor}
value={codeInput}
onChangeText={handleCodeChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
/>
</View>
{pairingConnectionError ? <ErrorBanner message={pairingConnectionError} /> : null}
<ConnectionSheetButton
icon="plus"
label={isSubmitting ? "Pairing..." : "Add environment"}
disabled={connectDisabled}
tone="primary"
onPress={() => {
void handleSubmit();
}}
/>
</View>
)}
</View>
</ScrollView>
</View>
);
}
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { extractPairingUrlFromQrPayload } from "./pairing";
import { extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
describe("extractPairingUrlFromQrPayload", () => {
it("trims raw pairing urls from qr payloads", () => {
@@ -23,3 +23,16 @@ describe("extractPairingUrlFromQrPayload", () => {
);
});
});
describe("parsePairingUrl", () => {
it("reads hosted pairing links into backend host fields", () => {
expect(
parsePairingUrl(
"https://app.t3.codes/pair?host=https%3A%2F%2Fdesktop.tailnet.ts.net%2F#token=pairing-token",
),
).toEqual({
host: "https://desktop.tailnet.ts.net",
code: "pairing-token",
});
});
});
@@ -1,3 +1,5 @@
import { readHostedPairingRequest } from "@t3tools/shared/remote";
const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
export function buildPairingUrl(host: string, code: string): string {
@@ -21,6 +23,14 @@ export function parsePairingUrl(url: string): { host: string; code: string } {
try {
const parsed = new URL(trimmed);
const hostedPairingRequest = readHostedPairingRequest(parsed);
if (hostedPairingRequest) {
return {
host: hostedPairingRequest.host.replace(/\/$/, ""),
code: hostedPairingRequest.token,
};
}
const hashParams = new URLSearchParams(parsed.hash.slice(1));
const hashToken = hashParams.get("token");
const queryToken = parsed.searchParams.get("token");
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const expoModulesCoreMocks = vi.hoisted(() => ({
requireNativeViewManager: vi.fn(),
const expoMocks = vi.hoisted(() => ({
requireNativeView: vi.fn(),
}));
const nativeView = () => null;
const originalExpo = globalThis.expo;
@@ -12,8 +12,8 @@ function setExpoViewConfigAvailable() {
} as unknown as typeof globalThis.expo;
}
vi.mock("expo-modules-core", () => ({
requireNativeViewManager: expoModulesCoreMocks.requireNativeViewManager,
vi.mock("expo", () => ({
requireNativeView: expoMocks.requireNativeView,
}));
describe("resolveNativeReviewDiffView", () => {
@@ -30,17 +30,15 @@ describe("resolveNativeReviewDiffView", () => {
it("returns null when the native review diff view config is unavailable", async () => {
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
expect(resolveNativeReviewDiffView()).toBeNull();
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
expect(expoMocks.requireNativeView).not.toHaveBeenCalled();
});
it("returns the native review diff view when the view config is installed", async () => {
setExpoViewConfigAvailable();
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
expoMocks.requireNativeView.mockReturnValue(nativeView);
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
expect(resolveNativeReviewDiffView()).toBe(nativeView);
expect(expoModulesCoreMocks.requireNativeViewManager).toHaveBeenCalledWith(
"T3ReviewDiffSurface",
);
expect(expoMocks.requireNativeView).toHaveBeenCalledWith("T3ReviewDiffSurface");
});
it("does not fall back to stale legacy native review diff view names", async () => {
@@ -52,15 +50,15 @@ describe("resolveNativeReviewDiffView", () => {
return null;
}),
} as unknown as typeof globalThis.expo;
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
expoMocks.requireNativeView.mockReturnValue(nativeView);
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
expect(resolveNativeReviewDiffView()).toBeNull();
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
expect(expoMocks.requireNativeView).not.toHaveBeenCalled();
});
it("returns null when the view manager cannot be required", async () => {
setExpoViewConfigAvailable();
expoModulesCoreMocks.requireNativeViewManager.mockImplementation(() => {
expoMocks.requireNativeView.mockImplementation(() => {
throw new Error("boom");
});
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
@@ -1,6 +1,6 @@
import type { ComponentType } from "react";
import type { NativeSyntheticEvent, ViewProps } from "react-native";
import { requireNativeViewManager } from "expo-modules-core";
import { requireNativeView } from "expo";
const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
@@ -144,7 +144,7 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
}
try {
cachedNativeReviewDiffView = requireNativeViewManager<NativeReviewDiffViewProps>(
cachedNativeReviewDiffView = requireNativeView<NativeReviewDiffViewProps>(
NATIVE_REVIEW_DIFF_MODULE_NAME,
);
} catch {
@@ -29,7 +29,6 @@ import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ControlPill } from "../../components/ControlPill";
import { ErrorBanner } from "../../components/ErrorBanner";
import { SourceControlIcon } from "../../components/SourceControlIcon";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -42,6 +41,7 @@ import {
refreshSourceControlDiscoveryForEnvironment,
useSourceControlDiscovery,
} from "../../state/use-source-control-discovery";
import { NewTaskSheetHeader } from "../threads/NewTaskSheetHeader";
interface EnvironmentOption {
readonly environmentId: EnvironmentId;
@@ -115,21 +115,21 @@ function AddProjectShell(props: {
return (
<View className="flex-1 bg-sheet">
<View className="flex-row items-center justify-between px-5 pb-1 pt-3">
<ControlPill
icon={props.closeToNew ? "xmark" : "chevron.left"}
onPress={() => router.back()}
/>
<Text className="text-[17px] font-t3-bold">{props.title}</Text>
<View className="h-11 w-11" />
</View>
<NewTaskSheetHeader
eyebrow="New project"
title={props.title}
control={{
icon: props.closeToNew ? "xmark" : "chevron.left",
onPress: () => router.back(),
}}
/>
<ScrollView
keyboardShouldPersistTaps="handled"
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
paddingHorizontal: 18,
paddingTop: 8,
paddingHorizontal: 20,
paddingTop: 16,
paddingBottom: Math.max(insets.bottom, 18) + 18,
gap: 10,
}}
@@ -141,7 +141,7 @@ function AddProjectShell(props: {
}
function ListSection(props: { readonly children: ReactNode }) {
return <View className="overflow-hidden rounded-2xl bg-card">{props.children}</View>;
return <View className="overflow-hidden rounded-[24px] bg-card">{props.children}</View>;
}
function ListRow(props: {
@@ -196,6 +196,48 @@ function ListRow(props: {
);
}
function PrimaryActionButton(props: {
readonly label: string;
readonly disabled?: boolean;
readonly loading?: boolean;
readonly onPress: () => void;
}) {
const primaryForeground = useThemeColor("--color-primary-foreground");
return (
<Pressable
disabled={props.disabled}
onPress={props.onPress}
className="h-12 items-center justify-center rounded-full bg-primary active:opacity-70 disabled:opacity-45"
>
{props.loading ? (
<ActivityIndicator color={String(primaryForeground)} />
) : (
<Text className="text-[14px] font-t3-bold text-primary-foreground">{props.label}</Text>
)}
</Pressable>
);
}
function ProjectPathInput(props: {
readonly value: string;
readonly onChangeText: (value: string) => void;
readonly onSubmit: () => void;
}) {
return (
<TextInput
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-[15px] leading-[20px]"
value={props.value}
onChangeText={props.onChangeText}
autoCapitalize="none"
autoCorrect={false}
placeholder="~/projects/my-app"
returnKeyType="done"
onSubmitEditing={props.onSubmit}
/>
);
}
function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
const { serverConfigByEnvironmentId } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
@@ -321,7 +363,7 @@ export function AddProjectSourceScreen() {
}, [selectedEnvironment]);
return (
<AddProjectShell title="Add project" closeToNew>
<AddProjectShell title="Select source" closeToNew>
{environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null}
{environmentOptions.length > 1 ? (
@@ -362,7 +404,6 @@ export function AddProjectSourceScreen() {
{selectedEnvironment ? (
<>
<SectionTitle>Sources</SectionTitle>
<ListSection>
<ListRow
title="Local folder"
@@ -473,7 +514,6 @@ export function AddProjectRepositoryScreen() {
const params = useLocalSearchParams<{ environmentId?: string; source?: string }>();
const environment = useEnvironmentFromParam();
const source = sourceFromParam(params.source);
const primaryForeground = useThemeColor("--color-primary-foreground");
const [repositoryInput, setRepositoryInput] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -524,7 +564,7 @@ export function AddProjectRepositoryScreen() {
<AddProjectShell title={source === "url" ? "Git URL" : addProjectRemoteSourceLabel(source)}>
{error ? <ErrorBanner message={error} /> : null}
<TextInput
className="h-12 min-h-12 rounded-xl px-3 py-0 text-[15px] leading-[20px]"
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-[15px] leading-[20px]"
value={repositoryInput}
onChangeText={setRepositoryInput}
autoCapitalize="none"
@@ -537,19 +577,12 @@ export function AddProjectRepositoryScreen() {
returnKeyType="next"
onSubmitEditing={() => void lookupRepository()}
/>
<Pressable
<PrimaryActionButton
label={source === "url" ? "Continue" : "Lookup repository"}
disabled={isSubmitting || repositoryInput.trim().length === 0}
onPress={() => void lookupRepository()}
className="h-11 items-center justify-center rounded-full bg-primary active:opacity-70 disabled:opacity-45"
>
{isSubmitting ? (
<ActivityIndicator color={String(primaryForeground)} />
) : (
<Text className="text-[14px] font-t3-bold text-primary-foreground">
{source === "url" ? "Continue" : "Lookup repository"}
</Text>
)}
</Pressable>
loading={isSubmitting}
/>
</AddProjectShell>
);
}
@@ -643,7 +676,6 @@ function FolderBrowser(props: {
export function AddProjectLocalFolderScreen() {
const environment = useEnvironmentFromParam();
const createProject = useCreateProject(environment);
const primaryForeground = useThemeColor("--color-primary-foreground");
const [pathInput, setPathInput] = useState(() =>
getAddProjectInitialQuery(environment?.baseDirectory),
);
@@ -683,27 +715,17 @@ export function AddProjectLocalFolderScreen() {
{error ? <ErrorBanner message={error} /> : null}
{environment ? (
<>
<TextInput
className="h-12 min-h-12 rounded-xl px-3 py-0 text-[15px] leading-[20px]"
<ProjectPathInput
value={pathInput}
onChangeText={setPathInput}
autoCapitalize="none"
autoCorrect={false}
placeholder="~/projects/my-app"
returnKeyType="done"
onSubmitEditing={() => void submitPath()}
onSubmit={() => void submitPath()}
/>
<Pressable
<PrimaryActionButton
label="Add project"
disabled={isSubmitting}
onPress={() => void submitPath()}
className="h-11 items-center justify-center rounded-full bg-primary active:opacity-70"
>
{isSubmitting ? (
<ActivityIndicator color={String(primaryForeground)} />
) : (
<Text className="text-[14px] font-t3-bold text-primary-foreground">Add project</Text>
)}
</Pressable>
loading={isSubmitting}
/>
<FolderBrowser
environment={environment}
pathInput={pathInput}
@@ -725,7 +747,6 @@ export function AddProjectDestinationScreen() {
}>();
const environment = useEnvironmentFromParam();
const createProject = useCreateProject(environment);
const primaryForeground = useThemeColor("--color-primary-foreground");
const remoteUrl = stringParam(params.remoteUrl);
const repositoryTitle = stringParam(params.repositoryTitle);
const [pathInput, setPathInput] = useState(() =>
@@ -772,7 +793,7 @@ export function AddProjectDestinationScreen() {
<AddProjectShell title="Clone destination">
{error ? <ErrorBanner message={error} /> : null}
{repositoryTitle ? (
<View className="rounded-xl bg-card px-3.5 py-2.5">
<View className="rounded-[24px] bg-card px-4 py-3">
<Text className="text-[14px] font-t3-bold">{repositoryTitle}</Text>
<Text className="mt-0.5 text-[12px] text-foreground-muted" numberOfLines={2}>
{remoteUrl}
@@ -781,29 +802,17 @@ export function AddProjectDestinationScreen() {
) : null}
{environment ? (
<>
<TextInput
className="h-12 min-h-12 rounded-xl px-3 py-0 text-[15px] leading-[20px]"
<ProjectPathInput
value={pathInput}
onChangeText={setPathInput}
autoCapitalize="none"
autoCorrect={false}
placeholder="~/projects/my-app"
returnKeyType="done"
onSubmitEditing={() => void submitPath()}
onSubmit={() => void submitPath()}
/>
<Pressable
<PrimaryActionButton
label="Clone project"
disabled={isSubmitting || !remoteUrl}
onPress={() => void submitPath()}
className="h-11 items-center justify-center rounded-full bg-primary active:opacity-70 disabled:opacity-45"
>
{isSubmitting ? (
<ActivityIndicator color={String(primaryForeground)} />
) : (
<Text className="text-[14px] font-t3-bold text-primary-foreground">
Clone project
</Text>
)}
</Pressable>
loading={isSubmitting}
/>
<FolderBrowser
environment={environment}
pathInput={pathInput}
@@ -2,9 +2,9 @@ import { useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { TextInputWrapper } from "expo-paste-input";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";
import { KeyboardStickyView } from "react-native-keyboard-controller";
import { KeyboardAvoidingView } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import ImageViewing from "react-native-image-viewing";
@@ -82,6 +82,10 @@ export function ReviewCommentComposerSheet() {
REVIEW_DIFF_LINE_HEIGHT,
);
const previewViewportWidth = Math.max(width - 40, 280);
const dismissComposer = useCallback(() => {
clearReviewCommentTarget();
router.dismiss();
}, [router]);
const handleNativePaste = useNativePaste((uris) => {
void (async () => {
try {
@@ -138,150 +142,147 @@ export function ReviewCommentComposerSheet() {
return (
<View style={{ flex: 1 }}>
<View
style={{
flex: 1,
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 82,
}}
>
<View className="flex-row items-center justify-between py-2">
<Pressable
className="bg-subtle h-12 w-12 items-center justify-center rounded-full"
onPress={() => {
clearReviewCommentTarget();
router.dismiss();
}}
>
<SymbolView name="xmark" size={18} tintColor={iconTint} type="monochrome" />
</Pressable>
<KeyboardAvoidingView automaticOffset behavior="padding" style={{ flex: 1 }}>
<View
style={{
flex: 1,
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: target ? 0 : Math.max(insets.bottom, 18),
}}
>
<View className="flex-row items-center justify-between py-2">
<Pressable
className="bg-subtle h-12 w-12 items-center justify-center rounded-full"
onPress={dismissComposer}
>
<SymbolView name="xmark" size={18} tintColor={iconTint} type="monochrome" />
</Pressable>
<Text className="text-[18px] font-t3-bold text-foreground">Add Comment</Text>
<Text className="text-[18px] font-t3-bold text-foreground">Add Comment</Text>
<View className="h-12 w-12" />
</View>
{!target ? (
<View className="rounded-[22px] border border-border bg-card px-4 py-5">
<Text className="text-[15px] font-t3-bold text-foreground">No selection</Text>
<Text className="mt-1 text-[13px] leading-[19px] text-foreground-muted">
Select a diff line or range first.
</Text>
<View className="h-12 w-12" />
</View>
) : (
<View className="flex-1 gap-4">
<View className="gap-1 px-1">
<Text className="text-[11px] font-t3-bold uppercase text-foreground-muted">
{selectionLabel}
</Text>
<Text
className="font-mono text-[12px] leading-[17px] text-foreground-muted"
ellipsizeMode="middle"
numberOfLines={2}
>
{target.filePath}
{!target ? (
<View className="rounded-[22px] border border-border bg-card px-4 py-5">
<Text className="text-[15px] font-t3-bold text-foreground">No selection</Text>
<Text className="mt-1 text-[13px] leading-[19px] text-foreground-muted">
Select a diff line or range first.
</Text>
</View>
<View className="overflow-hidden rounded-[22px] border border-border bg-card">
<ScrollView
horizontal
bounces={false}
keyboardShouldPersistTaps="always"
showsHorizontalScrollIndicator={false}
>
<ScrollView
bounces={false}
scrollEnabled={selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES}
nestedScrollEnabled
keyboardShouldPersistTaps="always"
showsVerticalScrollIndicator={
selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES
}
style={{ height: previewHeight }}
) : (
<View className="min-h-0 flex-1 gap-4">
<View className="gap-1 px-1">
<Text className="text-[11px] font-t3-bold uppercase text-foreground-muted">
{selectionLabel}
</Text>
<Text
className="font-mono text-[12px] leading-[17px] text-foreground-muted"
ellipsizeMode="middle"
numberOfLines={2}
>
<View style={{ minWidth: previewViewportWidth }}>
{selectedLines.map((line) => {
const lineNumber = getReviewUnifiedLineNumber(line);
{target.filePath}
</Text>
</View>
return (
<View
key={line.id}
className={cn("flex-row items-start", changeTone(line.change))}
style={{ height: REVIEW_DIFF_LINE_HEIGHT }}
>
<ReviewChangeBar change={line.change} />
<Text
className="w-9 py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
<View className="overflow-hidden rounded-[22px] border border-border bg-card">
<ScrollView
horizontal
bounces={false}
keyboardShouldPersistTaps="always"
showsHorizontalScrollIndicator={false}
>
<ScrollView
bounces={false}
scrollEnabled={selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES}
nestedScrollEnabled
keyboardShouldPersistTaps="always"
showsVerticalScrollIndicator={
selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES
}
style={{ height: previewHeight }}
>
<View style={{ minWidth: previewViewportWidth }}>
{selectedLines.map((line) => {
const lineNumber = getReviewUnifiedLineNumber(line);
return (
<View
key={line.id}
className={cn("flex-row items-start", changeTone(line.change))}
style={{ height: REVIEW_DIFF_LINE_HEIGHT }}
>
{lineNumber ?? ""}
</Text>
<View className="min-w-0 flex-1 shrink-0 px-1 py-1">
<DiffTokenText
fallback={line.content}
tokens={highlightedLinesById[line.id] ?? null}
change={line.change}
/>
<ReviewChangeBar change={line.change} />
<Text
className="w-9 py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
>
{lineNumber ?? ""}
</Text>
<View className="min-w-0 flex-1 shrink-0 px-1 py-1">
<DiffTokenText
fallback={line.content}
tokens={highlightedLinesById[line.id] ?? null}
change={line.change}
/>
</View>
</View>
</View>
);
})}
</View>
</ScrollView>
</ScrollView>
</View>
<View className="gap-2">
<Text className="text-[13px] font-t3-bold text-foreground">Comment</Text>
<View
className="overflow-hidden rounded-[20px] border border-border bg-card"
style={{ height: 172 }}
>
<View className="flex-1 px-4 pt-3.5">
<TextInputWrapper onPaste={handleNativePaste}>
<TextInput
autoFocus
multiline
placeholder="Leave a comment..."
textAlignVertical="top"
value={commentText}
onChangeText={setCommentText}
className="flex-1 border-0 bg-transparent px-0 py-0 font-sans text-[15px]"
/>
</TextInputWrapper>
</View>
{attachments.length > 0 ? (
<View className="px-4 pb-3 pt-2">
<ComposerAttachmentStrip
attachments={attachments}
imageBorderRadius={16}
imageSize={60}
onPressImage={setPreviewImageUri}
removeButtonPlacement="gutter"
onRemove={(imageId) => {
setAttachments((current) =>
current.filter((image) => image.id !== imageId),
);
}}
/>
})}
</View>
</ScrollView>
</ScrollView>
</View>
<View className="min-h-0 flex-1 gap-2">
<Text className="text-[13px] font-t3-bold text-foreground">Comment</Text>
<View className="min-h-[132px] flex-1 overflow-hidden rounded-[20px] border border-border bg-card">
<View className="flex-1 px-4 pt-3.5">
<TextInputWrapper onPaste={handleNativePaste} style={{ flex: 1 }}>
<TextInput
autoFocus
multiline
placeholder="Leave a comment..."
textAlignVertical="top"
value={commentText}
onChangeText={setCommentText}
className="h-full flex-1 border-0 bg-transparent px-0 py-0 font-sans text-[15px]"
style={{ flex: 1 }}
/>
</TextInputWrapper>
</View>
) : null}
{attachments.length > 0 ? (
<View className="px-4 pb-3 pt-2">
<ComposerAttachmentStrip
attachments={attachments}
imageBorderRadius={16}
imageSize={60}
onPressImage={setPreviewImageUri}
removeButtonPlacement="gutter"
onRemove={(imageId) => {
setAttachments((current) =>
current.filter((image) => image.id !== imageId),
);
}}
/>
</View>
) : null}
</View>
</View>
</View>
</View>
)}
</View>
{target ? (
<KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
<View
className="flex-row items-center gap-3 bg-sheet px-5 pt-3"
style={{ paddingBottom: Math.max(insets.bottom, 18) }}
>
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
)}
</View>
{target ? (
<View className="flex-row items-center gap-3 bg-sheet px-5 py-2">
<ControlPill
accessibilityLabel="Add image"
icon="plus"
onPress={() => void handlePickImages()}
/>
<View className="flex-1" />
<ControlPill
accessibilityLabel="Comment"
icon="arrow.up"
label="Comment"
variant="primary"
@@ -298,13 +299,12 @@ export function ReviewCommentComposerSheet() {
attachments,
});
setAttachments([]);
clearReviewCommentTarget();
router.dismiss();
dismissComposer();
}}
/>
</View>
</KeyboardStickyView>
) : null}
) : null}
</KeyboardAvoidingView>
<ImageViewing
images={previewImageUri ? [{ uri: previewImageUri }] : []}
imageIndex={0}
@@ -83,13 +83,13 @@ function ReviewSelectionActionBar(props: {
>
{props.onOpenComment ? (
<Pressable
className="min-h-[48px] flex-1 flex-row items-center justify-center gap-2 rounded-full bg-blue-600 px-5"
className="h-12 flex-1 flex-row items-center justify-center gap-2 rounded-full bg-blue-600 px-5"
onPress={props.onOpenComment}
>
{content}
</Pressable>
) : (
<View className="min-h-[48px] flex-1 flex-row items-center justify-center gap-2 rounded-full bg-blue-600 px-5">
<View className="h-12 flex-1 flex-row items-center justify-center gap-2 rounded-full bg-blue-600 px-5">
{content}
</View>
)}
@@ -353,7 +353,7 @@ export function ReviewSheet() {
key={`${reviewCache.threadKey}:${selectedSection.id}`}
collapsable={false}
testID="review-native-diff-view"
style={StyleSheet.absoluteFillObject}
style={StyleSheet.absoluteFill}
appearanceScheme={selectedTheme}
collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson}
collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson}
@@ -1,4 +1,4 @@
import { memo, useCallback, useEffect } from "react";
import { memo, useCallback, useEffect, useRef } from "react";
import {
Pressable,
ScrollView,
@@ -33,6 +33,7 @@ interface TerminalSurfaceProps extends ViewProps {
readonly buffer: string;
readonly fontSize?: number;
readonly isRunning: boolean;
readonly keyboardFocusRequest?: number;
readonly theme?: TerminalTheme;
readonly onInput: (data: string) => void;
readonly onResize: (size: { readonly cols: number; readonly rows: number }) => void;
@@ -53,6 +54,7 @@ function estimateGridSize(input: {
const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: TerminalSurfaceProps) {
const fontSize = props.fontSize ?? 12;
const inputRef = useRef<TextInput>(null);
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme);
const statusLabel = props.isRunning
@@ -64,6 +66,16 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
props.onResize(estimateGridSize({ width, height, fontSize }));
};
useEffect(() => {
if ((props.keyboardFocusRequest ?? 0) > 0) {
inputRef.current?.blur();
const focusFrame = requestAnimationFrame(() => inputRef.current?.focus());
return () => cancelAnimationFrame(focusFrame);
}
return undefined;
}, [props.keyboardFocusRequest]);
return (
<View
style={[
@@ -116,6 +128,7 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
}}
>
<TextInput
ref={inputRef}
autoCapitalize="none"
autoCorrect={false}
blurOnSubmit={false}
@@ -165,6 +178,7 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
const fontSize = props.fontSize ?? 12;
const keyboardInputRef = useRef<TextInput>(null);
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme);
const { onInput, onResize } = props;
@@ -195,21 +209,61 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
[onResize],
);
// Reopen focus through React and forward input normally; this avoids a native focus-command bridge.
useEffect(() => {
if (!NativeTerminalSurfaceView || (props.keyboardFocusRequest ?? 0) <= 0) {
return undefined;
}
keyboardInputRef.current?.blur();
const focusFrame = requestAnimationFrame(() => keyboardInputRef.current?.focus());
return () => cancelAnimationFrame(focusFrame);
}, [NativeTerminalSurfaceView, props.keyboardFocusRequest]);
const handleKeyboardInput = useCallback(
(data: string) => {
if (data.length > 0) {
onInput(data);
keyboardInputRef.current?.clear();
}
},
[onInput],
);
if (NativeTerminalSurfaceView) {
return (
<NativeTerminalSurfaceView
{...props}
appearanceScheme={appearanceScheme}
backgroundColor={theme.background}
foregroundColor={theme.foreground}
mutedForegroundColor={theme.mutedForeground}
terminalKey={props.terminalKey}
initialBuffer={props.buffer}
fontSize={fontSize}
themeConfig={buildGhosttyThemeConfig(theme)}
onInput={handleNativeInput}
onResize={handleNativeResize}
/>
<View style={props.style}>
<NativeTerminalSurfaceView
appearanceScheme={appearanceScheme}
backgroundColor={theme.background}
foregroundColor={theme.foreground}
mutedForegroundColor={theme.mutedForeground}
terminalKey={props.terminalKey}
initialBuffer={props.buffer}
fontSize={fontSize}
style={{ flex: 1 }}
themeConfig={buildGhosttyThemeConfig(theme)}
onInput={handleNativeInput}
onResize={handleNativeResize}
/>
<TextInput
ref={keyboardInputRef}
autoCapitalize="none"
autoCorrect={false}
blurOnSubmit={false}
caretHidden
editable={props.isRunning}
keyboardType="ascii-capable"
style={{ bottom: 0, height: 1, left: 0, opacity: 0.01, position: "absolute", width: 1 }}
onChangeText={handleKeyboardInput}
onKeyPress={(event) => {
if (event.nativeEvent.key === "Backspace") {
onInput("\u007f");
}
}}
onSubmitEditing={() => onInput("\n")}
/>
</View>
);
}
@@ -0,0 +1,175 @@
import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { getEnvironmentClient } from "../../state/environment-session-registry";
import {
attachTerminalSession,
useTerminalSession,
useTerminalSessionTarget,
} from "../../state/use-terminal-session";
import { TerminalSurface } from "./NativeTerminalSurface";
import { hasNativeTerminalSurface } from "./nativeTerminalModule";
import { terminalDebugLog } from "./terminalDebugLog";
interface ThreadTerminalPanelProps {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly cwd: string;
readonly worktreePath: string | null;
readonly visible: boolean;
readonly onClose: () => void;
}
const DEFAULT_TERMINAL_COLS = 80;
const DEFAULT_TERMINAL_ROWS = 24;
export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
props: ThreadTerminalPanelProps,
) {
const nativeTerminalAvailable = hasNativeTerminalSurface();
const terminalId = DEFAULT_TERMINAL_ID;
const target = useTerminalSessionTarget({
environmentId: props.environmentId,
threadId: props.threadId,
terminalId,
});
const terminal = useTerminalSession(target);
const [lastGridSize, setLastGridSize] = useState({
cols: DEFAULT_TERMINAL_COLS,
rows: DEFAULT_TERMINAL_ROWS,
});
const lastGridSizeRef = useRef(lastGridSize);
lastGridSizeRef.current = lastGridSize;
const terminalKey = `${props.environmentId}:${props.threadId}:${terminalId}`;
const isRunning = terminal.status === "running" || terminal.status === "starting";
useEffect(() => {
if (!props.visible) {
return;
}
const client = getEnvironmentClient(props.environmentId);
if (!client) {
terminalDebugLog("panel:attach-skip", {
reason: "no-environment-client",
environmentId: props.environmentId,
});
return;
}
terminalDebugLog("panel:attach", {
environmentId: props.environmentId,
threadId: props.threadId,
terminalId,
});
return attachTerminalSession({
environmentId: props.environmentId,
client,
terminal: {
threadId: props.threadId,
terminalId,
cwd: props.cwd,
worktreePath: props.worktreePath,
cols: lastGridSizeRef.current.cols,
rows: lastGridSizeRef.current.rows,
},
});
}, [
props.cwd,
props.environmentId,
props.threadId,
props.worktreePath,
props.visible,
terminalId,
]);
const handleInput = useCallback(
(data: string) => {
const client = getEnvironmentClient(props.environmentId);
if (!client || !isRunning) {
return;
}
void client.terminal.write({
threadId: props.threadId,
terminalId,
data,
});
},
[isRunning, props.environmentId, props.threadId, terminalId],
);
const handleResize = useCallback(
(size: { readonly cols: number; readonly rows: number }) => {
if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
return;
}
setLastGridSize(size);
const client = getEnvironmentClient(props.environmentId);
if (!client || !isRunning) {
return;
}
void client.terminal.resize({
threadId: props.threadId,
terminalId,
cols: size.cols,
rows: size.rows,
});
},
[
isRunning,
lastGridSize.cols,
lastGridSize.rows,
props.environmentId,
props.threadId,
terminalId,
],
);
if (!props.visible) {
return null;
}
return (
<View className="absolute inset-x-3 bottom-28 top-28 overflow-hidden rounded-[8px] border border-white/10 bg-neutral-950 shadow-2xl">
<View className="flex-row items-center justify-between border-b border-white/10 px-3 py-2">
<View className="min-w-0 flex-1">
<Text className="font-t3-bold text-[13px] text-neutral-100" numberOfLines={1}>
Terminal
</Text>
<Text className="text-[11px] text-neutral-500" numberOfLines={1}>
{nativeTerminalAvailable ? "Native Ghostty surface" : "Text fallback active"}
</Text>
</View>
<View className="flex-row items-center gap-2">
{terminal.error ? (
<Text className="max-w-44 text-right text-[11px] text-red-300" numberOfLines={1}>
{terminal.error}
</Text>
) : null}
<Pressable
className="h-8 w-8 items-center justify-center rounded-[8px] bg-white/10"
onPress={props.onClose}
>
<SymbolView name="xmark" size={13} tintColor="#e5e5e5" type="monochrome" />
</Pressable>
</View>
</View>
<TerminalSurface
terminalKey={terminalKey}
buffer={terminal.buffer}
isRunning={isRunning}
onInput={handleInput}
onResize={handleResize}
style={{ flex: 1 }}
/>
</View>
);
});
@@ -5,12 +5,28 @@ import {
ThreadId,
} from "@t3tools/contracts";
import type { KnownTerminalSession } from "@t3tools/client-runtime";
import { SymbolView } from "expo-symbols";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
import { KeyboardStickyView } from "react-native-keyboard-controller";
import {
Pressable,
ScrollView,
Text as RNText,
View,
useColorScheme,
type LayoutChangeEvent,
type NativeScrollEvent,
type NativeSyntheticEvent,
} from "react-native";
import {
KeyboardController,
KeyboardEvents,
KeyboardStickyView,
useKeyboardState,
} from "react-native-keyboard-controller";
import { EmptyState } from "../../components/EmptyState";
import { GlassSurface } from "../../components/GlassSurface";
import { LoadingScreen } from "../../components/LoadingScreen";
import { buildThreadTerminalNavigation } from "../../lib/routes";
import { getEnvironmentClient } from "../../state/environment-session-registry";
@@ -63,12 +79,14 @@ import {
const DEFAULT_TERMINAL_COLS = 80;
const DEFAULT_TERMINAL_ROWS = 24;
const TERMINAL_ACCESSORY_HEIGHT = 52;
const TERMINAL_ACCESSORY_FADE_WIDTH = 18;
type PendingModifier = "ctrl" | "meta";
type HostPlatform = "mac" | "linux" | "windows" | "unknown";
type TerminalToolbarAction =
| { readonly kind: "send"; readonly key: string; readonly label: string; readonly data: string }
| { readonly kind: "clear"; readonly key: string; readonly label: string }
| {
readonly kind: "modifier";
readonly key: string;
@@ -228,6 +246,17 @@ export function ThreadTerminalRouteScreen() {
},
);
const [fontSize, setFontSize] = useState(cachedFontSize ?? DEFAULT_TERMINAL_FONT_SIZE);
const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false);
const toolbarScrollGeometryRef = useRef({
contentWidth: 0,
offsetX: 0,
viewportWidth: 0,
});
const [toolbarScrollEdges, setToolbarScrollEdges] = useState({
showLeftFade: false,
showRightFade: false,
});
const hasOpenedRef = useRef(false);
const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const attachStreamLogCountRef = useRef(0);
@@ -384,6 +413,7 @@ export function ThreadTerminalRouteScreen() {
{ kind: "send", key: "esc", label: "esc", data: "\u001b" },
...modifierActions,
{ kind: "send", key: "tab", label: "tab", data: "\t" },
{ kind: "clear", key: "clear", label: "clear" },
{ kind: "send", key: "up", label: "↑", data: "\u001b[A" },
{ kind: "send", key: "down", label: "↓", data: "\u001b[B" },
{ kind: "send", key: "left", label: "←", data: "\u001b[D" },
@@ -394,7 +424,28 @@ export function ThreadTerminalRouteScreen() {
{ kind: "send", key: "dash", label: "-", data: "-" },
];
}, [hostPlatform]);
const terminalBottomInset = TERMINAL_ACCESSORY_HEIGHT;
const keyboardState = useKeyboardState((state) => ({
height: state.height,
isVisible: state.isVisible,
}));
const isAccessoryVisible = keyboardState.isVisible && !isAccessoryDismissed;
const terminalBottomInset =
(keyboardState.isVisible ? keyboardState.height : 0) +
(isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);
useEffect(() => {
const keyboardWillShow = KeyboardEvents.addListener("keyboardWillShow", () => {
setIsAccessoryDismissed(false);
});
const keyboardWillHide = KeyboardEvents.addListener("keyboardWillHide", () => {
setIsAccessoryDismissed(true);
});
return () => {
keyboardWillShow.remove();
keyboardWillHide.remove();
};
}, []);
const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
() =>
@@ -725,7 +776,6 @@ export function ThreadTerminalRouteScreen() {
router,
selectedThread?.environmentId,
selectedThread?.id,
selectedThreadDetail?.worktreePath,
selectedThreadProject?.workspaceRoot,
terminalId,
]);
@@ -867,6 +917,23 @@ export function ThreadTerminalRouteScreen() {
adjustFontSize(TERMINAL_FONT_SIZE_STEP);
}, [adjustFontSize]);
const handleClearTerminal = useCallback(() => {
if (!selectedThread) {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
setPendingModifierState({ terminalId, value: null });
void client.terminal.clear({
threadId: selectedThread.id,
terminalId,
});
}, [selectedThread, terminalId]);
const handleToolbarActionPress = useCallback(
(action: TerminalToolbarAction) => {
if (action.kind === "modifier") {
@@ -880,6 +947,11 @@ export function ThreadTerminalRouteScreen() {
return;
}
if (action.kind === "clear") {
handleClearTerminal();
return;
}
setPendingModifierState({ terminalId, value: null });
if (pendingModifier === "ctrl") {
writeInput(applyCtrlModifier(action.data));
@@ -889,9 +961,59 @@ export function ThreadTerminalRouteScreen() {
writeInput(action.data);
}
},
[pendingModifier, terminalId, writeInput],
[handleClearTerminal, pendingModifier, terminalId, writeInput],
);
const updateToolbarScrollEdges = useCallback(
(patch: Partial<(typeof toolbarScrollGeometryRef)["current"]>) => {
const nextGeometry = { ...toolbarScrollGeometryRef.current, ...patch };
toolbarScrollGeometryRef.current = nextGeometry;
const nextEdges = {
showLeftFade: nextGeometry.offsetX > 1,
showRightFade:
nextGeometry.offsetX + nextGeometry.viewportWidth < nextGeometry.contentWidth - 1,
};
setToolbarScrollEdges((current) =>
current.showLeftFade === nextEdges.showLeftFade &&
current.showRightFade === nextEdges.showRightFade
? current
: nextEdges,
);
},
[],
);
const handleToolbarLayout = useCallback(
(event: LayoutChangeEvent) => {
updateToolbarScrollEdges({ viewportWidth: event.nativeEvent.layout.width });
},
[updateToolbarScrollEdges],
);
const handleToolbarContentSizeChange = useCallback(
(contentWidth: number) => {
updateToolbarScrollEdges({ contentWidth });
},
[updateToolbarScrollEdges],
);
const handleToolbarScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
updateToolbarScrollEdges({ offsetX: event.nativeEvent.contentOffset.x });
},
[updateToolbarScrollEdges],
);
const handleDismissKeyboard = useCallback(() => {
setIsAccessoryDismissed(true);
void KeyboardController.dismiss();
}, []);
const handleShowKeyboard = useCallback(() => {
setKeyboardFocusRequest((current) => current + 1);
}, []);
if (!selectedThread) {
if (isLoadingSavedConnection) {
return <LoadingScreen message="Opening terminal…" />;
@@ -1029,6 +1151,7 @@ export function ThreadTerminalRouteScreen() {
buffer={terminalSurfaceBuffer}
fontSize={fontSize}
isRunning={isRunning}
keyboardFocusRequest={keyboardFocusRequest}
onInput={handleInput}
onResize={handleResize}
style={{ flex: 1 }}
@@ -1036,67 +1159,175 @@ export function ThreadTerminalRouteScreen() {
/>
</View>
<KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
<View
style={{
backgroundColor: terminalTheme.background,
borderTopColor: terminalTheme.border,
borderTopWidth: 1,
minHeight: TERMINAL_ACCESSORY_HEIGHT,
paddingBottom: 4,
paddingHorizontal: 8,
paddingTop: 4,
}}
{isAccessoryVisible ? (
<KeyboardStickyView
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<ScrollView
horizontal
contentContainerStyle={{ alignItems: "center", gap: 6, paddingRight: 2 }}
showsHorizontalScrollIndicator={false}
<View
style={{
backgroundColor: terminalTheme.background,
borderTopColor: terminalTheme.border,
borderTopWidth: 1,
minHeight: TERMINAL_ACCESSORY_HEIGHT,
paddingBottom: 4,
paddingHorizontal: 8,
paddingTop: 4,
}}
>
{terminalToolbarActions.map((action) => {
const active = action.kind === "modifier" && pendingModifier === action.modifier;
return (
<Pressable
key={action.key}
onPress={() => handleToolbarActionPress(action)}
style={({ pressed }) => ({
alignItems: "center",
backgroundColor: active
? withAlpha(terminalTheme.palette[10] ?? terminalTheme.foreground, "2e")
: pressed
? withAlpha(terminalTheme.foreground, "1f")
: withAlpha(terminalTheme.foreground, "12"),
borderColor: active
? withAlpha(terminalTheme.palette[10] ?? terminalTheme.foreground, "52")
: terminalTheme.border,
borderRadius: 12,
borderWidth: 1,
justifyContent: "center",
minWidth: action.label.length > 1 ? 46 : 38,
paddingHorizontal: 11,
paddingVertical: 8,
})}
<View style={{ alignItems: "center", flexDirection: "row", gap: 6 }}>
<View style={{ flex: 1, position: "relative" }}>
<ScrollView
horizontal
contentContainerStyle={{ alignItems: "center", gap: 6, paddingRight: 2 }}
onContentSizeChange={handleToolbarContentSizeChange}
onLayout={handleToolbarLayout}
onScroll={handleToolbarScroll}
scrollEventThrottle={16}
showsHorizontalScrollIndicator={false}
>
<RNText
{terminalToolbarActions.map((action) => {
const active =
action.kind === "modifier" && pendingModifier === action.modifier;
return (
<Pressable
key={action.key}
onPress={() => handleToolbarActionPress(action)}
style={({ pressed }) => ({
alignItems: "center",
backgroundColor: active
? withAlpha(
terminalTheme.palette[10] ?? terminalTheme.foreground,
"2e",
)
: pressed
? withAlpha(terminalTheme.foreground, "1f")
: withAlpha(terminalTheme.foreground, "12"),
borderColor: active
? withAlpha(
terminalTheme.palette[10] ?? terminalTheme.foreground,
"52",
)
: terminalTheme.border,
borderRadius: 12,
borderWidth: 1,
justifyContent: "center",
minWidth: action.label.length > 1 ? 46 : 38,
paddingHorizontal: 11,
paddingVertical: 8,
})}
>
<RNText
style={{
color: active
? (terminalTheme.palette[10] ?? terminalTheme.foreground)
: terminalTheme.foreground,
fontFamily: "DMSans_700Bold",
fontSize: 12,
fontWeight: "700",
textTransform:
action.kind === "modifier" || action.kind === "clear"
? "uppercase"
: "none",
}}
>
{action.label}
</RNText>
</Pressable>
);
})}
</ScrollView>
{toolbarScrollEdges.showLeftFade ? (
<View
pointerEvents="none"
style={{
color: active
? (terminalTheme.palette[10] ?? terminalTheme.foreground)
: terminalTheme.foreground,
fontFamily: "DMSans_700Bold",
fontSize: 12,
fontWeight: "700",
textTransform: action.kind === "modifier" ? "uppercase" : "none",
bottom: 0,
experimental_backgroundImage: `linear-gradient(to right, ${terminalTheme.background} 0%, ${withAlpha(terminalTheme.background, "00")} 100%)`,
left: 0,
position: "absolute",
top: 0,
width: TERMINAL_ACCESSORY_FADE_WIDTH,
}}
>
{action.label}
</RNText>
</Pressable>
);
})}
</ScrollView>
</View>
</KeyboardStickyView>
/>
) : null}
{toolbarScrollEdges.showRightFade ? (
<View
pointerEvents="none"
style={{
bottom: 0,
experimental_backgroundImage: `linear-gradient(to right, ${withAlpha(terminalTheme.background, "00")} 0%, ${terminalTheme.background} 100%)`,
position: "absolute",
right: 0,
top: 0,
width: TERMINAL_ACCESSORY_FADE_WIDTH,
}}
/>
) : null}
</View>
<Pressable
accessibilityLabel="Dismiss keyboard"
accessibilityRole="button"
onPress={handleDismissKeyboard}
style={({ pressed }) => ({
alignItems: "center",
backgroundColor: pressed
? withAlpha(terminalTheme.foreground, "1f")
: withAlpha(terminalTheme.foreground, "12"),
borderColor: terminalTheme.border,
borderRadius: 12,
borderWidth: 1,
justifyContent: "center",
minWidth: 38,
paddingHorizontal: 11,
paddingVertical: 8,
})}
>
<SymbolView
name={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
size={14}
tintColor={terminalTheme.foreground}
type="monochrome"
/>
</Pressable>
</View>
</View>
</KeyboardStickyView>
) : !keyboardState.isVisible ? (
<Pressable
accessibilityLabel="Show keyboard"
accessibilityRole="button"
onPress={handleShowKeyboard}
style={({ pressed }) => ({
bottom: 16,
borderRadius: 28,
opacity: pressed ? 0.72 : 1,
position: "absolute",
right: 16,
})}
>
<GlassSurface
chrome="none"
glassEffectStyle="regular"
tintColor="transparent"
style={{
alignItems: "center",
borderRadius: 24,
height: 48,
justifyContent: "center",
width: 48,
}}
pointerEvents="none"
>
<SymbolView
name={{ ios: "keyboard", android: "keyboard" }}
size={20}
tintColor={terminalTheme.foreground}
type="monochrome"
/>
</GlassSurface>
</Pressable>
) : null}
</View>
</>
);
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const expoModulesCoreMocks = vi.hoisted(() => ({
requireNativeViewManager: vi.fn(),
const expoMocks = vi.hoisted(() => ({
requireNativeView: vi.fn(),
}));
const nativeView = () => null;
const originalExpo = globalThis.expo;
@@ -12,8 +12,8 @@ function setExpoViewConfigAvailable() {
} as unknown as typeof globalThis.expo;
}
vi.mock("expo-modules-core", () => ({
requireNativeViewManager: expoModulesCoreMocks.requireNativeViewManager,
vi.mock("expo", () => ({
requireNativeView: expoMocks.requireNativeView,
}));
describe("resolveNativeTerminalSurfaceView", () => {
@@ -30,20 +30,20 @@ describe("resolveNativeTerminalSurfaceView", () => {
it("returns null when the native terminal view config is unavailable", async () => {
const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule");
expect(resolveNativeTerminalSurfaceView()).toBeNull();
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
expect(expoMocks.requireNativeView).not.toHaveBeenCalled();
});
it("returns the native terminal view when the view config is installed", async () => {
setExpoViewConfigAvailable();
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
expoMocks.requireNativeView.mockReturnValue(nativeView);
const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule");
expect(resolveNativeTerminalSurfaceView()).toBe(nativeView);
expect(expoModulesCoreMocks.requireNativeViewManager).toHaveBeenCalledWith("T3TerminalSurface");
expect(expoMocks.requireNativeView).toHaveBeenCalledWith("T3TerminalSurface");
});
it("returns null when the view manager cannot be required", async () => {
setExpoViewConfigAvailable();
expoModulesCoreMocks.requireNativeViewManager.mockImplementation(() => {
expoMocks.requireNativeView.mockImplementation(() => {
throw new Error("boom");
});
const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule");
@@ -1,6 +1,6 @@
import type { ComponentType } from "react";
import type { NativeSyntheticEvent, ViewProps } from "react-native";
import { requireNativeViewManager } from "expo-modules-core";
import { requireNativeView } from "expo";
const NATIVE_TERMINAL_MODULE_NAME = "T3TerminalSurface";
@@ -50,7 +50,7 @@ export function resolveNativeTerminalSurfaceView(): ComponentType<NativeTerminal
}
try {
cachedNativeTerminalSurfaceView = requireNativeViewManager<NativeTerminalSurfaceProps>(
cachedNativeTerminalSurfaceView = requireNativeView<NativeTerminalSurfaceProps>(
NATIVE_TERMINAL_MODULE_NAME,
);
} catch {
@@ -1,18 +1,16 @@
import { MenuView } from "@react-native-menu/menu";
import { useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { TextInputWrapper } from "expo-paste-input";
import { useCallback, useEffect, useMemo } from "react";
import { Pressable, View, useColorScheme } from "react-native";
import { KeyboardStickyView } from "react-native-keyboard-controller";
import { View } from "react-native";
import { KeyboardStickyView, useKeyboardState } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { EnvironmentId, type ModelSelection } from "@t3tools/contracts";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { AppTextInput as TextInput } from "../../components/AppText";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { ControlPill } from "../../components/ControlPill";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
@@ -20,6 +18,7 @@ import { buildThreadRoutePath } from "../../lib/routes";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useNativePaste } from "../../lib/useNativePaste";
import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions";
import { NewTaskSheetHeader } from "./NewTaskSheetHeader";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useProjectActions } from "./use-project-actions";
@@ -46,11 +45,10 @@ export function NewTaskDraftScreen(props: {
const flow = useNewTaskFlow();
const router = useRouter();
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const controlsBottomPadding = Math.max(insets.bottom, 10);
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
const iconColor = useThemeColor("--color-icon");
const borderColor = useThemeColor("--color-border");
useEffect(() => {
@@ -394,48 +392,21 @@ export function NewTaskDraftScreen(props: {
if (!selectedProject) {
return (
<View className="flex-1 bg-sheet">
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold">Loading task</Text>
</View>
<NewTaskSheetHeader title="Loading task" />
</View>
);
}
return (
<View className="flex-1 bg-sheet">
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
{flow.logicalProjects.length > 1 ? (
<Pressable
className="absolute left-3 top-4 h-9 w-9 items-center justify-center rounded-full bg-subtle"
style={{ zIndex: 1 }}
onPress={() => router.back()}
>
<SymbolView
name="chevron.left"
size={16}
tintColor={iconColor}
type="monochrome"
weight="medium"
/>
</Pressable>
) : null}
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold">{selectedProject.title}</Text>
</View>
<NewTaskSheetHeader
title={selectedProject.title}
control={
flow.logicalProjects.length > 1
? { icon: "chevron.left", onPress: () => router.back() }
: undefined
}
/>
<View style={{ flex: 1, paddingHorizontal: 20, paddingTop: 8 }}>
<TextInputWrapper
@@ -472,40 +443,36 @@ export function NewTaskDraftScreen(props: {
/>
</View>
) : null}
<View className="flex-row items-center justify-between gap-2 px-4 pb-1 pt-4">
<View className="flex-row items-center justify-between gap-2 px-4 pt-2">
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
<MenuView
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill
iconNode={
<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
}
/>
</MenuView>
<MenuView
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="slider.horizontal.3" />
</MenuView>
<MenuView
</ControlPillMenu>
<ControlPillMenu
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="desktopcomputer" />
</MenuView>
<MenuView
</ControlPillMenu>
<ControlPillMenu
actions={workspaceMenuActions}
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="point.topleft.down.curvedto.point.bottomright.up" />
</MenuView>
</ControlPillMenu>
<ControlPill
icon="arrow.up"
label={flow.submitting ? "Starting" : "Start"}
@@ -0,0 +1,46 @@
import { SymbolView } from "expo-symbols";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
export function NewTaskSheetHeader(props: {
readonly eyebrow?: string;
readonly title: string;
readonly control?: {
readonly icon: "chevron.left" | "xmark";
readonly onPress: () => void;
};
}) {
const iconColor = useThemeColor("--color-icon");
return (
<>
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
{props.control ? (
<Pressable
className="absolute left-3 top-4 h-9 w-9 items-center justify-center rounded-full bg-subtle"
style={{ zIndex: 1 }}
onPress={props.control.onPress}
>
<SymbolView
name={props.control.icon}
size={16}
tintColor={iconColor}
type="monochrome"
weight="medium"
/>
</Pressable>
) : null}
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
{props.eyebrow ?? "New task"}
</Text>
<Text className="text-[28px] font-t3-bold">{props.title}</Text>
</View>
</>
);
}
@@ -1,5 +1,4 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import { MenuView } from "@react-native-menu/menu";
import type {
EnvironmentId,
ModelSelection,
@@ -31,7 +30,7 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { ControlPill } from "../../components/ControlPill";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
@@ -763,20 +762,18 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}}
>
<ControlPill icon="plus" onPress={() => void props.onPickDraftImages()} />
<MenuView
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill iconNode={<ProviderIcon provider={modelProvider} size={16} />} />
</MenuView>
<MenuView
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="slider.horizontal.3" />
</MenuView>
</ControlPillMenu>
<ControlPill icon="arrow.clockwise" onPress={() => void props.onRefresh()} />
{showStopAction ? (
<ControlPill
@@ -748,7 +748,7 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: {
>
<NativeReviewDiffView
collapsable={false}
style={StyleSheet.absoluteFillObject}
style={StyleSheet.absoluteFill}
appearanceScheme={appearanceScheme}
contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
@@ -13,9 +13,10 @@ import {
type RuntimeMode,
} from "@t3tools/contracts";
import { buildTemporaryWorktreeBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { uuidv4 } from "../../lib/uuid";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { uuidv4 } from "../../lib/uuid";
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { getEnvironmentClient } from "../../state/environment-session-registry";
import { environmentRuntimeManager } from "../../state/use-environment-runtime";
import { vcsRefManager } from "../../state/use-vcs-refs";
@@ -93,8 +94,9 @@ export function useProjectActions() {
return null;
}
const threadId = ThreadId.make(uuidv4());
const createdAt = new Date().toISOString();
const metadata = makeTurnCommandMetadata();
const threadId = ThreadId.make(metadata.threadId);
const createdAt = metadata.createdAt;
const initialMessageText = input.initialMessageText.trim();
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
@@ -109,10 +111,10 @@ export function useProjectActions() {
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: CommandId.make(uuidv4()),
commandId: CommandId.make(metadata.commandId),
threadId,
message: {
messageId: MessageId.make(uuidv4()),
messageId: MessageId.make(metadata.messageId),
role: "user",
text: initialMessageText,
attachments: input.initialAttachments,
@@ -137,13 +139,13 @@ export function useProjectActions() {
prepareWorktree: {
projectCwd: input.project.workspaceRoot,
baseBranch: input.branch!,
branch: buildTemporaryWorktreeBranchName(),
branch: buildTemporaryWorktreeBranchName(uuidv4),
},
runSetupScript: true,
}
: {}),
},
createdAt: new Date().toISOString(),
createdAt,
});
await refreshRemoteData([input.project.environmentId]);
@@ -0,0 +1,36 @@
import { describe, expect, it, vi } from "vitest";
import { makeQueuedMessageMetadata, makeTurnCommandMetadata } from "./commandMetadata";
vi.mock("expo-crypto", () => ({
randomUUID: () => crypto.randomUUID(),
}));
describe("mobile command metadata", () => {
it("creates ids and timestamps for thread starts", () => {
const metadata = makeTurnCommandMetadata();
expect(metadata.commandId).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
);
expect(metadata.messageId).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
);
expect(metadata.threadId).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
);
expect(metadata.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
});
it("creates ids and timestamps for queued messages", () => {
const metadata = makeQueuedMessageMetadata();
expect(metadata.commandId).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
);
expect(metadata.messageId).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
);
expect(metadata.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
});
});
+25
View File
@@ -0,0 +1,25 @@
import { uuidv4 } from "./uuid";
export interface TurnCommandMetadata {
readonly commandId: string;
readonly messageId: string;
readonly threadId: string;
readonly createdAt: string;
}
export function makeTurnCommandMetadata(): TurnCommandMetadata {
return {
commandId: uuidv4(),
messageId: uuidv4(),
threadId: uuidv4(),
createdAt: new Date().toISOString(),
};
}
export function makeQueuedMessageMetadata(): Omit<TurnCommandMetadata, "threadId"> {
return {
commandId: uuidv4(),
messageId: uuidv4(),
createdAt: new Date().toISOString(),
};
}
+28
View File
@@ -0,0 +1,28 @@
import { describe, expect, it, vi } from "vitest";
import { redactPairingCredential } from "./connection";
vi.mock("./runtime", () => ({
mobileRemoteHttpRuntime: {
runPromise: vi.fn(),
},
}));
describe("mobile remote connection records", () => {
it("removes one-time bootstrap credentials before persisting pairing URLs", () => {
expect(redactPairingCredential("https://desktop.example/#token=bootstrap-token")).toBe(
"https://desktop.example/",
);
expect(redactPairingCredential("https://desktop.example/?token=bootstrap-token")).toBe(
"https://desktop.example/",
);
});
it("removes hosted pairing credentials while keeping the advertised host", () => {
expect(
redactPairingCredential(
"https://app.t3.codes/pair?host=https%3A%2F%2Fdesktop.example&token=bootstrap-token&label=Desktop",
),
).toBe("https://app.t3.codes/pair?host=https%3A%2F%2Fdesktop.example&label=Desktop");
});
});
+24 -10
View File
@@ -2,8 +2,9 @@ import { EnvironmentId } from "@t3tools/contracts";
import {
bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
resolveRemotePairingTarget,
} from "@t3tools/shared/remote";
} from "@t3tools/client-runtime";
import { resolveRemotePairingTarget, stripPairingTokenFromUrl } from "@t3tools/shared/remote";
import { mobileRemoteHttpRuntime } from "./runtime";
export interface RemoteConnectionInput {
readonly pairingUrl: string;
@@ -26,6 +27,15 @@ export type RemoteClientConnectionState =
| "reconnecting"
| "disconnected";
export function redactPairingCredential(pairingUrl: string): string {
const trimmed = pairingUrl.trim();
try {
return stripPairingTokenFromUrl(new URL(trimmed)).toString();
} catch {
return trimmed;
}
}
export async function bootstrapRemoteConnection(
input: RemoteConnectionInput,
): Promise<SavedRemoteConnection> {
@@ -33,19 +43,23 @@ export async function bootstrapRemoteConnection(
pairingUrl: input.pairingUrl,
});
const descriptor = await fetchRemoteEnvironmentDescriptor({
httpBaseUrl: target.httpBaseUrl,
});
const descriptor = await mobileRemoteHttpRuntime.runPromise(
fetchRemoteEnvironmentDescriptor({
httpBaseUrl: target.httpBaseUrl,
}),
);
const bootstrap = await bootstrapRemoteBearerSession({
httpBaseUrl: target.httpBaseUrl,
credential: target.credential,
});
const bootstrap = await mobileRemoteHttpRuntime.runPromise(
bootstrapRemoteBearerSession({
httpBaseUrl: target.httpBaseUrl,
credential: target.credential,
}),
);
return {
environmentId: descriptor.environmentId,
environmentLabel: descriptor.label,
pairingUrl: input.pairingUrl.trim(),
pairingUrl: redactPairingCredential(input.pairingUrl),
displayUrl: target.httpBaseUrl,
httpBaseUrl: target.httpBaseUrl,
wsBaseUrl: target.wsBaseUrl,
+3 -1
View File
@@ -1,9 +1,11 @@
import type { Href, Router } from "expo-router";
import type { Href, useRouter } from "expo-router";
import type { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import type { SelectedThreadRef } from "../state/remote-runtime-types";
type Router = ReturnType<typeof useRouter>;
type ThreadRouteInput =
| Pick<SelectedThreadRef, "environmentId" | "threadId">
| Pick<EnvironmentScopedThreadShell, "environmentId" | "id">;
+5
View File
@@ -0,0 +1,5 @@
import * as ManagedRuntime from "effect/ManagedRuntime";
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
export const mobileRemoteHttpRuntime = ManagedRuntime.make(remoteHttpClientLayer(fetch));
+14 -31
View File
@@ -1,7 +1,9 @@
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
import type { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts";
import { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts";
import type { SavedRemoteConnection } from "./connection";
@@ -21,6 +23,14 @@ export interface MobilePreferences {
readonly terminalFontSize?: number;
}
const CachedShellSnapshotSchema = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
snapshotReceivedAt: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
const decodeCachedShellSnapshot = Schema.decodeUnknownOption(CachedShellSnapshotSchema);
async function readStorageItem(key: string): Promise<string | null> {
return await SecureStore.getItemAsync(key);
}
@@ -42,34 +52,6 @@ async function readJsonStorageItem<T>(key: string): Promise<T | null> {
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isShellSnapshot(value: unknown): value is OrchestrationShellSnapshot {
if (!isRecord(value)) {
return false;
}
return (
typeof value.snapshotSequence === "number" &&
Array.isArray(value.projects) &&
Array.isArray(value.threads) &&
typeof value.updatedAt === "string"
);
}
function isCachedShellSnapshot(value: unknown): value is CachedShellSnapshot {
if (!isRecord(value)) {
return false;
}
return (
value.schemaVersion === SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION &&
typeof value.environmentId === "string" &&
typeof value.snapshotReceivedAt === "string" &&
isShellSnapshot(value.snapshot)
);
}
function cachedShellSnapshotFileName(environmentId: EnvironmentId): string {
return `${encodeURIComponent(environmentId)}.json`;
}
@@ -93,11 +75,12 @@ export async function loadCachedShellSnapshot(
}
const parsed = JSON.parse(await file.text()) as unknown;
if (!isCachedShellSnapshot(parsed) || parsed.environmentId !== environmentId) {
const decoded = decodeCachedShellSnapshot(parsed);
if (Option.isNone(decoded) || decoded.value.environmentId !== environmentId) {
return null;
}
return parsed;
return decoded.value;
} catch {
return null;
}
+2 -3
View File
@@ -1,4 +1,3 @@
import * as Effect from "effect/Effect";
import * as Random from "effect/Random";
import * as Crypto from "expo-crypto";
export const uuidv4 = () => Effect.runSync(Random.nextUUIDv4);
export const uuidv4 = () => Crypto.randomUUID();
+2 -2
View File
@@ -31,11 +31,11 @@ const projectsSortOrder = Order.mapInput(
const threadsSortOrder = Order.mapInput(
Order.Struct({
activityAt: Order.flip(Order.Number),
activityAt: Order.flip(Order.String),
environmentId: Order.String,
}),
(thread: EnvironmentScopedThreadShell) => ({
activityAt: new Date(thread.updatedAt ?? thread.createdAt).getTime(),
activityAt: thread.updatedAt ?? thread.createdAt,
environmentId: thread.environmentId,
}),
);
@@ -5,13 +5,14 @@ import { Alert } from "react-native";
import {
type EnvironmentRuntimeState,
createEnvironmentConnection,
createEnvironmentConnectionAttemptRegistry,
createKnownEnvironment,
createWsRpcClient,
EnvironmentConnectionState,
WsTransport,
resolveRemoteWebSocketConnectionUrl,
} from "@t3tools/client-runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import { resolveRemoteWebSocketConnectionUrl } from "@t3tools/shared/remote";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import * as Option from "effect/Option";
@@ -28,6 +29,7 @@ import {
saveConnection,
} from "../lib/storage";
import { appAtomRegistry } from "./atom-registry";
import { mobileRemoteHttpRuntime } from "../lib/runtime";
import {
drainEnvironmentSessions,
notifyEnvironmentConnectionListeners,
@@ -49,6 +51,7 @@ import {
import { subscribeTerminalMetadata, terminalSessionManager } from "./use-terminal-session";
const terminalMetadataUnsubscribers = new Map<EnvironmentId, () => void>();
const environmentConnectionAttempts = createEnvironmentConnectionAttemptRegistry();
const SAVED_CONNECTION_BOOTSTRAP_TIMEOUT_MS = 8_000;
interface RemoteEnvironmentLocalState {
@@ -175,8 +178,16 @@ function withTimeout<T>(
export async function disconnectEnvironment(
environmentId: EnvironmentId,
options?: { readonly preserveShellSnapshot?: boolean; readonly removeSaved?: boolean },
options?: {
readonly preserveShellSnapshot?: boolean;
readonly removeSaved?: boolean;
readonly preserveConnectionAttempt?: boolean;
},
) {
if (!options?.preserveConnectionAttempt) {
environmentConnectionAttempts.cancel(environmentId);
}
const session = removeEnvironmentSession(environmentId);
notifyEnvironmentConnectionListeners();
await session?.connection.dispose();
@@ -201,10 +212,22 @@ export async function connectSavedEnvironment(
connection: SavedRemoteConnection,
options?: { readonly persist?: boolean },
) {
await disconnectEnvironment(connection.environmentId, { preserveShellSnapshot: true });
const connectionAttempt = environmentConnectionAttempts.begin(connection.environmentId);
const isCurrentAttempt = connectionAttempt.isCurrent;
await disconnectEnvironment(connection.environmentId, {
preserveShellSnapshot: true,
preserveConnectionAttempt: true,
});
if (!isCurrentAttempt()) {
return;
}
if (options?.persist !== false) {
await saveConnection(connection);
if (!isCurrentAttempt()) {
return;
}
}
upsertSavedConnection(connection);
@@ -213,13 +236,19 @@ export async function connectSavedEnvironment(
const transport = new WsTransport(
() =>
resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: connection.wsBaseUrl,
httpBaseUrl: connection.httpBaseUrl,
bearerToken: connection.bearerToken,
}),
mobileRemoteHttpRuntime.runPromise(
resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: connection.wsBaseUrl,
httpBaseUrl: connection.httpBaseUrl,
bearerToken: connection.bearerToken,
}),
),
{
onAttempt: () => {
if (!isCurrentAttempt()) {
return;
}
environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (previous) => {
const nextState =
previous.connectionState === "ready" || previous.connectionState === "reconnecting"
@@ -235,9 +264,15 @@ export async function connectSavedEnvironment(
});
},
onError: (message) => {
setEnvironmentConnectionStatus(connection.environmentId, "disconnected", message);
if (isCurrentAttempt()) {
setEnvironmentConnectionStatus(connection.environmentId, "disconnected", message);
}
},
onClose: (details) => {
if (!isCurrentAttempt()) {
return;
}
const reason =
details.reason.trim().length > 0
? details.reason
@@ -266,9 +301,15 @@ export async function connectSavedEnvironment(
},
client,
applyShellEvent: (event, environmentId) => {
shellSnapshotManager.applyEvent({ environmentId }, event);
if (isCurrentAttempt()) {
shellSnapshotManager.applyEvent({ environmentId }, event);
}
},
syncShellSnapshot: (snapshot, environmentId) => {
if (!isCurrentAttempt()) {
return;
}
shellSnapshotManager.syncSnapshot({ environmentId }, snapshot);
markShellSnapshotLive(environmentId);
void saveCachedShellSnapshot(environmentId, snapshot);
@@ -279,16 +320,25 @@ export async function connectSavedEnvironment(
}));
},
onShellResubscribe: (environmentId) => {
shellSnapshotManager.markPending({ environmentId });
if (isCurrentAttempt()) {
shellSnapshotManager.markPending({ environmentId });
}
},
onConfigSnapshot: (serverConfig) => {
environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (runtime) => ({
...runtime,
serverConfig,
}));
if (isCurrentAttempt()) {
environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (runtime) => ({
...runtime,
serverConfig,
}));
}
},
});
if (!isCurrentAttempt()) {
await environmentConnection.dispose();
return;
}
setEnvironmentSession(connection.environmentId, {
client,
connection: environmentConnection,
@@ -312,11 +362,13 @@ export async function connectSavedEnvironment(
"Environment did not respond before the connection timeout.",
);
} catch (error) {
setEnvironmentConnectionStatus(
connection.environmentId,
"disconnected",
error instanceof Error ? error.message : "Failed to bootstrap remote connection.",
);
if (isCurrentAttempt()) {
setEnvironmentConnectionStatus(
connection.environmentId,
"disconnected",
error instanceof Error ? error.message : "Failed to bootstrap remote connection.",
);
}
}
}
@@ -404,6 +456,7 @@ export function useRemoteEnvironmentBootstrap() {
unsubscribe();
}
terminalMetadataUnsubscribers.clear();
environmentConnectionAttempts.clear();
environmentRuntimeManager.invalidate();
shellSnapshotManager.invalidate();
resetSourceControlDiscoveryState();
@@ -6,6 +6,7 @@ import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tool
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
import { Atom } from "effect/unstable/reactivity";
import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
import {
convertPastedImagesToAttachments,
pasteComposerClipboard,
@@ -14,7 +15,6 @@ import {
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { scopedThreadKey } from "../lib/scopedEntities";
import { buildThreadFeed, type QueuedThreadMessage } from "../lib/threadActivity";
import { uuidv4 } from "../lib/uuid";
import { appAtomRegistry } from "../state/atom-registry";
import { getEnvironmentClient } from "./environment-session-registry";
import type { ConnectedEnvironmentSummary } from "../state/remote-runtime-types";
@@ -356,15 +356,15 @@ export function useThreadComposerState() {
return;
}
const createdAt = new Date().toISOString();
const metadata = makeQueuedMessageMetadata();
enqueueQueuedMessage({
environmentId: selectedThreadShell.environmentId,
threadId: selectedThreadShell.id,
messageId: MessageId.make(uuidv4()),
commandId: CommandId.make(uuidv4()),
messageId: MessageId.make(metadata.messageId),
commandId: CommandId.make(metadata.commandId),
text,
attachments,
createdAt,
createdAt: metadata.createdAt,
});
clearDraft(threadKey);
}, [draftAttachmentsByThreadKey, draftMessageByThreadKey, selectedThreadShell]);
@@ -11,8 +11,8 @@ import {
ProviderDriverKind,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
import * as Queue from "effect/Queue";
import * as Random from "effect/Random";
import * as Stream from "effect/Stream";
import {
@@ -226,6 +226,7 @@ function missingSessionEffect(
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
Effect.gen(function* () {
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const crypto = yield* Crypto.Crypto;
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 0;
const sessions = new Map<ThreadId, SessionState>();
@@ -241,6 +242,18 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
>();
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
const randomUUIDv4 = (threadId: ThreadId) =>
crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterValidationError({
provider,
operation: "crypto/randomUUIDv4",
issue: `Failed to generate test runtime identifier for thread '${threadId}'.`,
cause,
}),
),
);
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
@@ -309,7 +322,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: yield* Random.nextUUIDv4,
eventId: yield* randomUUIDv4(input.threadId),
provider,
sessionId: RuntimeSessionId.make(String(input.threadId)),
};
@@ -366,7 +379,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.make(yield* Random.nextUUIDv4),
eventId: EventId.make(yield* randomUUIDv4(input.threadId)),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
+2 -4
View File
@@ -19,11 +19,11 @@
"build": "node scripts/cli.ts build",
"build:bundle": "tsdown",
"start": "node dist/bin.mjs",
"typecheck": "tsc --noEmit",
"typecheck": "tsgo --noEmit",
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
"@anthropic-ai/claude-agent-sdk": "^0.3.154",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
@@ -34,7 +34,6 @@
"node-pty": "^1.1.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
@@ -45,7 +44,6 @@
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"engines": {
+1 -3
View File
@@ -1,7 +1,6 @@
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
export const writeFileStringAtomically = (input: {
readonly filePath: string;
@@ -11,7 +10,6 @@ export const writeFileStringAtomically = (input: {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempFileId = yield* Random.nextUUIDv4;
const targetDirectory = path.dirname(input.filePath);
yield* fs.makeDirectory(targetDirectory, { recursive: true });
@@ -19,7 +17,7 @@ export const writeFileStringAtomically = (input: {
directory: targetDirectory,
prefix: `${path.basename(input.filePath)}.`,
});
const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
const tempPath = path.join(tempDirectory, "contents.tmp");
yield* fs.writeFileString(tempPath, input.contents);
yield* fs.rename(tempPath, input.filePath);
@@ -1,4 +1,5 @@
import type { AuthPairingLink } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -46,6 +47,7 @@ const generatePairingToken = (): string => {
};
export const makeBootstrapCredentialService = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const config = yield* ServerConfig;
const pairingLinks = yield* AuthPairingLinkRepository;
const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
@@ -141,7 +143,7 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {
const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
Effect.gen(function* () {
const id = crypto.randomUUID();
const id = yield* crypto.randomUUIDv4;
const credential = generatePairingToken();
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
const now = yield* DateTime.now;
@@ -1,5 +1,6 @@
import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -90,6 +91,7 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
}
export const makeSessionCredentialService = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const serverConfig = yield* ServerConfig;
const secretStore = yield* ServerSecretStore;
const authSessions = yield* AuthSessionRepository;
@@ -203,7 +205,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
const issue: SessionCredentialServiceShape["issue"] = (input) =>
Effect.gen(function* () {
const sessionId = AuthSessionId.make(crypto.randomUUID());
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
@@ -69,5 +69,5 @@ export interface AuthControlPlaneShape {
}
export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
"t3/AuthControlPlane",
"t3/auth/Services/AuthControlPlane",
) {}
+1 -1
View File
@@ -1,4 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off - NodeHttpServer.layer takes `NodeHttp.createServer` as arg
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
import * as NodeHttp from "node:http";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
+16 -5
View File
@@ -5,6 +5,7 @@ import {
type ClientOrchestrationCommand,
} from "@t3tools/contracts";
import * as Console from "effect/Console";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
@@ -58,6 +59,16 @@ class ProjectCommandError extends Data.TaggedError("ProjectCommandError")<{
readonly message: string;
}> {}
const projectCommandUuid = Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.mapError(
() =>
new ProjectCommandError({
message: "Failed to generate a project command identifier.",
}),
),
);
const ProjectCliRuntimeLive = Layer.mergeAll(
WorkspacePathsLive,
OrchestrationLayerLive.pipe(
@@ -260,7 +271,7 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
}) => Effect.Effect<
string,
Error,
FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
Crypto.Crypto | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
>,
) {
const logLevel = yield* GlobalFlag.LogLevel;
@@ -343,10 +354,10 @@ const projectAddCommand = Command.make("add", {
}
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
const projectId = ProjectId.make(crypto.randomUUID());
const projectId = ProjectId.make(yield* projectCommandUuid);
yield* dispatch({
type: "project.create",
commandId: CommandId.make(crypto.randomUUID()),
commandId: CommandId.make(yield* projectCommandUuid),
projectId,
title,
workspaceRoot,
@@ -384,7 +395,7 @@ const projectRemoveCommand = Command.make("remove", {
});
yield* dispatch({
type: "project.delete",
commandId: CommandId.make(crypto.randomUUID()),
commandId: CommandId.make(yield* projectCommandUuid),
projectId: project.id,
});
return `Removed project ${project.id} (${project.title}).`;
@@ -424,7 +435,7 @@ const projectRenameCommand = Command.make("rename", {
yield* dispatch({
type: "project.meta.update",
commandId: CommandId.make(crypto.randomUUID()),
commandId: CommandId.make(yield* projectCommandUuid),
projectId: project.id,
title: nextTitle,
});
@@ -1,9 +1,9 @@
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
import { ServerConfig } from "../../config.ts";
import { layer as ProcessRunnerLive } from "../../processRunner.ts";
@@ -39,6 +39,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const crypto = yield* Crypto.Crypto;
const readPersistedEnvironmentId = Effect.gen(function* () {
const exists = yield* fileSystem
@@ -64,7 +65,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
return persisted;
}
const generated = yield* Random.nextUUIDv4;
const generated = yield* crypto.randomUUIDv4;
yield* persistEnvironmentId(generated);
return generated;
});
+28 -22
View File
@@ -1,8 +1,7 @@
import { randomUUID } from "node:crypto";
import * as Arr from "effect/Array";
import * as Cache from "effect/Cache";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -532,32 +531,39 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const sourceControlProviders = yield* SourceControlProviderRegistry;
const textGeneration = yield* TextGeneration;
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const crypto = yield* Crypto.Crypto;
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
const serverSettingsService = yield* ServerSettingsService;
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
Effect.mapError((cause) =>
gitManagerError("randomUUIDv4", "Failed to generate Git operation identifier.", cause),
),
);
const createProgressEmitter = (
input: { cwd: string; action: GitStackedAction },
options?: GitRunStackedActionOptions,
) => {
const actionId = options?.actionId ?? randomUUID();
const reporter = options?.progressReporter;
) =>
(options?.actionId === undefined ? randomUUIDv4 : Effect.succeed(options.actionId)).pipe(
Effect.map((actionId) => {
const reporter = options?.progressReporter;
const emit = (event: GitActionProgressPayload) =>
reporter
? reporter.publish({
actionId,
cwd: input.cwd,
action: input.action,
...event,
} as GitActionProgressEvent)
: Effect.void;
const emit = (event: GitActionProgressPayload) =>
reporter
? reporter.publish({
actionId,
cwd: input.cwd,
action: input.action,
...event,
} as GitActionProgressEvent)
: Effect.void;
return {
actionId,
emit,
};
};
return {
actionId,
emit,
};
}),
);
const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")(
function* (
@@ -1301,7 +1307,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
modelSelection,
});
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${yield* randomUUIDv4}.md`);
yield* fileSystem
.writeFileString(bodyFile, generated.body)
.pipe(
@@ -1591,7 +1597,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fn("runStackedAction")(
function* (input, options) {
const progress = createProgressEmitter(input, options);
const progress = yield* createProgressEmitter(input, options);
const currentPhase = yield* Ref.make<Option.Option<GitActionProgressPhase>>(Option.none());
const runAction = Effect.fn("runStackedAction.runAction")(function* (): Effect.fn.Return<
@@ -10,10 +10,12 @@ import {
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as PlatformError from "effect/PlatformError";
import * as Stream from "effect/Stream";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
@@ -70,10 +72,12 @@ function checkpointStatusFromRuntime(status: string | undefined): "ready" | "mis
}
}
const serverCommandId = (tag: string): CommandId =>
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const randomUUID = crypto.randomUUIDv4;
const serverEventId = randomUUID.pipe(Effect.map(EventId.make));
const serverCommandId = (tag: string) =>
randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
@@ -88,24 +92,31 @@ const make = Effect.gen(function* () {
readonly detail: string;
readonly createdAt: string;
}) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
Effect.all({
commandId: serverCommandId("checkpoint-revert-failure"),
threadId: input.threadId,
activity: {
id: EventId.make(crypto.randomUUID()),
tone: "error",
kind: "checkpoint.revert.failed",
summary: "Checkpoint revert failed",
payload: {
turnCount: input.turnCount,
detail: input.detail,
},
turnId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
});
activityId: serverEventId,
}).pipe(
Effect.flatMap(({ commandId, activityId }) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId,
threadId: input.threadId,
activity: {
id: activityId,
tone: "error",
kind: "checkpoint.revert.failed",
summary: "Checkpoint revert failed",
payload: {
turnCount: input.turnCount,
detail: input.detail,
},
turnId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
}),
),
);
const appendCaptureFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -113,23 +124,30 @@ const make = Effect.gen(function* () {
readonly detail: string;
readonly createdAt: string;
}) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
Effect.all({
commandId: serverCommandId("checkpoint-capture-failure"),
threadId: input.threadId,
activity: {
id: EventId.make(crypto.randomUUID()),
tone: "error",
kind: "checkpoint.capture.failed",
summary: "Checkpoint capture failed",
payload: {
detail: input.detail,
},
turnId: input.turnId,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
});
activityId: serverEventId,
}).pipe(
Effect.flatMap(({ commandId, activityId }) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId,
threadId: input.threadId,
activity: {
id: activityId,
tone: "error",
kind: "checkpoint.capture.failed",
summary: "Checkpoint capture failed",
payload: {
detail: input.detail,
},
turnId: input.turnId,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
}),
),
);
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
threadId: ThreadId,
@@ -282,7 +300,7 @@ const make = Effect.gen(function* () {
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: serverCommandId("checkpoint-turn-diff-complete"),
commandId: yield* serverCommandId("checkpoint-turn-diff-complete"),
threadId: input.threadId,
turnId: input.turnId,
completedAt: input.createdAt,
@@ -312,10 +330,10 @@ const make = Effect.gen(function* () {
yield* orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: serverCommandId("checkpoint-captured-activity"),
commandId: yield* serverCommandId("checkpoint-captured-activity"),
threadId: input.threadId,
activity: {
id: EventId.make(crypto.randomUUID()),
id: EventId.make(yield* randomUUID),
tone: "info",
kind: "checkpoint.captured",
summary: "Checkpoint captured",
@@ -701,7 +719,7 @@ const make = Effect.gen(function* () {
yield* orchestrationEngine
.dispatch({
type: "thread.revert.complete",
commandId: serverCommandId("checkpoint-revert-complete"),
commandId: yield* serverCommandId("checkpoint-revert-complete"),
threadId: event.payload.threadId,
turnCount: event.payload.turnCount,
createdAt: now,
@@ -791,7 +809,11 @@ const make = Effect.gen(function* () {
const processInput = (
input: ReactorInput,
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError, never> =>
): Effect.Effect<
void,
CheckpointStoreError | OrchestrationDispatchError | PlatformError.PlatformError,
never
> =>
input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
const processInputSafely = (input: ReactorInput) =>
@@ -211,6 +211,7 @@ describe("OrchestrationEngine", () => {
Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(layer);
@@ -7,6 +7,7 @@ import type {
import { OrchestrationCommand } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
@@ -81,6 +82,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const crypto = yield* Crypto.Crypto;
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
let commandReadModel = createEmptyReadModel(yield* nowIso);
@@ -151,7 +153,18 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel: commandReadModel,
});
}).pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.mapError((cause) =>
isOrchestrationCommandInvariantError(cause)
? cause
: new OrchestrationCommandInvariantError({
commandType: envelope.command.type,
detail: "Failed to generate an event identifier.",
cause,
}),
),
);
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
const committedCommand = yield* sql
.withTransaction(
@@ -105,6 +105,7 @@ function isStalePendingApprovalFailureDetail(detail: string | null): boolean {
detail.includes("unknown pending permission request")
);
}
function derivePendingUserInputCountFromActivities(
activities: ReadonlyArray<ProjectionThreadActivity>,
): number {
@@ -15,6 +15,7 @@ import {
import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shared/git";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
@@ -81,9 +82,6 @@ function mapProviderSessionStatusToOrchestrationStatus(
const turnStartKeyForEvent = (event: ProviderIntentEvent): string =>
event.commandId !== null ? `command:${event.commandId}` : `event:${event.eventId}`;
const serverCommandId = (tag: string): CommandId =>
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
const HANDLED_TURN_START_KEY_MAX = 10_000;
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
@@ -178,6 +176,7 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
}
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
@@ -185,6 +184,9 @@ const make = Effect.gen(function* () {
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const serverCommandId = (tag: string) =>
crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make));
const handledTurnStartKeys = yield* Cache.make<string, true>({
capacity: HANDLED_TURN_START_KEY_MAX,
timeToLive: HANDLED_TURN_START_KEY_TTL,
@@ -214,24 +216,31 @@ const make = Effect.gen(function* () {
readonly createdAt: string;
readonly requestId?: string;
}) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
Effect.all({
commandId: serverCommandId("provider-failure-activity"),
threadId: input.threadId,
activity: {
id: EventId.make(crypto.randomUUID()),
tone: "error",
kind: input.kind,
summary: input.summary,
payload: {
detail: input.detail,
...(input.requestId ? { requestId: input.requestId } : {}),
},
turnId: input.turnId,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
});
eventId: serverEventId(),
}).pipe(
Effect.flatMap(({ commandId, eventId }) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId,
threadId: input.threadId,
activity: {
id: eventId,
tone: "error",
kind: input.kind,
summary: input.summary,
payload: {
detail: input.detail,
...(input.requestId ? { requestId: input.requestId } : {}),
},
turnId: input.turnId,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
}),
),
);
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
const failReason = cause.reasons.find(Cause.isFailReason);
@@ -249,13 +258,17 @@ const make = Effect.gen(function* () {
readonly session: OrchestrationSession;
readonly createdAt: string;
}) =>
orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: serverCommandId("provider-session-set"),
threadId: input.threadId,
session: input.session,
createdAt: input.createdAt,
});
serverCommandId("provider-session-set").pipe(
Effect.flatMap((commandId) =>
orchestrationEngine.dispatch({
type: "thread.session.set",
commandId,
threadId: input.threadId,
session: input.session,
createdAt: input.createdAt,
}),
),
);
const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
@@ -610,7 +623,7 @@ const make = Effect.gen(function* () {
const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("worktree-branch-rename"),
commandId: yield* serverCommandId("worktree-branch-rename"),
threadId: input.threadId,
branch: renamed.branch,
worktreePath: cwd,
@@ -657,7 +670,7 @@ const make = Effect.gen(function* () {
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("thread-title-rename"),
commandId: yield* serverCommandId("thread-title-rename"),
threadId: input.threadId,
title: generated.title,
});
@@ -19,6 +19,7 @@ import {
} from "@t3tools/contracts";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -39,8 +40,6 @@ import {
import { ServerSettingsService } from "../../serverSettings.ts";
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
CommandId.make(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
interface AssistantSegmentState {
baseKey: string;
@@ -607,11 +606,16 @@ function runtimeEventToActivities(
}
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const serverSettingsService = yield* ServerSettingsService;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),
);
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
@@ -848,7 +852,7 @@ const make = Effect.gen(function* () {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(input.event, input.commandTag),
commandId: yield* providerCommandId(input.event, input.commandTag),
threadId: input.threadId,
messageId: input.messageId,
delta: bufferedText,
@@ -915,7 +919,7 @@ const make = Effect.gen(function* () {
if (hasRenderableText) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(input.event, input.finalDeltaCommandTag),
commandId: yield* providerCommandId(input.event, input.finalDeltaCommandTag),
threadId: input.threadId,
messageId: input.messageId,
delta: text,
@@ -927,7 +931,7 @@ const make = Effect.gen(function* () {
if (input.hasProjectedMessage || hasRenderableText) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.complete",
commandId: providerCommandId(input.event, input.commandTag),
commandId: yield* providerCommandId(input.event, input.commandTag),
threadId: input.threadId,
messageId: input.messageId,
...(input.turnId ? { turnId: input.turnId } : {}),
@@ -1003,7 +1007,7 @@ const make = Effect.gen(function* () {
const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
commandId: yield* providerCommandId(input.event, "proposed-plan-upsert"),
threadId: input.threadId,
proposedPlan: {
id: input.planId,
@@ -1159,10 +1163,11 @@ const make = Effect.gen(function* () {
return;
}
const commandUuid = yield* crypto.randomUUIDv4;
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.make(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
`provider:source-proposed-plan-implemented:${implementationThreadId}:${commandUuid}`,
),
threadId: sourceThread.id,
proposedPlan: {
@@ -1296,7 +1301,7 @@ const make = Effect.gen(function* () {
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "thread-session-set"),
commandId: yield* providerCommandId(event, "thread-session-set"),
threadId: thread.id,
session: {
threadId: thread.id,
@@ -1342,7 +1347,7 @@ const make = Effect.gen(function* () {
if (spillChunk.length > 0) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(event, "assistant-delta-buffer-spill"),
commandId: yield* providerCommandId(event, "assistant-delta-buffer-spill"),
threadId: thread.id,
messageId: assistantMessageId,
delta: spillChunk,
@@ -1353,7 +1358,7 @@ const make = Effect.gen(function* () {
} else {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(event, "assistant-delta"),
commandId: yield* providerCommandId(event, "assistant-delta"),
threadId: thread.id,
messageId: assistantMessageId,
delta: assistantDelta,
@@ -1546,7 +1551,7 @@ const make = Effect.gen(function* () {
if (shouldApplyRuntimeError) {
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "runtime-error-session-set"),
commandId: yield* providerCommandId(event, "runtime-error-session-set"),
threadId: thread.id,
session: {
threadId: thread.id,
@@ -1568,7 +1573,7 @@ const make = Effect.gen(function* () {
if (event.type === "thread.metadata.updated" && event.payload.name) {
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: providerCommandId(event, "thread-meta-update"),
commandId: yield* providerCommandId(event, "thread-meta-update"),
threadId: thread.id,
title: event.payload.name,
});
@@ -1596,7 +1601,7 @@ const make = Effect.gen(function* () {
);
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: providerCommandId(event, "thread-turn-diff-complete"),
commandId: yield* providerCommandId(event, "thread-turn-diff-complete"),
threadId: thread.id,
turnId,
completedAt: now,
@@ -1613,13 +1618,17 @@ const make = Effect.gen(function* () {
const activities = runtimeEventToActivities(event);
yield* Effect.forEach(activities, (activity) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: providerCommandId(event, "thread-activity-append"),
threadId: thread.id,
activity,
createdAt: activity.createdAt,
}),
providerCommandId(event, "thread-activity-append").pipe(
Effect.flatMap((commandId) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId,
threadId: thread.id,
activity,
createdAt: activity.createdAt,
}),
),
),
).pipe(Effect.asVoid);
});
@@ -6,11 +6,11 @@ import {
ThreadId,
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { describe, expect, it } from "vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
@@ -20,93 +20,87 @@ const asEventId = (value: string): EventId => EventId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
async function seedReadModel(): Promise<OrchestrationReadModel> {
const seedReadModel = Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-delete"),
type: "project.created",
occurredAt: now,
commandId: asCommandId("cmd-project-create"),
causationEventId: null,
correlationId: asCommandId("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-delete"),
title: "Project Delete",
workspaceRoot: "/tmp/project-delete",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
}),
);
const withProject = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-delete"),
type: "project.created",
occurredAt: now,
commandId: asCommandId("cmd-project-create"),
causationEventId: null,
correlationId: asCommandId("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-delete"),
title: "Project Delete",
workspaceRoot: "/tmp/project-delete",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const withFirstThread = await Effect.runPromise(
projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create-1"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-1"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-1"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-1"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-1"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
const withFirstThread = yield* projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create-1"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-1"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-1"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-1"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-1"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
}),
);
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
return Effect.runPromise(
projectEvent(withFirstThread, {
sequence: 3,
eventId: asEventId("evt-thread-create-2"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-2"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-2"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-2"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-2"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 2",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
return yield* projectEvent(withFirstThread, {
sequence: 3,
eventId: asEventId("evt-thread-create-2"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-2"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-2"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-2"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-2"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 2",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
}),
);
}
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
});
type PlannedEvent = Omit<OrchestrationEvent, "sequence">;
@@ -142,12 +136,11 @@ function normalizeDeleteEvent(event: PlannedEvent | ReadonlyArray<PlannedEvent>)
});
}
describe("decider deletion flows", () => {
it("rejects deleting a non-empty project without force", async () => {
const readModel = await seedReadModel();
await expect(
Effect.runPromise(
it.layer(NodeServices.layer)("decider deletion flows", (it) => {
it.effect("rejects deleting a non-empty project without force", () =>
Effect.gen(function* () {
const readModel = yield* seedReadModel;
const error = yield* Effect.flip(
decideOrchestrationCommand({
command: {
type: "project.delete",
@@ -156,72 +149,69 @@ describe("decider deletion flows", () => {
},
readModel,
}),
),
).rejects.toThrow("cannot be deleted without force=true");
});
);
expect(error.message).toContain("cannot be deleted without force=true");
}),
);
it("reuses thread.delete semantics when force-deleting a non-empty project", async () => {
const readModel = await seedReadModel();
const projectDeleteCommand: Extract<OrchestrationCommand, { type: "project.delete" }> = {
type: "project.delete",
commandId: asCommandId("cmd-project-delete-force"),
projectId: asProjectId("project-delete"),
force: true,
};
it.effect("reuses thread.delete semantics when force-deleting a non-empty project", () =>
Effect.gen(function* () {
const readModel = yield* seedReadModel;
const projectDeleteCommand: Extract<OrchestrationCommand, { type: "project.delete" }> = {
type: "project.delete",
commandId: asCommandId("cmd-project-delete-force"),
projectId: asProjectId("project-delete"),
force: true,
};
const forcedResult = await Effect.runPromise(
decideOrchestrationCommand({
const forcedResult = yield* decideOrchestrationCommand({
command: projectDeleteCommand,
readModel,
}),
);
const forcedEvents = Array.isArray(forcedResult) ? forcedResult : [forcedResult];
});
const forcedEvents = Array.isArray(forcedResult) ? forcedResult : [forcedResult];
expect(forcedEvents.map((event) => event.type)).toEqual([
"thread.deleted",
"thread.deleted",
"project.deleted",
]);
expect(forcedEvents.map((event) => event.type)).toEqual([
"thread.deleted",
"thread.deleted",
"project.deleted",
]);
let sequentialReadModel = readModel;
let nextSequence = readModel.snapshotSequence;
const sequentialEvents: PlannedEvent[] = [];
for (const nextCommand of [
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-1"),
},
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-2"),
},
{
type: "project.delete",
commandId: projectDeleteCommand.commandId,
projectId: asProjectId("project-delete"),
},
] satisfies ReadonlyArray<OrchestrationCommand>) {
const decided = await Effect.runPromise(
decideOrchestrationCommand({
let sequentialReadModel = readModel;
let nextSequence = readModel.snapshotSequence;
const sequentialEvents: PlannedEvent[] = [];
for (const nextCommand of [
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-1"),
},
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-2"),
},
{
type: "project.delete",
commandId: projectDeleteCommand.commandId,
projectId: asProjectId("project-delete"),
},
] satisfies ReadonlyArray<OrchestrationCommand>) {
const decided = yield* decideOrchestrationCommand({
command: nextCommand,
readModel: sequentialReadModel,
}),
);
const nextEvents = Array.isArray(decided) ? decided : [decided];
sequentialEvents.push(...nextEvents);
for (const nextEvent of nextEvents) {
nextSequence += 1;
sequentialReadModel = await Effect.runPromise(
projectEvent(sequentialReadModel, {
});
const nextEvents = Array.isArray(decided) ? decided : [decided];
sequentialEvents.push(...nextEvents);
for (const nextEvent of nextEvents) {
nextSequence += 1;
sequentialReadModel = yield* projectEvent(sequentialReadModel, {
...nextEvent,
sequence: nextSequence,
}),
);
});
}
}
}
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
});
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
}),
);
});
@@ -8,8 +8,9 @@ import {
ProviderInstanceId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { describe, expect, it } from "vitest";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
@@ -17,14 +18,13 @@ import { createEmptyReadModel, projectEvent } from "./projector.ts";
const asEventId = (value: string): EventId => EventId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asMessageId = (value: string): MessageId => MessageId.make(value);
it.layer(NodeServices.layer)("decider project scripts", (it) => {
it.effect("emits empty scripts on project.create", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const readModel = createEmptyReadModel(now);
describe("decider project scripts", () => {
it("emits empty scripts on project.create", async () => {
const now = "2026-01-01T00:00:00.000Z";
const readModel = createEmptyReadModel(now);
const result = await Effect.runPromise(
decideOrchestrationCommand({
const result = yield* decideOrchestrationCommand({
command: {
type: "project.create",
commandId: CommandId.make("cmd-project-create-scripts"),
@@ -34,19 +34,19 @@ describe("decider project scripts", () => {
createdAt: now,
},
readModel,
}),
);
});
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.created");
expect((event.payload as { scripts: unknown[] }).scripts).toEqual([]);
});
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.created");
expect((event.payload as { scripts: unknown[] }).scripts).toEqual([]);
}),
);
it("propagates scripts in project.meta.update payload", async () => {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const readModel = await Effect.runPromise(
projectEvent(initial, {
it.effect("propagates scripts in project.meta.update payload", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const readModel = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create-scripts"),
aggregateKind: "project",
@@ -66,21 +66,19 @@ describe("decider project scripts", () => {
createdAt: now,
updatedAt: now,
},
}),
);
});
const scripts = [
{
id: "lint",
name: "Lint",
command: "bun run lint",
icon: "lint",
runOnWorktreeCreate: false,
},
] as const;
const scripts = [
{
id: "lint",
name: "Lint",
command: "bun run lint",
icon: "lint",
runOnWorktreeCreate: false,
},
] as const;
const result = await Effect.runPromise(
decideOrchestrationCommand({
const result = yield* decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-update-scripts"),
@@ -88,19 +86,19 @@ describe("decider project scripts", () => {
scripts: Array.from(scripts),
},
readModel,
}),
);
});
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.meta-updated");
expect((event.payload as { scripts?: unknown[] }).scripts).toEqual(scripts);
});
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.meta-updated");
expect((event.payload as { scripts?: unknown[] }).scripts).toEqual(scripts);
}),
);
it("emits user message and turn-start-requested events for thread.turn.start", async () => {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
it.effect("emits user message and turn-start-requested events for thread.turn.start", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
@@ -120,10 +118,8 @@ describe("decider project scripts", () => {
createdAt: now,
updatedAt: now,
},
}),
);
const readModel = await Effect.runPromise(
projectEvent(withProject, {
});
const readModel = yield* projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
@@ -149,11 +145,9 @@ describe("decider project scripts", () => {
createdAt: now,
updatedAt: now,
},
}),
);
});
const result = await Effect.runPromise(
decideOrchestrationCommand({
const result = yield* decideOrchestrationCommand({
command: {
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start"),
@@ -173,35 +167,35 @@ describe("decider project scripts", () => {
createdAt: now,
},
readModel,
}),
);
});
expect(Array.isArray(result)).toBe(true);
const events = Array.isArray(result) ? result : [result];
expect(events).toHaveLength(2);
expect(events[0]?.type).toBe("thread.message-sent");
const turnStartEvent = events[1];
expect(turnStartEvent?.type).toBe("thread.turn-start-requested");
expect(turnStartEvent?.causationEventId).toBe(events[0]?.eventId ?? null);
if (turnStartEvent?.type !== "thread.turn-start-requested") {
return;
}
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.make("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
runtimeMode: "approval-required",
});
});
expect(Array.isArray(result)).toBe(true);
const events = Array.isArray(result) ? result : [result];
expect(events).toHaveLength(2);
expect(events[0]?.type).toBe("thread.message-sent");
const turnStartEvent = events[1];
expect(turnStartEvent?.type).toBe("thread.turn-start-requested");
expect(turnStartEvent?.causationEventId).toBe(events[0]?.eventId ?? null);
if (turnStartEvent?.type !== "thread.turn-start-requested") {
return;
}
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.make("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
runtimeMode: "approval-required",
});
}),
);
it("emits thread.runtime-mode-set from thread.runtime-mode.set", async () => {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
it.effect("emits thread.runtime-mode-set from thread.runtime-mode.set", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
@@ -221,10 +215,8 @@ describe("decider project scripts", () => {
createdAt: now,
updatedAt: now,
},
}),
);
const readModel = await Effect.runPromise(
projectEvent(withProject, {
});
const readModel = yield* projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
@@ -250,11 +242,9 @@ describe("decider project scripts", () => {
createdAt: now,
updatedAt: now,
},
}),
);
});
const result = await Effect.runPromise(
decideOrchestrationCommand({
const result = yield* decideOrchestrationCommand({
command: {
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set"),
@@ -263,27 +253,27 @@ describe("decider project scripts", () => {
createdAt: now,
},
readModel,
}),
);
});
const singleResult = Array.isArray(result) ? null : result;
if (singleResult === null) {
throw new Error("Expected a single runtime-mode-set event.");
}
expect(singleResult).toMatchObject({
type: "thread.runtime-mode-set",
payload: {
threadId: ThreadId.make("thread-1"),
runtimeMode: "approval-required",
},
});
});
const singleResult = Array.isArray(result) ? null : result;
if (singleResult === null) {
throw new Error("Expected a single runtime-mode-set event.");
}
expect(singleResult).toMatchObject({
type: "thread.runtime-mode-set",
payload: {
threadId: ThreadId.make("thread-1"),
runtimeMode: "approval-required",
},
});
}),
);
it("emits thread.interaction-mode-set from thread.interaction-mode.set", async () => {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
it.effect("emits thread.interaction-mode-set from thread.interaction-mode.set", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
@@ -303,10 +293,8 @@ describe("decider project scripts", () => {
createdAt: now,
updatedAt: now,
},
}),
);
const readModel = await Effect.runPromise(
projectEvent(withProject, {
});
const readModel = yield* projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
@@ -332,11 +320,9 @@ describe("decider project scripts", () => {
createdAt: now,
updatedAt: now,
},
}),
);
});
const result = await Effect.runPromise(
decideOrchestrationCommand({
const result = yield* decideOrchestrationCommand({
command: {
type: "thread.interaction-mode.set",
commandId: CommandId.make("cmd-interaction-mode-set"),
@@ -345,19 +331,19 @@ describe("decider project scripts", () => {
createdAt: now,
},
readModel,
}),
);
});
const singleResult = Array.isArray(result) ? null : result;
if (singleResult === null) {
throw new Error("Expected a single interaction-mode-set event.");
}
expect(singleResult).toMatchObject({
type: "thread.interaction-mode-set",
payload: {
threadId: ThreadId.make("thread-1"),
interactionMode: "plan",
},
});
});
const singleResult = Array.isArray(result) ? null : result;
if (singleResult === null) {
throw new Error("Expected a single interaction-mode-set event.");
}
expect(singleResult).toMatchObject({
type: "thread.interaction-mode-set",
payload: {
threadId: ThreadId.make("thread-1"),
interactionMode: "plan",
},
});
}),
);
});
+86 -65
View File
@@ -1,10 +1,13 @@
import type {
OrchestrationCommand,
OrchestrationEvent,
OrchestrationReadModel,
import {
EventId,
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import type * as PlatformError from "effect/PlatformError";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
import {
@@ -27,17 +30,27 @@ function withEventBase(
readonly occurredAt: string;
readonly metadata?: OrchestrationEvent["metadata"];
},
): Omit<OrchestrationEvent, "sequence" | "type" | "payload"> {
return {
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
aggregateKind: input.aggregateKind,
aggregateId: input.aggregateId,
occurredAt: input.occurredAt,
commandId: input.commandId,
causationEventId: null,
correlationId: input.commandId,
metadata: input.metadata ?? {},
};
): Effect.Effect<
Omit<OrchestrationEvent, "sequence" | "type" | "payload">,
PlatformError.PlatformError,
Crypto.Crypto
> {
return Crypto.Crypto.pipe(
Effect.flatMap((crypto) =>
crypto.randomUUIDv4.pipe(
Effect.map((eventId) => ({
eventId: EventId.make(eventId),
aggregateKind: input.aggregateKind,
aggregateId: input.aggregateId,
occurredAt: input.occurredAt,
commandId: input.commandId,
causationEventId: null,
correlationId: input.commandId,
metadata: input.metadata ?? {},
})),
),
),
);
}
type PlannedOrchestrationEvent = Omit<OrchestrationEvent, "sequence">;
@@ -52,7 +65,11 @@ const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
}: {
readonly commands: ReadonlyArray<OrchestrationCommand>;
readonly readModel: OrchestrationReadModel;
}): Effect.fn.Return<ReadonlyArray<PlannedOrchestrationEvent>, OrchestrationCommandInvariantError> {
}): Effect.fn.Return<
ReadonlyArray<PlannedOrchestrationEvent>,
OrchestrationCommandInvariantError | PlatformError.PlatformError,
Crypto.Crypto
> {
let nextReadModel = readModel;
let nextSequence = readModel.snapshotSequence;
const plannedEvents: PlannedOrchestrationEvent[] = [];
@@ -82,7 +99,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}: {
readonly command: OrchestrationCommand;
readonly readModel: OrchestrationReadModel;
}): Effect.fn.Return<DecideOrchestrationCommandResult, OrchestrationCommandInvariantError> {
}): Effect.fn.Return<
DecideOrchestrationCommandResult,
OrchestrationCommandInvariantError | PlatformError.PlatformError,
Crypto.Crypto
> {
switch (command.type) {
case "project.create": {
yield* requireProjectAbsent({
@@ -92,12 +113,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "project",
aggregateId: command.projectId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
type: "project.created",
payload: {
projectId: command.projectId,
@@ -119,12 +140,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "project",
aggregateId: command.projectId,
occurredAt,
commandId: command.commandId,
}),
})),
type: "project.meta-updated",
payload: {
projectId: command.projectId,
@@ -176,12 +197,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
const occurredAt = yield* nowIso;
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "project",
aggregateId: command.projectId,
occurredAt,
commandId: command.commandId,
}),
})),
type: "project.deleted" as const,
payload: {
projectId: command.projectId,
@@ -202,12 +223,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
type: "thread.created",
payload: {
threadId: command.threadId,
@@ -232,12 +253,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
}),
})),
type: "thread.deleted",
payload: {
threadId: command.threadId,
@@ -254,12 +275,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
}),
})),
type: "thread.archived",
payload: {
threadId: command.threadId,
@@ -277,12 +298,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
}),
})),
type: "thread.unarchived",
payload: {
threadId: command.threadId,
@@ -299,12 +320,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
}),
})),
type: "thread.meta-updated",
payload: {
threadId: command.threadId,
@@ -327,12 +348,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
}),
})),
type: "thread.runtime-mode-set",
payload: {
threadId: command.threadId,
@@ -350,12 +371,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
}),
})),
type: "thread.interaction-mode-set",
payload: {
threadId: command.threadId,
@@ -396,12 +417,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
}
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
type: "thread.message-sent",
payload: {
threadId: command.threadId,
@@ -416,12 +437,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
},
};
const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
causationEventId: userMessageEvent.eventId,
type: "thread.turn-start-requested",
payload: {
@@ -447,12 +468,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
type: "thread.turn-interrupt-requested",
payload: {
threadId: command.threadId,
@@ -469,7 +490,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
@@ -477,7 +498,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
metadata: {
requestId: command.requestId,
},
}),
})),
type: "thread.approval-response-requested",
payload: {
threadId: command.threadId,
@@ -495,7 +516,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
@@ -503,7 +524,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
metadata: {
requestId: command.requestId,
},
}),
})),
type: "thread.user-input-response-requested",
payload: {
threadId: command.threadId,
@@ -521,12 +542,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
type: "thread.checkpoint-revert-requested",
payload: {
threadId: command.threadId,
@@ -543,12 +564,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
type: "thread.session-stop-requested",
payload: {
threadId: command.threadId,
@@ -564,13 +585,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
metadata: {},
}),
})),
type: "thread.session-set",
payload: {
threadId: command.threadId,
@@ -586,12 +607,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
type: "thread.message-sent",
payload: {
threadId: command.threadId,
@@ -613,12 +634,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
type: "thread.message-sent",
payload: {
threadId: command.threadId,
@@ -640,12 +661,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
type: "thread.proposed-plan-upserted",
payload: {
threadId: command.threadId,
@@ -661,12 +682,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
type: "thread.turn-diff-completed",
payload: {
threadId: command.threadId,
@@ -688,12 +709,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
})),
type: "thread.reverted",
payload: {
threadId: command.threadId,
@@ -717,13 +738,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
.requestId as OrchestrationEvent["metadata"]["requestId"])
: undefined;
return {
...withEventBase({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
...(requestId !== undefined ? { metadata: { requestId } } : {}),
}),
})),
type: "thread.activity-appended",
payload: {
threadId: command.threadId,
+4 -2
View File
@@ -58,8 +58,10 @@ export const orchestrationSnapshotRouteLayer = HttpRouter.add(
status: 200,
});
}).pipe(
Effect.catchTag("OrchestrationDispatchCommandError", respondToOrchestrationHttpError),
Effect.catchTag("OrchestrationGetSnapshotError", respondToOrchestrationHttpError),
Effect.catchTags({
OrchestrationDispatchCommandError: respondToOrchestrationHttpError,
OrchestrationGetSnapshotError: respondToOrchestrationHttpError,
}),
),
);
@@ -40,7 +40,7 @@ const AuthSessionDbRow = Schema.Struct({
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
});
function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): typeof AuthSessionRecord.Type {
function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecord {
return {
sessionId: row.sessionId,
subject: row.subject,
@@ -1,6 +1,4 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
yield* SqlClient.SqlClient;
});
export default Effect.asVoid(SqlClient.SqlClient);
@@ -252,14 +252,12 @@ export const layerConfig = (
config: Config.Wrap<SqliteClientConfig>,
): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
Layer.effectContext(
Config.unwrap(config)
.asEffect()
.pipe(
Effect.flatMap(make),
Effect.map((client) =>
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
),
Config.unwrap(config).pipe(
Effect.flatMap(make),
Effect.map((client) =>
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
),
),
).pipe(Layer.provide(Reactivity.layer));
export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient> =>
@@ -1,12 +1,12 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -651,7 +651,9 @@ it.layer(NodeServices.layer)("launchEditorProcess", (it) => {
Effect.gen(function* () {
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {});
const result = yield* launchEditorProcess({
command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
command: `t3code-no-such-command-${yield* Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
)}`,
args: [],
}).pipe(Effect.provide(spawnerLayer), Effect.result);
assert.equal(result._tag, "Failure");
+1 -1
View File
@@ -257,7 +257,7 @@ export interface ExternalLauncherShape {
* ExternalLauncher - Service tag for browser/editor launch operations.
*/
export class ExternalLauncher extends Context.Service<ExternalLauncher, ExternalLauncherShape>()(
"t3/process/ExternalLauncher",
"t3/process/externalLauncher",
) {}
// ==============================
+1 -1
View File
@@ -90,7 +90,7 @@ export interface ProcessRunnerShape {
}
export class ProcessRunner extends Context.Service<ProcessRunner, ProcessRunnerShape>()(
"t3/process/ProcessRunner",
"t3/processRunner",
) {}
const DEFAULT_TIMEOUT = "60 seconds";
@@ -41,4 +41,4 @@ export interface ProjectSetupScriptRunnerShape {
export class ProjectSetupScriptRunner extends Context.Service<
ProjectSetupScriptRunner,
ProjectSetupScriptRunnerShape
>()("t3/project/ProjectSetupScriptRunner") {}
>()("t3/project/Services/ProjectSetupScriptRunner") {}
@@ -15,6 +15,7 @@
import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Cache from "effect/Cache";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
@@ -77,6 +78,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
export type ClaudeDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
@@ -23,6 +23,7 @@
*/
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
@@ -69,6 +70,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
*/
export type CodexDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
Loaded 100 of 214 files, more files were not shown because too many files have changed in this diff. Show more