TypeScript
refactor: remove obsolete code (#9917)
Theo Browne9cb586acd049
diff --git a/apps/desktop/src/app/DesktopAppIdentity.test.ts b/apps/desktop/src/app/DesktopAppIdentity.test.tsindex 71bcf5f7aef..ce0c7d013a9 100644--- a/apps/desktop/src/app/DesktopAppIdentity.test.ts+++ b/apps/desktop/src/app/DesktopAppIdentity.test.ts@@ -57,7 +57,6 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>}),setAppUserModelId: () => Effect.void,getAppMetrics: Effect.succeed([]),- isDefaultProtocolClient: () => Effect.succeed(false),setAsDefaultProtocolClient: () => Effect.succeed(true),setDesktopName: () => Effect.void,setDockIcon: (iconPath) =>diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.tsindex aa28ff8d86e..fdc69841343 100644--- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts+++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts@@ -3,6 +3,7 @@ import { assert, describe, it } from "@effect/vitest";import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";import * as Effect from "effect/Effect";+import * as Encoding from "effect/Encoding";import * as FileSystem from "effect/FileSystem";import * as Path from "effect/Path";import * as Layer from "effect/Layer";@@ -22,6 +23,11 @@ const textEncoder = new TextEncoder();const decodeConnectionCatalog = Schema.decodeEffect(Schema.fromJsonString(ConnectionCatalogDocument),);+const encodeLegacySavedEnvironments = Schema.encodeEffect(+ Schema.fromJsonString(+ Schema.Struct({ version: Schema.Literal(1), records: Schema.Array(Schema.Unknown) }),+ ),+);function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {isEncryptionAvailable: Effect.succeed(available),@@ -125,7 +131,8 @@ describe("DesktopConnectionCatalogStore", () => {withStore(Effect.gen(function* () {const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;- const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;+ const environment = yield* DesktopEnvironment.DesktopEnvironment;+ const fileSystem = yield* FileSystem.FileSystem;const records: readonly PersistedSavedEnvironmentRecord[] = [{environmentId: EnvironmentId.make("relay-environment"),@@ -159,11 +166,21 @@ describe("DesktopConnectionCatalogStore", () => {lastConnectedAt: null,},];- yield* savedEnvironments.setRegistry(records);- assert.isTrue(- yield* savedEnvironments.setSecret({- environmentId: EnvironmentId.make("bearer-environment"),- secret: "legacy-token",+ yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });+ yield* fileSystem.writeFileString(+ environment.savedEnvironmentRegistryPath,+ yield* encodeLegacySavedEnvironments({+ version: 1,+ records: records.map((record) =>+ record.environmentId === "bearer-environment"+ ? {+ ...record,+ encryptedBearerToken: Encoding.encodeBase64(+ textEncoder.encode("encrypted:legacy-token"),+ ),+ }+ : record,+ ),}),);@@ -218,7 +235,10 @@ describe("DesktopConnectionCatalogStore", () => {assert.equal(catalog.credentials[0].credential.token, "legacy-token");}- yield* savedEnvironments.setRegistry([]);+ yield* fileSystem.writeFileString(+ environment.savedEnvironmentRegistryPath,+ '{"version":1,"records":[]}',+ );assert.deepEqual(yield* store.get, migrated);}),),diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.tsindex 515be6726c9..33c74f5a8b9 100644--- a/apps/desktop/src/app/DesktopLifecycle.test.ts+++ b/apps/desktop/src/app/DesktopLifecycle.test.ts@@ -43,7 +43,6 @@ function makeElectronAppLayer(setAboutPanelOptions: () => Effect.void,setAppUserModelId: () => Effect.void,getAppMetrics: Effect.succeed([]),- isDefaultProtocolClient: () => Effect.succeed(false),setAsDefaultProtocolClient: () => Effect.succeed(true),setDesktopName: () => Effect.void,setDockIcon: () => Effect.void,diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.tsindex 5a1ef70ad1c..df2001f1ac2 100644--- a/apps/desktop/src/backend/DesktopBackendManager.test.ts+++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts@@ -165,9 +165,7 @@ function makeTestInstance(input: MakeInstanceInput) {latest: Effect.succeed(Option.none()),changes: Stream.empty,encoded: input.desktopTelemetryStream ?? Stream.empty,- handleControl: () => Effect.void,- handleControlForSource: (_sourceId, message) =>- (input.desktopTelemetryPublisher?.handleControl ?? (() => Effect.void))(message),+ handleControlForSource: () => Effect.void,removeControlSource: () => Effect.void,publishUpdateReport: () => Effect.void,updateRequests: Stream.empty,@@ -596,7 +594,7 @@ describe("DesktopBackendManager", () => {const instance = yield* makeTestInstance({spawnerLayer,desktopTelemetryPublisher: {- handleControl: (message) =>+ handleControlForSource: (_sourceId, message) =>message.type === "setDiagnosticsDemand"? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid): Effect.void,diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.tsindex b9a96d72a77..7859223161b 100644--- a/apps/desktop/src/backend/DesktopBackendPool.test.ts+++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts@@ -70,7 +70,6 @@ function makePoolLayer(latest: Effect.succeed(Option.none()),changes: Stream.empty,encoded: Stream.empty,- handleControl: () => Effect.void,handleControlForSource: () => Effect.void,removeControlSource: () => Effect.void,publishUpdateReport: () => Effect.void,diff --git a/apps/desktop/src/electron/ElectronApp.test.ts b/apps/desktop/src/electron/ElectronApp.test.tsindex 4189ea793e2..84f37b6f5f5 100644--- a/apps/desktop/src/electron/ElectronApp.test.ts+++ b/apps/desktop/src/electron/ElectronApp.test.ts@@ -10,7 +10,6 @@ const {getAppPathMock,getSystemLocaleMock,getVersionMock,- isDefaultProtocolClientMock,onMock,quitMock,relaunchMock,@@ -32,7 +31,6 @@ const {getAppPathMock: vi.fn(() => "/app"),getSystemLocaleMock: vi.fn(() => "en-GB"),getVersionMock: vi.fn(() => "1.2.3"),- isDefaultProtocolClientMock: vi.fn(() => false),onMock: vi.fn(),quitMock: vi.fn(),relaunchMock: vi.fn(),@@ -64,7 +62,6 @@ vi.mock("electron", () => ({getAppPath: getAppPathMock,getSystemLocale: getSystemLocaleMock,getVersion: getVersionMock,- isDefaultProtocolClient: isDefaultProtocolClientMock,isPackaged: true,name: "T3 Code",on: onMock,diff --git a/apps/desktop/src/electron/ElectronApp.ts b/apps/desktop/src/electron/ElectronApp.tsindex b54da535add..f75ea51552e 100644--- a/apps/desktop/src/electron/ElectronApp.ts+++ b/apps/desktop/src/electron/ElectronApp.ts@@ -64,7 +64,6 @@ export class ElectronApp extends Context.Service<) => Effect.Effect<void>;readonly setAppUserModelId: (id: string) => Effect.Effect<void>;readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;- readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;readonly setAsDefaultProtocolClient: (protocol: string,path?: string,@@ -166,8 +165,6 @@ export const make = ElectronApp.of({Electron.app.setAppUserModelId(id);}),getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),- isDefaultProtocolClient: (protocol) =>- Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),setAsDefaultProtocolClient: (protocol, path, args) =>Effect.sync(() => {if (path === undefined) {diff --git a/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts b/apps/desktop/src/settings/DesktopSavedEnvironments.test.tsindex 348f6cb3843..dad53815f3a 100644--- a/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts+++ b/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts@@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import { assert, describe, it } from "@effect/vitest";import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";import * as Effect from "effect/Effect";+import * as Encoding from "effect/Encoding";import * as FileSystem from "effect/FileSystem";import * as Path from "effect/Path";import * as Layer from "effect/Layer";@@ -39,16 +40,29 @@ const SavedEnvironmentRegistryDocumentProbe = Schema.Struct({const SavedEnvironmentRegistryDocumentProbeJson = Schema.fromJsonString(SavedEnvironmentRegistryDocumentProbe,);-const decodeSavedEnvironmentRegistryDocumentProbe = Schema.decodeEffect(- SavedEnvironmentRegistryDocumentProbeJson,-);const encodeSavedEnvironmentRegistryDocumentProbe = Schema.encodeEffect(SavedEnvironmentRegistryDocumentProbeJson,);++const seedSavedEnvironmentRegistry = Effect.fn(function* (encryptedBearerToken?: string) {+ const environment = yield* DesktopEnvironment.DesktopEnvironment;+ const fileSystem = yield* FileSystem.FileSystem;+ yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });+ const encoded = yield* encodeSavedEnvironmentRegistryDocumentProbe({+ version: 1,+ records: [+ {+ ...savedRegistryRecord,+ ...(encryptedBearerToken === undefined ? {} : { encryptedBearerToken }),+ },+ ],+ });+ yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, `${encoded}\n`);+});+function makeSafeStorageLayer(input: {readonly available: boolean;readonly availabilityError?: unknown;- readonly encryptError?: unknown;readonly decryptError?: unknown;}) {return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {@@ -60,14 +74,7 @@ function makeSafeStorageLayer(input: {cause: input.availabilityError,}),),- encryptString: (value) =>- input.encryptError === undefined- ? Effect.succeed(textEncoder.encode(`enc:${value}`))- : Effect.fail(- new ElectronSafeStorage.ElectronSafeStorageEncryptError({- cause: input.encryptError,- }),- ),+ encryptString: (value) => Effect.succeed(textEncoder.encode(`enc:${value}`)),decryptString: (value) => {if (input.decryptError !== undefined) {return Effect.fail(@@ -96,7 +103,6 @@ function makeLayer(options?: {readonly availableSecretStorage?: boolean;readonly availabilityError?: unknown;- readonly encryptError?: unknown;readonly decryptError?: unknown;},fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,@@ -120,7 +126,6 @@ function makeLayer(const safeStorageLayer = makeSafeStorageLayer({available: options?.availableSecretStorage ?? true,availabilityError: options?.availabilityError,- encryptError: options?.encryptError,decryptError: options?.decryptError,});const dependencies = Layer.mergeAll(@@ -138,7 +143,6 @@ const withSavedEnvironments = <A, E, R>(options?: {readonly availableSecretStorage?: boolean;readonly availabilityError?: unknown;- readonly encryptError?: unknown;readonly decryptError?: unknown;},) =>@@ -151,20 +155,13 @@ const withSavedEnvironments = <A, E, R>(}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);describe("DesktopSavedEnvironments", () => {- it.effect("persists and reloads saved environment metadata", () =>+ it.effect("reads saved environment metadata", () =>withSavedEnvironments(Effect.gen(function* () {- const environment = yield* DesktopEnvironment.DesktopEnvironment;- const fileSystem = yield* FileSystem.FileSystem;const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;- yield* savedEnvironments.setRegistry([savedRegistryRecord]);+ yield* seedSavedEnvironmentRegistry();assert.deepEqual(yield* savedEnvironments.getRegistry, [savedRegistryRecord]);- const persisted = yield* decodeSavedEnvironmentRegistryDocumentProbe(- yield* fileSystem.readFileString(environment.savedEnvironmentRegistryPath),- );- assert.equal(persisted.version, 1);- assert.lengthOf(persisted.records, 1);}),),);@@ -205,17 +202,12 @@ describe("DesktopSavedEnvironments", () => {),);- it.effect("persists encrypted saved environment secrets when encryption is available", () =>+ it.effect("reads encrypted saved environment secrets when encryption is available", () =>withSavedEnvironments(Effect.gen(function* () {const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;- yield* savedEnvironments.setRegistry([savedRegistryRecord]);-- assert.isTrue(- yield* savedEnvironments.setSecret({- environmentId: savedRegistryRecord.environmentId,- secret: "bearer-token",- }),+ yield* seedSavedEnvironmentRegistry(+ Encoding.encodeBase64(textEncoder.encode("enc:bearer-token")),);assert.deepEqual(@@ -230,14 +222,8 @@ describe("DesktopSavedEnvironments", () => {withSavedEnvironments(Effect.gen(function* () {const environment = yield* DesktopEnvironment.DesktopEnvironment;- const fileSystem = yield* FileSystem.FileSystem;const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;- yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });- const encoded = yield* encodeSavedEnvironmentRegistryDocumentProbe({- version: 1,- records: [{ ...savedRegistryRecord, encryptedBearerToken: "%%%" }],- });- yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, `${encoded}\n`);+ yield* seedSavedEnvironmentRegistry("%%%");const error = yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)@@ -256,17 +242,17 @@ describe("DesktopSavedEnvironments", () => {),);- it.effect("returns false when writing secrets while encryption is unavailable", () =>+ it.effect("returns no secret while encryption is unavailable", () =>withSavedEnvironments(Effect.gen(function* () {const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;- yield* savedEnvironments.setRegistry([savedRegistryRecord]);+ yield* seedSavedEnvironmentRegistry(+ Encoding.encodeBase64(textEncoder.encode("enc:bearer-token")),+ );- assert.isFalse(- yield* savedEnvironments.setSecret({- environmentId: savedRegistryRecord.environmentId,- secret: "next-token",- }),+ assert.deepEqual(+ yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId),+ Option.none(),);}),{ availableSecretStorage: false },@@ -279,13 +265,12 @@ describe("DesktopSavedEnvironments", () => {Effect.gen(function* () {const environment = yield* DesktopEnvironment.DesktopEnvironment;const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;- yield* savedEnvironments.setRegistry([savedRegistryRecord]);+ yield* seedSavedEnvironmentRegistry(+ Encoding.encodeBase64(textEncoder.encode("enc:bearer-token")),+ );const error = yield* savedEnvironments- .setSecret({- environmentId: savedRegistryRecord.environmentId,- secret: "next-token",- })+ .getSecret(savedRegistryRecord.environmentId).pipe(Effect.flip);assert.instanceOf(@@ -309,45 +294,6 @@ describe("DesktopSavedEnvironments", () => {);});- it.effect("removes saved environment secrets", () =>- withSavedEnvironments(- Effect.gen(function* () {- const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;- yield* savedEnvironments.setRegistry([savedRegistryRecord]);- yield* savedEnvironments.setSecret({- environmentId: savedRegistryRecord.environmentId,- secret: "bearer-token",- });-- yield* savedEnvironments.removeSecret(savedRegistryRecord.environmentId);-- assert.isTrue(- Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),- );- }),- ),- );-- it.effect("removes saved environment metadata and its embedded secret atomically", () =>- withSavedEnvironments(- Effect.gen(function* () {- const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;- yield* savedEnvironments.setRegistry([savedRegistryRecord]);- yield* savedEnvironments.setSecret({- environmentId: savedRegistryRecord.environmentId,- secret: "bearer-token",- });-- yield* savedEnvironments.removeEnvironment(savedRegistryRecord.environmentId);-- assert.deepEqual(yield* savedEnvironments.getRegistry, []);- assert.isTrue(- Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),- );- }),- ),- );-it.effect("treats empty saved environment documents as empty", () =>withSavedEnvironments(Effect.gen(function* () {@@ -388,13 +334,6 @@ describe("DesktopSavedEnvironments", () => {secretError,DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,);- const mutationError = yield* savedEnvironments- .setRegistry([savedRegistryRecord])- .pipe(Effect.flip);- assert.instanceOf(- mutationError,- DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,- );}),),);@@ -431,77 +370,4 @@ describe("DesktopSavedEnvironments", () => {assert.notEqual(error.message, permissionError.message);}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),);-- it.effect("reports the failed saved environment write operation and path", () =>- Effect.gen(function* () {- const baseFileSystem = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({- prefix: "t3-desktop-saved-environments-test-",- });- const permissionError = PlatformError.systemError({- _tag: "PermissionDenied",- module: "FileSystem",- method: "makeDirectory",- pathOrDescriptor: path.join(baseDir, "userdata"),- });- const fileSystemLayer = Layer.succeed(- FileSystem.FileSystem,- FileSystem.makeNoop({- readFileString: baseFileSystem.readFileString,- makeDirectory: () => Effect.fail(permissionError),- }),- );- const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments.pipe(- Effect.provide(makeLayer(baseDir, undefined, fileSystemLayer)),- );-- const error = yield* savedEnvironments.setRegistry([savedRegistryRecord]).pipe(Effect.flip);- assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsWriteError);- assert.equal(error.operation, "create-directory");- assert.equal(error.path, path.join(baseDir, "userdata"));- assert.strictEqual(error.cause, permissionError);- assert.equal(- error.message,- `Desktop saved-environment write failed during create-directory at ${path.join(baseDir, "userdata")}.`,- );- assert.notEqual(error.message, permissionError.message);- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),- );-- it.effect("returns false when writing a secret without metadata", () =>- withSavedEnvironments(- Effect.gen(function* () {- const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;-- assert.isFalse(- yield* savedEnvironments.setSecret({- environmentId: savedRegistryRecord.environmentId,- secret: "bearer-token",- }),- );- }),- ),- );-- it.effect("preserves encrypted secrets when metadata is rewritten", () =>- withSavedEnvironments(- Effect.gen(function* () {- const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;- yield* savedEnvironments.setRegistry([savedRegistryRecord]);- yield* savedEnvironments.setSecret({- environmentId: savedRegistryRecord.environmentId,- secret: "bearer-token",- });-- yield* savedEnvironments.setRegistry([savedRegistryRecord]);-- assert.deepEqual(yield* savedEnvironments.getRegistry, [savedRegistryRecord]);- assert.deepEqual(- yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId),- Option.some("bearer-token"),- );- }),- ),- );});diff --git a/apps/desktop/src/settings/DesktopSavedEnvironments.ts b/apps/desktop/src/settings/DesktopSavedEnvironments.tsindex 79959bc3c73..f54b464a7db 100644--- a/apps/desktop/src/settings/DesktopSavedEnvironments.ts+++ b/apps/desktop/src/settings/DesktopSavedEnvironments.ts@@ -1,13 +1,11 @@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 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 Path from "effect/Path";import * as Schema from "effect/Schema";import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";@@ -65,37 +63,12 @@ const SavedEnvironmentRegistryDocumentJson = fromLenientJson(const decodeSavedEnvironmentRegistryDocumentJson = Schema.decodeEffect(SavedEnvironmentRegistryDocumentJson,);-const encodeSavedEnvironmentRegistryDocumentJson = Schema.encodeEffect(- SavedEnvironmentRegistryDocumentJson,-);--const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([- "create-temporary-file-name",- "encode-registry",- "create-directory",- "write-temporary-file",- "replace-registry-file",-]);const DesktopSavedEnvironmentSecretProtectionOperation = Schema.Literals(["check-encryption-availability",- "encrypt-secret","decrypt-secret",]);-export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedError<DesktopSavedEnvironmentsWriteError>()(- "DesktopSavedEnvironmentsWriteError",- {- operation: DesktopSavedEnvironmentsWriteOperation,- path: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Desktop saved-environment write failed during ${this.operation} at ${this.path}.`;- }-}-export class DesktopSavedEnvironmentsReadError extends Schema.TaggedError<DesktopSavedEnvironmentsReadError>()("DesktopSavedEnvironmentsReadError",{@@ -152,19 +125,12 @@ export type DesktopSavedEnvironmentsReadRegistryError =| DesktopSavedEnvironmentsReadError| DesktopSavedEnvironmentsDocumentDecodeError;-export type DesktopSavedEnvironmentsMutationError =- | DesktopSavedEnvironmentsReadRegistryError- | DesktopSavedEnvironmentsWriteError;-export type DesktopSavedEnvironmentsGetSecretError =| DesktopSavedEnvironmentsReadRegistryError| DesktopSavedEnvironmentSecretDecodeError| DesktopSavedEnvironmentSecretProtectionError;-export type DesktopSavedEnvironmentsSetSecretError =- | DesktopSavedEnvironmentsMutationError- | DesktopSavedEnvironmentSecretProtectionError;-+/** Reads the previous registry for connection-catalog migration. */export class DesktopSavedEnvironments extends Context.Service<DesktopSavedEnvironments,{@@ -172,22 +138,10 @@ export class DesktopSavedEnvironments extends Context.Service<readonly PersistedSavedEnvironmentRecord[],DesktopSavedEnvironmentsReadRegistryError>;- readonly setRegistry: (- records: readonly PersistedSavedEnvironmentRecord[],- ) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;- readonly removeEnvironment: (- environmentId: string,- ) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;+readonly getSecret: (environmentId: string,) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;- readonly setSecret: (input: {- readonly environmentId: string;- readonly secret: string;- }) => Effect.Effect<boolean, DesktopSavedEnvironmentsSetSecretError>;- readonly removeSecret: (- environmentId: string,- ) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;}>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}@@ -209,28 +163,6 @@ function toPersistedSavedEnvironmentRecord(};}-function toSavedEnvironmentStorageRecord(- record: PersistedSavedEnvironmentRecord | PersistedSavedEnvironmentStorageRecord,- encryptedBearerToken: Option.Option<string>,-): PersistedSavedEnvironmentStorageRecord {- const nextRecord = {- environmentId: record.environmentId,- label: record.label,- httpBaseUrl: record.httpBaseUrl,- wsBaseUrl: record.wsBaseUrl,- createdAt: record.createdAt,- lastConnectedAt: record.lastConnectedAt,- };- const metadata = {- ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),- ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}),- };- return Option.match(encryptedBearerToken, {- onNone: () => ({ ...nextRecord, ...metadata }),- onSome: (value) => ({ ...nextRecord, ...metadata, encryptedBearerToken: value }),- });-}-function normalizeSavedEnvironmentRegistryDocument(document: SavedEnvironmentRegistryStorageDocument,): SavedEnvironmentRegistryDocument {@@ -272,80 +204,6 @@ function readRegistryDocument();}-const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistryDocument")(- function* (input: {- readonly fileSystem: FileSystem.FileSystem;- readonly path: Path.Path;- readonly registryPath: string;- readonly document: SavedEnvironmentRegistryDocument;- readonly suffix: string;- }): Effect.fn.Return<void, DesktopSavedEnvironmentsWriteError> {- const directory = input.path.dirname(input.registryPath);- const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;- const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(- Effect.mapError(- (cause) =>- new DesktopSavedEnvironmentsWriteError({- operation: "encode-registry",- path: input.registryPath,- cause,- }),- ),- );- yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(- Effect.mapError(- (cause) =>- new DesktopSavedEnvironmentsWriteError({- operation: "create-directory",- path: directory,- cause,- }),- ),- );- yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(- Effect.mapError(- (cause) =>- new DesktopSavedEnvironmentsWriteError({- operation: "write-temporary-file",- path: tempPath,- cause,- }),- ),- );- yield* input.fileSystem.rename(tempPath, input.registryPath).pipe(- Effect.mapError(- (cause) =>- new DesktopSavedEnvironmentsWriteError({- operation: "replace-registry-file",- path: input.registryPath,- cause,- }),- ),- );- },-);--function preserveExistingSecrets(- currentDocument: SavedEnvironmentRegistryDocument,- records: readonly PersistedSavedEnvironmentRecord[],-): SavedEnvironmentRegistryDocument {- const encryptedBearerTokenById = new Map(- currentDocument.records.flatMap((record) =>- record.encryptedBearerToken- ? [[record.environmentId, record.encryptedBearerToken] as const]- : [],- ),- );-- return {- version: currentDocument.version,- records: records.map((record) => {- const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);- return toSavedEnvironmentStorageRecord(record, Option.fromNullishOr(encryptedBearerToken));- }),- };-}-function decodeSecretBytes(environmentId: string,registryPath: string,@@ -368,31 +226,8 @@ function decodeSecretBytes(export const make = Effect.gen(function* () {const environment = yield* DesktopEnvironment.DesktopEnvironment;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.mapError(- (cause) =>- new DesktopSavedEnvironmentsWriteError({- operation: "create-temporary-file-name",- path: environment.savedEnvironmentRegistryPath,- cause,- }),- ),- Effect.flatMap((suffix) =>- writeRegistryDocument({- fileSystem,- path,- registryPath: environment.savedEnvironmentRegistryPath,- document,- suffix,- }),- ),- );+ const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;return DesktopSavedEnvironments.of({getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(@@ -401,30 +236,7 @@ export const make = Effect.gen(function* () {),Effect.withSpan("desktop.savedEnvironments.getRegistry"),),- setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {- const currentDocument = yield* readRegistryDocument(- fileSystem,- environment.savedEnvironmentRegistryPath,- );- yield* writeDocument(preserveExistingSecrets(currentDocument, records));- }),- removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(- function* (environmentId) {- yield* Effect.annotateCurrentSpan({ environmentId });- const document = yield* readRegistryDocument(- fileSystem,- environment.savedEnvironmentRegistryPath,- );- if (!document.records.some((record) => record.environmentId === environmentId)) {- return;- }- yield* writeDocument({- version: document.version,- records: document.records.filter((record) => record.environmentId !== environmentId),- });- },- ),getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {yield* Effect.annotateCurrentSpan({ environmentId });const document = yield* readRegistryDocument(@@ -472,85 +284,6 @@ export const make = Effect.gen(function* () {),);}),- setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {- const { environmentId, secret } = input;- yield* Effect.annotateCurrentSpan({ environmentId });- const document = yield* readRegistryDocument(- fileSystem,- environment.savedEnvironmentRegistryPath,- );-- const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(- Effect.mapError(- (cause) =>- new DesktopSavedEnvironmentSecretProtectionError({- operation: "check-encryption-availability",- environmentId,- registryPath: environment.savedEnvironmentRegistryPath,- cause,- }),- ),- );- if (!encryptionAvailable) {- return false;- }-- const encryptedBearerToken = Encoding.encodeBase64(- yield* safeStorage.encryptString(secret).pipe(- Effect.mapError(- (cause) =>- new DesktopSavedEnvironmentSecretProtectionError({- operation: "encrypt-secret",- environmentId,- registryPath: environment.savedEnvironmentRegistryPath,- cause,- }),- ),- ),- );- let found = false;- const nextDocument: SavedEnvironmentRegistryDocument = {- version: document.version,- records: document.records.map((record) => {- if (record.environmentId !== environmentId) {- return record;- }-- found = true;- return toSavedEnvironmentStorageRecord(record, Option.some(encryptedBearerToken));- }),- };-- if (found) {- yield* writeDocument(nextDocument);- }- return found;- }),- removeSecret: Effect.fn("desktop.savedEnvironments.removeSecret")(function* (environmentId) {- yield* Effect.annotateCurrentSpan({ environmentId });- const document = yield* readRegistryDocument(- fileSystem,- environment.savedEnvironmentRegistryPath,- );- if (- !document.records.some(- (record) =>- record.environmentId === environmentId && record.encryptedBearerToken !== undefined,- )- ) {- return;- }-- yield* writeDocument({- version: document.version,- records: document.records.map((record) => {- if (record.environmentId !== environmentId) {- return record;- }- return toPersistedSavedEnvironmentRecord(record);- }),- });- }),});});diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.tsindex 5a76402b1d3..6a369a4598a 100644--- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts+++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts@@ -397,16 +397,6 @@ describe("DesktopShellEnvironment", () => {}),);- it("resolves dbus runtime dir candidates with existence checks", () => {- const busPath = DesktopShellEnvironment.resolveDefaultLinuxDbusSessionBusAddress({- env: { XDG_RUNTIME_DIR: "/tmp/stale-runtime" },- uid: 1000,- exists: (path) => path === "/run/user/1000/bus",- });-- assert.equal(busPath, "unix:path=/run/user/1000/bus");- });-it.effect("logs command failures with safe probe context and the exact cause", () => {const env: NodeJS.ProcessEnv = {SHELL: "/bin/bash",diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.tsindex 5c6b67fd58c..704b061db36 100644--- a/apps/desktop/src/shell/DesktopShellEnvironment.ts+++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts@@ -122,30 +122,6 @@ const linuxRuntimeDirCandidates = (return candidates.filter((candidate) => candidate.length > 0);};-function resolveDefaultLinuxDbusSessionBusPath(input: {- readonly env: NodeJS.ProcessEnv;- readonly uid: number | undefined;- readonly exists?: (path: string) => boolean;-}): string | null {- for (const runtimeDir of linuxRuntimeDirCandidates(input.env, input.uid)) {- const busPath = `${runtimeDir}/bus`;- if (input.exists === undefined || input.exists(busPath)) {- return busPath;- }- }-- return null;-}--export function resolveDefaultLinuxDbusSessionBusAddress(input: {- readonly env: NodeJS.ProcessEnv;- readonly exists: (path: string) => boolean;- readonly uid: number | undefined;-}): string | null {- const busPath = resolveDefaultLinuxDbusSessionBusPath(input);- return busPath !== null && input.exists(busPath) ? `unix:path=${busPath}` : null;-}-const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {const normalized = entry.trim().replace(/^"+|"+$/g, "");return platform === "win32" ? normalized.toLowerCase() : normalized;diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.tsindex b0094f6867b..b5e724084a2 100644--- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts+++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts@@ -45,10 +45,6 @@ export type DesktopSshEnvironmentOperationError =export type DesktopSshEnvironmentDiscoverError = SshHostDiscoveryError;-export type DesktopSshEnvironmentError =- | DesktopSshEnvironmentDiscoverError- | DesktopSshEnvironmentOperationError;-export class DesktopSshEnvironment extends Context.Service<DesktopSshEnvironment,{diff --git a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.ts b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.tsindex 120199da648..5c0bf0998f4 100644--- a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.ts+++ b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.ts@@ -164,10 +164,6 @@ export type DesktopSshPasswordPromptResolveError =| DesktopSshPromptInvalidRequestIdError| DesktopSshPromptExpiredError;-export type DesktopSshPasswordPromptError =- | DesktopSshPasswordPromptRequestError- | DesktopSshPasswordPromptResolveError;-export const DesktopSshPasswordPromptCancellation = Schema.Union([DesktopSshPromptCancelledError,DesktopSshPromptWindowClosedError,diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.tsindex d705252ef58..cef90b29874 100644--- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts+++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts@@ -39,7 +39,6 @@ function makeElectronAppLayer(onMetricsRead();return metrics;}),- isDefaultProtocolClient: () => Effect.succeed(false),setAsDefaultProtocolClient: () => Effect.succeed(true),setDesktopName: () => Effect.void,setDockIcon: () => Effect.void,@@ -172,7 +171,7 @@ describe("DesktopTelemetryPublisher", () => {const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);yield* Effect.yieldNow;- yield* publisher.handleControl({+ yield* publisher.handleControlForSource("primary-backend", {version: 1,type: "setDiagnosticsDemand",enabled: true,@@ -188,7 +187,7 @@ describe("DesktopTelemetryPublisher", () => {type: "setDiagnosticsDemand",enabled: true,});- yield* publisher.handleControl({+ yield* publisher.handleControlForSource("primary-backend", {version: 1,type: "setDiagnosticsDemand",enabled: false,@@ -308,7 +307,7 @@ describe("DesktopTelemetryPublisher", () => {Effect.forkChild,);yield* Effect.yieldNow;- yield* publisher.handleControl({+ yield* publisher.handleControlForSource("primary-backend", {version: 1,type: "setHostPowerIntervals",activeIntervalMs: 7_000,@@ -369,7 +368,7 @@ describe("DesktopTelemetryPublisher", () => {Effect.forkChild,);yield* Effect.yieldNow;- yield* publisher.handleControl({+ yield* publisher.handleControlForSource("primary-backend", {version: 1,type: "setDiagnosticsDemand",enabled: true,diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.tsindex 8fd478c821e..18ea0a8380a 100644--- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts+++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts@@ -63,7 +63,6 @@ export class DesktopTelemetryPublisher extends Context.Service<readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;readonly encoded: Stream.Stream<Uint8Array>;- readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;readonly handleControlForSource: (sourceId: string,message: DesktopTelemetryControlMessage,@@ -365,8 +364,6 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),),);- const handleControl: DesktopTelemetryPublisher["Service"]["handleControl"] = (message) =>- handleControlForSource("legacy", message);const snapshots = Stream.unwrap(Effect.gen(function* () {@@ -415,7 +412,6 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {latest: Ref.get(latest),changes: Stream.fromPubSub(changes),encoded,- handleControl,handleControlForSource,removeControlSource,publishUpdateReport,diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.test.tsindex 0f4cb970da2..1198429a170 100644--- a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts+++ b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts@@ -57,7 +57,6 @@ function runRemoteUpdatesTest(latest: Effect.succeedNone,changes: Stream.empty,encoded: Stream.empty,- handleControl: () => Effect.void,handleControlForSource: () => Effect.void,removeControlSource: () => Effect.void,publishUpdateReport: (report) =>diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.tsindex 4b06f5ee510..5f5cbaa1d7f 100644--- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts+++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts@@ -41,7 +41,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {setAboutPanelOptions: () => Effect.void,setAppUserModelId: () => Effect.void,getAppMetrics: Effect.succeed([]),- isDefaultProtocolClient: () => Effect.succeed(false),setAsDefaultProtocolClient: () => Effect.succeed(true),setDesktopName: () => Effect.void,setDockIcon: () => Effect.void,diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swiftindex 9b36d60f94e..74111988f15 100644--- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift+++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift@@ -2001,19 +2001,6 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {)}- private func fileStatusText(_ changeType: String?) -> String {- switch changeType {- case "new":- return "A"- case "deleted":- return "D"- case "renamed":- return "R"- default:- return ""- }- }-private func fileStatusColor(_ changeType: String?) -> UIColor {switch changeType {case "new":@@ -2027,13 +2014,6 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {}}- private func drawStatusPill(_ text: String, rect: CGRect, color: UIColor, font: UIFont) {- let path = UIBezierPath(roundedRect: rect, cornerRadius: rect.height / 2)- color.withAlphaComponent(0.12).setFill()- path.fill()- drawCenteredText(text, rect: rect, color: color, font: font)- }-private func drawFileIcon(rect: CGRect, changeType: String?) {let color = fileStatusColor(changeType)let outerPath = UIBezierPath(roundedRect: rect, cornerRadius: 6)diff --git a/apps/mobile/src/features/cloud/linkEnvironment.test.ts b/apps/mobile/src/features/cloud/linkEnvironment.test.tsindex feadf6c8189..8fa346c5be4 100644--- a/apps/mobile/src/features/cloud/linkEnvironment.test.ts+++ b/apps/mobile/src/features/cloud/linkEnvironment.test.ts@@ -4,20 +4,13 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import { EnvironmentId } from "@t3tools/contracts";import { RelayMobileClientId } from "@t3tools/contracts/relay";-import { DPOP_UNKNOWN_HINT, ManagedRelay } from "@t3tools/client-runtime/relay";+import { ManagedRelay } from "@t3tools/client-runtime/relay";import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";import { HttpClient } from "effect/unstable/http";-import { MobilePreferencesStore } from "../../persistence/mobile-preferences";+import { MobileStorage } from "../../persistence/mobile-storage";-import {- linkEnvironmentToCloud,- linkEnvironmentToCloudWithPreference,- connectCloudEnvironment,- listCloudEnvironments,- listCloudEnvironmentsWithStatus,- refreshCloudEnvironmentConnection,-} from "./linkEnvironment";+import { linkEnvironmentToCloudWithPreference } from "./linkEnvironment";vi.mock("expo-constants", () => ({default: {@@ -56,8 +49,6 @@ vi.mock("expo-secure-store", () => ({setItemAsync: vi.fn(),}));-const loadPreferences = vi.fn(() => Effect.succeed({}));-const savedConnection = {environmentId: EnvironmentId.make("env-1"),environmentLabel: "Desktop",@@ -68,8 +59,6 @@ const savedConnection = {bearerToken: "local-bearer",};-const stableClerkToken = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ1c2VyXzEyMyJ9.test";-const createProofMock = vi.fn((input: { readonly method: string; readonly url: string; readonly accessToken?: string }) =>Effect.succeed(`dpop:${input.method}:${input.url}`),@@ -86,14 +75,6 @@ function cloudClientLayer() {const httpClientLayer = remoteHttpClientLayer((input, init) => globalThis.fetch(input, init));return Layer.mergeAll(httpClientLayer,- Layer.succeed(- MobilePreferencesStore,- MobilePreferencesStore.of({- load: loadPreferences(),- savePatch: (patch) => Effect.succeed(patch),- update: () => Effect.succeed({}),- }),- ),Layer.succeed(MobileStorage,MobileStorage.of({@@ -123,7 +104,6 @@ const withCloudServices = <A, E>(| HttpClient.HttpClient| ManagedRelay.ManagedRelayClient| ManagedRelay.ManagedRelayDpopSigner- | MobilePreferencesStore| MobileStorage>,) => effect.pipe(Effect.provide(cloudClientLayer()));@@ -163,439 +143,12 @@ function requestBodyText(body: BodyInit | null | undefined): string {return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? "");}-function validDpopAccessTokenResponse(scope = "environment:status environment:connect") {- return {- access_token: "relay-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 300,- scope,- };-}--function listedEnvironment(environmentId: string) {- return {- environmentId: EnvironmentId.make(environmentId),- label: "Desktop",- endpoint: {- httpBaseUrl: `https://${environmentId}.example.test/`,- wsBaseUrl: `wss://${environmentId}.example.test/ws`,- providerKind: "cloudflare_tunnel" as const,- },- linkedAt: "2026-05-25T00:00:00.000Z",- };-}-describe("mobile cloud link environment client", () => {beforeEach(() => {vi.restoreAllMocks();createProofMock.mockClear();- loadPreferences.mockClear();});- it.effect("decodes relay environment list responses before returning records", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn(() =>- Promise.resolve(- Response.json({- environments: [- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ],- }),- ),- ),- );-- const records = yield* withCloudServices(- listCloudEnvironments({ clerkToken: "clerk-token" }),- );- expect(records).toEqual([- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ]);- }),- );-- it.effect("rejects malformed relay environment list responses", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn(() =>- Promise.resolve(- Response.json({- environments: [- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ],- }),- ),- ),- );-- const error = yield* withCloudServices(- listCloudEnvironments({ clerkToken: "clerk-token" }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: "https://relay.example.test/v1/environments failed",- });- }),- );-- it.effect("loads signed status for each advertised cloud environment", () =>- Effect.gen(function* () {- const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => {- if (String(url) === "https://relay.example.test/v1/environments") {- return Promise.resolve(- Response.json({- environments: [- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ],- }),- );- }- if (String(url) === "https://relay.example.test/v1/client/dpop-token") {- return Promise.resolve(Response.json(validDpopAccessTokenResponse()));- }- expect(String(url)).toBe("https://relay.example.test/v1/environments/env-1/status");- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- status: "online",- checkedAt: "2026-05-25T00:01:00.000Z",- descriptor: {- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- });- vi.stubGlobal("fetch", fetchMock);-- const records = yield* withCloudServices(- listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }),- );- expect(records).toMatchObject([- {- environment: {- environmentId: "env-1",- label: "Desktop",- },- status: {- environmentId: "env-1",- status: "online",- checkedAt: "2026-05-25T00:01:00.000Z",- },- statusError: null,- },- ]);- expect(String(fetchMock.mock.calls[2]?.[0])).toBe(- "https://relay.example.test/v1/environments/env-1/status",- );- expect(fetchMock.mock.calls[2]?.[1]?.method).toBe("POST");- const statusHeaders = new Headers(fetchMock.mock.calls[2]?.[1]?.headers);- expect(statusHeaders.get("authorization")).toBe("DPoP relay-dpop-token");- expect(statusHeaders.get("dpop")).toBe(- "dpop:POST:https://relay.example.test/v1/environments/env-1/status",- );- expect(createProofMock).toHaveBeenCalledWith({- method: "POST",- url: "https://relay.example.test/v1/environments/env-1/status",- accessToken: "relay-dpop-token",- });- }),- );-- it.effect("reuses one valid DPoP access token while probing multiple environment statuses", () =>- Effect.gen(function* () {- const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => {- if (String(url).endsWith("/v1/environments")) {- return Promise.resolve(- Response.json({- environments: [listedEnvironment("env-1"), listedEnvironment("env-2")],- }),- );- }- if (String(url).endsWith("/v1/client/dpop-token")) {- return Promise.resolve(Response.json(validDpopAccessTokenResponse()));- }- const environmentId = String(url).includes("/env-1/") ? "env-1" : "env-2";- return Promise.resolve(- Response.json({- environmentId,- endpoint: listedEnvironment(environmentId).endpoint,- status: "online",- checkedAt: "2026-05-25T00:01:00.000Z",- descriptor: {- environmentId,- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- });- vi.stubGlobal("fetch", fetchMock);-- yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: stableClerkToken }));-- expect(- fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")),- ).toHaveLength(1);- }),- );-- it.effect("reuses the status-and-connect token when connecting from the cloud list", () =>- Effect.gen(function* () {- const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => {- if (String(url).endsWith("/v1/environments")) {- return Promise.resolve(- Response.json({- environments: [listedEnvironment("env-1")],- }),- );- }- if (String(url).endsWith("/v1/client/dpop-token")) {- return Promise.resolve(Response.json(validDpopAccessTokenResponse()));- }- if (String(url).endsWith("/status")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: listedEnvironment("env-1").endpoint,- status: "online",- checkedAt: "2026-05-25T00:01:00.000Z",- descriptor: {- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- }- if (String(url).endsWith("/connect")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: listedEnvironment("env-1").endpoint,- credential: "one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- );- }- if (String(url).endsWith("/.well-known/t3/environment")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- }),- );- }- return Promise.resolve(- Response.json({- access_token: "environment-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 3600,- scope: "orchestration:read orchestration:operate terminal:operate review:write",- }),- );- });- vi.stubGlobal("fetch", fetchMock);-- yield* withCloudServices(- Effect.gen(function* () {- const records = yield* listCloudEnvironmentsWithStatus({- clerkToken: stableClerkToken,- });- yield* connectCloudEnvironment({- clerkToken: stableClerkToken,- environment: records[0]!.environment,- });- }),- );-- expect(- fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")),- ).toHaveLength(1);- const exchangeRequest = fetchMock.mock.calls.find(([url]) =>- String(url).endsWith("/v1/client/dpop-token"),- )?.[1];- expect(new URLSearchParams(requestBodyText(exchangeRequest?.body)).get("scope")).toBe(- "environment:status environment:connect",- );- const environmentTokenRequest = fetchMock.mock.calls.find(([url]) =>- String(url).endsWith("/oauth/token"),- )?.[1];- const environmentTokenBody = new URLSearchParams(- requestBodyText(environmentTokenRequest?.body),- );- expect(environmentTokenBody.get("client_label")).toBe("T3 Code Mobile");- expect(environmentTokenBody.get("client_device_type")).toBe("mobile");- expect(environmentTokenBody.get("client_os")).toBe("iOS");- }),- );-- it.effect("keeps advertised environments visible when status probing fails", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) => {- if (String(url) === "https://relay.example.test/v1/environments") {- return Promise.resolve(- Response.json({- environments: [- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ],- }),- );- }- if (String(url) === "https://relay.example.test/v1/client/dpop-token") {- return Promise.resolve(Response.json(validDpopAccessTokenResponse()));- }- return Promise.resolve(Response.json({ error: "offline" }, { status: 503 }));- }),- );-- const records = yield* withCloudServices(- listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }),- );- expect(records).toMatchObject([- {- environment: {- environmentId: "env-1",- label: "Desktop",- },- status: null,- statusError: "https://relay.example.test/v1/environments/env-1/status failed",- },- ]);- }),- );-- it.effect("rejects status responses for a different advertised environment", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) => {- if (String(url) === "https://relay.example.test/v1/environments") {- return Promise.resolve(- Response.json({- environments: [- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ],- }),- );- }- if (String(url) === "https://relay.example.test/v1/client/dpop-token") {- return Promise.resolve(Response.json(validDpopAccessTokenResponse()));- }- return Promise.resolve(- Response.json({- environmentId: "env-other",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- status: "online",- checkedAt: "2026-05-25T00:01:00.000Z",- descriptor: {- environmentId: "env-other",- label: "Other Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- }),- );-- const records = yield* withCloudServices(- listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }),- );- expect(records).toMatchObject([- {- environment: {- environmentId: "env-1",- label: "Desktop",- },- status: null,- statusError: "Relay returned status for a different environment.",- },- ]);- }),- );-it.effect("rejects relay link credentials for a different environment before persisting relay config",() =>@@ -612,9 +165,10 @@ describe("mobile cloud link environment client", () => {vi.stubGlobal("fetch", fetchMock);const error = yield* withCloudServices(- linkEnvironmentToCloud({+ linkEnvironmentToCloudWithPreference({clerkToken: "clerk-token",connection: savedConnection,+ liveActivitiesEnabled: true,}),).pipe(Effect.flip);expect(error).toMatchObject({@@ -644,9 +198,10 @@ describe("mobile cloud link environment client", () => {vi.stubGlobal("fetch", fetchMock);const error = yield* withCloudServices(- linkEnvironmentToCloud({+ linkEnvironmentToCloudWithPreference({clerkToken: "clerk-token",connection: savedConnection,+ liveActivitiesEnabled: true,}),).pipe(Effect.flip);expect(error._tag).toBe("CloudEnvironmentLinkError");@@ -681,9 +236,10 @@ describe("mobile cloud link environment client", () => {vi.stubGlobal("fetch", fetchMock);const error = yield* withCloudServices(- linkEnvironmentToCloud({+ linkEnvironmentToCloudWithPreference({clerkToken: "clerk-token",connection: savedConnection,+ liveActivitiesEnabled: true,}),).pipe(Effect.flip);expect(error).toMatchObject({@@ -718,9 +274,10 @@ describe("mobile cloud link environment client", () => {vi.stubGlobal("fetch", fetchMock);const error = yield* withCloudServices(- linkEnvironmentToCloud({+ linkEnvironmentToCloudWithPreference({clerkToken: "clerk-token",connection: savedConnection,+ liveActivitiesEnabled: true,}),).pipe(Effect.flip);expect(error).toMatchObject({@@ -733,7 +290,6 @@ describe("mobile cloud link environment client", () => {it.effect("preserves disabled Live Activity preferences when linking an environment", () =>Effect.gen(function* () {- loadPreferences.mockReturnValueOnce(Effect.succeed({ liveActivitiesEnabled: false }));const bodies: Array<unknown> = [];const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {if (init?.body) {@@ -756,9 +312,10 @@ describe("mobile cloud link environment client", () => {vi.stubGlobal("fetch", fetchMock);yield* withCloudServices(- linkEnvironmentToCloud({+ linkEnvironmentToCloudWithPreference({clerkToken: "clerk-token",connection: savedConnection,+ liveActivitiesEnabled: false,}),);@@ -786,9 +343,8 @@ describe("mobile cloud link environment client", () => {}),);- it.effect("uses an explicit Live Activity preference when persisted state is unavailable", () =>+ it.effect("enables Live Activities for both the link challenge and registration", () =>Effect.gen(function* () {- loadPreferences.mockReturnValueOnce(Effect.die("persisted preferences must not be read"));const bodies: Array<Record<string, unknown>> = [];const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {if (init?.body) {@@ -824,429 +380,4 @@ describe("mobile cloud link environment client", () => {]);}),);-- it.effect(- "does not persist cloud connect bootstrap credentials in saved connection records",- () =>- Effect.gen(function* () {- let connectRequestBody = "";- const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {- if (String(url).endsWith("/v1/client/dpop-token")) {- return Promise.resolve(- Response.json(validDpopAccessTokenResponse("environment:connect")),- );- }- if (String(url).endsWith("/.well-known/t3/environment")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- }),- );- }- if (String(url).endsWith("/oauth/token")) {- return Promise.resolve(- Response.json({- access_token: "environment-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 3600,- scope: "orchestration:read orchestration:operate terminal:operate review:write",- }),- );- }- connectRequestBody = requestBodyText(init?.body);- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- credential: "one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- );- });- vi.stubGlobal("fetch", fetchMock);-- const connection = yield* withCloudServices(- connectCloudEnvironment({- clerkToken: "clerk-token",- environment: {- environmentId: EnvironmentId.make("env-1"),- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- }),- );-- expect(connection.pairingUrl).toBe("https://desktop.example.test/");- expect(connection.pairingUrl).not.toContain("one-time-cloud-credential");- expect(connection.bearerToken).toBeNull();- expect(connection.authenticationMethod).toBe("dpop");- expect(connection.dpopAccessToken).toBe("environment-dpop-token");- expect(connection.relayManaged).toBe(true);- // @effect-diagnostics-next-line preferSchemaOverJson:off- expect(JSON.parse(connectRequestBody)).toMatchObject({- deviceId: "device-1",- clientKeyThumbprint: "client-proof-key-thumbprint",- });- expect(createProofMock).toHaveBeenCalledWith({- method: "POST",- url: "https://relay.example.test/v1/environments/env-1/connect",- accessToken: "relay-dpop-token",- });- expect(createProofMock).toHaveBeenCalledWith({- method: "POST",- url: "https://desktop.example.test/oauth/token",- });- }),- );-- it.effect("refreshes a saved environment against a rotated managed endpoint", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) => {- if (String(url).endsWith("/v1/client/dpop-token")) {- return Promise.resolve(- Response.json(validDpopAccessTokenResponse("environment:connect")),- );- }- if (String(url).endsWith("/.well-known/t3/environment")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- label: "Rotated Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- }),- );- }- if (String(url).endsWith("/oauth/token")) {- return Promise.resolve(- Response.json({- access_token: "fresh-environment-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 3600,- scope: "orchestration:read orchestration:operate terminal:operate review:write",- }),- );- }- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://rotated-desktop.example.test/",- wsBaseUrl: "wss://rotated-desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- credential: "rotated-one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- );- }),- );-- const connection = yield* withCloudServices(- refreshCloudEnvironmentConnection({- clerkToken: "clerk-token",- connection: {- environmentId: EnvironmentId.make("env-1"),- environmentLabel: "Desktop",- pairingUrl: "https://desktop.example.test/",- displayUrl: "https://desktop.example.test/",- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- bearerToken: null,- authenticationMethod: "dpop",- relayManaged: true,- },- }),- );-- expect(connection).toMatchObject({- environmentId: "env-1",- environmentLabel: "Rotated Desktop",- displayUrl: "https://rotated-desktop.example.test/",- httpBaseUrl: "https://rotated-desktop.example.test/",- wsBaseUrl: "wss://rotated-desktop.example.test/ws",- dpopAccessToken: "fresh-environment-dpop-token",- });- }),- );-- it.effect("rejects relay connect responses for a different environment", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) =>- Promise.resolve(- String(url).endsWith("/v1/client/dpop-token")- ? Response.json(validDpopAccessTokenResponse("environment:connect"))- : Response.json({- environmentId: "env-other",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- credential: "one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- ),- ),- );-- const error = yield* withCloudServices(- connectCloudEnvironment({- clerkToken: "clerk-token",- environment: {- environmentId: EnvironmentId.make("env-1"),- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: "Relay returned credentials for a different environment.",- });- }),- );-- it.effect("preserves relay DPoP auth failures while connecting environments", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) =>- Promise.resolve(- String(url).endsWith("/v1/client/dpop-token")- ? Response.json(validDpopAccessTokenResponse("environment:connect"))- : Response.json(- {- _tag: "RelayAuthInvalidError",- code: "auth_invalid",- reason: "invalid_dpop",- traceId: "trace-connect",- },- { status: 401 },- ),- ),- ),- );-- const error = yield* withCloudServices(- connectCloudEnvironment({- clerkToken: "clerk-token",- environment: {- environmentId: EnvironmentId.make("env-1"),- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: `https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof. ${DPOP_UNKNOWN_HINT}`,- traceId: "trace-connect",- });- }),- );-- it.effect(- "presents clock skew as one possible cause when an older environment rejects DPoP",- () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) => {- const value = String(url);- if (value.endsWith("/v1/client/dpop-token")) {- return Promise.resolve(- Response.json(validDpopAccessTokenResponse("environment:connect")),- );- }- if (value.endsWith("/v1/environments/env-1/connect")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- credential: "one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- );- }- if (value.endsWith("/.well-known/t3/environment")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- }),- );- }- return Promise.resolve(- Response.json(- {- _tag: "EnvironmentAuthInvalidError",- code: "auth_invalid",- reason: "invalid_credential",- traceId: "trace-environment",- },- { status: 401 },- ),- );- }),- );-- const error = yield* withCloudServices(- connectCloudEnvironment({- clerkToken: "clerk-token",- environment: {- environmentId: EnvironmentId.make("env-1"),- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- }),- ).pipe(Effect.flip);-- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: `Could not exchange a managed endpoint DPoP access token. ${DPOP_UNKNOWN_HINT}`,- traceId: "trace-environment",- });- }),- );-- it.effect("rejects relay connect responses for a different endpoint", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) =>- Promise.resolve(- String(url).endsWith("/v1/client/dpop-token")- ? Response.json(validDpopAccessTokenResponse("environment:connect"))- : Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://other-desktop.example.test/",- wsBaseUrl: "wss://other-desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- credential: "one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- ),- ),- );-- const error = yield* withCloudServices(- connectCloudEnvironment({- clerkToken: "clerk-token",- environment: {- environmentId: EnvironmentId.make("env-1"),- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: "Relay returned credentials for a different endpoint.",- });- }),- );-- it.effect(- "rejects managed endpoints whose descriptor does not match the selected environment",- () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) =>- Promise.resolve(- String(url).endsWith("/v1/client/dpop-token")- ? Response.json(validDpopAccessTokenResponse("environment:connect"))- : String(url).endsWith("/.well-known/t3/environment")- ? Response.json({- environmentId: "env-other",- label: "Other Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- })- : Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- credential: "one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- ),- ),- );-- const error = yield* withCloudServices(- connectCloudEnvironment({- clerkToken: "clerk-token",- environment: {- environmentId: EnvironmentId.make("env-1"),- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: "Connected endpoint descriptor does not match the selected environment.",- });- }),- );});diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.tsindex b8dc8f878e0..73bd28c550e 100644--- a/apps/mobile/src/features/cloud/linkEnvironment.ts+++ b/apps/mobile/src/features/cloud/linkEnvironment.ts@@ -4,45 +4,24 @@ import * as Schema from "effect/Schema";import { HttpClient } from "effect/unstable/http";import {EnvironmentCloudEndpointUnavailableError,- EnvironmentAuthInvalidError,EnvironmentHttpBadRequestError,EnvironmentHttpConflictError,EnvironmentHttpForbiddenError,EnvironmentHttpInternalServerError,EnvironmentHttpUnauthorizedError,} from "@t3tools/contracts";-import { stripPairingTokenFromUrl } from "@t3tools/shared/remote";import {- type RelayEnvironmentConnectResponse as RelayEnvironmentConnectResponseType,type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType,- RelayEnvironmentConnectScope,- RelayEnvironmentStatusScope,- type RelayDpopAccessTokenScope,- type RelayClientEnvironmentRecord,- type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,type RelayManagedEndpointProviderKind,} from "@t3tools/contracts/relay";-import { exchangeRemoteDpopAccessToken } from "@t3tools/client-runtime/authorization";-import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";import { findErrorTraceId } from "@t3tools/client-runtime/errors";-import {- dpopFailureMessage,- ManagedRelay,- relayProtectedErrorMessage,-} from "@t3tools/client-runtime/relay";+import { ManagedRelay, relayProtectedErrorMessage } from "@t3tools/client-runtime/relay";import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";-import { authClientMetadata } from "../../lib/authClientMetadata";import type { SavedRemoteConnection } from "../../lib/connection";-import * as MobilePreferences from "../../persistence/mobile-preferences";import * as MobileStorage from "../../persistence/mobile-storage";import { resolveCloudPublicConfig } from "./publicConfig";-const RELAY_STATUS_AND_CONNECT_SCOPES = [- RelayEnvironmentStatusScope,- RelayEnvironmentConnectScope,-] satisfies ReadonlyArray<RelayDpopAccessTokenScope>;-function readRelayUrl(): string | null {return resolveCloudPublicConfig().relay.url;}@@ -53,12 +32,6 @@ export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmenreadonly traceId?: string;}> {}-export interface CloudEnvironmentRecordWithStatus {- readonly environment: RelayClientEnvironmentRecord;- readonly status: RelayEnvironmentStatusResponseType | null;- readonly statusError: string | null;-}-const isEnvironmentCloudApiError = Schema.is(Schema.Union([EnvironmentHttpBadRequestError,@@ -69,24 +42,19 @@ const isEnvironmentCloudApiError = Schema.is(EnvironmentCloudEndpointUnavailableError,]),);-const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);const MANAGED_ENDPOINT_PROVIDER_KIND ="cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;-function cloudEnvironmentLinkError(message: string, options?: { readonly dpop?: boolean }) {+function cloudEnvironmentLinkError(message: string) {return (cause: unknown) => {const environmentError = findEnvironmentCloudApiError(cause);const traceId = findErrorTraceId(cause);- const dpopAuthError = options?.dpop ? findEnvironmentAuthInvalidError(cause) : null;const detail = environmentError? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`: withDevCause(message, cause);return new CloudEnvironmentLinkError({- message:- dpopAuthError?.reason === "invalid_credential"- ? dpopFailureMessage(detail, dpopAuthError.dpopFailureReason)- : detail,+ message: detail,cause,...(traceId === null ? {} : { traceId }),});@@ -143,16 +111,6 @@ function findEnvironmentCloudApiError(cause: unknown): { readonly message: strinreturn "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;}-function findEnvironmentAuthInvalidError(cause: unknown): EnvironmentAuthInvalidError | null {- if (isEnvironmentAuthInvalidError(cause)) {- return cause;- }- if (typeof cause !== "object" || cause === null) {- return null;- }- return "cause" in cause ? findEnvironmentAuthInvalidError(cause.cause) : null;-}-function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> {const relayUrl = readRelayUrl();return relayUrl@@ -186,54 +144,6 @@ function ensureLinkedEnvironmentMatches(input: {return Effect.void;}-function endpointMatches(- left: RelayClientEnvironmentRecord["endpoint"],- right: RelayClientEnvironmentRecord["endpoint"],-): boolean {- return (- left.httpBaseUrl === right.httpBaseUrl &&- left.wsBaseUrl === right.wsBaseUrl &&- left.providerKind === right.providerKind- );-}--function ensureStatusMatchesEnvironment(input: {- readonly environment: RelayClientEnvironmentRecord;- readonly status: RelayEnvironmentStatusResponseType;-}): Effect.Effect<void, CloudEnvironmentLinkError> {- if (input.status.environmentId !== input.environment.environmentId) {- return new CloudEnvironmentLinkError({- message: "Relay returned status for a different environment.",- });- }- if (!endpointMatches(input.status.endpoint, input.environment.endpoint)) {- return new CloudEnvironmentLinkError({- message: "Relay returned status for a different endpoint.",- });- }- if (- input.status.descriptor &&- input.status.descriptor.environmentId !== input.environment.environmentId- ) {- return new CloudEnvironmentLinkError({- message: "Relay returned status descriptor for a different environment.",- });- }- return Effect.void;-}--function ensureConnectEndpointMatchesEnvironment(input: {- readonly environment: RelayClientEnvironmentRecord;- readonly connect: RelayEnvironmentConnectResponseType;-}): Effect.Effect<void, CloudEnvironmentLinkError> {- if (!endpointMatches(input.connect.endpoint, input.environment.endpoint)) {- return new CloudEnvironmentLinkError({- message: "Relay returned credentials for a different endpoint.",- });- }- return Effect.void;-}-interface LinkEnvironmentToCloudInput {readonly connection: SavedRemoteConnection;readonly clerkToken: string;@@ -328,250 +238,3 @@ export function linkEnvironmentToCloudWithPreference();});}--export function linkEnvironmentToCloud(- input: LinkEnvironmentToCloudInput,-): Effect.Effect<- void,- CloudEnvironmentLinkError,- LinkEnvironmentToCloudRequirements | MobilePreferences.MobilePreferencesStore-> {- return MobilePreferences.MobilePreferencesStore.pipe(- Effect.flatMap((preferencesStore) => preferencesStore.load),- Effect.mapError(cloudEnvironmentLinkError("Could not load mobile notification preferences.")),- Effect.flatMap((preferences) =>- linkEnvironmentToCloudWithPreference({- ...input,- liveActivitiesEnabled: preferences.liveActivitiesEnabled !== false,- }),- ),- );-}--export function listCloudEnvironments(input: {- readonly clerkToken: string;-}): Effect.Effect<- ReadonlyArray<RelayClientEnvironmentRecord>,- CloudEnvironmentLinkError,- ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- const relayUrl = yield* requireRelayUrl();- const relayClient = yield* ManagedRelay.ManagedRelayClient;-- return yield* relayClient- .listEnvironments({- clerkToken: input.clerkToken,- })- .pipe(Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/environments failed`)));- });-}--export function getCloudEnvironmentStatus(input: {- readonly clerkToken: string;- readonly environment: RelayClientEnvironmentRecord;- readonly relayScopes?: ReadonlyArray<RelayDpopAccessTokenScope>;-}): Effect.Effect<- RelayEnvironmentStatusResponseType,- CloudEnvironmentLinkError,- ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- const relayUrl = yield* requireRelayUrl();- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const status = yield* relayClient- .getEnvironmentStatus({- clerkToken: input.clerkToken,- scopes: input.relayScopes ?? [RelayEnvironmentStatusScope],- environmentId: input.environment.environmentId,- })- .pipe(- Effect.mapError(- decodedRelayClientError(- `${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/status failed`,- ),- ),- );- yield* ensureStatusMatchesEnvironment({ environment: input.environment, status });- return status;- });-}--export function loadCloudEnvironmentStatuses(input: {- readonly clerkToken: string;- readonly environments: ReadonlyArray<RelayClientEnvironmentRecord>;-}): Effect.Effect<- ReadonlyArray<CloudEnvironmentRecordWithStatus>,- CloudEnvironmentLinkError,- ManagedRelay.ManagedRelayClient-> {- return Effect.forEach(- input.environments,- (environment) =>- getCloudEnvironmentStatus({- clerkToken: input.clerkToken,- environment,- relayScopes: RELAY_STATUS_AND_CONNECT_SCOPES,- }).pipe(- Effect.match({- onFailure: (error) => ({- environment,- status: null,- statusError: error.message,- }),- onSuccess: (status) => ({- environment,- status,- statusError: null,- }),- }),- ),- { concurrency: "unbounded" },- );-}--export function listCloudEnvironmentsWithStatus(input: {- readonly clerkToken: string;-}): Effect.Effect<- ReadonlyArray<CloudEnvironmentRecordWithStatus>,- CloudEnvironmentLinkError,- ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- const environments = yield* listCloudEnvironments(input);- return yield* loadCloudEnvironmentStatuses({- clerkToken: input.clerkToken,- environments,- });- });-}--const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(- function* () {- const storage = yield* MobileStorage.MobileStorage;- return yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(- Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),- );- },-);--const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManagedEnvironment")(- function* (input: {- readonly clerkToken: string;- readonly environmentId: RelayClientEnvironmentRecord["environmentId"];- readonly expectedEnvironment?: RelayClientEnvironmentRecord;- }) {- yield* Effect.annotateCurrentSpan({ "environment.id": input.environmentId });- const relayUrl = yield* requireRelayUrl();- const relayClient = yield* ManagedRelay.ManagedRelayClient;-- const deviceId = yield* loadAgentAwarenessDeviceId();- const connect = yield* relayClient- .connectEnvironment({- clerkToken: input.clerkToken,- scopes: [RelayEnvironmentConnectScope],- environmentId: input.environmentId,- deviceId,- })- .pipe(- Effect.mapError(- decodedRelayClientError(- `${relayUrl}/v1/environments/${encodeURIComponent(input.environmentId)}/connect failed`,- ),- ),- );- if (connect.environmentId !== input.environmentId) {- return yield* new CloudEnvironmentLinkError({- message: "Relay returned credentials for a different environment.",- });- }- if (input.expectedEnvironment) {- yield* ensureConnectEndpointMatchesEnvironment({- environment: input.expectedEnvironment,- connect,- });- }-- const descriptor = yield* fetchRemoteEnvironmentDescriptor({- httpBaseUrl: connect.endpoint.httpBaseUrl,- }).pipe(- Effect.mapError(- cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),- ),- );- if (descriptor.environmentId !== connect.environmentId) {- return yield* new CloudEnvironmentLinkError({- message: "Connected endpoint descriptor does not match the selected environment.",- });- }- const signer = yield* ManagedRelay.ManagedRelayDpopSigner;- const bootstrapDpop = yield* signer- .createProof({- method: "POST",- url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),- })- .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));- const bootstrap = yield* exchangeRemoteDpopAccessToken({- httpBaseUrl: connect.endpoint.httpBaseUrl,- credential: connect.credential,- dpopProof: bootstrapDpop,- clientMetadata: authClientMetadata(),- }).pipe(- Effect.mapError(- cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token.", {- dpop: true,- }),- ),- );- const pairingUrl = new URL(connect.endpoint.httpBaseUrl);- pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();-- return {- environmentId: descriptor.environmentId,- environmentLabel: descriptor.label,- pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),- displayUrl: connect.endpoint.httpBaseUrl,- httpBaseUrl: connect.endpoint.httpBaseUrl,- wsBaseUrl: connect.endpoint.wsBaseUrl,- bearerToken: null,- authenticationMethod: "dpop",- dpopAccessToken: bootstrap.access_token,- relayManaged: true,- } satisfies SavedRemoteConnection;- },-);--export function connectCloudEnvironment(input: {- readonly clerkToken: string;- readonly environment: RelayClientEnvironmentRecord;-}): Effect.Effect<- SavedRemoteConnection,- CloudEnvironmentLinkError,- | HttpClient.HttpClient- | ManagedRelay.ManagedRelayClient- | ManagedRelay.ManagedRelayDpopSigner- | MobileStorage.MobileStorage-> {- return connectRelayManagedEnvironment({- clerkToken: input.clerkToken,- environmentId: input.environment.environmentId,- expectedEnvironment: input.environment,- });-}--export function refreshCloudEnvironmentConnection(input: {- readonly clerkToken: string;- readonly connection: SavedRemoteConnection;-}): Effect.Effect<- SavedRemoteConnection,- CloudEnvironmentLinkError,- | HttpClient.HttpClient- | ManagedRelay.ManagedRelayClient- | ManagedRelay.ManagedRelayDpopSigner- | MobileStorage.MobileStorage-> {- return connectRelayManagedEnvironment({- clerkToken: input.clerkToken,- environmentId: input.connection.environmentId,- });-}diff --git a/apps/mobile/src/features/review/reviewPerf.ts b/apps/mobile/src/features/review/reviewPerf.tsindex 2ae1095b1c6..2613ff0c3db 100644--- a/apps/mobile/src/features/review/reviewPerf.ts+++ b/apps/mobile/src/features/review/reviewPerf.ts@@ -42,33 +42,6 @@ export function measureReviewWork<T>(name: string, callback: () => T): T {}}-export async function measureReviewAsyncWork<T>(- name: string,- callback: () => Promise<T>,-): Promise<T> {- if (!isReviewPerfEnabled()) {- return callback();- }-- const perf = getPerformance();- const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;- const startMark = `${marker}.start`;- const endMark = `${marker}.end`;- const startedAt = perf?.now?.() ?? Date.now();-- perf?.mark?.(startMark);- try {- return await callback();- } finally {- const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;- perf?.mark?.(endMark);- perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);- perf?.clearMarks?.(startMark);- perf?.clearMarks?.(endMark);- console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });- }-}-export function markReviewEvent(name: string, details?: Record<string, unknown>): void {if (!isReviewPerfEnabled()) {return;diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.tsindex 52e0b83be34..3050f1f67ee 100644--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts@@ -15,14 +15,12 @@ import * as Schema from "effect/Schema";import {resolveReviewHighlighterEngine,resolveReviewHighlighterEnginePreference,- type ReviewHighlighterEngine,} from "./reviewHighlighterEngine";import { createIncrementalSnippet } from "./incrementalSnippet";import type { ReviewRenderableLineRow } from "./reviewModel";import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";export type ReviewDiffTheme = "light" | "dark";-export type { ReviewHighlighterEngine };export class ReviewHighlighterEngineInitializationError extends Schema.TaggedError<ReviewHighlighterEngineInitializationError>()("ReviewHighlighterEngineInitializationError",@@ -181,7 +179,6 @@ const languageAliases: Record<string, string> = {txt: "text",};let highlighterPromise: Promise<HighlighterCore> | null = null;-let activeHighlighterEnginePromise: Promise<ReviewHighlighterEngine> | null = null;type LoadedLanguageModule = {default: Parameters<HighlighterCore["loadLanguage"]>[0];@@ -254,10 +251,7 @@ async function getHighlighter(): Promise<HighlighterCore> {engine: nativeEngineModule.createNativeEngine(),});logReviewHighlighterDiagnostic("using native engine");- return {- highlighter,- engine: "native" as const,- };+ return highlighter;}} catch (error) {nativeInitializationError = new ReviewHighlighterEngineInitializationError({@@ -308,55 +302,18 @@ async function getHighlighter(): Promise<HighlighterCore> {logReviewHighlighterDiagnostic("using javascript engine", {resolvedEngine: engine,});- return {- highlighter,- engine,- };+ return highlighter;})();- highlighterPromise = configuredHighlighterPromise- .then((result) => result.highlighter)- .catch((error) => {- highlighterPromise = null;- activeHighlighterEnginePromise = null;- throw error;- });- activeHighlighterEnginePromise = configuredHighlighterPromise- .then((result) => result.engine)- .catch((error) => {- activeHighlighterEnginePromise = null;- throw error;- });+ highlighterPromise = configuredHighlighterPromise.catch((error) => {+ highlighterPromise = null;+ throw error;+ });}return highlighterPromise;}-export async function getActiveReviewHighlighterEngine(): Promise<ReviewHighlighterEngine> {- await getHighlighter();- return activeHighlighterEnginePromise ?? Promise.resolve("javascript");-}--export async function prepareReviewHighlighter(): Promise<void> {- await getHighlighter();-}--export async function prepareReviewHighlighterLanguages(- languages: ReadonlyArray<string>,-): Promise<void> {- const highlighter = await getHighlighter();- await Promise.all(- languages.map(async (language) => {- const candidate = resolveLanguageAlias(language);- if (candidate === "text" || !(candidate in languageImports)) {- return;- }-- await loadSingleLanguage(highlighter, candidate);- }),- );-}-function resolveLanguageAlias(language: string): string {const normalized = language.toLowerCase();return languageAliases[normalized] ?? normalized;diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.tsindex ace2b0fc43b..0df54be2f70 100644--- a/apps/server/integration/OrchestrationEngineHarness.integration.ts+++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts@@ -28,11 +28,9 @@ import * as CheckpointStore from "../src/checkpointing/CheckpointStore.ts";import { TextGeneration } from "../src/textGeneration/TextGeneration.ts";import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";-import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts";import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts";import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";-import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";@@ -189,7 +187,6 @@ export interface OrchestrationIntegrationHarness {readonly snapshotQuery: ProjectionSnapshotQuery["Service"];readonly providerService: ProviderService["Service"];readonly checkpointStore: CheckpointStore.CheckpointStore["Service"];- readonly checkpointRepository: ProjectionCheckpointRepository["Service"];readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];readonly waitForThread: (threadId: string,@@ -313,7 +310,6 @@ export const makeOrchestrationIntegrationHarness = (const runtimeServicesLayer = Layer.mergeAll(projectionSnapshotQueryLayer,orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),- ProjectionCheckpointRepositoryLive,ProjectionPendingApprovalRepositoryLive,checkpointStoreLayer,providerLayer,@@ -463,10 +459,6 @@ export const makeOrchestrationIntegrationHarness = (const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>runtime.runPromise(Effect.service(CheckpointStore.CheckpointStore)),).pipe(Effect.orDie);- const checkpointRepository = yield* tryRuntimePromise(- "load ProjectionCheckpointRepository service",- () => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),- ).pipe(Effect.orDie);const pendingApprovalRepository = yield* tryRuntimePromise("load ProjectionPendingApprovalRepository service",() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),@@ -612,7 +604,6 @@ export const makeOrchestrationIntegrationHarness = (snapshotQuery,providerService,checkpointStore,- checkpointRepository,pendingApprovalRepository,waitForThread,waitForDomainEvent,diff --git a/apps/server/integration/orchestrationEngine.integration.test.ts b/apps/server/integration/orchestrationEngine.integration.test.tsindex abe00f16bb8..68b566e2ee4 100644--- a/apps/server/integration/orchestrationEngine.integration.test.ts+++ b/apps/server/integration/orchestrationEngine.integration.test.ts@@ -20,7 +20,6 @@ import {import { assert, it } from "@effect/vitest";import * as Clock from "effect/Clock";import * as Effect from "effect/Effect";-import * as Option from "effect/Option";import * as Schema from "effect/Schema";import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";@@ -247,14 +246,7 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +);assert.equal(thread.checkpoints[0]?.status, "ready");assert.equal(thread.checkpoints[0]?.checkpointTurnCount, 1);-- const checkpointRows = yield* harness.checkpointRepository.listByThreadId({- threadId: THREAD_ID,- });- assert.equal(checkpointRows.length, 1);- assert.equal(checkpointRows[0]?.checkpointTurnCount, 1);- assert.equal(checkpointRows[0]?.status, "ready");- assert.deepEqual(checkpointRows[0]?.files, []);+ assert.deepEqual(thread.checkpoints[0]?.files, []);const ref0 = checkpointRefForThreadTurn(THREAD_ID, 0);const ref1 = checkpointRefForThreadTurn(THREAD_ID, 1);@@ -498,11 +490,8 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>true,);- const checkpointRows = yield* harness.checkpointRepository.listByThreadId({- threadId: THREAD_ID,- });assert.deepEqual(- checkpointRows.map((row) => row.checkpointTurnCount),+ secondTurnThread.checkpoints.map((row) => row.checkpointTurnCount),[1, 2],);@@ -688,14 +677,7 @@ it.live("records failed turn runtime state and checkpoint status as error", () =assert.equal(thread.session?.status, "error");assert.equal(thread.checkpoints[0]?.status, "error");- const checkpointRow = yield* harness.checkpointRepository.getByThreadAndTurnCount({- threadId: THREAD_ID,- checkpointTurnCount: 1,- });- assert.equal(Option.isSome(checkpointRow), true);- if (Option.isSome(checkpointRow)) {- assert.equal(checkpointRow.value.status, "error");- }+ assert.equal(thread.checkpoints[0]?.checkpointTurnCount, 1);assert.equal(gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),true,@@ -878,11 +860,6 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + gitfalse,);assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);-- const checkpointRows = yield* harness.checkpointRepository.listByThreadId({- threadId: THREAD_ID,- });- assert.equal(checkpointRows.length, 1);}),),);diff --git a/apps/server/src/orchestration/Errors.ts b/apps/server/src/orchestration/Errors.tsindex dccb8b4be0f..5e6376072ce 100644--- a/apps/server/src/orchestration/Errors.ts+++ b/apps/server/src/orchestration/Errors.ts@@ -4,30 +4,6 @@ import * as Schema from "effect/Schema";import type { ProjectionRepositoryError } from "../persistence/Errors.ts";-export class OrchestrationCommandJsonParseError extends Schema.TaggedError<OrchestrationCommandJsonParseError>()(- "OrchestrationCommandJsonParseError",- {- detail: Schema.String,- cause: Schema.optional(Schema.Defect()),- },-) {- override get message(): string {- return `Invalid orchestration command JSON: ${this.detail}`;- }-}--export class OrchestrationCommandDecodeError extends Schema.TaggedError<OrchestrationCommandDecodeError>()(- "OrchestrationCommandDecodeError",- {- issue: Schema.String,- cause: Schema.optional(Schema.Defect()),- },-) {- override get message(): string {- return `Invalid orchestration command payload: ${this.issue}`;- }-}-export class OrchestrationCommandInvariantError extends Schema.TaggedError<OrchestrationCommandInvariantError>()("OrchestrationCommandInvariantError",{@@ -100,31 +76,12 @@ export class OrchestrationProjectorDecodeError extends Schema.TaggedError<Orches}}-export class OrchestrationListenerCallbackError extends Schema.TaggedError<OrchestrationListenerCallbackError>()(- "OrchestrationListenerCallbackError",- {- listener: Schema.Literals(["read-model", "domain-event"]),- detail: Schema.String,- cause: Schema.optional(Schema.Defect()),- },-) {- override get message(): string {- return `Orchestration ${this.listener} listener failed: ${this.detail}`;- }-}-export type OrchestrationDispatchError =| ProjectionRepositoryError| OrchestrationCommandRejection| OrchestrationCommandIdConflictError| OrchestrationCommandPreviouslyRejectedError- | OrchestrationProjectorDecodeError- | OrchestrationListenerCallbackError;--export type OrchestrationEngineError =- | OrchestrationDispatchError- | OrchestrationCommandJsonParseError- | OrchestrationCommandDecodeError;+ | OrchestrationProjectorDecodeError;export function toProjectorDecodeError(eventType: string) {return (error: Schema.SchemaError): OrchestrationProjectorDecodeError =>diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.tsindex 03bf1732928..1e7058742e2 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts@@ -8,6 +8,7 @@ import {MessageId,NonNegativeInt,OrchestrationCheckpointFile,+ OrchestrationCheckpointStatus,OrchestrationProposedPlanId,OrchestrationReadModel,OrchestrationThreadSearchSource,@@ -52,7 +53,6 @@ import {toPersistenceSqlError,type ProjectionRepositoryError,} from "../../persistence/Errors.ts";-import { ProjectionCheckpoint } from "../../persistence/Services/ProjectionCheckpoints.ts";import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";import { ThreadPlanProgressService } from "../ThreadPlanProgress.ts";import { ProjectionProject } from "../../persistence/Services/ProjectionProjects.ts";@@ -151,11 +151,16 @@ const ProjectionThreadRuntimeContextDbRowSchema = Schema.Struct({title: Schema.String,session: Schema.NullOr(ProjectionThreadSessionDbRowSchema),});-const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(- Struct.assign({- files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),- }),-);+const ProjectionCheckpointDbRowSchema = Schema.Struct({+ threadId: ThreadId,+ turnId: TurnId,+ checkpointTurnCount: NonNegativeInt,+ checkpointRef: CheckpointRef,+ status: OrchestrationCheckpointStatus,+ files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),+ assistantMessageId: Schema.NullOr(MessageId),+ completedAt: IsoDateTime,+});const ProjectionLatestTurnDbRowSchema = Schema.Struct({threadId: ProjectionThread.fields.threadId,turnId: TurnId,diff --git a/apps/server/src/persistence/Errors.test.ts b/apps/server/src/persistence/Errors.test.tsindex dfa35020df3..5b9d37b3a65 100644--- a/apps/server/src/persistence/Errors.test.ts+++ b/apps/server/src/persistence/Errors.test.ts@@ -42,7 +42,7 @@ it.effect("names a real SQLite condition without copying query data", () =>assert.equal(error.cause, cause);assert.notInclude(error.message, payload);assert.notInclude(error.message, "private_column");- }).pipe(Effect.provide(NodeSqliteClient.layerMemory())),+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),);it("reads the condition through a wrapping driver error", () => {diff --git a/apps/server/src/persistence/Errors.ts b/apps/server/src/persistence/Errors.tsindex 4625b368d8f..1e3c9027879 100644--- a/apps/server/src/persistence/Errors.ts+++ b/apps/server/src/persistence/Errors.ts@@ -124,42 +124,8 @@ export function toPersistenceDecodeError(operation: string) {export const isPersistenceError = (u: unknown) =>isPersistenceSqlError(u) || isPersistenceDecodeError(u);-// ===============================-// Provider Session Repository Errors-// ===============================--export class ProviderSessionRepositoryValidationError extends Schema.TaggedError<ProviderSessionRepositoryValidationError>()(- "ProviderSessionRepositoryValidationError",- {- operation: Schema.String,- issue: Schema.String,- cause: Schema.optional(Schema.Defect()),- },-) {- override get message(): string {- return `Provider session repository validation failed in ${this.operation}: ${this.issue}`;- }-}--export class ProviderSessionRepositoryPersistenceError extends Schema.TaggedError<ProviderSessionRepositoryPersistenceError>()(- "ProviderSessionRepositoryPersistenceError",- {- operation: Schema.String,- detail: Schema.String,- cause: Schema.optional(Schema.Defect()),- },-) {- override get message(): string {- return `Provider session repository persistence error in ${this.operation}: ${this.detail}`;- }-}-export type OrchestrationEventStoreError = PersistenceSqlError | PersistenceDecodeError;-export type ProviderSessionRepositoryError =- | ProviderSessionRepositoryValidationError- | ProviderSessionRepositoryPersistenceError;-export type OrchestrationCommandReceiptRepositoryError =| PersistenceSqlError| PersistenceDecodeError;diff --git a/apps/server/src/persistence/Layers/ProjectionCheckpoints.ts b/apps/server/src/persistence/Layers/ProjectionCheckpoints.tsdeleted file mode 100644index cfa5658d0e9..00000000000--- a/apps/server/src/persistence/Layers/ProjectionCheckpoints.ts+++ /dev/null@@ -1,217 +0,0 @@-import { OrchestrationCheckpointFile } from "@t3tools/contracts";-import * as SqlClient from "effect/unstable/sql/SqlClient";-import * as SqlSchema from "effect/unstable/sql/SqlSchema";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";-import * as Struct from "effect/Struct";--import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";-import {- DeleteByThreadIdInput,- GetByThreadAndTurnCountInput,- ListByThreadIdInput,- ProjectionCheckpoint,- ProjectionCheckpointRepository,- type ProjectionCheckpointRepositoryShape,-} from "../Services/ProjectionCheckpoints.ts";--const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(- Struct.assign({- files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),- }),-);--function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {- return (cause: unknown) =>- Schema.isSchemaError(cause)- ? toPersistenceDecodeError(decodeOperation)(cause)- : toPersistenceSqlError(sqlOperation)(cause);-}--const makeProjectionCheckpointRepository = Effect.gen(function* () {- const sql = yield* SqlClient.SqlClient;-- const clearCheckpointConflict = SqlSchema.void({- Request: GetByThreadAndTurnCountInput,- execute: ({ threadId, checkpointTurnCount }) =>- sql`- UPDATE projection_turns- SET- checkpoint_turn_count = NULL,- checkpoint_ref = NULL,- checkpoint_status = NULL,- checkpoint_files_json = '[]'- WHERE thread_id = ${threadId}- AND checkpoint_turn_count = ${checkpointTurnCount}- `,- });-- const upsertProjectionCheckpointRow = SqlSchema.void({- Request: ProjectionCheckpointDbRowSchema,- execute: (row) =>- sql`- INSERT INTO projection_turns (- thread_id,- turn_id,- pending_message_id,- assistant_message_id,- state,- requested_at,- started_at,- completed_at,- checkpoint_turn_count,- checkpoint_ref,- checkpoint_status,- checkpoint_files_json- )- VALUES (- ${row.threadId},- ${row.turnId},- NULL,- ${row.assistantMessageId},- ${row.status === "error" ? "error" : "completed"},- ${row.completedAt},- ${row.completedAt},- ${row.completedAt},- ${row.checkpointTurnCount},- ${row.checkpointRef},- ${row.status},- ${row.files}- )- ON CONFLICT (thread_id, turn_id)- DO UPDATE SET- assistant_message_id = excluded.assistant_message_id,- state = excluded.state,- completed_at = excluded.completed_at,- checkpoint_turn_count = excluded.checkpoint_turn_count,- checkpoint_ref = excluded.checkpoint_ref,- checkpoint_status = excluded.checkpoint_status,- checkpoint_files_json = excluded.checkpoint_files_json- `,- });-- const listProjectionCheckpointRows = SqlSchema.findAll({- Request: ListByThreadIdInput,- Result: ProjectionCheckpointDbRowSchema,- execute: ({ threadId }) =>- sql`- SELECT- thread_id AS "threadId",- turn_id AS "turnId",- checkpoint_turn_count AS "checkpointTurnCount",- checkpoint_ref AS "checkpointRef",- checkpoint_status AS "status",- checkpoint_files_json AS "files",- assistant_message_id AS "assistantMessageId",- completed_at AS "completedAt"- FROM projection_turns- WHERE thread_id = ${threadId}- AND checkpoint_turn_count IS NOT NULL- ORDER BY checkpoint_turn_count ASC- `,- });-- const getProjectionCheckpointRow = SqlSchema.findOneOption({- Request: GetByThreadAndTurnCountInput,- Result: ProjectionCheckpointDbRowSchema,- execute: ({ threadId, checkpointTurnCount }) =>- sql`- SELECT- thread_id AS "threadId",- turn_id AS "turnId",- checkpoint_turn_count AS "checkpointTurnCount",- checkpoint_ref AS "checkpointRef",- checkpoint_status AS "status",- checkpoint_files_json AS "files",- assistant_message_id AS "assistantMessageId",- completed_at AS "completedAt"- FROM projection_turns- WHERE thread_id = ${threadId}- AND checkpoint_turn_count = ${checkpointTurnCount}- `,- });-- const deleteProjectionCheckpointRows = SqlSchema.void({- Request: DeleteByThreadIdInput,- execute: ({ threadId }) =>- sql`- UPDATE projection_turns- SET- checkpoint_turn_count = NULL,- checkpoint_ref = NULL,- checkpoint_status = NULL,- checkpoint_files_json = '[]'- WHERE thread_id = ${threadId}- AND checkpoint_turn_count IS NOT NULL- `,- });-- const upsertCheckpointRow = (row: Schema.Schema.Type<typeof ProjectionCheckpointDbRowSchema>) =>- sql.withTransaction(- clearCheckpointConflict({- threadId: row.threadId,- checkpointTurnCount: row.checkpointTurnCount,- }).pipe(Effect.flatMap(() => upsertProjectionCheckpointRow(row))),- );-- const upsert: ProjectionCheckpointRepositoryShape["upsert"] = (row) =>- upsertCheckpointRow(row).pipe(- Effect.mapError(- toPersistenceSqlOrDecodeError(- "ProjectionCheckpointRepository.upsert:query",- "ProjectionCheckpointRepository.upsert:encodeRequest",- ),- ),- );-- const listByThreadId: ProjectionCheckpointRepositoryShape["listByThreadId"] = (input) =>- listProjectionCheckpointRows(input).pipe(- Effect.mapError(- toPersistenceSqlOrDecodeError(- "ProjectionCheckpointRepository.listByThreadId:query",- "ProjectionCheckpointRepository.listByThreadId:decodeRows",- ),- ),- Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionCheckpoint>>),- );-- const getByThreadAndTurnCount: ProjectionCheckpointRepositoryShape["getByThreadAndTurnCount"] = (- input,- ) =>- getProjectionCheckpointRow(input).pipe(- Effect.mapError(- toPersistenceSqlOrDecodeError(- "ProjectionCheckpointRepository.getByThreadAndTurnCount:query",- "ProjectionCheckpointRepository.getByThreadAndTurnCount:decodeRow",- ),- ),- Effect.flatMap((rowOption) =>- Option.match(rowOption, {- onNone: () => Effect.succeed(Option.none()),- onSome: (row) =>- Effect.succeed(Option.some(row as Schema.Schema.Type<typeof ProjectionCheckpoint>)),- }),- ),- );-- const deleteByThreadId: ProjectionCheckpointRepositoryShape["deleteByThreadId"] = (input) =>- deleteProjectionCheckpointRows(input).pipe(- Effect.mapError(- toPersistenceSqlError("ProjectionCheckpointRepository.deleteByThreadId:query"),- ),- );-- return {- upsert,- listByThreadId,- getByThreadAndTurnCount,- deleteByThreadId,- } satisfies ProjectionCheckpointRepositoryShape;-});--export const ProjectionCheckpointRepositoryLive = Layer.effect(- ProjectionCheckpointRepository,- makeProjectionCheckpointRepository,-);diff --git a/apps/server/src/persistence/Layers/ProjectionPendingApprovals.ts b/apps/server/src/persistence/Layers/ProjectionPendingApprovals.tsindex d5631cb0a62..883198402ee 100644--- a/apps/server/src/persistence/Layers/ProjectionPendingApprovals.ts+++ b/apps/server/src/persistence/Layers/ProjectionPendingApprovals.ts@@ -7,7 +7,6 @@ import * as Schema from "effect/Schema";import { toPersistenceSqlError } from "../Errors.ts";import {GetProjectionPendingApprovalInput,- DeleteProjectionPendingApprovalInput,ListProjectionPendingApprovalsInput,ProjectionPendingApproval,ProjectionPendingApprovalRepository,@@ -97,15 +96,6 @@ const makeProjectionPendingApprovalRepository = Effect.gen(function* () {`,});- const deleteProjectionPendingApprovalRow = SqlSchema.void({- Request: DeleteProjectionPendingApprovalInput,- execute: ({ requestId }) =>- sql`- DELETE FROM projection_pending_approvals- WHERE request_id = ${requestId}- `,- });-const deleteProjectionPendingApprovalRowsByThread = SqlSchema.void({Request: ListProjectionPendingApprovalsInput,execute: ({ threadId }) =>@@ -143,15 +133,6 @@ const makeProjectionPendingApprovalRepository = Effect.gen(function* () {),);- const deleteByRequestId: ProjectionPendingApprovalRepositoryShape["deleteByRequestId"] = (- input,- ) =>- deleteProjectionPendingApprovalRow(input).pipe(- Effect.mapError(- toPersistenceSqlError("ProjectionPendingApprovalRepository.deleteByRequestId:query"),- ),- );-const deleteByThreadId: ProjectionPendingApprovalRepositoryShape["deleteByThreadId"] = (input) =>deleteProjectionPendingApprovalRowsByThread(input).pipe(Effect.mapError(@@ -164,7 +145,6 @@ const makeProjectionPendingApprovalRepository = Effect.gen(function* () {listByThreadId,countPendingByThreadId,getByRequestId,- deleteByRequestId,deleteByThreadId,} satisfies ProjectionPendingApprovalRepositoryShape;});diff --git a/apps/server/src/persistence/Layers/ProjectionProjects.ts b/apps/server/src/persistence/Layers/ProjectionProjects.tsindex f34f8129412..c4f07dc4912 100644--- a/apps/server/src/persistence/Layers/ProjectionProjects.ts+++ b/apps/server/src/persistence/Layers/ProjectionProjects.ts@@ -9,7 +9,6 @@ import * as Struct from "effect/Struct";import { ModelSelection, ProjectIconOverride, ProjectScript } from "@t3tools/contracts";import { toPersistenceSqlError } from "../Errors.ts";import {- DeleteProjectionProjectInput,GetProjectionProjectInput,ProjectionProject,ProjectionProjectRepository,@@ -24,7 +23,6 @@ const ProjectionProjectDbRow = ProjectionProject.mapFields(scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),}),);-type ProjectionProjectDbRow = typeof ProjectionProjectDbRow.Type;const makeProjectionProjectRepository = Effect.gen(function* () {const sql = yield* SqlClient.SqlClient;@@ -100,38 +98,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {`,});- const listProjectionProjectRows = SqlSchema.findAll({- Request: Schema.Void,- Result: ProjectionProjectDbRow,- execute: () =>- sql`- SELECT- project_id AS "projectId",- title,- workspace_root AS "workspaceRoot",- default_model_selection_json AS "defaultModelSelection",- default_thread_env_mode AS "defaultThreadEnvMode",- auto_pull AS "autoPull",- favicon_path AS "faviconPath",- project_icon_json AS "projectIcon",- scripts_json AS "scripts",- created_at AS "createdAt",- updated_at AS "updatedAt",- deleted_at AS "deletedAt"- FROM projection_projects- ORDER BY created_at ASC, project_id ASC- `,- });-- const deleteProjectionProjectRow = SqlSchema.void({- Request: DeleteProjectionProjectInput,- execute: ({ projectId }) =>- sql`- DELETE FROM projection_projects- WHERE project_id = ${projectId}- `,- });-const upsert: ProjectionProjectRepositoryShape["upsert"] = (row) =>upsertProjectionProjectRow(row).pipe(Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.upsert:query")),@@ -143,22 +109,9 @@ const makeProjectionProjectRepository = Effect.gen(function* () {Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.getById:query")),);- const listAll: ProjectionProjectRepositoryShape["listAll"] = () =>- listProjectionProjectRows().pipe(- Effect.map((rows) => rows.map((row) => ({ ...row, autoPull: row.autoPull === 1 }))),- Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.listAll:query")),- );-- const deleteById: ProjectionProjectRepositoryShape["deleteById"] = (input) =>- deleteProjectionProjectRow(input).pipe(- Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.deleteById:query")),- );-return {upsert,getById,- listAll,- deleteById,} satisfies ProjectionProjectRepositoryShape;});diff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.tsindex b7b2fdefba2..4be65bd5650 100644--- a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts+++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts@@ -518,9 +518,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {assert.deepStrictEqual(Option.getOrNull(persisted)?.linkedPullRequest, linkedPullRequest);assert.deepStrictEqual(Option.getOrNull(persisted)?.branchPullRequest, branchPullRequest);- const listed = yield* threads.listByProjectId({ projectId: linkedPullRequest.projectId });- assert.deepStrictEqual(listed[0]?.branchPullRequest, branchPullRequest);-const row = Option.getOrNull(persisted);if (row === null) return yield* Effect.die("Expected linked thread row to exist.");yield* threads.upsert({ ...row, linkedPullRequest: null });diff --git a/apps/server/src/persistence/Layers/ProjectionState.ts b/apps/server/src/persistence/Layers/ProjectionState.tsindex a6fb7f3be4d..383ab7d9fee 100644--- a/apps/server/src/persistence/Layers/ProjectionState.ts+++ b/apps/server/src/persistence/Layers/ProjectionState.ts@@ -1,4 +1,3 @@-import { NonNegativeInt } from "@t3tools/contracts";import * as SqlClient from "effect/unstable/sql/SqlClient";import * as SqlSchema from "effect/unstable/sql/SqlSchema";import * as Effect from "effect/Effect";@@ -14,10 +13,6 @@ import {ProjectionState,} from "../Services/ProjectionState.ts";-const MinLastAppliedSequenceRowSchema = Schema.Struct({- minLastAppliedSequence: Schema.NullOr(NonNegativeInt),-});-const makeProjectionStateRepository = Effect.gen(function* () {const sql = yield* SqlClient.SqlClient;@@ -90,17 +85,6 @@ const makeProjectionStateRepository = Effect.gen(function* () {`,});- const readMinLastAppliedSequence = SqlSchema.findOne({- Request: Schema.Void,- Result: MinLastAppliedSequenceRowSchema,- execute: () =>- sql`- SELECT- MIN(last_applied_sequence) AS "minLastAppliedSequence"- FROM projection_state- `,- });-const upsert: ProjectionStateRepositoryShape["upsert"] = (row) =>upsertProjectionStateRow(row).pipe(Effect.mapError(toPersistenceSqlError("ProjectionStateRepository.upsert:query")),@@ -121,20 +105,11 @@ const makeProjectionStateRepository = Effect.gen(function* () {Effect.mapError(toPersistenceSqlError("ProjectionStateRepository.listAll:query")),);- const minLastAppliedSequence: ProjectionStateRepositoryShape["minLastAppliedSequence"] = () =>- readMinLastAppliedSequence(undefined).pipe(- Effect.mapError(- toPersistenceSqlError("ProjectionStateRepository.minLastAppliedSequence:query"),- ),- Effect.map((row) => row.minLastAppliedSequence),- );-return {upsert,upsertMany,getByProjector,listAll,- minLastAppliedSequence,} satisfies ProjectionStateRepositoryShape;});diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.tsindex 4feaf3a185b..af36578f286 100644--- a/apps/server/src/persistence/Layers/ProjectionThreads.ts+++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts@@ -7,9 +7,7 @@ import * as Struct from "effect/Struct";import { toPersistenceSqlError } from "../Errors.ts";import {- DeleteProjectionThreadInput,GetProjectionThreadInput,- ListProjectionThreadsByProjectInput,ProjectionThread,ProjectionThreadRepository,type ProjectionThreadRepositoryShape,@@ -24,7 +22,6 @@ const ProjectionThreadDbRow = ProjectionThread.mapFields(branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),}),);-type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;const makeProjectionThreadRepository = Effect.gen(function* () {const sql = yield* SqlClient.SqlClient;@@ -172,57 +169,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {`,});- const listProjectionThreadRows = SqlSchema.findAll({- Request: ListProjectionThreadsByProjectInput,- Result: ProjectionThreadDbRow,- execute: ({ projectId }) =>- sql`- SELECT- thread_id AS "threadId",- project_id AS "projectId",- title,- title_state_json AS "titleState",- model_selection_json AS "modelSelection",- runtime_mode AS "runtimeMode",- interaction_mode AS "interactionMode",- branch,- worktree_path AS "worktreePath",- linked_pull_request_json AS "linkedPullRequest",- branch_pull_request_json AS "branchPullRequest",- latest_turn_id AS "latestTurnId",- created_at AS "createdAt",- updated_at AS "updatedAt",- archived_at AS "archivedAt",- settled_override AS "settledOverride",- settled_at AS "settledAt",- unsettled_at AS "unsettledAt",- snoozed_until AS "snoozedUntil",- snoozed_at AS "snoozedAt",- pinned_at AS "pinnedAt",- pin_order_key AS "pinOrderKey",- active_order_key AS "activeOrderKey",- title_regeneration_request_id AS "titleRegenerationRequestId",- title_regeneration_started_at AS "titleRegenerationStartedAt",- latest_user_message_at AS "latestUserMessageAt",- pending_approval_count AS "pendingApprovalCount",- pending_user_input_count AS "pendingUserInputCount",- has_actionable_proposed_plan AS "hasActionableProposedPlan",- deleted_at AS "deletedAt"- FROM projection_threads- WHERE project_id = ${projectId}- ORDER BY created_at ASC, thread_id ASC- `,- });-- const deleteProjectionThreadRow = SqlSchema.void({- Request: DeleteProjectionThreadInput,- execute: ({ threadId }) =>- sql`- DELETE FROM projection_threads- WHERE thread_id = ${threadId}- `,- });-const upsert: ProjectionThreadRepositoryShape["upsert"] = (row) =>upsertProjectionThreadRow(row).pipe(Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.upsert:query")),@@ -233,21 +179,9 @@ const makeProjectionThreadRepository = Effect.gen(function* () {Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.getById:query")),);- const listByProjectId: ProjectionThreadRepositoryShape["listByProjectId"] = (input) =>- listProjectionThreadRows(input).pipe(- Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.listByProjectId:query")),- );-- const deleteById: ProjectionThreadRepositoryShape["deleteById"] = (input) =>- deleteProjectionThreadRow(input).pipe(- Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.deleteById:query")),- );-return {upsert,getById,- listByProjectId,- deleteById,} satisfies ProjectionThreadRepositoryShape;});diff --git a/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts b/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.tsindex fff5a738622..ca32b1bddd4 100644--- a/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts+++ b/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("016_CanonicalizeModelSelections", (it) => {it.effect(diff --git a/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.ts b/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.tsindex 040a9fa47b9..248c74b43b3 100644--- a/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.ts+++ b/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("019_ProjectionSnapshotLookupIndexes", (it) => {it.effect("creates indexes for targeted projection lookup filters", () =>diff --git a/apps/server/src/persistence/Migrations/024_BackfillProjectionThreadShellSummary.test.ts b/apps/server/src/persistence/Migrations/024_BackfillProjectionThreadShellSummary.test.tsindex 49585fb36f3..73c579a1336 100644--- a/apps/server/src/persistence/Migrations/024_BackfillProjectionThreadShellSummary.test.ts+++ b/apps/server/src/persistence/Migrations/024_BackfillProjectionThreadShellSummary.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("024_BackfillProjectionThreadShellSummary", (it) => {it.effect("backfills thread shell summary fields and clears stale projected approvals", () =>diff --git a/apps/server/src/persistence/Migrations/025_CleanupInvalidProjectionPendingApprovals.test.ts b/apps/server/src/persistence/Migrations/025_CleanupInvalidProjectionPendingApprovals.test.tsindex efdf88bf6c3..7e65f4c04f7 100644--- a/apps/server/src/persistence/Migrations/025_CleanupInvalidProjectionPendingApprovals.test.ts+++ b/apps/server/src/persistence/Migrations/025_CleanupInvalidProjectionPendingApprovals.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("025_CleanupInvalidProjectionPendingApprovals", (it) => {it.effect("removes pending-approval rows that do not come from approval requests", () =>diff --git a/apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts b/apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.tsindex 558183e216c..5dd053cfe77 100644--- a/apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts+++ b/apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("026_CanonicalizeModelSelectionOptions", (it) => {it.effect("converts legacy object-shape options into array-shape on projections and events", () =>diff --git a/apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts b/apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.tsindex b5e4f5cf3a2..aa99f0c862a 100644--- a/apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts+++ b/apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("027_028_ProviderInstanceIdColumns", (it) => {it.effect("continues when provider_session_runtime was partially migrated", () =>diff --git a/apps/server/src/persistence/Migrations/029_ProjectionThreadDetailOrderingIndexes.test.ts b/apps/server/src/persistence/Migrations/029_ProjectionThreadDetailOrderingIndexes.test.tsindex 7078450c96e..cd246d16ee8 100644--- a/apps/server/src/persistence/Migrations/029_ProjectionThreadDetailOrderingIndexes.test.ts+++ b/apps/server/src/persistence/Migrations/029_ProjectionThreadDetailOrderingIndexes.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("029_ProjectionThreadDetailOrderingIndexes", (it) => {it.effect("creates indexes matching thread detail ordering queries", () =>diff --git a/apps/server/src/persistence/Migrations/031_AuthAuthorizationScopes.test.ts b/apps/server/src/persistence/Migrations/031_AuthAuthorizationScopes.test.tsindex 63eba11aac7..60b0079d79f 100644--- a/apps/server/src/persistence/Migrations/031_AuthAuthorizationScopes.test.ts+++ b/apps/server/src/persistence/Migrations/031_AuthAuthorizationScopes.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("031_AuthAuthorizationScopes", (it) => {it.effect("invalidates role-based auth records and installs scoped auth tables", () =>diff --git a/apps/server/src/persistence/Migrations/035_ProjectionThreadTitleRegeneration.test.ts b/apps/server/src/persistence/Migrations/035_ProjectionThreadTitleRegeneration.test.tsindex 0e7f54812c2..cf0ecff3253 100644--- a/apps/server/src/persistence/Migrations/035_ProjectionThreadTitleRegeneration.test.ts+++ b/apps/server/src/persistence/Migrations/035_ProjectionThreadTitleRegeneration.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("035_ProjectionThreadTitleRegeneration", (it) => {it.effect("adds pending title regeneration columns", () =>diff --git a/apps/server/src/persistence/Migrations/040_ProjectionProjectFaviconPath.test.ts b/apps/server/src/persistence/Migrations/040_ProjectionProjectFaviconPath.test.tsindex 42728812500..524831e891a 100644--- a/apps/server/src/persistence/Migrations/040_ProjectionProjectFaviconPath.test.ts+++ b/apps/server/src/persistence/Migrations/040_ProjectionProjectFaviconPath.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("040_ProjectionProjectFaviconPath", (it) => {it.effect("adds the nullable favicon path to project projections", () =>diff --git a/apps/server/src/persistence/Migrations/041_AuthSessionClientConnection.test.ts b/apps/server/src/persistence/Migrations/041_AuthSessionClientConnection.test.tsindex b19f1ce7cf2..4f106de404a 100644--- a/apps/server/src/persistence/Migrations/041_AuthSessionClientConnection.test.ts+++ b/apps/server/src/persistence/Migrations/041_AuthSessionClientConnection.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("041_AuthSessionClientConnection", (it) => {it.effect("adds nullable client surface and app version columns to auth sessions", () =>diff --git a/apps/server/src/persistence/Migrations/042_ProjectionThreadLinkedPullRequest.test.ts b/apps/server/src/persistence/Migrations/042_ProjectionThreadLinkedPullRequest.test.tsindex 02e7f2f6c59..a4ed1653a96 100644--- a/apps/server/src/persistence/Migrations/042_ProjectionThreadLinkedPullRequest.test.ts+++ b/apps/server/src/persistence/Migrations/042_ProjectionThreadLinkedPullRequest.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("042_ProjectionThreadLinkedPullRequest", (it) => {it.effect("adds the linked pull request column", () =>diff --git a/apps/server/src/persistence/Migrations/046_RepairAutomaticSettlementTimestamps.test.ts b/apps/server/src/persistence/Migrations/046_RepairAutomaticSettlementTimestamps.test.tsindex f562fa655a1..de7c6f01f65 100644--- a/apps/server/src/persistence/Migrations/046_RepairAutomaticSettlementTimestamps.test.ts+++ b/apps/server/src/persistence/Migrations/046_RepairAutomaticSettlementTimestamps.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));const MODEL_SELECTION = '{"instanceId":"codex","model":"gpt-5.6-sol"}';diff --git a/apps/server/src/persistence/Migrations/047_ProjectionProjectIcon.test.ts b/apps/server/src/persistence/Migrations/047_ProjectionProjectIcon.test.tsindex da3f7cd366d..c601bb0077f 100644--- a/apps/server/src/persistence/Migrations/047_ProjectionProjectIcon.test.ts+++ b/apps/server/src/persistence/Migrations/047_ProjectionProjectIcon.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("047_ProjectionProjectIcon", (it) => {it.effect("adds the nullable project icon JSON to project projections", () =>diff --git a/apps/server/src/persistence/Migrations/049_ProjectionThreadsActiveOrderKey.test.ts b/apps/server/src/persistence/Migrations/049_ProjectionThreadsActiveOrderKey.test.tsindex 138d25754d7..938ab25d0f8 100644--- a/apps/server/src/persistence/Migrations/049_ProjectionThreadsActiveOrderKey.test.ts+++ b/apps/server/src/persistence/Migrations/049_ProjectionThreadsActiveOrderKey.test.ts@@ -6,13 +6,15 @@ import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";import { runMigrations } from "../Migrations.ts";import migrateActiveOrderKey from "./049_ProjectionThreadsActiveOrderKey.ts";-it.layer(NodeSqliteClient.layerMemory())("049_ProjectionThreadsActiveOrderKey", (it) => {- it.effect("migrates old threads without changing their timestamps or assigning an order", () =>- Effect.gen(function* () {- const sql = yield* SqlClient.SqlClient;- yield* runMigrations({ toMigrationInclusive: 48 });- const now = "2026-01-01T00:00:00.000Z";- yield* sql`+it.layer(NodeSqliteClient.layer({ filename: ":memory:" }))(+ "049_ProjectionThreadsActiveOrderKey",+ (it) => {+ it.effect("migrates old threads without changing their timestamps or assigning an order", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ yield* runMigrations({ toMigrationInclusive: 48 });+ const now = "2026-01-01T00:00:00.000Z";+ yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, runtime_mode,created_at, updated_at@@ -21,24 +23,25 @@ it.layer(NodeSqliteClient.layerMemory())("049_ProjectionThreadsActiveOrderKey",'{"instanceId":"codex","model":"gpt-5.4"}', 'full-access', ${now}, ${now})`;- yield* runMigrations({ toMigrationInclusive: 49 });- const migrated = yield* sql<{ readonly activeOrderKey: string | null }>`+ yield* runMigrations({ toMigrationInclusive: 49 });+ const migrated = yield* sql<{ readonly activeOrderKey: string | null }>`SELECT active_order_key AS "activeOrderKey" FROM projection_threads WHERE thread_id = 'thread-1'`;- assert.deepEqual(migrated, [{ activeOrderKey: null }]);- // Recovery may run the same migration against a database that already- // has the column, including a placement written after the upgrade.- yield* sql`UPDATE projection_threads SET active_order_key = 'gm' WHERE thread_id = 'thread-1'`;- yield* migrateActiveOrderKey;- const rows = yield* sql<{- readonly activeOrderKey: string | null;- readonly createdAt: string;- readonly updatedAt: string;- }>`+ assert.deepEqual(migrated, [{ activeOrderKey: null }]);+ // Recovery may run the same migration against a database that already+ // has the column, including a placement written after the upgrade.+ yield* sql`UPDATE projection_threads SET active_order_key = 'gm' WHERE thread_id = 'thread-1'`;+ yield* migrateActiveOrderKey;+ const rows = yield* sql<{+ readonly activeOrderKey: string | null;+ readonly createdAt: string;+ readonly updatedAt: string;+ }>`SELECT active_order_key AS "activeOrderKey", created_at AS "createdAt", updated_at AS "updatedAt"FROM projection_threads WHERE thread_id = 'thread-1'`;- assert.deepEqual(rows, [{ activeOrderKey: "gm", createdAt: now, updatedAt: now }]);- }),- );-});+ assert.deepEqual(rows, [{ activeOrderKey: "gm", createdAt: now, updatedAt: now }]);+ }),+ );+ },+);diff --git a/apps/server/src/persistence/Migrations/050_ProjectionThreadPullRequests.test.ts b/apps/server/src/persistence/Migrations/050_ProjectionThreadPullRequests.test.tsindex 61d9f0618e9..7f3bc58d1cc 100644--- a/apps/server/src/persistence/Migrations/050_ProjectionThreadPullRequests.test.ts+++ b/apps/server/src/persistence/Migrations/050_ProjectionThreadPullRequests.test.ts@@ -9,7 +9,7 @@ import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));interface PullRequestRow {readonly threadId: string;@@ -156,26 +156,29 @@ layer("050_ProjectionThreadPullRequests", (it) => {);});-it.layer(Layer.fresh(NodeSqliteClient.layerMemory()))("050 Azure legacy links", (it) => {- it.effect("keeps legacy Azure repositories distinct across organizations", () =>- Effect.gen(function* () {- const sql = yield* SqlClient.SqlClient;- yield* runMigrations({ toMigrationInclusive: 49 });- for (const organization of ["org-a", "org-b"]) {- yield* sql`+it.layer(Layer.fresh(NodeSqliteClient.layer({ filename: ":memory:" })))(+ "050 Azure legacy links",+ (it) => {+ it.effect("keeps legacy Azure repositories distinct across organizations", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ yield* runMigrations({ toMigrationInclusive: 49 });+ for (const organization of ["org-a", "org-b"]) {+ yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, linked_pull_request_json, created_at, updated_at)VALUES (${organization}, ${organization}, 'Azure', '{"instanceId":"codex","model":"gpt-5.4"}',${encodeJson({ projectId: organization, repository: "web", number: 7, url: `https://dev.azure.com/${organization}/project/_git/web/pullrequest/7` })},'2026-03-01T00:00:00.000Z', '2026-03-01T00:00:00.000Z')`;- }- yield* runMigrations({ toMigrationInclusive: 50 });- const rows =- yield* sql`SELECT host, repository, number FROM projection_thread_pull_requests ORDER BY repository`;- assert.deepStrictEqual(rows, [- { host: "dev.azure.com", repository: "org-a/project/_git/web", number: 7 },- { host: "dev.azure.com", repository: "org-b/project/_git/web", number: 7 },- ]);- }),- );-});+ }+ yield* runMigrations({ toMigrationInclusive: 50 });+ const rows =+ yield* sql`SELECT host, repository, number FROM projection_thread_pull_requests ORDER BY repository`;+ assert.deepStrictEqual(rows, [+ { host: "dev.azure.com", repository: "org-a/project/_git/web", number: 7 },+ { host: "dev.azure.com", repository: "org-b/project/_git/web", number: 7 },+ ]);+ }),+ );+ },+);diff --git a/apps/server/src/persistence/Migrations/051_ProjectionThreadMessageContext.test.ts b/apps/server/src/persistence/Migrations/051_ProjectionThreadMessageContext.test.tsindex c3cdfa1b9dc..a0e59217cd3 100644--- a/apps/server/src/persistence/Migrations/051_ProjectionThreadMessageContext.test.ts+++ b/apps/server/src/persistence/Migrations/051_ProjectionThreadMessageContext.test.ts@@ -6,7 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import { runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";-const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("051_ProjectionThreadMessageContext", (it) => {it.effect("accepts context added by an earlier development migration", () =>diff --git a/apps/server/src/persistence/Services/ProjectionCheckpoints.ts b/apps/server/src/persistence/Services/ProjectionCheckpoints.tsdeleted file mode 100644index 7796ebec2a8..00000000000--- a/apps/server/src/persistence/Services/ProjectionCheckpoints.ts+++ /dev/null@@ -1,95 +0,0 @@-/**- * ProjectionCheckpointRepository - Projection repository interface for checkpoints.- *- * Owns persistence operations for projected checkpoint summaries in thread- * timelines.- *- * @module ProjectionCheckpointRepository- */-import {- CheckpointRef,- IsoDateTime,- MessageId,- NonNegativeInt,- OrchestrationCheckpointFile,- OrchestrationCheckpointStatus,- ThreadId,- TurnId,-} from "@t3tools/contracts";-import * as Option from "effect/Option";-import * as Context from "effect/Context";-import * as Schema from "effect/Schema";-import type * as Effect from "effect/Effect";--import type { ProjectionRepositoryError } from "../Errors.ts";--export const ProjectionCheckpoint = Schema.Struct({- threadId: ThreadId,- turnId: TurnId,- checkpointTurnCount: NonNegativeInt,- checkpointRef: CheckpointRef,- status: OrchestrationCheckpointStatus,- files: Schema.Array(OrchestrationCheckpointFile),- assistantMessageId: Schema.NullOr(MessageId),- completedAt: IsoDateTime,-});-export type ProjectionCheckpoint = typeof ProjectionCheckpoint.Type;--export const ListByThreadIdInput = Schema.Struct({- threadId: ThreadId,-});-export type ListByThreadIdInput = typeof ListByThreadIdInput.Type;--export const GetByThreadAndTurnCountInput = Schema.Struct({- threadId: ThreadId,- checkpointTurnCount: NonNegativeInt,-});-export type GetByThreadAndTurnCountInput = typeof GetByThreadAndTurnCountInput.Type;--export const DeleteByThreadIdInput = Schema.Struct({- threadId: ThreadId,-});-export type DeleteByThreadIdInput = typeof DeleteByThreadIdInput.Type;--/**- * ProjectionCheckpointRepositoryShape - Service API for projected checkpoints.- */-export interface ProjectionCheckpointRepositoryShape {- /**- * Insert or replace a projected checkpoint row.- *- * Upserts by composite key `(threadId, checkpointTurnCount)`.- */- readonly upsert: (row: ProjectionCheckpoint) => Effect.Effect<void, ProjectionRepositoryError>;-- /**- * List projected checkpoints for a thread.- *- * Returned in ascending checkpoint turn-count order.- */- readonly listByThreadId: (- input: ListByThreadIdInput,- ) => Effect.Effect<ReadonlyArray<ProjectionCheckpoint>, ProjectionRepositoryError>;-- /**- * Read a projected checkpoint by thread and turn-count key.- */- readonly getByThreadAndTurnCount: (- input: GetByThreadAndTurnCountInput,- ) => Effect.Effect<Option.Option<ProjectionCheckpoint>, ProjectionRepositoryError>;-- /**- * Delete projected checkpoint rows by thread.- */- readonly deleteByThreadId: (- input: DeleteByThreadIdInput,- ) => Effect.Effect<void, ProjectionRepositoryError>;-}--/**- * ProjectionCheckpointRepository - Service tag for checkpoint projection persistence.- */-export class ProjectionCheckpointRepository extends Context.Service<- ProjectionCheckpointRepository,- ProjectionCheckpointRepositoryShape->()("t3/persistence/Services/ProjectionCheckpoints/ProjectionCheckpointRepository") {}diff --git a/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts b/apps/server/src/persistence/Services/ProjectionPendingApprovals.tsindex 43a829de639..9b9e090af76 100644--- a/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts+++ b/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts@@ -42,11 +42,6 @@ export const GetProjectionPendingApprovalInput = Schema.Struct({});export type GetProjectionPendingApprovalInput = typeof GetProjectionPendingApprovalInput.Type;-export const DeleteProjectionPendingApprovalInput = Schema.Struct({- requestId: ApprovalRequestId,-});-export type DeleteProjectionPendingApprovalInput = typeof DeleteProjectionPendingApprovalInput.Type;-/*** ProjectionPendingApprovalRepositoryShape - Service API for pending approvals.*/@@ -81,13 +76,6 @@ export interface ProjectionPendingApprovalRepositoryShape {input: GetProjectionPendingApprovalInput,) => Effect.Effect<Option.Option<ProjectionPendingApproval>, ProjectionRepositoryError>;- /**- * Delete a pending approval row by request id.- */- readonly deleteByRequestId: (- input: DeleteProjectionPendingApprovalInput,- ) => Effect.Effect<void, ProjectionRepositoryError>;-/*** Delete every pending approval row for a thread.*/diff --git a/apps/server/src/persistence/Services/ProjectionProjects.ts b/apps/server/src/persistence/Services/ProjectionProjects.tsindex e5d1f6ba1f1..3228855fc8e 100644--- a/apps/server/src/persistence/Services/ProjectionProjects.ts+++ b/apps/server/src/persistence/Services/ProjectionProjects.ts@@ -42,11 +42,6 @@ export const GetProjectionProjectInput = Schema.Struct({});export type GetProjectionProjectInput = typeof GetProjectionProjectInput.Type;-export const DeleteProjectionProjectInput = Schema.Struct({- projectId: ProjectId,-});-export type DeleteProjectionProjectInput = typeof DeleteProjectionProjectInput.Type;-/*** ProjectionProjectRepositoryShape - Service API for projected project records.*/@@ -64,23 +59,6 @@ export interface ProjectionProjectRepositoryShape {readonly getById: (input: GetProjectionProjectInput,) => Effect.Effect<Option.Option<ProjectionProject>, ProjectionRepositoryError>;-- /**- * List all projected project rows.- *- * Returned in deterministic creation order.- */- readonly listAll: () => Effect.Effect<- ReadonlyArray<ProjectionProject>,- ProjectionRepositoryError- >;-- /**- * Soft-delete a projected project row by id.- */- readonly deleteById: (- input: DeleteProjectionProjectInput,- ) => Effect.Effect<void, ProjectionRepositoryError>;}/**diff --git a/apps/server/src/persistence/Services/ProjectionState.ts b/apps/server/src/persistence/Services/ProjectionState.tsindex 9372acdeeb6..52dbc4cf637 100644--- a/apps/server/src/persistence/Services/ProjectionState.ts+++ b/apps/server/src/persistence/Services/ProjectionState.ts@@ -53,13 +53,6 @@ export interface ProjectionStateRepositoryShape {* List all projector cursor rows.*/readonly listAll: () => Effect.Effect<ReadonlyArray<ProjectionState>, ProjectionRepositoryError>;-- /**- * Read the minimum applied sequence across all projectors.- *- * Returns `null` when no projector state rows exist.- */- readonly minLastAppliedSequence: () => Effect.Effect<number | null, ProjectionRepositoryError>;}/**diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.tsindex 2c8186a321c..895fe596db2 100644--- a/apps/server/src/persistence/Services/ProjectionThreads.ts+++ b/apps/server/src/persistence/Services/ProjectionThreads.ts@@ -65,16 +65,6 @@ export const GetProjectionThreadInput = Schema.Struct({});export type GetProjectionThreadInput = typeof GetProjectionThreadInput.Type;-export const DeleteProjectionThreadInput = Schema.Struct({- threadId: ThreadId,-});-export type DeleteProjectionThreadInput = typeof DeleteProjectionThreadInput.Type;--export const ListProjectionThreadsByProjectInput = Schema.Struct({- projectId: ProjectId,-});-export type ListProjectionThreadsByProjectInput = typeof ListProjectionThreadsByProjectInput.Type;-/*** ProjectionThreadRepositoryShape - Service API for projected thread records.*/@@ -92,22 +82,6 @@ export interface ProjectionThreadRepositoryShape {readonly getById: (input: GetProjectionThreadInput,) => Effect.Effect<Option.Option<ProjectionThread>, ProjectionRepositoryError>;-- /**- * List projected threads for a project.- *- * Returned in deterministic creation order.- */- readonly listByProjectId: (- input: ListProjectionThreadsByProjectInput,- ) => Effect.Effect<ReadonlyArray<ProjectionThread>, ProjectionRepositoryError>;-- /**- * Soft-delete a projected thread row by id.- */- readonly deleteById: (- input: DeleteProjectionThreadInput,- ) => Effect.Effect<void, ProjectionRepositoryError>;}/**diff --git a/apps/server/src/provider/acp/XAiAcpExtension.ts b/apps/server/src/provider/acp/XAiAcpExtension.tsindex 620545569aa..08bbd674e9b 100644--- a/apps/server/src/provider/acp/XAiAcpExtension.ts+++ b/apps/server/src/provider/acp/XAiAcpExtension.ts@@ -110,10 +110,6 @@ interface XAiAskUserQuestionCancelledResponse {readonly outcome: "cancelled";}-export type XAiAskUserQuestionResponse =- | XAiAskUserQuestionAcceptedResponse- | XAiAskUserQuestionCancelledResponse;-interface NormalizedXAiAnswer {readonly questionText: string;readonly selectedLabels: ReadonlyArray<string>;diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.tsindex 512e55a64cb..2618020d388 100644--- a/apps/server/src/server.test.ts+++ b/apps/server/src/server.test.ts@@ -123,10 +123,7 @@ import * as Keybindings from "./keybindings.ts";import * as ExternalLauncher from "./process/externalLauncher.ts";import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";-import {- OrchestrationListenerCallbackError,- OrchestrationThreadSettleBlockedError,-} from "./orchestration/Errors.ts";+import { OrchestrationThreadSettleBlockedError } from "./orchestration/Errors.ts";import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";import { ThreadDeletionReactor } from "./orchestration/Services/ThreadDeletionReactor.ts";import * as PullRequestSyncReactor from "./orchestration/PullRequestSyncReactor.ts";@@ -7358,8 +7355,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {Effect.flatMap(() =>command.commandId === failedCommandId? Effect.fail(- new OrchestrationListenerCallbackError({- listener: "domain-event",+ new PersistenceSqlError({+ operation: "OrchestrationEventStore.append:query",detail: "thread creation failed",}),)@@ -10682,8 +10679,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {effects.push(`dispatch:${command.type}`);if (command.type === "thread.session.stop") {return Effect.fail(- new OrchestrationListenerCallbackError({- listener: "domain-event",+ new PersistenceSqlError({+ operation: "OrchestrationEventStore.append:query",detail: "simulated archive stop failure",}),);@@ -11629,8 +11626,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {setupActivityAppendAttempt += 1;if (setupActivityAppendAttempt === 2) {return Effect.fail(- new OrchestrationListenerCallbackError({- listener: "domain-event",+ new PersistenceSqlError({+ operation: "OrchestrationEventStore.append:query",detail: "failed to append setup-script.started activity",}),);@@ -12155,8 +12152,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {dispatchedCommands.push(command);if (command.type === "thread.delete") {return Effect.fail(- new OrchestrationListenerCallbackError({- listener: "domain-event",+ new PersistenceSqlError({+ operation: "OrchestrationEventStore.append:query",detail: "thread cleanup exploded",}),);diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.tsindex 27fc28df7bf..37634cea7e4 100644--- a/apps/server/src/textGeneration/TextGeneration.ts+++ b/apps/server/src/textGeneration/TextGeneration.ts@@ -10,8 +10,6 @@ import * as SourceControlProviderRegistry from "../sourceControl/SourceControlPrimport * as ThreadTitleLinks from "./ThreadTitleLinks.ts";import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";-export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "grok" | "opencode";-export interface CommitMessageGenerationInput {cwd: string;branch: string | null;diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.tsindex cac501aede0..a387dd189b3 100644--- a/apps/server/src/workspace/WorkspaceSearchIndex.ts+++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts@@ -107,12 +107,6 @@ export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedError<Worksp}}-export type WorkspaceSearchIndexError =- | WorkspaceSearchIndexCreateFailed- | WorkspaceSearchIndexScanTimedOut- | WorkspaceSearchIndexSearchFailed- | WorkspaceSearchIndexRefreshFailed;-export class WorkspaceSearchIndex extends Context.Service<WorkspaceSearchIndex,{diff --git a/apps/web/src/cloud/managedAuth.test.ts b/apps/web/src/cloud/managedAuth.test.tsindex aa29a59677e..63001bdb184 100644--- a/apps/web/src/cloud/managedAuth.test.ts+++ b/apps/web/src/cloud/managedAuth.test.ts@@ -1,11 +1,11 @@import { managedRelaySessionAtom, setManagedRelaySession } from "@t3tools/client-runtime/relay";+import * as Effect from "effect/Effect";import { afterEach, describe, expect, it, vi } from "vite-plus/test";import { appAtomRegistry } from "../rpc/atomRegistry";import {activateManagedRelayAuthentication,deactivateManagedRelayAuthentication,- readManagedRelayClerkToken,} from "./managedAuth";vi.mock("@clerk/react", () => ({@@ -32,13 +32,16 @@ describe("managed relay authentication", () => {it("clears all token access synchronously before account cleanup can fail", async () => {activateManagedRelayAuthentication("account-1", async () => "account-1-token");expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1");- expect(await readManagedRelayClerkToken()).toBe("account-1-token");+ const token = await Effect.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)).pipe(+ Effect.flatMap((session) => session.readClerkToken()),+ Effect.runPromise,+ );+ expect(token).toBe("account-1-token");deactivateManagedRelayAuthentication();const cleanup = Promise.reject(new Error("Persistence removal failed.")).catch(() => undefined);expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull();- expect(await readManagedRelayClerkToken()).toBeNull();await cleanup;});diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsxindex 2f631214501..f9bf1c966f4 100644--- a/apps/web/src/cloud/managedAuth.tsx+++ b/apps/web/src/cloud/managedAuth.tsx@@ -14,14 +14,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry";import { useAtomCommand } from "../state/use-atom-command";import { resolveRelayClerkTokenOptions } from "./publicConfig";-let relayTokenProvider: (() => Promise<string | null>) | null = null;--export async function readManagedRelayClerkToken(): Promise<string | null> {- return relayTokenProvider?.() ?? null;-}-export function deactivateManagedRelayAuthentication(): void {- relayTokenProvider = null;setManagedRelaySession(appAtomRegistry, null);}@@ -29,7 +22,6 @@ export function activateManagedRelayAuthentication(accountId: string,readClerkToken: () => Promise<string | null>,): void {- relayTokenProvider = readClerkToken;setManagedRelaySession(appAtomRegistry, {accountId,readClerkToken,diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.tsindex 799bd0bde7f..a2897ce3ddb 100644--- a/apps/web/src/components/ChatView.logic.test.ts+++ b/apps/web/src/components/ChatView.logic.test.ts@@ -32,7 +32,6 @@ import {usePreviewMiniPlayerStore,} from "../previewMiniPlayerStore";import {- MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,agentControlledBrowserCloseConfirmation,branchMismatchKey,@@ -52,7 +51,6 @@ import {shouldRefocusComposerOnWindowFocus,isBranchMismatchDismissedForSession,reconcileMountedTerminalThreadIds,- reconcileRetainedMountedThreadIds,recallCheckoutIsRepo,rememberCheckoutIsRepo,resolveBackgroundDraftWorkspaceOptions,@@ -1887,50 +1885,6 @@ describe("reconcileMountedTerminalThreadIds", () => {});});-describe("reconcileRetainedMountedThreadIds", () => {- it("retains hidden open threads and adds the active open thread", () => {- expect(- reconcileRetainedMountedThreadIds({- currentThreadIds: [ThreadId.make("thread-hidden")],- openThreadIds: [ThreadId.make("thread-hidden")],- activeThreadId: ThreadId.make("thread-active"),- activeThreadOpen: true,- maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,- }),- ).toEqual([ThreadId.make("thread-hidden"), ThreadId.make("thread-active")]);- });-- it("can retain the active thread as hidden when it is inactive", () => {- expect(- reconcileRetainedMountedThreadIds({- currentThreadIds: [ThreadId.make("thread-active")],- openThreadIds: [ThreadId.make("thread-active")],- activeThreadId: ThreadId.make("thread-active"),- activeThreadOpen: false,- maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,- retainInactiveActiveThread: true,- }),- ).toEqual([ThreadId.make("thread-active")]);- });-- it("evicts the oldest hidden threads beyond the configured cap", () => {- const currentThreadIds = Array.from(- { length: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS + 2 },- (_, index) => ThreadId.make(`thread-${index + 1}`),- );-- expect(- reconcileRetainedMountedThreadIds({- currentThreadIds,- openThreadIds: currentThreadIds,- activeThreadId: null,- activeThreadOpen: false,- maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,- }),- ).toEqual(currentThreadIds.slice(-MAX_HIDDEN_MOUNTED_PREVIEW_THREADS));- });-});-describe("shouldWriteThreadErrorToCurrentServerThread", () => {it("writes errors for a shell-derived active server thread", () => {const routeThreadRef = { environmentId, threadId };diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex bc68a9fcfa0..928d99c549a 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -60,7 +60,7 @@ import {export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;-export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;+export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000;export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);@@ -678,31 +678,15 @@ export function reconcileMountedTerminalThreadIds(input: {activeThreadId: string | null;activeThreadTerminalOpen: boolean;maxHiddenThreadCount?: number;-}): string[] {- return reconcileRetainedMountedThreadIds({- currentThreadIds: input.currentThreadIds,- openThreadIds: input.openThreadIds,- activeThreadId: input.activeThreadId,- activeThreadOpen: input.activeThreadTerminalOpen,- maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,- });-}--export function reconcileRetainedMountedThreadIds(input: {- currentThreadIds: ReadonlyArray<string>;- openThreadIds: ReadonlyArray<string>;- activeThreadId: string | null;- activeThreadOpen: boolean;- maxHiddenThreadCount: number;- retainInactiveActiveThread?: boolean;}): string[] {const openThreadIdSet = new Set(input.openThreadIds);const hiddenThreadIds = input.currentThreadIds.filter(- (threadId) =>- (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&- openThreadIdSet.has(threadId),+ (threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId),+ );+ const maxHiddenThreadCount = Math.max(+ 0,+ input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,);- const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);const nextThreadIds =hiddenThreadIds.length > maxHiddenThreadCount? hiddenThreadIds.slice(-maxHiddenThreadCount)@@ -710,7 +694,7 @@ export function reconcileRetainedMountedThreadIds(input: {if (input.activeThreadId &&- input.activeThreadOpen &&+ input.activeThreadTerminalOpen &&!nextThreadIds.includes(input.activeThreadId)) {nextThreadIds.push(input.activeThreadId);diff --git a/apps/web/src/components/preview/PreviewPanelShell.test.ts b/apps/web/src/components/preview/PreviewPanelShell.test.tsindex 23deb066a2a..765e0b0a1b0 100644--- a/apps/web/src/components/preview/PreviewPanelShell.test.ts+++ b/apps/web/src/components/preview/PreviewPanelShell.test.ts@@ -1,8 +1,6 @@-import { jsx } from "react/jsx-runtime";-import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vite-plus/test";-import { getPreviewPanelMaxWidth, PreviewPanelShell } from "./PreviewPanelShell";+import { getPreviewPanelMaxWidth } from "./PreviewPanelShell";describe("getPreviewPanelMaxWidth", () => {it("allows the panel to use 70% of an ultra-wide viewport without a pixel ceiling", () => {@@ -13,14 +11,6 @@ describe("getPreviewPanelMaxWidth", () => {expect(getPreviewPanelMaxWidth(2_001)).toBe(1_400);});- it("keeps inline panels inside their containing workspace", () => {- const markup = renderToStaticMarkup(- jsx(PreviewPanelShell, { mode: "inline", defaultWidth: 1_000, children: "Panel" }),- );-- expect(markup).toContain("max-w-full");- });-it("reserves the sibling column minimum when the flex row is known", () => {// Fullscreen 14" MacBook: viewport 1512, sidebar ~256 → row of 1256.// The 70% fraction (1058) would leave the chat column only ~198px;diff --git a/apps/web/src/components/settings/settingsLayout.test.tsx b/apps/web/src/components/settings/settingsLayout.test.tsxindex 51bb90b33ab..4195a359d1b 100644--- a/apps/web/src/components/settings/settingsLayout.test.tsx+++ b/apps/web/src/components/settings/settingsLayout.test.tsx@@ -1,12 +1,7 @@import { renderToStaticMarkup } from "react-dom/server";import { afterEach, describe, expect, it, vi } from "vite-plus/test";-import {- scrollToSettingsTarget,- SettingsRow,- SettingsSearchTargetProvider,- SettingsUnavailableGroup,-} from "./settingsLayout";+import { scrollToSettingsTarget, SettingsRow, SettingsUnavailableGroup } from "./settingsLayout";afterEach(() => {vi.unstubAllGlobals();@@ -27,19 +22,6 @@ describe("unavailable settings", () => {});describe("settings search targets", () => {- it("does not persist destination styling in the rendered row", () => {- const markup = renderToStaticMarkup(- <SettingsSearchTargetProvider targetId="word-wrap">- <SettingsRow id="word-wrap" title="Word wrap" description="Wrap long lines." />- <SettingsRow id="time-format" title="Time format" description="Choose a clock." />- </SettingsSearchTargetProvider>,- );-- expect(markup).toContain('id="word-wrap" tabindex="-1"');- expect(markup).not.toContain("data-settings-search-target");- expect(markup).not.toContain("settings-search-target-pulse");- });-it("scrolls directly to a section header and restarts the destination pulse", () => {const sectionScrollIntoView = vi.fn();const headerScrollIntoView = vi.fn();diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsxindex 94938b637db..c805e37f1bb 100644--- a/apps/web/src/components/settings/settingsLayout.tsx+++ b/apps/web/src/components/settings/settingsLayout.tsx@@ -57,7 +57,7 @@ const SettingsSearchTargetContext = createContext<SettingsSearchTargetContextValonTargetHandled: noop,});-export function SettingsSearchTargetProvider({+function SettingsSearchTargetProvider({targetId,highlightTarget = true,onTargetHandled = noop,diff --git a/apps/web/src/components/ui/alert-dialog.tsx b/apps/web/src/components/ui/alert-dialog.tsxindex 4f57e920118..6e6c1ce2b21 100644--- a/apps/web/src/components/ui/alert-dialog.tsx+++ b/apps/web/src/components/ui/alert-dialog.tsx@@ -9,16 +9,10 @@ import {DIALOG_POPUP_CLASS,} from "~/components/ui/dialog-styles";-const AlertDialogCreateHandle = AlertDialogPrimitive.createHandle;-const AlertDialog = AlertDialogPrimitive.Root;const AlertDialogPortal = AlertDialogPrimitive.Portal;-function AlertDialogTrigger(props: AlertDialogPrimitive.Trigger.Props) {- return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />;-}-function AlertDialogBackdrop({ className, ...props }: AlertDialogPrimitive.Backdrop.Props) {return (<AlertDialogPrimitive.Backdrop@@ -129,12 +123,10 @@ function AlertDialogClose(props: AlertDialogPrimitive.Close.Props) {}export {- AlertDialogCreateHandle,AlertDialog,AlertDialogPortal,AlertDialogBackdrop,AlertDialogBackdrop as AlertDialogOverlay,- AlertDialogTrigger,AlertDialogPopup,AlertDialogPopup as AlertDialogContent,AlertDialogHeader,diff --git a/apps/web/src/components/ui/autocomplete.tsx b/apps/web/src/components/ui/autocomplete.tsxindex b81701e2592..49735c97e3d 100644--- a/apps/web/src/components/ui/autocomplete.tsx+++ b/apps/web/src/components/ui/autocomplete.tsx@@ -136,16 +136,6 @@ function AutocompleteItem({ className, children, ...props }: AutocompletePrimiti);}-function AutocompleteSeparator({ className, ...props }: AutocompletePrimitive.Separator.Props) {- return (- <AutocompletePrimitive.Separator- className={cn("mx-2 my-1 h-px bg-border last:hidden", className)}- data-slot="autocomplete-separator"- {...props}- />- );-}-function AutocompleteGroup({ className, ...props }: AutocompletePrimitive.Group.Props) {return (<AutocompletePrimitive.Group@@ -179,16 +169,6 @@ function AutocompleteEmpty({ className, ...props }: AutocompletePrimitive.Empty.);}-function AutocompleteRow({ className, ...props }: AutocompletePrimitive.Row.Props) {- return (- <AutocompletePrimitive.Row className={className} data-slot="autocomplete-row" {...props} />- );-}--function AutocompleteValue({ ...props }: AutocompletePrimitive.Value.Props) {- return <AutocompletePrimitive.Value data-slot="autocomplete-value" {...props} />;-}-function AutocompleteList({ className, ...props }: AutocompletePrimitive.List.Props) {return (<ScrollArea scrollbarGutter scrollFade>@@ -216,19 +196,6 @@ function AutocompleteClear({ className, ...props }: AutocompletePrimitive.Clear.);}-function AutocompleteStatus({ className, ...props }: AutocompletePrimitive.Status.Props) {- return (- <AutocompletePrimitive.Status- className={cn(- "px-3 py-2 font-medium text-muted-foreground text-xs empty:m-0 empty:p-0",- className,- )}- data-slot="autocomplete-status"- {...props}- />- );-}-function AutocompleteCollection({ ...props }: AutocompletePrimitive.Collection.Props) {return <AutocompletePrimitive.Collection data-slot="autocomplete-collection" {...props} />;}@@ -249,23 +216,16 @@ function AutocompleteTrigger({);}-const useAutocompleteFilter = AutocompletePrimitive.useFilter;-export {Autocomplete,AutocompleteInput,AutocompleteTrigger,AutocompletePopup,AutocompleteItem,- AutocompleteSeparator,AutocompleteGroup,AutocompleteGroupLabel,AutocompleteEmpty,- AutocompleteValue,AutocompleteList,AutocompleteClear,- AutocompleteStatus,- AutocompleteRow,AutocompleteCollection,- useAutocompleteFilter,};diff --git a/apps/web/src/components/ui/combobox.tsx b/apps/web/src/components/ui/combobox.tsxindex 863726f3241..42a3b815e2f 100644--- a/apps/web/src/components/ui/combobox.tsx+++ b/apps/web/src/components/ui/combobox.tsx@@ -28,31 +28,6 @@ function Combobox<Value, Multiple extends boolean | undefined = false>();}-function ComboboxChipsInput({- className,- size,- ...props-}: Omit<ComboboxPrimitive.Input.Props, "size"> & {- size?: "sm" | "default" | "lg" | number;- ref?: React.Ref<HTMLInputElement>;-}) {- const sizeValue = (size ?? "default") as "sm" | "default" | "lg" | number;-- return (- <ComboboxPrimitive.Input- className={cn(- "min-w-12 flex-1 text-base outline-none sm:text-sm [[data-slot=combobox-chip]+&]:ps-0.5",- sizeValue === "sm" ? "ps-1.5" : "ps-2",- className,- )}- data-size={typeof sizeValue === "string" ? sizeValue : undefined}- data-slot="combobox-chips-input"- size={typeof sizeValue === "number" ? sizeValue : undefined}- {...props}- />- );-}-function ComboboxInput({className,inputClassName,@@ -240,36 +215,6 @@ function ComboboxItem({);}-function ComboboxSeparator({ className, ...props }: ComboboxPrimitive.Separator.Props) {- return (- <ComboboxPrimitive.Separator- className={cn("mx-2 my-1 h-px bg-border last:hidden", className)}- data-slot="combobox-separator"- {...props}- />- );-}--function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) {- return (- <ComboboxPrimitive.Group- className={cn("[[role=group]+&]:mt-1.5", className)}- data-slot="combobox-group"- {...props}- />- );-}--function ComboboxGroupLabel({ className, ...props }: ComboboxPrimitive.GroupLabel.Props) {- return (- <ComboboxPrimitive.GroupLabel- className={cn("px-2 py-1.5 font-medium text-muted-foreground text-xs", className)}- data-slot="combobox-group-label"- {...props}- />- );-}-function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {return (<ComboboxPrimitive.Empty@@ -283,14 +228,6 @@ function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {);}-function ComboboxRow({ className, ...props }: ComboboxPrimitive.Row.Props) {- return <ComboboxPrimitive.Row className={className} data-slot="combobox-row" {...props} />;-}--function ComboboxValue({ ...props }: ComboboxPrimitive.Value.Props) {- return <ComboboxPrimitive.Value data-slot="combobox-value" {...props} />;-}-function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {return (<ScrollArea scrollbarGutter scrollFade>@@ -334,102 +271,19 @@ function ComboboxStatus({ className, ...props }: ComboboxPrimitive.Status.Props));}-function ComboboxCollection(props: ComboboxPrimitive.Collection.Props) {- return <ComboboxPrimitive.Collection data-slot="combobox-collection" {...props} />;-}--function ComboboxChips({- className,- children,- startAddon,- ...props-}: ComboboxPrimitive.Chips.Props & {- startAddon?: React.ReactNode;-}) {- const { chipsRef } = React.use(ComboboxContext);-- return (- <ComboboxPrimitive.Chips- className={cn(- "relative inline-flex min-h-9 w-full flex-wrap gap-1 rounded-lg border border-input bg-background not-dark:bg-clip-padding p-[calc(--spacing(1)-1px)] text-base shadow-xs/5 outline-none ring-ring/24 transition-shadow *:min-h-7 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-has-disabled:not-focus-within:not-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] focus-within:border-ring focus-within:ring-[3px] has-disabled:pointer-events-none has-data-[size=lg]:min-h-10 has-data-[size=sm]:min-h-8 has-aria-invalid:border-destructive/36 has-autofill:bg-foreground/4 has-disabled:opacity-64 has-[:disabled,:focus-within,[aria-invalid]]:shadow-none focus-within:has-aria-invalid:border-destructive/64 focus-within:has-aria-invalid:ring-destructive/16 has-data-[size=lg]:*:min-h-8 has-data-[size=sm]:*:min-h-6 sm:min-h-8 sm:text-sm sm:has-data-[size=lg]:min-h-9 sm:has-data-[size=sm]:min-h-7 sm:*:min-h-6 sm:has-data-[size=lg]:*:min-h-7 sm:has-data-[size=sm]:*:min-h-5 dark:not-has-disabled:bg-input/32 dark:has-autofill:bg-foreground/8 dark:has-aria-invalid:ring-destructive/24 dark:not-has-disabled:not-focus-within:not-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)]",- className,- )}- data-slot="combobox-chips"- ref={chipsRef as React.Ref<HTMLDivElement> | null}- {...props}- >- {startAddon && (- <div- aria-hidden="true"- className="[&_svg]:-ms-0.5 [&_svg]:-me-1.5 flex shrink-0 items-center ps-2 opacity-80 has-[~[data-size=sm]]:has-[+[data-slot=combobox-chip]]:pe-1.5 has-[~[data-size=sm]]:ps-1.5 has-[+[data-slot=combobox-chip]]:pe-2 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none"- data-slot="combobox-start-addon"- >- {startAddon}- </div>- )}- {children}- </ComboboxPrimitive.Chips>- );-}--function ComboboxChip({ children, ...props }: ComboboxPrimitive.Chip.Props) {- const labelId = React.useId();-- return (- <ComboboxPrimitive.Chip- className="flex items-center rounded-[calc(var(--radius-md)-1px)] bg-accent ps-2 font-medium text-accent-foreground text-sm outline-none sm:text-xs/(--text-xs--line-height) [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5"- data-slot="combobox-chip"- {...props}- >- <span id={labelId}>{children}</span>- <ComboboxChipRemove labelId={labelId} />- </ComboboxPrimitive.Chip>- );-}--function ComboboxChipRemove({- labelId,- ...props-}: ComboboxPrimitive.ChipRemove.Props & { labelId: string }) {- const removeLabelId = `${labelId}-remove`;-- return (- <ComboboxPrimitive.ChipRemove- aria-labelledby={`${removeLabelId} ${labelId}`}- className="h-full shrink-0 cursor-pointer px-1.5 opacity-80 hover:opacity-100 [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5"- data-slot="combobox-chip-remove"- {...props}- >- <span id={removeLabelId} className="sr-only">- Remove- </span>- <XIcon aria-hidden="true" />- </ComboboxPrimitive.ChipRemove>- );-}-const useComboboxFilter = ComboboxPrimitive.useFilter;export {Combobox,- ComboboxChipsInput,ComboboxInput,ComboboxSearchInput,ComboboxTrigger,ComboboxPopup,ComboboxItem,- ComboboxSeparator,- ComboboxGroup,- ComboboxGroupLabel,ComboboxEmpty,- ComboboxValue,ComboboxList,ComboboxListVirtualized,ComboboxClear,ComboboxStatus,- ComboboxRow,- ComboboxCollection,- ComboboxChips,- ComboboxChip,useComboboxFilter,};diff --git a/apps/web/src/components/ui/command.tsx b/apps/web/src/components/ui/command.tsxindex c1952e9c6f3..f8e9b72b1b4 100644--- a/apps/web/src/components/ui/command.tsx+++ b/apps/web/src/components/ui/command.tsx@@ -7,13 +7,11 @@ import { cn } from "~/lib/utils";import {Autocomplete,AutocompleteCollection,- AutocompleteEmpty,AutocompleteGroup,AutocompleteGroupLabel,AutocompleteInput,AutocompleteItem,AutocompleteList,- AutocompleteSeparator,} from "~/components/ui/autocomplete";import { DIALOG_BACKDROP_CLASS, DIALOG_POPUP_CLASS } from "~/components/ui/dialog-styles";import { Button } from "~/components/ui/button";@@ -22,8 +20,6 @@ const CommandDialog = CommandDialogPrimitive.Root;const CommandDialogPortal = CommandDialogPrimitive.Portal;-const CommandCreateHandle = CommandDialogPrimitive.createHandle;-function CommandDialogTrigger(props: CommandDialogPrimitive.Trigger.Props) {return <CommandDialogPrimitive.Trigger data-slot="command-dialog-trigger" {...props} />;}@@ -135,16 +131,6 @@ function CommandList({ className, ...props }: React.ComponentProps<typeof Autoco);}-function CommandEmpty({ className, ...props }: React.ComponentProps<typeof AutocompleteEmpty>) {- return (- <AutocompleteEmpty- className={cn("not-empty:py-6", className)}- data-slot="command-empty"- {...props}- />- );-}-function CommandPanel({ className, ...props }: React.ComponentProps<"div">) {return (<div@@ -187,19 +173,6 @@ function CommandItem({ className, ...props }: React.ComponentProps<typeof Autoco);}-function CommandSeparator({- className,- ...props-}: React.ComponentProps<typeof AutocompleteSeparator>) {- return (- <AutocompleteSeparator- className={cn("my-2", className)}- data-slot="command-separator"- {...props}- />- );-}-function CommandShortcut({ className, ...props }: React.ComponentProps<"kbd">) {return (<kbd@@ -241,13 +214,11 @@ function CommandFooterAction({}export {- CommandCreateHandle,Command,CommandCollection,CommandDialog,CommandDialogPopup,CommandDialogTrigger,- CommandEmpty,CommandFooter,CommandFooterAction,CommandGroup,@@ -256,6 +227,5 @@ export {CommandItem,CommandList,CommandPanel,- CommandSeparator,CommandShortcut,};diff --git a/apps/web/src/components/ui/dialog.tsx b/apps/web/src/components/ui/dialog.tsxindex 1a7c96e00f4..22ce5637204 100644--- a/apps/web/src/components/ui/dialog.tsx+++ b/apps/web/src/components/ui/dialog.tsx@@ -13,8 +13,6 @@ import {} from "~/components/ui/dialog-styles";import { ScrollArea } from "~/components/ui/scroll-area";-const DialogCreateHandle = DialogPrimitive.createHandle;-const Dialog = DialogPrimitive.Root;const DialogPortal = DialogPrimitive.Portal;@@ -184,7 +182,6 @@ function DialogPanel({}export {- DialogCreateHandle,Dialog,DialogTrigger,DialogPortal,diff --git a/apps/web/src/components/ui/group.tsx b/apps/web/src/components/ui/group.tsxindex 6eedfdda922..75d8fbe786a 100644--- a/apps/web/src/components/ui/group.tsx+++ b/apps/web/src/components/ui/group.tsx@@ -1,7 +1,4 @@"use client";--import { mergeProps } from "@base-ui/react/merge-props";-import { useRender } from "@base-ui/react/use-render";import { cva, type VariantProps } from "class-variance-authority";import type * as React from "react";@@ -48,21 +45,6 @@ function Group({);}-function GroupText({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn(- "relative inline-flex items-center whitespace-nowrap gap-2 rounded-lg border border-input bg-muted not-dark:bg-clip-padding px-[calc(--spacing(3)-1px)] text-muted-foreground text-base sm:text-sm shadow-xs/5 outline-none transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/6%)] dark:bg-input/64 dark:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 [&_svg]:-mx-0.5",- className,- ),- "data-slot": "group-text",- };- return useRender({- defaultTagName: "div",- props: mergeProps(defaultProps, props),- render,- });-}-function GroupSeparator({className,orientation = "vertical",@@ -85,8 +67,6 @@ function GroupSeparator({export {Group,Group as ButtonGroup,- GroupText,- GroupText as ButtonGroupText,GroupSeparator,GroupSeparator as ButtonGroupSeparator,groupVariants,diff --git a/apps/web/src/components/ui/input-group.tsx b/apps/web/src/components/ui/input-group.tsxindex 04e34e5611e..9a9228ede61 100644--- a/apps/web/src/components/ui/input-group.tsx+++ b/apps/web/src/components/ui/input-group.tsx@@ -5,7 +5,6 @@ import type * as React from "react";import { cn } from "~/lib/utils";import { Input, type InputProps } from "~/components/ui/input";-import { Textarea, type TextareaProps } from "~/components/ui/textarea";const inputGroupVariants = cva("relative inline-flex w-full min-w-0 items-center rounded-[var(--control-radius)] border text-base text-foreground ring-ring/24 transition-shadow has-[input:focus-visible,textarea:focus-visible]:has-[input[aria-invalid],textarea[aria-invalid]]:border-destructive/64 has-[input:focus-visible,textarea:focus-visible]:has-[input[aria-invalid],textarea[aria-invalid]]:ring-destructive/16 has-[textarea]:h-auto has-data-[align=block-end]:h-auto has-data-[align=block-start]:h-auto has-data-[align=block-end]:flex-col has-data-[align=block-start]:flex-col has-[input:focus-visible,textarea:focus-visible]:border-ring has-[input[aria-invalid],textarea[aria-invalid]]:border-destructive/36 has-autofill:bg-foreground/4 has-[input:disabled,textarea:disabled]:opacity-64 has-[input:disabled,textarea:disabled,input:focus-visible,textarea:focus-visible,input[aria-invalid],textarea[aria-invalid]]:shadow-none has-[input:focus-visible,textarea:focus-visible]:ring-[3px] sm:text-sm dark:has-autofill:bg-foreground/8 dark:has-[input[aria-invalid],textarea[aria-invalid]]:ring-destructive/24 has-data-[align=inline-start]:**:[[data-size=sm]_input]:ps-1.5 has-data-[align=inline-end]:**:[[data-size=sm]_input]:pe-1.5 *:[[data-slot=input-control],[data-slot=textarea-control]]:contents *:[[data-slot=input-control],[data-slot=textarea-control]]:before:hidden has-[[data-align=block-start],[data-align=block-end]]:**:[input]:h-auto has-data-[align=inline-start]:**:[input]:ps-2 has-data-[align=inline-end]:**:[input]:pe-2 has-data-[align=block-end]:**:[input]:pt-1.5 has-data-[align=block-start]:**:[input]:pb-1.5 **:[textarea]:min-h-20.5 **:[textarea]:resize-none **:[textarea]:py-[calc(--spacing(3)-1px)] **:[textarea]:max-sm:min-h-23.5 **:[textarea_button]:rounded-[calc(var(--control-radius)-1px)]",@@ -90,24 +89,8 @@ function InputGroupAddon({);}-function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {- return (- <span- className={cn(- "[&_svg]:-mx-0.5 line-clamp-1 flex items-center gap-2 text-muted-foreground leading-none in-[[data-slot=input-group]:has([data-slot=input-control],[data-slot=textarea-control])]:[&_svg:not([class*='size-'])]:size-4.5 sm:in-[[data-slot=input-group]:has([data-slot=input-control],[data-slot=textarea-control])]:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none",- className,- )}- {...props}- />- );-}-function InputGroupInput({ className, ...props }: InputProps) {return <Input className={className} unstyled {...props} />;}-function InputGroupTextarea({ className, ...props }: TextareaProps) {- return <Textarea className={className} unstyled {...props} />;-}--export { InputGroup, InputGroupAddon, InputGroupText, InputGroupInput, InputGroupTextarea };+export { InputGroup, InputGroupAddon, InputGroupInput };diff --git a/apps/web/src/components/ui/menu.tsx b/apps/web/src/components/ui/menu.tsxindex 6f35c1dc278..ffcf0f374c8 100644--- a/apps/web/src/components/ui/menu.tsx+++ b/apps/web/src/components/ui/menu.tsx@@ -7,12 +7,8 @@ import type * as React from "react";import { cn } from "~/lib/utils";import { buttonVariants } from "./button";-const MenuCreateHandle = MenuPrimitive.createHandle;-const Menu = MenuPrimitive.Root;-const MenuPortal = MenuPrimitive.Portal;-function MenuTrigger({ className, children, ...props }: MenuPrimitive.Trigger.Props) {return (<MenuPrimitive.Trigger className={className} data-slot="menu-trigger" {...props}>@@ -304,12 +300,8 @@ function MenuSubPopup({}export {- MenuCreateHandle,- MenuCreateHandle as DropdownMenuCreateHandle,Menu,Menu as DropdownMenu,- MenuPortal,- MenuPortal as DropdownMenuPortal,MenuTrigger,MenuTrigger as DropdownMenuTrigger,MenuPopup,diff --git a/apps/web/src/components/ui/number-field.tsx b/apps/web/src/components/ui/number-field.tsxindex 4b348f2ffed..e1a758b0571 100644--- a/apps/web/src/components/ui/number-field.tsx+++ b/apps/web/src/components/ui/number-field.tsx@@ -4,13 +4,6 @@ import { NumberField as NumberFieldPrimitive } from "@base-ui/react/number-fieldimport { MinusIcon, PlusIcon } from "lucide-react";import * as React from "react";import { cn } from "~/lib/utils";-import { Label } from "~/components/ui/label";--export const NumberFieldContext: React.Context<{- fieldId: string;-} | null> = React.createContext<{- fieldId: string;-} | null>(null);export function NumberField({id,@@ -22,18 +15,14 @@ export function NumberField({}): React.ReactElement {const generatedId = React.useId();const fieldId = id ?? generatedId;- const contextValue = React.useMemo(() => ({ fieldId }), [fieldId]);-return (- <NumberFieldContext value={contextValue}>- <NumberFieldPrimitive.Root- className={cn("flex w-full flex-col items-start gap-2", className)}- data-size={size}- data-slot="number-field"- id={fieldId}- {...props}- />- </NumberFieldContext>+ <NumberFieldPrimitive.Root+ className={cn("flex w-full flex-col items-start gap-2", className)}+ data-size={size}+ data-slot="number-field"+ id={fieldId}+ {...props}+ />);}@@ -105,52 +94,4 @@ export function NumberFieldInput({);}-export function NumberFieldScrubArea({- className,- label,- ...props-}: NumberFieldPrimitive.ScrubArea.Props & {- label: string;-}): React.ReactElement {- const context = React.use(NumberFieldContext);-- if (!context) {- throw new Error(- "NumberFieldScrubArea must be used within a NumberField component for accessibility.",- );- }-- return (- <NumberFieldPrimitive.ScrubArea- className={cn("flex cursor-ew-resize", className)}- data-slot="number-field-scrub-area"- {...props}- >- <Label className="cursor-ew-resize" htmlFor={context.fieldId}>- {label}- </Label>- <NumberFieldPrimitive.ScrubAreaCursor className="drop-shadow-[0_1px_1px_#0008] filter">- <CursorGrowIcon />- </NumberFieldPrimitive.ScrubAreaCursor>- </NumberFieldPrimitive.ScrubArea>- );-}--export function CursorGrowIcon(props: React.ComponentProps<"svg">): React.ReactElement {- return (- <svg- aria-hidden="true"- fill="black"- height="14"- stroke="white"- viewBox="0 0 24 14"- width="26"- xmlns="http://www.w3.org/2000/svg"- {...props}- >- <path d="M19.5 5.5L6.49737 5.51844V2L1 6.9999L6.5 12L6.49737 8.5L19.5 8.5V12L25 6.9999L19.5 2V5.5Z" />- </svg>- );-}-export { NumberFieldPrimitive };diff --git a/apps/web/src/components/ui/popover.tsx b/apps/web/src/components/ui/popover.tsxindex 9534112e4e7..4bc76706ab2 100644--- a/apps/web/src/components/ui/popover.tsx+++ b/apps/web/src/components/ui/popover.tsx@@ -91,16 +91,6 @@ function PopoverTitle({ className, ...props }: PopoverPrimitive.Title.Props) {);}-function PopoverDescription({ className, ...props }: PopoverPrimitive.Description.Props) {- return (- <PopoverPrimitive.Description- className={cn("text-muted-foreground text-sm", className)}- data-slot="popover-description"- {...props}- />- );-}-export {PopoverCreateHandle,Popover,@@ -108,6 +98,5 @@ export {PopoverPopup,PopoverPopup as PopoverContent,PopoverTitle,- PopoverDescription,PopoverClose,};diff --git a/apps/web/src/components/ui/select.tsx b/apps/web/src/components/ui/select.tsxindex 46b2c8eb1ba..a7ab17eb928 100644--- a/apps/web/src/components/ui/select.tsx+++ b/apps/web/src/components/ui/select.tsx@@ -1,10 +1,7 @@"use client";--import { mergeProps } from "@base-ui/react/merge-props";import { Select as SelectPrimitive } from "@base-ui/react/select";-import { useRender } from "@base-ui/react/use-render";import { cva, type VariantProps } from "class-variance-authority";-import { ChevronDownIcon, ChevronsUpDownIcon, ChevronUpIcon } from "lucide-react";+import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";import type * as React from "react";import { cn } from "~/lib/utils";@@ -37,41 +34,6 @@ const selectTriggerVariants = cva(},);-const selectTriggerIconClassName = "-me-1 size-4.5 opacity-80 sm:size-4";--interface SelectButtonProps extends useRender.ComponentProps<"button"> {- size?: VariantProps<typeof selectTriggerVariants>["size"];- variant?: VariantProps<typeof selectTriggerVariants>["variant"];-}--function SelectButton({ className, size, variant, render, children, ...props }: SelectButtonProps) {- const typeValue: React.ButtonHTMLAttributes<HTMLButtonElement>["type"] = render- ? undefined- : "button";-- const defaultProps = {- children: (- <>- <span className="flex-1 truncate in-data-placeholder:text-placeholder">{children}</span>- {variant === "ghost" ? (- <ChevronDownIcon className="-me-1 size-3 opacity-50" />- ) : (- <ChevronsUpDownIcon className={selectTriggerIconClassName} />- )}- </>- ),- className: cn(selectTriggerVariants({ size, variant }), "min-w-none", className),- "data-slot": "select-button",- type: typeValue,- };-- return useRender({- defaultTagName: "button",- props: mergeProps<"button">(defaultProps, props),- render,- });-}-function SelectTrigger({className,size = "default",@@ -203,16 +165,6 @@ function SelectItem({);}-function SelectSeparator({ className, ...props }: SelectPrimitive.Separator.Props) {- return (- <SelectPrimitive.Separator- className={cn("mx-2 my-1 h-px bg-border", className)}- data-slot="select-separator"- {...props}- />- );-}-function SelectGroup(props: SelectPrimitive.Group.Props) {return <SelectPrimitive.Group data-slot="select-group" {...props} />;}@@ -230,13 +182,11 @@ function SelectGroupLabel(props: SelectPrimitive.GroupLabel.Props) {export {Select,SelectTrigger,- SelectButton,selectTriggerVariants,SelectValue,SelectPopup,SelectPopup as SelectContent,SelectItem,- SelectSeparator,SelectGroup,SelectGroupLabel,};diff --git a/apps/web/src/components/ui/sheet.tsx b/apps/web/src/components/ui/sheet.tsxindex f7711da8003..0b68ff11648 100644--- a/apps/web/src/components/ui/sheet.tsx+++ b/apps/web/src/components/ui/sheet.tsx@@ -5,20 +5,11 @@ import { XIcon } from "lucide-react";import type { CSSProperties } from "react";import { cn } from "~/lib/utils";import { Button } from "~/components/ui/button";-import { ScrollArea } from "~/components/ui/scroll-area";const Sheet = SheetPrimitive.Root;const SheetPortal = SheetPrimitive.Portal;-function SheetTrigger(props: SheetPrimitive.Trigger.Props) {- return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;-}--function SheetClose(props: SheetPrimitive.Close.Props) {- return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;-}-function SheetBackdrop({ className, ...props }: SheetPrimitive.Backdrop.Props) {return (<SheetPrimitive.Backdrop@@ -146,28 +137,6 @@ function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {);}-function SheetFooter({- className,- variant = "default",- ...props-}: React.ComponentProps<"div"> & {- variant?: "default" | "bare";-}) {- return (- <div- className={cn(- "flex flex-col-reverse gap-2 px-6 sm:flex-row sm:justify-end",- variant === "default" && "border-t bg-muted/72 py-4",- variant === "bare" &&- "in-[[data-slot=sheet-popup]:has([data-slot=sheet-panel])]:pt-3 pt-4 pb-6",- className,- )}- data-slot="sheet-footer"- {...props}- />- );-}-function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) {return (<SheetPrimitive.Title@@ -188,37 +157,14 @@ function SheetDescription({ className, ...props }: SheetPrimitive.Description.Pr);}-function SheetPanel({- className,- scrollFade = true,- ...props-}: React.ComponentProps<"div"> & { scrollFade?: boolean }) {- return (- <ScrollArea scrollFade={scrollFade}>- <div- className={cn(- "p-6 in-[[data-slot=sheet-popup]:has([data-slot=sheet-header])]:pt-1 in-[[data-slot=sheet-popup]:has([data-slot=sheet-footer]:not(.border-t))]:pb-1",- className,- )}- data-slot="sheet-panel"- {...props}- />- </ScrollArea>- );-}-export {Sheet,- SheetTrigger,SheetPortal,- SheetClose,SheetBackdrop,SheetBackdrop as SheetOverlay,SheetPopup,SheetPopup as SheetContent,SheetHeader,- SheetFooter,SheetTitle,SheetDescription,- SheetPanel,};diff --git a/apps/web/src/components/ui/sidebar.test.tsx b/apps/web/src/components/ui/sidebar.test.tsxindex 784c5e08796..1a3113d5216 100644--- a/apps/web/src/components/ui/sidebar.test.tsx+++ b/apps/web/src/components/ui/sidebar.test.tsx@@ -1,23 +1,8 @@-import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vite-plus/test";-import {- SidebarMenuButton,- SidebarMenuSubButton,- SidebarProvider,- SidebarTrigger,-} from "./sidebar";import { resolveSidebarState } from "./sidebarState";-function renderSidebarButton(className?: string) {- return renderToStaticMarkup(- <SidebarProvider>- <SidebarMenuButton className={className}>Projects</SidebarMenuButton>- </SidebarProvider>,- );-}--describe("sidebar interactive cursors", () => {+describe("responsive sidebar state", () => {it("uses mobile sheet visibility for the shared responsive state", () => {expect(resolveSidebarState({ isMobile: true, open: true, openMobile: false })).toBe("collapsed",@@ -27,73 +12,4 @@ describe("sidebar interactive cursors", () => {"expanded",);});-- it("exposes collapsed state for shared titlebar inset styling", () => {- const html = renderToStaticMarkup(- <SidebarProvider defaultOpen={false}>- <div />- </SidebarProvider>,- );-- expect(html).toContain('data-sidebar-state="collapsed"');- });-- it("keeps the sidebar trigger interactive inside Electron drag regions", () => {- const html = renderToStaticMarkup(- <SidebarProvider>- <SidebarTrigger />- </SidebarProvider>,- );-- expect(html).toContain("[-webkit-app-region:no-drag]");- expect(html).toContain("size-[var(--workspace-titlebar-control-size)]!");- });-- it("uses shared geometry and icon constraints for menu buttons by default", () => {- const html = renderSidebarButton();-- expect(html).toContain('data-slot="sidebar-menu-button"');- expect(html).toContain("h-8");- expect(html).toContain("rounded-[var(--control-radius)]");- expect(html).toContain("px-[var(--sidebar-row-content-inset)]");- expect(html).toContain("py-1.5");- expect(html).toContain("]:size-4");- expect(html).toContain("]:shrink-0");- expect(html).toContain("cursor-pointer");- expect(html).toContain("gap-[var(--sidebar-control-gap)]");- expect(html).toContain("text-[var(--sidebar-icon-color)]");- expect(html).not.toContain("[&>svg]:opacity-60");- });-- it("applies the shared default treatment to icon-only menu buttons", () => {- const html = renderToStaticMarkup(- <SidebarProvider>- <SidebarMenuButton size="icon">- <span>+</span>- </SidebarMenuButton>- </SidebarProvider>,- );-- expect(html).toContain("size-8");- expect(html).toContain("justify-center");- expect(html).toContain("p-0");- expect(html).toContain("font-medium");- expect(html).toContain("text-sidebar-muted-foreground/80");- });-- it("lets project drag handles override the default pointer cursor", () => {- const html = renderSidebarButton("cursor-grab");-- expect(html).toContain("cursor-grab");- expect(html).not.toContain("cursor-pointer");- });-- it("uses a pointer cursor for submenu buttons", () => {- const html = renderToStaticMarkup(- <SidebarMenuSubButton render={<button type="button" />}>Show more</SidebarMenuSubButton>,- );-- expect(html).toContain('data-slot="sidebar-menu-sub-button"');- expect(html).toContain("cursor-pointer");- });});diff --git a/apps/web/src/components/ui/sidebar.tsx b/apps/web/src/components/ui/sidebar.tsxindex 307feda7abf..32405fe72b0 100644--- a/apps/web/src/components/ui/sidebar.tsx+++ b/apps/web/src/components/ui/sidebar.tsx@@ -5,9 +5,7 @@ import { PanelLeftCloseIcon, PanelLeftIcon } from "lucide-react";import * as React from "react";import { cn } from "~/lib/utils";import { Button } from "~/components/ui/button";-import { Input } from "~/components/ui/input";import { ScrollArea } from "~/components/ui/scroll-area";-import { Separator } from "~/components/ui/separator";import {Sheet,SheetDescription,@@ -15,7 +13,6 @@ import {SheetPopup,SheetTitle,} from "~/components/ui/sheet";-import { Skeleton } from "~/components/ui/skeleton";import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";import { useResizeDrag } from "~/hooks/useResizeDrag";import { useIsMobile } from "~/hooks/useMediaQuery";@@ -544,17 +541,6 @@ function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {);}-function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {- return (- <Input- className={cn("h-8 w-full bg-background shadow-none", className)}- data-sidebar="input"- data-slot="sidebar-input"- {...props}- />- );-}-function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {return (<div@@ -577,17 +563,6 @@ function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {);}-function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {- return (- <Separator- className={cn("mx-2 w-auto! bg-sidebar-border", className)}- data-sidebar="separator"- data-slot="sidebar-separator"- {...props}- />- );-}-function SidebarContent({className,fixedHeader,@@ -635,55 +610,6 @@ function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {);}-function SidebarGroupLabel({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn(- "flex h-8 shrink-0 items-center rounded-lg px-2 font-medium text-sidebar-foreground text-xs outline-hidden ring-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",- "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",- className,- ),- "data-sidebar": "group-label",- "data-slot": "sidebar-group-label",- };-- return useRender({- defaultTagName: "div",- props: mergeProps(defaultProps, props),- render,- });-}--function SidebarGroupAction({ className, render, ...props }: useRender.ComponentProps<"button">) {- const defaultProps = {- className: cn(- "absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-ring transition-transform hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",- // Increases the hit area of the button on mobile.- "after:-inset-2 after:absolute md:after:hidden",- "group-data-[collapsible=icon]:hidden",- className,- ),- "data-sidebar": "group-action",- "data-slot": "sidebar-group-action",- };-- return useRender({- defaultTagName: "button",- props: mergeProps(defaultProps, props),- render,- });-}--function SidebarGroupContent({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- className={cn("w-full text-sm", className)}- data-sidebar="group-content"- data-slot="sidebar-group-content"- {...props}- />- );-}-function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {return (<ul@@ -782,58 +708,6 @@ function SidebarMenuButton({);}-function SidebarMenuBadge({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- className={cn(- "pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-lg px-1 font-medium text-sidebar-foreground text-xs tabular-nums",- "peer-hover/menu-button:text-sidebar-foreground peer-data-[active=true]/menu-button:text-sidebar-foreground",- "peer-data-[size=sm]/menu-button:top-1",- "peer-data-[size=default]/menu-button:top-1.5",- "peer-data-[size=lg]/menu-button:top-2.5",- "group-data-[collapsible=icon]:hidden",- className,- )}- data-sidebar="menu-badge"- data-slot="sidebar-menu-badge"- {...props}- />- );-}--function SidebarMenuSkeleton({- className,- showIcon = false,- ...props-}: React.ComponentProps<"div"> & {- showIcon?: boolean;-}) {- // Random width between 50 to 90%. Intentionally wrapped in useMemo to avoid changing width on every render.- const width = React.useMemo(() => {- return `${Math.floor(Math.random() * 40) + 50}%`;- }, []);-- return (- <div- className={cn("flex h-8 items-center gap-2 rounded-lg px-2", className)}- data-sidebar="menu-skeleton"- data-slot="sidebar-menu-skeleton"- {...props}- >- {showIcon && <Skeleton className="size-4 rounded-lg" data-sidebar="menu-skeleton-icon" />}- <Skeleton- className="h-4 max-w-(--skeleton-width) flex-1"- data-sidebar="menu-skeleton-text"- style={- {- "--skeleton-width": width,- } as React.CSSProperties- }- />- </div>- );-}-function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {return (<ul@@ -897,23 +771,16 @@ export {SidebarContent,SidebarFooter,SidebarGroup,- SidebarGroupAction,- SidebarGroupContent,- SidebarGroupLabel,SidebarHeader,- SidebarInput,SidebarInset,SidebarMenu,- SidebarMenuBadge,SidebarMenuButton,SidebarMenuItem,- SidebarMenuSkeleton,SidebarMenuSub,SidebarMenuSubButton,SidebarMenuSubItem,SidebarProvider,SidebarRail,- SidebarSeparator,SidebarTrigger,useSidebar,useSidebarVisibility,diff --git a/apps/web/src/components/ui/table.tsx b/apps/web/src/components/ui/table.tsxindex d3600f86993..d9ae0618071 100644--- a/apps/web/src/components/ui/table.tsx+++ b/apps/web/src/components/ui/table.tsx@@ -28,16 +28,6 @@ function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {);}-function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {- return (- <tfoot- data-slot="table-footer"- className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)}- {...props}- />- );-}-function TableRow({ className, ...props }: React.ComponentProps<"tr">) {return (<tr@@ -74,14 +64,4 @@ function TableCell({ className, ...props }: React.ComponentProps<"td">) {);}-function TableCaption({ className, ...props }: React.ComponentProps<"caption">) {- return (- <caption- data-slot="table-caption"- className={cn("mt-4 text-xs text-muted-foreground", className)}- {...props}- />- );-}--export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };+export { Table, TableHeader, TableBody, TableHead, TableRow, TableCell };diff --git a/apps/web/src/components/ui/toggle-group.tsx b/apps/web/src/components/ui/toggle-group.tsxindex 23501ec7a96..846a34a1086 100644--- a/apps/web/src/components/ui/toggle-group.tsx+++ b/apps/web/src/components/ui/toggle-group.tsx@@ -6,7 +6,6 @@ import type { VariantProps } from "class-variance-authority";import * as React from "react";import { cn } from "~/lib/utils";-import { Separator } from "~/components/ui/separator";import { Toggle as ToggleComponent, type toggleVariants } from "~/components/ui/toggle";const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({@@ -76,23 +75,4 @@ function Toggle({);}-function ToggleGroupSeparator({- className,- orientation = "vertical",- ...props-}: {- className?: string;-} & React.ComponentProps<typeof Separator>) {- return (- <Separator- className={cn(- "pointer-events-none relative bg-input before:absolute before:inset-0 dark:before:bg-input/32",- className,- )}- orientation={orientation}- {...props}- />- );-}--export { ToggleGroup, Toggle, Toggle as ToggleGroupItem, ToggleGroupSeparator };+export { ToggleGroup, Toggle, Toggle as ToggleGroupItem };diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsxindex 77b15a01e16..c0aaea40cea 100644--- a/apps/web/src/components/ui/tooltip.tsx+++ b/apps/web/src/components/ui/tooltip.tsx@@ -2,8 +2,6 @@ import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip";import { cn } from "~/lib/utils";-const TooltipCreateHandle = TooltipPrimitive.createHandle;-const TooltipProvider = TooltipPrimitive.Provider;const Tooltip = TooltipPrimitive.Root;@@ -61,4 +59,4 @@ function TooltipPopup({);}-export { TooltipCreateHandle, TooltipProvider, Tooltip, TooltipTrigger, TooltipPopup };+export { TooltipProvider, Tooltip, TooltipTrigger, TooltipPopup };diff --git a/apps/web/src/providerInstances.test.ts b/apps/web/src/providerInstances.test.tsindex 3e809e17f58..cfd834a5654 100644--- a/apps/web/src/providerInstances.test.ts+++ b/apps/web/src/providerInstances.test.ts@@ -9,7 +9,6 @@ import {isProviderInstancePickerVisible,resolveDefaultProviderModelSelection,resolveSelectableProviderInstance,- resolveProviderDriverKindForInstanceSelection,} from "./providerInstances";function provider(input: {@@ -362,44 +361,6 @@ describe("resolveSelectableProviderInstance", () => {});});-describe("resolveProviderDriverKindForInstanceSelection", () => {- it("maps custom provider instance ids back to their driver kind", () => {- const providers = [- provider({ provider: ProviderDriverKind.make("codex"), instanceId: "codex" }),- provider({- provider: ProviderDriverKind.make("claudeAgent"),- instanceId: "claude_openrouter",- displayName: "Claude OpenRouter",- }),- ];- const entries = deriveProviderInstanceEntries(providers);-- expect(- resolveProviderDriverKindForInstanceSelection(- entries,- providers,- ProviderInstanceId.make("claude_openrouter"),- ),- ).toBe("claudeAgent");- });-- it("does not guess a provider kind when the instance selection is unknown", () => {- const providers = [- provider({ provider: ProviderDriverKind.make("codex"), instanceId: "codex", enabled: false }),- provider({ provider: ProviderDriverKind.make("claudeAgent"), instanceId: "claudeAgent" }),- ];- const entries = deriveProviderInstanceEntries(providers);-- expect(- resolveProviderDriverKindForInstanceSelection(- entries,- providers,- ProviderInstanceId.make("removed_instance"),- ),- ).toBeUndefined();- });-});-describe("getDefaultProviderInstanceModel", () => {it("uses the instance's own models, not the default instance of the kind", () => {const providers = [diff --git a/apps/web/src/providerInstances.ts b/apps/web/src/providerInstances.tsindex 9230ab0a489..88ea8a25724 100644--- a/apps/web/src/providerInstances.ts+++ b/apps/web/src/providerInstances.ts@@ -298,21 +298,3 @@ export function resolveDefaultProviderModelSelection(const model = getDefaultProviderInstanceModel(providers, instanceId);return model ? { instanceId, model } : null;}--/**- * Resolve an open model-selection routing key back to a driver kind.- * Custom instance ids such as `claude_openrouter` are not themselves- * driver-kind slugs, but the composer still needs the owning driver kind- * for capabilities, options, icons, and turn dispatch metadata.- */-export function resolveProviderDriverKindForInstanceSelection(- entries: ReadonlyArray<ProviderInstanceEntry>,- providers: ReadonlyArray<ServerProvider>,- selection: ProviderInstanceId | ProviderDriverKind | null | undefined,-): ProviderDriverKind | undefined {- const matchedEntry = entries.find((entry) => entry.instanceId === selection);- if (matchedEntry) {- return matchedEntry.driverKind;- }- return undefined;-}diff --git a/apps/web/src/types.ts b/apps/web/src/types.tsindex 41ed6560fe5..381333fd29a 100644--- a/apps/web/src/types.ts+++ b/apps/web/src/types.ts@@ -5,7 +5,6 @@ import type {ChatUnknownAttachment as ContractChatUnknownAttachment,OrchestrationCheckpointFile,OrchestrationCheckpointSummary,- OrchestrationLatestTurn,OrchestrationMessage,OrchestrationProposedPlan,OrchestrationSession,@@ -86,9 +85,5 @@ export type Project = EnvironmentProject;export type Thread = EnvironmentThread;export type ThreadShell = EnvironmentThreadShell;-export interface ThreadTurnState {- latestTurn: OrchestrationLatestTurn | null;-}-export type SidebarThreadSummary = EnvironmentThreadShell;export type ThreadSession = OrchestrationSession;diff --git a/apps/web/src/vite-plus-browser-matchers.d.ts b/apps/web/src/vite-plus-browser-matchers.d.tsdeleted file mode 100644index 5f600145e4e..00000000000--- a/apps/web/src/vite-plus-browser-matchers.d.ts+++ /dev/null@@ -1,11 +0,0 @@-import type { ExpectPollOptions } from "vite-plus/test";-import type { Locator } from "vite-plus/test/browser";--declare module "vite-plus/test" {- interface ExpectStatic {- element: (- element: HTMLElement | SVGElement | null | Locator,- options?: ExpectPollOptions,- ) => any;- }-}diff --git a/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts b/infra/relay/src/agentActivity/AgentActivityPublisher.test.tsindex ae3d4e4ad24..366e387f1e6 100644--- a/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts+++ b/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts@@ -84,7 +84,6 @@ function makeEnvironmentLinks(): EnvironmentLinks.EnvironmentLinks["Service"] {return {upsert: () => Effect.void,- listUsersForEnvironment: () => Effect.succeed(["dev:julius"]),listDeliveryUsersForEnvironment: () =>Effect.succeed([{@@ -93,7 +92,6 @@ function makeEnvironmentLinks(liveActivitiesEnabled: true,},]),- listPublicKeysForEnvironment: () => Effect.succeed([]),listForUser: () => Effect.succeed([]),getForUser: () => Effect.succeed(null),revokeForUser: () => Effect.succeed(false),diff --git a/infra/relay/src/agentActivity/ApnsClient.ts b/infra/relay/src/agentActivity/ApnsClient.tsindex 17a2fe197b1..93c47af02e3 100644--- a/infra/relay/src/agentActivity/ApnsClient.ts+++ b/infra/relay/src/agentActivity/ApnsClient.ts@@ -9,7 +9,7 @@ import * as HttpClient from "effect/unstable/http/HttpClient";import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";import { ApnsEnvironment as ApnsEnvironmentSchema, type ApnsCredentials } from "../Config.ts";import type { ApnsLiveActivityAlert, ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";-import { ApnsJwtEncodingError, ApnsJwtSigningError } from "./apnsJwt.ts";+import type { ApnsJwtEncodingError, ApnsJwtSigningError } from "./apnsJwt.ts";import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";export { ApnsJwtEncodingError, ApnsJwtSigningError } from "./apnsJwt.ts";@@ -71,12 +71,7 @@ export class ApnsHttpRequestError extends Schema.TaggedError<ApnsHttpRequestErro}}-export const ApnsError = Schema.Union([- ApnsJwtEncodingError,- ApnsJwtSigningError,- ApnsHttpRequestError,-]);-export type ApnsError = typeof ApnsError.Type;+export type ApnsError = ApnsJwtEncodingError | ApnsJwtSigningError | ApnsHttpRequestError;const decodeApnsErrorResponseJson = Schema.decodeUnknownOption(Schema.fromJsonString(diff --git a/infra/relay/src/agentActivity/FcmDeliveries.test.ts b/infra/relay/src/agentActivity/FcmDeliveries.test.tsindex 73b90f99b0a..8f061fca16f 100644--- a/infra/relay/src/agentActivity/FcmDeliveries.test.ts+++ b/infra/relay/src/agentActivity/FcmDeliveries.test.ts@@ -162,7 +162,6 @@ function harness() {}),Layer.succeed(EnvironmentLinks, {upsert: () => Effect.void,- listUsersForEnvironment: () => Effect.succeed(["user"]),listDeliveryUsersForEnvironment: (input) =>Effect.sync(() =>current.linked && !current.revokedEnvironments.includes(input.environmentId)@@ -177,7 +176,6 @@ function harness() {]: [],),- listPublicKeysForEnvironment: () => Effect.succeed([]),listForUser: () => Effect.succeed([]),revokeForUser: () => Effect.succeed(false),getForUser: (input) =>diff --git a/infra/relay/src/agentActivity/MobileRegistrations.test.ts b/infra/relay/src/agentActivity/MobileRegistrations.test.tsindex 74d5c3740a5..457a545f74b 100644--- a/infra/relay/src/agentActivity/MobileRegistrations.test.ts+++ b/infra/relay/src/agentActivity/MobileRegistrations.test.ts@@ -106,7 +106,6 @@ function makeEnvironmentLinks(): EnvironmentLinks.EnvironmentLinks["Service"] {return {upsert: () => Effect.void,- listUsersForEnvironment: () => Effect.succeed(["dev:julius"]),listDeliveryUsersForEnvironment: () =>Effect.succeed([{@@ -115,7 +114,6 @@ function makeEnvironmentLinks(liveActivitiesEnabled: true,},]),- listPublicKeysForEnvironment: () => Effect.succeed([]),listForUser: () => Effect.succeed([]),getForUser: () => Effect.succeed(null),revokeForUser: () => Effect.succeed(false),diff --git a/infra/relay/src/environments/EnvironmentConnector.test.ts b/infra/relay/src/environments/EnvironmentConnector.test.tsindex 7f536bafb37..da6f4acc192 100644--- a/infra/relay/src/environments/EnvironmentConnector.test.ts+++ b/infra/relay/src/environments/EnvironmentConnector.test.ts@@ -209,9 +209,7 @@ function makeLinks(): EnvironmentLinks.EnvironmentLinks["Service"] {return {upsert: () => Effect.void,- listUsersForEnvironment: () => Effect.succeed([]),listDeliveryUsersForEnvironment: () => Effect.succeed([]),- listPublicKeysForEnvironment: () => Effect.succeed([environmentKeyPair.publicKey]),listForUser: () => Effect.succeed([]),getForUser: () =>Effect.succeed({diff --git a/infra/relay/src/environments/EnvironmentLinker.test.ts b/infra/relay/src/environments/EnvironmentLinker.test.tsindex c0811e82d92..78412e6c138 100644--- a/infra/relay/src/environments/EnvironmentLinker.test.ts+++ b/infra/relay/src/environments/EnvironmentLinker.test.ts@@ -123,9 +123,7 @@ function testLayer(input?: {}),Layer.succeed(EnvironmentLinks.EnvironmentLinks, {upsert: input?.upsert ?? (() => Effect.void),- listUsersForEnvironment: () => Effect.succeed([]),listDeliveryUsersForEnvironment: () => Effect.succeed([]),- listPublicKeysForEnvironment: () => Effect.succeed([]),listForUser: () => Effect.succeed([]),getForUser: () => Effect.succeed(null),revokeForUser: () => Effect.succeed(false),diff --git a/infra/relay/src/environments/EnvironmentLinks.test.ts b/infra/relay/src/environments/EnvironmentLinks.test.tsindex dccb9e39f60..0a856bcaf7f 100644--- a/infra/relay/src/environments/EnvironmentLinks.test.ts+++ b/infra/relay/src/environments/EnvironmentLinks.test.ts@@ -66,7 +66,7 @@ describe("EnvironmentLinks", () => {expect(error).toMatchObject({_tag: "EnvironmentLinkUserListPersistenceError",- operation: "list-delivery-users",+ message: "Environment link user query 'list-delivery-users' failed for environment 'env-1'",environmentId: "env-1",});expect(error.cause).toBe(cause);@@ -78,7 +78,7 @@ describe("EnvironmentLinks", () => {);});- it.effect("selects users when either notifications or Live Activities are enabled", () => {+ it.effect("selects notification or Live Activity users by environment key", () => {const whereConditions: Array<unknown> = [];const fakeDb = {select: (selection: unknown) => {@@ -99,7 +99,12 @@ describe("EnvironmentLinks", () => {return Effect.gen(function* () {const links = yield* EnvironmentLinks.EnvironmentLinks;- expect(yield* links.listUsersForEnvironment({ environmentId: "env-1" })).toEqual([]);+ expect(+ yield* links.listDeliveryUsersForEnvironment({+ environmentId: "env-1",+ environmentPublicKey: "public-key-1",+ }),+ ).toEqual([]);expect(whereConditions).toHaveLength(1);const query = new PgDialect().sqlToQuery(whereConditions[0] as never);@@ -107,8 +112,9 @@ describe("EnvironmentLinks", () => {expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');expect(query.sql).toContain('"relay_environment_links"."notifications_enabled" = $2');expect(query.sql).toContain('"relay_environment_links"."live_activities_enabled" = $3');+ expect(query.sql).toContain('"relay_environment_links"."environment_public_key" = $4');expect(query.sql).toContain(" or ");- expect(query.params).toEqual(["env-1", true, true]);+ expect(query.params).toEqual(["env-1", true, true, "public-key-1"]);}).pipe(Effect.provide(EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),diff --git a/infra/relay/src/environments/EnvironmentLinks.ts b/infra/relay/src/environments/EnvironmentLinks.tsindex 58347245d64..f41794d6053 100644--- a/infra/relay/src/environments/EnvironmentLinks.ts+++ b/infra/relay/src/environments/EnvironmentLinks.ts@@ -41,25 +41,12 @@ export class EnvironmentLinkUpsertPersistenceError extends Schema.TaggedError<Enexport class EnvironmentLinkUserListPersistenceError extends Schema.TaggedError<EnvironmentLinkUserListPersistenceError>()("EnvironmentLinkUserListPersistenceError",{- operation: Schema.Literals(["list-users", "list-delivery-users"]),environmentId: Schema.String,cause: Schema.Defect(),},) {override get message(): string {- return `Environment link user query '${this.operation}' failed for environment '${this.environmentId}'`;- }-}--export class EnvironmentPublicKeyListPersistenceError extends Schema.TaggedError<EnvironmentPublicKeyListPersistenceError>()(- "EnvironmentPublicKeyListPersistenceError",- {- environmentId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to list public keys for environment '${this.environmentId}'`;+ return `Environment link user query 'list-delivery-users' failed for environment '${this.environmentId}'`;}}@@ -110,9 +97,6 @@ export class EnvironmentLinks extends Context.Service<readonly proof: RelayEnvironmentLinkProofPayload;readonly endpoint: RelayManagedEndpoint;}) => Effect.Effect<void, EnvironmentLinkUpsertPersistenceError>;- readonly listUsersForEnvironment: (input: {- readonly environmentId: string;- }) => Effect.Effect<ReadonlyArray<string>, EnvironmentLinkUserListPersistenceError>;readonly listDeliveryUsersForEnvironment: (input: {readonly environmentId: string;readonly environmentPublicKey: string;@@ -120,9 +104,6 @@ export class EnvironmentLinks extends Context.Service<ReadonlyArray<AgentAwarenessDeliveryUserRecord>,EnvironmentLinkUserListPersistenceError>;- readonly listPublicKeysForEnvironment: (input: {- readonly environmentId: string;- }) => Effect.Effect<ReadonlyArray<string>, EnvironmentPublicKeyListPersistenceError>;readonly listForUser: (input: {readonly userId: string;}) => Effect.Effect<@@ -140,23 +121,17 @@ export class EnvironmentLinks extends Context.Service<}>()("t3code-relay/environments/EnvironmentLinks") {}-function agentAwarenessDeliveryUserCondition(environmentId: string) {+function agentAwarenessDeliveryUserKeyCondition(input: {+ readonly environmentId: string;+ readonly environmentPublicKey: string;+}) {return and(- eq(relayEnvironmentLinks.environmentId, environmentId),+ eq(relayEnvironmentLinks.environmentId, input.environmentId),isNull(relayEnvironmentLinks.revokedAt),or(eq(relayEnvironmentLinks.notificationsEnabled, true),eq(relayEnvironmentLinks.liveActivitiesEnabled, true),),- );-}--function agentAwarenessDeliveryUserKeyCondition(input: {- readonly environmentId: string;- readonly environmentPublicKey: string;-}) {- return and(- agentAwarenessDeliveryUserCondition(input.environmentId),eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),);}@@ -220,27 +195,6 @@ const make = Effect.gen(function* () {);}),- listUsersForEnvironment: Effect.fn("relay.environment_links.list_users_for_environment")(- function* (input) {- yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });- return yield* db- .select({ userId: relayEnvironmentLinks.userId })- .from(relayEnvironmentLinks)- .where(agentAwarenessDeliveryUserCondition(input.environmentId))- .pipe(- Effect.map((rows) => rows.map((row) => row.userId)),- Effect.mapError(- (cause) =>- new EnvironmentLinkUserListPersistenceError({- operation: "list-users",- environmentId: input.environmentId,- cause,- }),- ),- );- },- ),-listDeliveryUsersForEnvironment: Effect.fn("relay.environment_links.list_delivery_users_for_environment",)(function* (input) {@@ -264,34 +218,6 @@ const make = Effect.gen(function* () {Effect.mapError((cause) =>new EnvironmentLinkUserListPersistenceError({- operation: "list-delivery-users",- environmentId: input.environmentId,- cause,- }),- ),- );- }),-- listPublicKeysForEnvironment: Effect.fn(- "relay.environment_links.list_public_keys_for_environment",- )(function* (input) {- yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });- return yield* db- .select({ environmentPublicKey: relayEnvironmentLinks.environmentPublicKey })- .from(relayEnvironmentLinks)- .where(- and(- eq(relayEnvironmentLinks.environmentId, input.environmentId),- isNull(relayEnvironmentLinks.revokedAt),- ),- )- .pipe(- Effect.map((rows) => [- ...new Set(rows.map((row) => row.environmentPublicKey).filter((key) => key.length > 0)),- ]),- Effect.mapError(- (cause) =>- new EnvironmentPublicKeyListPersistenceError({environmentId: input.environmentId,cause,}),diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.tsindex edaf1d08ed7..af220de5261 100644--- a/infra/relay/src/http/Api.test.ts+++ b/infra/relay/src/http/Api.test.ts@@ -319,9 +319,7 @@ function relayUnlinkTestLayer(input?: {EnvironmentLinks.EnvironmentLinks,EnvironmentLinks.EnvironmentLinks.of({upsert: () => Effect.die("unused upsert"),- listUsersForEnvironment: () => Effect.die("unused listUsersForEnvironment"),listDeliveryUsersForEnvironment: () => Effect.die("unused listDeliveryUsersForEnvironment"),- listPublicKeysForEnvironment: () => Effect.die("unused listPublicKeysForEnvironment"),listForUser: () => Effect.die("unused listForUser"),getForUser: input?.getForUser ?? (() => Effect.succeed(null)),revokeForUser: input?.revokeForUser ?? (() => Effect.succeed(false)),diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.tsindex 5a4d0c9ca40..fbe867b7792 100644--- a/infra/relay/src/http/Api.ts+++ b/infra/relay/src/http/Api.ts@@ -1041,7 +1041,6 @@ const RelayCommonPersistenceError = Schema.Union([Devices.DeviceListPersistenceError,LiveActivities.LiveActivityRegistrationPersistenceError,EnvironmentLinks.EnvironmentLinkUserListPersistenceError,- EnvironmentLinks.EnvironmentPublicKeyListPersistenceError,EnvironmentLinks.EnvironmentLinkListPersistenceError,EnvironmentLinks.EnvironmentLinkLookupPersistenceError,EnvironmentLinks.EnvironmentLinkRevokePersistenceError,diff --git a/packages/client-runtime/src/authorization/remote.test.ts b/packages/client-runtime/src/authorization/remote.test.tsindex 0df4bab35ed..ec2861de91e 100644--- a/packages/client-runtime/src/authorization/remote.test.ts+++ b/packages/client-runtime/src/authorization/remote.test.ts@@ -10,7 +10,6 @@ import {appendClientConnectionParams,bootstrapRemoteBearerSession,exchangeRemoteDpopAccessToken,- fetchRemoteDpopSessionState,fetchRemoteSessionState,issueRemoteDpopWebSocketTicket,issueRemoteWebSocketTicket,@@ -380,45 +379,6 @@ describe("remote environment authorization", () => {}),);- it.effect("loads remote session state with a DPoP-bound access token", () =>- Effect.gen(function* () {- const fetch = recordedFetch(- Response.json({- authenticated: true,- auth: {- policy: "remote-reachable",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["dpop-access-token"],- sessionCookieName: "t3_session",- },- sessionMethod: "dpop-access-token",- scopes: [- "orchestration:read",- "orchestration:operate",- "terminal:operate",- "review:write",- ],- expiresAt: "2026-05-01T12:00:00.000Z",- }),- );-- yield* fetchRemoteDpopSessionState({- httpBaseUrl: "https://remote.example.com/",- accessToken: "dpop-access-token",- dpopProof: "dpop-proof",- }).pipe(provideRemoteHttp(fetch.fetchFn));-- expectFetchCall(fetch.calls, 1, {- url: "https://remote.example.com/api/auth/session",- method: "GET",- headers: {- authorization: "DPoP dpop-access-token",- dpop: "dpop-proof",- },- });- }),- );-it.effect("fails hung fetch requests on the configured timeout", () =>Effect.gen(function* () {const fetch = hangingFetch();diff --git a/packages/client-runtime/src/authorization/remote.ts b/packages/client-runtime/src/authorization/remote.tsindex be863e189a9..425d95d3ac1 100644--- a/packages/client-runtime/src/authorization/remote.ts+++ b/packages/client-runtime/src/authorization/remote.ts@@ -158,27 +158,6 @@ export const fetchRemoteSessionState = Effect.fn();});-export const fetchRemoteDpopSessionState = Effect.fn(- "clientRuntime.authorization.fetchRemoteDpopSessionState",-)(function* (input: {- readonly httpBaseUrl: string;- readonly accessToken: string;- readonly dpopProof: string;- readonly timeoutMs?: number;-}) {- const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");- return yield* executeEnvironmentHttpRequest(- environmentEndpointUrl(input.httpBaseUrl, "/api/auth/session"),- input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,- client.session({- headers: {- authorization: `DPoP ${input.accessToken}`,- dpop: input.dpopProof,- },- }),- );-});-export const issueRemoteWebSocketTicket = Effect.fn("clientRuntime.authorization.issueRemoteWebSocketTicket",)(function* (input: {diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 825dca87b63..70888f2988e 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -189,14 +189,6 @@ export const ExecutionEnvironmentDescriptor = Schema.Struct({});export type ExecutionEnvironmentDescriptor = typeof ExecutionEnvironmentDescriptor.Type;-export const EnvironmentConnectionState = Schema.Literals([- "connecting",- "connected",- "disconnected",- "error",-]);-export type EnvironmentConnectionState = typeof EnvironmentConnectionState.Type;-export const RepositoryIdentityLocator = Schema.Struct({source: Schema.Literal("git-remote"),remoteName: TrimmedNonEmptyString,@@ -228,9 +220,3 @@ export const ScopedThreadRef = Schema.Struct({threadId: ThreadId,});export type ScopedThreadRef = typeof ScopedThreadRef.Type;--export const ScopedThreadSessionRef = Schema.Struct({- environmentId: EnvironmentId,- threadId: ThreadId,-});-export type ScopedThreadSessionRef = typeof ScopedThreadSessionRef.Type;diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex e1af4f93614..7e738b97786 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -1,92 +1,15 @@-import type {- VcsCreateRefInput,- VcsCreateRefResult,- VcsCreateWorktreeInput,- VcsCreateWorktreeResult,- VcsInitInput,- VcsListRefsInput,- VcsListRefsResult,- VcsPullInput,- VcsPullResult,- VcsRemoveWorktreeInput,- VcsSwitchRefInput,- VcsSwitchRefResult,- GitPreparePullRequestThreadInput,- GitPreparePullRequestThreadResult,- GitPullRequestRefInput,- GitResolvePullRequestResult,- VcsStatusInput,- VcsStatusResult,-} from "./git.ts";-import type {- ReviewDiffFileContentsInput,- ReviewDiffFileContentsResult,- ReviewDiffPreviewInput,- ReviewDiffPreviewResult,-} from "./review.ts";-import type { FilesystemBrowseInput, FilesystemBrowseResult } from "./filesystem.ts";-import type { AssetCreateUrlInput, AssetCreateUrlResult } from "./assets.ts";-import type {- ProjectListEntriesInput,- ProjectListEntriesResult,- ProjectReadFileInput,- ProjectReadFileResult,- ProjectSearchEntriesInput,- ProjectSearchEntriesResult,- ProjectWriteFileInput,- ProjectWriteFileResult,-} from "./project.ts";-import type {- TerminalAttachInput,- TerminalAttachStreamEvent,- TerminalClearInput,- TerminalCloseInput,- TerminalMetadataStreamEvent,- TerminalOpenInput,- TerminalResizeInput,- TerminalRestartInput,- TerminalSessionSnapshot,- TerminalWriteInput,-} from "./terminal.ts";import * as Schema from "effect/Schema";-import type {- DiscoveredLocalServerList,- PreviewCloseInput,- PreviewEvent,- PreviewListInput,- PreviewListResult,- PreviewNavigateInput,- PreviewOpenInput,- PreviewRefreshInput,- PreviewReportStatusInput,- PreviewResizeInput,- PreviewSessionSnapshot,-} from "./preview.ts";+import {PreviewAutomationClickInput,PreviewAutomationEvaluateInput,- PreviewAutomationHost,- PreviewAutomationHostFocus,PreviewAutomationPressInput,- PreviewAutomationResponse,PreviewAutomationScrollInput,PreviewAutomationSnapshot,PreviewAutomationStatus,- PreviewAutomationStreamEvent,PreviewAutomationTypeInput,PreviewAutomationWaitForInput,} from "./previewAutomation.ts";-import type {- ClientOrchestrationCommand,- OrchestrationGetFullThreadDiffInput,- OrchestrationGetFullThreadDiffResult,- OrchestrationGetTurnDiffInput,- OrchestrationGetTurnDiffResult,- OrchestrationShellSnapshot,- OrchestrationShellStreamItem,- OrchestrationSubscribeThreadInput,- OrchestrationThreadStreamItem,-} from "./orchestration.ts";import { SnapShotSource } from "./orchestration.ts";import { EnvironmentId, TrimmedNonEmptyString } from "./baseSchemas.ts";import { BrowserProfileId } from "./browserProfile.ts";@@ -100,14 +23,7 @@ import { AdvertisedEndpoint } from "./remoteAccess.ts";import { ExecutionEnvironmentDescriptor } from "./environment.ts";import { type ClientSettings, type QuitConfirmationMode, SnapShotShortcut } from "./settings.ts";import type { EditorId } from "./editor.ts";-import type {- SourceControlCloneRepositoryInput,- SourceControlCloneRepositoryResult,- SourceControlPublishRepositoryInput,- SourceControlPublishRepositoryResult,- SourceControlRepositoryInfo,- SourceControlRepositoryLookupInput,-} from "./sourceControl.ts";+import type {DesktopAppActivationRequest,DesktopAppActivationResponse,@@ -694,19 +610,6 @@ export interface DesktopPreviewFavicon {capturedAt: number;}-export const DesktopPreviewFaviconSchema: Schema.Codec<DesktopPreviewFavicon> = Schema.Struct({- dataUrl: Schema.String.check(- Schema.isMaxLength(FAVICON_DATA_URL_MAX_LENGTH),- Schema.isPattern(/^data:image\/png;base64,[a-z0-9+/]+={0,2}$/i),- ),- pageUrl: Schema.String.check(Schema.isMaxLength(2_048)),- capturedAt: Schema.Number.check(- Schema.isFinite(),- Schema.isGreaterThanOrEqualTo(0),- Schema.isLessThanOrEqualTo(FAVICON_CAPTURED_AT_MAX),- ),-});-export interface DesktopPreviewTabState {tabId: string;webContentsId: number | null;@@ -746,27 +649,6 @@ export const DesktopPreviewAutomationStatusSchema = Schema.Struct({});export type DesktopPreviewAutomationStatus = typeof DesktopPreviewAutomationStatusSchema.Type;-export const DesktopPreviewNavStatusSchema = Schema.Union([- Schema.Struct({ kind: Schema.Literal("Idle") }),- Schema.Struct({- kind: Schema.Literal("Loading"),- url: Schema.String,- title: Schema.String,- }),- Schema.Struct({- kind: Schema.Literal("Success"),- url: Schema.String,- title: Schema.String,- }),- Schema.Struct({- kind: Schema.Literal("LoadFailed"),- url: Schema.String,- title: Schema.String,- code: Schema.Number,- description: Schema.String,- }),-]);-export interface DesktopPreviewPointerEvent {tabId: string;phase: "move" | "click";@@ -1474,135 +1356,3 @@ export interface LocalApi {setClientSettings: (settings: ClientSettings) => Promise<void>;};}--/**- * APIs bound to a specific backend environment connection.- *- * These operations must always be routed with explicit environment context.- * They represent remote stateful capabilities such as orchestration, terminal,- * project, VCS, and provider operations. In multi-environment mode, each environment gets- * its own instance of this surface, and callers should resolve it by- * `environmentId` rather than reaching through the local desktop bridge.- */-export interface EnvironmentApi {- terminal: {- open: (input: typeof TerminalOpenInput.Encoded) => Promise<TerminalSessionSnapshot>;- attach: (- input: typeof TerminalAttachInput.Encoded,- callback: (event: TerminalAttachStreamEvent) => void,- options?: {- onResubscribe?: () => void;- },- ) => () => void;- write: (input: typeof TerminalWriteInput.Encoded) => Promise<void>;- resize: (input: typeof TerminalResizeInput.Encoded) => Promise<void>;- clear: (input: typeof TerminalClearInput.Encoded) => Promise<void>;- restart: (input: typeof TerminalRestartInput.Encoded) => Promise<TerminalSessionSnapshot>;- close: (input: typeof TerminalCloseInput.Encoded) => Promise<void>;- onMetadata: (- callback: (event: TerminalMetadataStreamEvent) => void,- options?: {- onResubscribe?: () => void;- },- ) => () => void;- };- projects: {- listEntries: (input: ProjectListEntriesInput) => Promise<ProjectListEntriesResult>;- readFile: (input: ProjectReadFileInput) => Promise<ProjectReadFileResult>;- searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;- writeFile: (input: ProjectWriteFileInput) => Promise<ProjectWriteFileResult>;- };- filesystem: {- browse: (input: FilesystemBrowseInput) => Promise<FilesystemBrowseResult>;- };- assets: {- createUrl: (input: AssetCreateUrlInput) => Promise<AssetCreateUrlResult>;- };- sourceControl: {- lookupRepository: (- input: SourceControlRepositoryLookupInput,- ) => Promise<SourceControlRepositoryInfo>;- cloneRepository: (- input: SourceControlCloneRepositoryInput,- ) => Promise<SourceControlCloneRepositoryResult>;- publishRepository: (- input: SourceControlPublishRepositoryInput,- ) => Promise<SourceControlPublishRepositoryResult>;- };- vcs: {- listRefs: (input: VcsListRefsInput) => Promise<VcsListRefsResult>;- createWorktree: (input: VcsCreateWorktreeInput) => Promise<VcsCreateWorktreeResult>;- removeWorktree: (input: VcsRemoveWorktreeInput) => Promise<void>;- createRef: (input: VcsCreateRefInput) => Promise<VcsCreateRefResult>;- switchRef: (input: VcsSwitchRefInput) => Promise<VcsSwitchRefResult>;- init: (input: VcsInitInput) => Promise<void>;- pull: (input: VcsPullInput) => Promise<VcsPullResult>;- refreshStatus: (input: VcsStatusInput) => Promise<VcsStatusResult>;- onStatus: (- input: VcsStatusInput,- callback: (status: VcsStatusResult) => void,- options?: {- onResubscribe?: () => void;- },- ) => () => void;- };- git: {- resolvePullRequest: (input: GitPullRequestRefInput) => Promise<GitResolvePullRequestResult>;- preparePullRequestThread: (- input: GitPreparePullRequestThreadInput,- ) => Promise<GitPreparePullRequestThreadResult>;- };- review: {- getDiffPreview: (input: ReviewDiffPreviewInput) => Promise<ReviewDiffPreviewResult>;- getDiffFileContents: (- input: ReviewDiffFileContentsInput,- ) => Promise<ReviewDiffFileContentsResult>;- };- orchestration: {- dispatchCommand: (command: ClientOrchestrationCommand) => Promise<{ sequence: number }>;- getTurnDiff: (input: OrchestrationGetTurnDiffInput) => Promise<OrchestrationGetTurnDiffResult>;- getFullThreadDiff: (- input: OrchestrationGetFullThreadDiffInput,- ) => Promise<OrchestrationGetFullThreadDiffResult>;- getArchivedShellSnapshot: () => Promise<OrchestrationShellSnapshot>;- subscribeShell: (- callback: (event: OrchestrationShellStreamItem) => void,- options?: {- onResubscribe?: () => void;- },- ) => () => void;- subscribeThread: (- input: OrchestrationSubscribeThreadInput,- callback: (event: OrchestrationThreadStreamItem) => void,- options?: {- onResubscribe?: () => void;- },- ) => () => void;- };- preview: {- open: (input: typeof PreviewOpenInput.Encoded) => Promise<PreviewSessionSnapshot>;- navigate: (input: typeof PreviewNavigateInput.Encoded) => Promise<PreviewSessionSnapshot>;- resize: (input: typeof PreviewResizeInput.Encoded) => Promise<PreviewSessionSnapshot>;- refresh: (input: typeof PreviewRefreshInput.Encoded) => Promise<void>;- close: (input: typeof PreviewCloseInput.Encoded) => Promise<void>;- list: (input: typeof PreviewListInput.Encoded) => Promise<PreviewListResult>;- reportStatus: (input: typeof PreviewReportStatusInput.Encoded) => Promise<void>;- automation: {- connect: (- input: PreviewAutomationHost,- callback: (event: PreviewAutomationStreamEvent) => void,- options?: { onResubscribe?: () => void },- ) => () => void;- respond: (response: PreviewAutomationResponse) => Promise<void>;- focusHost: (input: PreviewAutomationHostFocus) => Promise<void>;- };- onEvent: (- callback: (event: PreviewEvent) => void,- options?: { onResubscribe?: () => void },- ) => () => void;- subscribePorts: (- callback: (servers: DiscoveredLocalServerList) => void,- options?: { onResubscribe?: () => void },- ) => () => void;- };-}diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex f477efd09c4..cf3aad4ba73 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -2208,26 +2208,6 @@ export const ProviderSessionRuntimeStatus = Schema.Literals([]);export type ProviderSessionRuntimeStatus = typeof ProviderSessionRuntimeStatus.Type;-const ProjectionThreadTurnStatus = Schema.Literals([- "running",- "completed",- "interrupted",- "error",-]);-export type ProjectionThreadTurnStatus = typeof ProjectionThreadTurnStatus.Type;--const ProjectionCheckpointRow = Schema.Struct({- threadId: ThreadId,- turnId: TurnId,- checkpointTurnCount: NonNegativeInt,- checkpointRef: CheckpointRef,- status: OrchestrationCheckpointStatus,- files: Schema.Array(OrchestrationCheckpointFile),- assistantMessageId: Schema.NullOr(MessageId),- completedAt: IsoDateTime,-});-export type ProjectionCheckpointRow = typeof ProjectionCheckpointRow.Type;-export const ProjectionPendingApprovalStatus = Schema.Literals(["pending", "resolved"]);export type ProjectionPendingApprovalStatus = typeof ProjectionPendingApprovalStatus.Type;diff --git a/packages/contracts/src/providerRuntime.test.ts b/packages/contracts/src/providerRuntime.test.tsindex 9ba30b235fc..f7404c66ed6 100644--- a/packages/contracts/src/providerRuntime.test.ts+++ b/packages/contracts/src/providerRuntime.test.ts@@ -1,19 +1,11 @@-import { describe, expect, expectTypeOf, it } from "vite-plus/test";+import { describe, expect, it } from "vite-plus/test";import * as Schema from "effect/Schema";-import {- classifyTaskAgentKind,- ProviderRuntimeEvent,- type ProviderRuntimeEventType,-} from "./providerRuntime.ts";+import { classifyTaskAgentKind, ProviderRuntimeEvent } from "./providerRuntime.ts";const decodeRuntimeEvent = Schema.decodeUnknownSync(ProviderRuntimeEvent);describe("ProviderRuntimeEvent", () => {- it("includes every runtime event in the public event type", () => {- expectTypeOf<ProviderRuntimeEvent["type"]>().toEqualTypeOf<ProviderRuntimeEventType>();- });-it("requires input and output totals for complete turn usage", () => {const completeEvent = {type: "turn.completed",diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.tsindex af1baac74f9..01a8f9ad8f8 100644--- a/packages/contracts/src/providerRuntime.ts+++ b/packages/contracts/src/providerRuntime.ts@@ -148,59 +148,6 @@ export const CanonicalRequestType = Schema.Literals([]);export type CanonicalRequestType = typeof CanonicalRequestType.Type;-const ProviderRuntimeEventType = Schema.Literals([- "session.started",- "session.configured",- "session.state.changed",- "session.exited",- "thread.started",- "thread.state.changed",- "thread.metadata.updated",- "thread.token-usage.updated",- "thread.realtime.started",- "thread.realtime.item-added",- "thread.realtime.audio.delta",- "thread.realtime.error",- "thread.realtime.closed",- "turn.started",- "turn.completed",- "turn.aborted",- "turn.plan.updated",- "turn.proposed.delta",- "turn.proposed.completed",- "turn.diff.updated",- "item.started",- "item.updated",- "item.completed",- "content.delta",- "request.opened",- "request.resolved",- "user-input.requested",- "user-input.resolved",- "task.started",- "task.progress",- "task.updated",- "task.completed",- "hook.started",- "hook.progress",- "hook.completed",- "tool.progress",- "tool.summary",- "tool.denied",- "auth.status",- "account.updated",- "account.rate-limits.updated",- "mcp.status.updated",- "mcp.oauth.completed",- "model.rerouted",- "config.warning",- "deprecation.notice",- "files.persisted",- "runtime.warning",- "runtime.error",-]);-export type ProviderRuntimeEventType = typeof ProviderRuntimeEventType.Type;-const SessionStartedType = Schema.Literal("session.started");const SessionConfiguredType = Schema.Literal("session.configured");const SessionStateChangedType = Schema.Literal("session.state.changed");diff --git a/packages/effect-codex-app-server/scripts/generate.ts b/packages/effect-codex-app-server/scripts/generate.tsindex e5d4db7da52..48509db8cc2 100644--- a/packages/effect-codex-app-server/scripts/generate.ts+++ b/packages/effect-codex-app-server/scripts/generate.ts@@ -413,7 +413,7 @@ function addAsyncQuestionFields(value: Schema.Json): Schema.Json {return {...value,properties: {- ...properties,+ ...Object.fromEntries(Object.entries(properties).filter(([key]) => key !== "type")),delivery: { anyOf: [{ type: "string", enum: ["async"] }, { type: "null" }] },questions: {anyOf: [@@ -433,6 +433,7 @@ function addAsyncQuestionFields(value: Schema.Json): Schema.Json {{ type: "null" },],},+ type: itemType,},};}@@ -760,7 +761,8 @@ const generateFiles = Effect.fn("generateFiles")(function* () {for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) =>left.localeCompare(right),)) {- generator.addSchema(name, addAsyncQuestionFields(schema) as never);+ aggregateSchemas[name] = addAsyncQuestionFields(schema);+ generator.addSchema(name, aggregateSchemas[name] as never);}const generatedEntries = new Map<string, string>();diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.tsindex 6738892a979..25b0ba2d38e 100644--- a/packages/shared/src/nodeSqliteClient.test.ts+++ b/packages/shared/src/nodeSqliteClient.test.ts@@ -5,7 +5,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";import * as SqliteClient from "./nodeSqliteClient.ts";-const layer = it.layer(SqliteClient.layerMemory());+const layer = it.layer(SqliteClient.layer({ filename: ":memory:" }));layer("NodeSqliteClient", (it) => {it.effect("runs prepared queries and returns positional values", () =>diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.tsindex d156d4cc3e5..71ba1188462 100644--- a/packages/shared/src/nodeSqliteClient.ts+++ b/packages/shared/src/nodeSqliteClient.ts@@ -36,11 +36,6 @@ export interface SqliteClientConfig {readonly transformQueryNames?: ((str: string) => string) | undefined;}-export interface SqliteMemoryClientConfig extends Omit<- SqliteClientConfig,- "filename" | "readonly"-> {}-export class UnsupportedNodeSqliteVersionError extends Schema.TaggedError<UnsupportedNodeSqliteVersionError>()("UnsupportedNodeSqliteVersionError",{@@ -86,9 +81,8 @@ const checkNodeSqliteCompat = () => {return Effect.void;};-const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (+const make = Effect.fn("makeWithDatabase")(function* (options: SqliteClientConfig,- openDatabase: () => NodeSqlite.DatabaseSync,): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {yield* checkNodeSqliteCompat();@@ -100,7 +94,11 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (const makeConnection = Effect.gen(function* () {const scope = yield* Effect.scope;const db = yield* Effect.try({- try: openDatabase,+ try: () =>+ new NodeSqlite.DatabaseSync(options.filename, {+ readOnly: options.readonly ?? false,+ allowExtension: options.allowExtension ?? false,+ }),catch: (cause) =>new SqlError({reason: classifySqliteError(cause, {@@ -281,39 +279,5 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (});});-const make = (- options: SqliteClientConfig,-): Effect.Effect<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>- makeWithDatabase(- options,- () =>- new NodeSqlite.DatabaseSync(options.filename, {- readOnly: options.readonly ?? false,- allowExtension: options.allowExtension ?? false,- }),- );--const makeMemory = (- config: SqliteMemoryClientConfig = {},-): Effect.Effect<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>- makeWithDatabase(- {- ...config,- filename: ":memory:",- readonly: false,- },- () => {- const database = new NodeSqlite.DatabaseSync(":memory:", {- allowExtension: config.allowExtension ?? false,- });- return database;- },- );-export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));--export const layerMemory = (- config: SqliteMemoryClientConfig = {},-): Layer.Layer<Client.SqlClient, SqlError> =>- Layer.effect(Client.SqlClient, makeMemory(config)).pipe(Layer.provide(Reactivity.layer));diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.tsindex 07ac73f8c6a..11a45907cc1 100644--- a/packages/shared/src/shell.ts+++ b/packages/shared/src/shell.ts@@ -11,7 +11,6 @@ import * as Path from "effect/Path";import { HostProcessEnvironment, HostProcessPlatform } from "./hostProcess.ts";import * as Context from "effect/Context";-const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;const WINDOWS_PATH_DELIMITER = ";";const POSIX_PATH_DELIMITER = ":";diff --git a/packages/tailscale/src/tailscale.ts b/packages/tailscale/src/tailscale.tsindex 3594742f274..096176aa42f 100644--- a/packages/tailscale/src/tailscale.ts+++ b/packages/tailscale/src/tailscale.ts@@ -111,13 +111,11 @@ export class TailscaleCommandTimeoutError extends Schema.TaggedError<TailscaleCo}}-export const TailscaleCommandError = Schema.Union([- TailscaleCommandSpawnError,- TailscaleCommandOutputError,- TailscaleCommandExitError,- TailscaleCommandTimeoutError,-]);-export type TailscaleCommandError = typeof TailscaleCommandError.Type;+export type TailscaleCommandError =+ | TailscaleCommandSpawnError+ | TailscaleCommandOutputError+ | TailscaleCommandExitError+ | TailscaleCommandTimeoutError;export class TailscaleStatusParseError extends Schema.TaggedError<TailscaleStatusParseError>()("TailscaleStatusParseError",diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.tsindex d11f8244bfe..5a44c7c1845 100644--- a/scripts/dev-runner.ts+++ b/scripts/dev-runner.ts@@ -190,17 +190,6 @@ export class DevRunnerHostNotProxiableError extends Schema.TaggedError<DevRunner}}-export const DevRunnerError = Schema.Union([- DevRunnerConfigurationError,- DevRunnerHostNotProxiableError,- DevRunnerInvalidPortOffsetError,- DevRunnerPortExhaustedError,- DevRunnerProcessError,- DevRunnerProcessExitError,-]);-export type DevRunnerError = typeof DevRunnerError.Type;-export const isDevRunnerError = Schema.is(DevRunnerError);-const optionalStringConfig = (name: string): Config.Config<string | undefined> =>Config.String(name).pipe(Config.option,diff --git a/scripts/lib/dev-share.ts b/scripts/lib/dev-share.tsindex f4806d77602..94a1c462043 100644--- a/scripts/lib/dev-share.ts+++ b/scripts/lib/dev-share.ts@@ -110,13 +110,10 @@ export class DevServeFailedError extends Schema.TaggedError<DevServeFailedError>}}-export const DevShareError = Schema.Union([- TailscaleUnavailableError,- TailnetNameMissingError,- DevServeFailedError,-]);-export type DevShareError = typeof DevShareError.Type;-export const isDevShareError = Schema.is(DevShareError);+export type DevShareError =+ | TailscaleUnavailableError+ | TailnetNameMissingError+ | DevServeFailedError;/*** Removes any mapping for `webPort`, reporting whether the port is now clear.diff --git a/scripts/mobile-showcase.ts b/scripts/mobile-showcase.tsindex 6b6adebeb77..ccce919a744 100644--- a/scripts/mobile-showcase.ts+++ b/scripts/mobile-showcase.ts@@ -26,8 +26,6 @@ import showcaseConfig, {import {SHOWCASE_ENVIRONMENTS,SHOWCASE_PROJECTS,- SHOWCASE_TERMINAL_ID,- SHOWCASE_THREAD_ID,seedShowcaseEnvironment,} from "./mobile-showcase-environment.ts";@@ -668,17 +666,6 @@ function buildShowcasePairingUrl(host: string, port: number, credential: string)return url.toString();}-export function showcaseSceneUrl(scene: ShowcaseScene, environmentId: string): string {- if (scene === "threads") return `${APP_SCHEME}://`;- if (scene === "environments") return `${APP_SCHEME}://settings/environments`;- const threadPath = `threads/${encodeURIComponent(environmentId)}/${SHOWCASE_THREAD_ID}`;- if (scene === "thread") return `${APP_SCHEME}://${threadPath}`;- if (scene === "terminal") {- return `${APP_SCHEME}://${threadPath}/terminal?terminalId=${SHOWCASE_TERMINAL_ID}`;- }- return `${APP_SCHEME}://${threadPath}/review`;-}-export function encodeAndroidPairingUrls(pairingUrls: ReadonlyArray<string>): string {return `json-uri:${encodeURIComponent(JSON.stringify(pairingUrls))}`;}diff --git a/scripts/notify-discord-release.test.ts b/scripts/notify-discord-release.test.tsindex 7ca108f3188..dba0c6cd5da 100644--- a/scripts/notify-discord-release.test.ts+++ b/scripts/notify-discord-release.test.ts@@ -3,11 +3,7 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import { HttpClient, HttpClientError, HttpClientResponse } from "effect/unstable/http";-import {- buildDiscordReleaseAnnouncement,- isDiscordReleaseAnnouncementError,- postDiscordWebhook,-} from "./notify-discord-release.ts";+import { buildDiscordReleaseAnnouncement, postDiscordWebhook } from "./notify-discord-release.ts";const latestAnnouncement = {target: "latest",@@ -135,7 +131,6 @@ it.effect("preserves webhook request context and the full client cause chain", (assert.equal(error.cause, clientError);assert.equal((error.cause as HttpClientError.HttpClientError).cause, requestCause);assert.ok(!error.message.includes(requestCause.message));- assert.equal(isDiscordReleaseAnnouncementError(error), true);});});@@ -169,6 +164,5 @@ it.effect("preserves a non-success response error with structured status context}assert.equal(error.cause.reason._tag, "StatusCodeError");assert.ok(!error.message.includes(error.cause.message));- assert.equal(isDiscordReleaseAnnouncementError(error), true);});});diff --git a/scripts/notify-discord-release.ts b/scripts/notify-discord-release.tsindex 8f9f1d7a33b..67cf556d472 100644--- a/scripts/notify-discord-release.ts+++ b/scripts/notify-discord-release.ts@@ -90,13 +90,6 @@ export class DiscordReleaseWebhookResponseError extends Schema.TaggedError<Disco}}-export const DiscordReleaseAnnouncementError = Schema.Union([- DiscordReleaseWebhookRequestError,- DiscordReleaseWebhookResponseError,-]);-export type DiscordReleaseAnnouncementError = typeof DiscordReleaseAnnouncementError.Type;-export const isDiscordReleaseAnnouncementError = Schema.is(DiscordReleaseAnnouncementError);-const targetLabels = {prerelease: "Prerelease",latest: "Latest",diff --git a/scripts/sync-reference-repos.ts b/scripts/sync-reference-repos.tsindex 2cb13d42683..e56c5fe9e4b 100644--- a/scripts/sync-reference-repos.ts+++ b/scripts/sync-reference-repos.ts@@ -91,14 +91,11 @@ export class ReferenceRepoGitSubtreeError extends Schema.TaggedError<ReferenceRe}}-export const ReferenceRepoSyncError = Schema.Union([- ReferenceRepoSelectionError,- ReferenceRepoVersionSourceError,- ReferenceRepoVersionResolutionError,- ReferenceRepoGitSubtreeError,-]);-export type ReferenceRepoSyncError = typeof ReferenceRepoSyncError.Type;-export const isReferenceRepoSyncError = Schema.is(ReferenceRepoSyncError);+export type ReferenceRepoSyncError =+ | ReferenceRepoSelectionError+ | ReferenceRepoVersionSourceError+ | ReferenceRepoVersionResolutionError+ | ReferenceRepoGitSubtreeError;const decodeJsonSource = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));const decodeYamlSource = Schema.decodeEffect(fromYaml(Schema.Unknown));