The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; |
| 2 | import { expect, it } from "@effect/vitest"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import { afterEach, beforeEach, vi } from "vite-plus/test"; |
| 5 | |
| 6 | type UploadOptions = { |
| 7 | signal: AbortSignal; |
| 8 | onProgress?: (progress: { bytesSent: number; totalBytes: number }) => void; |
| 9 | }; |
| 10 | type DraftFault = "decode" | "read" | "write" | null; |
| 11 | |
| 12 | const native = vi.hoisted(() => ({ |
| 13 | files: new Map<string, Uint8Array>(), |
| 14 | server: new Map<string, Uint8Array | null>(), |
| 15 | deleted: [] as string[], |
| 16 | fault: null as DraftFault, |
| 17 | canOperate: true, |
| 18 | nextId: 0, |
| 19 | nextUuid: 0, |
| 20 | remove: Symbol("remove"), |
| 21 | transfer: |
| 22 | vi.fn<(uri: string, url: string, options: UploadOptions) => Promise<{ status: number }>>(), |
| 23 | })); |
| 24 | |
| 25 | vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } })); |
| 26 | vi.mock("@effect/atom-react", () => ({ |
| 27 | useAtomValue: (atom: Parameters<typeof appAtomRegistry.get>[0]) => appAtomRegistry.get(atom), |
| 28 | })); |
| 29 | vi.mock("expo-file-system", () => { |
| 30 | const uriOf = (parent: string | { uri: string }) => |
| 31 | typeof parent === "string" ? parent : parent.uri; |
| 32 | class Directory { |
| 33 | readonly uri: string; |
| 34 | constructor(parent: string | { uri: string }, name?: string) { |
| 35 | this.uri = [uriOf(parent), name].filter(Boolean).join("/"); |
| 36 | } |
| 37 | create() {} |
| 38 | list() { |
| 39 | return [...native.files.keys()] |
| 40 | .filter((uri) => uri.startsWith(`${this.uri}/`)) |
| 41 | .map((uri) => new File(uri)); |
| 42 | } |
| 43 | } |
| 44 | class File { |
| 45 | readonly uri: string; |
| 46 | readonly name: string; |
| 47 | readonly parentDirectory: Directory; |
| 48 | constructor(parent: string | { uri: string }, name?: string) { |
| 49 | this.uri = [uriOf(parent), name].filter(Boolean).join("/"); |
| 50 | this.name = this.uri.split("/").at(-1)!; |
| 51 | this.parentDirectory = new Directory(this.uri.slice(0, this.uri.lastIndexOf("/"))); |
| 52 | } |
| 53 | get exists() { |
| 54 | return native.files.has(this.uri); |
| 55 | } |
| 56 | create() { |
| 57 | native.files.set(this.uri, new Uint8Array()); |
| 58 | } |
| 59 | async text() { |
| 60 | if (native.fault === "read" && this.uri.endsWith("/composer-drafts/drafts.json")) { |
| 61 | throw new Error("EACCES: drafts.json"); |
| 62 | } |
| 63 | return Buffer.from(native.files.get(this.uri)!).toString("utf8"); |
| 64 | } |
| 65 | write(value: string, options?: { encoding?: string }) { |
| 66 | if (native.fault === "write" && this.uri.includes("/composer-drafts/")) { |
| 67 | throw new Error("ENOSPC"); |
| 68 | } |
| 69 | native.files.set( |
| 70 | this.uri, |
| 71 | Buffer.from(value, options?.encoding === "base64" ? "base64" : "utf8"), |
| 72 | ); |
| 73 | } |
| 74 | moveSync(destination: File) { |
| 75 | native.files.set(destination.uri, native.files.get(this.uri)!); |
| 76 | native.files.delete(this.uri); |
| 77 | } |
| 78 | delete() { |
| 79 | native.files.delete(this.uri); |
| 80 | } |
| 81 | upload(url: string, options: UploadOptions) { |
| 82 | return native.transfer(this.uri, url, options); |
| 83 | } |
| 84 | } |
| 85 | return { |
| 86 | Directory, |
| 87 | File, |
| 88 | Paths: { document: new Directory("file:///documents"), cache: new Directory("file:///cache") }, |
| 89 | UploadType: { BINARY_CONTENT: 0 }, |
| 90 | }; |
| 91 | }); |
| 92 | vi.mock("../lib/uuid", () => ({ |
| 93 | uuidv4: () => `upload-${++native.nextUuid}`, |
| 94 | randomHex: () => "abcd", |
| 95 | })); |
| 96 | vi.mock("../features/sharing/incoming-share-storage", () => ({ |
| 97 | loadIncomingShareDrafts: async () => [], |
| 98 | })); |
| 99 | vi.mock("./entities", () => ({ |
| 100 | useProjects: () => [], |
| 101 | useServerConfigs: () => new Map([["environment-1", config]]), |
| 102 | useThreadShells: () => [], |
| 103 | useVisibleThreadShells: () => [], |
| 104 | })); |
| 105 | vi.mock("./projects", () => ({ environmentProjects: {} })); |
| 106 | vi.mock("./workspace", async () => { |
| 107 | const { Atom } = await import("effect/reactivity"); |
| 108 | return { |
| 109 | workspaceConnections: { environmentsAtom: Atom.make([{ environmentId: "environment-1" }]) }, |
| 110 | }; |
| 111 | }); |
| 112 | vi.mock("./server", async () => { |
| 113 | const { Atom } = await import("effect/reactivity"); |
| 114 | return { serverEnvironment: { configValueAtom: Atom.family(() => Atom.make(null)) } }; |
| 115 | }); |
| 116 | vi.mock("./git", () => ({ gitEnvironment: {} })); |
| 117 | vi.mock("./threads", () => ({ threadEnvironment: {} })); |
| 118 | vi.mock("./use-atom-command", () => ({ useAtomCommand: () => async () => undefined })); |
| 119 | vi.mock("./session", async () => { |
| 120 | const { Atom } = await import("effect/reactivity"); |
| 121 | const Option = await import("effect/Option"); |
| 122 | return { |
| 123 | readEnvironmentScope: () => native.canOperate, |
| 124 | useEnvironmentsWithScope: () => new Set(["environment-1"]), |
| 125 | environmentSession: { |
| 126 | preparedConnectionValueAtom: Atom.family(() => |
| 127 | Atom.make(Option.some({ httpBaseUrl: "https://environment.example/" })), |
| 128 | ), |
| 129 | }, |
| 130 | }; |
| 131 | }); |
| 132 | vi.mock("./attachments", async () => { |
| 133 | const Effect = await import("effect/Effect"); |
| 134 | return { |
| 135 | attachmentEnvironment: { |
| 136 | createUploadUrl: { |
| 137 | run: () => |
| 138 | Effect.sync(() => { |
| 139 | const id = `pending-${++native.nextId}`; |
| 140 | native.server.set(id, null); |
| 141 | return { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 }; |
| 142 | }), |
| 143 | }, |
| 144 | remove: native.remove, |
| 145 | }, |
| 146 | }; |
| 147 | }); |
| 148 | vi.mock("./assets", () => ({ assetEnvironment: { createUrl: (input: unknown) => input } })); |
| 149 | vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => { |
| 150 | const Effect = await import("effect/Effect"); |
| 151 | return { |
| 152 | ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()), |
| 153 | createEnvironmentRpcCommand: () => Symbol("rpc-command"), |
| 154 | awaitAtomResult: ( |
| 155 | _registry: unknown, |
| 156 | query: { input: { resource: { attachmentId: string } } }, |
| 157 | ) => |
| 158 | Effect.suspend(() => |
| 159 | native.server.get(query.input.resource.attachmentId) |
| 160 | ? Effect.succeed({}) |
| 161 | : Effect.fail({ _tag: "AssetAttachmentNotFoundError" }), |
| 162 | ), |
| 163 | runAtomCommand: async ( |
| 164 | _registry: unknown, |
| 165 | command: unknown, |
| 166 | target: { input: { attachmentId?: string } }, |
| 167 | ) => { |
| 168 | if (command === native.remove && target.input.attachmentId) { |
| 169 | native.deleted.push(target.input.attachmentId); |
| 170 | native.server.delete(target.input.attachmentId); |
| 171 | return { _tag: "Success", value: undefined }; |
| 172 | } |
| 173 | throw new Error("Unexpected RPC command"); |
| 174 | }, |
| 175 | }; |
| 176 | }); |
| 177 | vi.mock("./use-thread-outbox", async () => { |
| 178 | const { Atom } = await import("effect/reactivity"); |
| 179 | return { |
| 180 | editingQueuedMessageIdsAtom: Atom.make<Record<string, boolean>>({}).pipe(Atom.keepAlive), |
| 181 | dispatchingQueuedMessageIdsAtom: Atom.make<Record<string, true>>({}).pipe(Atom.keepAlive), |
| 182 | useThreadOutboxMessages: () => |
| 183 | appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), |
| 184 | retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), |
| 185 | threadOutboxShellStatusesAtom: Atom.make(new Map()), |
| 186 | }; |
| 187 | }); |
| 188 | |
| 189 | import { |
| 190 | composerAttachmentUploadBlockReason, |
| 191 | composerAttachmentsStillUploading, |
| 192 | composerAttachmentUploadKey, |
| 193 | } from "../lib/composerAttachmentUploadQueue"; |
| 194 | import type { DraftComposerAttachment } from "../lib/composerImages"; |
| 195 | import { Atom } from "effect/reactivity"; |
| 196 | import { appAtomRegistry } from "./atom-registry"; |
| 197 | import { |
| 198 | composerAttachmentUploadRequests, |
| 199 | composerAttachmentUploadsAtom, |
| 200 | createComposerAttachmentUploadWorker, |
| 201 | } from "./composer-attachment-uploads"; |
| 202 | import { |
| 203 | enqueueThreadOutboxMessage, |
| 204 | flattenQueuedThreadMessages, |
| 205 | flushThreadOutbox, |
| 206 | threadOutboxManager, |
| 207 | } from "./thread-outbox"; |
| 208 | import type { QueuedThreadMessage } from "./thread-outbox-model"; |
| 209 | import * as drafts from "./use-composer-drafts"; |
| 210 | import { prepareQueuedMessageAttachments } from "./threadOutboxDelivery"; |
| 211 | |
| 212 | const environmentId = EnvironmentId.make("environment-1"); |
| 213 | const draftKey = "environment-1:thread-1"; |
| 214 | const draftsUri = "file:///documents/composer-drafts/drafts.json"; |
| 215 | const config = { environment: { capabilities: {} } }; |
| 216 | const image: DraftComposerAttachment = { |
| 217 | id: "image-1", |
| 218 | type: "image", |
| 219 | name: "photo.png", |
| 220 | mimeType: "image/png", |
| 221 | sizeBytes: 3, |
| 222 | dataUrl: "data:image/png;base64,YWJj", |
| 223 | previewUri: "data:image/png;base64,YWJj", |
| 224 | }; |
| 225 | let disposeWorker: (() => void) | undefined; |
| 226 | |
| 227 | const requestsAtom = Atom.make((get) => |
| 228 | composerAttachmentUploadRequests({ |
| 229 | drafts: get(drafts.composerDraftUploadSourcesAtom), |
| 230 | queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom), |
| 231 | editingQueuedMessageIds: {}, |
| 232 | knownEnvironmentIds: [environmentId], |
| 233 | connectedEnvironmentIds: new Set([environmentId]), |
| 234 | operableEnvironmentIds: new Set([environmentId]), |
| 235 | serverConfigs: new Map([[environmentId, config]]), |
| 236 | }), |
| 237 | ); |
| 238 | |
| 239 | function worker() { |
| 240 | const { queue, dispose } = createComposerAttachmentUploadWorker(requestsAtom); |
| 241 | disposeWorker = dispose; |
| 242 | return queue; |
| 243 | } |
| 244 | |
| 245 | function sendInput() { |
| 246 | return { |
| 247 | environmentId, |
| 248 | attachments: drafts.getComposerDraftSnapshot(draftKey).attachments, |
| 249 | connected: true, |
| 250 | serverConfig: config, |
| 251 | states: appAtomRegistry.get(composerAttachmentUploadsAtom), |
| 252 | }; |
| 253 | } |
| 254 | |
| 255 | function queuedMessage(): QueuedThreadMessage { |
| 256 | return { |
| 257 | environmentId, |
| 258 | threadId: ThreadId.make("thread-1"), |
| 259 | messageId: MessageId.make("message-1"), |
| 260 | commandId: CommandId.make("command-1"), |
| 261 | text: "Look at this", |
| 262 | attachments: drafts.getComposerDraftSnapshot(draftKey).attachments, |
| 263 | createdAt: "2026-10-17T00:00:00.000Z", |
| 264 | }; |
| 265 | } |
| 266 | |
| 267 | beforeEach(async () => { |
| 268 | vi.spyOn(console, "warn").mockImplementation(() => {}); |
| 269 | native.files.clear(); |
| 270 | native.server.clear(); |
| 271 | native.deleted.length = 0; |
| 272 | native.fault = null; |
| 273 | native.canOperate = true; |
| 274 | native.nextId = 0; |
| 275 | native.nextUuid = 0; |
| 276 | native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}')); |
| 277 | drafts.resetComposerDraftsLoadState(); |
| 278 | appAtomRegistry.set(drafts.composerDraftsAtom, { |
| 279 | [draftKey]: { text: "Look at this", attachments: [image] }, |
| 280 | }); |
| 281 | appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {}); |
| 282 | await drafts.flushComposerDrafts(); |
| 283 | await threadOutboxManager.load(); |
| 284 | native.transfer.mockReset(); |
| 285 | native.transfer.mockImplementation(async (uri, url, options) => { |
| 286 | const bytes = native.files.get(uri)!; |
| 287 | options.onProgress?.({ bytesSent: bytes.length, totalBytes: bytes.length }); |
| 288 | native.server.set(url.split("/").at(-1)!, bytes); |
| 289 | return { status: 204 }; |
| 290 | }); |
| 291 | }); |
| 292 | |
| 293 | afterEach(async () => { |
| 294 | disposeWorker?.(); |
| 295 | disposeWorker = undefined; |
| 296 | native.fault = null; |
| 297 | native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}')); |
| 298 | drafts.resetComposerDraftsLoadState(); |
| 299 | await drafts.flushComposerDrafts(); |
| 300 | await flushThreadOutbox(); |
| 301 | vi.restoreAllMocks(); |
| 302 | }); |
| 303 | |
| 304 | function uploadState() { |
| 305 | return appAtomRegistry.get(composerAttachmentUploadsAtom)[ |
| 306 | composerAttachmentUploadKey(environmentId, image.id) |
| 307 | ]; |
| 308 | } |
| 309 | |
| 310 | it.effect.each(["decode", "write"] as const)( |
| 311 | "keeps an accepted upload ready when the draft %s fails", |
| 312 | (fault) => |
| 313 | Effect.gen(function* () { |
| 314 | native.fault = fault; |
| 315 | if (fault === "decode") |
| 316 | native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":')); |
| 317 | drafts.resetComposerDraftsLoadState(); |
| 318 | const queue = worker(); |
| 319 | yield* Effect.promise(() => queue.settled()); |
| 320 | expect(uploadState()).toEqual({ status: "ready" }); |
| 321 | expect(native.deleted).toEqual([]); |
| 322 | expect(composerAttachmentUploadBlockReason(sendInput())).toBeNull(); |
| 323 | expect(composerAttachmentsStillUploading(sendInput())).toBe(false); |
| 324 | |
| 325 | const message = queuedMessage(); |
| 326 | expect(message.attachments[0]?.uploadedAttachmentId).toBe("pending-1"); |
| 327 | yield* Effect.promise(() => enqueueThreadOutboxMessage(message)); |
| 328 | const prepared = yield* prepareQueuedMessageAttachments(message); |
| 329 | expect(prepared.status).toBe("ready"); |
| 330 | if (prepared.status !== "ready") throw new Error("Outbox preparation abandoned"); |
| 331 | expect(prepared.prepared.pendingAttachmentIds).toEqual(["pending-1"]); |
| 332 | expect(native.transfer).toHaveBeenCalledTimes(1); |
| 333 | }), |
| 334 | ); |
| 335 | |
| 336 | it.effect("uploads again at send time when the server swept a finished upload", () => |
| 337 | Effect.gen(function* () { |
| 338 | const queue = worker(); |
| 339 | yield* Effect.promise(() => queue.settled()); |
| 340 | expect(uploadState()).toEqual({ status: "ready" }); |
| 341 | // The server sweeps pending uploads nothing claimed, here while the draft sat unsent. |
| 342 | native.server.delete("pending-1"); |
| 343 | |
| 344 | const message = queuedMessage(); |
| 345 | yield* Effect.promise(() => enqueueThreadOutboxMessage(message)); |
| 346 | const prepared = yield* prepareQueuedMessageAttachments(message); |
| 347 | expect(prepared.status).toBe("ready"); |
| 348 | if (prepared.status !== "ready") throw new Error("Outbox preparation abandoned"); |
| 349 | expect(prepared.prepared.pendingAttachmentIds).toEqual(["pending-2"]); |
| 350 | expect(native.transfer).toHaveBeenCalledTimes(2); |
| 351 | }), |
| 352 | ); |
| 353 | |
| 354 | it("keeps an upload running when its message is sent mid-upload and records it on the message", async () => { |
| 355 | const transferStarted = Promise.withResolvers<void>(); |
| 356 | const finishTransfer = Promise.withResolvers<{ status: number }>(); |
| 357 | native.transfer.mockImplementationOnce(async (uri, url) => { |
| 358 | native.server.set(url.split("/").at(-1)!, native.files.get(uri)!); |
| 359 | transferStarted.resolve(); |
| 360 | return finishTransfer.promise; |
| 361 | }); |
| 362 | const queue = worker(); |
| 363 | await transferStarted.promise; |
| 364 | |
| 365 | // Send enqueues the message, then clears the draft that owned the upload. |
| 366 | await enqueueThreadOutboxMessage(queuedMessage()); |
| 367 | drafts.clearComposerDraftContent(draftKey, { deferAttachmentCleanup: true }); |
| 368 | finishTransfer.resolve({ status: 204 }); |
| 369 | await queue.settled(); |
| 370 | |
| 371 | expect(native.transfer).toHaveBeenCalledOnce(); |
| 372 | expect(native.deleted).toEqual([]); |
| 373 | const [queued] = flattenQueuedThreadMessages( |
| 374 | appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), |
| 375 | ); |
| 376 | expect(queued?.attachments[0]?.uploadedAttachmentId).toBe("pending-1"); |
| 377 | }); |
| 378 | |
| 379 | it.each(["http", "permission"] as const)( |
| 380 | "keeps a real %s upload failure blocking Send", |
| 381 | async (failure) => { |
| 382 | if (failure === "http") native.transfer.mockResolvedValueOnce({ status: 503 }); |
| 383 | if (failure === "permission") native.canOperate = false; |
| 384 | const queue = worker(); |
| 385 | await queue.settled(); |
| 386 | expect(composerAttachmentUploadBlockReason(sendInput())).toBe( |
| 387 | "Retry or remove the failed attachment", |
| 388 | ); |
| 389 | expect([...native.server.values()]).toEqual([]); |
| 390 | }, |
| 391 | ); |
| 392 | |
| 393 | it("keeps an unexpected draft flush error blocking Send", async () => { |
| 394 | vi.spyOn(drafts, "flushComposerDrafts").mockRejectedValueOnce( |
| 395 | new Error("Unexpected flush defect"), |
| 396 | ); |
| 397 | const queue = worker(); |
| 398 | await queue.settled(); |
| 399 | expect(composerAttachmentUploadBlockReason(sendInput())).toBe( |
| 400 | "Retry or remove the failed attachment", |
| 401 | ); |
| 402 | // The server sweeps pending uploads nothing claims; a retry uploads again. |
| 403 | expect(native.deleted).toEqual([]); |
| 404 | }); |
| 405 | |
| 406 | it("uploads draft attachments for threads whose ids contain colons", () => { |
| 407 | const keys = [ |
| 408 | "environment-1:thread-1", |
| 409 | "environment-1:thread:mcp:namespace:key:0", |
| 410 | "environment-1:command-1:fork", |
| 411 | "environment-1:thread-1~queued-edit~run:1", |
| 412 | ]; |
| 413 | const requests = composerAttachmentUploadRequests({ |
| 414 | drafts: Object.fromEntries(keys.map((key) => [key, { attachments: [{ ...image, id: key }] }])), |
| 415 | queuedMessagesByThreadKey: {}, |
| 416 | editingQueuedMessageIds: {}, |
| 417 | knownEnvironmentIds: [environmentId], |
| 418 | connectedEnvironmentIds: new Set([environmentId]), |
| 419 | operableEnvironmentIds: new Set([environmentId]), |
| 420 | serverConfigs: new Map([[environmentId, config]]), |
| 421 | }); |
| 422 | expect(requests.map((request) => [request.attachment.id, request.environmentId])).toEqual( |
| 423 | keys.map((key) => [key, environmentId]), |
| 424 | ); |
| 425 | }); |
| 426 | |
| 427 | it("does not upload a disconnected colon environment's draft to its connected prefix", () => { |
| 428 | const connected = EnvironmentId.make("a"); |
| 429 | const disconnected = EnvironmentId.make("a:vcs-status:b"); |
| 430 | const requests = composerAttachmentUploadRequests({ |
| 431 | drafts: { [`${disconnected}:thread-1`]: { attachments: [image] } }, |
| 432 | queuedMessagesByThreadKey: {}, |
| 433 | editingQueuedMessageIds: {}, |
| 434 | knownEnvironmentIds: [connected, disconnected], |
| 435 | connectedEnvironmentIds: new Set([connected]), |
| 436 | operableEnvironmentIds: new Set([connected]), |
| 437 | serverConfigs: new Map([[connected, config]]), |
| 438 | }); |
| 439 | expect(requests).toEqual([]); |
| 440 | }); |