@tangle-network/agent-app 0.50.3 → 0.50.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assistant/index.js +2 -2
- package/dist/channels/hooks.d.ts +5 -13
- package/dist/channels/index.js +8 -22
- package/dist/channels/index.js.map +1 -1
- package/dist/channels/numbers.d.ts +1 -1
- package/dist/channels/payment.d.ts +1 -1
- package/dist/chat-routes/index.js +3 -3
- package/dist/{chunk-KJEW23GR.js → chunk-3MIQCPUX.js} +2 -2
- package/dist/{chunk-FRVVHMZO.js → chunk-5DEQ2FJK.js} +2 -2
- package/dist/{chunk-3NM4GCAY.js → chunk-DPO7FGCN.js} +9 -6
- package/dist/chunk-DPO7FGCN.js.map +1 -0
- package/dist/{chunk-GEHULTVU.js → chunk-P5ZJQKOI.js} +31 -40
- package/dist/{chunk-GEHULTVU.js.map → chunk-P5ZJQKOI.js.map} +1 -1
- package/dist/{chunk-3UBAO3N5.js → chunk-Q3ZHNN5X.js} +38 -61
- package/dist/chunk-Q3ZHNN5X.js.map +1 -0
- package/dist/hosted-agent/application.js +1 -0
- package/dist/hosted-agent/application.js.map +1 -1
- package/dist/hosted-agent/react/index.js +9 -8
- package/dist/hosted-agent/react/index.js.map +1 -1
- package/dist/public-consultation/index.js +2 -2
- package/dist/sandbox/index.js +1 -1
- package/dist/sandbox/recovery.d.ts +31 -29
- package/dist/stream/index.js +1 -1
- package/dist/stream/turn-identity.d.ts +16 -11
- package/dist/web-react/async/index.js +1 -1
- package/dist/web-react/async/use-async-resource.d.ts +2 -2
- package/dist/web-react/async/use-confirmed-mutation.d.ts +6 -3
- package/dist/web-react/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-3NM4GCAY.js.map +0 -1
- package/dist/chunk-3UBAO3N5.js.map +0 -1
- /package/dist/{chunk-KJEW23GR.js.map → chunk-3MIQCPUX.js.map} +0 -0
- /package/dist/{chunk-FRVVHMZO.js.map → chunk-5DEQ2FJK.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/stream/turn-identity.ts","../src/stream/turn-observation.ts"],"sourcesContent":["import type { JsonRecord } from './stream-normalizer'\n\n/** Define the structure of a chat message stored for a specific conversation turn */\nexport interface PersistedChatMessageForTurn {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts: Array<Record<string, unknown>> | null\n}\n\n/** Represent a chat turn with resolved user message insertion and prior message context */\nexport interface ResolvedChatTurn {\n turnIndex: number\n shouldInsertUserMessage: boolean\n priorMessages: PersistedChatMessageForTurn[]\n userParts: JsonRecord[]\n /** The id of the user row this turn REUSES (retry dedup), when one was\n * found. Absent on the insert path, where no row exists yet.\n *\n * The reused row is deliberately EXCLUDED from `priorMessages` (it is this\n * turn's own user message, not prior context), so this field is the only\n * way a caller can name it. */\n reusedUserMessageId?: string\n}\n\n/** Normalize and validate a client turn ID string ensuring it meets format and length requirements */\nexport function normalizeClientTurnId(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined\n if (typeof value !== 'string') throw new Error('turnId must be a string')\n const trimmed = value.trim()\n if (!trimmed) throw new Error('turnId must not be blank')\n if (trimmed.length > 160) throw new Error('turnId is too long')\n if (!/^[A-Za-z0-9:_-]+$/.test(trimmed)) {\n throw new Error('turnId contains unsupported characters')\n }\n return trimmed\n}\n\n/** Build an array of text parts with optional turn ID for user input */\nexport function buildUserTextParts(text: string, turnId: string | undefined): JsonRecord[] {\n const part: JsonRecord = { type: 'text', text }\n if (turnId) part.turnId = turnId\n return [part]\n}\n\n/** Resolve whether a message contains any part with the specified turn ID */\nexport function messageHasTurnId(message: PersistedChatMessageForTurn, turnId: string): boolean {\n for (const part of message.parts ?? []) {\n if (part && typeof part === 'object' && String(part.turnId ?? '') === turnId) {\n return true\n }\n }\n return false\n}\n\n/** Resolve a chat turn by determining message reuse and constructing user message parts */\nexport function resolveChatTurn(input: {\n existingMessages: PersistedChatMessageForTurn[]\n userContent: string\n turnId?: string\n /** True when the thread has a turn still RUNNING in the turn-event buffer\n * (`turnStore.listRunning(threadId)`).\n *\n * Without incremental persistence the trailing row of a thread mid-turn is\n * always the user row, so the content fallback below could assume it. With\n * incremental persistence the assistant row lands seconds into the turn, so\n * a retry of that same turn finds an ASSISTANT row trailing and would\n * insert a duplicate user row.\n *\n * This flag is the discriminator that keeps both cases right, and it needs\n * no new state: an assistant row trailing a turn that is still running is\n * that turn's in-flight draft (walk past it — this is a retry), whereas an\n * assistant row trailing a SETTLED turn is a completed answer (stop — the\n * user genuinely repeated a message and deserves a new turn). */\n hasRunningTurn?: boolean\n}): ResolvedChatTurn {\n const { existingMessages, userContent, turnId } = input\n const reusableIndex = findReusableUserMessageIndex(\n existingMessages,\n userContent,\n turnId,\n input.hasRunningTurn === true,\n )\n if (reusableIndex >= 0) {\n // Guarded read: `id` is typed `string`, but these rows come from a product\n // store the shell does not validate, so an adapter that omits it must\n // surface as \"no id\" rather than as the string \"undefined\".\n const reusedId = existingMessages[reusableIndex]?.id\n return {\n turnIndex: countUserMessages(existingMessages.slice(0, reusableIndex)),\n shouldInsertUserMessage: false,\n priorMessages: existingMessages.slice(0, reusableIndex),\n userParts: buildUserTextParts(userContent, turnId),\n ...(typeof reusedId === 'string' && reusedId ? { reusedUserMessageId: reusedId } : {}),\n }\n }\n\n return {\n turnIndex: countUserMessages(existingMessages),\n shouldInsertUserMessage: true,\n priorMessages: existingMessages,\n userParts: buildUserTextParts(userContent, turnId),\n }\n}\n\nfunction findReusableUserMessageIndex(\n messages: PersistedChatMessageForTurn[],\n userContent: string,\n turnId: string | undefined,\n hasRunningTurn: boolean,\n): number {\n if (turnId) {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]\n if (message?.role === 'user' && messageHasTurnId(message, turnId)) return index\n }\n // A caller-supplied id is authoritative. A different id with identical\n // text is a deliberate new turn, while a transport retry reuses the same\n // id and takes the match above. Falling through to content dedup here lets\n // an unrelated abandoned running row swallow an intentional repeat.\n return -1\n }\n\n // Content fallback for a client that sends no turnId. Only the trailing rows\n // of a turn still RUNNING are walked past (they are that turn's incrementally\n // persisted assistant draft); a settled assistant row still ends the scan, so\n // a user who genuinely repeats a message gets a new turn exactly as before.\n let index = messages.length - 1\n if (hasRunningTurn) {\n while (index >= 0 && messages[index]?.role === 'assistant') index -= 1\n }\n const latest = index >= 0 ? messages[index] : undefined\n if (latest?.role === 'user' && latest.content === userContent) return index\n\n return -1\n}\n\nfunction countUserMessages(messages: PersistedChatMessageForTurn[]): number {\n return messages.filter((message) => message.role === 'user').length\n}\n","/** Read-side checkpoints for native chat NDJSON. This never submits or cancels work. */\nexport interface TurnObservation {\n schema: 'turn-observation-v1'\n streamId: string | null\n /** Replay ordinals only. Unsequenced live frames cannot advance this cursor. */\n lastSeq: number\n outcome: 'completed' | 'failed' | null\n replayStatus: string | null\n eventCount: number\n}\n\nexport function parseTurnObservation(value?: unknown): TurnObservation {\n if (value === undefined) return {\n schema: 'turn-observation-v1', streamId: null, lastSeq: 0,\n outcome: null, replayStatus: null, eventCount: 0,\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Invalid turn observation')\n const v = value as Record<string, unknown>\n if (v.schema !== 'turn-observation-v1'\n || !(v.streamId === null || (typeof v.streamId === 'string' && /^[A-Za-z0-9_-]+$/.test(v.streamId)))\n || !Number.isSafeInteger(v.lastSeq) || Number(v.lastSeq) < 0\n || !Number.isSafeInteger(v.eventCount) || Number(v.eventCount) < 0\n || !(v.outcome === null || v.outcome === 'completed' || v.outcome === 'failed')\n || !(v.replayStatus === null || typeof v.replayStatus === 'string')\n || (v.streamId === null && Number(v.lastSeq) > 0)) throw new TypeError('Invalid turn observation')\n return {\n schema: 'turn-observation-v1', streamId: v.streamId as string | null,\n lastSeq: Number(v.lastSeq), outcome: v.outcome as TurnObservation['outcome'],\n replayStatus: v.replayStatus as string | null, eventCount: Number(v.eventCount),\n }\n}\n\nexport interface TurnObservationUpdate {\n checkpoint: TurnObservation\n /** False only for an already-checkpointed replay ordinal. */\n accepted: boolean\n event: Record<string, unknown>\n}\n\n/** Reduce an observed frame. Ordered replay gaps are errors, not silent lost work. */\nexport function observeTurnEvent(previous: TurnObservation, raw: unknown): TurnObservationUpdate {\n const checkpoint = parseTurnObservation(previous)\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new TypeError('Turn frame must be an object')\n const outer = raw as Record<string, unknown>\n const inner = outer.kind === 'event' ? outer.event : outer\n if (!inner || typeof inner !== 'object' || Array.isArray(inner)) throw new TypeError('Invalid turn event envelope')\n const event = inner as Record<string, unknown>\n if (typeof event.type !== 'string' || !event.type) throw new TypeError('Turn frame requires a type')\n\n // Even a duplicate marker must not switch which execution we are observing.\n if (event.type === 'turn') {\n if (typeof event.turnId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(event.turnId)) throw new TypeError('Invalid stream identity')\n if (checkpoint.streamId !== null && checkpoint.streamId !== event.turnId) throw new Error('Replay stream identity changed')\n checkpoint.streamId = event.turnId\n }\n const seq = outer.seq\n if (seq !== undefined && seq !== -1) {\n if (!Number.isSafeInteger(seq) || Number(seq) < 1) throw new TypeError('Invalid replay ordinal')\n if (checkpoint.streamId === null) throw new Error('Replay ordinal arrived before stream identity')\n if (Number(seq) <= checkpoint.lastSeq) return { checkpoint, accepted: false, event }\n if (Number(seq) !== checkpoint.lastSeq + 1) throw new Error('Replay has a gap; retain the checkpoint and inspect durable history')\n checkpoint.lastSeq = Number(seq)\n } else if (seq === -1 && event.type !== 'turn_status') {\n throw new TypeError('Only a turn-status sentinel may have ordinal -1')\n }\n\n if (event.type === 'error' || event.type === 'session.run.failed') checkpoint.outcome = 'failed'\n if (event.type === 'session.run.completed' && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n if (event.type === 'turn_status') {\n if (typeof event.status !== 'string') throw new TypeError('Turn status requires a value')\n checkpoint.replayStatus = event.status\n if (['error', 'failed', 'aborted', 'cancelled'].includes(event.status)) checkpoint.outcome = 'failed'\n if (['complete', 'completed'].includes(event.status) && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n }\n checkpoint.eventCount += 1\n return { checkpoint, accepted: true, event }\n}\n\nexport interface ConsumeTurnStreamOptions {\n checkpoint?: TurnObservation\n /** Commit evidence and its checkpoint durably before acknowledging this frame. */\n commit(update: TurnObservationUpdate): Promise<void>\n /** Bound untrusted frame memory, not total run duration or total transcript size. */\n maxFrameBytes?: number\n}\n\n/**\n * Consume one viewing connection. EOF without a terminal event stays incomplete.\n * A disconnect/abort propagates; the last committed checkpoint remains resumable.\n * The caller owns network observation windows separately from execution deadlines.\n */\nexport async function consumeTurnStream(\n body: AsyncIterable<Uint8Array>,\n options: ConsumeTurnStreamOptions,\n): Promise<TurnObservation> {\n const maxFrameBytes = options.maxFrameBytes ?? 4 * 1024 * 1024\n if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes < 1) throw new RangeError('Frame byte limit must be positive')\n let state = parseTurnObservation(options.checkpoint)\n const decoder = new TextDecoder('utf-8', { fatal: true })\n let pending = ''\n let frameBytes = 0\n async function accept(line: string): Promise<void> {\n if (!line.trim()) return\n const update = observeTurnEvent(state, JSON.parse(line))\n if (update.accepted) await options.commit(update)\n state = update.checkpoint\n }\n for await (const chunk of body) {\n // Count bytes before decoding: a malicious unterminated frame cannot grow\n // without bound, and splitting UTF-8 characters across chunks stays valid.\n let start = 0\n for (let end = 0; end < chunk.length; end += 1) {\n if (chunk[end] !== 10) continue\n frameBytes += end - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start, end + 1), { stream: true })\n await accept(pending)\n pending = ''; frameBytes = 0; start = end + 1\n }\n frameBytes += chunk.length - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start), { stream: true })\n }\n pending += decoder.decode()\n await accept(pending)\n return state\n}\n"],"mappings":";AA0BO,SAAS,sBAAsB,OAAoC;A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AM,IAAI,CAAC;AACvD,QAAI,OAAO,SAAU,OAAM,QAAQ,OAAO,MAAM;AAChD,YAAQ,OAAO;AAAA,EACjB;AACA,mBAAiB,SAAS,MAAM;AAG9B,QAAI,QAAQ;AACZ,aAAS,MAAM,GAAG,MAAM,MAAM,QAAQ,OAAO,GAAG;AAC9C,UAAI,MAAM,GAAG,MAAM,GAAI;AACvB,oBAAc,MAAM;AACpB,UAAI,aAAa,cAAe,OAAM,IAAI,WAAW,+BAA+B;AACpF,iBAAW,QAAQ,OAAO,MAAM,SAAS,OAAO,MAAM,CAAC,GAAG,EAAE,QAAQ,KAAK,CAAC;AAC1E,YAAM,OAAO,OAAO;AACpB,gBAAU;AAAI,mBAAa;AAAG,cAAQ,MAAM;AAAA,IAC9C;AACA,kBAAc,MAAM,SAAS;AAC7B,QAAI,aAAa,cAAe,OAAM,IAAI,WAAW,+BAA+B;AACpF,eAAW,QAAQ,OAAO,MAAM,SAAS,KAAK,GAAG,EAAE,QAAQ,KAAK,CAAC;AAAA,EACnE;AACA,aAAW,QAAQ,OAAO;AAC1B,QAAM,OAAO,OAAO;AACpB,SAAO;AACT;","names":["index"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/web-react/async/state.ts","../src/web-react/async/use-async-resource.ts","../src/web-react/async/use-confirmed-mutation.ts","../src/web-react/async/async-view.tsx"],"sourcesContent":["/**\n * The fetch-state contract: a failed load cannot render as empty data.\n *\n * Three shapes produce that defect, and two audited verticals shipped dozens of\n * each: a `catch` handler that only clears a loading flag, an early return on a\n * non-ok response, and a bare `null` returned while loading. All three end with\n * the same pixels a successful-but-empty load produces — \"No templates\n * available\", an empty member list, a blank conversation — so the reader cannot\n * tell \"we asked and there is nothing\" from \"we could not ask\", and the retry\n * that would fix it is never offered.\n *\n * `AsyncResourceState` makes the two outcomes separate variants: `error` is the\n * only one carrying a message and it is never reachable with a value, `empty` is\n * the only one carrying a resolved-but-empty value and it never carries a\n * message. A component rendering one is structurally not rendering the other.\n *\n * This file is React-free so the state model, the emptiness rule and the\n * Response readers can be unit-tested and reused outside a component.\n */\n\n/**\n * - `idle` — no load has been attempted (the hook is disabled, or its inputs\n * are not resolved yet). Distinct from `loading`: nothing is in flight.\n * - `loading` — a load is in flight and no value is held.\n * - `error` — the load failed. Carries the message and never a value.\n * - `empty` — the load succeeded and the value is empty. Never carries a message.\n * - `ready` — the load succeeded and the value is non-empty.\n */\nexport type AsyncResourceStatus = 'idle' | 'loading' | 'error' | 'empty' | 'ready'\n\n/** Re-runs the load. Present on every variant so the error branch can never be\n * rendered without the action that recovers from it. */\nexport interface AsyncRetryable {\n readonly retry: () => void\n}\n\nexport type AsyncResourceState<T> =\n | ({ readonly status: 'idle' } & AsyncRetryable)\n | ({ readonly status: 'loading' } & AsyncRetryable)\n | ({ readonly status: 'error'; readonly message: string; readonly error: unknown } & AsyncRetryable)\n | ({ readonly status: 'empty'; readonly value: T } & AsyncRetryable)\n | ({ readonly status: 'ready'; readonly value: T } & AsyncRetryable)\n\n/** The state model without the retry action — what a reducer produces. */\nexport type AsyncResolution<T> =\n | { readonly status: 'idle' }\n | { readonly status: 'loading' }\n | { readonly status: 'error'; readonly message: string; readonly error: unknown }\n | { readonly status: 'empty'; readonly value: T }\n | { readonly status: 'ready'; readonly value: T }\n\nexport const DEFAULT_ASYNC_ERROR_MESSAGE = 'Something went wrong. Please try again.'\n\n/**\n * Default emptiness rule: `null`/`undefined`, an empty array, an empty `Map` or\n * `Set`. A string, a number and a plain object are `ready` — `''` and `{}` are\n * legitimate values for the resources that produce them, and guessing otherwise\n * would route a real answer into the empty branch. Pass `isEmpty` for a shape\n * this cannot see into (`{ items: [] }`, a paged envelope, a count).\n */\nexport function defaultIsEmpty(value: unknown): boolean {\n if (value === null || value === undefined) return true\n if (Array.isArray(value)) return value.length === 0\n if (value instanceof Map || value instanceof Set) return value.size === 0\n return false\n}\n\nfunction hasMessage(value: object): value is { message: unknown } {\n return 'message' in value\n}\n\n/** Best available human-readable message for a thrown value. Never returns an\n * empty string — a blank error block reads as a rendering bug. */\nexport function asyncErrorMessage(error: unknown, fallback: string = DEFAULT_ASYNC_ERROR_MESSAGE): string {\n if (typeof error === 'string' && error.trim() !== '') return error\n if (typeof error === 'object' && error !== null && hasMessage(error)) {\n const message = error.message\n if (typeof message === 'string' && message.trim() !== '') return message\n }\n return fallback\n}\n\n/** Classifies a successfully loaded value into `ready` or `empty`. */\nexport function resolveAsyncValue<T>(value: T, isEmpty: (value: T) => boolean = defaultIsEmpty): AsyncResolution<T> {\n return isEmpty(value) ? { status: 'empty', value } : { status: 'ready', value }\n}\n\n/**\n * A non-ok HTTP response, as a throwable. `requireOk`/`readOkJson` raise this so\n * a non-ok response reaches the `error` branch instead of an early `return` that\n * leaves the caller rendering the empty branch.\n */\nexport class AsyncRequestError extends Error {\n readonly status: number\n readonly statusText: string\n readonly url: string\n /** First 200 characters of the response body when it could be read, else `''`.\n * Kept off `message` so a server's HTML error page never becomes UI copy. */\n readonly body: string\n\n constructor(response: { status: number; statusText?: string; url?: string }, body = '') {\n const statusText = response.statusText ?? ''\n super(`Request failed (${response.status}${statusText ? ` ${statusText}` : ''})`)\n this.name = 'AsyncRequestError'\n this.status = response.status\n this.statusText = statusText\n this.url = response.url ?? ''\n this.body = body\n }\n}\n\nasync function readBodySnippet(response: Response): Promise<string> {\n try {\n return (await response.text()).slice(0, 200)\n } catch {\n // An already-consumed or unreadable body is a missing diagnostic, not a\n // second failure — the status is what the error reports.\n return ''\n }\n}\n\n/** Returns the response when ok; throws `AsyncRequestError` otherwise. Reads the\n * body only on the failure path, so the caller keeps an unconsumed stream. */\nexport async function requireOk(response: Response): Promise<Response> {\n if (response.ok) return response\n throw new AsyncRequestError(response, await readBodySnippet(response))\n}\n\n/**\n * `requireOk` + `response.json()`. Without `parse` the result is `unknown`, so a\n * caller narrows at the JSON boundary rather than inheriting an unchecked shape;\n * with `parse` the validator runs inside the load and a rejection lands in the\n * `error` branch.\n */\nexport async function readOkJson(response: Response): Promise<unknown>\nexport async function readOkJson<T>(response: Response, parse: (data: unknown) => T): Promise<T>\nexport async function readOkJson<T>(response: Response, parse?: (data: unknown) => T): Promise<T | unknown> {\n await requireOk(response)\n let data: unknown\n try {\n data = await response.json()\n } catch (error) {\n throw new Error('The response was not valid JSON.', { cause: error })\n }\n return parse ? parse(data) : data\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\n\nimport {\n asyncErrorMessage,\n defaultIsEmpty,\n resolveAsyncValue,\n type AsyncResolution,\n type AsyncResourceState,\n} from './state'\n\nexport interface AsyncLoadContext {\n /** Aborted when the inputs change, a retry supersedes this load, or the\n * component unmounts. Forward it to `fetch` so a superseded request stops. */\n readonly signal: AbortSignal\n}\n\nexport interface UseAsyncResourceOptions<T> {\n /**\n * The one load. Reject (or throw) to reach the `error` branch — a non-ok\n * response must reject too, which is what `requireOk`/`readOkJson` are for.\n * Read from a ref internally, so an inline arrow does not re-trigger; `deps`\n * is what declares when the load must run again.\n */\n load: (context: AsyncLoadContext) => Promise<T>\n /** Re-runs the load when any entry changes by `Object.is`, like `useEffect`. */\n deps?: readonly unknown[]\n /** `false` holds the resource at `idle` and runs nothing — for inputs that are\n * not resolved yet. Flipping it to `true` starts the load. */\n enabled?: boolean\n /** First-render seed (an SSR/loader page). The hook starts resolved and skips\n * the first load. Read once — later identity changes are ignored, so a\n * revalidating loader belongs in `deps`, not here. */\n initialValue?: T\n /** Splits a successful load into `empty` vs `ready`. Default: `defaultIsEmpty`. */\n isEmpty?: (value: T) => boolean\n /** Maps a thrown value to the message the `error` branch renders. */\n errorMessage?: (error: unknown) => string\n}\n\n/** Bumps a token when any dependency changes identity, so the effect's own\n * dependency list stays a fixed length whatever the caller passes. */\nfunction useChangeToken(deps: readonly unknown[]): number {\n const ref = useRef<{ deps: readonly unknown[]; token: number }>({ deps, token: 0 })\n const changed =\n ref.current.deps.length !== deps.length || deps.some((dep, index) => !Object.is(dep, ref.current.deps[index]))\n if (changed) ref.current = { deps, token: ref.current.token + 1 }\n return ref.current.token\n}\n\nconst NO_DEPS: readonly unknown[] = []\n\n/**\n * The five-state fetch machine: `idle | loading | error | empty | ready`.\n *\n * What it guarantees, and what the hand-rolled versions it replaces did not:\n *\n * - a rejected load lands on `error` with a message and a `retry`, never on an\n * empty list;\n * - `empty` is only reachable from a load that actually succeeded;\n * - a superseded load (inputs changed, retry pressed, component unmounted) is\n * aborted and its late result is dropped by a monotonic sequence guard, so it\n * cannot repaint a newer view.\n */\nexport function useAsyncResource<T>({\n load,\n deps = NO_DEPS,\n enabled = true,\n initialValue,\n isEmpty,\n errorMessage,\n}: UseAsyncResourceOptions<T>): AsyncResourceState<T> {\n const loadRef = useRef(load)\n loadRef.current = load\n const isEmptyRef = useRef(isEmpty ?? defaultIsEmpty)\n isEmptyRef.current = isEmpty ?? defaultIsEmpty\n const errorMessageRef = useRef(errorMessage)\n errorMessageRef.current = errorMessage\n\n const [resolution, setResolution] = useState<AsyncResolution<T>>(() => {\n if (initialValue !== undefined) return resolveAsyncValue(initialValue, isEmpty ?? defaultIsEmpty)\n return enabled ? { status: 'loading' } : { status: 'idle' }\n })\n const [reloadKey, setReloadKey] = useState(0)\n\n const seqRef = useRef(0)\n // Consumed by the first load attempt: a seeded resource must not throw its\n // seed away to re-fetch what the server already sent.\n const seededRef = useRef(initialValue !== undefined)\n const token = useChangeToken(deps)\n\n useEffect(() => {\n if (!enabled) return\n if (seededRef.current) {\n seededRef.current = false\n return\n }\n\n const seq = ++seqRef.current\n const controller = new AbortController()\n setResolution({ status: 'loading' })\n\n void (async () => {\n try {\n const value = await loadRef.current({ signal: controller.signal })\n if (seq !== seqRef.current || controller.signal.aborted) return\n setResolution(resolveAsyncValue(value, isEmptyRef.current))\n } catch (error) {\n if (seq !== seqRef.current || controller.signal.aborted) return\n setResolution({\n status: 'error',\n message: errorMessageRef.current ? errorMessageRef.current(error) : asyncErrorMessage(error),\n error,\n })\n }\n })()\n\n return () => controller.abort()\n }, [token, enabled, reloadKey])\n\n const retry = useCallback(() => {\n setReloadKey((key) => key + 1)\n }, [])\n\n return useMemo<AsyncResourceState<T>>(() => {\n switch (resolution.status) {\n case 'ready':\n return { status: 'ready', value: resolution.value, retry }\n case 'empty':\n return { status: 'empty', value: resolution.value, retry }\n case 'error':\n return { status: 'error', message: resolution.message, error: resolution.error, retry }\n case 'loading':\n return { status: 'loading', retry }\n case 'idle':\n return { status: 'idle', retry }\n }\n }, [resolution, retry])\n}\n","import { useCallback, useMemo, useRef, useState } from 'react'\n\nimport { asyncErrorMessage, readOkJson, requireOk } from './state'\nimport type { AsyncLoadContext } from './use-async-resource'\n\n/**\n * The brand that makes \"Saved\" unreachable without a confirmed write.\n *\n * A resolved promise is not a success: `fetch` resolves on a 404, and the\n * shipped defect this closes is a save button that rendered \"Saved\" because the\n * only thing awaited was that the request came back at all. The success variant\n * therefore carries a symbol no object literal can spell, so the only way into\n * `succeeded` is `confirmWrite` / `confirmResponse` / `confirmJson` — each of\n * which has already checked that the write landed.\n */\nexport const CONFIRMED_WRITE: unique symbol = Symbol('agent-app.confirmed-write')\n\nexport interface MutationConfirmed<T> {\n readonly succeeded: true\n readonly value: T\n readonly [CONFIRMED_WRITE]: true\n}\n\nexport interface MutationRejected {\n readonly succeeded: false\n /** Safe to render: what the user is told the write did not do. */\n readonly message: string\n readonly error?: unknown\n}\n\nexport type MutationOutcome<T> = MutationConfirmed<T> | MutationRejected\n\n/** Confirms a write whose success is already established (an SDK call that\n * throws on failure, a store returning its own typed outcome). The deliberate\n * act is the point — this call is what an audit greps for. */\nexport function confirmWrite<T>(value: T): MutationConfirmed<T> {\n return { succeeded: true, value, [CONFIRMED_WRITE]: true }\n}\n\n/** A write that did not land. Constructible by hand: failing loud is never the\n * direction that needs guarding. */\nexport function rejectWrite(message: string, error?: unknown): MutationRejected {\n return error === undefined ? { succeeded: false, message } : { succeeded: false, message, error }\n}\n\n/** Confirms only a 2xx response. A 404/500 becomes a rejection carrying the\n * status — never a success, whatever the promise did. */\nexport async function confirmResponse(response: Response): Promise<MutationOutcome<Response>> {\n try {\n return confirmWrite(await requireOk(response))\n } catch (error) {\n return rejectWrite(asyncErrorMessage(error), error)\n }\n}\n\n/** `confirmResponse` + a JSON body. A non-ok status, an unreadable body and a\n * throwing `parse` are all rejections. */\nexport async function confirmJson<T>(response: Response, parse: (data: unknown) => T): Promise<MutationOutcome<T>> {\n try {\n return confirmWrite(await readOkJson(response, parse))\n } catch (error) {\n return rejectWrite(asyncErrorMessage(error), error)\n }\n}\n\n/** True only for a value built by one of the confirm helpers. Takes `unknown`\n * because an untyped consumer can return anything from `mutate`. */\nexport function isConfirmedWrite<T>(outcome: unknown): outcome is MutationConfirmed<T> {\n if (typeof outcome !== 'object' || outcome === null) return false\n return (outcome as { readonly [CONFIRMED_WRITE]?: unknown })[CONFIRMED_WRITE] === true\n}\n\nfunction asRejection(outcome: unknown): MutationRejected | null {\n if (typeof outcome !== 'object' || outcome === null) return null\n const candidate = outcome as { succeeded?: unknown; message?: unknown; error?: unknown }\n if (candidate.succeeded !== false) return null\n const message = typeof candidate.message === 'string' && candidate.message.trim() !== ''\n ? candidate.message\n : UNCONFIRMED_MESSAGE\n return rejectWrite(message, candidate.error)\n}\n\nexport type MutationState<T> =\n | { readonly status: 'idle' }\n | { readonly status: 'pending' }\n | { readonly status: 'succeeded'; readonly value: T }\n | { readonly status: 'failed'; readonly message: string; readonly error: unknown }\n\nexport interface UseConfirmedMutationOptions<TInput, TValue> {\n /**\n * Performs the write and returns a confirmation. Anything else — including a\n * hand-written `{ succeeded: true }` — is treated as a failed write, because\n * an unbranded object is exactly the shape produced by code that never\n * checked the response.\n *\n * The context signal aborts only when a later `run` supersedes this one. It is\n * NOT aborted on unmount: a write the user asked for must not be cancelled by\n * navigating away.\n */\n mutate: (input: TInput, context: AsyncLoadContext) => Promise<MutationOutcome<TValue>>\n /** Fires after the state reaches `succeeded` (latest run only). */\n onSucceeded?: (value: TValue) => void\n /** Fires after the state reaches `failed` (latest run only). */\n onFailed?: (message: string, error: unknown) => void\n /** Maps a thrown value to the message the `failed` state renders. */\n errorMessage?: (error: unknown) => string\n}\n\nexport interface ConfirmedMutation<TInput, TValue> {\n readonly state: MutationState<TValue>\n /** Runs the write. Never rejects — the outcome is returned and mirrored into\n * `state`. Concurrent runs are last-write-wins; disable the control while\n * `state.status === 'pending'`. */\n readonly run: (input: TInput) => Promise<MutationOutcome<TValue>>\n /** Back to `idle` (dismisses a \"Saved\" or error affordance). */\n readonly reset: () => void\n}\n\nconst UNCONFIRMED_MESSAGE = 'The write could not be confirmed.'\n\nconst UNCONFIRMED_CONTRACT =\n 'mutate() resolved without a confirmation. Return confirmWrite(value), confirmResponse(response) or confirmJson(response, parse) so the success state proves the write landed.'\n\n/**\n * `idle | pending | succeeded | failed` over a write that must confirm itself.\n *\n * `succeeded` is reachable only through a branded confirmation, so the audited\n * \"Saved on a 404\" bug cannot be written with this hook: the 404 path produces\n * `failed` carrying the status, and a `mutate` that forgot to check produces\n * `failed` carrying the contract violation rather than a success it never\n * earned.\n */\nexport function useConfirmedMutation<TInput, TValue>({\n mutate,\n onSucceeded,\n onFailed,\n errorMessage,\n}: UseConfirmedMutationOptions<TInput, TValue>): ConfirmedMutation<TInput, TValue> {\n const mutateRef = useRef(mutate)\n mutateRef.current = mutate\n const onSucceededRef = useRef(onSucceeded)\n onSucceededRef.current = onSucceeded\n const onFailedRef = useRef(onFailed)\n onFailedRef.current = onFailed\n const errorMessageRef = useRef(errorMessage)\n errorMessageRef.current = errorMessage\n\n const [state, setState] = useState<MutationState<TValue>>({ status: 'idle' })\n const seqRef = useRef(0)\n const inFlightRef = useRef<AbortController | null>(null)\n\n const run = useCallback(async (input: TInput): Promise<MutationOutcome<TValue>> => {\n inFlightRef.current?.abort()\n const controller = new AbortController()\n inFlightRef.current = controller\n const seq = ++seqRef.current\n\n setState({ status: 'pending' })\n\n let outcome: MutationOutcome<TValue>\n try {\n const returned: unknown = await mutateRef.current(input, { signal: controller.signal })\n outcome = isConfirmedWrite<TValue>(returned)\n ? returned\n : asRejection(returned) ?? rejectWrite(UNCONFIRMED_MESSAGE, new Error(UNCONFIRMED_CONTRACT))\n } catch (error) {\n outcome = rejectWrite(errorMessageRef.current ? errorMessageRef.current(error) : asyncErrorMessage(error), error)\n }\n\n // A superseded run reports its own outcome to its own caller and never\n // repaints the state a newer run owns.\n if (seq !== seqRef.current) return outcome\n\n if (outcome.succeeded) {\n setState({ status: 'succeeded', value: outcome.value })\n onSucceededRef.current?.(outcome.value)\n } else {\n setState({ status: 'failed', message: outcome.message, error: outcome.error })\n onFailedRef.current?.(outcome.message, outcome.error)\n }\n return outcome\n }, [])\n\n const reset = useCallback(() => {\n seqRef.current += 1\n inFlightRef.current?.abort()\n inFlightRef.current = null\n setState({ status: 'idle' })\n }, [])\n\n return useMemo(() => ({ state, run, reset }), [state, run, reset])\n}\n","import { isValidElement, type ReactElement, type ReactNode } from 'react'\n\nimport type { AsyncResourceState } from './state'\nimport type { MutationState } from './use-confirmed-mutation'\n\nexport interface AsyncEmptyAction {\n label: string\n onClick: () => void\n}\n\nexport interface AsyncEmptySpec {\n /** What is not there, in the reader's words (\"No templates yet\"). Required:\n * an empty state with nothing to say is the state this module exists to\n * stop being mistaken for a failure. */\n title: string\n description?: string\n /** The next action. An element is rendered as supplied (a link, a dialog\n * trigger); the object form renders the standard button. */\n action?: AsyncEmptyAction | ReactElement\n}\n\nexport interface AsyncErrorRenderProps {\n message: string\n retry: () => void\n}\n\nexport interface AsyncViewProps<T> {\n state: AsyncResourceState<T>\n /** Rendered only for `ready`, with the loaded value — the branch cannot be\n * entered without one. */\n children: (value: T) => ReactNode\n /** Required: `empty` must name what is missing and what to do about it. */\n empty: AsyncEmptySpec | ReactElement\n /** Must return an element. Returning nothing is what produced the blank\n * screens this component replaces, so a nullish return falls back to the\n * built-in block rather than rendering nothing. */\n renderLoading?: () => ReactElement\n renderError?: (props: AsyncErrorRenderProps) => ReactElement\n /** `idle` renders the loading block by default — from the reader's side,\n * \"not started\" and \"in flight\" are the same wait. */\n renderIdle?: () => ReactElement\n loadingLabel?: string\n retryLabel?: string\n /** Applied to the wrapper around the non-`ready` branches. `ready` renders the\n * children with no wrapper element, so grids and lists keep their layout. */\n className?: string\n}\n\nconst BLOCK_CLASS = 'flex flex-col items-center justify-center gap-2 px-4 py-10 text-center'\n\n/**\n * Renders the branch the state is actually in.\n *\n * The three anti-patterns this replaces (`catch` that only clears a loading\n * flag, early return on a non-ok response, bare `null` while loading) all end at\n * the same rendered output as a successful-but-empty load. Here every branch is\n * reached from a different variant and each renders visibly: `loading` and\n * `idle` render a labelled busy block, `error` renders the message plus the\n * retry, `empty` renders the caller's copy and next action, and `ready` is the\n * only branch with a value to hand to `children`.\n */\nexport function AsyncView<T>({\n state,\n children,\n empty,\n renderLoading,\n renderError,\n renderIdle,\n loadingLabel = 'Loading…',\n retryLabel = 'Retry',\n className,\n}: AsyncViewProps<T>): ReactElement {\n if (state.status === 'ready') return <>{children(state.value)}</>\n\n // Every `??` here is the guarantee: a custom renderer that returns nothing\n // leaves the reader with the built-in block, never a blank region.\n const branch = (): ReactNode => {\n switch (state.status) {\n case 'idle':\n return renderIdle?.() ?? <LoadingBlock label={loadingLabel} />\n case 'loading':\n return renderLoading?.() ?? <LoadingBlock label={loadingLabel} />\n case 'error':\n return (\n renderError?.({ message: state.message, retry: state.retry }) ?? (\n <ErrorBlock message={state.message} retry={state.retry} retryLabel={retryLabel} />\n )\n )\n case 'empty':\n if (isValidElement(empty)) return empty\n return typeof empty === 'object' && empty !== null && typeof empty.title === 'string' ? (\n <EmptyBlock spec={empty} />\n ) : (\n <EmptyBlock spec={{ title: 'Nothing here yet.' }} />\n )\n }\n }\n\n // The busy signal lives on the WRAPPER, not inside the loading block, for the\n // same reason every `??` above exists: `renderLoading` is an escape hatch, and\n // a caller filling it with their own spinner would otherwise take the\n // announcement with them — a screen reader would hear nothing for exactly the\n // products that styled their wait state. The wrapper wraps every non-`ready`\n // branch, so it cannot be opted out of.\n //\n // `aria-busy` is emitted in BOTH states rather than only while loading: a\n // region that gains the attribute at the moment it goes busy, and drops it on\n // arrival, gives assistive tech no transition to report. The `error` branch\n // keeps its own `role=\"alert\"` and takes no live region here, because nesting\n // one inside another is what produces a doubled announcement.\n const busy = state.status === 'loading' || state.status === 'idle'\n const failed = state.status === 'error'\n return (\n <div\n data-async-state={state.status}\n className={className}\n role={failed ? undefined : 'status'}\n aria-live={failed ? undefined : 'polite'}\n aria-busy={busy}\n >\n {branch()}\n </div>\n )\n}\n\nfunction LoadingBlock({ label }: { label: string }): ReactElement {\n return (\n <div className={BLOCK_CLASS}>\n {/* The ring is the brand colour, not `border-border`. A divider token is\n tuned to be barely there, which is the opposite of what a busy\n indicator needs: measured on this block it painted 1.10:1 in light and\n 1.20:1 in dark against its own panel — below the 3:1 a meaningful\n graphic needs, and this spinner is the only signal that a fetch is in\n flight. `border-primary` is also what the composer's send spinner\n already uses, so this stops being the one that reads differently. */}\n <span\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent\"\n aria-hidden=\"true\"\n />\n <span className=\"text-sm text-muted-foreground\">{label}</span>\n </div>\n )\n}\n\nfunction ErrorBlock({\n message,\n retry,\n retryLabel,\n}: {\n message: string\n retry: () => void\n retryLabel: string\n}): ReactElement {\n return (\n <div role=\"alert\" className={BLOCK_CLASS}>\n <p className=\"max-w-md text-sm text-muted-foreground\">{message}</p>\n <button\n type=\"button\"\n onClick={retry}\n className=\"h-8 rounded-md border border-border px-3 text-xs font-medium text-foreground transition hover:bg-accent\"\n >\n {retryLabel}\n </button>\n </div>\n )\n}\n\nfunction EmptyBlock({ spec }: { spec: AsyncEmptySpec }): ReactElement {\n return (\n <div className={BLOCK_CLASS}>\n <p className=\"text-sm font-medium text-foreground\">{spec.title}</p>\n {spec.description ? <p className=\"max-w-md text-sm text-muted-foreground\">{spec.description}</p> : null}\n {spec.action ? (\n isValidElement(spec.action) ? (\n spec.action\n ) : (\n <button\n type=\"button\"\n onClick={(spec.action as AsyncEmptyAction).onClick}\n className=\"h-8 rounded-md border border-border px-3 text-xs font-medium text-foreground transition hover:bg-accent\"\n >\n {(spec.action as AsyncEmptyAction).label}\n </button>\n )\n ) : null}\n </div>\n )\n}\n\nexport interface MutationStatusLabels {\n pending?: string\n succeeded?: string\n}\n\nexport interface MutationStatusProps<T> {\n state: MutationState<T>\n labels?: MutationStatusLabels\n className?: string\n}\n\n/**\n * The write's own status line. \"Saved\" renders only from `succeeded`, which\n * `useConfirmedMutation` can only reach through a confirmed write, so the label\n * cannot appear over a failed request.\n */\nexport function MutationStatus<T>({ state, labels, className }: MutationStatusProps<T>): ReactElement | null {\n if (state.status === 'idle') return null\n if (state.status === 'pending') {\n return (\n <span role=\"status\" aria-live=\"polite\" aria-busy={true} className={className ?? 'text-xs text-muted-foreground'}>\n {labels?.pending ?? 'Saving…'}\n </span>\n )\n }\n if (state.status === 'succeeded') {\n return (\n <span role=\"status\" aria-live=\"polite\" aria-busy={false} className={className ?? 'text-xs text-muted-foreground'}>\n {labels?.succeeded ?? 'Saved'}\n </span>\n )\n }\n return (\n <span role=\"alert\" className={className ?? 'text-xs text-destructive'}>\n {state.message}\n </span>\n )\n}\n"],"mappings":";AAmDO,IAAM,8BAA8B;AASpC,SAAS,eAAe,OAAyB;AACtD,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAClD,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,WAAW;AAClD,MAAI,iBAAiB,OAAO,iBAAiB,IAAK,QAAO,MAAM,SAAS;AACxE,SAAO;AACT;AAEA,SAAS,WAAW,OAA8C;AAChE,SAAO,aAAa;AACtB;AAIO,SAAS,kBAAkB,OAAgB,WAAmB,6BAAqC;AACxG,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,GAAI,QAAO;AAC7D,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,WAAW,KAAK,GAAG;AACpE,UAAM,UAAU,MAAM;AACtB,QAAI,OAAO,YAAY,YA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,qBAAC,SAAI,MAAK,SAAQ,WAAW,aAC3B;AAAA,wBAAC,OAAE,WAAU,0CAA0C,mBAAQ;AAAA,IAC/D;AAAA,MAAC;AAAA;AAAA,QACC,MAAK;AAAA,QACL,SAAS;AAAA,QACT,WAAU;AAAA,QAET;AAAA;AAAA,IACH;AAAA,KACF;AAEJ;AAEA,SAAS,WAAW,EAAE,KAAK,GAA2C;AACpE,SACE,qBAAC,SAAI,WAAW,aACd;AAAA,wBAAC,OAAE,WAAU,uCAAuC,eAAK,OAAM;AAAA,IAC9D,KAAK,cAAc,oBAAC,OAAE,WAAU,0CAA0C,eAAK,aAAY,IAAO;AAAA,IAClG,KAAK,SACJ,eAAe,KAAK,MAAM,IACxB,KAAK,SAEL;AAAA,MAAC;AAAA;AAAA,QACC,MAAK;AAAA,QACL,SAAU,KAAK,OAA4B;AAAA,QAC3C,WAAU;AAAA,QAER,eAAK,OAA4B;AAAA;AAAA,IACrC,IAEA;AAAA,KACN;AAEJ;AAkBO,SAAS,eAAkB,EAAE,OAAO,QAAQ,UAAU,GAAgD;AAC3G,MAAI,MAAM,WAAW,OAAQ,QAAO;AACpC,MAAI,MAAM,WAAW,WAAW;AAC9B,WACE,oBAAC,UAAK,MAAK,UAAS,aAAU,UAAS,aAAW,MAAM,WAAW,aAAa,iCAC7E,kBAAQ,WAAW,gBACtB;AAAA,EAEJ;AACA,MAAI,MAAM,WAAW,aAAa;AAChC,WACE,oBAAC,UAAK,MAAK,UAAS,aAAU,UAAS,aAAW,OAAO,WAAW,aAAa,iCAC9E,kBAAQ,aAAa,SACxB;AAAA,EAEJ;AACA,SACE,oBAAC,UAAK,MAAK,SAAQ,WAAW,aAAa,4BACxC,gBAAM,SACT;AAEJ;","names":["useCallback","useMemo","useRef","useState","useRef","useState","useCallback","useMemo"]}
|
|
File without changes
|
|
File without changes
|