diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 63e1de8feb..1a9d16380a 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -14,13 +14,6 @@ import { getConnectionCatalog, setConnectionCatalog, } from "./methods/connectionCatalog.ts"; -import { - getSavedEnvironmentRegistry, - getSavedEnvironmentSecret, - removeSavedEnvironmentSecret, - setSavedEnvironmentRegistry, - setSavedEnvironmentSecret, -} from "./methods/savedEnvironments.ts"; import { getAdvertisedEndpoints, getServerExposureState, @@ -64,11 +57,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(getClientSettings); yield* ipc.handle(setClientSettings); - yield* ipc.handle(getSavedEnvironmentRegistry); - yield* ipc.handle(setSavedEnvironmentRegistry); - yield* ipc.handle(getSavedEnvironmentSecret); - yield* ipc.handle(setSavedEnvironmentSecret); - yield* ipc.handle(removeSavedEnvironmentSecret); yield* ipc.handle(getConnectionCatalog); yield* ipc.handle(setConnectionCatalog); yield* ipc.handle(clearConnectionCatalog); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 28fbf8b8eb..e270ef404b 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -20,11 +20,6 @@ export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding"; export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap"; export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings"; export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings"; -export const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry"; -export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry"; -export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret"; -export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret"; -export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret"; export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog"; export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog"; export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog"; diff --git a/apps/desktop/src/ipc/methods/savedEnvironments.ts b/apps/desktop/src/ipc/methods/savedEnvironments.ts deleted file mode 100644 index bc5e4a9aeb..0000000000 --- a/apps/desktop/src/ipc/methods/savedEnvironments.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; - -import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts"; -import * as IpcChannels from "../channels.ts"; -import { makeIpcMethod } from "../DesktopIpc.ts"; - -const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema); -const NonBlankString = Schema.String.check( - Schema.makeFilter((value) => - value.trim().length > 0 ? undefined : "Expected a non-empty string", - ), -); - -const SetSavedEnvironmentSecretInput = Schema.Struct({ - environmentId: EnvironmentId, - secret: NonBlankString, -}); - -export const getSavedEnvironmentRegistry = makeIpcMethod({ - channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, - payload: Schema.Void, - result: SavedEnvironmentRegistryPayload, - handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () { - const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; - return yield* savedEnvironments.getRegistry; - }), -}); - -export const setSavedEnvironmentRegistry = makeIpcMethod({ - channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, - payload: SavedEnvironmentRegistryPayload, - result: Schema.Void, - handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) { - const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; - yield* savedEnvironments.setRegistry(records); - }), -}); - -export const getSavedEnvironmentSecret = makeIpcMethod({ - channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, - payload: EnvironmentId, - result: Schema.NullOr(Schema.String), - handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) { - const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; - return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId)); - }), -}); - -export const setSavedEnvironmentSecret = makeIpcMethod({ - channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, - payload: SetSavedEnvironmentSecretInput, - result: Schema.Boolean, - handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({ - environmentId, - secret, - }) { - const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; - return yield* savedEnvironments.setSecret({ - environmentId, - secret, - }); - }), -}); - -export const removeSavedEnvironmentSecret = makeIpcMethod({ - channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, - payload: EnvironmentId, - result: Schema.Void, - handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) { - const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; - yield* savedEnvironments.removeSecret(environmentId); - }), -}); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 6c44394291..35c34d39c9 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -42,16 +42,6 @@ contextBridge.exposeInMainWorld("desktopBridge", { getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL), setClientSettings: (settings) => ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings), - getSavedEnvironmentRegistry: () => - ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL), - setSavedEnvironmentRegistry: (records) => - ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records), - getSavedEnvironmentSecret: (environmentId) => - ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId), - setSavedEnvironmentSecret: (environmentId, secret) => - ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, { environmentId, secret }), - removeSavedEnvironmentSecret: (environmentId) => - ipcRenderer.invoke(IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId), getConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.GET_CONNECTION_CATALOG_CHANNEL), setConnectionCatalog: (catalog) => ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog), diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 088186d4df..d6daa01d04 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -10,7 +10,7 @@ import type { } from "@t3tools/contracts"; import { formatDuration } from "@t3tools/shared/orchestrationTiming"; -import type { QueuedThreadMessage } from "../state/thread-outbox"; +import type { QueuedThreadMessage } from "../state/thread-outbox-model"; import * as Arr from "effect/Array"; import * as Order from "effect/Order"; diff --git a/apps/mobile/src/state/thread-outbox-manager.ts b/apps/mobile/src/state/thread-outbox-manager.ts new file mode 100644 index 0000000000..477cb1273a --- /dev/null +++ b/apps/mobile/src/state/thread-outbox-manager.ts @@ -0,0 +1,108 @@ +import type { EnvironmentId, MessageId } from "@t3tools/contracts"; +import { Atom, type AtomRegistry } from "effect/unstable/reactivity"; + +import { + flattenQueuedThreadMessages, + groupQueuedThreadMessages, + type QueuedThreadMessage, +} from "./thread-outbox-model"; +import type { ThreadOutboxStorage } from "./thread-outbox-storage"; + +export interface ThreadOutboxManagerOptions { + readonly registry: AtomRegistry.AtomRegistry; + readonly storage: ThreadOutboxStorage; + readonly warn?: (message: string, error: unknown) => void; +} + +export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) { + const queuedMessagesByThreadKeyAtom = Atom.make< + Record> + >({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-outbox:queued-messages")); + const warn = + options.warn ?? + ((message: string, error: unknown) => { + console.warn(message, error); + }); + let loadPromise: Promise | null = null; + let mutationQueue: Promise = Promise.resolve(); + + const serialize = (mutation: () => Promise): Promise => { + const result = mutationQueue.then(mutation, mutation); + mutationQueue = result.then( + () => undefined, + () => undefined, + ); + return result; + }; + + const currentMessages = (): ReadonlyArray => + flattenQueuedThreadMessages(options.registry.get(queuedMessagesByThreadKeyAtom)); + + const setMessages = (messages: ReadonlyArray): void => { + options.registry.set(queuedMessagesByThreadKeyAtom, groupQueuedThreadMessages(messages)); + }; + + const load = (): Promise => { + if (loadPromise !== null) { + return loadPromise; + } + loadPromise = serialize(async () => { + const persistedMessages = await options.storage.load(); + setMessages([...persistedMessages, ...currentMessages()]); + }).catch((error) => { + loadPromise = null; + warn("[thread-outbox] failed to load persisted messages", error); + }); + return loadPromise; + }; + + const enqueue = (message: QueuedThreadMessage): Promise => + serialize(async () => { + await options.storage.write(message); + setMessages([...currentMessages(), message]); + }); + + const remove = (message: QueuedThreadMessage): Promise => + serialize(async () => { + await options.storage.remove(message); + setMessages( + currentMessages().filter((candidate) => candidate.messageId !== message.messageId), + ); + }); + + const clearEnvironment = (environmentId: EnvironmentId): Promise => + serialize(async () => { + const persisted = await options.storage.load().catch((error) => { + warn("[thread-outbox] failed to load messages while clearing environment", error); + return []; + }); + const allMessages = flattenQueuedThreadMessages( + groupQueuedThreadMessages([...persisted, ...currentMessages()]), + ); + const removedMessageIds = new Set(); + + await Promise.all( + allMessages + .filter((message) => message.environmentId === environmentId) + .map(async (message) => { + try { + await options.storage.remove(message); + removedMessageIds.add(message.messageId); + } catch (error) { + warn("[thread-outbox] failed to clear persisted message", error); + } + }), + ); + + setMessages(allMessages.filter((message) => !removedMessageIds.has(message.messageId))); + }); + + return { + queuedMessagesByThreadKeyAtom, + serialize, + load, + enqueue, + remove, + clearEnvironment, + }; +} diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts new file mode 100644 index 0000000000..aa7a105513 --- /dev/null +++ b/apps/mobile/src/state/thread-outbox-model.ts @@ -0,0 +1,121 @@ +import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors"; +import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell"; +import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; + +import type { DraftComposerImageAttachment } from "../lib/composerImages"; +import { scopedThreadKey } from "../lib/scopedEntities"; + +const THREAD_OUTBOX_SCHEMA_VERSION = 1; +const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000; + +const DraftComposerImageAttachmentSchema = Schema.Struct({ + id: Schema.String, + previewUri: Schema.String, + type: Schema.Literal("image"), + name: Schema.String, + mimeType: Schema.String, + sizeBytes: Schema.Number, + dataUrl: Schema.String, +}); + +export const QueuedThreadMessageSchema = Schema.Struct({ + schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION), + environmentId: EnvironmentId, + threadId: ThreadId, + messageId: MessageId, + commandId: CommandId, + text: Schema.String, + attachments: Schema.Array(DraftComposerImageAttachmentSchema), + createdAt: IsoDateTime, +}); + +const decodeStoredQueuedThreadMessage = Schema.decodeUnknownSync(QueuedThreadMessageSchema); +const encodeStoredQueuedThreadMessage = Schema.encodeUnknownSync(QueuedThreadMessageSchema); + +export interface QueuedThreadMessage { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly messageId: MessageId; + readonly commandId: CommandId; + readonly text: string; + readonly attachments: ReadonlyArray; + readonly createdAt: string; +} + +export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown { + return encodeStoredQueuedThreadMessage({ + schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION, + ...message, + }); +} + +export function decodeQueuedThreadMessage(value: unknown): QueuedThreadMessage { + const { schemaVersion: _, ...message } = decodeStoredQueuedThreadMessage(value); + return message; +} + +export function groupQueuedThreadMessages( + messages: ReadonlyArray, +): Record> { + const deduplicated = new Map(); + for (const message of messages) { + deduplicated.set(message.messageId, message); + } + + const grouped: Record> = {}; + for (const message of deduplicated.values()) { + const threadKey = scopedThreadKey(message.environmentId, message.threadId); + (grouped[threadKey] ??= []).push(message); + } + for (const queue of Object.values(grouped)) { + queue.sort((left, right) => left.createdAt.localeCompare(right.createdAt)); + } + return grouped; +} + +export function flattenQueuedThreadMessages( + queues: Record>, +): ReadonlyArray { + return Object.values(queues).flat(); +} + +export function threadOutboxRetryDelayMs(attempt: number): number { + return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), THREAD_OUTBOX_MAX_RETRY_DELAY_MS); +} + +export type ThreadOutboxDeliveryAction = "wait" | "remove" | "send"; + +export function resolveThreadOutboxDeliveryAction(input: { + readonly threadExists: boolean; + readonly shellStatus: EnvironmentShellStatus; + readonly environmentConnected: boolean; + readonly threadBusy: boolean; +}): ThreadOutboxDeliveryAction { + if (!input.threadExists) { + return input.shellStatus === "live" ? "remove" : "wait"; + } + return input.environmentConnected && !input.threadBusy ? "send" : "wait"; +} + +function errorMessage(error: unknown): string | null { + if (error instanceof Error) { + return error.message; + } + if (typeof error === "object" && error !== null && "message" in error) { + return typeof error.message === "string" ? error.message : null; + } + return typeof error === "string" ? error : null; +} + +export function shouldRetryThreadOutboxDelivery(error: unknown): boolean { + if ( + typeof error === "object" && + error !== null && + "_tag" in error && + error._tag === "ConnectionTransientError" + ) { + return true; + } + return isTransportConnectionErrorMessage(errorMessage(error)); +} diff --git a/apps/mobile/src/state/thread-outbox-storage.ts b/apps/mobile/src/state/thread-outbox-storage.ts new file mode 100644 index 0000000000..e294aee454 --- /dev/null +++ b/apps/mobile/src/state/thread-outbox-storage.ts @@ -0,0 +1,64 @@ +import type { MessageId } from "@t3tools/contracts"; + +import { + decodeQueuedThreadMessage, + encodeQueuedThreadMessage, + type QueuedThreadMessage, +} from "./thread-outbox-model"; + +const THREAD_OUTBOX_DIRECTORY = "thread-outbox"; + +export interface ThreadOutboxStorage { + readonly load: () => Promise>; + readonly write: (message: QueuedThreadMessage) => Promise; + readonly remove: (message: QueuedThreadMessage) => Promise; +} + +function messageFileName(messageId: MessageId): string { + return `${encodeURIComponent(messageId)}.json`; +} + +async function getOutboxDirectory() { + const { Directory, Paths } = await import("expo-file-system"); + const directory = new Directory(Paths.document, THREAD_OUTBOX_DIRECTORY); + directory.create({ idempotent: true, intermediates: true }); + return directory; +} + +async function getMessageFile(messageId: MessageId) { + const { File } = await import("expo-file-system"); + return new File(await getOutboxDirectory(), messageFileName(messageId)); +} + +export const expoThreadOutboxStorage: ThreadOutboxStorage = { + load: async () => { + const { File } = await import("expo-file-system"); + const directory = await getOutboxDirectory(); + const messages: QueuedThreadMessage[] = []; + + for (const entry of directory.list()) { + if (!(entry instanceof File) || !entry.name.endsWith(".json")) { + continue; + } + try { + messages.push(decodeQueuedThreadMessage(JSON.parse(await entry.text()) as unknown)); + } catch (error) { + console.warn("[thread-outbox] ignored invalid persisted message", entry.name, error); + } + } + return messages; + }, + write: async (message) => { + const file = await getMessageFile(message.messageId); + if (!file.exists) { + file.create({ intermediates: true, overwrite: true }); + } + file.write(JSON.stringify(encodeQueuedThreadMessage(message))); + }, + remove: async (message) => { + const file = await getMessageFile(message.messageId); + if (file.exists) { + file.delete(); + } + }, +}; diff --git a/apps/mobile/src/state/thread-outbox.test.ts b/apps/mobile/src/state/thread-outbox.test.ts index 5c6ea82eff..d2634fb966 100644 --- a/apps/mobile/src/state/thread-outbox.test.ts +++ b/apps/mobile/src/state/thread-outbox.test.ts @@ -1,14 +1,17 @@ import { describe, expect, it } from "@effect/vitest"; import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; +import { AtomRegistry } from "effect/unstable/reactivity"; import { decodeQueuedThreadMessage, groupQueuedThreadMessages, - serializeThreadOutboxMutation, + resolveThreadOutboxDeliveryAction, shouldRetryThreadOutboxDelivery, threadOutboxRetryDelayMs, type QueuedThreadMessage, -} from "./thread-outbox"; +} from "./thread-outbox-model"; +import { createThreadOutboxManager } from "./thread-outbox-manager"; +import type { ThreadOutboxStorage } from "./thread-outbox-storage"; function queuedMessage(input: { readonly environmentId?: string; @@ -70,18 +73,27 @@ describe("thread outbox", () => { }); it("serializes mutations even when an earlier mutation is slower", async () => { + const registry = AtomRegistry.make(); + const manager = createThreadOutboxManager({ + registry, + storage: { + load: async () => [], + write: async () => undefined, + remove: async () => undefined, + }, + }); const order: string[] = []; let releaseFirst!: () => void; const firstBlocked = new Promise((resolve) => { releaseFirst = resolve; }); - const first = serializeThreadOutboxMutation(async () => { + const first = manager.serialize(async () => { order.push("first:start"); await firstBlocked; order.push("first:end"); }); - const second = serializeThreadOutboxMutation(async () => { + const second = manager.serialize(async () => { order.push("second"); }); @@ -90,6 +102,116 @@ describe("thread outbox", () => { releaseFirst(); await Promise.all([first, second]); expect(order).toEqual(["first:start", "first:end", "second"]); + registry.dispose(); + }); + + it("holds the mutation queue while persisted messages are loading", async () => { + const registry = AtomRegistry.make(); + const message = queuedMessage({ + messageId: "message-1", + createdAt: "2026-06-08T10:00:01.000Z", + }); + const stored = new Map([[message.messageId, message]]); + let loadCalls = 0; + let removeCalls = 0; + let releaseInitialLoad!: () => void; + const initialLoadBlocked = new Promise((resolve) => { + releaseInitialLoad = resolve; + }); + const storage: ThreadOutboxStorage = { + load: async () => { + loadCalls += 1; + if (loadCalls === 1) { + await initialLoadBlocked; + } + return [...stored.values()]; + }, + write: async () => undefined, + remove: async (candidate) => { + removeCalls += 1; + stored.delete(candidate.messageId); + }, + }; + const manager = createThreadOutboxManager({ registry, storage }); + + const loading = manager.load(); + await Promise.resolve(); + const clearing = manager.clearEnvironment(message.environmentId); + await Promise.resolve(); + await Promise.resolve(); + + expect(loadCalls).toBe(1); + expect(removeCalls).toBe(0); + + releaseInitialLoad(); + await Promise.all([loading, clearing]); + expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({}); + registry.dispose(); + }); + + it("keeps atom state aligned with durable writes and removals", async () => { + const registry = AtomRegistry.make(); + const stored = new Map(); + let failRemoval = true; + const storage: ThreadOutboxStorage = { + load: async () => [...stored.values()], + write: async (message) => { + stored.set(message.messageId, message); + }, + remove: async (message) => { + if (failRemoval) { + throw new Error("remove failed"); + } + stored.delete(message.messageId); + }, + }; + const manager = createThreadOutboxManager({ registry, storage }); + const message = queuedMessage({ + messageId: "message-1", + createdAt: "2026-06-08T10:00:01.000Z", + }); + + await manager.enqueue(message); + expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({ + "environment-1:thread-1": [message], + }); + + await expect(manager.remove(message)).rejects.toThrow("remove failed"); + expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({ + "environment-1:thread-1": [message], + }); + + failRemoval = false; + await manager.remove(message); + expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({}); + registry.dispose(); + }); + + it("only removes a missing-thread message after shell synchronization is live", () => { + expect( + resolveThreadOutboxDeliveryAction({ + threadExists: false, + shellStatus: "synchronizing", + environmentConnected: true, + threadBusy: false, + }), + ).toBe("wait"); + expect( + resolveThreadOutboxDeliveryAction({ + threadExists: false, + shellStatus: "live", + environmentConnected: true, + threadBusy: false, + }), + ).toBe("remove"); + expect( + resolveThreadOutboxDeliveryAction({ + threadExists: true, + shellStatus: "live", + environmentConnected: true, + threadBusy: false, + }), + ).toBe("send"); }); it("retries transport failures but drops deterministic command failures", () => { diff --git a/apps/mobile/src/state/thread-outbox.ts b/apps/mobile/src/state/thread-outbox.ts index 4be5f5e086..d5eb383a0e 100644 --- a/apps/mobile/src/state/thread-outbox.ts +++ b/apps/mobile/src/state/thread-outbox.ts @@ -1,252 +1,29 @@ -import { useAtomValue } from "@effect/atom-react"; -import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors"; -import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts"; -import * as Schema from "effect/Schema"; -import { Atom } from "effect/unstable/reactivity"; +import type { EnvironmentId } from "@t3tools/contracts"; -import type { DraftComposerImageAttachment } from "../lib/composerImages"; -import { scopedThreadKey } from "../lib/scopedEntities"; import { appAtomRegistry } from "./atom-registry"; +import { createThreadOutboxManager } from "./thread-outbox-manager"; +import type { QueuedThreadMessage } from "./thread-outbox-model"; +import { expoThreadOutboxStorage } from "./thread-outbox-storage"; -const THREAD_OUTBOX_SCHEMA_VERSION = 1; -const THREAD_OUTBOX_DIRECTORY = "thread-outbox"; -const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000; +export * from "./thread-outbox-model"; -const DraftComposerImageAttachmentSchema = Schema.Struct({ - id: Schema.String, - previewUri: Schema.String, - type: Schema.Literal("image"), - name: Schema.String, - mimeType: Schema.String, - sizeBytes: Schema.Number, - dataUrl: Schema.String, +export const threadOutboxManager = createThreadOutboxManager({ + registry: appAtomRegistry, + storage: expoThreadOutboxStorage, }); -export const QueuedThreadMessageSchema = Schema.Struct({ - schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION), - environmentId: EnvironmentId, - threadId: ThreadId, - messageId: MessageId, - commandId: CommandId, - text: Schema.String, - attachments: Schema.Array(DraftComposerImageAttachmentSchema), - createdAt: IsoDateTime, -}); - -const decodeStoredQueuedThreadMessage = Schema.decodeUnknownSync(QueuedThreadMessageSchema); -const encodeStoredQueuedThreadMessage = Schema.encodeUnknownSync(QueuedThreadMessageSchema); - -type StoredQueuedThreadMessage = typeof QueuedThreadMessageSchema.Type; - -export interface QueuedThreadMessage { - readonly environmentId: EnvironmentId; - readonly threadId: ThreadId; - readonly messageId: MessageId; - readonly commandId: CommandId; - readonly text: string; - readonly attachments: ReadonlyArray; - readonly createdAt: string; -} - -export const queuedMessagesByThreadKeyAtom = Atom.make< - Record> ->({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-outbox:queued-messages")); - -let loadPromise: Promise | null = null; -let mutationQueue: Promise = Promise.resolve(); - -export function serializeThreadOutboxMutation(mutation: () => Promise): Promise { - const result = mutationQueue.then(mutation, mutation); - mutationQueue = result.then( - () => undefined, - () => undefined, - ); - return result; -} - -function storedMessage(message: QueuedThreadMessage): StoredQueuedThreadMessage { - return { - schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION, - ...message, - }; -} - -function messageFileName(messageId: MessageId): string { - return `${encodeURIComponent(messageId)}.json`; -} - -async function getOutboxDirectory() { - const { Directory, Paths } = await import("expo-file-system"); - const directory = new Directory(Paths.document, THREAD_OUTBOX_DIRECTORY); - directory.create({ idempotent: true, intermediates: true }); - return directory; -} - -async function getMessageFile(messageId: MessageId) { - const { File } = await import("expo-file-system"); - return new File(await getOutboxDirectory(), messageFileName(messageId)); -} - -export function groupQueuedThreadMessages( - messages: ReadonlyArray, -): Record> { - const deduplicated = new Map(); - for (const message of messages) { - deduplicated.set(message.messageId, message); - } - - const grouped: Record> = {}; - for (const message of deduplicated.values()) { - const threadKey = scopedThreadKey(message.environmentId, message.threadId); - (grouped[threadKey] ??= []).push(message); - } - for (const queue of Object.values(grouped)) { - queue.sort((left, right) => left.createdAt.localeCompare(right.createdAt)); - } - return grouped; -} - -export function threadOutboxRetryDelayMs(attempt: number): number { - return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), THREAD_OUTBOX_MAX_RETRY_DELAY_MS); -} - -function errorMessage(error: unknown): string | null { - if (error instanceof Error) { - return error.message; - } - if (typeof error === "object" && error !== null && "message" in error) { - return typeof error.message === "string" ? error.message : null; - } - return typeof error === "string" ? error : null; -} - -export function shouldRetryThreadOutboxDelivery(error: unknown): boolean { - if ( - typeof error === "object" && - error !== null && - "_tag" in error && - error._tag === "ConnectionTransientError" - ) { - return true; - } - return isTransportConnectionErrorMessage(errorMessage(error)); -} - -export function decodeQueuedThreadMessage(value: unknown): QueuedThreadMessage { - const { schemaVersion: _, ...message } = decodeStoredQueuedThreadMessage(value); - return message; -} - -function flattenQueues( - queues: Record>, -): ReadonlyArray { - return Object.values(queues).flat(); -} - -async function loadPersistedMessages(): Promise> { - const { File } = await import("expo-file-system"); - const directory = await getOutboxDirectory(); - const messages: Array = []; - - for (const entry of directory.list()) { - if (!(entry instanceof File) || !entry.name.endsWith(".json")) { - continue; - } - try { - messages.push(decodeQueuedThreadMessage(JSON.parse(await entry.text()) as unknown)); - } catch (error) { - console.warn("[thread-outbox] ignored invalid persisted message", entry.name, error); - } - } - return messages; -} - export function ensureThreadOutboxLoaded(): void { - if (loadPromise !== null) { - return; - } - loadPromise = loadPersistedMessages() - .then((persistedMessages) => - serializeThreadOutboxMutation(async () => { - const current = flattenQueues(appAtomRegistry.get(queuedMessagesByThreadKeyAtom)); - appAtomRegistry.set( - queuedMessagesByThreadKeyAtom, - groupQueuedThreadMessages([...persistedMessages, ...current]), - ); - }), - ) - .catch((error) => { - loadPromise = null; - console.warn("[thread-outbox] failed to load persisted messages", error); - }); + void threadOutboxManager.load(); } -export async function enqueueThreadOutboxMessage(message: QueuedThreadMessage): Promise { - await serializeThreadOutboxMutation(async () => { - const encoded = encodeStoredQueuedThreadMessage(storedMessage(message)); - const file = await getMessageFile(message.messageId); - if (!file.exists) { - file.create({ intermediates: true, overwrite: true }); - } - file.write(JSON.stringify(encoded)); - - const current = flattenQueues(appAtomRegistry.get(queuedMessagesByThreadKeyAtom)); - appAtomRegistry.set( - queuedMessagesByThreadKeyAtom, - groupQueuedThreadMessages([...current, message]), - ); - }); +export function enqueueThreadOutboxMessage(message: QueuedThreadMessage): Promise { + return threadOutboxManager.enqueue(message); } -export async function removeThreadOutboxMessage(message: QueuedThreadMessage): Promise { - await serializeThreadOutboxMutation(async () => { - const file = await getMessageFile(message.messageId); - if (file.exists) { - file.delete(); - } - - const current = flattenQueues(appAtomRegistry.get(queuedMessagesByThreadKeyAtom)); - appAtomRegistry.set( - queuedMessagesByThreadKeyAtom, - groupQueuedThreadMessages( - current.filter((candidate) => candidate.messageId !== message.messageId), - ), - ); - }); +export function removeThreadOutboxMessage(message: QueuedThreadMessage): Promise { + return threadOutboxManager.remove(message); } -export async function clearThreadOutboxEnvironment(environmentId: EnvironmentId): Promise { - await serializeThreadOutboxMutation(async () => { - const current = flattenQueues(appAtomRegistry.get(queuedMessagesByThreadKeyAtom)); - const persisted = await loadPersistedMessages().catch((error) => { - console.warn("[thread-outbox] failed to load messages while clearing environment", error); - return []; - }); - const allMessages = flattenQueues(groupQueuedThreadMessages([...persisted, ...current])); - const removed = allMessages.filter((message) => message.environmentId === environmentId); - - await Promise.all( - removed.map(async (message) => { - try { - const file = await getMessageFile(message.messageId); - if (file.exists) { - file.delete(); - } - } catch (error) { - console.warn("[thread-outbox] failed to clear persisted message", error); - } - }), - ); - - appAtomRegistry.set( - queuedMessagesByThreadKeyAtom, - groupQueuedThreadMessages( - allMessages.filter((message) => message.environmentId !== environmentId), - ), - ); - }); -} - -export function useThreadOutboxMessages() { - return useAtomValue(queuedMessagesByThreadKeyAtom); +export function clearThreadOutboxEnvironment(environmentId: EnvironmentId): Promise { + return threadOutboxManager.clearEnvironment(environmentId); } diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.ts b/apps/mobile/src/state/use-selected-thread-git-actions.ts index d1791dcc5c..e85e89af26 100644 --- a/apps/mobile/src/state/use-selected-thread-git-actions.ts +++ b/apps/mobile/src/state/use-selected-thread-git-actions.ts @@ -13,23 +13,17 @@ import { sanitizeFeatureBranchName, } from "@t3tools/shared/git"; -import { gitEnvironment } from "../state/git"; import { useBranches } from "../state/queries"; import { threadEnvironment } from "../state/threads"; -import { vcsEnvironment } from "../state/vcs"; +import { vcsActionManager, vcsEnvironment } from "../state/vcs"; import { uuidv4 } from "../lib/uuid"; +import { appAtomRegistry } from "./atom-registry"; import { setPendingConnectionError } from "./use-remote-environment-registry"; -import { - beginVcsAction, - completeVcsAction, - failVcsAction, - showGitActionResult, -} from "./use-vcs-action-state"; +import { showGitActionResult } from "./use-vcs-action-state"; import { useThreadSelection } from "./use-thread-selection"; import { useSelectedThreadWorktree } from "./use-selected-thread-worktree"; export function useSelectedThreadGitActions() { - const runStackedAction = useAtomSet(gitEnvironment.runStackedAction, { mode: "promise" }); const updateThreadMetadata = useAtomSet(threadEnvironment.updateMetadata, { mode: "promise" }); const refreshStatus = useAtomSet(vcsEnvironment.refreshStatus, { mode: "promise" }); const switchRef = useAtomSet(vcsEnvironment.switchRef, { mode: "promise" }); @@ -38,6 +32,13 @@ export function useSelectedThreadGitActions() { const pull = useAtomSet(vcsEnvironment.pull, { mode: "promise" }); const { selectedThread, selectedThreadProject } = useThreadSelection(); const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree(); + const runStackedAction = useAtomSet( + vcsActionManager.runStackedAction({ + environmentId: selectedThread?.environmentId ?? null, + cwd: selectedThreadCwd, + }), + { mode: "promise" }, + ); const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null; const branchTarget = useMemo( @@ -81,26 +82,26 @@ export function useSelectedThreadGitActions() { } const target = { environmentId: selectedThread.environmentId, cwd }; - if (!options?.quiet) { - beginVcsAction(target, { - operation: "refresh_status", - label: "Refreshing source control status", - }); - } try { - const result = await refreshStatus({ - environmentId: selectedThread.environmentId, - input: { cwd }, - }); - if (!options?.quiet) { - completeVcsAction(target); - } + const execute = () => + refreshStatus({ + environmentId: selectedThread.environmentId, + input: { cwd }, + }); + const result = options?.quiet + ? await execute() + : await vcsActionManager.track( + appAtomRegistry, + target, + { + operation: "refresh_status", + label: "Refreshing source control status", + }, + execute, + ); setPendingConnectionError(null); return result; } catch (error) { - if (!options?.quiet) { - failVcsAction(target, "refresh_status", error); - } const message = error instanceof Error ? error.message : "Failed to refresh git status."; setPendingConnectionError(message); return null; @@ -125,6 +126,7 @@ export function useSelectedThreadGitActions() { readonly project: EnvironmentProject; readonly cwd: string; }) => Promise, + options?: { readonly managedExternally?: boolean }, ): Promise => { if (!selectedThread || !selectedThreadProject || !selectedThreadCwd) { return null; @@ -134,18 +136,20 @@ export function useSelectedThreadGitActions() { environmentId: selectedThread.environmentId, cwd: selectedThreadCwd, }; - beginVcsAction(target, { operation, label }); try { setPendingConnectionError(null); - const result = await execute({ - thread: selectedThread, - project: selectedThreadProject, - cwd: selectedThreadCwd, - }); - completeVcsAction(target); + const run = () => + execute({ + thread: selectedThread, + project: selectedThreadProject, + cwd: selectedThreadCwd, + }); + const result = + options?.managedExternally === true + ? await run() + : await vcsActionManager.track(appAtomRegistry, target, { operation, label }, run); return result; } catch (error) { - failVcsAction(target, operation, error); const message = error instanceof Error ? error.message : "Git action failed."; setPendingConnectionError(message); showGitActionResult({ type: "error", title: "Git action failed", description: message }); @@ -290,29 +294,19 @@ export function useSelectedThreadGitActions() { const onRunSelectedThreadGitAction = useCallback( async (input: GitActionRequestInput): Promise => { + const actionId = uuidv4(); return await runSelectedThreadGitMutation( "run_change_request", "Running source control action", async ({ thread, cwd }) => { - const event = await runStackedAction({ - environmentId: thread.environmentId, - input: { - cwd, - actionId: uuidv4(), - action: input.action, - ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}), - ...(input.featureBranch ? { featureBranch: input.featureBranch } : {}), - ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}), - }, + const result = await runStackedAction({ + actionId, + action: input.action, + ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}), + ...(input.featureBranch ? { featureBranch: input.featureBranch } : {}), + ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}), }); - if (event.kind === "action_failed") { - throw new Error(event.message); - } - if (event.kind !== "action_finished") { - throw new Error("Source control action ended without a result."); - } - const result = event.result; showGitActionResult({ type: "success", title: result.toast.title, @@ -334,6 +328,7 @@ export function useSelectedThreadGitActions() { } return result; }, + { managedExternally: true }, ); }, [ diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index a3200a3840..d7b66751d0 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -27,7 +27,8 @@ import { import { setPendingConnectionError } from "../state/use-remote-environment-registry"; import { useSelectedThreadDetail } from "../state/use-thread-detail"; import { useThreadSelection } from "../state/use-thread-selection"; -import { enqueueThreadOutboxMessage, useThreadOutboxMessages } from "./thread-outbox"; +import { enqueueThreadOutboxMessage } from "./thread-outbox"; +import { useThreadOutboxMessages } from "./use-thread-outbox"; import { dispatchingQueuedMessageIdAtom } from "./use-thread-outbox-drain"; export function appendReviewCommentToDraft(input: { diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/use-thread-outbox-drain.ts index 6a9277d616..a9adba097b 100644 --- a/apps/mobile/src/state/use-thread-outbox-drain.ts +++ b/apps/mobile/src/state/use-thread-outbox-drain.ts @@ -7,15 +7,15 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { scopedThreadKey } from "../lib/scopedEntities"; import { appAtomRegistry } from "./atom-registry"; import { useThreadShells } from "./entities"; +import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox"; import { - ensureThreadOutboxLoaded, - removeThreadOutboxMessage, + resolveThreadOutboxDeliveryAction, shouldRetryThreadOutboxDelivery, threadOutboxRetryDelayMs, type QueuedThreadMessage, - useThreadOutboxMessages, -} from "./thread-outbox"; +} from "./thread-outbox-model"; import { threadEnvironment } from "./threads"; +import { useThreadOutboxMessages, useThreadOutboxShellStatuses } from "./use-thread-outbox"; import { useRemoteConnectionStatus } from "./use-remote-environment-registry"; export const dispatchingQueuedMessageIdAtom = Atom.make(null).pipe( @@ -46,6 +46,7 @@ export function useThreadOutboxDrain(): void { const startTurn = useAtomSet(threadEnvironment.startTurn, { mode: "promise" }); const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom); const queuedMessagesByThreadKey = useThreadOutboxMessages(); + const shellStatuses = useThreadOutboxShellStatuses(); const threads = useThreadShells(); const { connectedEnvironments } = useRemoteConnectionStatus(); const [retryTick, setRetryTick] = useState(0); @@ -64,13 +65,7 @@ export function useThreadOutboxDrain(): void { }, []); const sendQueuedMessage = useCallback( - async (queuedMessage: QueuedThreadMessage) => { - const thread = findThread(threads, queuedMessage); - if (!thread) { - await removeThreadOutboxMessage(queuedMessage); - return true; - } - + async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => { try { await startTurn({ environmentId: queuedMessage.environmentId, @@ -88,8 +83,6 @@ export function useThreadOutboxDrain(): void { createdAt: queuedMessage.createdAt, }, }); - await removeThreadOutboxMessage(queuedMessage); - return true; } catch (error) { const retry = shouldRetryThreadOutboxDelivery(error); console.warn("[thread-outbox] queued message delivery failed", { @@ -102,11 +95,22 @@ export function useThreadOutboxDrain(): void { if (retry) { return false; } + } + + try { await removeThreadOutboxMessage(queuedMessage); return true; + } catch (error) { + console.warn("[thread-outbox] failed to remove delivered queued message", { + environmentId: queuedMessage.environmentId, + threadId: queuedMessage.threadId, + messageId: queuedMessage.messageId, + error, + }); + return false; } }, - [startTurn, threads], + [startTurn], ); useEffect(() => { @@ -124,23 +128,42 @@ export function useThreadOutboxDrain(): void { } const thread = findThread(threads, nextQueuedMessage); - if (!thread || scopedThreadKey(thread.environmentId, thread.id) !== threadKey) { + if (thread && scopedThreadKey(thread.environmentId, thread.id) !== threadKey) { continue; } const environment = connectedEnvironments.find( (candidate) => candidate.environmentId === nextQueuedMessage.environmentId, ); - if (!environment || environment.connectionState !== "connected") { - continue; - } - - if (thread.session?.status === "running" || thread.session?.status === "starting") { + const deliveryAction = resolveThreadOutboxDeliveryAction({ + threadExists: thread !== undefined, + shellStatus: shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty", + environmentConnected: environment?.connectionState === "connected", + threadBusy: thread?.session?.status === "running" || thread?.session?.status === "starting", + }); + if (deliveryAction === "wait") { continue; } beginDispatchingQueuedMessage(nextQueuedMessage.messageId); - void sendQueuedMessage(nextQueuedMessage) + const delivery = + deliveryAction === "remove" + ? removeThreadOutboxMessage(nextQueuedMessage).then( + () => true, + (error) => { + console.warn("[thread-outbox] failed to remove message for a missing thread", { + environmentId: nextQueuedMessage.environmentId, + threadId: nextQueuedMessage.threadId, + messageId: nextQueuedMessage.messageId, + error, + }); + return false; + }, + ) + : thread !== undefined + ? sendQueuedMessage(nextQueuedMessage, thread) + : Promise.resolve(false); + void delivery .then((sent) => { if (sent) { retryAttemptRef.current.delete(nextQueuedMessage.messageId); @@ -178,6 +201,7 @@ export function useThreadOutboxDrain(): void { queuedMessagesByThreadKey, retryTick, sendQueuedMessage, + shellStatuses, threads, ]); } diff --git a/apps/mobile/src/state/use-thread-outbox.ts b/apps/mobile/src/state/use-thread-outbox.ts new file mode 100644 index 0000000000..fb090cd088 --- /dev/null +++ b/apps/mobile/src/state/use-thread-outbox.ts @@ -0,0 +1,28 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { Atom } from "effect/unstable/reactivity"; + +import { environmentShell } from "./shell"; +import { threadOutboxManager } from "./thread-outbox"; + +const threadOutboxShellStatusesAtom = Atom.make( + (get): ReadonlyMap => { + const statuses = new Map(); + for (const queue of Object.values(get(threadOutboxManager.queuedMessagesByThreadKeyAtom))) { + const environmentId = queue[0]?.environmentId; + if (environmentId !== undefined && !statuses.has(environmentId)) { + statuses.set(environmentId, get(environmentShell.stateValueAtom(environmentId)).status); + } + } + return statuses; + }, +).pipe(Atom.withLabel("mobile:thread-outbox:shell-statuses")); + +export function useThreadOutboxMessages() { + return useAtomValue(threadOutboxManager.queuedMessagesByThreadKeyAtom); +} + +export function useThreadOutboxShellStatuses() { + return useAtomValue(threadOutboxShellStatusesAtom); +} diff --git a/apps/mobile/src/state/use-vcs-action-state.ts b/apps/mobile/src/state/use-vcs-action-state.ts index a63a0c085f..4cba19fdb0 100644 --- a/apps/mobile/src/state/use-vcs-action-state.ts +++ b/apps/mobile/src/state/use-vcs-action-state.ts @@ -1,83 +1,11 @@ import { useAtomValue } from "@effect/atom-react"; -import { - applyVcsActionProgressEvent, - EMPTY_VCS_ACTION_ATOM, - EMPTY_VCS_ACTION_STATE, - getVcsActionTargetKey, - type VcsActionState, - type VcsActionTarget, - vcsActionStateAtom, -} from "@t3tools/client-runtime/state/vcs"; -import type { GitActionProgressEvent } from "@t3tools/contracts"; -import * as Option from "effect/Option"; -import { AsyncResult } from "effect/unstable/reactivity"; +import { type VcsActionState, type VcsActionTarget } from "@t3tools/client-runtime/state/vcs"; import { useCallback, useEffect, useRef, useState } from "react"; -import { appAtomRegistry } from "./atom-registry"; -import { gitEnvironment } from "./git"; - -function setVcsActionState(target: VcsActionTarget, state: VcsActionState): void { - const targetKey = getVcsActionTargetKey(target); - if (targetKey !== null) { - appAtomRegistry.set(vcsActionStateAtom(targetKey), state); - } -} - -export function beginVcsAction( - target: VcsActionTarget, - input: { - readonly operation: VcsActionState["operation"]; - readonly label: string; - }, -): void { - setVcsActionState(target, { - ...EMPTY_VCS_ACTION_STATE, - isRunning: true, - operation: input.operation, - currentLabel: input.label, - currentPhaseLabel: input.label, - phaseStartedAtMs: Date.now(), - }); -} - -export function completeVcsAction(target: VcsActionTarget): void { - setVcsActionState(target, EMPTY_VCS_ACTION_STATE); -} - -export function failVcsAction( - target: VcsActionTarget, - operation: VcsActionState["operation"], - error: unknown, -): void { - setVcsActionState(target, { - ...EMPTY_VCS_ACTION_STATE, - operation, - error: error instanceof Error ? error.message : "Source control action failed.", - }); -} +import { vcsActionManager } from "./vcs"; export function useVcsActionState(target: VcsActionTarget): VcsActionState { - const targetKey = getVcsActionTargetKey(target); - const runStackedActionState = useAtomValue(gitEnvironment.runStackedAction); - const state = useAtomValue( - targetKey !== null ? vcsActionStateAtom(targetKey) : EMPTY_VCS_ACTION_ATOM, - ); - - useEffect(() => { - const event = Option.getOrNull(AsyncResult.value(runStackedActionState)); - if (event === null || targetKey === null || event.cwd !== target.cwd) { - return; - } - appAtomRegistry.set( - vcsActionStateAtom(targetKey), - applyVcsActionProgressEvent( - appAtomRegistry.get(vcsActionStateAtom(targetKey)), - event as GitActionProgressEvent, - ), - ); - }, [runStackedActionState, target.cwd, targetKey]); - - return targetKey === null ? EMPTY_VCS_ACTION_STATE : state; + return useAtomValue(vcsActionManager.stateAtom(target)); } export interface GitActionResultNotification { diff --git a/apps/mobile/src/state/vcs.ts b/apps/mobile/src/state/vcs.ts index af18fe0bd9..dc8c251149 100644 --- a/apps/mobile/src/state/vcs.ts +++ b/apps/mobile/src/state/vcs.ts @@ -1,5 +1,9 @@ -import { createVcsEnvironmentAtoms } from "@t3tools/client-runtime/state/vcs"; +import { + createVcsActionManager, + createVcsEnvironmentAtoms, +} from "@t3tools/client-runtime/state/vcs"; import { connectionAtomRuntime } from "../connection/runtime"; export const vcsEnvironment = createVcsEnvironmentAtoms(connectionAtomRuntime); +export const vcsActionManager = createVcsActionManager(connectionAtomRuntime); diff --git a/apps/web/src/clientPersistenceStorage.test.ts b/apps/web/src/clientPersistenceStorage.test.ts index e2cf84ccc7..6c449eea2b 100644 --- a/apps/web/src/clientPersistenceStorage.test.ts +++ b/apps/web/src/clientPersistenceStorage.test.ts @@ -1,23 +1,6 @@ -import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -const testEnvironmentId = EnvironmentId.make("environment-1"); - -const savedRegistryRecord: PersistedSavedEnvironmentRecord = { - environmentId: testEnvironmentId, - label: "Remote environment", - httpBaseUrl: "https://remote.example.com/", - wsBaseUrl: "wss://remote.example.com/", - createdAt: "2026-04-09T00:00:00.000Z", - lastConnectedAt: null, - desktopSsh: { - alias: "devbox", - hostname: "devbox.example.com", - username: "julius", - port: 22, - }, -}; - function createLocalStorageStub(): Storage { const store = new Map(); return { @@ -55,32 +38,17 @@ afterEach(() => { }); describe("clientPersistenceStorage", () => { - it("stores browser secrets inline with the saved environment record", async () => { - const testWindow = getTestWindow(); - const { - SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY, - readBrowserSavedEnvironmentRegistry, - readBrowserSavedEnvironmentSecret, - writeBrowserSavedEnvironmentRegistry, - writeBrowserSavedEnvironmentSecret, - } = await import("./clientPersistenceStorage"); + it("persists client settings in browser storage", async () => { + getTestWindow(); + const { readBrowserClientSettings, writeBrowserClientSettings } = + await import("./clientPersistenceStorage"); + const settings = { + ...DEFAULT_CLIENT_SETTINGS, + timestampFormat: "24-hour" as const, + }; - writeBrowserSavedEnvironmentRegistry([savedRegistryRecord]); - expect(writeBrowserSavedEnvironmentSecret(testEnvironmentId, "bearer-token")).toBe(true); - writeBrowserSavedEnvironmentRegistry([savedRegistryRecord]); + writeBrowserClientSettings(settings); - expect(readBrowserSavedEnvironmentRegistry()).toEqual([savedRegistryRecord]); - expect(readBrowserSavedEnvironmentSecret(testEnvironmentId)).toBe("bearer-token"); - expect( - JSON.parse(testWindow.localStorage.getItem(SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY)!), - ).toEqual({ - version: 1, - records: [ - { - ...savedRegistryRecord, - bearerToken: "bearer-token", - }, - ], - }); + expect(readBrowserClientSettings()).toEqual(settings); }); }); diff --git a/apps/web/src/clientPersistenceStorage.ts b/apps/web/src/clientPersistenceStorage.ts index 2838f50288..b6a9f1f8e0 100644 --- a/apps/web/src/clientPersistenceStorage.ts +++ b/apps/web/src/clientPersistenceStorage.ts @@ -1,66 +1,13 @@ -import { - ClientSettingsSchema, - EnvironmentId, - type ClientSettings, - type EnvironmentId as EnvironmentIdValue, - type PersistedSavedEnvironmentRecord, -} from "@t3tools/contracts"; -import * as Schema from "effect/Schema"; +import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts"; import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage"; export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1"; -export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1"; - -const BrowserSavedEnvironmentRecordSchema = Schema.Struct({ - environmentId: EnvironmentId, - label: Schema.String, - httpBaseUrl: Schema.String, - wsBaseUrl: Schema.String, - createdAt: Schema.String, - lastConnectedAt: Schema.NullOr(Schema.String), - desktopSsh: Schema.optionalKey( - Schema.Struct({ - alias: Schema.String, - hostname: Schema.String, - username: Schema.NullOr(Schema.String), - port: Schema.NullOr(Schema.Number), - }), - ), - relayManaged: Schema.optionalKey(Schema.Struct({ relayUrl: Schema.String })), - bearerToken: Schema.optionalKey(Schema.String), -}); -type BrowserSavedEnvironmentRecord = typeof BrowserSavedEnvironmentRecordSchema.Type; - -const BrowserSavedEnvironmentRegistryDocumentSchema = Schema.Struct({ - version: Schema.optionalKey(Schema.Number), - records: Schema.optionalKey(Schema.Array(BrowserSavedEnvironmentRecordSchema)), -}); -type BrowserSavedEnvironmentRegistryDocument = - typeof BrowserSavedEnvironmentRegistryDocumentSchema.Type; function hasWindow(): boolean { return typeof window !== "undefined"; } -function toPersistedSavedEnvironmentRecord( - record: PersistedSavedEnvironmentRecord, -): PersistedSavedEnvironmentRecord { - const nextRecord = { - environmentId: record.environmentId, - label: record.label, - httpBaseUrl: record.httpBaseUrl, - wsBaseUrl: record.wsBaseUrl, - createdAt: record.createdAt, - lastConnectedAt: record.lastConnectedAt, - }; - return { - ...nextRecord, - ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}), - ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}), - }; -} - export function readBrowserClientSettings(): ClientSettings | null { if (!hasWindow()) { return null; @@ -80,138 +27,3 @@ export function writeBrowserClientSettings(settings: ClientSettings): void { setLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, settings, ClientSettingsSchema); } - -function readBrowserSavedEnvironmentRegistryDocument(): BrowserSavedEnvironmentRegistryDocument { - if (!hasWindow()) { - return {}; - } - - try { - const parsed = getLocalStorageItem( - SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY, - BrowserSavedEnvironmentRegistryDocumentSchema, - ); - return parsed ?? {}; - } catch { - return {}; - } -} - -function writeBrowserSavedEnvironmentRegistryDocument( - document: BrowserSavedEnvironmentRegistryDocument, -): void { - if (!hasWindow()) { - return; - } - - setLocalStorageItem( - SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY, - document, - BrowserSavedEnvironmentRegistryDocumentSchema, - ); -} - -function readBrowserSavedEnvironmentRecordsWithSecrets(): ReadonlyArray { - return readBrowserSavedEnvironmentRegistryDocument().records ?? []; -} - -function writeBrowserSavedEnvironmentRecords( - records: ReadonlyArray, -): void { - writeBrowserSavedEnvironmentRegistryDocument({ - version: 1, - records, - }); -} - -export function readBrowserSavedEnvironmentRegistry(): ReadonlyArray { - return readBrowserSavedEnvironmentRecordsWithSecrets().map((record) => - toPersistedSavedEnvironmentRecord(record), - ); -} - -export function writeBrowserSavedEnvironmentRegistry( - records: ReadonlyArray, -): void { - const existing = new Map( - readBrowserSavedEnvironmentRecordsWithSecrets().map( - (record) => [record.environmentId, record] as const, - ), - ); - writeBrowserSavedEnvironmentRecords( - records.map((record) => { - const bearerToken = existing.get(record.environmentId)?.bearerToken; - return bearerToken - ? { - environmentId: record.environmentId, - label: record.label, - httpBaseUrl: record.httpBaseUrl, - wsBaseUrl: record.wsBaseUrl, - createdAt: record.createdAt, - lastConnectedAt: record.lastConnectedAt, - ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}), - ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}), - bearerToken, - } - : toPersistedSavedEnvironmentRecord(record); - }), - ); -} - -export function readBrowserSavedEnvironmentSecret( - environmentId: EnvironmentIdValue, -): string | null { - return ( - readBrowserSavedEnvironmentRecordsWithSecrets().find( - (record) => record.environmentId === environmentId, - )?.bearerToken ?? null - ); -} - -export function writeBrowserSavedEnvironmentSecret( - environmentId: EnvironmentIdValue, - secret: string, -): boolean { - const document = readBrowserSavedEnvironmentRegistryDocument(); - const records = document.records ?? []; - let found = false; - writeBrowserSavedEnvironmentRegistryDocument({ - version: document.version ?? 1, - // The persistence update is copy-on-write so storage subscribers observe a new document. - // oxlint-disable-next-line oxc/no-map-spread - records: records.map((record) => { - if (record.environmentId !== environmentId) { - return record; - } - found = true; - const nextRecord: BrowserSavedEnvironmentRecord = { - environmentId: record.environmentId, - label: record.label, - httpBaseUrl: record.httpBaseUrl, - wsBaseUrl: record.wsBaseUrl, - createdAt: record.createdAt, - lastConnectedAt: record.lastConnectedAt, - bearerToken: secret, - }; - return { - ...nextRecord, - ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}), - ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}), - }; - }), - }); - return found; -} - -export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentIdValue): void { - const document = readBrowserSavedEnvironmentRegistryDocument(); - writeBrowserSavedEnvironmentRegistryDocument({ - version: document.version ?? 1, - records: (document.records ?? []).map((record) => { - if (record.environmentId !== environmentId) { - return record; - } - return toPersistedSavedEnvironmentRecord(record); - }), - }); -} diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index a55c389236..be30408968 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -820,11 +820,6 @@ const createDesktopBridgeStub = (overrides?: { }), getClientSettings: vi.fn().mockResolvedValue(null), setClientSettings: vi.fn().mockResolvedValue(undefined), - getSavedEnvironmentRegistry: vi.fn().mockResolvedValue([]), - setSavedEnvironmentRegistry: vi.fn().mockResolvedValue(undefined), - getSavedEnvironmentSecret: vi.fn().mockResolvedValue(null), - setSavedEnvironmentSecret: vi.fn().mockResolvedValue(true), - removeSavedEnvironmentSecret: vi.fn().mockResolvedValue(undefined), discoverSshHosts: overrides?.discoverSshHosts ?? vi.fn().mockResolvedValue([]), ensureSshEnvironment: vi.fn().mockImplementation(async (target) => ({ target, diff --git a/apps/web/src/connection/platform.test.ts b/apps/web/src/connection/platform.test.ts new file mode 100644 index 0000000000..2b428e2669 --- /dev/null +++ b/apps/web/src/connection/platform.test.ts @@ -0,0 +1,88 @@ +import { + AuthStandardClientScopes, + EnvironmentId, + type DesktopBridge, + type DesktopSshEnvironmentTarget, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; + +import { provisionDesktopSshEnvironment } from "./platform.ts"; + +const TARGET: DesktopSshEnvironmentTarget = { + alias: "devbox", + hostname: "devbox.example.test", + username: "developer", + port: 22, +}; + +function makeBridge( + calls: string[], + options?: { readonly failDescriptor?: boolean }, +): DesktopBridge { + return { + ensureSshEnvironment: async (target: DesktopSshEnvironmentTarget) => { + calls.push("ensure"); + return { + target, + httpBaseUrl: "http://127.0.0.1:3201/", + wsBaseUrl: "ws://127.0.0.1:3201/", + pairingToken: "pairing-token", + }; + }, + fetchSshEnvironmentDescriptor: async () => { + calls.push("descriptor"); + if (options?.failDescriptor === true) { + throw new Error("descriptor unavailable"); + } + return { + environmentId: EnvironmentId.make("environment-ssh"), + label: "SSH environment", + platform: { + os: "linux", + arch: "x64", + }, + serverVersion: "0.0.0-test", + capabilities: { + repositoryIdentity: true, + }, + }; + }, + bootstrapSshBearerSession: async () => { + calls.push("token"); + return { + access_token: "bearer-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "Bearer", + expires_in: 3_600, + scope: AuthStandardClientScopes.join(" "), + }; + }, + } as unknown as DesktopBridge; +} + +describe("desktop SSH pairing", () => { + it.effect("fetches the descriptor before consuming the one-time credential", () => + Effect.gen(function* () { + const calls: string[] = []; + + const provisioned = yield* provisionDesktopSshEnvironment(makeBridge(calls), TARGET); + + expect(provisioned.environmentId).toBe(EnvironmentId.make("environment-ssh")); + expect(calls).toEqual(["ensure", "descriptor", "token"]); + }), + ); + + it.effect("does not consume the credential when descriptor discovery fails", () => + Effect.gen(function* () { + const calls: string[] = []; + + yield* provisionDesktopSshEnvironment( + makeBridge(calls, { failDescriptor: true }), + TARGET, + ).pipe(Effect.flip); + + expect(calls).toEqual(["ensure", "descriptor"]); + }), + ); +}); diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts index 16d0f7c203..3a2f418db5 100644 --- a/apps/web/src/connection/platform.ts +++ b/apps/web/src/connection/platform.ts @@ -18,7 +18,11 @@ import { import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment"; import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay"; import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc"; -import { AuthStandardClientScopes } from "@t3tools/contracts"; +import { + AuthStandardClientScopes, + type DesktopBridge, + type DesktopSshEnvironmentTarget, +} from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -127,6 +131,39 @@ function sshPreparationError(cause: unknown) { }); } +export const provisionDesktopSshEnvironment = Effect.fn( + "web.connectionPlatform.ssh.provisionDesktop", +)(function* (bridge: DesktopBridge, target: DesktopSshEnvironmentTarget) { + const bootstrap = yield* Effect.tryPromise({ + try: () => + bridge.ensureSshEnvironment(target, { + issuePairingToken: true, + }), + catch: sshPreparationError, + }); + const pairingToken = bootstrap.pairingToken; + if (pairingToken === null) { + return yield* new ConnectionBlockedError({ + reason: "authentication", + message: "The SSH environment did not issue a pairing credential.", + }); + } + const descriptor = yield* Effect.tryPromise({ + try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl), + catch: sshPreparationError, + }); + const access = yield* Effect.tryPromise({ + try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken), + catch: sshPreparationError, + }); + return { + environmentId: descriptor.environmentId, + label: descriptor.label, + bootstrap, + bearerToken: access.access_token, + }; +}); + const capabilitiesLayer = Layer.effectContext( Effect.sync(() => { const presentation = ClientPresentation.of({ @@ -172,39 +209,7 @@ const capabilitiesLayer = Layer.effectContext( message: "SSH environments are only available in the desktop app.", }); } - const bootstrap = yield* Effect.tryPromise({ - try: () => - bridge.ensureSshEnvironment(target, { - issuePairingToken: true, - }), - catch: sshPreparationError, - }); - if (bootstrap.pairingToken === null) { - return yield* new ConnectionBlockedError({ - reason: "authentication", - message: "The SSH environment did not issue a pairing credential.", - }); - } - const { descriptor, access } = yield* Effect.all( - { - descriptor: Effect.tryPromise({ - try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl), - catch: sshPreparationError, - }), - access: Effect.tryPromise({ - try: () => - bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!), - catch: sshPreparationError, - }), - }, - { concurrency: "unbounded" }, - ); - return { - environmentId: descriptor.environmentId, - label: descriptor.label, - bootstrap, - bearerToken: access.access_token, - }; + return yield* provisionDesktopSshEnvironment(bridge, target); }), prepare: Effect.fn("web.connectionPlatform.ssh.prepare")(function* (input) { const bridge = window.desktopBridge; diff --git a/apps/web/src/connection/storage.test.ts b/apps/web/src/connection/storage.test.ts index 624a9a34e6..0f0656dee9 100644 --- a/apps/web/src/connection/storage.test.ts +++ b/apps/web/src/connection/storage.test.ts @@ -3,8 +3,9 @@ import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; +import { afterEach, vi } from "vite-plus/test"; -import { makeCatalogStore } from "./storage"; +import { makeCatalogBackend, makeCatalogStore } from "./storage"; const emptyCatalog = { schemaVersion: 1, @@ -15,6 +16,11 @@ const emptyCatalog = { } as const; const decodeCatalog = Schema.decodeUnknownSync(Schema.fromJsonString(ConnectionCatalogDocument)); +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + describe("makeCatalogStore", () => { it.effect("quarantines malformed catalogs and starts from an empty document", () => Effect.gen(function* () { @@ -48,3 +54,24 @@ describe("makeCatalogStore", () => { }), ); }); + +describe("makeCatalogBackend", () => { + it.effect("fails writes when desktop secure storage declines the catalog", () => + Effect.gen(function* () { + const setConnectionCatalog = vi.fn().mockResolvedValue(false); + vi.stubGlobal("window", { + desktopBridge: { + getConnectionCatalog: vi.fn().mockResolvedValue(null), + setConnectionCatalog, + }, + }); + const backend = makeCatalogBackend({} as IDBDatabase); + + const error = yield* backend.write("{}").pipe(Effect.flip); + + expect(error).toBeInstanceOf(ConnectionTransientError); + expect(error.message).toContain("Desktop secure storage is unavailable"); + expect(setConnectionCatalog).toHaveBeenCalledWith("{}"); + }), + ); +}); diff --git a/apps/web/src/connection/storage.ts b/apps/web/src/connection/storage.ts index 2f2246de59..19a4a8454e 100644 --- a/apps/web/src/connection/storage.ts +++ b/apps/web/src/connection/storage.ts @@ -208,13 +208,13 @@ const encodeCatalog = Effect.fn("web.connectionStorage.encodeCatalog")(function* ); }); -interface CatalogBackend { +export interface CatalogBackend { readonly read: Effect.Effect; readonly write: (raw: string) => Effect.Effect; readonly quarantine?: (raw: string) => Effect.Effect; } -function makeCatalogBackend(database: IDBDatabase): CatalogBackend { +export function makeCatalogBackend(database: IDBDatabase): CatalogBackend { const bridge = window.desktopBridge; if (bridge?.getConnectionCatalog !== undefined && bridge.setConnectionCatalog !== undefined) { return { @@ -230,8 +230,11 @@ function makeCatalogBackend(database: IDBDatabase): CatalogBackend { Effect.flatMap((stored) => stored ? Effect.void - : Effect.logWarning( - "Desktop secure storage is unavailable; connection changes will be kept only for this session.", + : Effect.fail( + catalogError( + "save", + "Desktop secure storage is unavailable in this system context.", + ), ), ), ), diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts index 2e8534f1b5..3379f5ed98 100644 --- a/apps/web/src/localApi.test.ts +++ b/apps/web/src/localApi.test.ts @@ -1,5 +1,8 @@ -import type { ContextMenuItem, DesktopBridge } from "@t3tools/contracts"; -import { EnvironmentId } from "@t3tools/contracts"; +import { + DEFAULT_CLIENT_SETTINGS, + type ContextMenuItem, + type DesktopBridge, +} from "@t3tools/contracts"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; const showContextMenuFallbackMock = @@ -82,60 +85,40 @@ describe("LocalApi", () => { it("delegates host capabilities and persistence to the desktop bridge", async () => { const showContextMenu = vi.fn().mockResolvedValue("delete"); const pickFolder = vi.fn().mockResolvedValue("/tmp/project"); - const getSavedEnvironmentSecret = vi.fn().mockResolvedValue("secret"); - const setSavedEnvironmentSecret = vi.fn().mockResolvedValue(true); - const removeSavedEnvironmentSecret = vi.fn().mockResolvedValue(undefined); + const getClientSettings = vi.fn().mockResolvedValue(DEFAULT_CLIENT_SETTINGS); + const setClientSettings = vi.fn().mockResolvedValue(undefined); testWindow().desktopBridge = { showContextMenu, pickFolder, - getSavedEnvironmentSecret, - setSavedEnvironmentSecret, - removeSavedEnvironmentSecret, + getClientSettings, + setClientSettings, } as unknown as DesktopBridge; const { createLocalApi } = await import("./localApi"); const api = createLocalApi(); - const environmentId = EnvironmentId.make("environment-1"); const items = [{ id: "delete", label: "Delete" }] as const; await expect(api.contextMenu.show(items)).resolves.toBe("delete"); await expect(api.dialogs.pickFolder({ initialPath: "/tmp" })).resolves.toBe("/tmp/project"); - await expect(api.persistence.getSavedEnvironmentSecret(environmentId)).resolves.toBe("secret"); - await expect(api.persistence.setSavedEnvironmentSecret(environmentId, "next")).resolves.toBe( - true, - ); - await api.persistence.removeSavedEnvironmentSecret(environmentId); + await expect(api.persistence.getClientSettings()).resolves.toEqual(DEFAULT_CLIENT_SETTINGS); + await api.persistence.setClientSettings(DEFAULT_CLIENT_SETTINGS); expect(showContextMenu).toHaveBeenCalledWith(items, undefined); expect(pickFolder).toHaveBeenCalledWith({ initialPath: "/tmp" }); - expect(getSavedEnvironmentSecret).toHaveBeenCalledWith(environmentId); - expect(setSavedEnvironmentSecret).toHaveBeenCalledWith(environmentId, "next"); - expect(removeSavedEnvironmentSecret).toHaveBeenCalledWith(environmentId); + expect(getClientSettings).toHaveBeenCalledTimes(1); + expect(setClientSettings).toHaveBeenCalledWith(DEFAULT_CLIENT_SETTINGS); }); - it("persists connection records and secrets in browser storage", async () => { + it("persists client settings in browser storage", async () => { const { createLocalApi } = await import("./localApi"); const api = createLocalApi(); - const environmentId = EnvironmentId.make("environment-1"); - const records = [ - { - environmentId, - label: "Remote", - httpBaseUrl: "https://remote.example.test", - wsBaseUrl: "wss://remote.example.test", - createdAt: "2026-06-06T00:00:00.000Z", - lastConnectedAt: null, - }, - ]; + const settings = { + ...DEFAULT_CLIENT_SETTINGS, + timestampFormat: "12-hour" as const, + }; - await api.persistence.setSavedEnvironmentRegistry(records); - await api.persistence.setSavedEnvironmentSecret(environmentId, "secret"); - - await expect(api.persistence.getSavedEnvironmentRegistry()).resolves.toEqual(records); - await expect(api.persistence.getSavedEnvironmentSecret(environmentId)).resolves.toBe("secret"); - - await api.persistence.removeSavedEnvironmentSecret(environmentId); - await expect(api.persistence.getSavedEnvironmentSecret(environmentId)).resolves.toBeNull(); + await api.persistence.setClientSettings(settings); + await expect(api.persistence.getClientSettings()).resolves.toEqual(settings); }); it("prefers the native LocalApi when one is injected", async () => { diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.ts index 484dd7bb78..2fbf183f91 100644 --- a/apps/web/src/localApi.ts +++ b/apps/web/src/localApi.ts @@ -2,15 +2,7 @@ import type { ContextMenuItem, LocalApi } from "@t3tools/contracts"; import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState"; import { showContextMenuFallback } from "./contextMenuFallback"; -import { - readBrowserClientSettings, - readBrowserSavedEnvironmentRegistry, - readBrowserSavedEnvironmentSecret, - removeBrowserSavedEnvironmentSecret, - writeBrowserClientSettings, - writeBrowserSavedEnvironmentRegistry, - writeBrowserSavedEnvironmentSecret, -} from "./clientPersistenceStorage"; +import { readBrowserClientSettings, writeBrowserClientSettings } from "./clientPersistenceStorage"; let cachedApi: LocalApi | undefined; @@ -70,36 +62,6 @@ function createBrowserLocalApi(): LocalApi { } writeBrowserClientSettings(settings); }, - getSavedEnvironmentRegistry: async () => { - if (window.desktopBridge) { - return window.desktopBridge.getSavedEnvironmentRegistry(); - } - return readBrowserSavedEnvironmentRegistry(); - }, - setSavedEnvironmentRegistry: async (records) => { - if (window.desktopBridge) { - return window.desktopBridge.setSavedEnvironmentRegistry(records); - } - writeBrowserSavedEnvironmentRegistry(records); - }, - getSavedEnvironmentSecret: async (environmentId) => { - if (window.desktopBridge) { - return window.desktopBridge.getSavedEnvironmentSecret(environmentId); - } - return readBrowserSavedEnvironmentSecret(environmentId); - }, - setSavedEnvironmentSecret: async (environmentId, secret) => { - if (window.desktopBridge) { - return window.desktopBridge.setSavedEnvironmentSecret(environmentId, secret); - } - return writeBrowserSavedEnvironmentSecret(environmentId, secret); - }, - removeSavedEnvironmentSecret: async (environmentId) => { - if (window.desktopBridge) { - return window.desktopBridge.removeSavedEnvironmentSecret(environmentId); - } - removeBrowserSavedEnvironmentSecret(environmentId); - }, }, server: { getConfig: () => Promise.reject(unavailableLocalBackendError()), diff --git a/apps/web/src/state/sourceControlActions.test.ts b/apps/web/src/state/sourceControlActions.test.ts deleted file mode 100644 index b4ef12cb9f..0000000000 --- a/apps/web/src/state/sourceControlActions.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { EnvironmentId, type GitActionProgressEvent } from "@t3tools/contracts"; -import { describe, expect, it, vi } from "@effect/vitest"; - -import { createGitActionTransportId, deliverGitActionProgress } from "./sourceControlActions"; - -const cwd = "/workspace"; -const actionId = "shared-action-id"; - -function progress(actionId: string): GitActionProgressEvent { - return { - actionId, - action: "commit_push", - cwd, - kind: "phase_started", - phase: "push", - label: "Pushing...", - }; -} - -describe("source control action progress isolation", () => { - it("does not deliver same-cwd progress across environments", () => { - const environmentA = EnvironmentId.make("environment-a"); - const environmentB = EnvironmentId.make("environment-b"); - const transportActionA = createGitActionTransportId(environmentA, actionId); - const transportActionB = createGitActionTransportId(environmentB, actionId); - const onProgressA = vi.fn(); - const onProgressB = vi.fn(); - const event = progress(transportActionB); - - deliverGitActionProgress( - { - transportActionId: transportActionA, - actionId, - cwd, - onProgress: onProgressA, - }, - event, - ); - deliverGitActionProgress( - { - transportActionId: transportActionB, - actionId, - cwd, - onProgress: onProgressB, - }, - event, - ); - - expect(onProgressA).not.toHaveBeenCalled(); - expect(onProgressB).toHaveBeenCalledOnce(); - expect(onProgressB).toHaveBeenCalledWith({ - ...event, - actionId, - }); - }); -}); diff --git a/apps/web/src/state/sourceControlActions.ts b/apps/web/src/state/sourceControlActions.ts index fc0032b84e..17dd6bf4ea 100644 --- a/apps/web/src/state/sourceControlActions.ts +++ b/apps/web/src/state/sourceControlActions.ts @@ -1,4 +1,5 @@ import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import type { VcsActionOperation } from "@t3tools/client-runtime/state/vcs"; import type { EnvironmentId, GitActionProgressEvent, @@ -11,22 +12,13 @@ import type { ThreadId, VcsPullResult, } from "@t3tools/contracts"; -import * as Option from "effect/Option"; -import { AsyncResult } from "effect/unstable/reactivity"; -import { - useCallback, - useEffect, - useMemo, - useRef, - useState, - useSyncExternalStore, - useTransition, -} from "react"; +import { useCallback, useEffect } from "react"; +import { appAtomRegistry } from "../rpc/atomRegistry"; import { gitEnvironment } from "./git"; import { useEnvironmentQuery } from "./query"; import { sourceControlEnvironment } from "./sourceControl"; -import { vcsEnvironment } from "./vcs"; +import { vcsActionManager, vcsEnvironment } from "./vcs"; export type SourceControlActionKind = | "init" @@ -47,107 +39,57 @@ interface SourceControlActionState, TResult readonly resetError: () => void; } -const actionListeners = new Set<() => void>(); -const activeActionCounts = new Map(); const pullRequestResolutionCache = new Map(); -interface GitActionProgressListener { - readonly transportActionId: string; - readonly actionId: string; - readonly cwd: string; - readonly onProgress: (event: GitActionProgressEvent) => void; -} - -export function createGitActionTransportId(environmentId: EnvironmentId, actionId: string): string { - return `${environmentId.length}:${environmentId}${actionId}`; -} - -export function deliverGitActionProgress( - listener: GitActionProgressListener | null, - event: GitActionProgressEvent, -): void { - if ( - listener === null || - event.actionId !== listener.transportActionId || - event.cwd !== listener.cwd - ) { - return; - } - listener.onProgress({ - ...event, - actionId: listener.actionId, - }); -} - -function actionKey(kind: SourceControlActionKind, scope: SourceControlActionScope): string { - return `${kind}:${scope.environmentId ?? ""}:${scope.cwd ?? ""}`; -} - -function notifyActionListeners(): void { - for (const listener of actionListeners) { - listener(); - } -} - -function beginAction(key: string): () => void { - activeActionCounts.set(key, (activeActionCounts.get(key) ?? 0) + 1); - notifyActionListeners(); - let completed = false; - return () => { - if (completed) { - return; - } - completed = true; - const next = (activeActionCounts.get(key) ?? 1) - 1; - if (next <= 0) { - activeActionCounts.delete(key); - } else { - activeActionCounts.set(key, next); - } - notifyActionListeners(); - }; -} +const ACTION_OPERATION = { + init: "init", + pull: "pull", + publishRepository: "publish_repository", + runStackedAction: "run_change_request", + preparePullRequestThread: "prepare_pull_request_thread", +} as const satisfies Record; function useAction, TResult>(input: { readonly kind: SourceControlActionKind; + readonly label: string; readonly scope: SourceControlActionScope; readonly action: (...args: TArgs) => Promise; readonly onSuccess?: () => void; + readonly managedExternally?: boolean; }): SourceControlActionState { - const [error, setError] = useState(null); - const [activeCount, setActiveCount] = useState(0); - const [isTransitionPending, startTransition] = useTransition(); - const key = actionKey(input.kind, input.scope); + const operation = ACTION_OPERATION[input.kind]; + const state = useAtomValue(vcsActionManager.stateAtom(input.scope)); + const ownsState = state.operation === operation; const resetError = useCallback(() => { - startTransition(() => setError(null)); - }, []); + vcsActionManager.resetError(appAtomRegistry, input.scope, operation); + }, [input.scope, operation]); const run = useCallback( async (...args: TArgs): Promise => { - const complete = beginAction(key); - startTransition(() => { - setError(null); - setActiveCount((count) => count + 1); - }); - try { + const execute = async () => { const result = await input.action(...args); input.onSuccess?.(); return result; - } catch (cause) { - startTransition(() => setError(cause)); - throw cause; - } finally { - complete(); - startTransition(() => setActiveCount((count) => Math.max(0, count - 1))); - } + }; + return input.managedExternally === true + ? execute() + : vcsActionManager.track( + appAtomRegistry, + input.scope, + { + operation, + label: input.label, + }, + execute, + ); }, - [input.action, input.onSuccess, key], + [input.action, input.label, input.managedExternally, input.onSuccess, input.scope, operation], ); return { - error, - isPending: activeCount > 0 || isTransitionPending, + error: ownsState ? state.error : null, + isPending: ownsState && state.isRunning, resetError, run, }; @@ -167,14 +109,11 @@ export function useSourceControlActionRunning( scope: SourceControlActionScope, kinds: ReadonlyArray, ): boolean { - const stableKinds = useMemo(() => kinds.toSorted(), [kinds]); - return useSyncExternalStore( - (listener) => { - actionListeners.add(listener); - return () => actionListeners.delete(listener); - }, - () => stableKinds.some((kind) => (activeActionCounts.get(actionKey(kind, scope)) ?? 0) > 0), - () => false, + const state = useAtomValue(vcsActionManager.stateAtom(scope)); + return ( + state.isRunning && + state.operation !== null && + kinds.some((kind) => ACTION_OPERATION[kind] === state.operation) ); } @@ -187,7 +126,7 @@ export function useVcsInitAction(scope: SourceControlActionScope) { input: { cwd: target.cwd }, }); }, [init, scope]); - return useAction({ kind: "init", scope, action }); + return useAction({ kind: "init", label: "Initializing repository", scope, action }); } export function useVcsPullAction(scope: SourceControlActionScope) { @@ -209,6 +148,7 @@ export function useVcsPullAction(scope: SourceControlActionScope) { }, [pull, scope]); return useAction({ kind: "pull", + label: "Pulling latest changes", scope, action, onSuccess: status.refresh, @@ -216,10 +156,9 @@ export function useVcsPullAction(scope: SourceControlActionScope) { } export function useGitStackedAction(scope: SourceControlActionScope) { - const runStackedAction = useAtomSet(gitEnvironment.runStackedAction, { + const runStackedAction = useAtomSet(vcsActionManager.runStackedAction(scope), { mode: "promise", }); - const progress = useAtomValue(gitEnvironment.runStackedAction); const status = useEnvironmentQuery( scope.environmentId !== null && scope.cwd !== null ? vcsEnvironment.status({ @@ -228,14 +167,6 @@ export function useGitStackedAction(scope: SourceControlActionScope) { }) : null, ); - const progressListenerRef = useRef(null); - - useEffect(() => { - const event = Option.getOrNull(AsyncResult.value(progress)); - if (event !== null) { - deliverGitActionProgress(progressListenerRef.current, event); - } - }, [progress]); const action = useCallback( async (input: { @@ -246,48 +177,26 @@ export function useGitStackedAction(scope: SourceControlActionScope) { filePaths?: string[]; onProgress?: (event: GitActionProgressEvent) => void; }): Promise => { - const target = requireScope(scope, "Git action is unavailable."); - const transportActionId = createGitActionTransportId(target.environmentId, input.actionId); - progressListenerRef.current = - input.onProgress === undefined - ? null - : { - transportActionId, - actionId: input.actionId, - cwd: target.cwd, - onProgress: input.onProgress, - }; - try { - const event = await runStackedAction({ - environmentId: target.environmentId, - input: { - actionId: transportActionId, - cwd: target.cwd, - action: input.action, - ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}), - ...(input.featureBranch ? { featureBranch: true } : {}), - ...(input.filePaths?.length ? { filePaths: input.filePaths } : {}), - }, - }); - if (event.kind === "action_failed") { - throw new Error(event.message); - } - if (event.kind !== "action_finished") { - throw new Error("Source control action ended without a result."); - } - return event.result; - } finally { - progressListenerRef.current = null; - } + requireScope(scope, "Git action is unavailable."); + return runStackedAction({ + actionId: input.actionId, + action: input.action, + ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}), + ...(input.featureBranch ? { featureBranch: true } : {}), + ...(input.filePaths?.length ? { filePaths: input.filePaths } : {}), + ...(input.onProgress ? { onProgress: input.onProgress } : {}), + }); }, - [progressListenerRef, runStackedAction, scope], + [runStackedAction, scope], ); return useAction({ kind: "runStackedAction", + label: "Running source control action", scope, action, onSuccess: status.refresh, + managedExternally: true, }); } @@ -324,6 +233,7 @@ export function useSourceControlPublishRepositoryAction(scope: SourceControlActi ); return useAction({ kind: "publishRepository", + label: "Publishing repository", scope, action, onSuccess: status.refresh, @@ -349,7 +259,12 @@ export function usePreparePullRequestThreadAction(scope: SourceControlActionScop }, [preparePullRequestThread, scope], ); - return useAction({ kind: "preparePullRequestThread", scope, action }); + return useAction({ + kind: "preparePullRequestThread", + label: "Preparing pull request thread", + scope, + action, + }); } export interface PullRequestResolutionTarget { diff --git a/apps/web/src/state/vcs.ts b/apps/web/src/state/vcs.ts index af18fe0bd9..dc8c251149 100644 --- a/apps/web/src/state/vcs.ts +++ b/apps/web/src/state/vcs.ts @@ -1,5 +1,9 @@ -import { createVcsEnvironmentAtoms } from "@t3tools/client-runtime/state/vcs"; +import { + createVcsActionManager, + createVcsEnvironmentAtoms, +} from "@t3tools/client-runtime/state/vcs"; import { connectionAtomRuntime } from "../connection/runtime"; export const vcsEnvironment = createVcsEnvironmentAtoms(connectionAtomRuntime); +export const vcsActionManager = createVcsActionManager(connectionAtomRuntime); diff --git a/docs/architecture/connection-runtime.md b/docs/architecture/connection-runtime.md index 1ad5946664..06f7e6338c 100644 --- a/docs/architecture/connection-runtime.md +++ b/docs/architecture/connection-runtime.md @@ -49,9 +49,11 @@ The supervisor is the only retry owner. The UI derives `available`, `offline`, `connecting`, `reconnecting`, `connected`, and `error` from supervisor state plus explicit data-sync state. It does not infer connection health from cached data or the existence of a -transport object. A healthy RPC transport with a failed mandatory shell -subscription is shown as a synchronization error, not as a reconnect that is -not actually scheduled. +transport object. An environment becomes `connected` after the socket opens and +the initial config RPC succeeds, proving that the server is responsive. Shell +and thread synchronization are independent data states. A healthy RPC +transport with a failed shell subscription is shown as connected with a +synchronization error, not as a reconnect that is not actually scheduled. ## Data Boundary @@ -59,10 +61,12 @@ Finite requests, durable subscriptions, and commands are separate APIs: - Query atoms revalidate when the RPC generation changes. - Subscription atoms switch to replacement sessions. +- Expected subscription failures update domain sync state and wait for a + replacement session; they do not take down a healthy transport. - Mutations resolve the current environment runtime at execution time. - Shell and thread snapshots are available while offline. -- A ready transport remains `synchronizing` until the first live shell snapshot - arrives. +- A connected transport may have `empty`, `cached`, `synchronizing`, `live`, or + failed shell and thread data independently. - Cached shell and thread projections are never allowed to overwrite newer live data during a fast reconnect. - Domain atom factories route effects through the environment registry and diff --git a/packages/client-runtime/src/connection/onboarding.test.ts b/packages/client-runtime/src/connection/onboarding.test.ts index 1af021359f..9bee0dad6f 100644 --- a/packages/client-runtime/src/connection/onboarding.test.ts +++ b/packages/client-runtime/src/connection/onboarding.test.ts @@ -26,12 +26,20 @@ const CLIENT_PRESENTATION_LAYER = Layer.succeed( }), ); -function pairingHttpLayer(calls: Array<{ readonly url: string; readonly init: RequestInit }>) { +function pairingHttpLayer( + calls: Array<{ readonly url: string; readonly init: RequestInit }>, + options?: { readonly failDescriptor?: boolean }, +) { const fetchFn = ((input, init = {}) => { const url = String(input); calls.push({ url, init }); if (url.endsWith("/.well-known/t3/environment")) { + if (options?.failDescriptor === true) { + return Promise.resolve( + Response.json({ message: "descriptor unavailable" }, { status: 503 }), + ); + } return Promise.resolve( Response.json({ environmentId: "environment-paired", @@ -93,7 +101,7 @@ describe("connection onboarding", () => { token: "bearer-token", }, }); - expect(calls.map((call) => call.url).toSorted()).toEqual([ + expect(calls.map((call) => call.url)).toEqual([ "https://remote.example.test/.well-known/t3/environment", "https://remote.example.test/oauth/token", ]); @@ -110,6 +118,29 @@ describe("connection onboarding", () => { }), ); + it.effect("does not consume a pairing credential when descriptor discovery fails", () => + Effect.gen(function* () { + const calls: Array<{ readonly url: string; readonly init: RequestInit }> = []; + + yield* preparePairingRegistration({ + host: "remote.example.test", + pairingCode: "pairing-token", + }).pipe( + Effect.provide( + Layer.mergeAll( + CLIENT_PRESENTATION_LAYER, + pairingHttpLayer(calls, { failDescriptor: true }), + ), + ), + Effect.flip, + ); + + expect(calls.map((call) => call.url)).toEqual([ + "https://remote.example.test/.well-known/t3/environment", + ]); + }), + ); + it.effect("rejects invalid pairing details before making a request", () => Effect.gen(function* () { const calls: Array<{ readonly url: string; readonly init: RequestInit }> = []; diff --git a/packages/client-runtime/src/connection/onboarding.ts b/packages/client-runtime/src/connection/onboarding.ts index c1e0131a28..14f71b5859 100644 --- a/packages/client-runtime/src/connection/onboarding.ts +++ b/packages/client-runtime/src/connection/onboarding.ts @@ -82,20 +82,15 @@ export const preparePairingRegistration = Effect.fn( )(function* (input: PairingConnectionInput) { const target = yield* resolvePairingTarget(input); const presentation = yield* ClientPresentation; - const { descriptor, access } = yield* Effect.all( - { - descriptor: fetchRemoteEnvironmentDescriptor({ - httpBaseUrl: target.httpBaseUrl, - }), - access: bootstrapRemoteBearerSession({ - httpBaseUrl: target.httpBaseUrl, - credential: target.credential, - scopes: presentation.scopes, - clientMetadata: presentation.metadata, - }), - }, - { concurrency: "unbounded" }, - ).pipe(Effect.mapError(mapRemoteEnvironmentError)); + const descriptor = yield* fetchRemoteEnvironmentDescriptor({ + httpBaseUrl: target.httpBaseUrl, + }).pipe(Effect.mapError(mapRemoteEnvironmentError)); + const access = yield* bootstrapRemoteBearerSession({ + httpBaseUrl: target.httpBaseUrl, + credential: target.credential, + scopes: presentation.scopes, + clientMetadata: presentation.metadata, + }).pipe(Effect.mapError(mapRemoteEnvironmentError)); const connectionId = `bearer:${descriptor.environmentId}`; return new BearerConnectionRegistration({ diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.ts index 49f6fb2ff1..f0efe9b054 100644 --- a/packages/client-runtime/src/connection/registry.test.ts +++ b/packages/client-runtime/src/connection/registry.test.ts @@ -20,6 +20,7 @@ import { BearerConnectionCredential, BearerConnectionProfile, BearerConnectionRegistration, + type ConnectionRegistration, ConnectionCredentialStore, ConnectionProfileStore, PrimaryConnectionRegistration, @@ -134,6 +135,9 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* ( initialCredentials: ReadonlyArray = [], options?: { readonly beforeSessionConnect?: (environmentId: EnvironmentId) => Effect.Effect; + readonly beforeRegistrationRegister?: ( + registration: ConnectionRegistration, + ) => Effect.Effect; readonly beforeRegistrationRemove?: ( target: ConnectionTarget, ) => Effect.Effect; @@ -179,6 +183,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* ( const registrationStore = ConnectionRegistrationStore.of({ register: (registration) => Effect.gen(function* () { + yield* options?.beforeRegistrationRegister?.(registration) ?? Effect.void; yield* Ref.update(storedTargets, (current) => { const next = new Map(current); next.set(registration.target.environmentId, registration.target); @@ -685,7 +690,7 @@ describe("EnvironmentRegistry", () => { }), ); - it.effect("closes relay runtimes before fallible persistence removal", () => + it.effect("keeps the runtime registered when durable removal fails", () => Effect.gen(function* () { const harness = yield* makeHarness([RELAY_TARGET], [], [], { beforeRegistrationRemove: () => @@ -709,11 +714,13 @@ describe("EnvironmentRegistry", () => { const error = yield* Effect.flip(registry.removeRelayEnvironments()); expect(error._tag).toBe("ConnectionPersistenceError"); - expect(yield* Ref.get(harness.releasedSessions)).toBe(1); + expect(yield* Ref.get(harness.releasedSessions)).toBe(0); expect((yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId)).toBe( - false, + true, ); expect((yield* Ref.get(harness.storedTargets)).has(RELAY_TARGET.environmentId)).toBe(true); + expect(yield* Ref.get(harness.cacheClears)).toEqual([]); + expect(yield* Ref.get(harness.ownedDataClears)).toEqual([]); }).pipe(Effect.provide(harness.layer), Effect.scoped); }), ); @@ -775,6 +782,76 @@ describe("EnvironmentRegistry", () => { }), ); + it.effect("gives a primary platform registration precedence over persisted registrations", () => + Effect.gen(function* () { + const shadowedTarget = new RelayConnectionTarget({ + environmentId: TARGET.environmentId, + label: "Shadowed relay environment", + }); + const harness = yield* makeHarness([shadowedTarget]); + + yield* Effect.gen(function* () { + const registry = yield* EnvironmentRegistry; + yield* registry.registerPlatform(new PrimaryConnectionRegistration({ target: TARGET })); + + expect( + (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target, + ).toEqual(TARGET); + expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false); + + yield* registry.register(new RelayConnectionRegistration({ target: shadowedTarget })); + + expect( + (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target, + ).toEqual(TARGET); + expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + }), + ); + + it.effect("rechecks platform ownership after waiting for the environment lease", () => + Effect.gen(function* () { + const registrationStarted = yield* Deferred.make(); + const continueRegistration = yield* Deferred.make(); + const shadowedTarget = new RelayConnectionTarget({ + environmentId: TARGET.environmentId, + label: "Shadowed relay environment", + }); + const harness = yield* makeHarness([], [], [], { + beforeRegistrationRegister: () => + Deferred.succeed(registrationStarted, undefined).pipe( + Effect.andThen(Deferred.await(continueRegistration)), + ), + }); + + yield* Effect.gen(function* () { + const registry = yield* EnvironmentRegistry; + const persistedRegistration = yield* registry + .register(new RelayConnectionRegistration({ target: shadowedTarget })) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(registrationStarted); + + const platformRegistration = yield* registry + .registerPlatform(new PrimaryConnectionRegistration({ target: TARGET })) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.yieldNow; + const removal = yield* Effect.flip(registry.remove(TARGET.environmentId)).pipe( + Effect.forkChild({ startImmediately: true }), + ); + + yield* Deferred.succeed(continueRegistration, undefined); + yield* Fiber.join(persistedRegistration); + yield* Fiber.join(platformRegistration); + const error = yield* Fiber.join(removal); + + expect(error._tag).toBe("PlatformEnvironmentRemovalError"); + expect( + (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target, + ).toEqual(TARGET); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + }), + ); + it.effect("does not reacquire a runtime while its registration is being removed", () => Effect.gen(function* () { const removalStarted = yield* Deferred.make(); diff --git a/packages/client-runtime/src/connection/registry.ts b/packages/client-runtime/src/connection/registry.ts index 450c296f09..7560d06f50 100644 --- a/packages/client-runtime/src/connection/registry.ts +++ b/packages/client-runtime/src/connection/registry.ts @@ -22,8 +22,12 @@ import { connectionRegistrationCatalogEntry, } from "./catalog.ts"; import { Connectivity } from "./connectivity.ts"; -import type { NetworkStatus, SupervisorConnectionState } from "./model.ts"; -import type { ConnectionAttemptError } from "./model.ts"; +import type { + ConnectionAttemptError, + ConnectionTarget, + NetworkStatus, + SupervisorConnectionState, +} from "./model.ts"; import { type ConnectionPersistenceError, ConnectionRegistrationStore, @@ -146,6 +150,9 @@ const makeEnvironmentRegistry = Effect.fn("EnvironmentRegistry.make")(function* ReadonlyMap >(new Map()); const platformEnvironmentIds = yield* Ref.make>(new Set()); + const persistedTargetsByEnvironment = yield* Ref.make< + ReadonlyMap + >(new Map(persistedTargets.map((target) => [target.environmentId, target]))); interface LeaseLock { readonly semaphore: Semaphore.Semaphore; readonly users: number; @@ -338,42 +345,52 @@ const makeEnvironmentRegistry = Effect.fn("EnvironmentRegistry.make")(function* ); }).pipe(Effect.withSpan("EnvironmentRegistry.start")); - const installEntry = Effect.fn("EnvironmentRegistry.installEntry")(function* ( + const installEntryLocked = Effect.fn("EnvironmentRegistry.installEntryLocked")(function* ( entry: ConnectionCatalogEntry, options?: { readonly retainEquivalentRuntime?: boolean }, ) { const target = entry.target; - yield* withLeaseLock( - target.environmentId, - Effect.gen(function* () { - const previous = (yield* SubscriptionRef.get(entries)).get(target.environmentId); - const existingScope = (yield* SubscriptionRef.get(serviceScopes)).get(target.environmentId); - if ( - options?.retainEquivalentRuntime === true && - previous !== undefined && - Equal.equals(previous, entry) && - existingScope !== undefined && - Equal.equals(existingScope.entry, entry) - ) { - return; - } + const previous = (yield* SubscriptionRef.get(entries)).get(target.environmentId); + const existingScope = (yield* SubscriptionRef.get(serviceScopes)).get(target.environmentId); + if ( + options?.retainEquivalentRuntime === true && + previous !== undefined && + Equal.equals(previous, entry) && + existingScope !== undefined && + Equal.equals(existingScope.entry, entry) + ) { + return; + } - yield* closeServiceScope(target.environmentId); - yield* SubscriptionRef.update(entries, (current) => { - const next = new Map(current); - next.set(target.environmentId, entry); - return next; - }); - yield* createServiceScope(entry); - }), - ); + yield* closeServiceScope(target.environmentId); + yield* SubscriptionRef.update(entries, (current) => { + const next = new Map(current); + next.set(target.environmentId, entry); + return next; + }); + yield* createServiceScope(entry); }); const register = Effect.fn("EnvironmentRegistry.register")(function* ( registration: ConnectionRegistration, ) { - yield* registrations.register(registration); - yield* installEntry(connectionRegistrationCatalogEntry(registration)); + const entry = connectionRegistrationCatalogEntry(registration); + const environmentId = entry.target.environmentId; + yield* withLeaseLock( + environmentId, + Effect.gen(function* () { + if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) { + return; + } + yield* registrations.register(registration); + yield* Ref.update(persistedTargetsByEnvironment, (current) => { + const next = new Map(current); + next.set(environmentId, registration.target); + return next; + }); + yield* installEntryLocked(entry); + }), + ); }); const registerPlatform = Effect.fn("EnvironmentRegistry.registerPlatform")(function* ( @@ -381,30 +398,87 @@ const makeEnvironmentRegistry = Effect.fn("EnvironmentRegistry.make")(function* ) { const entry = connectionRegistrationCatalogEntry(registration); const target = entry.target; - yield* Ref.update(platformEnvironmentIds, (current) => { - const next = new Set(current); - next.add(target.environmentId); - return next; - }); - yield* installEntry(entry, { retainEquivalentRuntime: true }); + yield* withLeaseLock( + target.environmentId, + Effect.gen(function* () { + yield* Ref.update(platformEnvironmentIds, (current) => { + const next = new Set(current); + next.add(target.environmentId); + return next; + }); + + const persistedTarget = (yield* Ref.get(persistedTargetsByEnvironment)).get( + target.environmentId, + ); + if (persistedTarget !== undefined) { + yield* registrations.remove(persistedTarget).pipe( + Effect.tap(() => + Ref.update(persistedTargetsByEnvironment, (current) => { + const next = new Map(current); + next.delete(target.environmentId); + return next; + }), + ), + Effect.catch((error) => + Effect.logWarning( + "Could not remove a persisted registration shadowed by the primary environment.", + { + environmentId: target.environmentId, + error, + }, + ), + ), + ); + } + + yield* installEntryLocked(entry, { retainEquivalentRuntime: true }); + }), + ); }); const remove = Effect.fn("EnvironmentRegistry.remove")(function* (environmentId: EnvironmentId) { - if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) { - return yield* new PlatformEnvironmentRemovalError({ - environmentId, - message: "Platform-managed environments cannot be removed.", - }); - } return yield* withLeaseLock( environmentId, Effect.gen(function* () { + if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) { + return yield* new PlatformEnvironmentRemovalError({ + environmentId, + message: "Platform-managed environments cannot be removed.", + }); + } const target = (yield* getEntry(environmentId)).target; const profile = target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget" ? yield* profiles.get(target.connectionId) : Option.none(); + yield* registrations.remove(target); + yield* Ref.update(persistedTargetsByEnvironment, (current) => { + const next = new Map(current); + next.delete(environmentId); + return next; + }); + yield* closeServiceScope(environmentId); + yield* SubscriptionRef.update(entries, (current) => { + const next = new Map(current); + next.delete(environmentId); + return next; + }); + yield* Effect.all( + [ + cache.clear(environmentId).pipe( + Effect.catch((error) => + Effect.logWarning("Could not clear cached environment data after removal.", { + environmentId, + error, + }), + ), + ), + ownedDataCleanup.clear(environmentId), + ], + { concurrency: "unbounded", discard: true }, + ); + if ( target._tag === "SshConnectionTarget" && Option.isSome(profile) && @@ -420,18 +494,6 @@ const makeEnvironmentRegistry = Effect.fn("EnvironmentRegistry.make")(function* Effect.ignore, ); } - - yield* closeServiceScope(environmentId); - yield* SubscriptionRef.update(entries, (current) => { - const next = new Map(current); - next.delete(environmentId); - return next; - }); - yield* registrations.remove(target); - yield* Effect.all([cache.clear(environmentId), ownedDataCleanup.clear(environmentId)], { - concurrency: "unbounded", - discard: true, - }); }), ); }); diff --git a/packages/client-runtime/src/rpc/client.test.ts b/packages/client-runtime/src/rpc/client.test.ts index 9191751822..28daf4b609 100644 --- a/packages/client-runtime/src/rpc/client.test.ts +++ b/packages/client-runtime/src/rpc/client.test.ts @@ -4,7 +4,9 @@ import { WS_METHODS, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; @@ -248,4 +250,89 @@ describe("environment RPC", () => { expect(yield* Ref.get(retryCount)).toBe(0); }), ); + + it.effect("keeps handled domain failures dormant until a replacement session arrives", () => + Effect.gen(function* () { + const domainError = new Error("terminal subscription rejected"); + const subscriptions: string[] = []; + const observedFailures: Error[] = []; + const firstClient = { + [WS_METHODS.subscribeTerminalEvents]: () => { + subscriptions.push("first"); + return Stream.fail(domainError); + }, + } as unknown as WsRpcProtocolClient; + const secondClient = { + [WS_METHODS.subscribeTerminalEvents]: () => { + subscriptions.push("second"); + return Stream.never; + }, + } as unknown as WsRpcProtocolClient; + const { activeSession, retryCount, supervisor } = yield* makeHarness(); + + yield* SubscriptionRef.set(activeSession, Option.some(session(firstClient))); + const subscriptionFiber = yield* subscribe( + WS_METHODS.subscribeTerminalEvents, + {}, + { + onExpectedFailure: (cause) => + Effect.sync(() => { + observedFailures.push(Cause.squash(cause) as Error); + }), + }, + ).pipe( + Stream.runDrain, + Effect.provideService(EnvironmentSupervisor, supervisor), + Effect.forkChild, + ); + for (let attempt = 0; attempt < 100 && observedFailures.length < 1; attempt += 1) { + yield* Effect.yieldNow; + } + + expect(subscriptions).toEqual(["first"]); + expect(observedFailures).toEqual([domainError]); + + yield* SubscriptionRef.set(activeSession, Option.some(session(secondClient))); + for (let attempt = 0; attempt < 100 && subscriptions.length < 2; attempt += 1) { + yield* Effect.yieldNow; + } + yield* Fiber.interrupt(subscriptionFiber); + + expect(subscriptions).toEqual(["first", "second"]); + expect(yield* Ref.get(retryCount)).toBe(0); + }), + ); + + it.effect("does not classify subscription defects as expected failures", () => + Effect.gen(function* () { + const defect = new Error("subscription invariant failed"); + let expectedFailureCount = 0; + const client = { + [WS_METHODS.subscribeTerminalEvents]: () => Stream.die(defect), + } as unknown as WsRpcProtocolClient; + const { activeSession, supervisor } = yield* makeHarness(); + + yield* SubscriptionRef.set(activeSession, Option.some(session(client))); + const exit = yield* subscribe( + WS_METHODS.subscribeTerminalEvents, + {}, + { + onExpectedFailure: () => + Effect.sync(() => { + expectedFailureCount += 1; + }), + }, + ).pipe( + Stream.runDrain, + Effect.provideService(EnvironmentSupervisor, supervisor), + Effect.exit, + ); + + expect(Exit.isFailure(exit)).toBe(true); + if (Exit.isFailure(exit)) { + expect(Cause.hasDies(exit.cause)).toBe(true); + } + expect(expectedFailureCount).toBe(0); + }), + ); }); diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index ba16e8be68..ce68a4fcbd 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -150,6 +150,11 @@ export function runStream( export function subscribe( tag: TTag, input: EnvironmentRpcInput, + options?: { + readonly onExpectedFailure?: ( + cause: Cause.Cause>, + ) => Effect.Effect; + }, ): Stream.Stream< EnvironmentRpcStreamValue, EnvironmentRpcStreamFailure, @@ -171,24 +176,30 @@ export function subscribe( >; return method(input).pipe( Stream.catchCause((cause) => { - const isTransportFailure = + const hasOnlyExpectedFailures = cause.reasons.length > 0 && + cause.reasons.every((reason) => reason._tag === "Fail"); + const isTransportFailure = + hasOnlyExpectedFailures && cause.reasons.every( (reason) => reason._tag === "Fail" && isRpcClientError(reason.error), ); - if (!isTransportFailure) { - return Stream.failCause(cause); + if (isTransportFailure) { + return Stream.fromEffect( + Effect.logWarning( + "Durable RPC subscription lost its transport; waiting for the next session.", + { + cause: Cause.pretty(cause), + method: tag, + environmentId: supervisor.target.environmentId, + }, + ), + ).pipe(Stream.drain); } - return Stream.fromEffect( - Effect.logWarning( - "Durable RPC subscription lost its transport; waiting for the next session.", - { - cause: Cause.pretty(cause), - method: tag, - environmentId: supervisor.target.environmentId, - }, - ), - ).pipe(Stream.drain); + if (hasOnlyExpectedFailures && options?.onExpectedFailure !== undefined) { + return Stream.fromEffect(options.onExpectedFailure(cause)).pipe(Stream.drain); + } + return Stream.failCause(cause); }), ); }, diff --git a/packages/client-runtime/src/state/git.ts b/packages/client-runtime/src/state/git.ts index 1cf4ae4174..5a8a7a1bbe 100644 --- a/packages/client-runtime/src/state/git.ts +++ b/packages/client-runtime/src/state/git.ts @@ -1,11 +1,7 @@ import { WS_METHODS } from "@t3tools/contracts"; import { Atom } from "effect/unstable/reactivity"; -import { - createEnvironmentRpcMutation, - createEnvironmentRpcQueryAtomFamily, - createEnvironmentRpcStreamMutation, -} from "./runtime.ts"; +import { createEnvironmentRpcMutation, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; import type { EnvironmentRegistry } from "../connection/registry.ts"; export function createGitEnvironmentAtoms( @@ -16,10 +12,6 @@ export function createGitEnvironmentAtoms( label: "environment-data:git:resolve-pull-request", tag: WS_METHODS.gitResolvePullRequest, }), - runStackedAction: createEnvironmentRpcStreamMutation(runtime, { - label: "environment-data:git:run-stacked-action", - tag: WS_METHODS.gitRunStackedAction, - }), resolvePullRequest: createEnvironmentRpcMutation(runtime, { label: "environment-data:git:resolve-pull-request", tag: WS_METHODS.gitResolvePullRequest, diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index 214a6f2f34..73ecff1327 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -1,5 +1,10 @@ +import { describe, expect, it } from "@effect/vitest"; import { EnvironmentId } from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Latch from "effect/Latch"; +import * as Stream from "effect/Stream"; +import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity"; import { environmentRpcKey } from "./runtime.ts"; @@ -25,3 +30,112 @@ describe("environmentRpcKey", () => { ).not.toBe(environmentRpcKey(originalTarget)); }); }); + +describe("Atom.fn mutation semantics", () => { + it.effect("interrupts the previous invocation when the same mutation atom is written again", () => + Effect.gen(function* () { + const firstLatch = Latch.makeUnsafe(); + const secondLatch = Latch.makeUnsafe(); + const interrupted: string[] = []; + const mutation = Atom.fn((id: "first" | "second") => + (id === "first" ? firstLatch : secondLatch).await.pipe( + Effect.as(id), + Effect.onInterrupt(() => + Effect.sync(() => { + interrupted.push(id); + }), + ), + ), + ); + const registry = AtomRegistry.make(); + const unmount = registry.mount(mutation); + + registry.set(mutation, "first"); + registry.set(mutation, "second"); + yield* Effect.yieldNow; + + expect(interrupted).toEqual(["first"]); + + secondLatch.openUnsafe(); + expect( + yield* AtomRegistry.getResult(registry, mutation, { + suspendOnWaiting: true, + }), + ).toBe("second"); + + unmount(); + registry.dispose(); + }), + ); + + it.effect("keeps stream mutations waiting until the final emitted value", () => + Effect.gen(function* () { + const completionLatch = Latch.makeUnsafe(); + const mutation = Atom.fn(() => + Stream.make("progress").pipe( + Stream.concat(Stream.fromEffect(completionLatch.await.pipe(Effect.as("done")))), + ), + ); + const registry = AtomRegistry.make(); + const unmount = registry.mount(mutation); + + registry.set(mutation, undefined); + + const progress = registry.get(mutation); + expect(AsyncResult.isSuccess(progress)).toBe(true); + if (AsyncResult.isSuccess(progress)) { + expect(progress.value).toBe("progress"); + expect(progress.waiting).toBe(true); + } + + completionLatch.openUnsafe(); + expect( + yield* AtomRegistry.getResult(registry, mutation, { + suspendOnWaiting: true, + }), + ).toBe("done"); + + unmount(); + registry.dispose(); + }), + ); + + it.effect( + "allows concurrent effects to finish but does not correlate results to individual writes", + () => + Effect.gen(function* () { + const firstLatch = Latch.makeUnsafe(); + const secondLatch = Latch.makeUnsafe(); + const mutation = Atom.fn( + (id: "first" | "second") => + (id === "first" ? firstLatch : secondLatch).await.pipe(Effect.as(id)), + { concurrent: true }, + ); + const registry = AtomRegistry.make(); + const unmount = registry.mount(mutation); + + registry.set(mutation, "first"); + const firstResult = yield* AtomRegistry.getResult(registry, mutation, { + suspendOnWaiting: true, + }).pipe(Effect.forkChild({ startImmediately: true })); + registry.set(mutation, "second"); + const secondResult = yield* AtomRegistry.getResult(registry, mutation, { + suspendOnWaiting: true, + }).pipe(Effect.forkChild({ startImmediately: true })); + + secondLatch.openUnsafe(); + yield* Effect.yieldNow; + + const stillWaiting = registry.get(mutation); + expect(stillWaiting.waiting).toBe(true); + + firstLatch.openUnsafe(); + + expect(yield* Fiber.join(firstResult)).toBe("first"); + expect(yield* Fiber.join(secondResult)).toBe("first"); + + unmount(); + registry.dispose(); + }), + ); +}); diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts index 5ebf9fe5f1..be44eb66c0 100644 --- a/packages/client-runtime/src/state/shell.ts +++ b/packages/client-runtime/src/state/shell.ts @@ -128,13 +128,13 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") }); }); - yield* subscribe(ORCHESTRATION_WS_METHODS.subscribeShell, {}).pipe( - Stream.runForEach(applyItem), - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) ? Effect.interrupt : setStreamError(Cause.squash(cause)), - ), - Effect.forkScoped, - ); + yield* subscribe( + ORCHESTRATION_WS_METHODS.subscribeShell, + {}, + { + onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)), + }, + ).pipe(Stream.runForEach(applyItem), Effect.forkScoped); yield* SubscriptionRef.changes(supervisor.state).pipe( Stream.runForEach((connectionState) => { switch (connectionProjectionPhase(connectionState)) { diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index d2bccf7914..ba468ac257 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -170,6 +170,7 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o supervisorSession, savedThreads, removedThreads, + replaceSession: SubscriptionRef.set(supervisorSession, Option.some(testSession(client))), }; }); @@ -292,7 +293,7 @@ describe("EnvironmentThreads", () => { }), ); - it.effect("preserves the latest data and surfaces a domain stream failure", () => + it.effect("preserves data after a domain failure and resumes on a replacement session", () => Effect.gen(function* () { const harness = yield* makeHarness({ cached: BASE_THREAD }); yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD)); @@ -305,6 +306,31 @@ describe("EnvironmentThreads", () => { expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD); expect(Option.getOrThrow(state.error)).toBe("stream failed"); expect(yield* Ref.get(harness.retryCount)).toBe(0); + + yield* harness.replaceSession; + for (let attempt = 0; attempt < 100; attempt += 1) { + if ((yield* Ref.get(harness.subscriptionCount)) >= 2) { + break; + } + yield* Effect.yieldNow; + } + yield* Queue.offer( + harness.inputs, + snapshot({ + ...BASE_THREAD, + title: "Recovered thread", + }), + ); + const recovered = yield* awaitThreadState( + harness.observed, + (value) => + value.status === "live" && + Option.isSome(value.data) && + value.data.value.title === "Recovered thread", + ); + + expect(Option.isNone(recovered.error)).toBe(true); + expect(yield* Ref.get(harness.subscriptionCount)).toBe(2); }), ); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index fd6804b5ad..ffcd913646 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -201,13 +201,13 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make ); yield* setSynchronizing; - yield* subscribe(ORCHESTRATION_WS_METHODS.subscribeThread, { threadId }).pipe( - Stream.runForEach(applyItem), - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) ? Effect.interrupt : setStreamError(cause), - ), - Effect.forkScoped, - ); + yield* subscribe( + ORCHESTRATION_WS_METHODS.subscribeThread, + { threadId }, + { + onExpectedFailure: setStreamError, + }, + ).pipe(Stream.runForEach(applyItem), Effect.forkScoped); yield* Effect.addFinalizer(() => SubscriptionRef.get(state).pipe( diff --git a/packages/client-runtime/src/state/vcsAction.test.ts b/packages/client-runtime/src/state/vcsAction.test.ts index 96689fb624..22909be665 100644 --- a/packages/client-runtime/src/state/vcsAction.test.ts +++ b/packages/client-runtime/src/state/vcsAction.test.ts @@ -1,15 +1,54 @@ -import { EnvironmentId, type GitActionProgressEvent } from "@t3tools/contracts"; +import { + EnvironmentId, + type GitActionProgressEvent, + type GitRunStackedActionResult, +} from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; +import { Atom, AtomRegistry } from "effect/unstable/reactivity"; +import type { EnvironmentRegistry } from "../connection/registry.ts"; import { applyVcsActionProgressEvent, + beginVcsActionState, + consumeVcsActionProgress, + createVcsActionManager, + createVcsActionTransportId, EMPTY_VCS_ACTION_STATE, getVcsActionTargetKey, + normalizeVcsActionProgressEvent, } from "./vcsAction.ts"; const actionId = "action-123"; const action = "commit_push" as const; const cwd = "/repo"; +const environmentId = EnvironmentId.make("environment-1"); +const result: GitRunStackedActionResult = { + action, + branch: { + status: "skipped_not_requested", + }, + commit: { + status: "created", + commitSha: "abc123", + subject: "Test commit", + }, + push: { + status: "pushed", + branch: "feature", + }, + pr: { + status: "skipped_not_requested", + }, + toast: { + title: "Changes pushed", + cta: { + kind: "none", + }, + }, +}; function progress(event: T): T { return event; @@ -17,8 +56,13 @@ function progress(event: T): T { describe("vcsActionState", () => { it("projects phase and hook progress without owning the async operation", () => { + const initial = beginVcsActionState({ + operation: "run_change_request", + label: "Running source control action", + actionId, + }); const phase = applyVcsActionProgressEvent( - EMPTY_VCS_ACTION_STATE, + initial, progress({ actionId, action, @@ -81,8 +125,13 @@ describe("vcsActionState", () => { }); it("retains a terminal action error for presentation", () => { + const initial = beginVcsActionState({ + operation: "run_change_request", + label: "Running source control action", + actionId, + }); const failed = applyVcsActionProgressEvent( - EMPTY_VCS_ACTION_STATE, + initial, progress({ actionId, action, @@ -102,19 +151,190 @@ describe("vcsActionState", () => { }); }); + it("ignores progress after a newer action owns the target", () => { + const current = beginVcsActionState({ + operation: "pull", + label: "Pulling latest changes", + actionId: "newer-action", + }); + + expect( + applyVcsActionProgressEvent( + current, + progress({ + actionId, + action, + cwd, + kind: "phase_started", + phase: "push", + label: "Pushing...", + }), + ), + ).toBe(current); + }); + it("keys presentation state only when the environment and repository are known", () => { expect( getVcsActionTargetKey({ - environmentId: EnvironmentId.make("environment-1"), + environmentId, cwd, }), - ).toBe(`environment-1:${cwd}`); + ).toBe(JSON.stringify([environmentId, cwd])); expect(getVcsActionTargetKey({ environmentId: null, cwd })).toBeNull(); expect( getVcsActionTargetKey({ - environmentId: EnvironmentId.make("environment-1"), + environmentId, cwd: null, }), ).toBeNull(); }); + + it("normalizes progress only for the matching environment-scoped action", () => { + const target = { environmentId, cwd }; + const otherTarget = { + environmentId: EnvironmentId.make("environment-2"), + cwd, + }; + const transportActionId = createVcsActionTransportId(target, actionId); + const event = progress({ + actionId: createVcsActionTransportId(otherTarget, actionId), + action, + cwd, + kind: "phase_started", + phase: "push", + label: "Pushing...", + }); + + expect(normalizeVcsActionProgressEvent(target, transportActionId, actionId, event)).toBeNull(); + expect( + normalizeVcsActionProgressEvent(target, transportActionId, actionId, { + ...event, + actionId: transportActionId, + }), + ).toEqual({ + ...event, + actionId, + }); + }); + + it.effect("consumes progress through the terminal event and returns its result", () => + Effect.gen(function* () { + const target = { environmentId, cwd }; + const transportActionId = createVcsActionTransportId(target, actionId); + const observed: GitActionProgressEvent[] = []; + const events: GitActionProgressEvent[] = [ + { + actionId: "unrelated-action", + action, + cwd, + kind: "phase_started", + phase: "commit", + label: "Ignored", + }, + { + actionId: transportActionId, + action, + cwd, + kind: "phase_started", + phase: "push", + label: "Pushing...", + }, + { + actionId: transportActionId, + action, + cwd, + kind: "action_finished", + result, + }, + ]; + + const actual = yield* consumeVcsActionProgress(Stream.fromIterable(events), { + target, + transportActionId, + actionId, + onProgress: (event) => + Effect.sync(() => { + observed.push(event); + }), + }); + + expect(actual).toEqual(result); + expect(observed.map((event) => event.actionId)).toEqual([actionId, actionId]); + expect(observed.map((event) => event.kind)).toEqual(["phase_started", "action_finished"]); + }), + ); + + it("keys mutation ownership by environment and cwd", () => { + const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime< + EnvironmentRegistry, + never + >; + const manager = createVcsActionManager(runtime); + const registry = AtomRegistry.make(); + const target = { environmentId, cwd }; + const otherTarget = { + environmentId: EnvironmentId.make("environment-2"), + cwd, + }; + + expect(manager.runStackedAction(target)).toBe(manager.runStackedAction({ ...target })); + expect(manager.runStackedAction(target)).not.toBe(manager.runStackedAction(otherTarget)); + expect(registry.get(manager.stateAtom(target))).toEqual(EMPTY_VCS_ACTION_STATE); + + registry.dispose(); + }); + + it("tracks finite mutations without letting an older completion clear newer state", async () => { + const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime< + EnvironmentRegistry, + never + >; + const manager = createVcsActionManager(runtime); + const registry = AtomRegistry.make(); + const target = { environmentId, cwd }; + let finishFirst!: () => void; + let failSecond!: (error: Error) => void; + const firstAction = new Promise((resolve) => { + finishFirst = resolve; + }); + const secondAction = new Promise((_resolve, reject) => { + failSecond = reject; + }); + + const first = manager.track( + registry, + target, + { operation: "pull", label: "Pulling latest changes" }, + () => firstAction, + ); + const firstActionId = registry.get(manager.stateAtom(target)).actionId; + const second = manager.track( + registry, + target, + { operation: "switch_ref", label: "Switching branch" }, + () => secondAction, + ); + const secondActionId = registry.get(manager.stateAtom(target)).actionId; + + finishFirst(); + await first; + expect(registry.get(manager.stateAtom(target))).toMatchObject({ + actionId: secondActionId, + isRunning: true, + operation: "switch_ref", + }); + expect(secondActionId).not.toBe(firstActionId); + + const secondFailure = expect(second).rejects.toThrow("switch failed"); + failSecond(new Error("switch failed")); + await secondFailure; + expect(registry.get(manager.stateAtom(target))).toMatchObject({ + actionId: secondActionId, + error: "switch failed", + isRunning: false, + operation: "switch_ref", + }); + + registry.dispose(); + }); }); diff --git a/packages/client-runtime/src/state/vcsAction.ts b/packages/client-runtime/src/state/vcsAction.ts index 5fcdd23428..b2ec4b8eaf 100644 --- a/packages/client-runtime/src/state/vcsAction.ts +++ b/packages/client-runtime/src/state/vcsAction.ts @@ -1,6 +1,21 @@ -import type { EnvironmentId, GitActionProgressEvent, GitStackedAction } from "@t3tools/contracts"; +import { + EnvironmentId, + type EnvironmentId as EnvironmentIdType, + type GitActionProgressEvent, + type GitRunStackedActionInput, + type GitRunStackedActionResult, + type GitStackedAction, + WS_METHODS, +} from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; -import { Atom } from "effect/unstable/reactivity"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { Atom, type AtomRegistry } from "effect/unstable/reactivity"; + +import type { EnvironmentRegistry } from "../connection/registry.ts"; +import { runStream } from "../rpc/client.ts"; +import { runStreamInEnvironment } from "./runtime.ts"; export type VcsActionOperation = | "refresh_status" @@ -9,7 +24,9 @@ export type VcsActionOperation = | "switch_ref" | "create_ref" | "create_worktree" - | "init"; + | "init" + | "publish_repository" + | "prepare_pull_request_thread"; export interface VcsActionState { readonly isRunning: boolean; @@ -26,10 +43,44 @@ export interface VcsActionState { } export interface VcsActionTarget { - readonly environmentId: EnvironmentId | null; + readonly environmentId: EnvironmentIdType | null; readonly cwd: string | null; } +export interface ResolvedVcsActionTarget { + readonly environmentId: EnvironmentIdType; + readonly cwd: string; +} + +export interface BeginVcsActionInput { + readonly operation: VcsActionOperation; + readonly label: string; + readonly actionId?: string; +} + +export interface RunVcsStackedActionInput { + readonly actionId: string; + readonly action: GitStackedAction; + readonly commitMessage?: string; + readonly featureBranch?: boolean; + readonly filePaths?: ReadonlyArray; + readonly onProgress?: (event: GitActionProgressEvent) => void; +} + +export class VcsActionUnavailableError extends Schema.TaggedErrorClass()( + "VcsActionUnavailableError", + { + message: Schema.String, + }, +) {} + +export class VcsActionExecutionError extends Schema.TaggedErrorClass()( + "VcsActionExecutionError", + { + message: Schema.String, + }, +) {} + export const EMPTY_VCS_ACTION_STATE = Object.freeze({ isRunning: false, operation: null, @@ -45,6 +96,7 @@ export const EMPTY_VCS_ACTION_STATE = Object.freeze({ }); const nowMs = (): number => DateTime.toEpochMillis(DateTime.nowUnsafe()); +let nextLocalActionId = 0; export const vcsActionStateAtom = Atom.family((key: string) => { return Atom.make(EMPTY_VCS_ACTION_STATE).pipe( @@ -62,13 +114,134 @@ export function getVcsActionTargetKey(target: VcsActionTarget): string | null { if (target.environmentId === null || target.cwd === null) { return null; } - return `${target.environmentId}:${target.cwd}`; + return JSON.stringify([target.environmentId, target.cwd]); +} + +function parseVcsActionTargetKey(key: string): ResolvedVcsActionTarget { + const [environmentId, cwd] = JSON.parse(key) as [string, string]; + return { + environmentId: EnvironmentId.make(environmentId), + cwd, + }; +} + +export function getVcsActionStateAtom(target: VcsActionTarget) { + const key = getVcsActionTargetKey(target); + return key === null ? EMPTY_VCS_ACTION_ATOM : vcsActionStateAtom(key); +} + +function createLocalActionId(): string { + nextLocalActionId += 1; + return `local-vcs-action:${nextLocalActionId}`; +} + +export function beginVcsActionState( + input: BeginVcsActionInput, +): VcsActionState & { readonly actionId: string } { + const actionId = input.actionId ?? createLocalActionId(); + const startedAt = nowMs(); + return { + ...EMPTY_VCS_ACTION_STATE, + isRunning: true, + operation: input.operation, + actionId, + currentLabel: input.label, + currentPhaseLabel: input.label, + phaseStartedAtMs: startedAt, + }; +} + +export function failVcsActionState( + operation: VcsActionOperation, + actionId: string, + error: unknown, +): VcsActionState { + return { + ...EMPTY_VCS_ACTION_STATE, + operation, + actionId, + error: error instanceof Error ? error.message : "Source control action failed.", + }; +} + +export function createVcsActionTransportId( + target: ResolvedVcsActionTarget, + actionId: string, +): string { + const targetKey = JSON.stringify([target.environmentId, target.cwd]); + return `${targetKey.length}:${targetKey}${actionId}`; +} + +export function normalizeVcsActionProgressEvent( + target: ResolvedVcsActionTarget, + transportActionId: string, + actionId: string, + event: GitActionProgressEvent, +): GitActionProgressEvent | null { + if (event.actionId !== transportActionId || event.cwd !== target.cwd) { + return null; + } + return { + ...event, + actionId, + }; +} + +export function consumeVcsActionProgress( + stream: Stream.Stream, + input: { + readonly target: ResolvedVcsActionTarget; + readonly transportActionId: string; + readonly actionId: string; + readonly onProgress: (event: GitActionProgressEvent) => Effect.Effect; + }, +): Effect.Effect { + return Effect.suspend(() => { + let terminalEvent: GitActionProgressEvent | null = null; + return stream.pipe( + Stream.runForEach((event) => { + const normalized = normalizeVcsActionProgressEvent( + input.target, + input.transportActionId, + input.actionId, + event, + ); + if (normalized === null) { + return Effect.void; + } + if (normalized.kind === "action_finished" || normalized.kind === "action_failed") { + terminalEvent = normalized; + } + return input.onProgress(normalized); + }), + Effect.flatMap(() => { + if (terminalEvent?.kind === "action_finished") { + return Effect.succeed(terminalEvent.result); + } + if (terminalEvent?.kind === "action_failed") { + return Effect.fail( + new VcsActionExecutionError({ + message: terminalEvent.message, + }), + ); + } + return Effect.fail( + new VcsActionExecutionError({ + message: "Source control action ended without a result.", + }), + ); + }), + ); + }); } export function applyVcsActionProgressEvent( current: VcsActionState, event: GitActionProgressEvent, ): VcsActionState { + if (current.actionId !== event.actionId) { + return current; + } const now = nowMs(); switch (event.kind) { @@ -155,3 +328,136 @@ export function applyVcsActionProgressEvent( }; } } + +export function createVcsActionManager( + runtime: Atom.AtomRuntime, +) { + const unavailableTargetKey = "vcs-action-target:unavailable"; + const runStackedActionFamily = Atom.family((key: string) => { + const target = key === unavailableTargetKey ? null : parseVcsActionTargetKey(key); + const stateAtom = target === null ? EMPTY_VCS_ACTION_ATOM : vcsActionStateAtom(key); + return runtime + .fn()((input, get) => { + if (target === null) { + return Effect.fail( + new VcsActionUnavailableError({ + message: "Source control action is unavailable.", + }), + ); + } + const transportActionId = createVcsActionTransportId(target, input.actionId); + get.set( + stateAtom, + beginVcsActionState({ + operation: "run_change_request", + label: "Running source control action", + actionId: input.actionId, + }), + ); + + const rpcInput: GitRunStackedActionInput = { + actionId: transportActionId, + cwd: target.cwd, + action: input.action, + ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}), + ...(input.featureBranch ? { featureBranch: true } : {}), + ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}), + }; + return consumeVcsActionProgress( + runStreamInEnvironment( + target.environmentId, + runStream(WS_METHODS.gitRunStackedAction, rpcInput), + ), + { + target, + transportActionId, + actionId: input.actionId, + onProgress: (event) => + Effect.sync(() => { + const current = get(stateAtom); + if (current.actionId !== input.actionId) { + return; + } + get.set(stateAtom, applyVcsActionProgressEvent(current, event)); + if (input.onProgress !== undefined) { + try { + input.onProgress(event); + } catch { + // Presentation callbacks must not fail the source-control operation. + } + } + }), + }, + ).pipe( + Effect.tapError((error) => + Effect.sync(() => { + const current = get(stateAtom); + if (current.actionId === input.actionId && current.isRunning) { + get.set(stateAtom, failVcsActionState("run_change_request", input.actionId, error)); + } + }), + ), + ); + }) + .pipe(Atom.withLabel(`vcs-action:run-stacked:${key}`)); + }); + + const setState = ( + registry: AtomRegistry.AtomRegistry, + target: VcsActionTarget, + update: (current: VcsActionState) => VcsActionState, + ): void => { + const key = getVcsActionTargetKey(target); + if (key === null) { + return; + } + const stateAtom = vcsActionStateAtom(key); + registry.set(stateAtom, update(registry.get(stateAtom))); + }; + + return { + stateAtom: getVcsActionStateAtom, + runStackedAction: (target: VcsActionTarget) => { + const key = getVcsActionTargetKey(target); + return runStackedActionFamily(key ?? unavailableTargetKey); + }, + track: async ( + registry: AtomRegistry.AtomRegistry, + target: VcsActionTarget, + input: BeginVcsActionInput, + action: () => Promise, + ): Promise => { + const key = getVcsActionTargetKey(target); + if (key === null) { + throw new VcsActionUnavailableError({ + message: "Source control action is unavailable.", + }); + } + const stateAtom = vcsActionStateAtom(key); + const next = beginVcsActionState(input); + registry.set(stateAtom, next); + try { + const result = await action(); + if (registry.get(stateAtom).actionId === next.actionId) { + registry.set(stateAtom, EMPTY_VCS_ACTION_STATE); + } + return result; + } catch (error) { + const current = registry.get(stateAtom); + if (current.actionId === next.actionId) { + registry.set(stateAtom, failVcsActionState(input.operation, next.actionId, error)); + } + throw error; + } + }, + resetError: ( + registry: AtomRegistry.AtomRegistry, + target: VcsActionTarget, + operation: VcsActionOperation, + ): void => { + setState(registry, target, (current) => + !current.isRunning && current.operation === operation ? EMPTY_VCS_ACTION_STATE : current, + ); + }, + }; +} diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index bc64056f89..03c06d2f81 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -899,13 +899,6 @@ export interface DesktopBridge { getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null; getClientSettings: () => Promise; setClientSettings: (settings: ClientSettings) => Promise; - getSavedEnvironmentRegistry: () => Promise; - setSavedEnvironmentRegistry: ( - records: readonly PersistedSavedEnvironmentRecord[], - ) => Promise; - getSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise; - setSavedEnvironmentSecret: (environmentId: EnvironmentId, secret: string) => Promise; - removeSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise; getConnectionCatalog?: () => Promise; setConnectionCatalog?: (catalog: string) => Promise; clearConnectionCatalog?: () => Promise; @@ -1052,13 +1045,6 @@ export interface LocalApi { persistence: { getClientSettings: () => Promise; setClientSettings: (settings: ClientSettings) => Promise; - getSavedEnvironmentRegistry: () => Promise; - setSavedEnvironmentRegistry: ( - records: readonly PersistedSavedEnvironmentRecord[], - ) => Promise; - getSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise; - setSavedEnvironmentSecret: (environmentId: EnvironmentId, secret: string) => Promise; - removeSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise; }; server: { getConfig: () => Promise;