Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1cc9019479 | ||
|
|
4db082a2d2 | ||
|
|
907f4d7501 | ||
|
|
1e929ad74f | ||
|
|
3ee6fbba2c | ||
|
|
6b48288f77 | ||
|
|
2632c9251e | ||
|
|
89672b3d89 | ||
|
|
90fea7bb2f | ||
|
|
7793bd6de7 | ||
|
|
7f03f4d19a | ||
|
|
4ac2618403 | ||
|
|
e7b41d72a8 | ||
|
|
c87cc163f8 | ||
|
|
570cc46e51 | ||
|
|
8d65f131f0 | ||
|
|
fbd89d303c | ||
|
|
e793c07a21 | ||
|
|
ab95f11360 | ||
|
|
d950f45672 | ||
|
|
594df47fb7 | ||
|
|
b487b0588c | ||
|
|
3c9c14f6b3 | ||
|
|
8916eeb042 | ||
|
|
6db3098a21 | ||
|
|
eba28035d2 | ||
|
|
a49c2d1301 | ||
|
|
509a7a84cc | ||
|
|
9aae833e45 | ||
|
|
b305a44b9f | ||
|
|
7a285d1172 | ||
|
|
37908166ed | ||
|
|
da56bd50d9 | ||
|
|
e27b561b84 | ||
|
|
df425a86ca | ||
|
|
2faef729a4 | ||
|
|
cca1bacc71 | ||
|
|
f1ae412400 | ||
|
|
ccac2d8228 | ||
|
|
58587923b4 | ||
|
|
343074470f | ||
|
|
3c78384d43 | ||
|
|
dcf4d6d38e | ||
|
|
43d534ad67 | ||
|
|
4de9770810 | ||
|
|
df4223bf7d | ||
|
|
14e56f8a09 |
No files matched your search
@@ -46,14 +46,6 @@ 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
|
||||
|
||||
|
||||
@@ -98,14 +98,6 @@ 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
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"dev:electron": "node scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"start": "node scripts/start-electron.mjs",
|
||||
"typecheck": "tsgo --noEmit",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
@@ -25,9 +25,11 @@
|
||||
"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)"
|
||||
|
||||
@@ -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,8 +26,7 @@ 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 = Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
const makeDesktopRunId = Random.nextUUIDv4.pipe(
|
||||
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
|
||||
);
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ export interface DesktopAppIdentityShape {
|
||||
export class DesktopAppIdentity extends Context.Service<
|
||||
DesktopAppIdentity,
|
||||
DesktopAppIdentityShape
|
||||
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
|
||||
>()("t3/desktop/AppIdentity") {}
|
||||
|
||||
const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
const trimmed = value.trim();
|
||||
|
||||
@@ -18,7 +18,7 @@ export interface DesktopAssetsShape {
|
||||
}
|
||||
|
||||
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
|
||||
"@t3tools/desktop/app/DesktopAssets",
|
||||
"t3/desktop/Assets",
|
||||
) {}
|
||||
|
||||
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
|
||||
|
||||
@@ -32,7 +32,9 @@ const makeEnvironment = (
|
||||
overrides: Partial<DesktopEnvironment.MakeDesktopEnvironmentInput> = {},
|
||||
env: Record<string, string | undefined> = {},
|
||||
) =>
|
||||
DesktopEnvironment.DesktopEnvironment.pipe(Effect.provide(makeEnvironmentLayer(overrides, env)));
|
||||
Effect.gen(function* () {
|
||||
return yield* DesktopEnvironment.DesktopEnvironment;
|
||||
}).pipe(Effect.provide(makeEnvironmentLayer(overrides, env)));
|
||||
|
||||
describe("DesktopEnvironment", () => {
|
||||
it.effect("derives state paths and development identity inside Effect", () =>
|
||||
|
||||
@@ -78,7 +78,7 @@ export interface DesktopEnvironmentShape {
|
||||
export class DesktopEnvironment extends Context.Service<
|
||||
DesktopEnvironment,
|
||||
DesktopEnvironmentShape
|
||||
>()("@t3tools/desktop/app/DesktopEnvironment") {}
|
||||
>()("t3/desktop/Environment") {}
|
||||
|
||||
const APP_BASE_NAME = "T3 Code";
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ export interface DesktopShutdownShape {
|
||||
}
|
||||
|
||||
export class DesktopShutdown extends Context.Service<DesktopShutdown, DesktopShutdownShape>()(
|
||||
"@t3tools/desktop/app/DesktopLifecycle/DesktopShutdown",
|
||||
"t3/desktop/Shutdown",
|
||||
) {}
|
||||
|
||||
const makeShutdown = Effect.gen(function* () {
|
||||
@@ -61,11 +61,8 @@ 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>()(
|
||||
"@t3tools/desktop/app/DesktopLifecycle",
|
||||
"t3/desktop/Lifecycle",
|
||||
) {}
|
||||
|
||||
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
|
||||
|
||||
@@ -43,7 +43,7 @@ export interface DesktopBackendOutputLogShape {
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
DesktopBackendOutputLogShape
|
||||
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLog") {}
|
||||
>()("t3/desktop/BackendOutputLog") {}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
@@ -9,7 +9,7 @@ export interface DesktopStateShape {
|
||||
}
|
||||
|
||||
export class DesktopState extends Context.Service<DesktopState, DesktopStateShape>()(
|
||||
"@t3tools/desktop/app/DesktopState",
|
||||
"t3/desktop/State",
|
||||
) {}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
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 PlatformError from "effect/PlatformError";
|
||||
import * as Random from "effect/Random";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
@@ -15,16 +13,13 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
|
||||
export interface DesktopBackendConfigurationShape {
|
||||
readonly resolve: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
readonly resolve: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
|
||||
}
|
||||
|
||||
export class DesktopBackendConfiguration extends Context.Service<
|
||||
DesktopBackendConfiguration,
|
||||
DesktopBackendConfigurationShape
|
||||
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
|
||||
>()("t3/desktop/BackendConfiguration") {}
|
||||
|
||||
interface BackendObservabilitySettings {
|
||||
readonly otlpTracesUrl: Option.Option<string>;
|
||||
@@ -85,6 +80,23 @@ 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;
|
||||
@@ -136,22 +148,11 @@ 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;
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken(tokenRef);
|
||||
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
|
||||
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
|
||||
>()("t3/desktop/BackendManager") {}
|
||||
|
||||
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-manager");
|
||||
@@ -329,19 +329,9 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
}
|
||||
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
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 config = yield* configuration.resolve;
|
||||
const entryExists = yield* fileSystem
|
||||
.exists(config.value.entryPath)
|
||||
.exists(config.entryPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
yield* cancelRestart;
|
||||
@@ -349,11 +339,11 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
...latest,
|
||||
desiredRunning: true,
|
||||
ready: false,
|
||||
config: Option.some(config.value),
|
||||
config: Option.some(config),
|
||||
}));
|
||||
|
||||
if (!entryExists) {
|
||||
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
|
||||
yield* scheduleRestart(`missing server entry at ${config.entryPath}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -435,7 +425,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
});
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
...config,
|
||||
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
@@ -443,7 +433,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
}));
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
|
||||
details: `pid=${pid} port=${config.bootstrap.port} cwd=${config.cwd}`,
|
||||
});
|
||||
}),
|
||||
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
|
||||
|
||||
@@ -275,7 +275,7 @@ export interface DesktopServerExposureShape {
|
||||
export class DesktopServerExposure extends Context.Service<
|
||||
DesktopServerExposure,
|
||||
DesktopServerExposureShape
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
|
||||
>()("t3/desktop/ServerExposure") {}
|
||||
|
||||
export interface DesktopNetworkInterfacesServiceShape {
|
||||
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
|
||||
@@ -284,7 +284,7 @@ export interface DesktopNetworkInterfacesServiceShape {
|
||||
export class DesktopNetworkInterfacesService extends Context.Service<
|
||||
DesktopNetworkInterfacesService,
|
||||
DesktopNetworkInterfacesServiceShape
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure/DesktopNetworkInterfacesService") {}
|
||||
>()("t3/desktop/ServerExposure/NetworkInterfaces") {}
|
||||
|
||||
interface RuntimeState {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
|
||||
@@ -39,7 +39,7 @@ export interface ElectronAppShape {
|
||||
}
|
||||
|
||||
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
|
||||
"@t3tools/desktop/electron/ElectronApp",
|
||||
"t3/desktop/electron/App",
|
||||
) {}
|
||||
|
||||
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
|
||||
|
||||
@@ -29,7 +29,7 @@ export interface ElectronDialogShape {
|
||||
}
|
||||
|
||||
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
|
||||
"@t3tools/desktop/electron/ElectronDialog",
|
||||
"t3/desktop/electron/Dialog",
|
||||
) {}
|
||||
|
||||
const make = ElectronDialog.of({
|
||||
|
||||
@@ -33,7 +33,7 @@ export interface ElectronMenuShape {
|
||||
}
|
||||
|
||||
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
|
||||
"@t3tools/desktop/electron/ElectronMenu",
|
||||
"t3/desktop/electron/Menu",
|
||||
) {}
|
||||
|
||||
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
|
||||
|
||||
@@ -52,7 +52,7 @@ export interface ElectronProtocolShape {
|
||||
}
|
||||
|
||||
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
|
||||
"@t3tools/desktop/electron/ElectronProtocol",
|
||||
"t3/desktop/electron/Protocol",
|
||||
) {}
|
||||
|
||||
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/electron/ElectronSafeStorage") {}
|
||||
>()("@t3tools/desktop/ElectronSafeStorage") {}
|
||||
|
||||
const make = ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
|
||||
@@ -26,7 +26,7 @@ export interface ElectronShellShape {
|
||||
}
|
||||
|
||||
export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
|
||||
"@t3tools/desktop/electron/ElectronShell",
|
||||
"t3/desktop/electron/Shell",
|
||||
) {}
|
||||
|
||||
const make = ElectronShell.of({
|
||||
|
||||
@@ -13,7 +13,7 @@ export interface ElectronThemeShape {
|
||||
}
|
||||
|
||||
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
|
||||
"@t3tools/desktop/electron/ElectronTheme",
|
||||
"t3/desktop/electron/Theme",
|
||||
) {}
|
||||
|
||||
const make = ElectronTheme.of({
|
||||
|
||||
@@ -67,7 +67,7 @@ export interface ElectronUpdaterShape {
|
||||
}
|
||||
|
||||
export class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
|
||||
"@t3tools/desktop/electron/ElectronUpdater",
|
||||
"t3/desktop/electron/Updater",
|
||||
) {}
|
||||
|
||||
export const layer = Layer.succeed(ElectronUpdater, {
|
||||
|
||||
@@ -33,7 +33,7 @@ export interface ElectronWindowShape {
|
||||
}
|
||||
|
||||
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
|
||||
"@t3tools/desktop/electron/ElectronWindow",
|
||||
"t3/desktop/electron/Window",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
|
||||
@@ -42,9 +42,7 @@ export interface DesktopIpcShape {
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
}
|
||||
|
||||
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
|
||||
"@t3tools/desktop/ipc/DesktopIpc",
|
||||
) {}
|
||||
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()("t3/desktop/Ipc") {}
|
||||
|
||||
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
|
||||
DesktopIpc.of({
|
||||
|
||||
@@ -6,7 +6,6 @@ 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";
|
||||
@@ -14,6 +13,7 @@ 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
|
||||
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
|
||||
>()("t3/desktop/AppSettings") {}
|
||||
|
||||
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 tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${suffix}.tmp`;
|
||||
const encoded = yield* encodeDesktopSettingsJson(
|
||||
toDesktopSettingsDocument(input.settings, input.defaultSettings),
|
||||
);
|
||||
@@ -240,7 +240,6 @@ 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 = (
|
||||
@@ -252,18 +251,13 @@ export const layer = Layer.effect(
|
||||
return Effect.succeed([settingsChange(settings, false), settings] as const);
|
||||
}
|
||||
|
||||
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,
|
||||
}),
|
||||
),
|
||||
return writeSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.desktopSettingsPath,
|
||||
settings: nextSettings,
|
||||
defaultSettings: environment.defaultDesktopSettings,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) => new DesktopSettingsWriteError({ cause })),
|
||||
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
|
||||
);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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";
|
||||
@@ -9,6 +8,7 @@ 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
|
||||
>()("@t3tools/desktop/settings/DesktopClientSettings") {}
|
||||
>()("t3/desktop/ClientSettings") {}
|
||||
|
||||
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 tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${suffix}.tmp`;
|
||||
const encoded = yield* encodeClientSettingsJson(input.settings);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
@@ -90,24 +90,18 @@ 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) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeClientSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
settings,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
writeClientSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
settings,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) => new DesktopClientSettingsWriteError({ cause })),
|
||||
Effect.withSpan("desktop.clientSettings.set"),
|
||||
),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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";
|
||||
@@ -10,6 +9,7 @@ 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
|
||||
>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}
|
||||
>()("t3/desktop/SavedEnvironments") {}
|
||||
|
||||
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 tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
|
||||
const tempPath = `${input.registryPath}.${process.pid}.${suffix}.tmp`;
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
@@ -247,22 +247,14 @@ 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) =>
|
||||
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 })),
|
||||
);
|
||||
writeRegistryDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
document,
|
||||
}).pipe(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
|
||||
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
|
||||
>()("t3/desktop/ShellEnvironment") {}
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
|
||||
@@ -68,7 +68,7 @@ export interface DesktopSshEnvironmentShape {
|
||||
export class DesktopSshEnvironment extends Context.Service<
|
||||
DesktopSshEnvironment,
|
||||
DesktopSshEnvironmentShape
|
||||
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}
|
||||
>()("t3/desktop/SshEnvironment") {}
|
||||
|
||||
export interface DesktopSshEnvironmentLayerOptions {
|
||||
readonly resolveCliPackageSpec?: () => string;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
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";
|
||||
@@ -87,7 +86,6 @@ 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,7 +2,6 @@ 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";
|
||||
@@ -10,6 +9,7 @@ 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
|
||||
>()("@t3tools/desktop/ssh/DesktopSshPasswordPrompts") {}
|
||||
>()("t3/desktop/SshPasswordPrompts") {}
|
||||
|
||||
interface PendingSshPasswordPrompt {
|
||||
readonly requestId: string;
|
||||
@@ -163,7 +163,6 @@ 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;
|
||||
@@ -231,11 +230,7 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
|
||||
});
|
||||
}
|
||||
|
||||
const requestId = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
() => new DesktopSshPromptUnavailableError({ reason: "Secure randomness is unavailable." }),
|
||||
),
|
||||
);
|
||||
const requestId = yield* Random.nextUUIDv4;
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.formatIso(
|
||||
DateTime.add(now, { milliseconds: passwordPromptTimeoutMs }),
|
||||
|
||||
@@ -53,7 +53,7 @@ export interface DesktopSshRemoteApiShape {
|
||||
export class DesktopSshRemoteApi extends Context.Service<
|
||||
DesktopSshRemoteApi,
|
||||
DesktopSshRemoteApiShape
|
||||
>()("@t3tools/desktop/ssh/DesktopSshRemoteApi") {}
|
||||
>()("t3/desktop/SshRemoteApi") {}
|
||||
|
||||
const decodeExecutionEnvironmentDescriptor = Schema.decodeUnknownEffect(
|
||||
ExecutionEnvironmentDescriptor,
|
||||
|
||||
@@ -100,7 +100,7 @@ export interface DesktopUpdatesShape {
|
||||
}
|
||||
|
||||
export class DesktopUpdates extends Context.Service<DesktopUpdates, DesktopUpdatesShape>()(
|
||||
"@t3tools/desktop/updates/DesktopUpdates",
|
||||
"t3/desktop/Updates",
|
||||
) {}
|
||||
|
||||
const {
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface DesktopApplicationMenuShape {
|
||||
export class DesktopApplicationMenu extends Context.Service<
|
||||
DesktopApplicationMenu,
|
||||
DesktopApplicationMenuShape
|
||||
>()("@t3tools/desktop/window/DesktopApplicationMenu") {}
|
||||
>()("t3/desktop/ApplicationMenu") {}
|
||||
|
||||
type DesktopApplicationMenuRuntimeServices =
|
||||
| DesktopUpdates.DesktopUpdates
|
||||
|
||||
@@ -62,7 +62,7 @@ export interface DesktopWindowShape {
|
||||
}
|
||||
|
||||
export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowShape>()(
|
||||
"@t3tools/desktop/window/DesktopWindow",
|
||||
"t3/desktop/Window",
|
||||
) {}
|
||||
|
||||
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
|
||||
|
||||
@@ -49,6 +49,7 @@ function resolveAppVariant(value: string | undefined): AppVariant {
|
||||
}
|
||||
|
||||
const variant = VARIANT_CONFIG[APP_VARIANT];
|
||||
const allowsCleartextTraffic = APP_VARIANT === "development";
|
||||
|
||||
const config: ExpoConfig = {
|
||||
name: variant.appName,
|
||||
@@ -67,16 +68,23 @@ 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: {
|
||||
NSAppTransportSecurity: {
|
||||
NSAllowsArbitraryLoads: true,
|
||||
},
|
||||
NSLocalNetworkUsageDescription:
|
||||
"Allow T3 Code to connect to T3 Code servers on your local network or tailnet.",
|
||||
...(allowsCleartextTraffic
|
||||
? {
|
||||
NSAppTransportSecurity: {
|
||||
NSAllowsArbitraryLoads: true,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
ITSAppUsesNonExemptEncryption: false,
|
||||
},
|
||||
},
|
||||
@@ -119,14 +127,13 @@ const config: ExpoConfig = {
|
||||
"expo-build-properties",
|
||||
{
|
||||
ios: {
|
||||
deploymentTarget: "16.4",
|
||||
deploymentTarget: "16.1",
|
||||
},
|
||||
},
|
||||
],
|
||||
"expo-secure-store",
|
||||
"expo-router",
|
||||
"expo-font",
|
||||
"./plugins/withAndroidCleartextTraffic.cjs",
|
||||
...(allowsCleartextTraffic ? ["./plugins/withAndroidCleartextTraffic.cjs"] : []),
|
||||
],
|
||||
extra: {
|
||||
appVariant: APP_VARIANT,
|
||||
|
||||
Vendored
-1
@@ -1 +0,0 @@
|
||||
declare module "*.css";
|
||||
+29
-30
@@ -38,7 +38,6 @@
|
||||
"@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",
|
||||
@@ -54,47 +53,47 @@
|
||||
"clsx": "^2.1.1",
|
||||
"diff": "8.0.3",
|
||||
"effect": "catalog:",
|
||||
"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": "~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-paste-input": "^0.1.15",
|
||||
"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",
|
||||
"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",
|
||||
"punycode": "^2.3.1",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-native": "0.85.3",
|
||||
"react-native-gesture-handler": "~2.31.1",
|
||||
"react": "19.2.5",
|
||||
"react-dom": "19.2.5",
|
||||
"react-native": "0.83.4",
|
||||
"react-native-gesture-handler": "~2.30.0",
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
"react-native-keyboard-controller": "1.21.6",
|
||||
"react-native-keyboard-controller": "1.20.7",
|
||||
"react-native-nitro-markdown": "^0.5.0",
|
||||
"react-native-nitro-modules": "^0.35.4",
|
||||
"react-native-reanimated": "4.3.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "4.25.2",
|
||||
"react-native-reanimated": "4.2.1",
|
||||
"react-native-safe-area-context": "~5.6.2",
|
||||
"react-native-screens": "~4.23.0",
|
||||
"react-native-shiki-engine": "^0.3.9",
|
||||
"react-native-svg": "15.15.4",
|
||||
"react-native-worklets": "0.8.3",
|
||||
"react-native-svg": "15.15.3",
|
||||
"react-native-worklets": "0.7.2",
|
||||
"shiki": "3.23.0",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"uniwind": "^1.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "~19.2.0",
|
||||
"babel-preset-expo": "~56.0.0",
|
||||
"babel-preset-expo": "~55.0.8",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:"
|
||||
},
|
||||
|
||||
@@ -1,12 +1,38 @@
|
||||
import { Stack, useRouter } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { type ComponentProps, useState } from "react";
|
||||
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
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 ───────────────────────────────────────────────────── */
|
||||
|
||||
@@ -18,6 +44,7 @@ export default function HomeRouteScreen() {
|
||||
|
||||
const isDark = useColorScheme() === "dark";
|
||||
const iconColor = String(useThemeColor("--color-icon"));
|
||||
const status = resolveHeaderStatus(catalogState);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -78,16 +105,15 @@ export default function HomeRouteScreen() {
|
||||
</Stack.Toolbar>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu icon="ellipsis.circle" separateBackground>
|
||||
<Stack.Toolbar.Label>More</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="desktopcomputer"
|
||||
<Stack.Toolbar.View hidesSharedBackground>
|
||||
<Pressable
|
||||
accessibilityLabel={status.label}
|
||||
className="h-11 w-11 items-center justify-center rounded-full bg-card active:opacity-70"
|
||||
onPress={() => router.push("/connections")}
|
||||
subtitle="Manage connected hosts"
|
||||
>
|
||||
<Stack.Toolbar.Label>Environments</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
<SymbolView name={status.icon} size={21} tintColor={status.color} type="monochrome" />
|
||||
</Pressable>
|
||||
</Stack.Toolbar.View>
|
||||
</Stack.Toolbar>
|
||||
|
||||
{/* Bottom toolbar: search + compose, visually split like iMessage */}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { Ref } from "react";
|
||||
import {
|
||||
Text as RNText,
|
||||
TextInput as RNTextInput,
|
||||
@@ -19,26 +18,17 @@ export function AppText({ className, ...props }: AppTextProps) {
|
||||
return <RNText className={cn("font-sans text-foreground", className)} {...props} />;
|
||||
}
|
||||
|
||||
export type AppTextInputProps = RNTextInputProps & {
|
||||
readonly className?: string;
|
||||
readonly ref?: Ref<RNTextInput>;
|
||||
};
|
||||
export type AppTextInputProps = RNTextInputProps & { readonly className?: string };
|
||||
|
||||
/**
|
||||
* Thin wrapper around RN TextInput with default input styling.
|
||||
* Uses Uniwind className — no manual style parsing.
|
||||
*/
|
||||
export function AppTextInput({
|
||||
className,
|
||||
placeholderTextColor,
|
||||
ref,
|
||||
...props
|
||||
}: AppTextInputProps) {
|
||||
export function AppTextInput({ className, placeholderTextColor, ...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,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { MenuView } from "@react-native-menu/menu";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { Pressable, useColorScheme, View } from "react-native";
|
||||
import { Pressable, View } from "react-native";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
@@ -11,7 +10,6 @@ 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;
|
||||
@@ -57,13 +55,7 @@ export function ControlPill(props: {
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel ?? props.label}
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
disabled={props.disabled}
|
||||
className={containerClassName}
|
||||
>
|
||||
<Pressable 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 ? (
|
||||
@@ -73,17 +65,3 @@ 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
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, parsePairingUrl } from "./pairing";
|
||||
import { extractPairingUrlFromQrPayload } from "./pairing";
|
||||
|
||||
describe("extractPairingUrlFromQrPayload", () => {
|
||||
it("trims raw pairing urls from qr payloads", () => {
|
||||
@@ -23,16 +23,3 @@ 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,5 +1,3 @@
|
||||
import { readHostedPairingRequest } from "@t3tools/shared/remote";
|
||||
|
||||
const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
|
||||
|
||||
export function buildPairingUrl(host: string, code: string): string {
|
||||
@@ -23,14 +21,6 @@ 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 expoMocks = vi.hoisted(() => ({
|
||||
requireNativeView: vi.fn(),
|
||||
const expoModulesCoreMocks = vi.hoisted(() => ({
|
||||
requireNativeViewManager: vi.fn(),
|
||||
}));
|
||||
const nativeView = () => null;
|
||||
const originalExpo = globalThis.expo;
|
||||
@@ -12,8 +12,8 @@ function setExpoViewConfigAvailable() {
|
||||
} as unknown as typeof globalThis.expo;
|
||||
}
|
||||
|
||||
vi.mock("expo", () => ({
|
||||
requireNativeView: expoMocks.requireNativeView,
|
||||
vi.mock("expo-modules-core", () => ({
|
||||
requireNativeViewManager: expoModulesCoreMocks.requireNativeViewManager,
|
||||
}));
|
||||
|
||||
describe("resolveNativeReviewDiffView", () => {
|
||||
@@ -30,15 +30,17 @@ describe("resolveNativeReviewDiffView", () => {
|
||||
it("returns null when the native review diff view config is unavailable", async () => {
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
|
||||
expect(resolveNativeReviewDiffView()).toBeNull();
|
||||
expect(expoMocks.requireNativeView).not.toHaveBeenCalled();
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the native review diff view when the view config is installed", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
expoMocks.requireNativeView.mockReturnValue(nativeView);
|
||||
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
|
||||
expect(resolveNativeReviewDiffView()).toBe(nativeView);
|
||||
expect(expoMocks.requireNativeView).toHaveBeenCalledWith("T3ReviewDiffSurface");
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).toHaveBeenCalledWith(
|
||||
"T3ReviewDiffSurface",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not fall back to stale legacy native review diff view names", async () => {
|
||||
@@ -50,15 +52,15 @@ describe("resolveNativeReviewDiffView", () => {
|
||||
return null;
|
||||
}),
|
||||
} as unknown as typeof globalThis.expo;
|
||||
expoMocks.requireNativeView.mockReturnValue(nativeView);
|
||||
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
|
||||
expect(resolveNativeReviewDiffView()).toBeNull();
|
||||
expect(expoMocks.requireNativeView).not.toHaveBeenCalled();
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns null when the view manager cannot be required", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
expoMocks.requireNativeView.mockImplementation(() => {
|
||||
expoModulesCoreMocks.requireNativeViewManager.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 { requireNativeView } from "expo";
|
||||
import { requireNativeViewManager } from "expo-modules-core";
|
||||
|
||||
const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
|
||||
|
||||
@@ -144,7 +144,7 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
|
||||
}
|
||||
|
||||
try {
|
||||
cachedNativeReviewDiffView = requireNativeView<NativeReviewDiffViewProps>(
|
||||
cachedNativeReviewDiffView = requireNativeViewManager<NativeReviewDiffViewProps>(
|
||||
NATIVE_REVIEW_DIFF_MODULE_NAME,
|
||||
);
|
||||
} catch {
|
||||
|
||||
@@ -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 { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";
|
||||
import { KeyboardAvoidingView } from "react-native-keyboard-controller";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
|
||||
@@ -82,10 +82,6 @@ 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 {
|
||||
@@ -142,147 +138,150 @@ export function ReviewCommentComposerSheet() {
|
||||
|
||||
return (
|
||||
<View style={{ flex: 1 }}>
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<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 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>
|
||||
|
||||
{!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.
|
||||
) : (
|
||||
<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}
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<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}
|
||||
>
|
||||
{target.filePath}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View className="overflow-hidden rounded-[22px] border border-border bg-card">
|
||||
<View className="overflow-hidden rounded-[22px] border border-border bg-card">
|
||||
<ScrollView
|
||||
horizontal
|
||||
bounces={false}
|
||||
keyboardShouldPersistTaps="always"
|
||||
showsHorizontalScrollIndicator={false}
|
||||
>
|
||||
<ScrollView
|
||||
horizontal
|
||||
bounces={false}
|
||||
scrollEnabled={selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES}
|
||||
nestedScrollEnabled
|
||||
keyboardShouldPersistTaps="always"
|
||||
showsHorizontalScrollIndicator={false}
|
||||
showsVerticalScrollIndicator={
|
||||
selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES
|
||||
}
|
||||
style={{ height: previewHeight }}
|
||||
>
|
||||
<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);
|
||||
<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 }}
|
||||
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 }}
|
||||
>
|
||||
<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>
|
||||
{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>
|
||||
</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>
|
||||
);
|
||||
})}
|
||||
</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>
|
||||
) : null}
|
||||
</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>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
</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>
|
||||
)}
|
||||
</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 className="flex-1" />
|
||||
<ControlPill
|
||||
accessibilityLabel="Comment"
|
||||
icon="arrow.up"
|
||||
label="Comment"
|
||||
variant="primary"
|
||||
@@ -299,12 +298,13 @@ export function ReviewCommentComposerSheet() {
|
||||
attachments,
|
||||
});
|
||||
setAttachments([]);
|
||||
dismissComposer();
|
||||
clearReviewCommentTarget();
|
||||
router.dismiss();
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</KeyboardAvoidingView>
|
||||
</KeyboardStickyView>
|
||||
) : null}
|
||||
<ImageViewing
|
||||
images={previewImageUri ? [{ uri: previewImageUri }] : []}
|
||||
imageIndex={0}
|
||||
|
||||
@@ -83,13 +83,13 @@ function ReviewSelectionActionBar(props: {
|
||||
>
|
||||
{props.onOpenComment ? (
|
||||
<Pressable
|
||||
className="h-12 flex-1 flex-row items-center justify-center gap-2 rounded-full bg-blue-600 px-5"
|
||||
className="min-h-[48px] flex-1 flex-row items-center justify-center gap-2 rounded-full bg-blue-600 px-5"
|
||||
onPress={props.onOpenComment}
|
||||
>
|
||||
{content}
|
||||
</Pressable>
|
||||
) : (
|
||||
<View className="h-12 flex-1 flex-row items-center justify-center gap-2 rounded-full bg-blue-600 px-5">
|
||||
<View className="min-h-[48px] 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.absoluteFill}
|
||||
style={StyleSheet.absoluteFillObject}
|
||||
appearanceScheme={selectedTheme}
|
||||
collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson}
|
||||
collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { memo, useCallback, useEffect, useRef } from "react";
|
||||
import { memo, useCallback, useEffect } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
ScrollView,
|
||||
@@ -33,7 +33,6 @@ 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;
|
||||
@@ -54,7 +53,6 @@ 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
|
||||
@@ -66,16 +64,6 @@ 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={[
|
||||
@@ -128,7 +116,6 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
|
||||
}}
|
||||
>
|
||||
<TextInput
|
||||
ref={inputRef}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
blurOnSubmit={false}
|
||||
@@ -178,7 +165,6 @@ 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;
|
||||
@@ -209,61 +195,21 @@ 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 (
|
||||
<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>
|
||||
<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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,28 +5,12 @@ 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,
|
||||
type LayoutChangeEvent,
|
||||
type NativeScrollEvent,
|
||||
type NativeSyntheticEvent,
|
||||
} from "react-native";
|
||||
import {
|
||||
KeyboardController,
|
||||
KeyboardEvents,
|
||||
KeyboardStickyView,
|
||||
useKeyboardState,
|
||||
} from "react-native-keyboard-controller";
|
||||
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { KeyboardStickyView } 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";
|
||||
@@ -79,14 +63,12 @@ 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;
|
||||
@@ -246,17 +228,6 @@ 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);
|
||||
@@ -413,7 +384,6 @@ 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" },
|
||||
@@ -424,28 +394,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
{ kind: "send", key: "dash", label: "-", data: "-" },
|
||||
];
|
||||
}, [hostPlatform]);
|
||||
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 terminalBottomInset = TERMINAL_ACCESSORY_HEIGHT;
|
||||
|
||||
const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
|
||||
() =>
|
||||
@@ -917,23 +866,6 @@ 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") {
|
||||
@@ -947,11 +879,6 @@ export function ThreadTerminalRouteScreen() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (action.kind === "clear") {
|
||||
handleClearTerminal();
|
||||
return;
|
||||
}
|
||||
|
||||
setPendingModifierState({ terminalId, value: null });
|
||||
if (pendingModifier === "ctrl") {
|
||||
writeInput(applyCtrlModifier(action.data));
|
||||
@@ -961,59 +888,9 @@ export function ThreadTerminalRouteScreen() {
|
||||
writeInput(action.data);
|
||||
}
|
||||
},
|
||||
[handleClearTerminal, pendingModifier, terminalId, writeInput],
|
||||
[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…" />;
|
||||
@@ -1151,7 +1028,6 @@ export function ThreadTerminalRouteScreen() {
|
||||
buffer={terminalSurfaceBuffer}
|
||||
fontSize={fontSize}
|
||||
isRunning={isRunning}
|
||||
keyboardFocusRequest={keyboardFocusRequest}
|
||||
onInput={handleInput}
|
||||
onResize={handleResize}
|
||||
style={{ flex: 1 }}
|
||||
@@ -1159,175 +1035,67 @@ export function ThreadTerminalRouteScreen() {
|
||||
/>
|
||||
</View>
|
||||
|
||||
{isAccessoryVisible ? (
|
||||
<KeyboardStickyView
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
<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,
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: terminalTheme.background,
|
||||
borderTopColor: terminalTheme.border,
|
||||
borderTopWidth: 1,
|
||||
minHeight: TERMINAL_ACCESSORY_HEIGHT,
|
||||
paddingBottom: 4,
|
||||
paddingHorizontal: 8,
|
||||
paddingTop: 4,
|
||||
}}
|
||||
<ScrollView
|
||||
horizontal
|
||||
contentContainerStyle={{ alignItems: "center", gap: 6, paddingRight: 2 }}
|
||||
showsHorizontalScrollIndicator={false}
|
||||
>
|
||||
<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}
|
||||
>
|
||||
{terminalToolbarActions.map((action) => {
|
||||
const active =
|
||||
action.kind === "modifier" && pendingModifier === action.modifier;
|
||||
{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>
|
||||
);
|
||||
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,
|
||||
})}
|
||||
</ScrollView>
|
||||
{toolbarScrollEdges.showLeftFade ? (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
>
|
||||
<RNText
|
||||
style={{
|
||||
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,
|
||||
color: active
|
||||
? (terminalTheme.palette[10] ?? terminalTheme.foreground)
|
||||
: terminalTheme.foreground,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
textTransform: action.kind === "modifier" ? "uppercase" : "none",
|
||||
}}
|
||||
/>
|
||||
) : 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}
|
||||
>
|
||||
{action.label}
|
||||
</RNText>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const expoMocks = vi.hoisted(() => ({
|
||||
requireNativeView: vi.fn(),
|
||||
const expoModulesCoreMocks = vi.hoisted(() => ({
|
||||
requireNativeViewManager: vi.fn(),
|
||||
}));
|
||||
const nativeView = () => null;
|
||||
const originalExpo = globalThis.expo;
|
||||
@@ -12,8 +12,8 @@ function setExpoViewConfigAvailable() {
|
||||
} as unknown as typeof globalThis.expo;
|
||||
}
|
||||
|
||||
vi.mock("expo", () => ({
|
||||
requireNativeView: expoMocks.requireNativeView,
|
||||
vi.mock("expo-modules-core", () => ({
|
||||
requireNativeViewManager: expoModulesCoreMocks.requireNativeViewManager,
|
||||
}));
|
||||
|
||||
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(expoMocks.requireNativeView).not.toHaveBeenCalled();
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the native terminal view when the view config is installed", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
expoMocks.requireNativeView.mockReturnValue(nativeView);
|
||||
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
|
||||
const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule");
|
||||
expect(resolveNativeTerminalSurfaceView()).toBe(nativeView);
|
||||
expect(expoMocks.requireNativeView).toHaveBeenCalledWith("T3TerminalSurface");
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).toHaveBeenCalledWith("T3TerminalSurface");
|
||||
});
|
||||
|
||||
it("returns null when the view manager cannot be required", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
expoMocks.requireNativeView.mockImplementation(() => {
|
||||
expoModulesCoreMocks.requireNativeViewManager.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 { requireNativeView } from "expo";
|
||||
import { requireNativeViewManager } from "expo-modules-core";
|
||||
|
||||
const NATIVE_TERMINAL_MODULE_NAME = "T3TerminalSurface";
|
||||
|
||||
@@ -50,7 +50,7 @@ export function resolveNativeTerminalSurfaceView(): ComponentType<NativeTerminal
|
||||
}
|
||||
|
||||
try {
|
||||
cachedNativeTerminalSurfaceView = requireNativeView<NativeTerminalSurfaceProps>(
|
||||
cachedNativeTerminalSurfaceView = requireNativeViewManager<NativeTerminalSurfaceProps>(
|
||||
NATIVE_TERMINAL_MODULE_NAME,
|
||||
);
|
||||
} catch {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { MenuView } from "@react-native-menu/menu";
|
||||
import { useRouter } from "expo-router";
|
||||
import { TextInputWrapper } from "expo-paste-input";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
import { View } from "react-native";
|
||||
import { KeyboardStickyView, useKeyboardState } from "react-native-keyboard-controller";
|
||||
import { View, useColorScheme } from "react-native";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
@@ -10,7 +11,7 @@ import { EnvironmentId, type ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
import { AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
|
||||
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
|
||||
@@ -45,8 +46,8 @@ export function NewTaskDraftScreen(props: {
|
||||
const flow = useNewTaskFlow();
|
||||
const router = useRouter();
|
||||
const insets = useSafeAreaInsets();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const controlsBottomPadding = Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
@@ -443,36 +444,40 @@ export function NewTaskDraftScreen(props: {
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<View className="flex-row items-center justify-between gap-2 px-4 pt-2">
|
||||
<View className="flex-row items-center justify-between gap-2 px-4 pb-1 pt-4">
|
||||
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
|
||||
<ControlPillMenu
|
||||
<MenuView
|
||||
actions={modelMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill
|
||||
iconNode={
|
||||
<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
</MenuView>
|
||||
<MenuView
|
||||
actions={optionsMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill icon="slider.horizontal.3" />
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
</MenuView>
|
||||
<MenuView
|
||||
actions={environmentMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill icon="desktopcomputer" />
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
</MenuView>
|
||||
<MenuView
|
||||
actions={workspaceMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill icon="point.topleft.down.curvedto.point.bottomright.up" />
|
||||
</ControlPillMenu>
|
||||
</MenuView>
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
label={flow.submitting ? "Starting" : "Start"}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import { MenuView } from "@react-native-menu/menu";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ModelSelection,
|
||||
@@ -30,7 +31,7 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
@@ -762,18 +763,20 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}}
|
||||
>
|
||||
<ControlPill icon="plus" onPress={() => void props.onPickDraftImages()} />
|
||||
<ControlPillMenu
|
||||
<MenuView
|
||||
actions={modelMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill iconNode={<ProviderIcon provider={modelProvider} size={16} />} />
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
</MenuView>
|
||||
<MenuView
|
||||
actions={optionsMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
|
||||
themeVariant={isDarkMode ? "dark" : "light"}
|
||||
>
|
||||
<ControlPill icon="slider.horizontal.3" />
|
||||
</ControlPillMenu>
|
||||
</MenuView>
|
||||
<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.absoluteFill}
|
||||
style={StyleSheet.absoluteFillObject}
|
||||
appearanceScheme={appearanceScheme}
|
||||
contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
|
||||
rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
|
||||
|
||||
@@ -13,10 +13,9 @@ 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 { makeTurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import { uuidv4 } from "../../lib/uuid";
|
||||
import { getEnvironmentClient } from "../../state/environment-session-registry";
|
||||
import { environmentRuntimeManager } from "../../state/use-environment-runtime";
|
||||
import { vcsRefManager } from "../../state/use-vcs-refs";
|
||||
@@ -94,9 +93,8 @@ export function useProjectActions() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const metadata = makeTurnCommandMetadata();
|
||||
const threadId = ThreadId.make(metadata.threadId);
|
||||
const createdAt = metadata.createdAt;
|
||||
const threadId = ThreadId.make(uuidv4());
|
||||
const createdAt = new Date().toISOString();
|
||||
const initialMessageText = input.initialMessageText.trim();
|
||||
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
|
||||
|
||||
@@ -111,10 +109,10 @@ export function useProjectActions() {
|
||||
|
||||
await client.orchestration.dispatchCommand({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
commandId: CommandId.make(uuidv4()),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
messageId: MessageId.make(uuidv4()),
|
||||
role: "user",
|
||||
text: initialMessageText,
|
||||
attachments: input.initialAttachments,
|
||||
@@ -139,13 +137,13 @@ export function useProjectActions() {
|
||||
prepareWorktree: {
|
||||
projectCwd: input.project.workspaceRoot,
|
||||
baseBranch: input.branch!,
|
||||
branch: buildTemporaryWorktreeBranchName(uuidv4),
|
||||
branch: buildTemporaryWorktreeBranchName(),
|
||||
},
|
||||
runSetupScript: true,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
createdAt,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
await refreshRemoteData([input.project.environmentId]);
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
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/);
|
||||
});
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
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(),
|
||||
};
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -2,9 +2,8 @@ import { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
bootstrapRemoteBearerSession,
|
||||
fetchRemoteEnvironmentDescriptor,
|
||||
} from "@t3tools/client-runtime";
|
||||
import { resolveRemotePairingTarget, stripPairingTokenFromUrl } from "@t3tools/shared/remote";
|
||||
import { mobileRemoteHttpRuntime } from "./runtime";
|
||||
resolveRemotePairingTarget,
|
||||
} from "@t3tools/shared/remote";
|
||||
|
||||
export interface RemoteConnectionInput {
|
||||
readonly pairingUrl: string;
|
||||
@@ -27,15 +26,6 @@ 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> {
|
||||
@@ -43,23 +33,19 @@ export async function bootstrapRemoteConnection(
|
||||
pairingUrl: input.pairingUrl,
|
||||
});
|
||||
|
||||
const descriptor = await mobileRemoteHttpRuntime.runPromise(
|
||||
fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl: target.httpBaseUrl,
|
||||
}),
|
||||
);
|
||||
const descriptor = await fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl: target.httpBaseUrl,
|
||||
});
|
||||
|
||||
const bootstrap = await mobileRemoteHttpRuntime.runPromise(
|
||||
bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: target.httpBaseUrl,
|
||||
credential: target.credential,
|
||||
}),
|
||||
);
|
||||
const bootstrap = await bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: target.httpBaseUrl,
|
||||
credential: target.credential,
|
||||
});
|
||||
|
||||
return {
|
||||
environmentId: descriptor.environmentId,
|
||||
environmentLabel: descriptor.label,
|
||||
pairingUrl: redactPairingCredential(input.pairingUrl),
|
||||
pairingUrl: input.pairingUrl.trim(),
|
||||
displayUrl: target.httpBaseUrl,
|
||||
httpBaseUrl: target.httpBaseUrl,
|
||||
wsBaseUrl: target.wsBaseUrl,
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import type { Href, useRouter } from "expo-router";
|
||||
import type { Href, Router } 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">;
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
|
||||
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
|
||||
|
||||
export const mobileRemoteHttpRuntime = ManagedRuntime.make(remoteHttpClientLayer(fetch));
|
||||
@@ -1,9 +1,7 @@
|
||||
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 { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts";
|
||||
|
||||
import type { SavedRemoteConnection } from "./connection";
|
||||
|
||||
@@ -23,14 +21,6 @@ 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);
|
||||
}
|
||||
@@ -52,6 +42,34 @@ 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`;
|
||||
}
|
||||
@@ -75,12 +93,11 @@ export async function loadCachedShellSnapshot(
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(await file.text()) as unknown;
|
||||
const decoded = decodeCachedShellSnapshot(parsed);
|
||||
if (Option.isNone(decoded) || decoded.value.environmentId !== environmentId) {
|
||||
if (!isCachedShellSnapshot(parsed) || parsed.environmentId !== environmentId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return decoded.value;
|
||||
return parsed;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Crypto from "expo-crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Random from "effect/Random";
|
||||
|
||||
export const uuidv4 = () => Crypto.randomUUID();
|
||||
export const uuidv4 = () => Effect.runSync(Random.nextUUIDv4);
|
||||
@@ -31,11 +31,11 @@ const projectsSortOrder = Order.mapInput(
|
||||
|
||||
const threadsSortOrder = Order.mapInput(
|
||||
Order.Struct({
|
||||
activityAt: Order.flip(Order.String),
|
||||
activityAt: Order.flip(Order.Number),
|
||||
environmentId: Order.String,
|
||||
}),
|
||||
(thread: EnvironmentScopedThreadShell) => ({
|
||||
activityAt: thread.updatedAt ?? thread.createdAt,
|
||||
activityAt: new Date(thread.updatedAt ?? thread.createdAt).getTime(),
|
||||
environmentId: thread.environmentId,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -5,14 +5,13 @@ 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";
|
||||
@@ -29,7 +28,6 @@ import {
|
||||
saveConnection,
|
||||
} from "../lib/storage";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { mobileRemoteHttpRuntime } from "../lib/runtime";
|
||||
import {
|
||||
drainEnvironmentSessions,
|
||||
notifyEnvironmentConnectionListeners,
|
||||
@@ -51,7 +49,6 @@ 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 {
|
||||
@@ -178,16 +175,8 @@ function withTimeout<T>(
|
||||
|
||||
export async function disconnectEnvironment(
|
||||
environmentId: EnvironmentId,
|
||||
options?: {
|
||||
readonly preserveShellSnapshot?: boolean;
|
||||
readonly removeSaved?: boolean;
|
||||
readonly preserveConnectionAttempt?: boolean;
|
||||
},
|
||||
options?: { readonly preserveShellSnapshot?: boolean; readonly removeSaved?: boolean },
|
||||
) {
|
||||
if (!options?.preserveConnectionAttempt) {
|
||||
environmentConnectionAttempts.cancel(environmentId);
|
||||
}
|
||||
|
||||
const session = removeEnvironmentSession(environmentId);
|
||||
notifyEnvironmentConnectionListeners();
|
||||
await session?.connection.dispose();
|
||||
@@ -212,22 +201,10 @@ export async function connectSavedEnvironment(
|
||||
connection: SavedRemoteConnection,
|
||||
options?: { readonly persist?: boolean },
|
||||
) {
|
||||
const connectionAttempt = environmentConnectionAttempts.begin(connection.environmentId);
|
||||
const isCurrentAttempt = connectionAttempt.isCurrent;
|
||||
|
||||
await disconnectEnvironment(connection.environmentId, {
|
||||
preserveShellSnapshot: true,
|
||||
preserveConnectionAttempt: true,
|
||||
});
|
||||
if (!isCurrentAttempt()) {
|
||||
return;
|
||||
}
|
||||
await disconnectEnvironment(connection.environmentId, { preserveShellSnapshot: true });
|
||||
|
||||
if (options?.persist !== false) {
|
||||
await saveConnection(connection);
|
||||
if (!isCurrentAttempt()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
upsertSavedConnection(connection);
|
||||
@@ -236,19 +213,13 @@ export async function connectSavedEnvironment(
|
||||
|
||||
const transport = new WsTransport(
|
||||
() =>
|
||||
mobileRemoteHttpRuntime.runPromise(
|
||||
resolveRemoteWebSocketConnectionUrl({
|
||||
wsBaseUrl: connection.wsBaseUrl,
|
||||
httpBaseUrl: connection.httpBaseUrl,
|
||||
bearerToken: connection.bearerToken,
|
||||
}),
|
||||
),
|
||||
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"
|
||||
@@ -264,15 +235,9 @@ export async function connectSavedEnvironment(
|
||||
});
|
||||
},
|
||||
onError: (message) => {
|
||||
if (isCurrentAttempt()) {
|
||||
setEnvironmentConnectionStatus(connection.environmentId, "disconnected", message);
|
||||
}
|
||||
setEnvironmentConnectionStatus(connection.environmentId, "disconnected", message);
|
||||
},
|
||||
onClose: (details) => {
|
||||
if (!isCurrentAttempt()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const reason =
|
||||
details.reason.trim().length > 0
|
||||
? details.reason
|
||||
@@ -301,15 +266,9 @@ export async function connectSavedEnvironment(
|
||||
},
|
||||
client,
|
||||
applyShellEvent: (event, environmentId) => {
|
||||
if (isCurrentAttempt()) {
|
||||
shellSnapshotManager.applyEvent({ environmentId }, event);
|
||||
}
|
||||
shellSnapshotManager.applyEvent({ environmentId }, event);
|
||||
},
|
||||
syncShellSnapshot: (snapshot, environmentId) => {
|
||||
if (!isCurrentAttempt()) {
|
||||
return;
|
||||
}
|
||||
|
||||
shellSnapshotManager.syncSnapshot({ environmentId }, snapshot);
|
||||
markShellSnapshotLive(environmentId);
|
||||
void saveCachedShellSnapshot(environmentId, snapshot);
|
||||
@@ -320,25 +279,16 @@ export async function connectSavedEnvironment(
|
||||
}));
|
||||
},
|
||||
onShellResubscribe: (environmentId) => {
|
||||
if (isCurrentAttempt()) {
|
||||
shellSnapshotManager.markPending({ environmentId });
|
||||
}
|
||||
shellSnapshotManager.markPending({ environmentId });
|
||||
},
|
||||
onConfigSnapshot: (serverConfig) => {
|
||||
if (isCurrentAttempt()) {
|
||||
environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (runtime) => ({
|
||||
...runtime,
|
||||
serverConfig,
|
||||
}));
|
||||
}
|
||||
environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (runtime) => ({
|
||||
...runtime,
|
||||
serverConfig,
|
||||
}));
|
||||
},
|
||||
});
|
||||
|
||||
if (!isCurrentAttempt()) {
|
||||
await environmentConnection.dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
setEnvironmentSession(connection.environmentId, {
|
||||
client,
|
||||
connection: environmentConnection,
|
||||
@@ -362,13 +312,11 @@ export async function connectSavedEnvironment(
|
||||
"Environment did not respond before the connection timeout.",
|
||||
);
|
||||
} catch (error) {
|
||||
if (isCurrentAttempt()) {
|
||||
setEnvironmentConnectionStatus(
|
||||
connection.environmentId,
|
||||
"disconnected",
|
||||
error instanceof Error ? error.message : "Failed to bootstrap remote connection.",
|
||||
);
|
||||
}
|
||||
setEnvironmentConnectionStatus(
|
||||
connection.environmentId,
|
||||
"disconnected",
|
||||
error instanceof Error ? error.message : "Failed to bootstrap remote connection.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -456,7 +404,6 @@ export function useRemoteEnvironmentBootstrap() {
|
||||
unsubscribe();
|
||||
}
|
||||
terminalMetadataUnsubscribers.clear();
|
||||
environmentConnectionAttempts.clear();
|
||||
environmentRuntimeManager.invalidate();
|
||||
shellSnapshotManager.invalidate();
|
||||
resetSourceControlDiscoveryState();
|
||||
|
||||
@@ -6,7 +6,6 @@ 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,
|
||||
@@ -15,6 +14,7 @@ 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 metadata = makeQueuedMessageMetadata();
|
||||
const createdAt = new Date().toISOString();
|
||||
enqueueQueuedMessage({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
messageId: MessageId.make(uuidv4()),
|
||||
commandId: CommandId.make(uuidv4()),
|
||||
text,
|
||||
attachments,
|
||||
createdAt: metadata.createdAt,
|
||||
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,7 +226,6 @@ 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>();
|
||||
@@ -242,18 +241,6 @@ 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* () {
|
||||
@@ -322,7 +309,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
for (const fixtureEvent of response.events) {
|
||||
const rawEvent: Record<string, unknown> = {
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: yield* randomUUIDv4(input.threadId),
|
||||
eventId: yield* Random.nextUUIDv4,
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.make(String(input.threadId)),
|
||||
};
|
||||
@@ -379,7 +366,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make(yield* randomUUIDv4(input.threadId)),
|
||||
eventId: EventId.make(yield* Random.nextUUIDv4),
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
|
||||
@@ -19,11 +19,11 @@
|
||||
"build": "node scripts/cli.ts build",
|
||||
"build:bundle": "tsdown",
|
||||
"start": "node dist/bin.mjs",
|
||||
"typecheck": "tsgo --noEmit",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.154",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/platform-node-shared": "catalog:",
|
||||
@@ -34,6 +34,7 @@
|
||||
"node-pty": "^1.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
@@ -44,6 +45,7 @@
|
||||
"effect-acp": "workspace:*",
|
||||
"effect-codex-app-server": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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;
|
||||
@@ -10,6 +11,7 @@ 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 });
|
||||
@@ -17,7 +19,7 @@ export const writeFileStringAtomically = (input: {
|
||||
directory: targetDirectory,
|
||||
prefix: `${path.basename(input.filePath)}.`,
|
||||
});
|
||||
const tempPath = path.join(tempDirectory, "contents.tmp");
|
||||
const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
|
||||
|
||||
yield* fs.writeFileString(tempPath, input.contents);
|
||||
yield* fs.rename(tempPath, input.filePath);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
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";
|
||||
@@ -47,7 +46,6 @@ 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>());
|
||||
@@ -143,7 +141,7 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {
|
||||
|
||||
const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const id = yield* crypto.randomUUIDv4;
|
||||
const id = crypto.randomUUID();
|
||||
const credential = generatePairingToken();
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const now = yield* DateTime.now;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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";
|
||||
@@ -91,7 +90,6 @@ 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;
|
||||
@@ -205,7 +203,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(yield* crypto.randomUUIDv4);
|
||||
const sessionId = AuthSessionId.make(crypto.randomUUID());
|
||||
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/auth/Services/AuthControlPlane",
|
||||
"t3/AuthControlPlane",
|
||||
) {}
|
||||
@@ -1,4 +1,4 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
|
||||
// @effect-diagnostics-next-line nodeBuiltinImport:off - NodeHttpServer.layer takes `NodeHttp.createServer` as arg
|
||||
import * as NodeHttp from "node:http";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
@@ -5,7 +5,6 @@ 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";
|
||||
@@ -59,16 +58,6 @@ 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(
|
||||
@@ -271,7 +260,7 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
|
||||
}) => Effect.Effect<
|
||||
string,
|
||||
Error,
|
||||
Crypto.Crypto | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
|
||||
FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
|
||||
>,
|
||||
) {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
@@ -354,10 +343,10 @@ const projectAddCommand = Command.make("add", {
|
||||
}
|
||||
|
||||
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
|
||||
const projectId = ProjectId.make(yield* projectCommandUuid);
|
||||
const projectId = ProjectId.make(crypto.randomUUID());
|
||||
yield* dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make(yield* projectCommandUuid),
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId,
|
||||
title,
|
||||
workspaceRoot,
|
||||
@@ -395,7 +384,7 @@ const projectRemoveCommand = Command.make("remove", {
|
||||
});
|
||||
yield* dispatch({
|
||||
type: "project.delete",
|
||||
commandId: CommandId.make(yield* projectCommandUuid),
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId: project.id,
|
||||
});
|
||||
return `Removed project ${project.id} (${project.title}).`;
|
||||
@@ -435,7 +424,7 @@ const projectRenameCommand = Command.make("rename", {
|
||||
|
||||
yield* dispatch({
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make(yield* projectCommandUuid),
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
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,7 +39,6 @@ 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
|
||||
@@ -65,7 +64,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
|
||||
return persisted;
|
||||
}
|
||||
|
||||
const generated = yield* crypto.randomUUIDv4;
|
||||
const generated = yield* Random.nextUUIDv4;
|
||||
yield* persistEnvironmentId(generated);
|
||||
return generated;
|
||||
});
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
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";
|
||||
@@ -531,39 +532,32 @@ 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,
|
||||
) =>
|
||||
(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 actionId = options?.actionId ?? randomUUID();
|
||||
const reporter = options?.progressReporter;
|
||||
|
||||
return {
|
||||
actionId,
|
||||
emit,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const emit = (event: GitActionProgressPayload) =>
|
||||
reporter
|
||||
? reporter.publish({
|
||||
actionId,
|
||||
cwd: input.cwd,
|
||||
action: input.action,
|
||||
...event,
|
||||
} as GitActionProgressEvent)
|
||||
: Effect.void;
|
||||
|
||||
return {
|
||||
actionId,
|
||||
emit,
|
||||
};
|
||||
};
|
||||
|
||||
const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")(
|
||||
function* (
|
||||
@@ -1307,7 +1301,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
modelSelection,
|
||||
});
|
||||
|
||||
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${yield* randomUUIDv4}.md`);
|
||||
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
|
||||
yield* fileSystem
|
||||
.writeFileString(bodyFile, generated.body)
|
||||
.pipe(
|
||||
@@ -1597,7 +1591,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fn("runStackedAction")(
|
||||
function* (input, options) {
|
||||
const progress = yield* createProgressEmitter(input, options);
|
||||
const progress = createProgressEmitter(input, options);
|
||||
const currentPhase = yield* Ref.make<Option.Option<GitActionProgressPhase>>(Option.none());
|
||||
|
||||
const runAction = Effect.fn("runStackedAction.runAction")(function* (): Effect.fn.Return<
|
||||
|
||||
@@ -10,12 +10,10 @@ 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";
|
||||
|
||||
@@ -72,12 +70,10 @@ 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;
|
||||
@@ -92,31 +88,24 @@ const make = Effect.gen(function* () {
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
Effect.all({
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("checkpoint-revert-failure"),
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
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,
|
||||
});
|
||||
|
||||
const appendCaptureFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -124,30 +113,23 @@ const make = Effect.gen(function* () {
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
Effect.all({
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("checkpoint-capture-failure"),
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
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,
|
||||
});
|
||||
|
||||
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
|
||||
threadId: ThreadId,
|
||||
@@ -300,7 +282,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: yield* serverCommandId("checkpoint-turn-diff-complete"),
|
||||
commandId: serverCommandId("checkpoint-turn-diff-complete"),
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
completedAt: input.createdAt,
|
||||
@@ -330,10 +312,10 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: yield* serverCommandId("checkpoint-captured-activity"),
|
||||
commandId: serverCommandId("checkpoint-captured-activity"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.make(yield* randomUUID),
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
tone: "info",
|
||||
kind: "checkpoint.captured",
|
||||
summary: "Checkpoint captured",
|
||||
@@ -719,7 +701,7 @@ const make = Effect.gen(function* () {
|
||||
yield* orchestrationEngine
|
||||
.dispatch({
|
||||
type: "thread.revert.complete",
|
||||
commandId: yield* serverCommandId("checkpoint-revert-complete"),
|
||||
commandId: serverCommandId("checkpoint-revert-complete"),
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
createdAt: now,
|
||||
@@ -809,11 +791,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const processInput = (
|
||||
input: ReactorInput,
|
||||
): Effect.Effect<
|
||||
void,
|
||||
CheckpointStoreError | OrchestrationDispatchError | PlatformError.PlatformError,
|
||||
never
|
||||
> =>
|
||||
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError, never> =>
|
||||
input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
|
||||
|
||||
const processInputSafely = (input: ReactorInput) =>
|
||||
|
||||
@@ -211,7 +211,6 @@ describe("OrchestrationEngine", () => {
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
|
||||
@@ -7,7 +7,6 @@ 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";
|
||||
@@ -82,7 +81,6 @@ 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);
|
||||
@@ -153,18 +151,7 @@ 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,7 +105,6 @@ function isStalePendingApprovalFailureDetail(detail: string | null): boolean {
|
||||
detail.includes("unknown pending permission request")
|
||||
);
|
||||
}
|
||||
|
||||
function derivePendingUserInputCountFromActivities(
|
||||
activities: ReadonlyArray<ProjectionThreadActivity>,
|
||||
): number {
|
||||
|
||||
@@ -15,7 +15,6 @@ 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";
|
||||
@@ -82,6 +81,9 @@ 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";
|
||||
@@ -176,7 +178,6 @@ 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;
|
||||
@@ -184,9 +185,6 @@ 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,
|
||||
@@ -216,31 +214,24 @@ const make = Effect.gen(function* () {
|
||||
readonly createdAt: string;
|
||||
readonly requestId?: string;
|
||||
}) =>
|
||||
Effect.all({
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("provider-failure-activity"),
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
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,
|
||||
});
|
||||
|
||||
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
|
||||
const failReason = cause.reasons.find(Cause.isFailReason);
|
||||
@@ -258,17 +249,13 @@ const make = Effect.gen(function* () {
|
||||
readonly session: OrchestrationSession;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
serverCommandId("provider-session-set").pipe(
|
||||
Effect.flatMap((commandId) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId,
|
||||
threadId: input.threadId,
|
||||
session: input.session,
|
||||
createdAt: input.createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: serverCommandId("provider-session-set"),
|
||||
threadId: input.threadId,
|
||||
session: input.session,
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -623,7 +610,7 @@ const make = Effect.gen(function* () {
|
||||
const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: yield* serverCommandId("worktree-branch-rename"),
|
||||
commandId: serverCommandId("worktree-branch-rename"),
|
||||
threadId: input.threadId,
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
@@ -670,7 +657,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: yield* serverCommandId("thread-title-rename"),
|
||||
commandId: serverCommandId("thread-title-rename"),
|
||||
threadId: input.threadId,
|
||||
title: generated.title,
|
||||
});
|
||||
|
||||
@@ -19,7 +19,6 @@ 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";
|
||||
@@ -40,6 +39,8 @@ 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;
|
||||
@@ -606,16 +607,11 @@ 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,
|
||||
@@ -852,7 +848,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: yield* providerCommandId(input.event, input.commandTag),
|
||||
commandId: providerCommandId(input.event, input.commandTag),
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
delta: bufferedText,
|
||||
@@ -919,7 +915,7 @@ const make = Effect.gen(function* () {
|
||||
if (hasRenderableText) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: yield* providerCommandId(input.event, input.finalDeltaCommandTag),
|
||||
commandId: providerCommandId(input.event, input.finalDeltaCommandTag),
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
delta: text,
|
||||
@@ -931,7 +927,7 @@ const make = Effect.gen(function* () {
|
||||
if (input.hasProjectedMessage || hasRenderableText) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.complete",
|
||||
commandId: yield* providerCommandId(input.event, input.commandTag),
|
||||
commandId: providerCommandId(input.event, input.commandTag),
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
...(input.turnId ? { turnId: input.turnId } : {}),
|
||||
@@ -1007,7 +1003,7 @@ const make = Effect.gen(function* () {
|
||||
const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.proposed-plan.upsert",
|
||||
commandId: yield* providerCommandId(input.event, "proposed-plan-upsert"),
|
||||
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
|
||||
threadId: input.threadId,
|
||||
proposedPlan: {
|
||||
id: input.planId,
|
||||
@@ -1163,11 +1159,10 @@ 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}:${commandUuid}`,
|
||||
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
|
||||
),
|
||||
threadId: sourceThread.id,
|
||||
proposedPlan: {
|
||||
@@ -1301,7 +1296,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: yield* providerCommandId(event, "thread-session-set"),
|
||||
commandId: providerCommandId(event, "thread-session-set"),
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
@@ -1347,7 +1342,7 @@ const make = Effect.gen(function* () {
|
||||
if (spillChunk.length > 0) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: yield* providerCommandId(event, "assistant-delta-buffer-spill"),
|
||||
commandId: providerCommandId(event, "assistant-delta-buffer-spill"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
delta: spillChunk,
|
||||
@@ -1358,7 +1353,7 @@ const make = Effect.gen(function* () {
|
||||
} else {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: yield* providerCommandId(event, "assistant-delta"),
|
||||
commandId: providerCommandId(event, "assistant-delta"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
delta: assistantDelta,
|
||||
@@ -1551,7 +1546,7 @@ const make = Effect.gen(function* () {
|
||||
if (shouldApplyRuntimeError) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: yield* providerCommandId(event, "runtime-error-session-set"),
|
||||
commandId: providerCommandId(event, "runtime-error-session-set"),
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
@@ -1573,7 +1568,7 @@ const make = Effect.gen(function* () {
|
||||
if (event.type === "thread.metadata.updated" && event.payload.name) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: yield* providerCommandId(event, "thread-meta-update"),
|
||||
commandId: providerCommandId(event, "thread-meta-update"),
|
||||
threadId: thread.id,
|
||||
title: event.payload.name,
|
||||
});
|
||||
@@ -1601,7 +1596,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: yield* providerCommandId(event, "thread-turn-diff-complete"),
|
||||
commandId: providerCommandId(event, "thread-turn-diff-complete"),
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
completedAt: now,
|
||||
@@ -1618,17 +1613,13 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const activities = runtimeEventToActivities(event);
|
||||
yield* Effect.forEach(activities, (activity) =>
|
||||
providerCommandId(event, "thread-activity-append").pipe(
|
||||
Effect.flatMap((commandId) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId,
|
||||
threadId: thread.id,
|
||||
activity,
|
||||
createdAt: activity.createdAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: providerCommandId(event, "thread-activity-append"),
|
||||
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 * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
@@ -20,87 +20,93 @@ const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
const seedReadModel = Effect.gen(function* () {
|
||||
async function seedReadModel(): Promise<OrchestrationReadModel> {
|
||||
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",
|
||||
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 = 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",
|
||||
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,
|
||||
},
|
||||
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",
|
||||
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,
|
||||
},
|
||||
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,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
type PlannedEvent = Omit<OrchestrationEvent, "sequence">;
|
||||
|
||||
@@ -136,11 +142,12 @@ function normalizeDeleteEvent(event: PlannedEvent | ReadonlyArray<PlannedEvent>)
|
||||
});
|
||||
}
|
||||
|
||||
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(
|
||||
describe("decider deletion flows", () => {
|
||||
it("rejects deleting a non-empty project without force", async () => {
|
||||
const readModel = await seedReadModel();
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.delete",
|
||||
@@ -149,69 +156,72 @@ it.layer(NodeServices.layer)("decider deletion flows", (it) => {
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
expect(error.message).toContain("cannot be deleted without force=true");
|
||||
}),
|
||||
);
|
||||
),
|
||||
).rejects.toThrow("cannot be deleted without 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,
|
||||
};
|
||||
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,
|
||||
};
|
||||
|
||||
const forcedResult = yield* decideOrchestrationCommand({
|
||||
const forcedResult = await Effect.runPromise(
|
||||
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 = yield* 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 = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: nextCommand,
|
||||
readModel: sequentialReadModel,
|
||||
});
|
||||
const nextEvents = Array.isArray(decided) ? decided : [decided];
|
||||
sequentialEvents.push(...nextEvents);
|
||||
for (const nextEvent of nextEvents) {
|
||||
nextSequence += 1;
|
||||
sequentialReadModel = yield* projectEvent(sequentialReadModel, {
|
||||
}),
|
||||
);
|
||||
const nextEvents = Array.isArray(decided) ? decided : [decided];
|
||||
sequentialEvents.push(...nextEvents);
|
||||
for (const nextEvent of nextEvents) {
|
||||
nextSequence += 1;
|
||||
sequentialReadModel = await Effect.runPromise(
|
||||
projectEvent(sequentialReadModel, {
|
||||
...nextEvent,
|
||||
sequence: nextSequence,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
|
||||
}),
|
||||
);
|
||||
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
|
||||
});
|
||||
});
|
||||
@@ -8,9 +8,8 @@ import {
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { describe, expect, it } from "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";
|
||||
@@ -18,13 +17,14 @@ 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);
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
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({
|
||||
command: {
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-create-scripts"),
|
||||
@@ -34,19 +34,19 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
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.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, {
|
||||
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, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create-scripts"),
|
||||
aggregateKind: "project",
|
||||
@@ -66,19 +66,21 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
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 = yield* decideOrchestrationCommand({
|
||||
const result = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make("cmd-project-update-scripts"),
|
||||
@@ -86,19 +88,19 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
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.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, {
|
||||
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, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
@@ -118,8 +120,10 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
const readModel = yield* projectEvent(withProject, {
|
||||
}),
|
||||
);
|
||||
const readModel = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
@@ -145,9 +149,11 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
const result = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start"),
|
||||
@@ -167,35 +173,35 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
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.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, {
|
||||
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, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
@@ -215,8 +221,10 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
const readModel = yield* projectEvent(withProject, {
|
||||
}),
|
||||
);
|
||||
const readModel = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
@@ -242,9 +250,11 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
const result = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.make("cmd-runtime-mode-set"),
|
||||
@@ -253,27 +263,27 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
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.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, {
|
||||
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, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
@@ -293,8 +303,10 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
const readModel = yield* projectEvent(withProject, {
|
||||
}),
|
||||
);
|
||||
const readModel = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
@@ -320,9 +332,11 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
const result = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: CommandId.make("cmd-interaction-mode-set"),
|
||||
@@ -331,19 +345,19 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
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",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,10 @@
|
||||
import {
|
||||
EventId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
import type {
|
||||
OrchestrationCommand,
|
||||
OrchestrationEvent,
|
||||
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 {
|
||||
@@ -30,27 +27,17 @@ function withEventBase(
|
||||
readonly occurredAt: string;
|
||||
readonly metadata?: OrchestrationEvent["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 ?? {},
|
||||
})),
|
||||
),
|
||||
),
|
||||
);
|
||||
): 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 ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
type PlannedOrchestrationEvent = Omit<OrchestrationEvent, "sequence">;
|
||||
@@ -65,11 +52,7 @@ const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
|
||||
}: {
|
||||
readonly commands: ReadonlyArray<OrchestrationCommand>;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
}): Effect.fn.Return<
|
||||
ReadonlyArray<PlannedOrchestrationEvent>,
|
||||
OrchestrationCommandInvariantError | PlatformError.PlatformError,
|
||||
Crypto.Crypto
|
||||
> {
|
||||
}): Effect.fn.Return<ReadonlyArray<PlannedOrchestrationEvent>, OrchestrationCommandInvariantError> {
|
||||
let nextReadModel = readModel;
|
||||
let nextSequence = readModel.snapshotSequence;
|
||||
const plannedEvents: PlannedOrchestrationEvent[] = [];
|
||||
@@ -99,11 +82,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}: {
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
}): Effect.fn.Return<
|
||||
DecideOrchestrationCommandResult,
|
||||
OrchestrationCommandInvariantError | PlatformError.PlatformError,
|
||||
Crypto.Crypto
|
||||
> {
|
||||
}): Effect.fn.Return<DecideOrchestrationCommandResult, OrchestrationCommandInvariantError> {
|
||||
switch (command.type) {
|
||||
case "project.create": {
|
||||
yield* requireProjectAbsent({
|
||||
@@ -113,12 +92,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "project",
|
||||
aggregateId: command.projectId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "project.created",
|
||||
payload: {
|
||||
projectId: command.projectId,
|
||||
@@ -140,12 +119,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "project",
|
||||
aggregateId: command.projectId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "project.meta-updated",
|
||||
payload: {
|
||||
projectId: command.projectId,
|
||||
@@ -197,12 +176,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "project",
|
||||
aggregateId: command.projectId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "project.deleted" as const,
|
||||
payload: {
|
||||
projectId: command.projectId,
|
||||
@@ -223,12 +202,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.created",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -253,12 +232,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.deleted",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -275,12 +254,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.archived",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -298,12 +277,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.unarchived",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -320,12 +299,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.meta-updated",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -348,12 +327,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.runtime-mode-set",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -371,12 +350,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.interaction-mode-set",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -417,12 +396,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
}
|
||||
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -437,12 +416,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
},
|
||||
};
|
||||
const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
causationEventId: userMessageEvent.eventId,
|
||||
type: "thread.turn-start-requested",
|
||||
payload: {
|
||||
@@ -468,12 +447,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.turn-interrupt-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -490,7 +469,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
@@ -498,7 +477,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
metadata: {
|
||||
requestId: command.requestId,
|
||||
},
|
||||
})),
|
||||
}),
|
||||
type: "thread.approval-response-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -516,7 +495,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
@@ -524,7 +503,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
metadata: {
|
||||
requestId: command.requestId,
|
||||
},
|
||||
})),
|
||||
}),
|
||||
type: "thread.user-input-response-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -542,12 +521,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.checkpoint-revert-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -564,12 +543,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.session-stop-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -585,13 +564,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
metadata: {},
|
||||
})),
|
||||
}),
|
||||
type: "thread.session-set",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -607,12 +586,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -634,12 +613,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -661,12 +640,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.proposed-plan-upserted",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -682,12 +661,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.turn-diff-completed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -709,12 +688,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
}),
|
||||
type: "thread.reverted",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -738,13 +717,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
.requestId as OrchestrationEvent["metadata"]["requestId"])
|
||||
: undefined;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
...(requestId !== undefined ? { metadata: { requestId } } : {}),
|
||||
})),
|
||||
}),
|
||||
type: "thread.activity-appended",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
|
||||
@@ -58,10 +58,8 @@ export const orchestrationSnapshotRouteLayer = HttpRouter.add(
|
||||
status: 200,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
OrchestrationDispatchCommandError: respondToOrchestrationHttpError,
|
||||
OrchestrationGetSnapshotError: respondToOrchestrationHttpError,
|
||||
}),
|
||||
Effect.catchTag("OrchestrationDispatchCommandError", respondToOrchestrationHttpError),
|
||||
Effect.catchTag("OrchestrationGetSnapshotError", respondToOrchestrationHttpError),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ const AuthSessionDbRow = Schema.Struct({
|
||||
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
});
|
||||
|
||||
function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecord {
|
||||
function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): typeof AuthSessionRecord.Type {
|
||||
return {
|
||||
sessionId: row.sessionId,
|
||||
subject: row.subject,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.asVoid(SqlClient.SqlClient);
|
||||
export default Effect.gen(function* () {
|
||||
yield* SqlClient.SqlClient;
|
||||
});
|
||||
@@ -252,12 +252,14 @@ export const layerConfig = (
|
||||
config: Config.Wrap<SqliteClientConfig>,
|
||||
): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
|
||||
Layer.effectContext(
|
||||
Config.unwrap(config).pipe(
|
||||
Effect.flatMap(make),
|
||||
Effect.map((client) =>
|
||||
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
|
||||
Config.unwrap(config)
|
||||
.asEffect()
|
||||
.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,9 +651,7 @@ 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* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
)}`,
|
||||
command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
|
||||
args: [],
|
||||
}).pipe(Effect.provide(spawnerLayer), Effect.result);
|
||||
assert.equal(result._tag, "Failure");
|
||||
|
||||
@@ -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",
|
||||
) {}
|
||||
|
||||
// ==============================
|
||||
|
||||
@@ -90,7 +90,7 @@ export interface ProcessRunnerShape {
|
||||
}
|
||||
|
||||
export class ProcessRunner extends Context.Service<ProcessRunner, ProcessRunnerShape>()(
|
||||
"t3/processRunner",
|
||||
"t3/process/ProcessRunner",
|
||||
) {}
|
||||
|
||||
const DEFAULT_TIMEOUT = "60 seconds";
|
||||
|
||||
@@ -41,4 +41,4 @@ export interface ProjectSetupScriptRunnerShape {
|
||||
export class ProjectSetupScriptRunner extends Context.Service<
|
||||
ProjectSetupScriptRunner,
|
||||
ProjectSetupScriptRunnerShape
|
||||
>()("t3/project/Services/ProjectSetupScriptRunner") {}
|
||||
>()("t3/project/ProjectSetupScriptRunner") {}
|
||||
@@ -15,7 +15,6 @@
|
||||
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";
|
||||
@@ -78,7 +77,6 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
*/
|
||||
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";
|
||||
@@ -70,7 +69,6 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
*/
|
||||
export type CodexDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
*/
|
||||
import { CursorSettings, 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";
|
||||
@@ -62,7 +61,6 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
*/
|
||||
import { OpenCodeSettings, 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";
|
||||
@@ -74,7 +73,6 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime
|
||||
|
||||
@@ -42,7 +42,7 @@ const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
// Test-local service tag so the rest of the file can keep using `yield* ClaudeAdapter`.
|
||||
class ClaudeAdapter extends Context.Service<ClaudeAdapter, ClaudeAdapterShape>()(
|
||||
"t3/provider/Layers/ClaudeAdapter.test/ClaudeAdapter",
|
||||
"test/ClaudeAdapter",
|
||||
) {}
|
||||
|
||||
class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
|
||||
|
||||
@@ -52,7 +52,6 @@ import {
|
||||
resolvePromptInjectedEffort,
|
||||
} from "@t3tools/shared/model";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -61,6 +60,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Random from "effect/Random";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
@@ -70,7 +70,6 @@ import { ServerConfig } from "../../config.ts";
|
||||
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
|
||||
import {
|
||||
getClaudeModelCapabilities,
|
||||
isClaudeUltracodeEffort,
|
||||
normalizeClaudeCliEffort,
|
||||
resolveClaudeApiModelId,
|
||||
resolveClaudeEffort,
|
||||
@@ -260,11 +259,8 @@ function normalizeClaudeStreamMessages(
|
||||
return squashed.length > 0 ? [squashed] : [];
|
||||
}
|
||||
|
||||
function getEffectiveClaudeAgentEffort(
|
||||
effort: string | null | undefined,
|
||||
model: string | null | undefined,
|
||||
): ClaudeSdkEffort | null {
|
||||
const normalized = normalizeClaudeCliEffort(effort, model);
|
||||
function getEffectiveClaudeAgentEffort(effort: string | null | undefined): ClaudeSdkEffort | null {
|
||||
const normalized = normalizeClaudeCliEffort(effort);
|
||||
return normalized ? (normalized as ClaudeSdkEffort) : null;
|
||||
}
|
||||
|
||||
@@ -1006,7 +1002,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, options?.environment).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
@@ -1033,18 +1028,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "crypto/randomUUIDv4",
|
||||
detail: "Failed to generate Claude runtime identifier.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));
|
||||
const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));
|
||||
const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
|
||||
|
||||
const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
@@ -1068,7 +1052,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
id:
|
||||
"uuid" in message && typeof message.uuid === "string"
|
||||
? message.uuid
|
||||
: yield* randomUUIDv4,
|
||||
: yield* Random.nextUUIDv4,
|
||||
kind: "notification",
|
||||
provider: PROVIDER,
|
||||
createdAt: observedAt,
|
||||
@@ -1152,7 +1136,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
}
|
||||
|
||||
const block: AssistantTextBlockState = {
|
||||
itemId: yield* randomUUIDv4,
|
||||
itemId: yield* Random.nextUUIDv4,
|
||||
blockIndex,
|
||||
emittedTextDelta: false,
|
||||
fallbackText: options?.fallbackText ?? "",
|
||||
@@ -1985,7 +1969,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
// Auto-start a synthetic turn for assistant messages that arrive without
|
||||
// an active turn (e.g., background agent/subagent responses between user prompts).
|
||||
if (!context.turnState) {
|
||||
const turnId = TurnId.make(yield* randomUUIDv4);
|
||||
const turnId = TurnId.make(yield* Random.nextUUIDv4);
|
||||
const startedAt = yield* nowIso;
|
||||
context.turnState = {
|
||||
turnId,
|
||||
@@ -2398,17 +2382,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
toProcessError(cause, "Claude runtime stream failed.", context.session.threadId),
|
||||
).pipe(
|
||||
Stream.takeWhile(() => !context.stopped),
|
||||
Stream.runForEach((message) =>
|
||||
handleSdkMessage(context, message).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
toProcessError(
|
||||
cause,
|
||||
"Failed to process Claude runtime event.",
|
||||
context.session.threadId,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.runForEach((message) => handleSdkMessage(context, message)),
|
||||
);
|
||||
|
||||
const handleStreamExit = Effect.fn("handleStreamExit")(function* (
|
||||
@@ -2582,7 +2556,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const resumeState = readClaudeResumeState(input.resumeCursor);
|
||||
const threadId = input.threadId;
|
||||
const existingResumeSessionId = resumeState?.resume;
|
||||
const newSessionId = existingResumeSessionId === undefined ? yield* randomUUIDv4 : undefined;
|
||||
const newSessionId =
|
||||
existingResumeSessionId === undefined ? yield* Random.nextUUIDv4 : undefined;
|
||||
const sessionId = existingResumeSessionId ?? newSessionId;
|
||||
|
||||
const runtimeContext = yield* Effect.context<never>();
|
||||
@@ -2617,7 +2592,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
readonly toolUseID?: string;
|
||||
},
|
||||
) {
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
|
||||
|
||||
// Parse questions from the SDK's AskUserQuestion input.
|
||||
// `id` MUST equal the full question text — Claude SDK >= 2.1.121 looks
|
||||
@@ -2787,7 +2762,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
} satisfies PermissionResult;
|
||||
}
|
||||
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
|
||||
const requestType = classifyRequestType(toolName);
|
||||
const detail = summarizeToolRequest(toolName, toolInput);
|
||||
const decisionDeferred = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
@@ -2916,8 +2891,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const thinking = thinkingSupported
|
||||
? getModelSelectionBooleanOptionValue(modelSelection, "thinking")
|
||||
: undefined;
|
||||
const ultracode = isClaudeUltracodeEffort(effort);
|
||||
const effectiveEffort = getEffectiveClaudeAgentEffort(effort, modelSelection?.model);
|
||||
const effectiveEffort = getEffectiveClaudeAgentEffort(effort);
|
||||
const runtimeModeToPermission: Record<string, PermissionMode> = {
|
||||
"auto-accept-edits": "acceptEdits",
|
||||
"full-access": "bypassPermissions",
|
||||
@@ -2926,7 +2900,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const settings = {
|
||||
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(ultracode ? { ultracode: true } : {}),
|
||||
};
|
||||
const queryOptions: ClaudeQueryOptions = {
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
@@ -2934,8 +2907,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
pathToClaudeCodeExecutable: claudeBinaryPath,
|
||||
systemPrompt: { type: "preset", preset: "claude_code" },
|
||||
settingSources: [...CLAUDE_SETTING_SOURCES],
|
||||
// `ultracode` is a Claude Code setting, not an API effort level. It is
|
||||
// normalized to `xhigh` above and paired with `settings.ultracode`.
|
||||
// The SDK type lags the CLI here: Opus 4.7 accepts `xhigh` even though
|
||||
// the published `Options["effort"]` union currently stops at `max`.
|
||||
...(effectiveEffort
|
||||
? {
|
||||
effort: effectiveEffort as unknown as NonNullable<ClaudeQueryOptions["effort"]>,
|
||||
@@ -3090,11 +3063,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
if (context.streamFiber === streamFiber) {
|
||||
context.streamFiber = undefined;
|
||||
}
|
||||
return handleStreamExit(context, exit).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logError("Failed to close Claude runtime stream.", { cause }),
|
||||
),
|
||||
);
|
||||
return handleStreamExit(context, exit);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -3155,7 +3124,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
}
|
||||
|
||||
const turnId = TurnId.make(yield* randomUUIDv4);
|
||||
const turnId = TurnId.make(yield* Random.nextUUIDv4);
|
||||
const turnState: ClaudeTurnState = {
|
||||
turnId,
|
||||
startedAt: yield* nowIso,
|
||||
@@ -3304,12 +3273,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
emitExitEvent: false,
|
||||
}),
|
||||
{ discard: true },
|
||||
).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logError("Failed to emit Claude session shutdown event.", { cause }),
|
||||
),
|
||||
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
|
||||
),
|
||||
).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))),
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user