diff --git a/AGENTS.md b/AGENTS.md index 6979196..752ad50 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,12 +52,15 @@ Files: `src/agent.ts` (dispatch), `authorize.ts`, `lock.ts`, `ops.ts`, `plans.ts - Deploys, restarts and dashboard money actions are the user's. Prepare and verify; let them ship. - The retired owner dashboard frontend and its public entry are removed. `web` builds only the confirm/stop entry. Keep it independent of owner-session reads; consuming apps own their product UI. + On that page: a held payout is never shown as a completed payment and status text stays visible; review context + comes before the action in mobile document order; a required selection never clears on a repeated click; controls + keep a 44px minimum target. - `pnpm test:live` moves or touches real funds: run only when asked, never scheduled. `PLATFORM_URL= pnpm smoke` is the read-only check of a host. - An unattended run or freeze may be in progress: ask the user before editing money-path files. ## Calibrated claims -`evidence/inventory.ts` is the canonical requirement/evidence inventory. The app imports it; +`evidence/inventory.ts` is the canonical requirement/evidence inventory. `pnpm evidence:write` generates the area tables and DEMO verification section. Do not hand-edit generated sections. Record dated observations in `docs/mainnet-log.md`, reference them in the inventory, then regenerate. README and walkthroughs link to the canonical presentations. diff --git a/docs/architecture.md b/docs/architecture.md index 9cb4fa0..6bbf1ea 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -74,10 +74,7 @@ existing domain calls. Submission remains centralized in dispatch. make (`allowlist.ts`), and, for members, proposal decoding for "What am I voting on?" (`proposals.ts`, `sign-requests.ts`). App access (`app-access.ts`, `app-routes.ts`) serves `/apps/v1` to app servers; `app-confirm.ts` holds the NEP-366 owner actions apps prepare and serves the confirm page's two calls. -- **Web** (`web/src/`): one app for both areas, plus the standalone confirm page (`confirm.tsx`, its own build entry). `format.ts` `kindOf` uses the configured area, with a policy-based fallback for legacy instances; `beats.ts` holds each area's briefs, requirements and stages; `showcase.tsx` shows - them. `timeline-payment.tsx` follows one held payment step by step, each step read from its own record; it shows data - only on the instance that holds those records (approvals filed there). The autopilot run view is no longer here: its - route (`/follow/run`) redirects to the agent's app. +- **Web** (`web/src/`): the standalone confirm and stop page (`confirm.tsx`, the one build entry) and nothing else. - **Packages**: a release candidate builds one from the tested snapshot (`test/build-context.test.ts` declares it; the prototype's `dao` package retired with its hosts on 2026-11-08). `platform` (`scripts/package-platform.mjs`) is the engine for apps: the @@ -276,13 +273,10 @@ grants, agreements, payments, strategy, runs and Activity) belong to the consumi The owner dashboard (public entry, sign-in, agent launcher, setup, agent-access consent, walkthroughs, the Payables rehearsal and the evidence view) and its browser suites were removed in 0.6.0; [the prototype record](prototype.md) -describes what it did. Modules it used for session and query handling and for payment display remain under -`web/src/app`, `web/src/features` and `web/src/shared`, built into no entry and kept with their offline unit tests: -`payment-records.ts` joins retained local transfers, provider history, held observations and owner records, and a -failed or incomplete provider history read cannot hide a transfer already present in local activity -(`test/payment-records.test.ts`, `test/payment-queue.test.ts`, `test/frontend-boundaries.test.ts` with the payment -stages); `owner-observation.ts` follows a prepared owner action by its correlation ID (`test/owner-observation.test.ts`). -They are neither durable evidence nor authorization. +describes what it did. The modules it used for session and query handling and for payment display, kept at first +with their offline unit tests, are removed too: that logic and its tests belong to the consuming apps. The page's +build-time libraries are development dependencies, so the platform image, which ships the page prebuilt, installs +none of them. The invoice listener serves the page and its browser module from the same origin. The browser module owns drafts, refresh ordering and DOM updates; TypeScript checks its JSDoc types during `pnpm typecheck`. Sign-out and an explicit diff --git a/docs/enforcement.md b/docs/enforcement.md index 035da0a..c39bd75 100644 --- a/docs/enforcement.md +++ b/docs/enforcement.md @@ -64,22 +64,22 @@ and [demo at 77cce32](https://github.com/NEAR-Intents-Agent-API/demo/blob/77cce3 describe stripping `nearcom:` and lowercasing its account for Intents transfers. These are documentation/source observations, not evidence of a deployed provider version. -Our dashboard normalizes owner-entered payees before policy matching and payment review; the RPC -normalizes transfer destinations before preparation or dispatch. Signed policies and provider +The RPC normalizes transfer destinations before preparation or dispatch; normalizing owner-entered +payees before policy matching and payment review is the consuming app's. Signed policies and provider evidence are not rewritten. Equivalent recipient inputs reach the existing duplicate held-payout check. Expired and revoked grants remain visible as history; only live grants can authorize new actions. These changes are tested offline in `test/upstream-compat.test.ts`, -`test/intents-account.test.ts`, `test/form-validation.test.ts` and +`test/intents-account.test.ts` and the apps' `test/browser/upstream-compat.cjs`; they have not been verified on mainnet. **Provider display follow-up (offline-tested).** Upstream's [funds changes at demo@f888f7d](https://github.com/NEAR-Intents-Agent-API/demo/commit/f888f7d) retain price timestamps and snake-case transaction/refund fields; its [error changes at demo@7841c1e](https://github.com/NEAR-Intents-Agent-API/demo/commit/7841c1e) -allowlist budget and availability metadata. Our dashboard now preserves balances when prices are -missing, marks stale or unverified price freshness, and withholds the managed book's USD total and -allocation when a held managed asset lacks a fresh price. Unmanaged holdings remain listed separately. -Prices expire against the browser clock even if a refresh fails. +allowlist budget and availability metadata. The platform's valuation (`src/valuation.ts`) reports a price as +stale or unavailable, gives no USD value for a held asset without a fresh price, and gives no total when any +value is missing (`test/provider-values.test.ts`); how balances, freshness and the managed book's total are +shown is the consuming app's. The demo preflight also refuses an unavailable or invalid managed-book USD total instead of counting missing values as zero (`test/demo-check.test.ts`, offline fixtures). The execution holdings calculation now also requires fresh prices and finite managed valuations before @@ -106,9 +106,9 @@ exact valuation, settlement-time prices or fees, or provider accounting. No depl RPC errors and immediate payment refusals carry only validated budget-remaining and availability metadata. Availability is an observation, not permission to retry; ambiguous outcomes remain unresolved. -Supplementary refusal metadata is not persisted in the journal. Payment review shows provider-reported -transaction hashes and refund fields, marks missing evidence explicitly, and does not infer an explorer -URL, refund asset, or independent settlement proof. Refund amounts remain exact raw units. These changes +Supplementary refusal metadata is not persisted in the journal. The payment evidence the platform returns +carries only provider-reported transaction hashes and refund fields, leaves missing evidence empty, and infers +no explorer URL, refund asset, or independent settlement proof; how a review screen presents it is the consuming app's. Refund amounts remain exact raw units. These changes are covered by `test/provider-display.test.ts`, `test/provider-values.test.ts`, `test/payment-status.test.ts` and the apps' `test/browser/provider-display.cjs`; deployed behavior is unverified. @@ -444,10 +444,10 @@ not verified on the hosted deployment. The underlying provider dependencies abov Agreement terms are voter guidance, not an invoice-to-agreement binding. An owner offer is marked filed when any later invoice from that payee exists (`src/agreements.ts`); multiple offers can match -the same invoice. Payment review shows the terms of the payee's newest non-declined agreement with terms -(`termsInForce`, as the server's `termsFor`), which need not be the terms of that invoice; a payee's agreements all -read `agreed` once the policy lists the payee. The offline test (`web/src/features/payables/payment-stages.test.ts`) -covers selecting the newest terms, excluding declined agreements and other payees. It does not establish +the same invoice. The server reports the terms of the payee's newest non-declined agreement with terms +(`termsFor`), which need not be the terms of that invoice; a payee's agreements all +read `agreed` once the policy lists the payee. `test/agreements.test.ts` covers returning a payee's terms and +excluding a declined agreement; choosing the newest of several is not separately tested. It does not establish agreement-specific enforcement. Autopilot summaries distinguish swaps skipped for cost from a book with no rebalance legs meeting diff --git a/docs/market.md b/docs/market.md index 4ad0584..5513f14 100644 --- a/docs/market.md +++ b/docs/market.md @@ -244,7 +244,13 @@ Mostly the app's: the agency lists its agent on the market from its owner's mark token, receives `hire.*` webhooks (and polls `GET /v1/agents/me/assignments`), does the work and submits deliverables. The offline stack (`pnpm test:e2e:stack --app covenant --market --no-browser`) now lists `writer`, `refuser` and -`worker` at its simulated `/v1/agents` directory. `worker` exposes token-scoped assignments, start and submit routes; +`worker` at its simulated `/v1/agents` directory. `worker` exposes token-scoped assignments, start and submit routes, +and managed deliverable history, latest raw and version-specific raw reads. The history/raw shapes were checked +against the Market OpenAPI on 2026-11-14 (`test/fixtures/market-deliverable-contract.json`); account-session +admission and external deliverables are not simulated. A known owned assignment starts with an empty history; +unknown assignments remain 404 and other workers are refused. `test/market-deliverable-history.test.ts` +checks immutable version bytes, reads after a lost acknowledgement without resubmission, and late-delivery +history without payment settlement. This is offline simulator coverage, not a deployed provider observation; the stack keeps its `aat_` token and signing secret in a mode-0600 `market-worker-credentials.json`, named by path only in `state.json`. `--market-webhook-url http://127.0.0.1:/webhook` sends signed `hire.created` events to a local receiver; the simulator refuses non-loopback URLs. A 2xx webhook receipt marks start, and a repeated delivery uses the diff --git a/docs/sdk-changes.md b/docs/sdk-changes.md index f2f83e4..d108978 100644 --- a/docs/sdk-changes.md +++ b/docs/sdk-changes.md @@ -55,8 +55,17 @@ removed or narrowed, so an app server on `appClient` moves from 0.5.9 without co Platform only: - **The retired owner dashboard is no longer built.** The web build has one entry, the confirm and stop page; the - dashboard's pages and their browser suites are deleted. The owner-session routes it called - (`/gw/*`, `/a//rpc/*`) still answer for apps that hold a session. + dashboard's pages and their browser suites are deleted, and so are the session, query and payment-display modules + it used, with their unit tests: `web/src` holds the page alone, and that logic belongs to the consuming apps. The + owner-session routes it called (`/gw/*`, `/a//rpc/*`) still answer for apps that hold a session. +- **The platform image installs only what the engine runs.** The confirm page ships prebuilt, so its build-time + libraries (React, Radix, the fonts, near-connect) and the crash test's `openai` client are development dependencies + now; `@tanstack/react-query` and `@phosphor-icons/react` are dropped. A production install is ten packages. Checked by + building the image from the package and booting it offline (`pnpm check:platform-image`); not deployed. +- **`dispatch` takes its optional inputs as one named object** (`sending`, `preparedKey`, `expectedPolicy`, + `requestKey`, `payout`, `market`, and `order` for a limit order) in place of up to seven positional arguments, so an + invoice's prepared key and a request's key can't be passed in each other's place. Its types still refuse the same + combinations; every check and its order is unchanged. Offline-tested. - **Owner-signed Market funding allocation** ([market allocation](market-allocation.md)): an operator command records a wallet owner's NEP-413 permission to use a fully proven funding-only observation for one exact hire, as a `market-allocation` journal line (`journalVersion: 4`). It sends nothing; the hire still goes through dispatch, diff --git a/docs/treasury.md b/docs/treasury.md index 7ce0757..5b14930 100644 --- a/docs/treasury.md +++ b/docs/treasury.md @@ -200,3 +200,9 @@ against its ceiling; shields are excluded and refunds do not replenish the limit refuses. The journal supplies these existing records, so no counter migration is needed. This is offline-tested in `test/planning-valuation.test.ts`; it does not establish settlement-time cost or provider budget accounting. See [execution valuation](enforcement.md#how-each-claim-is-known). + +Autopilot authority refusal (0.6.0 candidate): when this executor has no live grant, a tick records +`grant_missing` before sweep or quote planning. A live grant that does not approve the strategy +still permits the existing plan-for-owner behavior; dispatch authorization remains unchanged. +Offline regression covers absent, revoked and expired grants, zero provider quote/submission calls, +unchanged balances and unchanged operations (`test/autopilot.test.ts`). Not mainnet-observed. diff --git a/package.json b/package.json index af51ab1..f07616d 100644 --- a/package.json +++ b/package.json @@ -50,30 +50,22 @@ }, "dependencies": { "@ag-ui/core": "1.0.3", - "@fastnear/near-connect": "^0.14.1", - "@fontsource-variable/geist": "^5.3.0", - "@fontsource-variable/geist-mono": "^5.3.0", - "@fontsource-variable/inter": "^5.3.0", "@near-intents-agent-api/sdk": "0.8.2", "@orpc/client": "2.0.0-beta.47", "@orpc/contract": "2.0.0-beta.47", "@orpc/server": "2.0.0-beta.47", - "@phosphor-icons/react": "^2.1.10", - "@tanstack/react-query": "5.105.0", - "class-variance-authority": "0.7.1", - "cn": "^0.5.0", "effect": "4.1.0", "near-kit": "^0.20.2", - "openai": "^7.45.1", "proper-lockfile": "^4.1.2", - "radix-ui": "1.8.1", - "react": "^19.3.1", - "react-dom": "^19.3.1", "tsx": "^4.23.15", "zod": "^4.6.7" }, "devDependencies": { "@babel/parser": "^8.0.10", + "@fastnear/near-connect": "^0.14.1", + "@fontsource-variable/geist": "^5.3.0", + "@fontsource-variable/geist-mono": "^5.3.0", + "@fontsource-variable/inter": "^5.3.0", "@playwright/test": "1.64.1", "@rsbuild/core": "^2.3.0", "@rsbuild/plugin-react": "^2.1.1", @@ -83,9 +75,15 @@ "@types/proper-lockfile": "^4.1.4", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", + "class-variance-authority": "0.7.1", + "cn": "^0.5.0", "esbuild": "0.28.2", + "openai": "^7.45.1", "playwright": "1.64.1", + "radix-ui": "1.8.1", "railway": "3.16.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", "shadcn": "4.23.0", "tailwindcss": "^4.3.3", "tw-animate-css": "^1.4.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0c98806..d7d6928 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -169,18 +169,6 @@ importers: '@ag-ui/core': specifier: 1.0.3 version: 1.0.3(zod@4.6.7) - '@fastnear/near-connect': - specifier: ^0.14.1 - version: 0.14.1 - '@fontsource-variable/geist': - specifier: ^5.3.0 - version: 5.3.0 - '@fontsource-variable/geist-mono': - specifier: ^5.3.0 - version: 5.3.0 - '@fontsource-variable/inter': - specifier: ^5.3.0 - version: 5.3.0 '@near-intents-agent-api/sdk': specifier: 0.8.2 version: 0.8.2 @@ -193,39 +181,15 @@ importers: '@orpc/server': specifier: 2.0.0-beta.47 version: 2.0.0-beta.47 - '@phosphor-icons/react': - specifier: ^2.1.10 - version: 2.1.10(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - '@tanstack/react-query': - specifier: 5.105.0 - version: 5.105.0(@types/react@19.3.0)(react@19.3.1) - class-variance-authority: - specifier: 0.7.1 - version: 0.7.1 - cn: - specifier: ^0.5.0 - version: 0.5.0 effect: specifier: 4.1.0 version: 4.1.0 near-kit: specifier: ^0.20.2 version: 0.20.2 - openai: - specifier: ^7.45.1 - version: 7.45.1(undici@7.30.1)(zod@4.6.7) proper-lockfile: specifier: ^4.1.2 version: 4.1.2 - radix-ui: - specifier: 1.8.1 - version: 1.8.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - react: - specifier: ^19.3.1 - version: 19.3.1 - react-dom: - specifier: ^19.3.1 - version: 19.3.1(react@19.3.1) tsx: specifier: ^4.23.15 version: 4.23.15 @@ -236,6 +200,18 @@ importers: '@babel/parser': specifier: ^8.0.10 version: 8.0.10 + '@fastnear/near-connect': + specifier: ^0.14.1 + version: 0.14.1 + '@fontsource-variable/geist': + specifier: ^5.3.0 + version: 5.3.0 + '@fontsource-variable/geist-mono': + specifier: ^5.3.0 + version: 5.3.0 + '@fontsource-variable/inter': + specifier: ^5.3.0 + version: 5.3.0 '@playwright/test': specifier: 1.64.1 version: 1.64.1 @@ -263,15 +239,33 @@ importers: '@types/react-dom': specifier: ^19.3.0 version: 19.3.0(@types/react@19.3.0) + class-variance-authority: + specifier: 0.7.1 + version: 0.7.1 + cn: + specifier: ^0.5.0 + version: 0.5.0 esbuild: specifier: 0.28.2 version: 0.28.2 + openai: + specifier: ^7.45.1 + version: 7.45.1(undici@7.30.1)(zod@4.6.7) playwright: specifier: 1.64.1 version: 1.64.1 + radix-ui: + specifier: 1.8.1 + version: 1.8.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) railway: specifier: 3.16.0 version: 3.16.0 + react: + specifier: ^19.3.1 + version: 19.3.1 + react-dom: + specifier: ^19.3.1 + version: 19.3.1(react@19.3.1) shadcn: specifier: 4.23.0 version: 4.23.0 @@ -824,13 +818,6 @@ packages: '@orpc/shared@2.0.0-beta.47': resolution: {integrity: sha512-m8SLQbZFgkj888haL8H8VFDNnc7PNOhx0hPCX2Uy/dAs8CBhO/Tkl9dJRoL7qPtv4lVh/2ZDd5MVHiT65Tj8fw==} - '@phosphor-icons/react@2.1.10': - resolution: {integrity: sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==} - engines: {node: '>=10'} - peerDependencies: - react: '>= 16.8' - react-dom: '>= 16.8' - '@playwright/test@1.64.1': resolution: {integrity: sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==} engines: {node: '>=20'} @@ -1790,18 +1777,6 @@ packages: engines: {node: '>=20.12.0'} hasBin: true - '@tanstack/query-core@5.105.0': - resolution: {integrity: sha512-7p56vRmT/z4UJ6sctGIdl5WRUQyUv53IUpUwEKi2g97zMbO7zh8ZsCLffGAvCPBR4xD72e3VXsDyLwXHhoNTMQ==} - - '@tanstack/react-query@5.105.0': - resolution: {integrity: sha512-y+hMuDERvgg6ay1da0V1a6ZC0ZONt7dELxSFkqRZuwm7p1TTZs0MoXrPlBRflIpRoYjvzQVYxycnLImpFLhWrw==} - peerDependencies: - '@types/react': ^18 || ^19 - react: ^18 || ^19 - peerDependenciesMeta: - '@types/react': - optional: true - '@ts-morph/common@0.27.0': resolution: {integrity: sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ==} @@ -3509,11 +3484,6 @@ snapshots: radash: 12.1.1 type-fest: 5.10.0 - '@phosphor-icons/react@2.1.10(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': - dependencies: - react: 19.3.1 - react-dom: 19.3.1(react@19.3.1) - '@playwright/test@1.64.1': dependencies: playwright: 1.64.1 @@ -4516,15 +4486,6 @@ snapshots: '@tanstack/intent@0.5.6': {} - '@tanstack/query-core@5.105.0': {} - - '@tanstack/react-query@5.105.0(@types/react@19.3.0)(react@19.3.1)': - dependencies: - '@tanstack/query-core': 5.105.0 - react: 19.3.1 - optionalDependencies: - '@types/react': 19.3.0 - '@ts-morph/common@0.27.0': dependencies: fast-glob: 3.3.3 diff --git a/src/agent.ts b/src/agent.ts index efe80fb..13d965f 100644 --- a/src/agent.ts +++ b/src/agent.ts @@ -121,6 +121,21 @@ function submitClaimed(action: Action, idempotencyKey: string, lock: MoneyLock, export type Sending = { planned: { plan: Plan; leg: PlannedAction } | null; autopilot: boolean; now: () => Date; onSubmitted?: (method: Exclude, correlationId: string) => void }; +/** + * What a dispatch carries beyond its action, each named so none is mistaken for another. + * `sending`: a strategy send's plan leg, autopilot flag and clock. + * `preparedKey`: a prepared invoice's operation, sent on its recorded identity. + * `expectedPolicy`: the policy the owner reviewed; a different one now refuses. + * `requestKey`: the operation's identity derived from a caller's request (payout-requests.ts), instead of a new one. + * `payout`: a payout request's opt-out from the duplicate-held check. + * `market`: the hire a market send is for (src/market/hire.ts). A payment's outcome is never awaited here: it is the + * chain's, recorded by reconciliation (src/recover.ts). + */ +type Dispatching = { sending?: Sending; preparedKey?: string; expectedPolicy?: ReviewedPolicy; requestKey?: string; + payout?: { allowDuplicateHeld?: boolean }; market?: MarketSend }; +/** The signed Treasury proposal a limit order is placed for. */ +type OrderDispatching = { order: { proposalId: string } }; + /** * Sends one money action under the money lock and follows it to a stable status. The request is * logged with its key, the mandate digest it runs under and its USD value before sending; the @@ -129,19 +144,15 @@ export type Sending = { planned: { plan: Plan; leg: PlannedAction } | null; auto * attempt. Anything else unanswered stays unresolved, and blocks new money actions until * status-only reconciliation proves its outcome. */ -/** - * `requestKey`: the operation's identity derived from a caller's request (payout-requests.ts), instead of a new one. - * `market`: the hire a market send is for (src/market/hire.ts). A payment's outcome is never awaited here: it is the - * chain's, recorded by reconciliation (src/recover.ts). - */ -export function dispatch(lock: MoneyLock, kind: string, action: X402Action, sending: undefined, preparedKey: undefined, expectedPolicy: ReviewedPolicy | undefined, requestKey: string | undefined, payout: undefined, market: MarketSend): Promise; -export function dispatch(lock: MoneyLock, kind: string, action: ProviderAction, sending?: Sending, preparedKey?: string, expectedPolicy?: ReviewedPolicy, requestKey?: string, payout?: { allowDuplicateHeld?: boolean }, market?: MarketSend): Promise; -export function dispatch(lock: MoneyLock, kind: "limit-order", action: LimitOrderAction, sending: undefined, preparedKey: undefined, - expectedPolicy: ReviewedPolicy | undefined, requestKey: undefined, payout: undefined, market: undefined, - order: { proposalId: string }): Promise; +export function dispatch(lock: MoneyLock, kind: string, action: X402Action, options: Pick & { market: MarketSend }): Promise; +export function dispatch(lock: MoneyLock, kind: string, action: ProviderAction, options?: Dispatching): Promise; +export function dispatch(lock: MoneyLock, kind: "limit-order", action: LimitOrderAction, options: Pick & OrderDispatching): Promise; export function dispatch(lock: MoneyLock, kind: "limit-order-cancel", action: CancelOrderAction): Promise; -export async function dispatch(lock: MoneyLock, kind: string, action: Action | CancelOrderAction, sending?: Sending, preparedKey?: string, expectedPolicy?: ReviewedPolicy, - requestKey?: string, payout?: { allowDuplicateHeld?: boolean }, market?: MarketSend, order?: { proposalId: string }): Promise { +export async function dispatch(lock: MoneyLock, kind: string, action: Action | CancelOrderAction, + options: Dispatching & Partial = {}): Promise { + // Read once, before anything is awaited: a caller cannot alter what is sent by changing its options meanwhile. + const { sending, preparedKey, requestKey, payout, order } = options; + let { expectedPolicy, market } = options; assertCanSendAfterRelease(); action = structuredClone(action); expectedPolicy = expectedPolicy && { ...expectedPolicy }; @@ -566,7 +577,7 @@ export async function pay(request: { asset: string; amount: string; recipient: s request = structuredClone(request); expectedPolicy = expectedPolicy && { ...expectedPolicy }; try { - const settled = await withMoneyLock((lock) => dispatch(lock, "payout", { method: "transfer", request }, undefined, undefined, expectedPolicy)); + const settled = await withMoneyLock((lock) => dispatch(lock, "payout", { method: "transfer", request }, { expectedPolicy })); return { outcome: "settled" as const, status: settled.status, diff --git a/src/autopilot.ts b/src/autopilot.ts index 1409c3c..d3ac4c5 100644 --- a/src/autopilot.ts +++ b/src/autopilot.ts @@ -49,13 +49,12 @@ export function status() { } /** - * Whether this server's live grant is the owner's approval of the strategy in force. `authorize` refuses - * every autopilot send without it; checked first so that such a tick waits for the owner instead of - * recording refusals. + * Read live authority separately from strategy approval: an absent grant cannot quote; a live + * grant for another strategy can still plan for owner review. Dispatch rechecks every send. */ async function mandateApproved(strategy: Strategy) { const grant = liveGrant(await api.listGrants(agentId()), process.env.AGENT_GRANT_TOKEN); - return grant !== undefined && grantApproves(grant.label, strategy); + return { grant, approved: grant !== undefined && grantApproves(grant.label, strategy) }; } let running = false; @@ -140,8 +139,12 @@ async function run(found: Found, progress: (event: ProgressEvent) => void): Prom } // Every send, a sweep's shield included, needs the owner's grant for the strategy in force. - const approved = await mandateApproved(strategy); + const { grant, approved } = await mandateApproved(strategy); if (strategyChanged()) return changed(); + if (!grant) { + found.refusal = "grant_missing"; + return done("Refused: no live grant is held for this agent; the owner's grant doesn't approve this strategy. Issue a new grant from Policy."); + } if (!approved) report.push("sweep left for the owner: the owner's grant doesn't approve this strategy"); else { progress({ type: "STEP_STARTED", stepName: "sweep" }); diff --git a/src/invoices.ts b/src/invoices.ts index d811ffc..86475bc 100644 --- a/src/invoices.ts +++ b/src/invoices.ts @@ -112,7 +112,7 @@ export const file = (invoice: InvoiceInput, authenticatedPayee: string, expected } await dispatch(lock, "invoices", { method: "transfer", request: { asset: ASSETS.USDC, amount: known.amount, recipient: known.payee, confidential: true, - } }, undefined, known.operation.idempotencyKey, expectedPolicy); + } }, { preparedKey: known.operation.idempotencyKey, expectedPolicy }); return { id, status: paymentStatus(getInvoice(id)!) }; } catch (error) { if (error instanceof MoneyLockBusy || error instanceof UnresolvedOperations) return { id, status: "busy" }; diff --git a/src/limit-orders/service.ts b/src/limit-orders/service.ts index 01249e1..8eff886 100644 --- a/src/limit-orders/service.ts +++ b/src/limit-orders/service.ts @@ -248,9 +248,8 @@ export async function placeLimitOrder(context: CallContext, input: unknown) { throw refused("signature_invalid", "The stored owner approval does not match this order."); try { await withMoneyLock(async lock => { - await dispatch(lock, "limit-order", { method: "limit_order", request: loaded.record.order }, undefined, undefined, - undefined, undefined, undefined, undefined, - { proposalId: id }); + await dispatch(lock, "limit-order", { method: "limit_order", request: loaded.record.order }, + { order: { proposalId: id } }); if (readOrderPlacement(id)) try { await refreshTrackedOrder(id); } catch { /* The funded order remains tracked for status-only recovery. */ } }); } catch (error) { diff --git a/src/market/hire.ts b/src/market/hire.ts index 76f348f..2af40e0 100644 --- a/src/market/hire.ts +++ b/src/market/hire.ts @@ -121,8 +121,8 @@ const topUp = async (lock: MoneyLock, market: MarketSend, stage: MarketStage, ac context?: FundingContext) => { if (context) await assertFundingContext(context); return dispatch(lock, "market-topup", { method: "withdraw", request: { asset, amount, chain: "near", recipient: account, confidential: true } }, - undefined, undefined, context?.reviewedPolicy, marketStageKey(market.bindingKey, stage), undefined, - { ...market, stage, ...(context && { reviewedGrant: context.reviewedGrant }) }); + { expectedPolicy: context?.reviewedPolicy, requestKey: marketStageKey(market.bindingKey, stage), + market: { ...market, stage, ...(context && { reviewedGrant: context.reviewedGrant }) } }); }; /** A provider SUCCESS is not a chain receipt. A stage stays reserved until its exact credit is final. */ @@ -304,7 +304,7 @@ async function executeHire(actor: string | undefined, input: HireInput, approval asset: usdc, amount: quote.row!.amount, payer: signer.account, publicKey: signer.publicKey, nonce: (view.keyNonce! + 1n).toString(), maxBlockHeight: paymentExpiry(view.height, quote.terms).toString(), balanceAtSigning: view.balance.toString() }; - return dispatch(lock, "market-hire", { method: "x402", request }, undefined, undefined, undefined, key, undefined, market); + return dispatch(lock, "market-hire", { method: "x402", request }, { requestKey: key, market }); }); } catch (error) { // A binding can outlive its approval or a provider read; its stage operation is never replaced under a new key. diff --git a/src/payout-requests.ts b/src/payout-requests.ts index 1c1d9af..436a891 100644 --- a/src/payout-requests.ts +++ b/src/payout-requests.ts @@ -64,8 +64,8 @@ export async function requestPayout(actor: string | undefined, input: { requestI if (recorded()) return answer(input.requestId, recorded()); try { // A request recorded meanwhile can't be recorded again: the journal refuses a second preparation of one key. - await withMoneyLock((lock) => dispatch(lock, "payout", terms, undefined, undefined, input.expectedPolicy, key, - { allowDuplicateHeld: input.allowDuplicateHeld === true })); + await withMoneyLock((lock) => dispatch(lock, "payout", terms, { expectedPolicy: input.expectedPolicy, requestKey: key, + payout: { allowDuplicateHeld: input.allowDuplicateHeld === true } })); } catch (error) { // Recorded: the journal holds the outcome (a refusal, or none proven). Not recorded: nothing reached the send site, // and a refusal made before recording keeps its code, so the same requestId can be asked again. diff --git a/src/planning/execution.ts b/src/planning/execution.ts index cb565cd..9da9036 100644 --- a/src/planning/execution.ts +++ b/src/planning/execution.ts @@ -86,7 +86,7 @@ export async function* executePlan(id: string, now = () => new Date(), { autopil if (problems.length) { yield { type: "rejected", problems }; return; } if (action.type === "shield") { const request = { asset: action.asset, amount: action.amount }; - const settled = await dispatch(lock, plan.source, { method: "shield", request }, sending(action)); + const settled = await dispatch(lock, plan.source, { method: "shield", request }, { sending: sending(action) }); yield { type: "action", index, action, status: settled.status, correlationId: settled.correlation_id, failureCode: settled.failure_code }; if (settled.status !== "SUCCESS") return; continue; diff --git a/src/treasury.ts b/src/treasury.ts index 15fa72f..15dc13c 100644 --- a/src/treasury.ts +++ b/src/treasury.ts @@ -144,11 +144,11 @@ export async function executeLeg(lock: MoneyLock, leg: Leg, minAmountOut: string let shielded: StatusResponse | undefined; if (shortfall > 0n) { const request = { asset: leg.from.asset, amount: shortfall.toString() }; - shielded = await dispatch(lock, "shield", { method: "shield", request }, sending); + shielded = await dispatch(lock, "shield", { method: "shield", request }, { sending }); if (shielded.status !== "SUCCESS") return { shortfall, shielded }; } const request = { ...swapRequest(leg), min_amount_out: minAmountOut }; - try { return { shortfall, shielded, swapped: await dispatch(lock, kind, { method: "swap", request }, sending) }; } + try { return { shortfall, shielded, swapped: await dispatch(lock, kind, { method: "swap", request }, { sending }) }; } catch (error) { const code = shielded ? sendRefusal(error) : undefined; if (code === undefined) throw error; @@ -181,7 +181,7 @@ async function* sweepRun(lock: MoneyLock | undefined, sending: Sending | undefin if (!lock) return; for (const h of exposed) { - const settled = await dispatch(lock, "sweep", { method: "shield", request: { asset: h.asset, amount: h.public.toString() } }, sending); + const settled = await dispatch(lock, "sweep", { method: "shield", request: { asset: h.asset, amount: h.public.toString() } }, { sending }); yield { type: "shield", asset: h.asset, diff --git a/test/autopilot.test.ts b/test/autopilot.test.ts index e3ee48f..ce4b10a 100644 --- a/test/autopilot.test.ts +++ b/test/autopilot.test.ts @@ -522,3 +522,24 @@ test("a held invoice whose status read answers for another operation stops the t assert.deepEqual(sends, []); assert.ok(readOps().some(op => op.idempotencyKey === held.operation.idempotencyKey && blocksDispatch(op))); }); + +for (const state of ["missing", "revoked", "expired"] as const) test(`${state} authority records a refusal before quotes or submissions`, async () => { + limit(100); + book[ASSETS.USDC]!.public = 10n; + const before = structuredClone(book); + const operations = readOps(); + const grant = fixtureGrant(grantLabel()); + mock.method(api, "listGrants", async () => state === "missing" ? [] : [{ ...grant, + ...(state === "revoked" ? { revoked_at: new Date().toISOString() } : { expires_at: new Date(0).toISOString() }) }]); + let calls = 0; + mock.method(api, "forGrant", () => { calls++; throw new Error("No authority: must not quote or submit"); }); + const report = await tick("schedule"); + assert.match(report, /Refused: no live grant/); + assert.equal(calls, 0); + assert.deepEqual(sends, []); + assert.deepEqual(book, before); + assert.deepEqual(readOps(), operations); + const end = ticks().ticks[0]!.end!; + assert.equal(end.refusal, "grant_missing"); + assert.deepEqual([end.plan, end.steps, end.shields], [null, [], []]); +}); diff --git a/test/browser/fixtures/navigation.cjs b/test/browser/fixtures/navigation.cjs deleted file mode 100644 index adaaef7..0000000 --- a/test/browser/fixtures/navigation.cjs +++ /dev/null @@ -1,9 +0,0 @@ -/** Open the responsive navigation explicitly; never alter app state from the fixture. */ -async function openWorkspaceNavigation(page) { - const menu = page.getByRole('button', { name: 'Menu', exact: true }); - if (await menu.isVisible() && !await page.getByRole('dialog', { name: 'Workspace navigation' }).isVisible()) { - await menu.click(); - await page.getByRole('dialog', { name: 'Workspace navigation' }).waitFor(); - } -} -module.exports = { openWorkspaceNavigation }; diff --git a/test/browser/fixtures/owner-status.cjs b/test/browser/fixtures/owner-status.cjs deleted file mode 100644 index 316f4af..0000000 --- a/test/browser/fixtures/owner-status.cjs +++ /dev/null @@ -1,42 +0,0 @@ -const path = require('node:path'); -const { rpcValue } = require('./rpc.cjs'); - -/** Explicit read-only payment and schedule evidence for owner-facing status checks. */ -async function openOwnerStatus(browser, root, scenario, width) { - const page = await browser.newPage({viewport:{width,height:900}}); - page.setDefaultTimeout(5000); - const treasury = scenario.startsWith('schedule-'); - const name = treasury ? 'treasury' : 'payables'; - const dao = scenario === 'dao'; - const at = new Date().toISOString(); - const expiresAt = '2030-01-01T00:00:00Z'; - const request = {asset:'usdc',amount:'123456789',recipient:'payee.near',confidential:true}; - const errors = [], writes = []; - page.on('pageerror', e => errors.push(e.message)); - await page.route('**/*', async route => { - const url = new URL(route.request().url()), p = url.pathname; - if (url.hostname !== 'frontend.test') return route.abort(); - if (p === '/gw/me') return route.fulfill({json:{agents:[{name,owner:dao?'owner.sputnik-dao.near':'owner.near',dao}],invoices:null,viewer:{account:'owner.near',access:{[name]:{canSign:!dao,canPropose:true,canVote:true,canExecute:true,canManage:true}}}}}); - if (p === '/gw/proposals') return route.fulfill({json:[{id:42,hash:'fixture-hash',status:'Approved',votes:{'owner.near':'Approve'},submittedAt:at}]}); - if (p.includes('/rpc/')) { - const method = p.split('/rpc/')[1]; - const values = { - get instance() { return { agentId: this.setup?.agentId ?? null, executor: this.setup?.executor !== false }; }, setup:{executor:false,agentId:'fixture',wallet:'agent.near',owner:{type:'near',account_id:dao?'owner.sputnik-dao.near':'owner.near'},grant:{label:treasury?'treasury':'payout',expiresAt},dao:null}, - overview:{agentId:'fixture',digest:'fixture',notInForce:null,agreed:[],unmanaged:[],target:{usdc:1},rebalance:{minLegUsd:1,maxCostBps:100},book:[{asset:'usdc',symbol:'USDC',decimals:6,public:'0',confidential:'10000000',usd:10,price:1}],policy:{policy:{actions:treasury?['swap','transfer']:['transfer'],frozen:false,destinations:{mode:'only',list:[]},assets:'any',budget:{},limits:{}},usage:{budget:{}},cooldowns:{}}}, - 'treasury/get':null,held:[],unresolved:treasury?[{key:'unresolved-fixture',at,kind:'swap',sent:true,status:'PROCESSING'}]:[],activity:[],invoices:[],'inbox/list':[],'workOrders/list': [], 'agreements/list':[], - 'owner/pending':dao?[{correlationId:'owner-record',hash:'fixture-hash',state:'done',expiresAt,payment:{correlationId:'payment',verdict:'approve'}}]:[], - 'owner/status':{stage:'submitted',status:'SUCCESS'}, - 'owner/actions':['approved','rejected'].includes(scenario)?[{correlationId:'owner-record',type:'approval_vote',signer:'wallet',stage:'settled',expiresAt,ownerSucceeded:true,status:scenario==='rejected'?'FAILED':'SUCCESS',payment:{correlationId:'payment',verdict:scenario==='rejected'?'reject':'approve'}}]:[], - paymentHistory:{items:[{correlationId:'payment',at}],complete:true}, - paymentStatus:{status:scenario==='rejected'?'FAILED':'SUCCESS',failureCode:null,createdAt:at,updatedAt:at,request,approvalId:scenario==='unknown'?null:'approval',expiresAt,detailError:null}, - 'autopilot/get':{on:scenario==='schedule-on',everyMin:60,maxUsd:10},'autopilot/evidence':{ticks:[]}, - }; - if (!(method in values)) { writes.push(method); return route.abort(); } - return route.fulfill({json:{json:rpcValue(values, method)}}); - } - if (p.startsWith('/static/')) return route.fulfill({path:root+p,contentType:p.endsWith('.js')?'application/javascript':p.endsWith('.css')?'text/css':'font/woff2'}); - return route.fulfill({path:path.join(root,'index.html'),contentType:'text/html'}); - }); - return { page, errors, writes, treasury, dao, name }; -} -module.exports = { openOwnerStatus }; diff --git a/test/browser/fixtures/workspace.cjs b/test/browser/fixtures/workspace.cjs deleted file mode 100644 index 3989015..0000000 --- a/test/browser/fixtures/workspace.cjs +++ /dev/null @@ -1,87 +0,0 @@ -const assert = require('node:assert/strict'); -const { join } = require('node:path'); -const { rpcValue } = require('./rpc.cjs'); -const { makeTick, recordingFor } = require('./run.cjs'); - -/** Fresh presentation evidence; each suite still declares its own allowed RPCs and overrides. */ -function workspaceEvidence({ policyDetails = false, grants = false } = {}) { - const budget = Object.fromEntries(['daily', 'weekly', 'monthly'].map(period => [period, - { limit_usd: '100', remaining_usd: '90', spent_usd: '10' }, - ])); - const setup = { agentId: 'fixture', wallet: 'agent.near', owner: { type: 'near', account_id: 'owner.near' }, - grant: { label: 'treasury', expiresAt: '2030-01-01T00:00:00Z' }, dao: null }; - const overview = kind => ({ agentId: 'fixture', digest: 'fixture', notInForce: null, agreed: [], unmanaged: [], ...(grants && { grants: [] }), - rebalance: { minLegUsd: 1, maxCostBps: 100 }, target: { usdc: 1 }, - book: [{ asset: 'usdc', symbol: 'USDC', decimals: 6, public: '0', confidential: '10000000', usd: 10, price: 1 }], - policy: { policy: { actions: kind === 'treasury' ? ['swap', 'transfer'] : ['transfer'], frozen: false, - destinations: { mode: 'only', list: [] }, assets: 'any', ...(policyDetails && { budget: {}, limits: {} }) }, - ...(policyDetails && { revision: 1 }), usage: { budget }, cooldowns: {} }, - }); - return { budget, setup, overview }; -} - -/** Shared transport only: no default RPC response, write handler, or missing-evidence repair. */ -function workspaceOpener(root, { budget, values, proposals = false }) { - return async function open(context, routePath, options = {}) { - const page = await context.newPage(); - page.setDefaultTimeout(15_000); - if (options.clock) await page.clock.install(); - const calls = [], requests = [], errors = []; - const state = { error: options.error, delay: options.delay, - agents: options.onlyPayables ? ['payables'] : ['treasury', 'payables'], deniedAgent: null }; - const run = makeTick(options.outcome || 'quiet', budget); - if (options.oldRun) { - run.at = '2020-01-01T00:00:00Z'; - run.end.endedAt = run.at; - run.end.before.at = run.at; - run.end.after.at = run.at; - } - let gatewayReads = 0; - page.on('pageerror', error => errors.push(error.message)); - await page.route('**/*', async route => { - const { hostname, pathname } = new URL(route.request().url()); - // `external` lets a suite land on another host (an agent's app) and read the full URL it reached. - if (hostname !== 'frontend.test') return options.external ? route.fulfill({ contentType: 'text/html', body: 'App' }) : route.abort(); - if (pathname === '/gw/me') { - if (++gatewayReads > 1 && options.invoiceLinkError) return route.fulfill({ status: 503, json: { error: 'Invoice link unavailable' } }); - return route.fulfill({ json: { - agents: state.agents.map(name => ({ name, owner: 'owner.near', dao: Boolean(options.dao) })), ...(options.apps && { apps: options.apps }), - invoices: options.noInvoiceLink ? null : 'https://invoices.example', viewer: options.public ? null : { account: 'owner.near', - access: Object.fromEntries(state.agents.map(name => [name, { canSign: !options.dao && !(options.member && name === 'payables'), canPropose: !(options.member && name === 'payables'), canVote: !(options.member && name === 'payables'), canExecute: !(options.member && name === 'payables'), canManage: !(options.member && name === 'payables') }])) }, - } }); - } - if (proposals && pathname === '/gw/proposals') return route.fulfill({ json: options.proposals || [] }); - if (pathname.includes('/rpc/')) { - const method = pathname.split('/rpc/')[1]; - calls.push(method); requests.push(pathname); - if (state.deniedAgent && pathname.startsWith(`/a/${state.deniedAgent}/rpc/`)) { - return route.fulfill({ status: 403, json: { error: 'Fixture agent access removed', access: 'agent' } }); - } - if (method === state.delay && (!options.onlyTreasury || pathname.includes('/treasury/'))) await new Promise(resolve => setTimeout(resolve, 2500)); - if (page.isClosed()) return; - if (method === state.error && (!options.onlyTreasury || pathname.includes('/treasury/'))) { - return route.fulfill({ status: 500, json: { json: { defined: false, code: 'INTERNAL_SERVER_ERROR', message: 'Fixture read unavailable' } } }); - } - if (method === 'autopilot/log') { - assert.equal(route.request().postDataJSON().json.tickId, run.id, 'recording read must select the displayed run'); - assert.ok(!options.approveOnly, 'approve-only views must not read recordings'); - return route.fulfill({ json: { json: recordingFor(run) } }); - } - const kind = pathname.includes('/payables/') ? 'payables' : 'treasury'; - const declared = values(kind, options, state, run); - if (options.oldRun && method === 'autopilot/evidence') { - const input = route.request().postData() || new URL(route.request().url()).search; - declared[method] = { ticks: input.includes('since') ? [] : [run], corrupt: [] }; - } - return route.fulfill({ json: { json: rpcValue(declared, method) } }); - } - if (pathname.startsWith('/static/')) return route.fulfill({ path: join(root, pathname), - contentType: pathname.endsWith('.js') ? 'application/javascript' : pathname.endsWith('.css') ? 'text/css' : 'font/woff2' }); - if (pathname.startsWith('/gw/')) throw new Error('Unexpected gateway request: ' + pathname); - return route.fulfill({ path: join(root, 'index.html'), contentType: 'text/html' }); - }); - await page.goto('http://frontend.test' + routePath); - return { page, calls, requests, errors, state }; - }; -} -module.exports = { workspaceEvidence, workspaceOpener }; diff --git a/test/e2e/market-worker.spec.mjs b/test/e2e/market-worker.spec.mjs index a79c474..5e384fb 100644 --- a/test/e2e/market-worker.spec.mjs +++ b/test/e2e/market-worker.spec.mjs @@ -92,12 +92,20 @@ test('a listed worker receives an instant hire and payment settles only on deliv await expect.poll(async () => (await (await api(worker.token, '/v1/agents/me/assignments?status=all')).json()) .assignments[0].assignment.startedAt).not.toBeNull(); // 2xx webhook is the worker's start. const submitPath = `/v1/assignments/${assignmentId}/submit`; + const historyPath = `/v1/assignments/${assignmentId}/deliverable/versions`; + expect((await api(poller.token, historyPath)).status).toBe(403); + expect(await (await api(worker.token, historyPath)).json()).toEqual({ versions: [] }); const body = JSON.stringify({ deliverableMarkdown: '# The article\nDelivered by the worker.' }); expect((await api(poller.token, submitPath, { method: 'POST', body })).status).toBe(403); expect((await api(worker.token, submitPath, { method: 'POST', body: JSON.stringify({ deliverableMarkdown: '' }) })).status).toBe(400); expect(stack.market.chain.accounts.get(account.account).transfers).toHaveLength(0); const submitted = await (await api(worker.token, submitPath, { method: 'POST', body })).json(); expect(submitted.status).toBe('submitted'); + const history = await (await api(worker.token, historyPath)).json(); + expect(history.versions).toHaveLength(1); + expect(history.versions[0]).toMatchObject({ version: 1, files: [], senderAgentId: worker.agentId, + deliverableHash: submitted.deliverableHash, submittedAt: submitted.submittedAt }); + expect(await (await api(worker.token, history.versions[0].deliverableUrl)).text()).toBe('# The article\nDelivered by the worker.'); expect((await (await api(worker.token, '/v1/agents/me/assignments?status=all')).json()).assignments[0].assignment.status).toBe('accepted'); await expect.poll(async () => value(await buyer.call('market/status', { requestId: 'worker-hire' })).state, { timeout: 30_000 }).toBe('paid'); expect(value(await buyer.call('market/status', { requestId: 'worker-hire' })).deliverable).toBe('# The article\nDelivered by the worker.'); diff --git a/test/e2e/market.mjs b/test/e2e/market.mjs index 48a59b4..1f80d96 100644 --- a/test/e2e/market.mjs +++ b/test/e2e/market.mjs @@ -238,6 +238,23 @@ export async function market({ agents = {}, payee = {}, height = 1_000_000n, web const mine = [...assignments.values()].filter(item => item.handle === handle && (status === 'all' || item.assignment.status === status)); return json(res, 200, { assignments: mine.slice(offset, offset + limit).map(({ assignment, job }) => ({ assignment, job, latestMessage: null })) }); } + // Market OpenAPI 2.0.0, verified 2026-11-14: worker aat_ admission also covers managed + // history and raw reads. This fixture models worker tokens only, not account-session access. + const deliverableRoute = /^\/v1\/assignments\/([^/]+)\/deliverable\/(versions|raw|versions\/([1-9][0-9]*)\/raw)$/.exec(url.pathname); + if (req.method === 'GET' && deliverableRoute) { + const handle = workerAuth(req, res); + if (!handle) return; + const item = assignments.get(deliverableRoute[1]); + if (!item) return json(res, 404, { error: 'assignment_not_found' }); + if (item.handle !== handle) return json(res, 403, { error: 'agent_token_scope_forbidden' }); + const versions = item.versions ?? []; + if (deliverableRoute[2] === 'versions') return json(res, 200, { versions: versions.map(({ view }) => view) }); + const version = deliverableRoute[2] === 'raw' ? versions.at(-1) + : versions.find(({ view }) => String(view.version) === deliverableRoute[3]); + if (!version) return json(res, 404, { error: 'deliverable_not_found' }); + res.writeHead(200, { 'content-type': 'text/markdown; charset=utf-8' }); + return res.end(version.markdown); + } const assignmentRoute = /^\/v1\/assignments\/([^/]+)\/(start|submit)$/.exec(url.pathname); if (req.method === 'POST' && assignmentRoute) { const handle = workerAuth(req, res); @@ -257,8 +274,16 @@ export async function market({ agents = {}, payee = {}, height = 1_000_000n, web return json(res, 400, { error: 'invalid_deliverable' }); if (item.assignment.status !== 'in_progress') return json(res, 409, { error: 'assignment_not_in_progress' }); const now = new Date().toISOString(); + const versions = item.versions ??= []; + const version = versions.length + 1; + const deliverableHash = createHash('sha256').update(markdown).digest('hex'); + const deliverableUrl = `/v1/assignments/${assignmentRoute[1]}/deliverable/versions/${version}/raw`; + // Capture a new immutable snapshot before settlement. Later assignment changes cannot + // rewrite prior bytes; reading after a lost acknowledgement never submits or relays again. + versions.push({ markdown, view: Object.freeze({ version, files: [], submittedAt: now, + deliverableHash, deliverableUrl, senderAgentId: listings.get(handle).agentId }) }); Object.assign(item.assignment, { status: 'submitted', submittedAt: now, updatedAt: now, - deliverableHash: createHash('sha256').update(markdown).digest('hex') }); + deliverableHash, deliverableUrl }); // The response shows the submission. X402 accepts immediately on delivery, but only after the delegate // actually transfers; an expired or unusable delegate must never make the simulated buyer look paid. const submitted = { ...item.assignment }; diff --git a/test/evidence-docs.test.ts b/test/evidence-docs.test.ts index d3a8426..3ca2e9c 100644 --- a/test/evidence-docs.test.ts +++ b/test/evidence-docs.test.ts @@ -1,15 +1,8 @@ import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; import { test } from "node:test"; import { documentationUpdates, replaceGenerated, requirementsMarkdown } from "../scripts/evidence-docs.js"; import { PROTOTYPES, PROVEN, VERIFICATIONS, knownLabel, summarizeRequirements, type Requirement } from "../evidence/inventory.js"; -test("the app uses the canonical evidence inventory instead of a handwritten copy", () => { - const source = readFileSync(new URL("../web/src/features/evidence/beats.ts", import.meta.url), "utf8"); - assert.ok(source.includes('export * from "../../../../evidence/inventory.js"')); - assert.doesNotMatch(source, /export const PROTOTYPES/); -}); - test("coverage separates observation scope and never promotes missing scope or offline tests", () => { const requirement = (known: Requirement["known"], where?: Requirement["where"]): Requirement => ({ type: "guarantee", text: "Example", evidence: "Fixture", stoppedBy: "policy", known, where, diff --git a/test/fixtures/invoice-terminal-replay.ts b/test/fixtures/invoice-terminal-replay.ts index 4476a60..0a58a26 100644 --- a/test/fixtures/invoice-terminal-replay.ts +++ b/test/fixtures/invoice-terminal-replay.ts @@ -56,8 +56,8 @@ async function rejectReplay() { assert.throws(() => claimInvoiceSubmission(operation.idempotencyKey, operation.request), /replay is blocked/); const lock = await acquireMoneyLock(); try { - await assert.rejects(dispatch(lock, "invoices", { method: "transfer", request }, undefined, - operation.idempotencyKey), /not prepared; replay is blocked/); + await assert.rejects(dispatch(lock, "invoices", { method: "transfer", request }, + { preparedKey: operation.idempotencyKey }), /not prepared; replay is blocked/); } finally { await lock.release(); } } diff --git a/test/fixtures/market-deliverable-contract.json b/test/fixtures/market-deliverable-contract.json new file mode 100644 index 0000000..179e085 --- /dev/null +++ b/test/fixtures/market-deliverable-contract.json @@ -0,0 +1,200 @@ +{ + "source": "https://market.near.ai/openapi.json", + "captured": "2026-11-14", + "documentSha256": "d514bad243a4dc299d85c538638529ee203a496d13abcb9a9aa82cb56db3ecbf", + "paths": { + "/v1/assignments/{id}/deliverable/raw": { + "get": { + "tags": [ + "jobs" + ], + "summary": "GET /v1/assignments/{id}/deliverable/raw \u2014 streams a **managed** deliverable from the\nprivate bucket to the job creator, the worker's owner, or the worker agent's own `aat_` token.", + "description": "A bid or a co-worker's own assignment does not admit \u2014 the line the roster\n(`GET /v1/jobs/{id}/assignments`) draws too, so every `/raw` URL it lists\nopens for its reader. External deliverables have no `/raw`.", + "operationId": "deliverable_raw", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Assignment id", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The latest managed deliverable", + "content": { + "text/markdown": {} + } + }, + "401": { + "description": "Not authenticated (account session or aat_ bearer)" + }, + "403": { + "description": "Caller is not a party to this assignment, nor its worker agent" + }, + "404": { + "description": "Unknown assignment, or an external deliverable" + } + } + } + }, + "/v1/assignments/{id}/deliverable/versions": { + "get": { + "tags": [ + "jobs" + ], + "summary": "GET /v1/assignments/{id}/deliverable/versions \u2014 every submitted version of\nthe deliverable; same admission as `/deliverable/raw`, the worker's `aat_` token included.", + "operationId": "list_deliverable_versions", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Assignment id", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Every submitted version, oldest first", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeliverableVersionsResponse" + } + } + } + }, + "401": { + "description": "Not authenticated (account session or aat_ bearer)" + }, + "403": { + "description": "Caller is not a party to this assignment, nor its worker agent" + }, + "404": { + "description": "Unknown assignment" + } + } + } + }, + "/v1/assignments/{id}/deliverable/versions/{version}/raw": { + "get": { + "tags": [ + "jobs" + ], + "summary": "GET /v1/assignments/{id}/deliverable/versions/{version}/raw \u2014 streams one\nmanaged version from the private bucket; same admission as `/deliverable/raw`,\nthe worker's `aat_` token included. An external version has no `/raw`.", + "operationId": "deliverable_version_raw", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Assignment id", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "version", + "in": "path", + "description": "Version number, from 1", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "That managed version", + "content": { + "text/markdown": {} + } + }, + "401": { + "description": "Not authenticated (account session or aat_ bearer)" + }, + "403": { + "description": "Caller is not a party to this assignment, nor its worker agent" + }, + "404": { + "description": "Unknown assignment or version, or an external version" + } + } + } + } + }, + "schemas": { + "DeliverableVersionView": { + "type": "object", + "description": "One entry of `GET /v1/assignments/{id}/deliverable/versions`.", + "required": [ + "version", + "files", + "submittedAt" + ], + "properties": { + "deliverableHash": { + "type": [ + "string", + "null" + ] + }, + "deliverableUrl": { + "type": [ + "string", + "null" + ], + "description": "[`result_href`]: the `/deliverable/versions/{n}/raw` path for a managed\nversion, the worker's own URL otherwise; `null` for an A2A result." + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AttachmentBrief" + }, + "description": "The files this version delivers; `downloadUrl` is the id-scoped `/v1/files/{id}/raw`." + }, + "senderAgentId": { + "type": [ + "string", + "null" + ], + "format": "uuid", + "description": "`Some` when the agent itself submitted this version." + }, + "submittedAt": { + "type": "string", + "format": "date-time" + }, + "version": { + "type": "integer", + "format": "int32" + } + } + }, + "DeliverableVersionsResponse": { + "type": "object", + "required": [ + "versions" + ], + "properties": { + "versions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DeliverableVersionView" + }, + "description": "Oldest first; the last entry is what the assignment's `deliverableUrl` points at." + } + } + } + } +} diff --git a/test/form-validation.test.ts b/test/form-validation.test.ts deleted file mode 100644 index d5337fc..0000000 --- a/test/form-validation.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { accountError, deadlineError, payeeError } from "../web/src/shared/form-validation.js"; - -test("payee entry accepts near.com accounts without changing owner-account validation", () => { - for (const account of ["nearcom:Payee.near", "NEARCOM:0x" + "AB".repeat(20), "nearcom:" + "a".repeat(64)]) { - assert.equal(payeeError(account), undefined); - assert.ok(accountError(account)); - } - for (const account of ["nearcom:", "nearcom:nearcom:payee.near", "nearcom:alice..near", "nearcom: alice.near"]) - assert.ok(payeeError(account)); -}); - -test("NEAR account feedback accepts full named and implicit accounts, rejects malformed identifiers", () => { - for (const account of ["payee.near", "team.sputnik-dao.near", "a".repeat(64), " payee.near ", "aa", "alice_bob.near"]) - assert.equal(accountError(account), undefined, account); - for (const account of ["", "a", "Alice.near", "alice..near", "alice-.near", "alice near", "a".repeat(65)]) - assert.ok(accountError(account), account); -}); - -test("agreement deadline feedback rejects empty, impossible and expired days before date conversion", () => { - const now = Date.parse("2026-10-14T12:00:00.000Z"); - for (const value of ["", "not-a-date", "2026-02-30", "2026-10-13", "2026-1-4"]) - assert.ok(deadlineError(value, now), value); - for (const value of ["2026-10-14", "2026-10-15", "2028-02-29"]) - assert.equal(deadlineError(value, now), undefined, value); - assert.ok(deadlineError("2026-10-14", Date.parse("2026-10-15T00:00:00Z"))); -}); diff --git a/test/frontend-boundaries.test.ts b/test/frontend-boundaries.test.ts index 61be178..a528a39 100644 --- a/test/frontend-boundaries.test.ts +++ b/test/frontend-boundaries.test.ts @@ -1,4 +1,3 @@ -import "../web/src/features/payables/payment-stages.test.js"; import assert from "node:assert/strict"; import { readFileSync, existsSync } from "node:fs"; import { dirname, resolve } from "node:path"; diff --git a/test/gateway-session.test.ts b/test/gateway-session.test.ts deleted file mode 100644 index d71f978..0000000 --- a/test/gateway-session.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { QueryClient, QueryObserver } from "@tanstack/react-query"; - -test("refreshing gateway permissions updates every session consumer from the same snapshot", async () => { - Object.defineProperty(globalThis, "location", { value: { pathname: "/a/payables/" }, configurable: true }); - const { clearAgentCapabilities, gatewayQueries } = await import(new URL("../web/src/app/queries.ts", import.meta.url).href); - const { loadGateway } = await import(new URL("../web/src/app/session.tsx", import.meta.url).href); - // Exercise every session query definition; these used to give the shell and sibling controls - // independent snapshots even though they loaded the same gateway response. - const definitions = Object.values(gatewayQueries).filter((entry): entry is { - queryKey: string[]; queryFn: () => Promise | null>; staleTime: number; retry: false; - } => Boolean(entry && typeof entry === "object" && "queryFn" in entry && entry.queryFn === loadGateway)); - assert.ok(definitions.length > 0); - const session = (canExecute: boolean) => ({ - agents: [{ name: "payables", owner: "owner.near", dao: false }], invoices: null, - viewer: { account: "owner.near", access: { - payables: { canSign: false, canExecute, canManage: false, canPropose: true, canVote: canExecute }, - treasury: { canSign: true, canExecute: true, canManage: true, canPropose: false, canVote: false }, - } }, - }); - const client = new QueryClient(); - for (const definition of definitions) client.setQueryData(definition.queryKey, session(true)); - const shell = new QueryObserver(client, definitions[0]!); - const sibling = new QueryObserver(client, definitions.at(-1)!); - const unsubscribe = [shell.subscribe(() => {}), sibling.subscribe(() => {})]; - const originalFetch = globalThis.fetch; - let reads = 0; - globalThis.fetch = async () => { reads++; return Response.json(session(false)); }; - try { - await sibling.refetch(); - assert.equal(sibling.getCurrentResult().data?.viewer?.access.payables?.canExecute, false); - assert.equal(shell.getCurrentResult().data?.viewer?.access.payables?.canExecute, false, - "a successful permission refresh must also update the shell instead of leaving stale execution access"); - assert.equal(reads, 1, "one refresh serves both consumers"); - clearAgentCapabilities(client, ""); - assert.deepEqual(shell.getCurrentResult().data, session(false), "a workspace feed denial cannot change unrelated agent permissions"); - const observedAt = shell.getCurrentResult().dataUpdatedAt; - clearAgentCapabilities(client, "/a/payables"); - const refused = session(false); - refused.viewer.access.payables.canPropose = false; - assert.deepEqual(shell.getCurrentResult().data, refused, "a procedure denial clears only that agent's actions and keeps its membership"); - assert.deepEqual(sibling.getCurrentResult().data, refused, "every consumer loses the refused authority immediately"); - assert.equal(shell.getCurrentResult().dataUpdatedAt, observedAt, "a refusal is not a fresh permission read"); - globalThis.fetch = async () => Response.json({ error: "Gateway unavailable" }, { status: 503 }); - await shell.refetch(); - assert.match(shell.getCurrentResult().error?.message ?? "", /Gateway unavailable/); - assert.match(sibling.getCurrentResult().error?.message ?? "", /Gateway unavailable/); - assert.deepEqual(shell.getCurrentResult().data, refused, "failed refresh cannot restore refused capabilities or become local access"); - } finally { - for (const stop of unsubscribe) stop(); - globalThis.fetch = originalFetch; - client.clear(); - Reflect.deleteProperty(globalThis, "location"); - } -}); diff --git a/test/integration/shared-frontend.ts b/test/integration/shared-frontend.ts deleted file mode 100644 index 229f5b4..0000000 --- a/test/integration/shared-frontend.ts +++ /dev/null @@ -1,272 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { createServer, request, type Server } from 'node:http'; -import { spawn } from 'node:child_process'; -import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs'; -import { join } from 'node:path'; -import { createRequire } from 'node:module'; -import { tmpdir } from 'node:os'; -import { supplierEnvironment, supplierCookie } from '../../src/gateway/hosted-supplier.js'; -import { sessionToken } from '../../src/signin.js'; -import { chromium } from 'playwright'; -import { generateKey, Near, type PrivateKey } from 'near-kit'; - -const listen = (server: Server) => new Promise((resolve, reject) => { - server.once('error', reject); - server.listen(0, '127.0.0.1', () => resolve((server.address() as { port: number }).port)); -}); -const area = process.env.SHARED_FRONTEND_AREA ?? 'treasury'; -const host = `${area}.test`; -test(`independent ${area} build signs into the real gateway and keeps reads host/owner scoped`, { timeout: 90_000 }, async t => { - const runtime = process.env.SHARED_RUNTIME_ROOT ?? process.cwd(); - const dist = process.env.SHARED_FRONTEND_DIST!; - const directory = mkdtempSync(join(tmpdir(), 'treasury-consumer-')); - t.after(() => rmSync(directory, { recursive: true, force: true })); - const key = generateKey(); - const near = new Near({ network: 'mainnet', privateKey: key.secretKey as PrivateKey, defaultSignerId: 'alice.near' }); - const reads: string[] = []; - let ready = false; - const { setup, overview } = createRequire(import.meta.url)('../browser/fixtures/workspace.cjs').workspaceEvidence(); - const agent = createServer((req, res) => { - const path = req.url!; - reads.push(path); - const values: Record = { - '/rpc/ownerIdentity': { agentId: null, owner: null }, - '/rpc/setup': { agentId: null, wallet: null, owner: null, grant: null, dao: null, executor: true }, - '/rpc/owner/actions': [], - ...(area === 'payables' ? { '/rpc/overview': null, '/rpc/held': [], '/rpc/autopilot/get': { on: false }, '/rpc/unresolved': [], '/rpc/agreements/list': [], '/rpc/inbox/list': [] } : {}), - '/rpc/instance': { agentId: null, executor: true }, - }; - if (ready) Object.assign(values, { - '/rpc/setup': { ...setup, owner: { type: 'near', account_id: 'alice.near' } }, - '/rpc/overview': overview('facilitator'), '/rpc/instance': { agentId: 'fixture', executor: false }, - '/rpc/treasury/get': null, '/rpc/invoices': [], '/rpc/activity': [], '/rpc/owner/pending': [], - '/rpc/compensation/list': { agreements: [], requests: [], history: [], payments: [] }, - '/rpc/paymentHistory': { items: [], complete: true }, '/rpc/workOrders/list': [order], - '/rpc/workOrders/get': { order, agentId: null, wallet: null, balance: null, policyReady: false, grant: null, invoice: null, ownerActions: [], approval: null, error: null }, - }); - res.writeHead(path in values ? 200 : 500, { 'content-type': 'application/json' }).end(JSON.stringify({ json: path in values ? values[path] : 'Unexpected procedure' })); - }); - const agentPort = await listen(agent); t.after(() => agent.close()); - const linkedAgent = createServer((req, res) => { agent.emit('request', req, res); }); - const linkedPort = await listen(linkedAgent); t.after(() => linkedAgent.close()); - const chain = createServer((req, res) => { - let body = ''; req.on('data', chunk => body += chunk).on('end', () => { - const { id, params } = JSON.parse(body); - const answer = params.request_type === 'view_access_key' && ['alice.near', 'bob.near'].includes(params.account_id) && params.public_key === key.publicKey.toString() - ? { result: { permission: 'FullAccess', nonce: 0, block_height: 1, block_hash: '11111111111111111111111111111111' } } - : { error: { name: 'HANDLER_ERROR', cause: { name: 'UNKNOWN_ACCOUNT', info: {} }, code: -32000, message: 'Server error' } }; - res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ jsonrpc: '2.0', id, ...answer })); - }); - }); - const chainPort = await listen(chain); t.after(() => chain.close()); - const provider = createServer((req, res) => { - if (req.method === 'GET' && req.url === `/v1/agents/${'b'.repeat(64)}`) { - res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ owner: { type: 'near', account_id: 'bob.near' } })); - } else if (req.method === 'GET' && req.url === `/v1/agents/${'b'.repeat(64)}/policy`) { - res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ policy: null })); - } else res.writeHead(503).end('No provider actions in this fixture'); - }); - const providerPort = await listen(provider); t.after(() => provider.close()); - - const probe = createServer(); const port = await listen(probe); await new Promise(resolve => probe.close(() => resolve())); - writeFileSync(join(directory, 'dashboard.json'), JSON.stringify({ host, invoices: 'https://legacy-intake.test/', selfService: true, hosts: { - [host]: { demo: area, agents: area === 'payables' ? ['treasury', 'linked-payout'] : ['treasury'], hostedAreas: [area], frontendDist: dist }, - 'invoices.test': { demo: 'invoices', agents: [], hostedAreas: ['payables'] }, - 'other.test': { demo: 'showcase', agents: ['treasury'] }, - }, agents: [{ name: 'treasury', owner: 'alice.near', area, port: agentPort, executor: false }, ...(area === 'payables' ? [{ name: 'linked-payout', owner: 'alice.near', area: 'payables', port: linkedPort, executor: false, invoices: 'https://invoices.test/submit?source=agency' }] : [])] })); - const startGateway = () => spawn(process.execPath, ['--import', join(runtime, 'node_modules/tsx/dist/loader.mjs'), join(runtime, 'src/gateway/server.ts')], { - cwd: directory, env: { ...process.env, PORT: String(port), SESSION_SECRET: 'offline-shared-frontend-secret-123456789', NEAR_RPC_URL: `http://127.0.0.1:${chainPort}`, NEAR_INTENTS_AGENT_API_URL: `http://127.0.0.1:${providerPort}` }, stdio: ['ignore', 'pipe', 'pipe'], - }); - let gateway = startGateway(); - t.after(async () => { if (gateway.exitCode === null) { gateway.kill(); await new Promise(resolve => gateway.once('exit', resolve)); } }); - let diagnostics = ''; - const waitGateway = async () => { - gateway.stderr!.on('data', chunk => diagnostics += chunk); - await new Promise((resolve, reject) => { - const timer = setTimeout(() => reject(new Error(diagnostics || 'Gateway did not start')), 10_000); - gateway.stdout!.on('data', chunk => { if (String(chunk).includes('on port')) { clearTimeout(timer); resolve(); } }); - gateway.once('exit', () => { clearTimeout(timer); reject(new Error(diagnostics)); }); - }); - }; - await waitGateway(); - const browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE }); - t.after(() => browser.close()); - const context = await browser.newContext({ serviceWorkers: 'block' }); - await context.route('**/*', route => route.abort()); - await context.routeWebSocket('**/*', socket => socket.close()); - const page = await context.newPage(); page.setDefaultTimeout(12_000); - let badDiscovery = false; - const errors: string[] = []; page.on('pageerror', error => errors.push(error.message)); - let walletAccount = 'alice.near'; - await page.exposeFunction('fixtureSign', async (value: { message: string; recipient: string; nonce: number[] }) => { - const signed = await near.signMessage({ ...value, nonce: new Uint8Array(value.nonce) }); - return { ...signed, accountId: walletAccount }; - }); - // Raw JavaScript avoids TypeScript/esbuild helper references in the browser realm. - await page.addInitScript({ content: `(() => { - if (location.protocol !== 'https:') return; - localStorage.setItem('member:selected-wallet:mainnet', 'fixture-wallet'); - localStorage.setItem('selected-wallet:mainnet', 'fixture-wallet'); - const accounts = [{ accountId: localStorage.getItem('fixture-account') || 'alice.near' }]; - const wallet = { manifest: { id: 'fixture-wallet', name: 'Offline wallet', features: { signMessage: true, signDelegateActions: true }, permissions: {} }, - getAccounts: async () => accounts, signIn: async () => accounts, signOut: async () => {}, - signMessage: async value => window.fixtureSign({ ...value, nonce: Array.from(value.nonce) }), - signDelegateActions: async () => { throw new Error('No owner signing in this test'); }, - signAndSendTransaction: async () => { throw new Error('No transaction in this test'); } }; - window.addEventListener('near-selector-ready', () => window.dispatchEvent(new CustomEvent('near-wallet-injected', { detail: wallet }))); - })();` }); - let managedPresentation: string | undefined; - const orderId = '12345678-1234-4234-8234-123456789abc'; - const order = { version: 1, id: orderId, parentAgentId: 'b'.repeat(64), payee: 'supplier.near', amount: '1250000', note: 'Offline packaged work', until: '2030-01-01T00:00:00.000Z', createdAt: '2026-10-15T00:00:00.000Z', asset: 'usdc', owner: { type: 'near', account_id: 'bob.near', public_key: 'fixture' } }; - const supplierRequests: string[] = []; - // Browser traffic reaches the real gateway over loopback. Everything else is blocked. - await context.route('**/*', async route => { - const url = new URL(route.request().url()); - if (url.href === 'https://cdn.jsdelivr.net/npm/@fastnear/near-connect@0.14.1/+esm') return route.fulfill({ headers: { 'access-control-allow-origin': '*' }, contentType: 'application/javascript', body: 'export class NearConnector { connect() { throw new Error("Supplier wallet signing disabled in fixture"); } disconnect() {} }' }); - if (![host, 'other.test', 'invoices.test'].includes(url.hostname)) return route.abort(); - if (url.hostname === 'invoices.test') supplierRequests.push(url.pathname + url.search); - // Presentation observations only. Discovery, admission and supplier routing use the real gateway. - if (managedPresentation && url.pathname.startsWith(`/a/${managedPresentation}/rpc/`)) { - const method = url.pathname.split('/rpc/')[1]!; - const values: Record = { - setup: { ...setup, owner: { type: 'near', account_id: 'bob.near' } }, overview: overview('facilitator'), instance: { agentId: 'b'.repeat(64), executor: false }, - 'owner/actions': [], 'owner/pending': [], 'treasury/get': null, held: [], unresolved: [], 'inbox/list': [], 'agreements/list': [], invoices: [], activity: [], - 'compensation/list': { agreements: [], requests: [], history: [], payments: [] }, - paymentHistory: { items: [], complete: true }, 'autopilot/get': { on: false }, 'workOrders/list': [order], - 'workOrders/get': { order, agentId: null, wallet: null, balance: null, policyReady: false, grant: null, invoice: null, ownerActions: [], approval: null, error: null }, - }; - assert.ok(method in values, `Unexpected presentation procedure: ${method}`); - return route.fulfill({ json: { json: values[method] } }); - } - if (badDiscovery && url.pathname === '/gw/me') return route.fulfill({ contentType: 'text/html', body: 'Misconfigured static fallback' }); - const answer = await new Promise<{ status: number; headers: Record; body: Buffer }>((resolve, reject) => { - const headers = { ...route.request().headers(), host: url.host }; delete (headers as Record).connection; - const upstream = request({ hostname: '127.0.0.1', port, method: route.request().method(), path: url.pathname + url.search, headers }, res => { - const chunks: Buffer[] = []; res.on('data', chunk => chunks.push(chunk)).on('end', () => resolve({ status: res.statusCode!, headers: Object.fromEntries(Object.entries(res.headers).filter(([, value]) => value !== undefined).map(([key, value]) => [key, Array.isArray(value) ? value.join('\n') : String(value)])), body: Buffer.concat(chunks) })); - }); upstream.on('error', reject); upstream.end(route.request().postDataBuffer()); - }); - await route.fulfill(answer); - }); - await page.goto(`https://${host}/`); - await page.getByRole('button', { name: area === 'treasury' ? 'Connect wallet' : 'Connect wallet to start', exact: true }).first().waitFor(); - assert.ok(await page.title()); - assert.equal(reads.length, 0, 'public entry reads no agent'); - await page.getByRole('button', { name: area === 'treasury' ? 'Connect wallet' : 'Connect wallet to start', exact: true }).first().click(); - await page.getByRole('heading', { name: area === 'treasury' ? 'Create your Treasury' : 'Set up your Payables agent', exact: true }).waitFor().catch(async error => { throw new Error(`${error}\nPage: ${await page.locator('body').innerText()}\nGateway: ${diagnostics}\nBrowser errors: ${errors.join("; ")}`); }); - await page.getByRole('link', { name: area === 'treasury' ? 'alice.near' : 'Review agent', exact: true }).first().click(); - await page.getByRole('button', { name: 'Create agent', exact: true }).waitFor().catch(async error => { throw new Error(`${error}\n${await page.locator('body').innerText()}\nReads: ${reads.join(', ')}\nErrors: ${errors.join('; ')}`); }); - assert.ok(reads.includes('/rpc/setup')); - assert.deepEqual(await page.evaluate(async () => (await fetch('/a/treasury/rpc/instance', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })).json()), { json: { agentId: null, executor: true } }); - assert.equal(await page.evaluate(async () => (await fetch('/a/missing/rpc/instance', { method: 'POST', body: '{}' })).status), 404); - // No owner intent, plan or money procedure was requested. - assert.ok(reads.every(path => ['/rpc/ownerIdentity', '/rpc/setup', '/rpc/owner/actions', '/rpc/instance', ...(area === 'payables' ? ['/rpc/overview', '/rpc/held', '/rpc/autopilot/get', '/rpc/unresolved', '/rpc/agreements/list', '/rpc/inbox/list'] : [])].includes(path))); - if (area === 'payables') { - ready = true; - await page.goto(`https://${host}/a/treasury/payees`); - await page.getByText("This agent's invoice page address is not configured here.", { exact: true }).waitFor(); - assert.equal(await page.getByRole('link', { name: 'Open invoice page', exact: true }).count(), 0); - assert.equal(await page.locator('a[href^="https://legacy-intake.test"]').count(), 0); - await page.goto(`https://${host}/a/linked-payout/payees`); - const view = await page.evaluate(async () => (await fetch('/gw/me')).json()); - assert.equal(view.agents.find((a: {name: string}) => a.name === 'linked-payout').invoices, 'https://invoices.test/submit?source=agency'); - assert.equal(view.agents.find((a: {name: string}) => a.name === 'treasury').invoices, undefined); - assert.equal(await page.getByRole('link', { name: 'Open invoice page', exact: true }).getAttribute('href'), 'https://invoices.test/submit?source=agency'); - await page.getByRole('button', { name: 'Review work order', exact: true }).click(); - const staticLink = page.getByRole('link', { name: 'Open work order on the invoice page', exact: true }); - assert.equal(await staticLink.getAttribute('href'), `https://invoices.test/submit?source=agency&workOrder=${orderId}`); - await page.reload(); - await page.getByRole('button', { name: 'Review work order', exact: true }).click(); - assert.equal(await staticLink.getAttribute('href'), `https://invoices.test/submit?source=agency&workOrder=${orderId}`); - - } - await page.evaluate(async () => { await fetch('/gw/logout', { method: 'POST' }); }); - assert.equal(await page.evaluate(async () => (await fetch('/a/treasury/rpc/instance', { method: 'POST', body: '{}' })).status), 401); - const bobChallenge = await page.evaluate(async () => (await fetch('/gw/challenge')).json()); - const bobSigned = await near.signMessage({ ...bobChallenge, nonce: Buffer.from(bobChallenge.nonce, 'base64') }); - const bobStatus = await page.evaluate(async body => (await fetch('/gw/session', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })).status, { ...bobSigned, accountId: 'bob.near', nonce: bobChallenge.nonce }); - assert.equal(bobStatus, 200); - assert.equal(await page.evaluate(async () => (await fetch('/a/treasury/rpc/instance', { method: 'POST', body: '{}' })).status), 403); - if (area === 'payables') { - walletAccount = 'bob.near'; - await page.evaluate(() => localStorage.setItem('fixture-account', 'bob.near')); - await page.goto(`https://${host}/`); - const reservationResponse = page.waitForResponse(response => response.url().endsWith('/gw/agents') && response.request().method() === 'POST'); - await page.getByRole('button', { name: 'Continue to Payables setup', exact: true }).click(); - const response = await reservationResponse; - assert.equal(response.status(), 200); - assert.deepEqual(response.request().postDataJSON(), { owner: 'bob.near', kind: 'wallet', area: 'payables' }); - await page.waitForURL(url => /^\/a\/own-[0-9a-f]{24}\/$/.test(url.pathname)); - const name = new URL(page.url()).pathname.split('/')[2]; - let admitted = false; - for (let attempt = 0; attempt < 100; attempt++) { - const view = await page.evaluate(async () => (await fetch('/gw/me')).json()); - if (view.viewer?.access[name!]) { admitted = true; break; } - await new Promise(resolve => setTimeout(resolve, 100)); - } - assert.ok(admitted, diagnostics); - await page.reload(); - const discovery = await page.evaluate(async () => (await fetch('/gw/me')).json()); - assert.equal(discovery.agents.length, 1, JSON.stringify({ discovery, diagnostics, body: await page.locator('body').innerText() })); - assert.equal(discovery.agents[0].name, name); - assert.equal(discovery.agents[0].invoices, `https://invoices.test/i/${name}/`); - assert.equal(discovery.agents[0].managed, true); - // Fixture-only restart: assign an offline identity so the actual supplier handler can start. - await page.goto('about:blank'); - gateway.kill(); await new Promise(resolve => gateway.once('exit', resolve)); - const settings = join(directory, '.hosted', `${name}.env`); - writeFileSync(settings, readFileSync(settings, 'utf8') + `AGENT_ID=${'b'.repeat(64)}\n`); - const ordersDirectory = join(directory, '.work-orders', 'b'.repeat(64)); - mkdirSync(ordersDirectory, { recursive: true }); - writeFileSync(join(ordersDirectory, `${orderId}.json`), JSON.stringify(order)); - writeFileSync(join(ordersDirectory, '22345678-1234-4234-8234-123456789abc.json'), JSON.stringify({ ...order, id: '22345678-1234-4234-8234-123456789abc', note: 'Another order must not be selected' })); - gateway = startGateway(); await waitGateway(); - managedPresentation = name; - await page.goto(`https://${host}/a/${name}/payees`); - for (let attempt = 0; attempt < 100; attempt++) { - const view = await page.evaluate(async () => (await fetch('/gw/me')).json()); - if (view.viewer?.access[name!]) break; - await new Promise(resolve => setTimeout(resolve, 100)); - } - await page.goto(`https://${host}/a/${name}/payees`); - assert.equal(await page.getByRole('link', { name: 'Open invoice page', exact: true }).getAttribute('href'), `https://invoices.test/i/${name}/`); - await page.getByRole('button', { name: 'Review work order', exact: true }).click(); - const link = page.getByRole('link', { name: 'Open work order on the invoice page', exact: true }); - const href = await link.getAttribute('href'); - assert.equal(href, `https://invoices.test/i/${name}/?workOrder=${orderId}`); - const supplier = await context.newPage(); - await supplier.goto(href!); - // Startup may initially return 502 while the isolated child opens its listener. - for (let attempt = 0; attempt < 100 && !(await supplier.locator('#signin').count()); attempt++) { - await new Promise(resolve => setTimeout(resolve, 100)); await supplier.reload(); - } - assert.ok((await supplier.content()).includes(`/i/${name}/invoice-browser.js`)); - assert.equal(new URL(supplier.url()).searchParams.get('workOrder'), orderId); - await supplier.reload(); - assert.equal(new URL(supplier.url()).searchParams.get('workOrder'), orderId); - assert.ok(supplierRequests.includes(`/i/${name}/?workOrder=${orderId}`)); - assert.equal(await supplier.evaluate(async () => (await fetch('/i/own-' + 'f'.repeat(24) + '/api/work-orders')).status), 404); - assert.equal(await supplier.evaluate(async base => (await fetch(base + 'api/work-orders')).status, `/i/${name}/`), 401); - const supplierEnv = supplierEnvironment({ name: name!, owner: 'bob.near', kind: 'wallet', area: 'payables', port: 9000, executor: true, envFile: 'unused' }, 'invoices.test', 'offline-shared-frontend-secret-123456789'); - await context.addCookies([{ name: supplierCookie(name!), value: sessionToken('supplier.near', supplierEnv.INVOICES_SESSION_SECRET!), domain: 'invoices.test', path: '/', secure: true, httpOnly: true, sameSite: 'Strict' }]); - await supplier.reload(); - await supplier.locator('#work-order-note').filter({ hasText: 'Offline packaged work' }).waitFor(); - assert.ok(supplierRequests.includes(`/i/${name}/api/work-orders/${orderId}`)); - assert.equal(await supplier.locator('#work-order-note').innerText(), 'Offline packaged work'); - await supplier.reload(); - await supplier.locator('#work-order-note').filter({ hasText: 'Offline packaged work' }).waitFor(); - assert.equal(new URL(supplier.url()).searchParams.get('workOrder'), orderId); - assert.equal(await supplier.locator('#work-order-file').isDisabled(), true, 'unfunded fixture cannot file a payment'); - await supplier.close(); - - - } - await page.goto('https://other.test/gw/me'); - assert.equal(JSON.parse(await page.locator('body').innerText()).viewer, null, 'session never crosses hosts'); - const beforeBadDiscovery = reads.length; - badDiscovery = true; - await page.goto(`https://${host}/a/treasury/`); - await page.getByRole('heading', { name: 'Dashboard unavailable', exact: true }).waitFor(); - assert.equal(reads.length, beforeBadDiscovery, 'HTML discovery never mounts trusted agent reads'); - assert.deepEqual(errors, []); -}); diff --git a/test/limit-order-dispatch.test.ts b/test/limit-order-dispatch.test.ts index f5f7689..71b727f 100644 --- a/test/limit-order-dispatch.test.ts +++ b/test/limit-order-dispatch.test.ts @@ -80,7 +80,7 @@ async function place(proposal: OrderProposalRecord) { const lock = await acquireMoneyLock(); try { return await dispatch(lock, "limit-order", { method: "limit_order", request: proposal.order }, - undefined, undefined, undefined, undefined, undefined, undefined, { proposalId: proposal.id }); + { order: { proposalId: proposal.id } }); } finally { await lock.release(); } } @@ -106,7 +106,7 @@ test("an owner-approved proposal places once under the money lock and saves orde /submission must pass through dispatch/); assert.deepEqual(readOps(), [], "direct send never prepares a journal entry"); assert.equal((await dispatch(lock, "limit-order", { method: "limit_order", request: proposal.order }, - undefined, undefined, undefined, undefined, undefined, undefined, { proposalId: proposal.id })).status, "SUCCESS"); + { order: { proposalId: proposal.id } })).status, "SUCCESS"); } finally { await lock.release(); } assert.equal(submissions, 1); diff --git a/test/market-deliverable-history.test.ts b/test/market-deliverable-history.test.ts new file mode 100644 index 0000000..a4175f1 --- /dev/null +++ b/test/market-deliverable-history.test.ts @@ -0,0 +1,99 @@ +import assert from "node:assert/strict"; +import { createHash, randomUUID } from "node:crypto"; +import { test } from "node:test"; +import { generateKey } from "near-kit"; +import { market, MARKET_USDC, MARKET_PAYEE } from "./e2e/market.mjs"; +import { keySigner } from "../src/market/payment-key.js"; +import { paymentHeader } from "../src/market/x402.js"; + +const agents = { + worker: { amount: "100000", windowSeconds: 600, outcome: "worker" }, + other: { amount: "100000", windowSeconds: 600, outcome: "worker" }, +}; +const get = (sim: any, path: string, worker = "worker") => fetch(sim.url + path, { + headers: worker ? { authorization: `Bearer ${sim.credentials(worker).token}`, accept: "application/json" } : {}, +}); +const base = (id: string) => `/v1/assignments/${id}/deliverable`; + +async function hire(sim: any) { + const payer = keySigner(generateKey().secretKey); + sim.fund(payer.account, "100000"); + const row = { amount: "100000", asset: MARKET_USDC, maxTimeoutSeconds: 1200, + network: "near:mainnet", payTo: MARKET_PAYEE, scheme: "exact" }; + const signed = await payer.sign({ asset: MARKET_USDC, payTo: MARKET_PAYEE, amount: row.amount, + nonce: 1n, maxBlockHeight: sim.chain.height + 1190n }); + const response = await fetch(`${sim.url}/a2a/worker/v1`, { method: "POST", + headers: { "content-type": "application/json", "x-payment": paymentHeader(row, signed.signedDelegateAction) }, + body: JSON.stringify({ jsonrpc: "2.0", id: "fixture", method: "SendMessage", params: { message: { parts: [{ text: "Offline history fixture" }] } } }) }); + assert.equal(response.status, 200); + const answer = await response.json() as any; + assert.ok(answer.result?.task?.id, JSON.stringify(answer)); + return { id: answer.result.task.id as string, payer }; +} + +test("known owned assignments expose empty history; all deliverable reads enforce worker isolation", async () => { + const sim = await market({ agents }); + try { + const id = randomUUID(); + sim.assignments.set(id, { handle: "worker", assignment: { assignmentId: id, status: "in_progress" }, job: {} }); + const history = await get(sim, base(id) + "/versions"); + assert.equal(history.status, 200); + assert.deepEqual(await history.json(), { versions: [] }); + for (const suffix of ["/versions", "/raw", "/versions/1/raw"]) { + assert.equal((await get(sim, base(id) + suffix, "")).status, 401); + assert.equal((await get(sim, base(id) + suffix, "other")).status, 403); + assert.equal((await get(sim, base(randomUUID()) + suffix)).status, 404); + } + assert.equal((await get(sim, base(id) + "/raw")).status, 404); + assert.equal((await get(sim, base(id) + "/versions/1/raw")).status, 404); + assert.equal(sim.calls.some((c: any) => c.method === "POST"), false); + } finally { await sim.close(); } +}); + +test("a delivered version survives a lost acknowledgement and fresh reads without resubmission or another payment", async () => { + const sim = await market({ agents }); + try { + const { id, payer } = await hire(sim); + const markdown = "# Exact managed Markdown\nUnicode: café ☕\n"; + const response = await fetch(`${sim.url}/v1/assignments/${id}/submit`, { method: "POST", + headers: { authorization: `Bearer ${sim.credentials("worker").token}`, "content-type": "application/json" }, + body: JSON.stringify({ deliverableMarkdown: markdown }) }); + assert.equal(response.status, 200); + await response.body?.cancel(); // The client retains no submission acknowledgement. + const versions = (await (await get(sim, base(id) + "/versions")).json() as any).versions; + assert.equal(versions.length, 1); + assert.deepEqual(versions[0], { version: 1, files: [], submittedAt: sim.assignments.get(id).assignment.submittedAt, + deliverableHash: createHash("sha256").update(markdown).digest("hex"), + deliverableUrl: base(id) + "/versions/1/raw", senderAgentId: sim.credentials("worker").agentId }); + assert.equal((await get(sim, base(id) + "/versions/1/raw")).headers.get("content-type"), "text/markdown; charset=utf-8"); + for (const suffix of ["/raw", "/versions/1/raw"]) assert.equal(await (await get(sim, base(id) + suffix)).text(), markdown); + assert.equal((await get(sim, base(id) + "/versions/2/raw")).status, 404); + assert.deepEqual((await (await get(sim, base(id) + "/versions")).json() as any).versions, versions); + assert.equal(sim.chain.accounts.get(payer.account).transfers.length, 1); + assert.equal(sim.calls.filter((c: any) => c.path.endsWith("/submit")).length, 1); + } finally { await sim.close(); } +}); + +test("version history is append-only across fixture rework and never makes an expired payment paid", async () => { + const sim = await market({ agents }); + try { + const { id, payer } = await hire(sim); + sim.advance(2000); + const submit = (markdown: string) => fetch(`${sim.url}/v1/assignments/${id}/submit`, { method: "POST", + headers: { authorization: `Bearer ${sim.credentials("worker").token}`, "content-type": "application/json" }, + body: JSON.stringify({ deliverableMarkdown: markdown }) }); + assert.equal((await submit("first version")).status, 200); + const first = (await (await get(sim, base(id) + "/versions")).json() as any).versions[0]; + // Fixture-only rework: no provider review/acceptance endpoint is simulated by this mutation. + sim.assignments.get(id).assignment.status = "in_progress"; + assert.equal((await submit("second version")).status, 200); + const versions = (await (await get(sim, base(id) + "/versions")).json() as any).versions; + assert.deepEqual(versions.map((v: any) => v.version), [1, 2]); + assert.deepEqual(versions[0], first); + assert.equal(await (await get(sim, base(id) + "/versions/1/raw")).text(), "first version"); + assert.equal(await (await get(sim, base(id) + "/versions/2/raw")).text(), "second version"); + assert.equal(await (await get(sim, base(id) + "/raw")).text(), "second version"); + assert.equal(sim.assignments.get(id).assignment.status, "submitted"); + assert.equal(sim.chain.accounts.get(payer.account).transfers.length, 0); + } finally { await sim.close(); } +}); diff --git a/test/market-hire.test.ts b/test/market-hire.test.ts index 2f1b3ce..72b0db0 100644 --- a/test/market-hire.test.ts +++ b/test/market-hire.test.ts @@ -263,8 +263,8 @@ for (const refusedStage of ["open", "usdc"] as const) test(`dispatch cannot cont asset: nextStage === "open" ? ASSETS.wNEAR : ASSETS.USDC, amount: nextStage === "open" ? OPEN_ACCOUNT_WNEAR : approved.amount, chain: "near", recipient: KEY, confidential: true, - } }, undefined, undefined, undefined, marketStageKey(bindingKey, nextStage), undefined, - { hire: approved, bindingKey, stage: nextStage }), /market_binding_closed/); + } }, { requestKey: marketStageKey(bindingKey, nextStage), + market: { hire: approved, bindingKey, stage: nextStage } }), /market_binding_closed/); // Even a fully funded key cannot pay the closed hire through a direct dispatch call. sim.fund(KEY, approved.amount); await assert.rejects(dispatch(lock, "market-hire", { method: "x402", request: { @@ -273,7 +273,7 @@ for (const refusedStage of ["open", "usdc"] as const) test(`dispatch cannot cont payTo: approved.payTo, maxTimeoutSeconds: approved.maxTimeoutSeconds }, asset: ASSETS.USDC, amount: approved.amount, payer: KEY, publicKey: parseKey(secretKey).publicKey.toString(), nonce: "1", maxBlockHeight: (sim.chain.height + 1_200n).toString(), balanceAtSigning: approved.amount, - } }, undefined, undefined, undefined, bindingKey, undefined, { hire: approved, bindingKey }), /market_binding_closed/); + } }, { requestKey: bindingKey, market: { hire: approved, bindingKey } }), /market_binding_closed/); } finally { await lock.release(); } assert.deepEqual(readOps(), before, "neither rejected dispatch prepares another operation"); assert.equal(withdrawals.length, 0); @@ -618,7 +618,7 @@ test("dispatch independently blocks an x402 action for a funding-only binding", payTo: approved.payTo, maxTimeoutSeconds: approved.maxTimeoutSeconds }, asset: ASSETS.USDC, amount: approved.amount, payer: KEY, publicKey: parseKey(secretKey).publicKey.toString(), nonce: "1", maxBlockHeight: (sim.chain.height + 1_200n).toString(), balanceAtSigning: approved.amount, - } }, undefined, undefined, undefined, bindingKey, undefined, { hire: approved, bindingKey }), /funding_only/); + } }, { requestKey: bindingKey, market: { hire: approved, bindingKey } }), /funding_only/); } finally { await lock.release(); } assert.equal(readOps().some(o => o.method === "x402"), false); }); @@ -844,8 +844,8 @@ test("dispatch cannot add native funding or exceed an allocation's signed USDC t await assert.rejects(dispatch(lock, "market-topup", { method: "withdraw", request: { asset: stage === "open" ? ASSETS.wNEAR : ASSETS.USDC, amount: stage === "open" ? "20000000000000000000000" : "490001", chain: "near", recipient: KEY, confidential: true, - } }, undefined, undefined, undefined, marketStageKey(key, stage), undefined, - { hire: target.approved, bindingKey: key, stage }), /exact bounded USDC top-up/); + } }, { requestKey: marketStageKey(key, stage), + market: { hire: target.approved, bindingKey: key, stage } }), /exact bounded USDC top-up/); } } finally { await lock.release(); } assert.equal(withdrawals.length, 2); diff --git a/test/market-signing-race.test.ts b/test/market-signing-race.test.ts index 23a395a..79c6c5c 100644 --- a/test/market-signing-race.test.ts +++ b/test/market-signing-race.test.ts @@ -68,8 +68,8 @@ for (const fault of faults) test(`x402 signing followed by ${fault.name} never c }); const callsBefore = sim.calls.filter(c => c.payment !== null).length; try { - await assert.rejects(dispatch(lock, "market-hire", action, undefined, undefined, undefined, bindingKey, undefined, - { hire: quote.terms, bindingKey })); + await assert.rejects(dispatch(lock, "market-hire", action, + { requestKey: bindingKey, market: { hire: quote.terms, bindingKey } })); assert.equal(signedCount, 1, "the fault is injected only after the real signer completed"); assert.equal(sim.calls.filter(c => c.payment !== null).length, callsBefore, "the signed header must never be sent"); assert.equal(sim.chain.accounts.get(account)!.transfers.length, 0); diff --git a/test/owner-observation.test.ts b/test/owner-observation.test.ts deleted file mode 100644 index d345551..0000000 --- a/test/owner-observation.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { observeOwnerAction, ownerActionState } from "../web/src/features/owner/owner-observation.js"; - -test("observation follows an existing intent and cancellation stops further polling", async () => { - const controller = new AbortController(); - let reads = 0; - const following = observeOwnerAction(async () => { reads++; return { stage: "submitting" }; }, controller.signal, () => controller.abort(), 1); - await assert.rejects(following); - assert.equal(reads, 1); -}); -test("owner success stays separate from payment outcome and submitted records remain recovering", async () => { - const state = ownerActionState([{ stage: "submitted", ownerSucceeded: true }]); - assert.equal(state.recovering?.stage, "submitted"); - assert.equal(state.succeeded?.ownerSucceeded, true); - let reads = 0; - const final = await observeOwnerAction(async () => ({ stage: ++reads === 1 ? "submitting" : "submitted", status: "SUCCESS" }), new AbortController().signal, undefined, 1); - assert.equal(final.status, "SUCCESS"); - assert.equal(reads, 2); -}); diff --git a/test/payment-progress.test.ts b/test/payment-progress.test.ts deleted file mode 100644 index 91e9a26..0000000 --- a/test/payment-progress.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { paymentProgress } from "../web/src/features/payables/payment-progress.js"; -const base = { statusError: false, ownerError: false, approved: false, rejected: false }; -test("owner approval never establishes payment processing or completion", () => { - assert.deepEqual(paymentProgress({ ...base, approved: true, status: "PENDING_APPROVAL" }), { owner: "Approval recorded", outcome: "Held for approval" }); - assert.equal(paymentProgress({ ...base, approved: true, status: "PROCESSING" }).outcome, "Payment processing"); - assert.equal(paymentProgress({ ...base, status: "SUCCESS" }).owner, "No owner decision confirmed"); - assert.equal(paymentProgress({ ...base, status: "SUCCESS" }).outcome, "Paid"); -}); -test("failed reads and unknown statuses do not inherit a successful conclusion", () => { - assert.equal(paymentProgress({ ...base, statusError: true, status: "SUCCESS" }).outcome, "Status unavailable"); - assert.equal(paymentProgress({ ...base, ownerError: true, approved: true }).owner, "Owner decision unavailable"); - assert.equal(paymentProgress({ ...base, status: "FUTURE_STATUS" }).outcome, "Outcome unresolved"); - assert.deepEqual(paymentProgress({ ...base, rejected: true, status: "PROCESSING" }), { owner: "Rejection recorded", outcome: "Payment processing" }); - assert.equal(paymentProgress({ ...base, recovering: "submitted" }).owner, "Owner action submitted"); -}); diff --git a/test/payment-queue.test.ts b/test/payment-queue.test.ts deleted file mode 100644 index a311ee8..0000000 --- a/test/payment-queue.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { buildPaymentQueue, filterPaymentQueue, type QueueInvoice, type QueueOperation } from "../web/src/features/payables/payment-queue.js"; -import type { PaymentRecord } from "../web/src/features/payables/payment-records.js"; - -const at = "2026-10-15T12:00:00Z"; -const earlier = "2026-10-14T12:00:00Z"; -const later = "2026-10-16T12:00:00Z"; -const request = { recipient: "Payee.near", asset: "usdc", amount: "1000000" }; -const payment = (id: string, time = at): [string, PaymentRecord] => [id, { at: time, request }]; -const operation = (correlationId: string, status?: string): QueueOperation => ({ correlationId, status, request, idempotencyKey: `operation-${correlationId}` }); -const invoice = (id: string, operation: QueueOperation, review = false): QueueInvoice => ({ id, at, payee: "Invoice-payee.near", review, operation }); - -test("review work comes first, oldest first; retained terminal records come newest first with stable ties", () => { - const payments = [payment("paid-old", earlier), payment("unknown-new", later), payment("unknown-b", earlier), - payment("paid-new", later), payment("unknown-a", earlier), payment("unknown-time", ""), payment("invalid-time", "invalid")]; - const original = payments.map(([id, record]) => [id, { ...record }]); - const queue = buildPaymentQueue({ payments, activity: [operation("paid-old", "SUCCESS"), operation("paid-new", "FAILED")] }); - assert.deepEqual(queue.map(entry => entry.id), ["unknown-a", "unknown-b", "unknown-new", "invalid-time", "unknown-time", "paid-new", "paid-old"]); - assert.deepEqual(filterPaymentQueue(queue, "review", "").map(entry => entry.id), queue.slice(0, 5).map(entry => entry.id)); - assert.deepEqual(payments, original, "the projection does not sort or annotate discovery records in place"); - assert.ok(payments.every(([, record]) => !("status" in record) && !("needsReview" in record))); -}); - -test("approval, rejection and identity-only history cannot establish payment completion", () => { - const ownerActions = [ - { stage: "settled", ownerSucceeded: true, payment: { correlationId: "approved", verdict: "approve" } }, - { stage: "settled", ownerSucceeded: true, payment: { correlationId: "rejected", verdict: "reject" } }, - ]; - const queue = buildPaymentQueue({ payments: [payment("approved"), payment("rejected"), payment("history-only")], ownerActions }); - assert.equal(filterPaymentQueue(queue, "review", "").length, 3); - assert.ok(queue.every(entry => entry.reason === "Payment outcome unknown")); -}); - -test("outstanding owner, held and invoice conditions remain reviewable after a retained terminal outcome", () => { - const ids = ["held", "pending", "prepared-owner", "submitted-owner", "changed-invoice", "prepared-invoice", "complete"]; - const ownerActions = [ - { stage: "prepared", payment: { correlationId: "prepared-owner" }, expiresAt: "2000-01-01T00:00:00Z" }, - { stage: "submitted", payment: { correlationId: "submitted-owner" }, expiresAt: "2000-01-01T00:00:00Z" }, - ]; - const queue = buildPaymentQueue({ payments: ids.map(id => payment(id)), activity: ids.map(id => operation(id, "SUCCESS")), - invoices: [invoice("changed", operation("changed-invoice", "SUCCESS"), true), - invoice("prepared", { ...operation("prepared-invoice", "PREPARED"), submissionState: "PREPARED" })], - heldIds: new Set(["held"]), pendingIds: new Set(["pending"]), ownerActions }); - assert.deepEqual(new Set(filterPaymentQueue(queue, "review", "").map(entry => entry.id)), new Set(ids.filter(id => id !== "complete"))); - assert.equal(queue.find(entry => entry.id === "changed-invoice")?.reason, "Invoice changes need review"); - assert.equal(queue.find(entry => entry.id === "prepared-invoice")?.reason, "Prepared invoice; never submitted"); - assert.equal(queue.find(entry => entry.id === "submitted-owner")?.reason, "Owner action submitted", "an expired attempted signature still needs recovery"); -}); - -test("terminal or refused observations leave review only when no source disagrees or outstanding condition remains", () => { - const ids = ["paid", "failed", "refunded", "refused", "processing", "held", "unknown", "missing", "resolved-without-outcome"]; - const activity = [operation("paid", "SUCCESS"), operation("failed", "FAILED"), operation("refunded", "REFUNDED"), - { ...operation("refused", "UNKNOWN"), refused: "invoice_cancelled_before_submission" }, operation("processing", "PROCESSING"), - operation("held", "PENDING_APPROVAL"), operation("unknown", "UNRECOGNIZED"), operation("missing"), - { ...operation("resolved-without-outcome"), submissionState: "RESOLVED" }]; - const queue = buildPaymentQueue({ payments: ids.map(id => payment(id)), activity }); - assert.deepEqual(new Set(queue.filter(entry => !entry.needsReview).map(entry => entry.id)), new Set(["paid", "failed", "refunded", "refused"])); - assert.equal(filterPaymentQueue(queue, "all", "").length, ids.length, "terminal exceptions remain available in All"); -}); - -test("stale disagreements between invoice and activity observations conservatively retain review", () => { - const pairs: [string, QueueOperation, QueueOperation][] = [ - ["old-processing", operation("old-processing", "PROCESSING"), operation("old-processing", "SUCCESS")], - ["old-success", operation("old-success", "SUCCESS"), operation("old-success", "PROCESSING")], - ["unknown", operation("unknown"), operation("unknown", "SUCCESS")], - ["terminal-conflict", operation("terminal-conflict", "SUCCESS"), operation("terminal-conflict", "REFUNDED")], - ["refusal-conflict", { ...operation("refusal-conflict"), refused: "refused" }, operation("refusal-conflict", "SUCCESS")], - ]; - const queue = buildPaymentQueue({ payments: pairs.map(([id]) => payment(id)), - activity: pairs.map(([, activity]) => activity), invoices: pairs.map(([id, , op]) => invoice(`invoice-${id}`, op)) }); - assert.equal(queue.length, pairs.length, "an invoice joins its actual provider reference into one row"); - assert.ok(queue.every(entry => entry.needsReview && entry.reason === "Retained payment observations disagree")); - const agreed = buildPaymentQueue({ payments: [payment("agreed")], activity: [operation("agreed", "SUCCESS")], - invoices: [invoice("invoice", operation("agreed", "SUCCESS"))] }); - assert.equal(agreed[0]?.needsReview, false); -}); - -test("local invoice identities and operation keys never become or join provider payment references", () => { - const prepared = invoice("local-invoice", { idempotencyKey: "provider-payment", request, status: "PREPARED", submissionState: "PREPARED" }); - const queue = buildPaymentQueue({ payments: [payment("provider-payment")], - activity: [operation("provider-payment", "SUCCESS")], invoices: [prepared] }); - assert.equal(queue.length, 2); - const local = queue.find(entry => entry.invoice?.id === "local-invoice")!; - assert.equal(local.id, undefined); - assert.equal(local.payment, undefined); - assert.equal(local.needsReview, true); - assert.equal(queue.find(entry => entry.id === "provider-payment")?.invoice, undefined); - assert.equal(filterPaymentQueue(queue, "all", "provider-payment").length, 2, "a search match does not establish identity"); - assert.deepEqual(buildPaymentQueue({ payments: [], invoices: [invoice("linked-invoice", operation("explicit-provider-id", "PROCESSING"))] }) - .map(entry => entry.id), ["explicit-provider-id"], "only an explicit correlation ID can create a provider reference"); -}); - -test("search is trimmed, case insensitive, local, and limited by the selected view and supplied accessible sources", () => { - const privateInvoice = invoice("Private-Invoice", { ...operation("paid", "SUCCESS"), idempotencyKey: "Invoice-Key" }); - const input = { payments: [payment("paid"), payment("Held-Reference")], activity: [operation("paid", "SUCCESS"), operation("Held-Reference", "PENDING_APPROVAL")] }; - const operatorQueue = buildPaymentQueue({ ...input, invoices: [privateInvoice] }); - for (const term of [" payEE.near ", " HELD-reference ", " Operation-held-REFERENCE "]) - assert.equal(filterPaymentQueue(operatorQueue, "review", term).length, 1); - for (const term of [" PRIVATE-invoice ", " invoice-KEY ", " invoice-PAYEE.near "]) - assert.equal(filterPaymentQueue(operatorQueue, "all", term)[0]?.id, "paid"); - assert.equal(filterPaymentQueue(operatorQueue, "review", "Private-Invoice").length, 0); - const memberQueue = buildPaymentQueue(input); - for (const term of ["Private-Invoice", "Invoice-Key", "Invoice-payee.near"]) - assert.equal(filterPaymentQueue(memberQueue, "all", term).length, 0, "an omitted invoice source cannot leak through search"); - assert.ok(memberQueue.every(entry => entry.invoice === undefined)); - assert.deepEqual(buildPaymentQueue({ payments: [] }), [], "missing sources do not create records or reuse another call's records"); - assert.equal(filterPaymentQueue(operatorQueue, "all", " ").length, operatorQueue.length); -}); diff --git a/test/payment-records.test.ts b/test/payment-records.test.ts deleted file mode 100644 index bd6493d..0000000 --- a/test/payment-records.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { paymentRecords, type PaymentRecord } from "../web/src/features/payables/payment-records.js"; - -const at = "2026-10-14T12:00:00Z"; -const request = { recipient: "payee.near", asset: "usdc", amount: "123456789", confidential: true }; - -test("local transfers remain discoverable without provider history or owner intents", () => { - const records = paymentRecords({ activity: [ - { correlationId: "payment", at, request }, - { correlationId: "swap", at, request: { origin_asset: "usdc", amount: "1" } }, - { at, request }, - ] }, new Map(), 0); - assert.deepEqual(records, [["payment", { at, request }]]); -}); - -test("identity-only history and owner actions do not erase remembered terms", () => { - const remembered = new Map([["payment", { at, request, approvalId: "approval" }]]); - const records = paymentRecords({ history: { items: [{ correlationId: "payment", at }] }, - ownerActions: [{ payment: { correlationId: "payment" } }], pending: [{ payment: { correlationId: "payment" }, expiresAt: at }] }, remembered, 0); - assert.deepEqual(records, [...remembered]); - assert.equal(records[0]![1].request, request); - assert.deepEqual(remembered.get("payment"), { at, request, approvalId: "approval" }, "projection never mutates its inputs"); -}); - -test("held observations enrich one identity without fabricating an outcome", () => { - const records = paymentRecords({ history: { items: [{ correlationId: "payment", at }] }, - held: [{ correlationId: "payment", at, request, approvalId: "approval" }], - ownerActions: [{ payment: { correlationId: "unknown" } }], - pending: [{ payment: { correlationId: "expired" }, expiresAt: "2000-01-01T00:00:00Z" }] }, new Map(), Date.parse(at)); - assert.deepEqual(records, [["payment", { at, request, approvalId: "approval" }], ["unknown", { at: "" }]]); - assert.ok(records.every(([, record]) => !("status" in record))); -}); - -test("invoices join discovery only through an actual provider correlation ID", () => { - const records = paymentRecords({ invoices: [ - { at, operation: { request } }, - { at, operation: { correlationId: "invoice-payment", request } }, - ], history: { items: [{ correlationId: "invoice-payment", at }] } }, new Map(), 0); - assert.deepEqual(records, [["invoice-payment", { at, request }]]); - assert.ok(records.every(([, record]) => !("status" in record)), "invoice discovery does not prove settlement"); -}); - -test("current held details take priority over retained invoice terms", () => { - const heldRequest = { ...request, amount: "2000000" }; - const records = paymentRecords({ invoices: [{ at, operation: { correlationId: "invoice-payment", request } }], - held: [{ correlationId: "invoice-payment", at, request: heldRequest, approvalId: "approval" }] }, new Map(), 0); - assert.deepEqual(records, [["invoice-payment", { at, request: heldRequest, approvalId: "approval" }]]); -}); diff --git a/test/planning-valuation.test.ts b/test/planning-valuation.test.ts index b2ebeb9..e5e1b7a 100644 --- a/test/planning-valuation.test.ts +++ b/test/planning-valuation.test.ts @@ -212,10 +212,10 @@ test("dispatch values and authorizes against one clock observation after provide prices = () => timedPrices(Object.entries(ASSETS).map(([symbol, asset_id]) => ({ symbol, asset_id, decimals: 0, price: 1 })), observedAt); await withMoneyLock(lock => dispatch(lock, "rebalance", { method: "swap", request: { origin_asset: input, destination_asset: output, amount: "5", min_amount_out: "5", confidential: true, - } }, { planned: { plan, leg: plan.actions[0]! }, autopilot: true, now: () => { + } }, { sending: { planned: { plan, leg: plan.actions[0]! }, autopilot: true, now: () => { clockReads++; return new Date(observedAt); - } })); + } } })); assert.equal(clockReads, 1); assert.deepEqual(sends, ["swap"]); assert.equal(readOps()[0]?.usdIn, 5, "journal valuation uses the authorization clock, not wall time"); diff --git a/test/proposal-access.test.ts b/test/proposal-access.test.ts deleted file mode 100644 index f414a92..0000000 --- a/test/proposal-access.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { QueryClient } from "@tanstack/react-query"; -import type { Decoded } from "../src/gateway/proposals.js"; - -test("late shared-DAO proposal reads cannot put denied-agent payloads back in the query cache", async () => { - Object.defineProperty(globalThis, "location", { value: { pathname: "/" }, configurable: true }); - // Load browser modules after supplying their location; no browser or network is involved. - const { gatewayQueries, redactProposalCaches } = await import(new URL("../web/src/app/queries.ts", import.meta.url).href); - const { reportAccessDenial, onAccessDenial, visibleProposals } = await import(new URL("../web/src/shared/access.ts", import.meta.url).href); - const proposals: Decoded[] = ["denied", "healthy"].map((agent, id) => ({ - id, agent, what: "agent", type: "policy_update", correlationId: agent, expiresAt: "2099-01-01T00:00:00Z", - state: "waiting", hash: agent, status: "InProgress", proposer: "owner.near", description: "", - submittedAt: "2026-01-01T00:00:00Z", votes: {}, - check: { kind: "verified", standard: "nep413", message: { private: agent } }, - })); - const client = new QueryClient(); - const cached = ["gw", "proposals", "cached.near"]; - client.setQueryData(cached, proposals); - client.setQueryData(["sibling", "healthy"], { allowed: true }); - const stop = onAccessDenial((denial: { scope: string }) => { - if (denial.scope !== "procedure") redactProposalCaches(client); - }); - const originalFetch = globalThis.fetch; - let finish!: (response: Response) => void; - let started!: () => void; - const requested = new Promise(resolve => { started = resolve; }); - globalThis.fetch = async () => { started(); return new Promise(resolve => { finish = resolve; }); }; - try { - const forbidden = gatewayQueries.proposals("forbidden.near"); - client.setQueryData(forbidden.queryKey, [proposals[1]]); - const waitingFetch = globalThis.fetch; - globalThis.fetch = async () => Response.json({ error: "Proposal access denied", access: "procedure" }, { status: 403 }); - await assert.rejects(client.fetchQuery(forbidden), /Proposal access denied/); - globalThis.fetch = waitingFetch; - const options = gatewayQueries.proposals("shared.near"); - const pending = client.fetchQuery(options); - void pending.catch(() => {}); // Keep failure cleanup from reporting a second cancellation error. - await requested; - reportAccessDenial({ base: "/a/denied", scope: "agent", message: "Access denied" }); - assert.equal(client.getQueryState(forbidden.queryKey)?.status, "error", "another agent denial must not clear an existing proposal denial"); - assert.match(String(client.getQueryState(forbidden.queryKey)?.error), /Proposal access denied/); - assert.deepEqual(client.getQueryData(cached), [proposals[1]], "previously cached private payloads are removed immediately"); - assert.deepEqual(visibleProposals(proposals), [proposals[1]], "render-time consumers use the current denial"); - assert.deepEqual(client.getQueryData(["sibling", "healthy"]), { allowed: true }); - finish(Response.json(proposals)); - assert.deepEqual(await pending, [proposals[1]], "late successful reads must exclude the denied payload"); - assert.deepEqual(client.getQueryData(options.queryKey), [proposals[1]], "the shared cache retains the healthy sibling only"); - reportAccessDenial({ base: "", scope: "procedure", message: "Procedure denied" }); - assert.deepEqual(client.getQueryData(cached), [proposals[1]], "procedure denials preserve permitted sibling reads"); - let releaseSession!: (response: Response) => void; - let sessionStarted!: () => void; - const sessionRequested = new Promise(resolve => { sessionStarted = resolve; }); - globalThis.fetch = async () => { sessionStarted(); return new Promise(resolve => { releaseSession = resolve; }); }; - const sessionPending = client.fetchQuery(gatewayQueries.proposals("session.near")); - await sessionRequested; - reportAccessDenial({ base: "", scope: "session", message: "Session expired" }); - assert.deepEqual(client.getQueryData(cached), []); - releaseSession(Response.json(proposals)); - assert.deepEqual(await sessionPending, [], "late successful reads cannot restore any proposal after session expiry"); - } finally { - stop(); - globalThis.fetch = originalFetch; - client.clear(); - Reflect.deleteProperty(globalThis, "location"); - } -}); diff --git a/test/provider-values.test.ts b/test/provider-values.test.ts index 9e159d1..4d1888e 100644 --- a/test/provider-values.test.ts +++ b/test/provider-values.test.ts @@ -3,7 +3,6 @@ import { test } from "node:test"; import { AgentApiError } from "@near-intents-agent-api/sdk"; import { displayedUsd, priceState, totalUsd } from "../src/valuation.js"; import { paymentEvidence, refusalDetails } from "../src/provider-display.js"; -import { errorMessage, providerDetailText } from "../web/src/shared/provider-message.js"; const now = Date.parse("2026-10-14T12:00:00Z"); const fresh = { price: 2, priceUpdatedAt: "2026-10-14T11:59:00Z", priceExpiresAt: "2026-10-14T12:01:00Z", decimals: 6, public: "1000000", confidential: "2000000" }; @@ -35,15 +34,6 @@ test("provider metadata is bounded and allowlisted, never inferred from other er assert.deepEqual(refusalDetails(error("policy_change_throttled", { available_at: "tomorrow" })), {}); }); -test("refusal copy preserves sub-cent values and gives no retry authorization", () => { - const details = { budgetRemainingUsd: "0.000001", availableAt: "2030-01-01T00:00:00Z" }; - const text = errorMessage(Object.assign(new Error("Budget exceeded"), { data: details })); - assert.match(text, /0\.000001 USD/); - assert.match(text, /Check the current state/); - assert.doesNotMatch(text, /Try again|safe to|nothing moved/); - assert.match(providerDetailText({ budgetRemainingUsd: "0" }), /0 USD/); -}); - test("malformed evidence and arbitrary provider fields are not forwarded", () => { const empty = { txHash: null, destinationTxHash: null, refundTxHash: null, refundTo: null, refundedAmount: null }; for (const value of [null, [], "bad", { tx_hash: 123, destination_tx_hash: "a".repeat(257), refund_tx_hash: "line\nbreak", refund_to: {}, refunded_amount: "1.5", secret: "token" }]) diff --git a/test/query-refresh.test.ts b/test/query-refresh.test.ts deleted file mode 100644 index 872e315..0000000 --- a/test/query-refresh.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { QueryClient } from "@tanstack/react-query"; -import { refreshQueries } from "../web/src/shared/query-refresh.js"; - -test("scoped refresh invalidates affected reads without invalidating unrelated provider observations", async () => { - const client = new QueryClient(); - for (const key of [["inbox"], ["inbox", "detail"], ["overview"], ["held"]]) client.setQueryData(key, {}); - await refreshQueries(client, [["inbox"]]); - assert.equal(client.getQueryState(["inbox"])?.isInvalidated, true); - assert.equal(client.getQueryState(["inbox", "detail"])?.isInvalidated, true); - assert.equal(client.getQueryState(["overview"])?.isInvalidated, false); - assert.equal(client.getQueryState(["held"])?.isInvalidated, false); - client.clear(); -}); - -test("previews can leave shared reads alone while default money-action refresh remains broad", async () => { - const client = new QueryClient(); - client.setQueryData(["overview"], {}); client.setQueryData(["held"], {}); - await refreshQueries(client, []); - assert.equal(client.getQueryState(["overview"])?.isInvalidated, false); - await refreshQueries(client); - assert.equal(client.getQueryState(["overview"])?.isInvalidated, true); - assert.equal(client.getQueryState(["held"])?.isInvalidated, true); - client.clear(); -}); diff --git a/test/review-regressions.test.ts b/test/review-regressions.test.ts index 69b5e4b..e2838b8 100644 --- a/test/review-regressions.test.ts +++ b/test/review-regressions.test.ts @@ -18,12 +18,3 @@ test("gateway approve-only survives an instance file requesting execution", () = assert.equal(result.stdout.trim(), "false\nfalse"); } finally { rmSync(dir, {recursive:true,force:true}); } }); - -const { paymentAssets } = await import(new URL("../web/src/features/payables/payment-assets.ts", import.meta.url).href); -const { ASSETS } = await import("../src/policy.js"); -const book = [{ asset: ASSETS.USDC, symbol: "USDC", decimals: 6, public: "0", confidential: "0", usd: 0, price: 1 }]; -test("payout choices exclude unsupported assets even when wNEAR is first", () => { - const all = [{ ...book[0], asset: ASSETS.wNEAR, symbol: "wNEAR" }, ...book]; - for (const label of ["payout", "invoices"]) assert.deepEqual(paymentAssets(all, label), book); - assert.deepEqual(paymentAssets(all, "treasury"), all); -}); diff --git a/test/viewer-access.test.ts b/test/viewer-access.test.ts deleted file mode 100644 index 3bfc38c..0000000 --- a/test/viewer-access.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { viewerOf, type GatewayViewer } from "../web/src/app/viewer.js"; - -const account: GatewayViewer = { account: "alice.near", access: { - treasury: { canSign: false, canPropose: true, canVote: true, canExecute: true, canManage: true }, - payables: { canSign: false, canPropose: false, canVote: false, canExecute: false, canManage: false }, -} }; - -test("workspace identity never inherits authority from one of its agents", () => { - const workspace = viewerOf(account, null); - assert.equal(workspace.account, account.account); - assert.equal(workspace.access, null); -}); - -test("selected-agent access cannot borrow another agent's permissions", () => { - assert.deepEqual(viewerOf(account, "payables"), { account: account.account, access: account.access.payables }); - const missing = viewerOf(account, "unknown"); - assert.equal(missing.access, null); -}); diff --git a/web/AGENTS.md b/web/AGENTS.md deleted file mode 100644 index f515767..0000000 --- a/web/AGENTS.md +++ /dev/null @@ -1,53 +0,0 @@ -# Frontend components - -The root `components.json` configures shadcn/ui with Radix Maia, Phosphor icons, -and the existing navy/blue palette. Run the CLI from the repository root. -`pnpm exec shadcn info --json` shows the installed components and resolved paths. - -## Component ownership - -- `src/components/ui/` contains the shadcn source and our product variants. -- `src/shared/ui.tsx` and `src/shared/form.tsx` preserve existing feature APIs. - Shared `Card` includes horizontal padding for its direct children; new composed - cards should import the primitive and use its header, content and footer slots. -- `src/styles.css` owns semantic colors, typography, radius and dark mode. - Use `cn` for class merging and variants for appearance. Keep `className` for layout. -- Forms compose `FieldGroup`, `Field`, labels and errors. Use `FieldSet` and - `FieldLegend` for related inputs. The shared `Field` keeps `className` on its wrapper. - -## Product requirements - -- Every button size and text input has a minimum 44px target. Small buttons reduce - horizontal padding, not the target height. Buttons default to `type="button"`; - form submission must be explicit. -- `--input` is the strong control border; `--input-surface` is the subtle fill. - Preserve visible keyboard focus and field-error associations in both themes. -- Badge variants retain neutral, success, warning, info and destructive meanings. - A held payout is not a completed payment. Status text must stay visible. -- Payment tables keep their local compact spacing. Shared cards use Maia spacing. -- Native review dialogs keep their snapshot, stale-review, cancellation and focus - behavior. Replacing a dialog requires the relevant payment-review regressions. - -## Updating components - -Use `pnpm exec shadcn docs ` before composing a new primitive. Preview -updates with `pnpm exec shadcn add --dry-run` and `--diff `; -merge upstream changes while retaining the product requirements above. - -Run `pnpm typecheck`, `pnpm test`, and the affected offline browser suites. -Root `AGENTS.md` governs money-path changes and live-system actions. - -## Prototype flows - -- Organize each view around one decision, its relevant context, and the resulting outcome. - Put the review context before the action in the mobile document order. -- Public pages explain each workflow and its status without simulated execution or approval. - Preserve legacy example links as static area overviews and keep the public import boundary - free of private reads and evidence. -- Use a visible single-selection ToggleGroup for short option sets, and NativeSelect - for longer native choices. Required selections must not clear on a repeated click. -- Keep status badges short; put full explanations and provider codes in wrapping text. - Native disclosures use 44px summaries. Supporting cards may use `size="sm"`. -- Live walkthroughs follow the exact returned payment or confirmed plan identifier. - Never choose the newest record as a substitute, or infer settlement from UI progress. - Preserve mounted confirmations and stream state through observation changes. diff --git a/web/src/app/queries.ts b/web/src/app/queries.ts deleted file mode 100644 index 56fa210..0000000 --- a/web/src/app/queries.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { queryOptions, type QueryClient } from "@tanstack/react-query"; -import { clientFor, gw } from "../shared/client"; -import type { Decoded } from "../../../src/gateway/proposals.js"; -import { loadGateway } from "./session"; -import { visibleProposals } from "../shared/access"; - -export function redactProposalCaches(client: QueryClient) { - for (const query of client.getQueryCache().findAll({ queryKey: ["gw", "proposals"] })) { - const data = query.state.data as Decoded[] | undefined; - // Redaction is not a successful read: keep existing denials, freshness and fetch state. - if (data) query.setState({ data: visibleProposals(data) }); - } -} - -/** A refused agent action cannot reuse stale capabilities while session refresh is pending or fails. */ -export function clearAgentCapabilities(client: QueryClient, base: string) { - const name = base.match(/^\/a\/([a-z0-9-]+)$/)?.[1]; - if (!name) return; - const query = client.getQueryCache().find({ queryKey: gatewayQueries.session.queryKey, exact: true }); - const data = query?.state.data as Awaited> | undefined; - if (!query || !data?.viewer?.access[name]) return; - // Keep membership, read caches and freshness; only a successful session read restores capabilities. - query.setState({ data: { ...data, viewer: { ...data.viewer, access: { ...data.viewer.access, - [name]: { canSign: false, canPropose: false, canVote: false, canExecute: false, canManage: false }, - } } } }); -} - -export const gatewayQueries = { - // The shell, sibling actions and invoice links observe one session. Later mounts retain the - // metadata refresh window; explicit denials invalidate this same snapshot immediately. - session: queryOptions({ queryKey: ["gateway"], queryFn: loadGateway, retry: false, staleTime: 60_000, refetchOnReconnect: false }), - proposals: (dao: string | undefined) => queryOptions({ queryKey: ["gw", "proposals", dao], - queryFn: async () => visibleProposals(await gw(`/gw/proposals?dao=${encodeURIComponent(dao!)}`)), enabled: Boolean(dao), refetchInterval: 15_000, - retry: (failures, error) => !["UNAUTHORIZED", "FORBIDDEN"].includes((error as { code?: string }).code ?? "") && failures < 3 }), - sibling: (name: string) => queryOptions({ queryKey: ["sibling", name], staleTime: 60_000, queryFn: async () => { - const api = clientFor(`/a/${name}`); - const [setup, overview] = await Promise.all([api.setup(), api.overview()]); - return { setup, overview }; - } }), -}; diff --git a/web/src/app/session.tsx b/web/src/app/session.tsx deleted file mode 100644 index cd55a14..0000000 --- a/web/src/app/session.tsx +++ /dev/null @@ -1,99 +0,0 @@ -import { SignIn as SignInIcon, SignOut } from "@phosphor-icons/react"; -import type { FrontendArea as Area } from "../../../src/contract/areas.js"; -import { useState } from "react"; -import { errorMessage, gw } from "../shared/lib"; -import { Button, Card, ErrorBox, Spinner } from "../shared/ui"; -import { type GatewayViewer, useViewer } from "./viewer"; -import { signChallenge, signOutMember } from "../shared/wallet"; - -/** An agent behind the gateway and the account it answers to; `dao` when that account is a DAO, signing by proposal. */ -export type GatewayAgent = { name: string; owner: string; dao: boolean; area?: Area; invoices?: string | null }; -/** The agent's area as the gateway reports it; an agent named "treasury" predates the reported area. */ -export const areaOf = (agent: GatewayAgent): Area => agent.area ?? (agent.name === "treasury" ? "treasury" : "payables"); -export type Gateway = { demo?: "showcase" | "payables" | "treasury" | "invoices"; agents: GatewayAgent[]; invoices: string | null; viewer: GatewayViewer | null; apps?: Partial>; walkthroughs?: boolean; selfService?: boolean; setupAreas?: Area[] }; - -/** The agents' owners, each once, in order. Signed out, the gateway lists only DAOs' agents, so these are DAOs. */ -export const ownersOf = (agents: GatewayAgent[]) => [...new Set(agents.map((a) => a.owner))]; - -/** - * The gateway's view of this visitor, or null when the page is served by a local agent server, which - * answers /gw/me with the page itself. An error from a gateway, or from the proxy in front of it, - * throws: a hosted page must never fall back to the trusted local view on loopback. - */ -export async function loadGateway(): Promise { - const response = await fetch(/\/access\/?$/.test(location.pathname) ? "/gw/access-session" : "/gw/me"); - if (!response.headers.get("content-type")?.includes("application/json")) { - if (response.ok) return null; - // A proxy's error page in front of a gateway that is down, not a local server. - throw new Error(`The dashboard answered ${response.status}.`); - } - const body = (await response.json()) as Gateway & { error?: string }; - if (!response.ok) throw new Error(body.error ?? `The dashboard answered ${response.status}`); - return body; -} - -export async function signOut() { - await fetch("/gw/logout", { method: "POST" }); - await signOutMember().catch(() => {}); - location.assign("/"); -} - -export function SignIn({ daos, compact = false, selfService = false }: { daos: string[]; compact?: boolean; selfService?: boolean }) { - const [busy, setBusy] = useState(false); - const [error, setError] = useState(); - const signIn = async () => { - setBusy(true); - setError(undefined); - try { - const challenge = await gw<{ message: string; recipient: string; nonce: string }>("/gw/challenge"); - await gw("/gw/session", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify(await signChallenge(challenge)), - }); - // Back to the page they asked for: signed out, any address shows the public page in its place. - // A reload, not assign: assigning a URL with a hash is a fragment navigation and loads nothing. - location.reload(); - } catch (e) { - setError(errorMessage(e)); - setBusy(false); - } - }; - const action = <> - - {busy ? "Complete sign-in in your NEAR wallet." : ""} - - ; - if (compact) return
{action}
; - return ( - -
-

{selfService ? "Sign in to get started" : "Members"}

-

- {selfService ? "Sign in with your regular NEAR wallet. You can then create an agent owned by that wallet, or select a DAO through Trezu using your member account." : <>Sign in with the NEAR wallet that owns an agent here{daos.length > 0 && `, or as a member of ${daos.join(" or ")}`}.} Signing in sends nothing on chain. -

-
- {action} -
- ); -} - -export function ViewerBadge() { - const viewer = useViewer(); - if (!viewer) return null; - return ( -
-
- - {viewer.account} - - Signed in -
- -
- ); -} diff --git a/web/src/app/viewer.ts b/web/src/app/viewer.ts deleted file mode 100644 index 8f380a1..0000000 --- a/web/src/app/viewer.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { createContext, useContext } from "react"; -import type { Access } from "../../../src/gateway/roles.js"; -import { mayCall } from "../../../src/gateway/allowlist.js"; - -/** - * Who is looking, when the dashboard is hosted behind the gateway (src/gateway). Locally there is - * no gateway and no viewer: the trusted local session can do everything. - */ -export type { Access }; -/** The gateway's answer: the signed-in account and its access to each agent it may see. */ -export type GatewayViewer = { account: string; access: Record }; -/** Identity is shared across the workspace. Authority always belongs to the selected agent. */ -export type Viewer = { account: string; access: Access | null }; - -export function viewerOf({ account, access }: GatewayViewer, agent: string | null): Viewer { - return { account, access: agent !== null ? access[agent] ?? null : null }; -} - -/** The hosted viewer; null locally. */ -export const ViewerContext = createContext(null); -export const useViewer = () => useContext(ViewerContext); - -/** Authority for one RPC on the selected agent. The gateway enforces the same rule. */ -export const useCanCall = (path: string) => { - const viewer = useViewer(); - return viewer === null || (viewer.access !== null && mayCall(viewer.access, path)); -}; diff --git a/web/src/components/ui/empty.tsx b/web/src/components/ui/empty.tsx deleted file mode 100644 index ce4b35a..0000000 --- a/web/src/components/ui/empty.tsx +++ /dev/null @@ -1,103 +0,0 @@ -import { cva, type VariantProps } from "class-variance-authority" -import { cn } from "cn" - -function Empty({ className, ...props }: React.ComponentProps<"div">) { - return ( -
- ) -} - -function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) { - return ( -
- ) -} - -const emptyMediaVariants = cva( - "flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0", - { - variants: { - variant: { - default: "bg-transparent", - icon: "flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg:not([class*='size-'])]:size-6", - }, - }, - defaultVariants: { - variant: "default", - }, - } -) - -function EmptyMedia({ - className, - variant = "default", - ...props -}: React.ComponentProps<"div"> & VariantProps) { - return ( -
- ) -} - -function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) { - return ( -
- ) -} - -function EmptyDescription({ className, ...props }: React.ComponentProps<"div">) { - return ( -
a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary", - className - )} - {...props} - /> - ) -} - -function EmptyContent({ className, ...props }: React.ComponentProps<"div">) { - return ( -
- ) -} - -export { - Empty, - EmptyHeader, - EmptyTitle, - EmptyDescription, - EmptyContent, - EmptyMedia, -} diff --git a/web/src/components/ui/input.tsx b/web/src/components/ui/input.tsx deleted file mode 100644 index ab793eb..0000000 --- a/web/src/components/ui/input.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import * as React from "react" -import { cn } from "cn" - -/** Shared with native controls until their existing forms adopt Input. */ -const inputStyles = - "h-11 min-w-0 rounded-4xl border border-input bg-input-surface/30 px-4 text-sm text-foreground transition-colors placeholder:text-muted-foreground focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive" - -function Input({ className, type, ...props }: React.ComponentProps<"input">) { - return ( - - ) -} - -export { Input, inputStyles } diff --git a/web/src/components/ui/skeleton.tsx b/web/src/components/ui/skeleton.tsx deleted file mode 100644 index 612df2d..0000000 --- a/web/src/components/ui/skeleton.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { cn } from "cn" - -function Skeleton({ className, ...props }: React.ComponentProps<"div">) { - return ( -
- ) -} - -export { Skeleton } diff --git a/web/src/features/activity/queries.ts b/web/src/features/activity/queries.ts deleted file mode 100644 index 75825bd..0000000 --- a/web/src/features/activity/queries.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { queryOptions } from "@tanstack/react-query"; -import type { QuerySource } from "../../shared/query-source"; - -export function activityQueriesFor(api: QuerySource, key: (local: string[], fleet?: string) => readonly string[]) { - return { - unresolved: queryOptions({ queryKey: key(["unresolved"]), queryFn: () => api.unresolved(), refetchInterval: 30_000 }), - activity: queryOptions({ queryKey: key(["activity"]), queryFn: () => api.activity() }), - }; -} diff --git a/web/src/features/evidence/beats.ts b/web/src/features/evidence/beats.ts deleted file mode 100644 index 2da060d..0000000 --- a/web/src/features/evidence/beats.ts +++ /dev/null @@ -1,7 +0,0 @@ -// Canonical requirements and evidence; do not maintain a second inventory here. -export * from "../../../../evidence/inventory.js"; - -import type { Kind } from "../../../../evidence/inventory.js"; - -/** Product labels only; requirement names and evidence remain canonical. */ -export const AREA_NAMES: Record = { facilitator: "Payables", treasury: "Portfolio" }; diff --git a/web/src/features/owner/owner-observation.ts b/web/src/features/owner/owner-observation.ts deleted file mode 100644 index e52f0d8..0000000 --- a/web/src/features/owner/owner-observation.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** Observes an existing intent only. It never prepares, signs, or submits one. */ -export type OwnerObservation = { stage: string; status?: string; failureCode?: string | null; error?: string }; -export async function observeOwnerAction( - read: (signal: AbortSignal) => Promise, signal: AbortSignal, - onObservation: (state: T) => void = () => {}, intervalMs = 5_000, -): Promise { - while (true) { - signal.throwIfAborted(); - const state = await read(signal); - signal.throwIfAborted(); - onObservation(state); - if (!["voting", "submitting"].includes(state.stage)) return state; - await new Promise((resolve, reject) => { - const abort = () => { clearTimeout(timer); reject(signal.reason); }; - const timer = setTimeout(() => { signal.removeEventListener("abort", abort); resolve(); }, intervalMs); - signal.addEventListener("abort", abort, { once: true }); - if (signal.aborted) abort(); - }); - } -} - -export function ownerActionState(records: T[]) { - return { - records, - recovering: records.find(a => a.stage === "prepared" || a.stage === "submitted"), - succeeded: records.find(a => a.ownerSucceeded), - }; -} diff --git a/web/src/features/owner/queries.ts b/web/src/features/owner/queries.ts deleted file mode 100644 index 148bfd4..0000000 --- a/web/src/features/owner/queries.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { queryOptions } from "@tanstack/react-query"; -import type { QuerySource } from "../../shared/query-source"; - -export function ownerQueriesFor(api: QuerySource, key: (local: string[], fleet?: string) => readonly string[]) { - return { - ownerActions: queryOptions({ queryKey: key(["owner", "actions"]), queryFn: () => api.owner.actions(), refetchInterval: 5_000, retry: false }), - ownerPending: queryOptions({ queryKey: key(["owner", "pending"]), queryFn: () => api.owner.pending(), refetchInterval: 5_000 }), - ownerStatus: (correlationId: string) => queryOptions({ queryKey: key(["owner", "status", correlationId]), queryFn: ({ signal }) => api.owner.status({ correlationId }, { signal }), retry: false }), - }; -} diff --git a/web/src/features/payables/payment-assets.ts b/web/src/features/payables/payment-assets.ts deleted file mode 100644 index b1c8e94..0000000 --- a/web/src/features/payables/payment-assets.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { ASSETS } from "../../../../src/policy"; -import type { Holding } from "../../shared/format"; - -/** Payout and invoice grants can transfer confidential USDC only. */ -export function paymentAssets(book: Holding[], label?: string) { - return label === "payout" || label === "invoices" ? book.filter(h => h.asset === ASSETS.USDC) : book; -} diff --git a/web/src/features/payables/payment-progress.ts b/web/src/features/payables/payment-progress.ts deleted file mode 100644 index ac71c04..0000000 --- a/web/src/features/payables/payment-progress.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { isMoving } from "./payment-status.js"; - -/** Owner intent evidence and provider payment outcomes are independent observations. */ -export function paymentProgress({ status, statusError, ownerError, approved, rejected, recovering }: { - status?: string; statusError: boolean; ownerError: boolean; approved: boolean; rejected: boolean; recovering?: string; -}) { - return { - owner: ownerError ? "Owner decision unavailable" : approved ? "Approval recorded" : rejected ? "Rejection recorded" - : recovering ? `Owner action ${recovering}` : "No owner decision confirmed", - outcome: statusError ? "Status unavailable" : status === "SUCCESS" ? "Paid" : status === "PENDING_APPROVAL" ? "Held for approval" - : isMoving(status) ? "Payment processing" : status === "FAILED" || status === "REFUNDED" ? `Provider reported ${status.toLowerCase()}` - : status ? "Outcome unresolved" : "Reading payment status…", - }; -} diff --git a/web/src/features/payables/payment-queue.ts b/web/src/features/payables/payment-queue.ts deleted file mode 100644 index c014b17..0000000 --- a/web/src/features/payables/payment-queue.ts +++ /dev/null @@ -1,118 +0,0 @@ -import type { PaymentRecord } from "./payment-records.js"; -import { isMoving, isSettled } from "./payment-status.js"; - -/** Already-read observations only. These fields never authorize or recover a payment. */ -export type QueueOperation = { - correlationId?: string; - idempotencyKey?: string; - request?: Record; - status?: string; - refused?: string; - submissionState?: string; -}; -export type QueueInvoice = { id: string; at: string; payee: string; review: boolean; operation: QueueOperation }; -export type QueueOwnerAction = { stage: string; payment?: { correlationId: string } | null }; -export type PaymentQueueEntry = { - id?: string; - at: string; - payment?: PaymentRecord; - invoice?: Invoice; - needsReview: boolean; - reason?: string; - /** Search metadata only; a local operation key is never a provider payment reference. */ - operationKeys?: readonly string[]; -}; -export type PaymentQueueSources = { - payments: readonly (readonly [string, PaymentRecord])[]; - invoices?: readonly Invoice[]; - activity?: readonly QueueOperation[]; - heldIds?: ReadonlySet; - pendingIds?: ReadonlySet; - ownerActions?: readonly QueueOwnerAction[]; -}; - -const outcome = (operation: QueueOperation) => operation.refused !== undefined - ? `refused:${operation.refused}` - : operation.submissionState === "PREPARED" ? "PREPARED" : operation.status ?? "UNKNOWN"; -const recordedTime = (at: string) => { - const time = Date.parse(at); - return Number.isFinite(time) ? time : undefined; -}; -const identity = (entry: PaymentQueueEntry) => entry.id ? `payment:${entry.id}` : `invoice:${entry.invoice?.id ?? ""}`; - -/** - * A conservative display filter, not a fresh settlement check. Identity-only history and owner - * signatures never establish an outcome. Conflicting retained sources remain visible for review. - * The caller supplies only accessible records and keeps read failures/partial coverage visible. - */ -export function buildPaymentQueue(sources: PaymentQueueSources): PaymentQueueEntry[] { - const invoices = sources.invoices ?? []; - const activities = new Map(); - for (const operation of sources.activity ?? []) { - if (!operation.correlationId) continue; - const records = activities.get(operation.correlationId) ?? []; - records.push(operation); - activities.set(operation.correlationId, records); - } - const recovering = new Map(); - for (const action of sources.ownerActions ?? []) { - if (action.payment && (action.stage === "prepared" || action.stage === "submitted")) - recovering.set(action.payment.correlationId, action.stage); - } - const entries = new Map>(); - for (const [id, payment] of sources.payments) - entries.set(`payment:${id}`, { id, at: payment.at, payment, needsReview: true }); - for (const invoice of invoices) { - const id = invoice.operation.correlationId; - const key = id ? `payment:${id}` : `invoice:${invoice.id}`; - const previous = entries.get(key); - entries.set(key, { ...previous, id, at: previous?.at || invoice.at, invoice, needsReview: true }); - } - - for (const entry of entries.values()) { - const { id, invoice } = entry; - const operations = [...(id ? activities.get(id) ?? [] : []), ...(invoice ? [invoice.operation] : [])]; - entry.operationKeys = [...new Set(operations.flatMap(operation => operation.idempotencyKey ? [operation.idempotencyKey] : []))]; - const outcomes = new Set(operations.map(outcome)); - const recovery = id ? recovering.get(id) : undefined; - if (invoice?.review) entry.reason = "Invoice changes need review"; - else if (invoice?.operation.submissionState === "PREPARED") entry.reason = "Prepared invoice; never submitted"; - else if (recovery) entry.reason = `Owner action ${recovery}`; - else if (id && sources.heldIds?.has(id)) entry.reason = "Held at last check"; - else if (id && sources.pendingIds?.has(id)) entry.reason = "Owner approval record needs review"; - else if (outcomes.size > 1) entry.reason = "Retained payment observations disagree"; - else if (outcomes.has("PENDING_APPROVAL")) entry.reason = "Held at last check"; - else if ([...outcomes].some(isMoving)) entry.reason = "Payment processing"; - else if (!operations.length || operations.some(operation => operation.refused === undefined && - (operation.submissionState === "PREPARED" || !isSettled(operation.status)))) - entry.reason = "Payment outcome unknown"; - else entry.needsReview = false; - } - - return [...entries.values()].sort((left, right) => { - if (left.needsReview !== right.needsReview) return left.needsReview ? -1 : 1; - const a = recordedTime(left.at), b = recordedTime(right.at); - // Unknown timing has no invented age; it follows dated records within the same group. - if (a === undefined && b !== undefined) return 1; - if (a !== undefined && b === undefined) return -1; - if (a !== undefined && b !== undefined && a !== b) return left.needsReview ? a - b : b - a; - const leftId = identity(left), rightId = identity(right); - return leftId < rightId ? -1 : leftId > rightId ? 1 : 0; - }); -} - -/** Local search over recorded recipient/reference fields; it never discovers or reads a payment. */ -export function filterPaymentQueue(queue: readonly Entry[], view: "review" | "all", query: string): Entry[] { - const term = query.trim().toLowerCase(); - return queue.filter(entry => { - if (view === "review" && !entry.needsReview) return false; - if (!term) return true; - const recipient = entry.payment?.request?.recipient; - const invoiceRecipient = entry.invoice?.operation.request?.recipient; - return [entry.id, entry.invoice?.id, entry.invoice?.payee, - typeof recipient === "string" ? recipient : undefined, - typeof invoiceRecipient === "string" ? invoiceRecipient : undefined, - entry.invoice?.operation.idempotencyKey, ...(entry.operationKeys ?? [])] - .some(value => value?.toLowerCase().includes(term)); - }); -} diff --git a/web/src/features/payables/payment-records.ts b/web/src/features/payables/payment-records.ts deleted file mode 100644 index 0114723..0000000 --- a/web/src/features/payables/payment-records.ts +++ /dev/null @@ -1,38 +0,0 @@ -/** Discovery and display only: a remembered request never proves approval or settlement. */ -export type PaymentRecord = { at: string; request?: Record; approvalId?: string }; -type Identity = { correlationId: string; at: string }; -type Sources = { - history?: { items: Identity[] }; - activity?: { correlationId?: string; at: string; request: Record }[]; - held?: (Identity & { request: Record; approvalId: string })[]; - ownerActions?: { payment: { correlationId: string } | null }[]; - pending?: { payment: { correlationId: string } | null; expiresAt: string }[]; - invoices?: { at: string; operation: { correlationId?: string; request: Record } }[]; -}; - -/** Independent sources may be absent. Never replace known terms with an identity-only observation. */ -export function paymentRecords(sources: Sources, remembered: ReadonlyMap, since: number): [string, PaymentRecord][] { - const known = new Map(remembered); - const merge = (id: string, value: PaymentRecord) => { - const previous = known.get(id); - known.set(id, { ...previous, ...value, at: value.at || previous?.at || "" }); - }; - for (const payment of sources.history?.items ?? []) merge(payment.correlationId, { at: payment.at }); - for (const action of sources.ownerActions ?? []) if (action.payment) merge(action.payment.correlationId, { at: "" }); - for (const pending of sources.pending ?? []) { - if (pending.payment && Date.parse(pending.expiresAt) >= since) merge(pending.payment.correlationId, { at: "" }); - } - // An invoice's local identity and idempotency key are never provider payment references. - for (const invoice of sources.invoices ?? []) { - if (invoice.operation.correlationId) - merge(invoice.operation.correlationId, { at: invoice.at, request: invoice.operation.request }); - } - // Activity includes swaps and shields too. A transfer's recorded request identifies its payee. - for (const operation of sources.activity ?? []) { - if (operation.correlationId && typeof operation.request.recipient === "string") - merge(operation.correlationId, { at: operation.at, request: operation.request }); - } - for (const payment of sources.held ?? []) - merge(payment.correlationId, { at: payment.at, request: payment.request, approvalId: payment.approvalId }); - return [...known].sort(([a, left], [b, right]) => right.at.localeCompare(left.at) || a.localeCompare(b)); -} diff --git a/web/src/features/payables/payment-stages.test.ts b/web/src/features/payables/payment-stages.test.ts deleted file mode 100644 index 9f69f40..0000000 --- a/web/src/features/payables/payment-stages.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { paymentStages } from "./payment-stages.js"; - -const unknown = { heldEvidence: false, approved: false, rejected: false, paid: false, failed: false, isHeld: false }; -test("settlement does not manufacture held or owner-approval evidence", () => { - const stage = paymentStages({ ...unknown, paid: true, s: "SUCCESS" }); - assert.equal(stage(1), "unverified"); - assert.equal(stage(2), "unverified"); - assert.equal(stage(3), "unverified"); - assert.equal(stage(4), "complete"); -}); -test("a successful owner decision does not establish payment completion", () => { - const stage = paymentStages({ ...unknown, approved: true, heldEvidence: true, isHeld: true, s: "PENDING_APPROVAL" }); - assert.equal(stage(3), "complete"); - assert.equal(stage(4), "upcoming"); -}); -test("an attempted owner action stays in progress and failed payment stays separate", () => { - const stage = paymentStages({ ...unknown, recovering: { stage: "submitted" }, failed: true, s: "FAILED" }); - assert.equal(stage(3), "current"); - assert.equal(stage(4), "stopped"); -}); - -test("a DAO proposal that ended without approval stops the vote stage instead of reading as still voting", () => { - for (const status of ["Rejected", "Removed", "Expired"]) - assert.equal(paymentStages({ ...unknown, proposal: { status } })(2), "stopped", status); - // Finalize can re-run a Failed proposal; a status not known to end it stays open. - for (const status of ["InProgress", "Failed", "Moved", "Unrecognised"]) - assert.equal(paymentStages({ ...unknown, proposal: { status } })(2), "current", status); - assert.equal(paymentStages({ ...unknown, proposal: { status: "Approved" } })(2), "complete"); -}); - -test("a payment on its way reads as processing everywhere, as the payee's invoice reads it as paying", async () => { - const { paymentProgress } = await import("./payment-progress.js"); - const { buildPaymentQueue } = await import("./payment-queue.js"); - for (const status of ["PROCESSING", "QUEUED", "SENT"]) { - assert.equal(paymentProgress({ status, statusError: false, ownerError: false, approved: false, rejected: false }).outcome, "Payment processing", status); - const [held] = buildPaymentQueue({ payments: [["c", { at: "2026-01-01T00:00:00Z" } as never]], activity: [{ correlationId: "c", idempotencyKey: "k", status }] as never }); - assert.equal(held?.reason, "Payment processing", status); - } -}); - -test("a held payout is checked against its payee's newest agreed terms, as the server's termsFor picks them", async () => { - const { termsInForce } = await import("./payment-terms.js"); - const terms = (maxAmount: string) => ({ maxAmount, until: "2030-01-01T00:00:00Z" }); - // agreements/list answers newest first. - const listed = [ - { payee: "p.near", status: "declined", terms: terms("9") }, - { payee: "q.near", status: "agreed", terms: terms("8") }, - { payee: "p.near", status: "agreed", terms: terms("3") }, - { payee: "p.near", status: "requested" }, - { payee: "p.near", status: "filed", terms: terms("1") }, - ]; - assert.deepEqual(termsInForce(listed, "p.near"), terms("3")); - assert.equal(termsInForce(listed, "r.near"), undefined); -}); diff --git a/web/src/features/payables/payment-stages.ts b/web/src/features/payables/payment-stages.ts deleted file mode 100644 index 65e8615..0000000 --- a/web/src/features/payables/payment-stages.ts +++ /dev/null @@ -1,16 +0,0 @@ -export type PaymentStage = "complete" | "current" | "upcoming" | "stopped" | "unverified"; - -const ENDED_UNAPPROVED = new Set(["Rejected", "Removed", "Expired"]); - -/** Each stage requires its own evidence; settlement never reconstructs an owner decision. */ -export function paymentStages({ heldEvidence, proposal, approved, rejected, recovering, paid, failed, s, isHeld }: { heldEvidence: boolean; proposal?: { status: string }; approved: boolean; rejected: boolean; recovering?: { stage: string }; paid: boolean; failed: boolean; s?: string; isHeld: boolean }) { - const step = (index: number): PaymentStage => { - if (index === 1) return heldEvidence ? "complete" : "unverified"; - // Rejected, Removed and Expired end a Sputnik proposal unapproved; Failed can be finalized again, and any other status isn't known to end it. - if (index === 2) return proposal ? (proposal.status === "Approved" ? "complete" : ENDED_UNAPPROVED.has(proposal.status) ? "stopped" : "current") - : approved || rejected ? "complete" : "unverified"; - if (index === 3) return rejected ? "stopped" : approved ? "complete" : recovering?.stage === "submitted" ? "current" : "unverified"; - return paid ? "complete" : failed ? "stopped" : s && !isHeld ? "current" : "upcoming"; - }; - return step; -} diff --git a/web/src/features/payables/payment-status.ts b/web/src/features/payables/payment-status.ts deleted file mode 100644 index d127021..0000000 --- a/web/src/features/payables/payment-status.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { isTerminal } from "../../../../src/operation-status.js"; - -/** - * Provider payment statuses, read as the server reads them: settled as both operation stores do - * (src/operation-status.ts), on its way as the payee's invoice reads it (src/invoices.ts `fromApi`, "paying"). SENT is - * recorded once a submission was accepted, before the first provider read. - */ -const MOVING = new Set(["PROCESSING", "QUEUED", "SENT"]); - -/** The provider reported how it ended; nothing later changes it. */ -export const isSettled = (status: string | undefined) => status !== undefined && isTerminal(status); -/** On its way: says nothing yet about how it ends. */ -export const isMoving = (status: string | undefined) => MOVING.has(status ?? ""); diff --git a/web/src/features/payables/payment-terms.ts b/web/src/features/payables/payment-terms.ts deleted file mode 100644 index 073c0c5..0000000 --- a/web/src/features/payables/payment-terms.ts +++ /dev/null @@ -1,8 +0,0 @@ -type Terms = { maxAmount: string; until: string }; - -/** - * The terms a voter checks a held payout against: the payee's newest agreement with terms that isn't declined, as - * src/agreements.ts `termsFor` picks them. `agreements` is `agreements/list`'s answer, newest first. - */ -export const termsInForce = (agreements: readonly A[], payee: string) => - agreements.find((a) => a.payee === payee && a.terms && a.status !== "declined")?.terms; diff --git a/web/src/features/payables/queries.ts b/web/src/features/payables/queries.ts deleted file mode 100644 index db6bfaa..0000000 --- a/web/src/features/payables/queries.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { queryOptions } from "@tanstack/react-query"; -import type { QuerySource } from "../../shared/query-source"; - -export function payablesQueriesFor(api: QuerySource, key: (local: string[], fleet?: string) => readonly string[]) { - return { - invoices: queryOptions({ queryKey: key(["invoices"]), queryFn: () => api.invoices(), refetchInterval: 15_000 }), - paymentStatus: (correlationId: string | undefined) => queryOptions({ queryKey: key(["paymentStatus", correlationId ?? ""]), queryFn: ({ signal }) => api.paymentStatus({ correlationId: correlationId! }, { signal }), enabled: Boolean(correlationId), retry: false }), - held: queryOptions({ queryKey: key(["held"]), queryFn: () => api.held(), refetchInterval: 15_000 }), - agreements: queryOptions({ queryKey: key(["agreements"]), queryFn: () => api.agreements.list(), refetchInterval: 30_000 }), - paymentHistory: queryOptions({ queryKey: key(["paymentHistory"]), queryFn: ({ signal }) => api.paymentHistory(undefined, { signal }), refetchInterval: 30_000, retry: false }), - }; -} diff --git a/web/src/shared/access.ts b/web/src/shared/access.ts deleted file mode 100644 index c1f8be2..0000000 --- a/web/src/shared/access.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { useSyncExternalStore } from "react"; -import type { Decoded } from "../../../src/gateway/proposals.js"; - -export type AccessDenial = { base: string; scope: "session" | "agent" | "procedure"; message: string }; -type AccessState = { session?: AccessDenial; agents: Readonly> }; -let state: AccessState = { agents: {} }; -const listeners = new Set<() => void>(); -const handlers = new Set<(denial: AccessDenial) => void>(); - -/** An explicit gateway denial hides private observations before its permission refresh returns. */ -export function reportAccessDenial(denial: AccessDenial) { - if (denial.scope === "session") { - if (state.session) return; - state = { ...state, session: denial }; - } else if (denial.scope === "agent") { - if (state.agents[denial.base]) return; - state = { ...state, agents: { ...state.agents, [denial.base]: denial } }; - } - for (const listener of listeners) listener(); - for (const handler of handlers) handler(denial); -} - -export const onAccessDenial = (handler: (denial: AccessDenial) => void) => { - handlers.add(handler); - return () => { handlers.delete(handler); }; -}; -export const useAccessState = () => useSyncExternalStore(listener => { - listeners.add(listener); - return () => { listeners.delete(listener); }; -}, () => state); -export const deniedAt = (snapshot: AccessState, base: string) => snapshot.session ?? snapshot.agents[base]; - -/** The same latched denial filters cached rows, render-time reads and responses arriving later. */ -export function visibleProposals(proposals: readonly Decoded[], snapshot: AccessState = state): Decoded[] { - if (snapshot.session) return []; - return proposals.filter(p => p.what !== "agent" || !deniedAt(snapshot, `/a/${p.agent}`)); -} - -/** Reloading checks the session and starts fresh caches; no owner action or payment is retried. */ -export const recheckAccess = () => location.reload(); diff --git a/web/src/shared/action-hooks.ts b/web/src/shared/action-hooks.ts deleted file mode 100644 index 565eb8b..0000000 --- a/web/src/shared/action-hooks.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { useEffect, useState } from "react"; -import { useQueryClient, type QueryKey } from "@tanstack/react-query"; -import { errorMessage } from "./provider-message"; -import { refreshQueries } from "./query-refresh"; - -/** Seconds until `iso`, ticking while `iso` is set. */ -export function useCountdown(iso?: string) { - const [now, setNow] = useState(Date.now()); - useEffect(() => { - if (!iso) return; - const timer = setInterval(() => setNow(Date.now()), 1000); - return () => clearInterval(timer); - }, [iso]); - return iso ? Math.max(0, Math.round((new Date(iso).getTime() - now) / 1000)) : null; -} - -/** - * One action at a time with its outcome: `attempt` runs it, shows its message or its error, and - * refreshes affected reads on success or failure. Money actions default to refreshing every read. - */ -export function useAttempt(refreshKeys?: readonly QueryKey[]) { - const queryClient = useQueryClient(); - const [message, setMessage] = useState(); - const [error, setError] = useState(); - const [busy, setBusy] = useState(false); - /** Runs `work`; a string it returns is shown as its outcome. */ - async function attempt(work: () => Promise) { - setBusy(true); - setError(undefined); - setMessage(undefined); - try { - const outcome = await work(); - setMessage(typeof outcome === "string" && outcome ? outcome : undefined); - } catch (e) { - setError(errorMessage(e)); - } finally { - setBusy(false); - await refreshQueries(queryClient, refreshKeys); - } - } - return { message, error, busy, attempt }; -} diff --git a/web/src/shared/client.ts b/web/src/shared/client.ts deleted file mode 100644 index 9ef1c57..0000000 --- a/web/src/shared/client.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { createORPCClient, ORPCError } from "@orpc/client"; -import { RPCLink } from "@orpc/client/fetch"; -import type { RouterClient } from "@orpc/server"; -import type { Router } from "../../../src/router.js"; -import { reportAccessDenial } from "./access"; - -/** - * Where this agent's pages live: "" when a local agent server serves them, "/a/" behind the - * hosted gateway, which forwards that prefix's calls to the agent's own server. - */ -export const BASE = (location.pathname.match(/^\/a\/[a-z0-9-]+/)?.[0] ?? "") as "" | `/${string}`; - -/** A client for the agent server whose pages live at `base` (see BASE). */ -export const clientFor = (base: "" | `/${string}`): RouterClient => createORPCClient(new RPCLink({ - url: `${base}/rpc`, - async fetch(request, init) { - const response = await fetch(request, init); - // Gateway denials are plain HTTP responses, not encoded RPC errors. - if (response.status === 401 || response.status === 403) { - const body = await response.clone().json().catch(() => null); - // Preserve encoded RPC errors, including their messages and structured details. - if (typeof body?.json?.code !== "string") { - // Older gateways have no scope field. Their procedure denial must not revoke agent reads. - const scope = body?.access === "procedure" || body?.error === "Operators only" ? "procedure" - : body?.access === "session" || response.status === 401 ? "session" : "agent"; - reportAccessDenial({ base, scope, message: typeof body?.error === "string" ? body.error : "Access is no longer available." }); - throw new ORPCError(response.status === 401 ? "UNAUTHORIZED" : "FORBIDDEN", { - message: typeof body?.error === "string" ? body.error : undefined, - }); - } - } - return response; - }, -})); - -export const client = clientFor(BASE); - -/** One call to the hosted gateway's own API (`/gw/...`); its `{ error }` answer is thrown. */ -export async function gw(path: `/gw/${string}`, init?: RequestInit): Promise { - const response = await fetch(path, init); - const body = (await response.json().catch(() => ({}))) as T & { error?: string }; - if (!response.ok) { - const message = body.error ?? `${path}: ${response.status}`; - if (response.status === 401 || response.status === 403) { - reportAccessDenial({ base: "", scope: response.status === 401 ? "session" : "procedure", message }); - throw new ORPCError(response.status === 401 ? "UNAUTHORIZED" : "FORBIDDEN", { message }); - } - throw new Error(message); - } - return body; -} diff --git a/web/src/shared/form-validation.ts b/web/src/shared/form-validation.ts deleted file mode 100644 index 3c85048..0000000 --- a/web/src/shared/form-validation.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** Client-side feedback only. Server/provider authorization remains authoritative. */ -import { intentsAccount, validIntentsAccount } from "../../../src/intents-account.js"; - -export const payeeError = (value: string) => validIntentsAccount(intentsAccount(value)) - ? undefined : "Enter a NEAR Intents account or near.com address, for example nearcom:payee.near."; - -export const accountError = (value: string) => - /^(?=.{2,64}$)[a-z0-9]+(?:[._-][a-z0-9]+)*$/.test(value.trim()) ? undefined : "Enter a NEAR account, for example payee.near."; - -export const deadlineError = (value: string, now = Date.now()) => { - const date = new Date(`${value}T23:59:59.999Z`); - return /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value && date.getTime() > now - ? undefined : "Choose today or a later date. Terms end at 23:59:59 UTC."; -}; diff --git a/web/src/shared/format.ts b/web/src/shared/format.ts deleted file mode 100644 index 76c930d..0000000 --- a/web/src/shared/format.ts +++ /dev/null @@ -1,49 +0,0 @@ -import type { client } from "./client"; -import type { Kind } from "../features/evidence/beats"; -export { exactPayment, fromUnits } from "./payment-copy"; - -export type Overview = Awaited>; -export type Holding = Overview["book"][number]; - -/** Whether the policy lets the agent swap. The target allocation and rebalancing apply only then. */ -export const swaps = (data: Overview) => Boolean(data.policy.policy?.actions.includes("swap")); - -/** Configured area is stable across policy changes. Legacy servers retain their policy-based fallback. */ -export const kindOf = (data: Overview): Kind => data.area ? (data.area === "treasury" ? "treasury" : "facilitator") : (swaps(data) ? "treasury" : "facilitator"); - -export const units = (raw: bigint | string, decimals: number) => Number(raw) / 10 ** decimals; - -/** An account or id short enough for a badge: its head and tail, when it is longer than `max`. */ -export const short = (id: string, max = 20) => (id.length > max ? `${id.slice(0, 8)}…${id.slice(-6)}` : id); - -export const amount = (raw: bigint | string, h: Pick) => { - const n = units(raw, h.decimals); - const digits = n === 0 ? 0 : n < 1 ? 5 : n < 100 ? 3 : 2; - return `${n.toLocaleString("en-US", { maximumFractionDigits: digits })} ${h.symbol}`; -}; - -/** "1.5" at 6 decimals → "1500000"; null unless it is a positive decimal that fits. */ -export function toUnits(value: string, decimals: number) { - const match = /^(\d*)(?:\.(\d*))?$/.exec(value.trim()); - if (!match || (!match[1] && !match[2])) return null; - const [, whole = "", fraction = ""] = match; - if (fraction.length > decimals) return null; - const raw = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(fraction.padEnd(decimals, "0") || "0"); - return raw > 0n ? raw.toString() : null; -} - -export const usd = (n: number | string | null | undefined) => - n == null - ? "—" - : Number(n).toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 2 }); - -const relative = new Intl.RelativeTimeFormat("en", { numeric: "auto" }); -export function ago(iso: string) { - const seconds = (new Date(iso).getTime() - Date.now()) / 1000; - for (const [unit, size] of [["day", 86400], ["hour", 3600], ["minute", 60]] as const) - if (Math.abs(seconds) >= size) return relative.format(Math.round(seconds / size), unit); - return relative.format(Math.round(seconds), "second"); -} - -/** 125 seconds → "2:05". */ -export const minutesSeconds = (seconds: number) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; diff --git a/web/src/shared/lib.ts b/web/src/shared/lib.ts deleted file mode 100644 index bcfb1d7..0000000 --- a/web/src/shared/lib.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** Compatibility exports; implementations live with their responsibility. */ -export * from "./client"; -export * from "./format"; -export * from "./action-hooks"; -export { queries, APPROVAL_WINDOW_MS } from "./queries"; -export { errorMessage } from "./provider-message"; diff --git a/web/src/shared/payment-copy.ts b/web/src/shared/payment-copy.ts index 326946d..df88d96 100644 --- a/web/src/shared/payment-copy.ts +++ b/web/src/shared/payment-copy.ts @@ -1,6 +1,6 @@ import { ASSETS } from "../../../src/contract/assets.js"; -/** "1500000" at 6 decimals → "1.5", exactly: the inverse of `toUnits`. */ +/** "1500000" at 6 decimals → "1.5", exactly. */ export function fromUnits(raw: string, decimals: number) { const digits = raw.padStart(decimals + 1, "0"); const fraction = digits.slice(digits.length - decimals).replace(/0+$/, ""); diff --git a/web/src/shared/provider-message.ts b/web/src/shared/provider-message.ts deleted file mode 100644 index 978e5bc..0000000 --- a/web/src/shared/provider-message.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { RefusalDetails } from "../../../src/provider-display.js"; - -/** Metadata describes the provider's observation; a time never grants permission to repeat a payment. */ -export function providerDetailText(details?: RefusalDetails | null): string { - const parts: string[] = []; - if (typeof details?.budgetRemainingUsd === "string" && /^\d{1,12}(\.\d{1,18})?$/.test(details.budgetRemainingUsd)) - parts.push(`Provider-reported budget remaining: ${details.budgetRemainingUsd} USD.`); - if (typeof details?.availableAt === "string" && details.availableAt.length <= 40 && Number.isFinite(Date.parse(details.availableAt))) - parts.push(`Provider-reported availability: ${new Date(details.availableAt).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" })}. Check the current state before another action.`); - return parts.join(" "); -} - -export function errorMessage(error: unknown): string { - if (!(error instanceof Error)) return String(error); - const extra = providerDetailText((error as Error & { data?: RefusalDetails }).data); - return extra ? `${error.message.replace(/\.?\s*$/, ".")} ${extra}` : error.message; -} diff --git a/web/src/shared/queries.ts b/web/src/shared/queries.ts deleted file mode 100644 index 92f1247..0000000 --- a/web/src/shared/queries.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { activityQueriesFor } from "../features/activity/queries"; -import { ownerQueriesFor } from "../features/owner/queries"; -import { payablesQueriesFor } from "../features/payables/queries"; -import { queryOptions } from "@tanstack/react-query"; -import { client, type clientFor } from "./client"; - -/** Scope is [] inside an isolated agent document, or ["fleet", name] on shared pages. */ -export function queriesFor(api: ReturnType, scope: readonly string[] = []) { - const key = (local: string[], fleet = local.join("-")) => scope.length ? [...scope, fleet] : local; - return { - ...payablesQueriesFor(api, key), - ...ownerQueriesFor(api, key), - ...activityQueriesFor(api, key), - setup: queryOptions({ queryKey: key(["setup"]), queryFn: () => api.setup(), retry: false }), - overview: queryOptions({ queryKey: key(["overview"]), queryFn: () => api.overview(), refetchInterval: 30_000 }), - }; -} -export const queries = queriesFor(client); -export const APPROVAL_WINDOW_MS = 24 * 60 * 60_000; diff --git a/web/src/shared/query-refresh.ts b/web/src/shared/query-refresh.ts deleted file mode 100644 index c232613..0000000 --- a/web/src/shared/query-refresh.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { QueryClient, QueryKey } from "@tanstack/react-query"; - -/** Omitted scope refreshes all reads; an empty scope is for previews with no shared read changes. */ -export async function refreshQueries(client: QueryClient, keys?: readonly QueryKey[]) { - if (keys === undefined) { await client.invalidateQueries(); return; } - await Promise.all(keys.map(queryKey => client.invalidateQueries({ queryKey }))); -} diff --git a/web/src/shared/query-source.ts b/web/src/shared/query-source.ts deleted file mode 100644 index 4beeb5e..0000000 --- a/web/src/shared/query-source.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { clientFor } from "./client"; -export type QuerySource = ReturnType; diff --git a/web/src/shared/ui.tsx b/web/src/shared/ui.tsx index 0d393af..f227575 100644 --- a/web/src/shared/ui.tsx +++ b/web/src/shared/ui.tsx @@ -1,63 +1,17 @@ -import { Check, Copy } from "@phosphor-icons/react"; import type { ReactNode } from "react"; -import { useState } from "react"; import { Button } from "@/components/ui/button"; import { Badge as BadgePrimitive } from "@/components/ui/badge"; -import { Card as CardPrimitive, CardHeader as CardHeaderPrimitive, CardTitle, CardDescription } from "@/components/ui/card"; +import { Card as CardPrimitive } from "@/components/ui/card"; import { Alert, AlertDescription } from "@/components/ui/alert"; -import { Empty as EmptyPrimitive, EmptyContent, EmptyMedia } from "@/components/ui/empty"; -import { Skeleton } from "@/components/ui/skeleton"; import { cn } from "@/lib/utils"; export { Button }; -/** Native input/select callers share the same states as the Input component. */ -export { inputStyles as input } from "@/components/ui/input"; - -/** Maia surface only; native dialog focus and each review's authorization remain with the caller. */ -export const reviewDialog = - "m-auto max-h-[90dvh] w-[calc(100%-2rem)] max-w-md overflow-y-auto overscroll-contain rounded-4xl border-0 bg-popover p-6 text-popover-foreground ring-1 ring-foreground/5 backdrop:bg-black/80 backdrop:backdrop-blur-xs"; - export type Tone = "neutral" | "success" | "warning" | "info" | "destructive"; export function Badge({ tone = "neutral", children }: { tone?: Tone; children: ReactNode }) { return {children}; } -/** Settled operation statuses, mapped once so every list reads them the same way. */ -export const statusTone = (status: string | undefined): Tone => - status === "SUCCESS" - ? "success" - : status === "FAILED" || status === "REFUNDED" - ? "destructive" - : status - ? "warning" - : "neutral"; - -export function Section({ - title, - description, - action, - children, -}: { - title: string; - description?: string; - action?: ReactNode; - children: ReactNode; -}) { - return ( -
-
-
-

{title}

- {description &&

{description}

} -
- {action} -
- {children} -
- ); -} - export function Card({ className = "", size = "default", children }: { className?: string; size?: "default" | "sm"; children: ReactNode }) { // Existing feature cards contain direct children; keep their horizontal padding. return {children}; @@ -67,50 +21,6 @@ export function Spinner() { return ; } -/** - * One step of a numbered flow: the current step shows its body, a finished one collapses to a - * checked row with a one-line summary. - */ -export function Step({ - number, - title, - status, - summary, - last, - children, -}: { - number: number; - title: string; - status: "complete" | "current" | "upcoming"; - summary?: ReactNode; - last?: boolean; - children?: ReactNode; -}) { - return ( -
  • - {!last && } - - {status === "complete" ? : number} - -
    -
    -

    {title}

    - {status === "complete" && summary &&

    {summary}

    } -
    - {status === "current" && children} -
    -
  • - ); -} - /** Why an action failed, in the server's or wallet's words; nothing when it didn't. */ export function ErrorBox({ error }: { error?: string }) { return
    @@ -126,99 +36,3 @@ export function Loading({ label }: { label: string }) {

    ); } - -/** Reserve record space on an initial read; placeholders never represent known records. */ -export function LoadingRecords({ label, rows = 3 }: { label: string; rows?: number }) { - return
    -

    {label}

    - -
    ; -} - -/** A query that failed: the server's words, and a retry, so a failure never reads as "nothing here". */ -export function QueryError({ error, retry }: { error: { message: string }; retry: () => void }) { - return ( - - {error.message} - - - ); -} - -/** An operation's settled status, with the provider's failure code when it has one. */ -export function StatusBadge({ status, failureCode, children }: { status: string; failureCode?: string | null; children?: ReactNode }) { - return ( - - {children && {children}} - {status.toLowerCase()} - {failureCode && {failureCode}} - - ); -} - -export function CopyButton({ text }: { text: string }) { - const [busy, setBusy] = useState(false); - const [result, setResult] = useState<{ text: string; message: string }>(); - const message = result?.text === text ? result.message : ""; - const copy = async () => { - setBusy(true); - setResult(undefined); - try { - await navigator.clipboard.writeText(text); - setResult({ text, message: "Copied." }); - } catch { - setResult({ text, message: "Could not copy. Try again or copy the displayed text." }); - } finally { - setBusy(false); - } - }; - return ( - - - {message} - - ); -} - -/** Detail most readers skip, such as identifiers and rare controls, folded under a one-line summary. */ -export function Details({ summary, open, className = "", children }: { summary: string; open?: boolean; className?: string; children: ReactNode }) { - return ( -
    - {summary} -
    {children}
    -
    - ); -} - -/** A card's heading: its icon, title and what it does. */ -export function CardHeader({ icon, title, description }: { icon: ReactNode; title: string; description: string }) { - return ( - -
    {icon}
    -
    -

    {title}

    - {description} -
    -
    - ); -} - -/** Fills a card's body when there is nothing to list yet. */ -export function Empty({ icon, children }: { icon: ReactNode; children: ReactNode }) { - return ( - - - {children} - - ); -} diff --git a/web/src/shared/wallet.ts b/web/src/shared/wallet.ts index fa759c5..6e8fb68 100644 --- a/web/src/shared/wallet.ts +++ b/web/src/shared/wallet.ts @@ -3,19 +3,9 @@ import { type DataStorage, NearConnector } from "@fastnear/near-connect"; import { useSyncExternalStore } from "react"; type WalletState = { status: "idle" | "connecting" | "connected"; accountId?: string; publicKey?: string }; -export type Transaction = { - receiverId: string; - actions: ( - | { type: "FunctionCall"; params: { methodName: string; args: object; gas: string; deposit: string } } - | { type: "Transfer"; params: { deposit: string } } - )[]; -}; -/** - * One wallet connection as an external store: its account, connect and disconnect, and sending - * a transaction as that account. - */ -function walletSession(createConnector: () => NearConnector, walletId?: string) { +/** One wallet connection as an external store: its account, connect and disconnect. */ +function walletSession(createConnector: () => NearConnector) { let instance: NearConnector | undefined; const connector = () => { if (!instance) { @@ -43,7 +33,6 @@ function walletSession(createConnector: () => NearConnector, walletId?: string) return { get connector() { return connector(); }, - update, use: () => useSyncExternalStore( (listener) => { @@ -56,7 +45,7 @@ function walletSession(createConnector: () => NearConnector, walletId?: string) async connect() { update({ status: "connecting" }); try { - await connector().connect(walletId ? { walletId } : undefined); + await connector().connect(); } finally { await sync(); } @@ -65,13 +54,6 @@ function walletSession(createConnector: () => NearConnector, walletId?: string) await connector().disconnect(); update({ status: "idle" }); }, - /** Sends `transaction` as the connected account. Through Trezu that files it as a DAO proposal. */ - async send(transaction: Transaction) { - const { wallet, accounts } = await connector().getConnectedWallet(); - const signerId = accounts[0]?.accountId; - if (!signerId) throw new Error("Connect a wallet first"); - return wallet.signAndSendTransaction({ signerId, ...transaction }); - }, }; } @@ -98,36 +80,8 @@ const namespaced = (prefix: string): DataStorage => ({ remove: async (key) => localStorage.removeItem(`${prefix}:${key}`), }); -/** - * A DAO acting through Trezu, a second connection beside the owner's: it signs as the DAO by - * filing each transaction as a proposal its members vote on. - */ -export const dao = walletSession( - () => new NearConnector({ - network: "mainnet", - manifest: HOT_WALLETS, - storage: namespaced("dao"), - }), - "trezu-wallet", -); - export const useWallet = owner.use; -/** A member signing in to the hosted dashboard: a NEP-413 signature is all it needs. */ -const member = walletSession(() => new NearConnector({ network: "mainnet", features: { signMessage: true }, storage: namespaced("member") })); - -/** Signs the gateway's sign-in challenge with the member's wallet, connecting first. */ -export async function signChallenge({ message, recipient, nonce }: { message: string; recipient: string; nonce: string }) { - if ((await member.connector.getConnectedWallet().catch(() => null))?.accounts.length !== 1) await member.connect(); - const { wallet } = await member.connector.getConnectedWallet(); - const signed = await wallet.signMessage({ message, recipient, nonce: fromBase64(nonce) }); - // Some wallets also sign the page that asked as a callback URL, without saying so: offer the candidates. - const callbackUrls = [...new Set([`${location.origin}/`, location.href])]; - return { accountId: signed.accountId, publicKey: signed.publicKey, signature: signed.signature, nonce, callbackUrls }; -} - -export const signOutMember = () => member.disconnect(); - /** * A wallet owner's own stop (the confirm build's stop page): one NEP-413 signature is all it needs, so every wallet * that signs messages is offered, not only those that also sign delegate actions. Its session is apart from the owner's. @@ -158,35 +112,10 @@ export async function switchStopWallet() { await stopper.connect(); } -/** Sends a transaction from the signed-in member's own wallet, such as a DAO proposal they file. */ -export const sendAsMember = (transaction: Transaction) => member.send(transaction); export const connect = () => owner.connect(); -export const disconnect = () => owner.disconnect(); -export const send = (transaction: Transaction) => owner.send(transaction); const fromBase64 = (value: string) => Uint8Array.from(atob(value), (c) => c.charCodeAt(0)); -/** - * The connected account as an agent owner. Some wallets report the key only with a signature, - * so a missing key is read from a one-off signed message. - */ -export async function ownerWallet() { - const { wallet, accounts } = await owner.connector.getConnectedWallet(); - const [account] = accounts; - if (!account) throw new Error("Connect a wallet first"); - const publicKey = - account.publicKey ?? - ( - await wallet.signMessage({ - message: "Identify my key as the owner of an Agentic Treasury agent", - recipient: location.host, - nonce: crypto.getRandomValues(new Uint8Array(32)), - }) - ).publicKey; - owner.update({ status: "connected", accountId: account.accountId, publicKey }); - return { type: "near" as const, account_id: account.accountId, public_key: publicKey }; -} - /** Signs an owner intent's payload exactly as the API generated it, by the standard it chose. */ export async function signIntent(intent: Intent): Promise> { return signWith((await owner.connector.getConnectedWallet()).wallet, intent);