The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | PROVIDER_SEND_TURN_MAX_FILE_BYTES, |
| 3 | WS_METHODS, |
| 4 | type AttachmentCreateUploadUrlInput, |
| 5 | type AttachmentCreateUploadUrlResult, |
| 6 | type AttachmentDeleteInput, |
| 7 | type EnvironmentId, |
| 8 | } from "@t3tools/contracts"; |
| 9 | import * as Cause from "effect/Cause"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Exit from "effect/Exit"; |
| 12 | import { mFallback, msg } from "gt-i18n"; |
| 13 | import type { MFunctionType } from "gt-i18n/types"; |
| 14 | import type { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; |
| 15 | |
| 16 | import type { EnvironmentRegistry } from "../connection/registry.ts"; |
| 17 | import { |
| 18 | createEnvironmentRpcCommand, |
| 19 | awaitAtomResult, |
| 20 | runAtomCommand, |
| 21 | type AtomCommand, |
| 22 | } from "./runtime.ts"; |
| 23 | |
| 24 | export function createAttachmentEnvironmentAtoms<R, E>( |
| 25 | runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>, |
| 26 | ) { |
| 27 | return { |
| 28 | createUploadUrl: createEnvironmentRpcCommand(runtime, { |
| 29 | label: "environment-command:attachments:create-upload-url", |
| 30 | tag: WS_METHODS.attachmentsCreateUploadUrl, |
| 31 | }), |
| 32 | remove: createEnvironmentRpcCommand(runtime, { |
| 33 | label: "environment-command:attachments:delete", |
| 34 | tag: WS_METHODS.attachmentsDelete, |
| 35 | }), |
| 36 | }; |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Pending uploads expire, so this is the signal to upload the bytes again rather than retry the |
| 41 | * lookup. A structural `_tag` check rather than a schema check: the squashed cause of a failed |
| 42 | * RPC is not guaranteed to be a decoded error class instance, only a tagged value. |
| 43 | */ |
| 44 | export function isAssetAttachmentNotFoundFailure(error: unknown): boolean { |
| 45 | return ( |
| 46 | typeof error === "object" && |
| 47 | error !== null && |
| 48 | "_tag" in error && |
| 49 | error._tag === "AssetAttachmentNotFoundError" |
| 50 | ); |
| 51 | } |
| 52 | |
| 53 | export type PersistedAttachmentVerification = |
| 54 | | { readonly status: "verified" } |
| 55 | | { readonly status: "missing" } |
| 56 | | { readonly status: "failed"; readonly error: unknown }; |
| 57 | |
| 58 | export function verifyPersistedAttachmentUpload<A, E>(input: { |
| 59 | readonly registry: AtomRegistry.AtomRegistry; |
| 60 | readonly createAssetUrl: (query: { |
| 61 | readonly environmentId: EnvironmentId; |
| 62 | readonly input: { |
| 63 | readonly resource: { readonly _tag: "attachment"; readonly attachmentId: string }; |
| 64 | }; |
| 65 | }) => Atom.Atom<AsyncResult.AsyncResult<A, E>>; |
| 66 | readonly environmentId: EnvironmentId; |
| 67 | readonly attachmentId: string; |
| 68 | }): Effect.Effect<PersistedAttachmentVerification> { |
| 69 | return awaitAtomResult( |
| 70 | input.registry, |
| 71 | input.createAssetUrl({ |
| 72 | environmentId: input.environmentId, |
| 73 | input: { resource: { _tag: "attachment", attachmentId: input.attachmentId } }, |
| 74 | }), |
| 75 | // `refresh` forces a server round trip: the asset URL query atom caches |
| 76 | // results (SWR), so a retry right after a transient failure would |
| 77 | // otherwise re-observe the cached failure and never ask the server. |
| 78 | { refresh: true }, |
| 79 | ).pipe( |
| 80 | Effect.matchCause({ |
| 81 | onSuccess: (): PersistedAttachmentVerification => ({ status: "verified" }), |
| 82 | onFailure: (cause): PersistedAttachmentVerification => { |
| 83 | const error = Cause.squash(cause); |
| 84 | return isAssetAttachmentNotFoundFailure(error) |
| 85 | ? { status: "missing" } |
| 86 | : { status: "failed", error }; |
| 87 | }, |
| 88 | }), |
| 89 | Effect.withSpan("Attachments.verifyPersistedUpload"), |
| 90 | ); |
| 91 | } |
| 92 | |
| 93 | type AttachmentCreateUploadUrlCommand<E> = AtomCommand< |
| 94 | { readonly environmentId: EnvironmentId; readonly input: AttachmentCreateUploadUrlInput }, |
| 95 | AttachmentCreateUploadUrlResult, |
| 96 | E |
| 97 | >; |
| 98 | |
| 99 | type AttachmentRemoveCommand<E> = AtomCommand< |
| 100 | { readonly environmentId: EnvironmentId; readonly input: AttachmentDeleteInput }, |
| 101 | unknown, |
| 102 | E |
| 103 | >; |
| 104 | |
| 105 | export function deletePendingAttachmentUpload<E>(input: { |
| 106 | readonly registry: AtomRegistry.AtomRegistry; |
| 107 | readonly remove: AttachmentRemoveCommand<E>; |
| 108 | readonly environmentId: EnvironmentId; |
| 109 | readonly attachmentId: string; |
| 110 | }): void { |
| 111 | void runAtomCommand( |
| 112 | input.registry, |
| 113 | input.remove, |
| 114 | { environmentId: input.environmentId, input: { attachmentId: input.attachmentId } }, |
| 115 | { reportFailure: false, reportDefect: false }, |
| 116 | ); |
| 117 | } |
| 118 | |
| 119 | export type AttachmentUploadCycleResult = |
| 120 | | { readonly status: "uploaded"; readonly attachmentId: string } |
| 121 | | { |
| 122 | readonly status: "failed"; |
| 123 | readonly step: "mint" | "resolve-url" | "transfer"; |
| 124 | readonly attachmentId: string | null; |
| 125 | readonly error: unknown; |
| 126 | }; |
| 127 | |
| 128 | /** |
| 129 | * Mints an upload slot and sends the bytes. A failure keeps the minted id in the result so the |
| 130 | * caller decides between retry and release. Interrupting the cycle aborts the transfer and |
| 131 | * deletes the fresh mint, including when the interruption arrives while minting. |
| 132 | */ |
| 133 | export function runAttachmentUploadCycle<E, RE, TE>(input: { |
| 134 | readonly registry: AtomRegistry.AtomRegistry; |
| 135 | readonly createUploadUrl: AttachmentCreateUploadUrlCommand<E>; |
| 136 | readonly remove: AttachmentRemoveCommand<RE>; |
| 137 | readonly environmentId: EnvironmentId; |
| 138 | readonly upload: AttachmentCreateUploadUrlInput; |
| 139 | readonly resolveUploadUrl: (relativeUrl: string) => string | null; |
| 140 | /** Sends the bytes; interrupting it aborts the transfer. */ |
| 141 | readonly transport: (url: string) => Effect.Effect<void, TE>; |
| 142 | }): Effect.Effect<AttachmentUploadCycleResult> { |
| 143 | return Effect.uninterruptibleMask((restore) => |
| 144 | Effect.gen(function* () { |
| 145 | const minted = yield* Effect.exit( |
| 146 | input.createUploadUrl.run(input.registry, { |
| 147 | environmentId: input.environmentId, |
| 148 | input: input.upload, |
| 149 | }), |
| 150 | ); |
| 151 | if (Exit.isFailure(minted)) { |
| 152 | return { |
| 153 | status: "failed", |
| 154 | step: "mint", |
| 155 | attachmentId: null, |
| 156 | error: Cause.squash(minted.cause), |
| 157 | } as const; |
| 158 | } |
| 159 | const attachmentId = minted.value.attachmentId; |
| 160 | return yield* restore( |
| 161 | Effect.suspend(() => { |
| 162 | const url = input.resolveUploadUrl(minted.value.relativeUrl); |
| 163 | if (!url) { |
| 164 | return Effect.succeed<AttachmentUploadCycleResult>({ |
| 165 | status: "failed", |
| 166 | step: "resolve-url", |
| 167 | attachmentId, |
| 168 | error: new Error("The environment is not connected."), |
| 169 | }); |
| 170 | } |
| 171 | return input.transport(url).pipe( |
| 172 | Effect.as<AttachmentUploadCycleResult>({ status: "uploaded", attachmentId }), |
| 173 | Effect.catch((error) => |
| 174 | Effect.succeed<AttachmentUploadCycleResult>({ |
| 175 | status: "failed", |
| 176 | step: "transfer", |
| 177 | attachmentId, |
| 178 | error, |
| 179 | }), |
| 180 | ), |
| 181 | ); |
| 182 | }), |
| 183 | ).pipe( |
| 184 | Effect.onInterrupt(() => |
| 185 | Effect.sync(() => |
| 186 | deletePendingAttachmentUpload({ |
| 187 | registry: input.registry, |
| 188 | remove: input.remove, |
| 189 | environmentId: input.environmentId, |
| 190 | attachmentId, |
| 191 | }), |
| 192 | ), |
| 193 | ), |
| 194 | ); |
| 195 | }), |
| 196 | ).pipe(Effect.withSpan("Attachments.runUploadCycle")); |
| 197 | } |
| 198 | |
| 199 | /** |
| 200 | * The contract caps what a turn may reference, so a larger advertised value must not admit |
| 201 | * files the send would then refuse. |
| 202 | */ |
| 203 | export function clampFileAttachmentUploadBytes(advertisedMaxUploadBytes: number): number { |
| 204 | return Math.min(advertisedMaxUploadBytes, PROVIDER_SEND_TURN_MAX_FILE_BYTES); |
| 205 | } |
| 206 | |
| 207 | export function formatAttachmentSize( |
| 208 | sizeBytes: number, |
| 209 | resolve: MFunctionType = mFallback, |
| 210 | ): string { |
| 211 | const kilobytes = Math.max(1, Math.ceil(sizeBytes / 1024)); |
| 212 | // Pick the unit after rounding, so 1023.5 KB reads "1.0 MB", not "1024 KB". |
| 213 | return kilobytes >= 1024 |
| 214 | ? resolve(msg("{size} MB", { size: (sizeBytes / (1024 * 1024)).toFixed(1) })) |
| 215 | : resolve(msg("{size} KB", { size: kilobytes })); |
| 216 | } |
| 217 | |
| 218 | export function fileAttachmentTooLargeMessage( |
| 219 | name: string, |
| 220 | maxUploadBytes: number, |
| 221 | resolve: MFunctionType = mFallback, |
| 222 | ): string { |
| 223 | const size = |
| 224 | maxUploadBytes >= 1024 * 1024 && maxUploadBytes % (1024 * 1024) === 0 |
| 225 | ? resolve(msg("{count} MB", { count: maxUploadBytes / (1024 * 1024) })) |
| 226 | : maxUploadBytes >= 1024 && maxUploadBytes % 1024 === 0 |
| 227 | ? resolve(msg("{count} KB", { count: maxUploadBytes / 1024 })) |
| 228 | : resolve( |
| 229 | msg("{count, plural, one {{count} byte} other {{count} bytes}}", { |
| 230 | count: maxUploadBytes, |
| 231 | }), |
| 232 | ); |
| 233 | return resolve(msg("''{name}'' exceeds the {size} attachment limit.", { name, size })); |
| 234 | } |