Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor: remove TinyPlace from core and app\n\n

Steven Enamakel93fb9e258e47
diff --git a/.env.example b/.env.example
index 03cd19f2d9..e9527cd996 100644
--- a/.env.example
+++ b/.env.example
@@ -292,18 +292,9 @@ OPENHUMAN_TELEGRAM_BOT_USERNAME=openhuman_bot
# Solana cluster the wallet broadcasts to: "mainnet" (default) or "devnet".
# Selects BOTH the default Solana RPC endpoint and the USDC SPL mint, so a
-# devnet x402 payment lands on devnet with the devnet mint. Pair with a staging
-# TINYPLACE_API_BASE_URL when testing tiny.place on devnet.
+# devnet x402 payment lands on devnet with the devnet mint.
# OPENHUMAN_SOLANA_CLUSTER=devnet
-# [optional] tiny.place's Solana settlement RPC. ONLY tiny.place payment
-# broadcasts use this (general wallet ops keep OPENHUMAN_WALLET_RPC_SOLANA): they
-# try this endpoint first and fall back to the public cluster RPC if it is
-# unreachable. Defaults to <TINYPLACE_API_BASE_URL>/solana/rpc
-# (i.e. https://api.tiny.place/solana/rpc), so it tracks prod/staging
-# automatically — set this only to point settlement at a different RPC.
-# TINYPLACE_SOLANA_RPC_URL=https://api.tiny.place/solana/rpc
-
# ---------------------------------------------------------------------------
# x402 Machine Payments
# ---------------------------------------------------------------------------
@@ -479,15 +470,6 @@ RUST_LOG=info
# [optional] Default: 0 (set to 1 for full backtraces)
RUST_BACKTRACE=1
-# ---------------------------------------------------------------------------
-# tiny.place Agent World integration
-# ---------------------------------------------------------------------------
-# [optional] Base URL for the tiny.place backend API.
-# When unset, the default follows OPENHUMAN_APP_ENV: a `staging` app env uses
-# https://staging-api.tiny.place, otherwise https://api.tiny.place (production).
-# Set this to pin an explicit host — it always overrides the app-env default.
-# TINYPLACE_API_BASE_URL=https://staging-api.tiny.place
-
# ---------------------------------------------------------------------------
# Testing (do not set in production)
# ---------------------------------------------------------------------------
diff --git a/.github/workflows/ci-lite.yml b/.github/workflows/ci-lite.yml
index 941f4b0d4c..61f0f86b07 100644
--- a/.github/workflows/ci-lite.yml
+++ b/.github/workflows/ci-lite.yml
@@ -614,7 +614,6 @@ jobs:
openhuman/memory/people/mod.rs
openhuman/platform/socket/event_handlers.rs
openhuman/platform/socket/ops.rs
- openhuman/tinyplace/manifest.rs
openhuman/tools/registry/ops_tests.rs
openhuman/tools/registry/schemas.rs
openhuman/tools/ops_tests.rs
diff --git a/.gitmodules b/.gitmodules
index a7c232daf1..2d3cffade1 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -10,9 +10,6 @@
[submodule "vendor/tinychannels"]
path = vendor/tinychannels
url = https://github.com/tinyhumansai/tinychannels
-[submodule "vendor/tinyplace"]
- path = vendor/tinyplace
- url = https://github.com/tinyhumansai/tiny.place.git
[submodule "vendor/tinyhumans-sdk"]
path = vendor/tinyhumans-sdk
url = https://github.com/tinyhumansai/sdk.git
diff --git a/AGENTS.md b/AGENTS.md
index 8bded59678..4ffeb0f389 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -172,7 +172,7 @@ No `UserProvider`/`AIProvider`/`SkillProvider` — auth lives in `CoreStateProvi
**Analytics**: use `Button analyticsId="stable-content-free-id"` for shared button interactions, `AnalyticsPageTracker` once inside the router, and `trackAnalyticsEvent` from `components/analytics` for successful domain outcomes (messages, automation runs, connections, etc.). Native controls and links may use `data-analytics-id` directly. Use privacy-safe dimensions only; never send user-authored text, entity IDs, filenames, credentials, or error messages. `services/analytics.ts` is the consent/provider implementation, not the feature-code API.
-**Routing** (`AppRoutes.tsx`, HashRouter): `/` (Welcome), `/auth`, `/onboarding/*`, `/chat/:threadId?`, `/human`, `/brain` (+ `/brain/tinyplace-orchestration`), `/orchestration`, `/connections`, `/flows` (+ `/flows/:id`, `/flows/draft`), `/agent-world/*`, `/invites`, `/notifications`, `/rewards`, `/settings/*`, `/feedback`. Back-compat redirects: `/home`→`/chat`, `/skills`→`/connections`, `/channels`→`/connections?tab=messaging`, `/intelligence` & `/activity`→`/settings/notifications`, `/routines` & `/workflows`→`/settings/automations`, `/webhooks`→`/settings/integrations#webhooks`. No `/login`, `/mnemonic`, `/agents`, `/conversations`.
+**Routing** (`AppRoutes.tsx`, HashRouter): `/` (Welcome), `/auth`, `/onboarding/*`, `/chat/:threadId?`, `/human`, `/brain`, `/connections`, `/flows` (+ `/flows/:id`, `/flows/draft`), `/invites`, `/notifications`, `/rewards`, `/settings/*`, `/feedback`. Back-compat redirects: `/home`→`/chat`, `/skills`→`/connections`, `/channels`→`/connections?tab=messaging`, `/intelligence` & `/activity`→`/settings/notifications`, `/routines` & `/workflows`→`/settings/automations`, `/webhooks`→`/settings/integrations#webhooks`. No `/login`, `/mnemonic`, `/agents`, `/conversations`.
**AI config**: bundled prompts in `src/openhuman/agent/prompts/` ship via `tauri.conf.json` resources and are read core-side (`app/src/lib/ai/` holds agent-context helpers, not prompt loaders).
@@ -419,7 +419,7 @@ two paths' equivalence — keep that as call sites migrate.
~31 domain directories — authoritative list: `ls -d src/openhuman/*/`. Major families: agent (`agent` — with `agent/{artifacts,context,experience,file_state,harness_init,learning,orchestration,plan_review,profiles,registry,session_db,session_import,tinyagents}`), memory (`memory` — with `memory/{agent,conversations,diff,goals,people,queue,search,sources,store,sync,tinycortex,tool_memory,tree}`), skills/flows (`skills` — with `skills/{catalog,runtime,webhooks}` —, `flows` — with `flows/{tinyflows,rhai}`), inference/AI (`inference` — with `inference/{embeddings,tokenjuice}` —, `routing`), MCP (`mcp` — with `mcp/{server,registry,audit,config_servers,http_client}`), runtimes (`runtime` — with `runtime/{node,python,python_server,pool,javascript}` —, `sandbox` — with `sandbox/cwd_jail`), channels (`channels`), web3 (`web3` — with `web3/{wallet,x402}`), plus kernel domains (`platform` — with `platform/{about_app,connectivity,cost,doctor,health,proc_metrics,service,socket,startup,update}` —, `config` — with `config/{migrations,migration_helpers,workspace}` —, `cron` — with `cron/scheduler_gate` —, `integrations`, `security` — with `security/{approval,credentials,keyring,keyring_consent,encryption,prompt_injection,devices}` —, `threads` — with `threads/{goals,todos}` —, `tools` — with `tools/{registry,status,timeout,agent_policy}` —, `util` — with `util/{text,retry,tls,types}` —, `voice`, …).
-**Family directories (in progress).** The flat tree is being collapsed so that **one directory equals one feature gate**: a capability spread across sibling top-level dirs costs a `#[cfg]` per dir plus five parallel registries to keep in sync. Landed so far (124 → 28 top-level dirs, 0 root-level `*.rs`): `util/` (incl. `util/sanitize`), `mcp/{server,registry,audit,config_servers,http_client}`, `sandbox/cwd_jail`, `cron/scheduler_gate`, `runtime/`, `media/`, `voice/audio_toolkit`, `web3/{wallet,x402}`, `medulla/chat`, `flows/{tinyflows,rhai}`, `desktop/` (accessibility, app_state, dashboard, notifications, overlay, provider_surfaces), `hosted/` (announcements, billing, orchestration, referral, team — all thin proxies to the TinyHumans backend), `threads/{goals,todos}`, `tools/{registry,status,timeout,agent_policy}`, `platform/` (about_app, connectivity, cost, doctor, health, proc_metrics, service, socket, startup, update), `config/{migrations,migration_helpers,workspace}`, `integrations/{composio,file_storage,task_sources}`, `skills/{catalog,runtime,webhooks}`, `inference/{embeddings,tokenjuice}`, `security/{approval,credentials,keyring,keyring_consent,encryption,prompt_injection,devices}` (the kernel security family — never gated), and `agent/{experience,orchestration,registry,harness_init,session_db,session_import,context,profiles,learning,plan_review,file_state,artifacts,tinyagents}` (the agent harness is kernel and is never gated; `agent/` stayed put as the parent rather than becoming `agent/core`, which would have cost ~999 extra import rewrites for no gate benefit), and `memory/{store,sync,tree,search,sources,queue,diff,goals,conversations,tool_memory,tinycortex,agent,people}` (the largest family, moved last; `memory/` stayed put as the parent — a `memory → memory/core` rename would have cost ~545 extra rewrites — with the pre-existing `memory/sync.rs` renamed to `memory/sync_events.rs` to free the name for `memory_sync`, and `memory_tools` landing as `memory/tool_memory` to avoid the pre-existing `memory/tools/` agent-tool directory). Plan, target tree, and move-PR rules: [`docs/specs/2026-08-02-core-kernel-domain-reorg.md`](docs/specs/2026-08-02-core-kernel-domain-reorg.md).
+**Family directories (in progress).** The flat tree is being collapsed so that **one directory equals one feature gate**: a capability spread across sibling top-level dirs costs a `#[cfg]` per dir plus five parallel registries to keep in sync. Landed so far (124 → 28 top-level dirs, 0 root-level `*.rs`): `util/` (incl. `util/sanitize`), `mcp/{server,registry,audit,config_servers,http_client}`, `sandbox/cwd_jail`, `cron/scheduler_gate`, `runtime/`, `media/`, `voice/audio_toolkit`, `web3/{wallet,x402}`, `medulla/chat`, `flows/{tinyflows,rhai}`, `desktop/` (accessibility, app_state, dashboard, notifications, overlay, provider_surfaces), `hosted/` (announcements, billing, referral, team — all thin proxies to the TinyHumans backend), `threads/{goals,todos}`, `tools/{registry,status,timeout,agent_policy}`, `platform/` (about_app, connectivity, cost, doctor, health, proc_metrics, service, socket, startup, update), `config/{migrations,migration_helpers,workspace}`, `integrations/{composio,file_storage,task_sources}`, `skills/{catalog,runtime,webhooks}`, `inference/{embeddings,tokenjuice}`, `security/{approval,credentials,keyring,keyring_consent,encryption,prompt_injection,devices}` (the kernel security family — never gated), and `agent/{experience,orchestration,registry,harness_init,session_db,session_import,context,profiles,learning,plan_review,file_state,artifacts,tinyagents}` (the agent harness is kernel and is never gated; `agent/` stayed put as the parent rather than becoming `agent/core`, which would have cost ~999 extra import rewrites for no gate benefit), and `memory/{store,sync,tree,search,sources,queue,diff,goals,conversations,tool_memory,tinycortex,agent,people}` (the largest family, moved last; `memory/` stayed put as the parent — a `memory → memory/core` rename would have cost ~545 extra rewrites — with the pre-existing `memory/sync.rs` renamed to `memory/sync_events.rs` to free the name for `memory_sync`, and `memory_tools` landing as `memory/tool_memory` to avoid the pre-existing `memory/tools/` agent-tool directory). Plan, target tree, and move-PR rules: [`docs/specs/2026-08-02-core-kernel-domain-reorg.md`](docs/specs/2026-08-02-core-kernel-domain-reorg.md).
A move never changes the wire surface — RPC namespaces are string literals in `ControllerSchema`, not derived from module paths — so **do not rename namespace strings to match new paths**.
@@ -433,10 +433,9 @@ UI rather than gated off, so there is no flag that brings them back:
| AgentBox | `agent/agentbox/`, the `agentbox` RPC namespace, the GMI MaaS provider bridge, the `AgentBoxPanel` settings page | Moved to [tinybox](https://github.com/tinyhumansai/tinybox). The unauthenticated `/run` and `/jobs/` routes left `core::auth`'s public-path list with it — `agentbox_run_and_jobs_paths_are_no_longer_public` pins that they stay authenticated. |
| Meetings | the `meet` Cargo gate and `openhuman::meet/` (join validation, live agent loop, backend bot), `MeetConfig`, the `meet`/`meet_agent`/`agent_meetings` namespaces, every `BackendMeet*`/`Meeting*` `DomainEvent`, the meetings UI, and `integrations/recall_calendar` (its only purpose was Meet auto-join) | `DomainGroup::Meet` is gone, so `DomainGroup::COUNT` dropped 23 → 22. The approval gate's in-call branch went with it — nothing set `APPROVAL_IN_CALL_CONTEXT` any more. |
| Subconscious | `openhuman::subconscious/` (engine, heartbeat, planner, monitors, triggers, user_thread), the `openhuman subconscious` CLI, the monitor + `notify_user` agent tools, the Brain/Activity subconscious tabs | `DomainGroup::Automation` now means cron alone. **`HeartbeatConfig` stays** — `threads::goals::continuation` reads `heartbeat.goal_continuation_enabled` / `goal_idle_minutes`, and **the `subconscious` provider role stays** because `agent::triage::routing` resolves its provider through it. |
+| TinyPlace | `openhuman::tinyplace/`, hosted orchestration, relay controllers/events/services, pairing support, the TinyPlace dependency and submodule, Agent World and Brain orchestration UI, routes, settings, tests, and documentation | The Medulla harness envelope is now core-owned. The security path denylist retains the legacy `tinyplace` directory name so upgraded workspaces cannot expose old private state to agent file tools. |
-Two things deliberately survived and should not be "cleaned up": the tiny.place
-orchestration surface still has a pinned **subconscious chat window**
-(`hosted/orchestration`, a different concept from the deleted domain), and
+One compatibility behavior deliberately survived and should not be "cleaned up":
`threadFilter`'s `MEETINGS_LABELS` still routes historical meeting-labelled
threads so existing user data does not leak into the General bucket.
@@ -451,27 +450,13 @@ not "the domain is gone", and only one of these took its domain with it:
| `people_*` | all 7 | `memory/tools/people.rs` deleted; the `people` RPC surface and `memory/people/` (address book, the `contacts` gate) stay. |
| `thread_*` | all 17, plus `transcript_search` | `threads/tools.rs` deleted; the `threads` domain stays — it is `DomainGroup::Threads` kernel surface and backs the whole chat UI. `todo_*` and `goal_*` are untouched. |
| `billing_*`, `team_*`, `referral_*` | all 34 | `hosted/{billing,team,referral}/tools.rs` deleted; every controller stays (32 `team` and 5 `billing` frontend call sites). |
-| `tinyplace_*` | the whole curated agent surface (`tinyplace/agent_tools`, `tinyplace/tools.rs`) | The **domain stays.** See the note below. |
-Two agents went with them: **`account_admin_agent`** (its belt was billing +
-team + referral) and **`tinyplace_agent`**. `account_admin_agent`'s read-only
+One agent went with them: **`account_admin_agent`** (its belt was billing +
+team + referral). `account_admin_agent`'s read-only
half — `session_state`, `session_get_user`, `credential_list`,
`oauth_connect_url`, `oauth_list` — moved to `settings_agent`: that is account
*state*, which is settings territory, and has nothing to do with the money
-movement that went away. The `tinyplace_autopilot` cron seed went too, and with
-it `cron::seed::seed_proactive_agents_on_boot`, whose only job was backfilling
-that one job.
-
-**`openhuman::tinyplace/` was NOT deleted, and this is a deliberate stop, not an
-oversight.** It is ~17.8k lines with ~180 references across ~30 files outside
-itself, and the two heaviest consumers are surfaces that must survive:
-`hosted/orchestration` (the tiny.place orchestration surface the note above
-says not to clean up) and `web3::wallet`, whose `tinyplace_solana_rpc_endpoints`
-/ `tinyplace_signer_seed` are documented API. Deleting the domain means deleting
-or rewriting `hosted/orchestration` first. What is gone is the agent's route to
-it; `DomainGroup::Relay` still exists and still serves its controllers, it just
-owns no agent tool any more — which is why `Relay` is now in `TOOL_LESS` in
-`tools/ops_tests.rs`.
+movement that went away.
**Known regression, accepted:** removing `thread_list` from the orchestrator
reopens #4744 — "list my recent conversation threads" has no direct route and
@@ -667,7 +652,7 @@ So `GroupMode` has three states, not two:
**Packs now carry an `owners` list, and a pack is skipped entirely for its owner.** This is new with the raw-tool packs and was not needed before: the original packs held only synthesised `delegate_*` tools, which exist on the orchestrator alone. A pack over raw tools is different — `settings_agent` exists precisely to run `config_*` / `health_*` / `service_*`, so withholding the `system` pack from it would put a `load_skill` round trip in front of the first call of every one of its turns and hide nothing that was idle. Its whole belt *is* the pack. `strip_packed_from_visible` therefore takes the agent id.
-**`DomainGroup` tracks family directories 1:1.** After the domain reorg (#5328) each variant names a `src/openhuman/` family, so the runtime axis stopped sweeping half the surface into the `Platform` catch-all. Groups: the harness families (`Agent`, `Memory`, `Threads`, `Config`, `Security`), the compile-gate families (`Flows`, `Skills`, `Mcp`, `Channels`, `Web3`, `Voice`, `Media`, `Medulla`), the families carved out of `Platform` (`Inference`, `Integrations`, `Automation` = cron, `Runtimes` = runtime + sandbox, `Desktop`, `Hosted`, `Relay` = tinyplace, `Modules` = the native module host), and `Platform` itself — now only the kernel surfaces with no family of their own (`platform/`, `tools/`, `http_host/`, `test_support/`).
+**`DomainGroup` tracks family directories 1:1.** After the domain reorg (#5328) each variant names a `src/openhuman/` family, so the runtime axis stopped sweeping half the surface into the `Platform` catch-all. Groups: the harness families (`Agent`, `Memory`, `Threads`, `Config`, `Security`), the compile-gate families (`Flows`, `Skills`, `Mcp`, `Channels`, `Web3`, `Voice`, `Media`, `Medulla`), the families carved out of `Platform` (`Inference`, `Integrations`, `Automation` = cron, `Runtimes` = runtime + sandbox, `Desktop`, `Hosted`, `Modules` = the native module host), and `Platform` itself — now only the kernel surfaces with no family of their own (`platform/`, `tools/`, `http_host/`, `test_support/`).
That realignment fixed two real defects, both pinned by tests in `src/core/all_tests.rs`:
@@ -791,7 +776,7 @@ Two columns because there are two sets (see above): **Contrib** is `[features] d
| `flows` | ON | ON | `openhuman::flows` (saved automation graphs — create/run/schedule, the `workflow_builder` + `flow_discovery` agents), `openhuman::flows::tinyflows` (engine seam), `openhuman::flows::rhai` (`.ragsh` language-workflow tool) | `tinyflows`, `jaq-core`, `jaq-std`, `jaq-json`, `rhai` |
| `mcp` | ON | ON | `openhuman::mcp::server` (the `openhuman mcp` stdio/HTTP server), `openhuman::mcp::registry` (dynamic Smithery installs — `mcp_clients` RPC namespace, SQLite, boot spawn, supervisor, OAuth), `openhuman::mcp::audit` (write-audit log), and the static config-declared server set in `openhuman::mcp::config_servers`. ~19 agent tools, ~20k LOC | **none** — and the `tinymcp` module extraction does not change that either; see the scope note |
| `tui` | OFF | — | `openhuman::tui` — the tabbed ratatui/crossterm CLI UI (Logs, Chat, Config, Settings), auto-opened by bare `openhuman` on interactive non-container hosts and forced with `openhuman tui` (alias `chat`). Runs the core in-process. No controllers, no agent tools. **Intentionally NOT forwarded to the desktop shell** (allowlisted in `check-feature-forwarding.mjs`). | `ratatui`, `crossterm` |
-| `channels` | ON | ON | `openhuman::channels` (external-messaging providers — Telegram/Discord/Slack/Signal/WhatsApp/iMessage/IRC/… — plus the channel runtime, controllers, host, proactive messaging + inbound dispatch) and the `webview_notifications` bridge domain. **Carve-outs `channels::{traits, cli}` stay ungated.** The family now owns **no agent tool** — the three `whatsapp_data_*` tools were its only ones and went with the store (see below) — which is why `DomainGroup::Channels` is in `TOOL_LESS` in `tools/ops_tests.rs`, alongside `Relay`. | **28** via `tinychannels/{email,lark}` — the crate itself stays (load-bearing), its two heavy providers do not |
+| `channels` | ON | ON | `openhuman::channels` (external-messaging providers — Telegram/Discord/Slack/Signal/WhatsApp/iMessage/IRC/… — plus the channel runtime, controllers, host, proactive messaging + inbound dispatch) and the `webview_notifications` bridge domain. **Carve-outs `channels::{traits, cli}` stay ungated.** The family now owns **no agent tool** — the three `whatsapp_data_*` tools were its only ones and went with the store (see below) — which is why `DomainGroup::Channels` is in `TOOL_LESS` in `tools/ops_tests.rs`. | **28** via `tinychannels/{email,lark}` — the crate itself stays (load-bearing), its two heavy providers do not |
| `contacts` | OFF | ON | `memory::people::address_book`'s macOS CNContactStore reader — the address-book seeding path for the people domain. Leaf gate over a **pre-existing** off-state: the module already shipped a non-macOS `imp` stub returning an empty contact list, so the gate only widens that stub's cfg. `read`/`read_with`/`AddressBookError`/`SystemContactsSource` and the whole `people` RPC surface stay compiled in every build; off ⇒ a refresh seeds nothing instead of failing. | **6** on macOS (`objc2`, `objc2-foundation`, `objc2-contacts`, `block2` + 2 transitive). **No-op on Linux/Windows** — never in those graphs, so the kernel-floor ratchet does not move. Verify cross-target: `cargo tree --target aarch64-apple-darwin -e normal -i objc2-contacts --no-default-features` (294 → 288 packages). |
| `runtime-node` | OFF | ON | `runtime::node` (the client that asks the `tinyruntime` module for a Node.js toolchain), the `runtime::javascript` language slot, `runtime::pool::node`, the `node_exec` / `npm_exec` agent tools, and the `node_runtime` harness-init step. **Facade + stub** — `ShellTool` holds `Option<Arc<NodeBootstrap>>` and `shell.rs` is kernel, so the module cannot simply vanish; `runtime/node/stub.rs` carries the `NodeBootstrap` type surface while registration sites are leaf-gated. **The generic native-tool dispatcher (`runtime::node::ops` / `runtime::node::types`) is NOT gated** — it backs both the gated `javascript.*` controllers and the ungated `flows` `oh:` `NativeToolBackend`, so native flow tools (`memory_search`, file, shell, …) keep working when the managed Node runtime is off. Off ⇒ `try_cached`/`probe_installed` return `None` and the shell never prepends a managed bin dir, identical to today's `node.enabled = false` path. | **Nothing any more.** This gate used to shed `xz2` and its static liblzma C build; download and extraction moved into the `tinyruntime` module, so that native build left the manifest for **every** configuration rather than only for slim ones. The gate still buys the absence of the tools and controllers. |
@@ -801,9 +786,7 @@ Two columns because there are two sets (see above): **Contrib** is `[features] d
The `voice` gate still does not drop `llama` or `cpal`: `cpal` belongs to the `inference` gate above, and `llama`/`whisper` inference for the *local model runtime* is a separate concern. Earlier revisions of this note promised a future `inference` gate that would shed whisper — that gate exists and sheds `cpal`; whisper left the graph entirely instead.
-**`web3` gate — first gate that sheds real crypto deps.** Same facade pattern: `pub mod wallet;` / `pub mod web3;` / `pub mod x402;` stay always-compiled, real submodules are `#[cfg(feature = "web3")]`, and each domain's `stub.rs` re-exposes the always-on caller surface with disabled-error / empty bodies. When off, the wallet/web3/x402 controllers are unregistered, the web3 swap/bridge/dapp agent tools are absent (via `all_web3_agent_tools()` → empty), and the exclusive `bitcoin` (BTC P2WPKH PSBT) + `ethers-core` / `ethers-signers` / `coins-bip39` (EVM/mnemonic signing, used by the multi-chain wallet's EVM path) deps are dropped. `curve25519-dalek` (used for Solana off-curve ATA here) is **not** among them — it stays enabled transitively through the always-on `ed25519-dalek`. **tinyplace on-chain payments degrade to graceful "wallet disabled" errors** (the tinyplace comms path and the core itself are unaffected — `tinyplace::signer` still works via ed25519). The stubs cover `WALLET_NOT_CONFIGURED_MESSAGE`, `status`, `secret_material`, `WalletChain`, `prepare_transfer`/`execute_prepared` (+ param/result types), `solana_cluster`/`SolanaCluster`/`tinyplace_solana_rpc_endpoints`, `tinyplace_signer_seed`, `wallet::rpc::{redact_rpc_url, with_tinyplace_solana_endpoints}`, and the `all_*_registered_controllers`/`all_*_controller_schemas`/`all_web3_agent_tools` entry points. Two caller families still need per-call `#[cfg(feature = "web3")]` because they name concrete gated types rather than a stubbable aggregator: the six `Wallet*Tool` + `X402RequestTool` registrations in `tools/ops.rs`, the `wallet::tools::*` glob in `tools/mod.rs`, and the x402 402-retry path in `tools/impl/network/http_request.rs` (with the feature off a 402 returns to the caller unpaid).
-
-**`bs58` and `ed25519-dalek` still do NOT drop, deliberately.** `orchestration/ingest` and `tinyplace/payment` use them for agent-network identity, which is unrelated to the wallet. `curve25519-dalek` also survives now, beneath `ed25519-dalek`. Measured: excluding all three from the cohort costs **0**, because tinyplace pulls them in regardless — so there is nothing to gain by chasing them.
+**`web3` gate — first gate that sheds real crypto deps.** Same facade pattern: `pub mod wallet;` / `pub mod web3;` / `pub mod x402;` stay always-compiled, real submodules are `#[cfg(feature = "web3")]`, and each domain's `stub.rs` re-exposes the always-on caller surface with disabled-error / empty bodies. When off, the wallet/web3/x402 controllers are unregistered, the web3 swap/bridge/dapp agent tools are absent (via `all_web3_agent_tools()` → empty), and the exclusive `bitcoin` (BTC P2WPKH PSBT) + `ethers-core` / `ethers-signers` / `coins-bip39` (EVM/mnemonic signing, used by the multi-chain wallet's EVM path) deps are dropped. `curve25519-dalek` (used for Solana off-curve ATA here) is **not** among them — it stays enabled transitively through the always-on `ed25519-dalek`. The stubs cover `WALLET_NOT_CONFIGURED_MESSAGE`, `status`, `secret_material`, `WalletChain`, `prepare_transfer`/`execute_prepared` (+ param/result types), `solana_cluster`/`SolanaCluster`, `wallet::rpc::redact_rpc_url`, and the `all_*_registered_controllers`/`all_*_controller_schemas`/`all_web3_agent_tools` entry points. Two caller families still need per-call `#[cfg(feature = "web3")]` because they name concrete gated types rather than a stubbable aggregator: the six `Wallet*Tool` + `X402RequestTool` registrations in `tools/ops.rs`, the `wallet::tools::*` glob in `tools/mod.rs`, and the x402 402-retry path in `tools/impl/network/http_request.rs` (with the feature off a 402 returns to the caller unpaid).
`core/all.rs`'s `flows` registration builds a `Vec` and conditionally `push`es rather than using a `vec![]` literal, because an element of a `vec![]` cannot carry `#[cfg]`.
diff --git a/Cargo.lock b/Cargo.lock
index 37a6570ee2..9d5db3fdd7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4167,7 +4167,6 @@ dependencies = [
"tinymemory-bus",
"tinymemory-core",
"tinymemory-tinycortex",
- "tinyplace",
"tinyruntime-bus",
"tinytools",
"tinyvoice-bus",
@@ -6663,33 +6662,6 @@ dependencies = [
"uuid",
]
-[[package]]
-name = "tinyplace"
-version = "2.0.4"
-dependencies = [
- "aes",
- "async-trait",
- "base64 0.22.1",
- "bs58",
- "cbc",
- "chrono",
- "curve25519-dalek",
- "ed25519-dalek",
- "futures-util",
- "hkdf",
- "hmac 0.12.1",
- "rand 0.8.6",
- "reqwest",
- "serde",
- "serde_json",
- "sha2 0.10.9",
- "thiserror 2.0.18",
- "tokio",
- "tokio-tungstenite 0.29.0",
- "url",
- "x25519-dalek",
-]
-
[[package]]
name = "tinyruntime-bus"
version = "0.2.2"
diff --git a/Cargo.toml b/Cargo.toml
index 7ff8388000..e7b1fcad83 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -127,10 +127,6 @@ crate-type = ["rlib"]
# upstream in the SDK repo, not re-implemented in `src/api/`.
# After cloning: `git submodule update --init vendor/tinyhumans-sdk`.
tinyhumans-sdk = { path = "vendor/tinyhumans-sdk", default-features = false }
-# tiny.place A2A social network SDK — published on crates.io and patched below
-# to the vendored tiny.place submodule so OpenHuman can test SDK changes before
-# publishing.
-tinyplace = "2.0"
# tinyflows — host-agnostic workflow engine (typed node graph → validate → compile →
# run on tinyagents). Powers the "Workflows" feature via the seam in
# `src/openhuman/tinyflows/` + the `flows::` domain. Pulls tinyagents 2.1 transitively
@@ -906,22 +902,14 @@ voice = [
# off-curve ATA) + `ethers-core` / `ethers-signers` / `coins-bip39` (EVM/mnemonic
# signing, used by the multi-chain wallet's EVM path) dependencies. Composes
# with the runtime `DomainSet::Web3` flag (#4796): the feature narrows the
-# compile-time surface, `DomainSet` gates it at runtime. When off, tinyplace
-# payments degrade to graceful "wallet disabled" errors via the wallet/web3/x402
-# stub facades.
-#
-# `bs58` and `ed25519-dalek` deliberately stay always-on: `orchestration/ingest`
-# and `tinyplace/payment` use them for agent-network identity, which has nothing
-# to do with the wallet. Measured: excluding them costs 0, because tinyplace
-# pulls them in regardless.
+# compile-time surface, `DomainSet` gates it at runtime.
# `k256` and `coins-bip39` are gone from this list: nothing in the shipped
# binary derives a key or signs with secp256k1 any more — the wallet module
# does both. Both crates remain under [dev-dependencies], where test fixtures
# still derive a known account and check a signature against a fixed vector.
#
# `curve25519-dalek` stays: `associated_token_account` needs the off-curve check
-# to derive a Solana ATA, which is address arithmetic rather than signing, and
-# tinyplace pulls it in through `ed25519-dalek` regardless.
+# to derive a Solana ATA, which is address arithmetic rather than signing.
web3 = [
"dep:tinywallet-bus",
"dep:curve25519-dalek",
@@ -1252,7 +1240,7 @@ motosan-ai-oauth = { path = "vendor/motosan-ai-oauth" }
# version in lockstep with the `tinyagents` requirement above. After cloning:
# `git submodule update --init vendor/tinyagents` (worktrees included).
tinyagents = { path = "vendor/tinyagents" }
-# TinyFlows, TinyCortex, TinyChannels, and TinyPlace are vendored beside
+# TinyFlows, TinyCortex, and TinyChannels are vendored beside
# TinyAgents so integration work can test crate changes against OpenHuman before
# publishing.
tinyflows = { path = "vendor/tinyflows" }
@@ -1262,7 +1250,6 @@ tinycortex = { path = "vendor/tinycortex" }
# copy of the contract types and the trait identities unify.
tinycortex-api = { path = "vendor/tinycortex/api" }
tinychannels = { path = "vendor/tinychannels" }
-tinyplace = { path = "vendor/tinyplace/sdk/rust" }
# Emit just enough DWARF in release builds for Sentry to symbolicate Rust
# panics + render surrounding source lines. `line-tables-only` keeps the
diff --git a/README.md b/README.md
index b9de905f9e..411443f081 100644
--- a/README.md
+++ b/README.md
@@ -76,7 +76,6 @@ OpenHuman is three things most assistants aren't: **a brain** that builds a pers
- **[Workflows](https://tinyhumans.gitbook.io/openhuman/features/workflows)**: the agent proposes the automation; you review it on a canvas and save. Durable, trigger-driven, approval-gated runs on open-source [tinyflows](https://github.com/tinyhumansai/tinyflows).
- **[A harness that finishes the job](https://tinyhumans.gitbook.io/openhuman/developing/architecture/agent-harness)**: checkpointed graph runs on open-source [tinyagents](https://github.com/tinyhumansai/tinyagents). Stuck agents get steered, halted ones return a root cause, and every run replays with real per-call costs.
- **[A split brain, always on](https://tinyhumans.gitbook.io/openhuman/features/orchestration)**: a fast reflex agent triages inbound traffic while a deep reasoning core delegates to worker fleets, steered by the subconscious.
-- **[An agent economy](https://tinyhumans.gitbook.io/openhuman/features/tinyplace)**: a `@handle` on [tiny.place](https://tiny.place), Signal-encrypted agent-to-agent orchestration, x402 USDC bounties and trading. Keys never touch disk.
### 🔬 The deep researcher & doer
diff --git a/app/src-tauri/Cargo.lock b/app/src-tauri/Cargo.lock
index 24a7b4cc88..764d6de9d4 100644
--- a/app/src-tauri/Cargo.lock
+++ b/app/src-tauri/Cargo.lock
@@ -590,15 +590,6 @@ dependencies = [
"hybrid-array",
]
-[[package]]
-name = "block-padding"
-version = "0.3.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
-dependencies = [
- "generic-array",
-]
-
[[package]]
name = "block2"
version = "0.5.1"
@@ -751,15 +742,6 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
]
-[[package]]
-name = "cbc"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
-dependencies = [
- "cipher",
-]
-
[[package]]
name = "cc"
version = "1.4.4"
@@ -2937,7 +2919,6 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
- "block-padding",
"generic-array",
]
@@ -4355,7 +4336,6 @@ dependencies = [
"tinymemory-bus",
"tinymemory-core",
"tinymemory-tinycortex",
- "tinyplace",
"tinyruntime-bus",
"tinytools",
"tinyvoice-bus",
@@ -7277,33 +7257,6 @@ dependencies = [
"uuid",
]
-[[package]]
-name = "tinyplace"
-version = "2.0.4"
-dependencies = [
- "aes",
- "async-trait",
- "base64 0.22.1",
- "bs58",
- "cbc",
- "chrono",
- "curve25519-dalek",
- "ed25519-dalek",
- "futures-util",
- "hkdf",
- "hmac",
- "rand 0.8.7",
- "reqwest 0.12.28",
- "serde",
- "serde_json",
- "sha2 0.10.9",
- "thiserror 2.0.20",
- "tokio",
- "tokio-tungstenite 0.29.0",
- "url",
- "x25519-dalek",
-]
-
[[package]]
name = "tinyruntime-bus"
version = "0.2.2"
diff --git a/app/src-tauri/Cargo.toml b/app/src-tauri/Cargo.toml
index 1c09f8213a..65d37f917a 100644
--- a/app/src-tauri/Cargo.toml
+++ b/app/src-tauri/Cargo.toml
@@ -275,7 +275,7 @@ tinyagents = { path = "../../vendor/tinyagents" }
# match the one the core crate names, or cargo resolves two distinct packages
# and the shell's `dyn Tool` stops being the core's. See the core manifest.
tinytools = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools" }
-# TinyFlows, TinyCortex, TinyChannels, and TinyPlace are vendored beside
+# TinyFlows, TinyCortex, and TinyChannels are vendored beside
# TinyAgents so integration work can test crate changes against OpenHuman before
# publishing.
tinyflows = { path = "../../vendor/tinyflows" }
@@ -286,7 +286,6 @@ tinycortex = { path = "../../vendor/tinycortex" }
# tries to resolve it from crates.io and fails (it was never published).
tinycortex-api = { path = "../../vendor/tinycortex/api" }
tinychannels = { path = "../../vendor/tinychannels" }
-tinyplace = { path = "../../vendor/tinyplace/sdk/rust" }
[dev-dependencies]
diff --git a/app/src-tauri/src/lib.rs b/app/src-tauri/src/lib.rs
index 8e0f5dec3c..cff0bf1ee7 100644
--- a/app/src-tauri/src/lib.rs
+++ b/app/src-tauri/src/lib.rs
@@ -2121,10 +2121,8 @@ fn append_platform_cef_gpu_workarounds(
//
// The original workaround disabled the GPU path with `--disable-gpu`, but
// that shuts the GPU process down entirely — and with it every WebGL
- // surface. That regressed Tiny Place (#4193): the world renderer needs a
- // WebGL2 context, so on every packaged Linux build it failed to initialise
- // and the world page showed a black screen with "Could not start the world
- // renderer" (the Rive mascot on the Human tab is collateral damage too).
+ // surface. That regressed WebGL rendering (#4193), including the Rive
+ // mascot on the Human tab.
//
// Instead of killing the GPU process, pin it to ANGLE's SwiftShader
// software backend. SwiftShader is a pure-software rasteriser that needs no
@@ -2144,7 +2142,7 @@ fn append_platform_cef_gpu_workarounds(
} else {
push_swiftshader_software_gl(args);
log::info!(
- "[cef-startup] Linux detected: forcing ANGLE/SwiftShader software GL so WebGL surfaces (Tiny Place world renderer, Rive mascot) render without the crash-prone hardware GPU process (issues #1697/#4193); set OPENHUMAN_FORCE_GPU=1 for hardware acceleration"
+ "[cef-startup] Linux detected: forcing ANGLE/SwiftShader software GL so WebGL surfaces render without the crash-prone hardware GPU process (issues #1697/#4193); set OPENHUMAN_FORCE_GPU=1 for hardware acceleration"
);
}
}
diff --git a/app/src-tauri/src/lib_tests.rs b/app/src-tauri/src/lib_tests.rs
index 17bb6b6290..e2620bc68b 100644
--- a/app/src-tauri/src/lib_tests.rs
+++ b/app/src-tauri/src/lib_tests.rs
@@ -309,7 +309,7 @@ fn platform_cef_gpu_workarounds_force_swiftshader_on_linux() {
append_platform_cef_gpu_workarounds(&mut args, "linux", "x86_64", None, None);
// #4193: the GPU process must NOT be killed outright — `--disable-gpu`
- // takes every WebGL surface (the Tiny Place world renderer) down with it.
+ // takes every WebGL surface down with it.
assert!(
!args.contains(&("--disable-gpu", None)),
"--disable-gpu kills WebGL and must not be set, got: {args:?}"
diff --git a/app/src/AppRoutes.tsx b/app/src/AppRoutes.tsx
index 43b2f75c8b..efd0b0c091 100644
--- a/app/src/AppRoutes.tsx
+++ b/app/src/AppRoutes.tsx
@@ -1,4 +1,4 @@
-import { type Location, Navigate, Route, Routes, useLocation } from 'react-router-dom';
+import { type Location, Navigate, Route, Routes } from 'react-router-dom';
import AppRoutesIOS from './AppRoutesIOS';
import DefaultRedirect from './components/DefaultRedirect';
@@ -36,54 +36,6 @@ interface AppRoutesProps {
location?: Location | string;
}
-/**
- * Redirects the retired `/orchestration` route to its new home under Brain
- * (`/brain?tab=orchestration`), mapping the legacy `?tab=`/`?sub=` query onto
- * Brain's `?ov=`/`?sub=` scheme so old deep links land on the same view:
- * - `?tab=connections|discover|usage` → `?ov=network&sub=<that>`
- * - `?tab=agent|overview|tasks|network|medulla` → `?ov=<that>`
- * - `?session=` is preserved for the agent chat.
- */
-const NETWORK_SUBS = ['connections', 'discover', 'usage'];
-const ORCH_VIEWS = ['medulla', 'agent', 'overview', 'tasks', 'network'];
-
-export function OrchestrationRedirect() {
- const { search } = useLocation();
- const legacy = new URLSearchParams(search);
- const tab = legacy.get('tab');
- // Privacy-safe: only the allowlisted branch id and whether a session param was
- // present are logged — never the session value or any raw query string.
- console.debug(
- '[routes] orchestration-redirect: entry tab=%s',
- tab && ORCH_VIEWS.includes(tab) ? tab : tab && NETWORK_SUBS.includes(tab) ? tab : '<unmapped>'
- );
-
- const next = new URLSearchParams();
- next.set('tab', 'orchestration');
- let branch: string;
- if (tab && NETWORK_SUBS.includes(tab)) {
- next.set('ov', 'network');
- next.set('sub', tab);
- branch = 'network-sub';
- } else {
- if (tab && ORCH_VIEWS.includes(tab)) next.set('ov', tab);
- const sub = legacy.get('sub');
- if (sub && NETWORK_SUBS.includes(sub)) next.set('sub', sub);
- branch = tab && ORCH_VIEWS.includes(tab) ? 'view' : 'default';
- }
- const session = legacy.get('session');
- if (session) next.set('session', session);
-
- console.debug(
- '[routes] orchestration-redirect: exit branch=%s ov=%s hasSub=%s hasSession=%s',
- branch,
- next.get('ov') ?? '<none>',
- next.has('sub'),
- next.has('session')
- );
- return <Navigate to={`/brain?${next.toString()}`} replace />;
-}
-
const AppRoutes = ({ location }: AppRoutesProps = {}) => {
// Mobile target (iOS or Android): pair → Human/Chat/Settings only.
// Desktop routes are not rendered.
@@ -185,18 +137,6 @@ const AppRoutes = ({ location }: AppRoutesProps = {}) => {
}
/>
- {/* Orchestration folded back under Brain (`/brain?tab=orchestration`).
- The old first-class `/orchestration` route and the even older Brain
- deep link both redirect there; `<OrchestrationRedirect>` maps the
- legacy `?tab=`/`?sub=` query onto Brain's `?ov=`/`?sub=` scheme so
- deep links (e.g. `/orchestration?tab=tasks`) keep landing on the same
- view. */}
- <Route path="/orchestration" element={<OrchestrationRedirect />} />
- <Route
- path="/brain/tinyplace-orchestration"
- element={<Navigate to="/brain?tab=orchestration" replace />}
- />
-
{/* Back-compat: /activity and /intelligence → settings notifications page. */}
<Route path="/activity" element={<Navigate to="/settings/notifications" replace />} />
<Route path="/intelligence" element={<Navigate to="/settings/notifications" replace />} />
diff --git a/app/src/components/chat/ChatComposer.tsx b/app/src/components/chat/ChatComposer.tsx
index fb252966eb..3664c1aed0 100644
--- a/app/src/components/chat/ChatComposer.tsx
+++ b/app/src/components/chat/ChatComposer.tsx
@@ -173,8 +173,8 @@ export interface ChatComposerProps {
* `ComposerPrimitive.*` reads its runtime from React context, so every surface
* rendering this component should sit under a runtime scoped to *its own*
* thread. Two did not, and would have inherited the app-wide one bound to
- * `selectedThreadId` — the home chat's thread; both now mount their own (see
- * `WorkflowCopilotPanel` and `orchestration/AgentChatPanel`). The default
+ * `selectedThreadId` — the home chat's thread; `WorkflowCopilotPanel` now
+ * mounts its own. The default
* export wraps this body in `ComposerRuntimeBoundary`, which supplies an inert
* runtime when there is none at all; read that file before assuming the
* boundary makes the per-surface decision unnecessary — it cannot, because an
diff --git a/app/src/components/chat/composer/ComposerRuntimeBoundary.tsx b/app/src/components/chat/composer/ComposerRuntimeBoundary.tsx
index 636bfcdfd2..9dd8d1bee2 100644
--- a/app/src/components/chat/composer/ComposerRuntimeBoundary.tsx
+++ b/app/src/components/chat/composer/ComposerRuntimeBoundary.tsx
@@ -26,10 +26,10 @@ const selectHasComposer = (s: AssistantState) => s.optional.composer != null;
* app shell that mounts no runtime of its own does not error — it silently
* inherits the app-wide one from `ChatRuntimeProvider`, which is bound to
* `state.thread.selectedThreadId`, the HOME chat's thread. Two surfaces were in
- * exactly that position (the flows Workflow Copilot, whose own provider closed
- * around its transcript only, and the orchestration agent chat, which has no
- * chat thread at all); both now mount their own runtime explicitly, because a
- * composer pointed at an unrelated conversation is a data-loss-shaped bug.
+ * in exactly that position: the flows Workflow Copilot, whose own provider
+ * closed around its transcript only. It now mounts its own runtime explicitly,
+ * because a composer pointed at an unrelated conversation is a data-loss-shaped
+ * bug.
*
* This boundary is the net under that decision, not a replacement for it. Where
* a runtime already exists it is a pass-through and the surface keeps whatever
diff --git a/app/src/components/chat/composer/DetachedComposerRuntime.tsx b/app/src/components/chat/composer/DetachedComposerRuntime.tsx
index f1f0585f0e..3a7976dadd 100644
--- a/app/src/components/chat/composer/DetachedComposerRuntime.tsx
+++ b/app/src/components/chat/composer/DetachedComposerRuntime.tsx
@@ -15,9 +15,8 @@ const NO_MESSAGES: ThreadMessageLike[] = [];
* runtime of its own therefore inherits the app-wide one from
* `ChatRuntimeProvider` — which is bound to `state.thread.selectedThreadId`,
* the HOME chat's thread. For a surface whose conversation is not a chat thread
- * at all (the orchestration agent chat talks to sessions over
- * `orchestrationClient`), that inheritance points its composer at an unrelated
- * conversation. That is a data-loss-shaped mistake, not a cosmetic one.
+ * at all, that inheritance points its composer at an unrelated conversation.
+ * That is a data-loss-shaped mistake, not a cosmetic one.
*
* The obvious fix — `AssistantUiRuntimeProvider threadId={null}` — is the right
* shape but the wrong dependency: that provider reads Redux unconditionally
diff --git a/app/src/components/intelligence/AttentionQueue.test.tsx b/app/src/components/intelligence/AttentionQueue.test.tsx
deleted file mode 100644
index dc1e1593db..0000000000
--- a/app/src/components/intelligence/AttentionQueue.test.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { AttentionQueue } from '../../lib/orchestration/orchestrationClient';
-import AttentionQueueView from './AttentionQueue';
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const populated: AttentionQueue = {
- items: [
- {
- id: 'approval:req-1',
- kind: 'approval',
- instanceId: 'req-1',
- title: 'shell',
- summary: 'run a command',
- action: { type: 'approval', requestId: 'req-1' },
- },
- {
- id: 'unread:h-1',
- kind: 'unread',
- instanceId: 'h-1',
- title: 'Codex',
- count: 2,
- action: { type: 'open-session', sessionId: 'h-1' },
- },
- ],
- counts: { total: 2, approvals: 1, needsInput: 0, unread: 1 },
-};
-
-const empty: AttentionQueue = {
- items: [],
- counts: { total: 0, approvals: 0, needsInput: 0, unread: 0 },
-};
-
-describe('AttentionQueue', () => {
- it('renders each item and a total badge when populated', () => {
- render(<AttentionQueueView queue={populated} />);
- expect(screen.getByTestId('attention-queue-count')).toHaveTextContent('2');
- expect(screen.getByTestId('attention-item-approval:req-1')).toBeInTheDocument();
- expect(screen.getByTestId('attention-item-unread:h-1')).toBeInTheDocument();
- expect(screen.queryByTestId('attention-queue-empty')).toBeNull();
- });
-
- it('renders the empty state and no badge when the queue is clear', () => {
- render(<AttentionQueueView queue={empty} />);
- expect(screen.getByTestId('attention-queue-empty')).toBeInTheDocument();
- expect(screen.queryByTestId('attention-queue-count')).toBeNull();
- });
-
- it('renders nothing while the first load is pending', () => {
- const { container } = render(<AttentionQueueView queue={null} loading />);
- expect(container).toBeEmptyDOMElement();
- });
-});
diff --git a/app/src/components/intelligence/AttentionQueue.tsx b/app/src/components/intelligence/AttentionQueue.tsx
deleted file mode 100644
index bd310b015f..0000000000
--- a/app/src/components/intelligence/AttentionQueue.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- * AttentionQueue — the "Needs you" zone of the Orchestration tab: a priority-
- * ordered list of everything blocked on the user (pending approvals, agent runs
- * awaiting input, instances with unread messages).
- *
- * Presentational only. The parent (layout-rewrite PR) loads the queue via
- * `orchestrationClient.attention()` and passes an `onAction` router. An empty
- * queue renders a calm "all caught up" state rather than hiding — the zone is a
- * stable anchor the user learns to glance at.
- */
-import { useT } from '../../lib/i18n/I18nContext';
-import type { AttentionAction, AttentionQueue } from '../../lib/orchestration/orchestrationClient';
-import AttentionQueueItem from './AttentionQueueItem';
-
-interface AttentionQueueProps {
- queue: AttentionQueue | null;
- loading?: boolean;
- onAction?: (action: AttentionAction) => void;
-}
-
-export default function AttentionQueueView({
- queue,
- loading,
- onAction,
-}: AttentionQueueProps): React.ReactElement | null {
- const { t } = useT();
-
- // Nothing to show until the first load resolves — the parent renders its own
- // shell; we stay out of the way rather than flashing an empty state.
- if (loading && !queue) return null;
-
- const total = queue?.counts.total ?? 0;
-
- return (
- <section data-testid="attention-queue" className="flex flex-col">
- <header className="flex items-center justify-between px-3 py-2">
- <h3 className="text-[11px] font-semibold uppercase tracking-wide text-content-secondary">
- {t('tinyplaceOrchestration.attention.title')}
- </h3>
- {total > 0 ? (
- <span
- data-testid="attention-queue-count"
- className="flex-none rounded-full bg-amber-500 px-1.5 py-0.5 text-[10px] font-semibold text-content-inverted">
- {total}
- </span>
- ) : null}
- </header>
- {total === 0 ? (
- <p data-testid="attention-queue-empty" className="px-3 py-2 text-[11px] text-content-faint">
- {t('tinyplaceOrchestration.attention.empty')}
- </p>
- ) : (
- <div className="flex flex-col gap-1">
- {queue?.items.map(item => (
- <AttentionQueueItem key={item.id} item={item} onAction={onAction} />
- ))}
- </div>
- )}
- </section>
- );
-}
diff --git a/app/src/components/intelligence/AttentionQueueItem.test.tsx b/app/src/components/intelligence/AttentionQueueItem.test.tsx
deleted file mode 100644
index c2791cbce2..0000000000
--- a/app/src/components/intelligence/AttentionQueueItem.test.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { AttentionItem } from '../../lib/orchestration/orchestrationClient';
-import AttentionQueueItem from './AttentionQueueItem';
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const approval: AttentionItem = {
- id: 'approval:req-1',
- kind: 'approval',
- instanceId: 'req-1',
- title: 'shell',
- summary: 'run `ls -la`',
- action: { type: 'approval', requestId: 'req-1' },
- createdAt: '2026-07-06T10:00:00Z',
-};
-
-// A REMOTE agent session parked on an approval: same `approval` kind as a local
-// gate approval, but its action opens the orchestration chat window instead of
-// the local approval surface.
-const remoteApproval: AttentionItem = {
- id: 'remote-approval:h-remote',
- kind: 'approval',
- instanceId: 'h-remote',
- title: 'Claude · deploy',
- summary: 'approve `rm -rf build/`',
- action: { type: 'open-session', sessionId: 'h-remote' },
- createdAt: '2026-07-06T12:00:00Z',
-};
-
-const needsInput: AttentionItem = {
- id: 'needs-input:run-1',
- kind: 'needs-input',
- instanceId: 'run-1',
- title: 'researcher',
- summary: 'blocked on a clarifying question',
- action: { type: 'open-thread', threadId: 'thread-9' },
-};
-
-const unread: AttentionItem = {
- id: 'unread:h-1',
- kind: 'unread',
- instanceId: 'h-1',
- title: 'Claude · repo audit',
- count: 4,
- action: { type: 'open-session', sessionId: 'h-1' },
-};
-
-describe('AttentionQueueItem', () => {
- it('renders an approval with its summary and a Review action', () => {
- const onAction = vi.fn();
- render(<AttentionQueueItem item={approval} onAction={onAction} />);
- const row = screen.getByTestId('attention-item-approval:req-1');
- expect(row).toHaveAttribute('data-kind', 'approval');
- expect(screen.getByText('shell')).toBeInTheDocument();
- expect(screen.getByText('run `ls -la`')).toBeInTheDocument();
- expect(screen.getByText('tinyplaceOrchestration.attention.kind.approval')).toBeInTheDocument();
-
- const action = screen.getByTestId('attention-item-action');
- expect(action).toHaveTextContent('tinyplaceOrchestration.attention.review');
- fireEvent.click(action);
- expect(onAction).toHaveBeenCalledWith({ type: 'approval', requestId: 'req-1' });
- });
-
- it('renders a remote approval (approval kind) whose action opens its session', () => {
- const onAction = vi.fn();
- render(<AttentionQueueItem item={remoteApproval} onAction={onAction} />);
- const row = screen.getByTestId('attention-item-remote-approval:h-remote');
- expect(row).toHaveAttribute('data-kind', 'approval');
- // Approval kind → the amber "Review" verb, and the summary is shown.
- expect(screen.getByText('Claude · deploy')).toBeInTheDocument();
- expect(screen.getByText('approve `rm -rf build/`')).toBeInTheDocument();
- const action = screen.getByTestId('attention-item-action');
- expect(action).toHaveTextContent('tinyplaceOrchestration.attention.review');
- // Clicking routes the open-session action so the tab opens the chat window.
- fireEvent.click(action);
- expect(onAction).toHaveBeenCalledWith({ type: 'open-session', sessionId: 'h-remote' });
- });
-
- it('renders a needs-input row with the Open action carrying its thread', () => {
- const onAction = vi.fn();
- render(<AttentionQueueItem item={needsInput} onAction={onAction} />);
- expect(screen.getByText('blocked on a clarifying question')).toBeInTheDocument();
- const action = screen.getByTestId('attention-item-action');
- expect(action).toHaveTextContent('tinyplaceOrchestration.attention.open');
- fireEvent.click(action);
- expect(onAction).toHaveBeenCalledWith({ type: 'open-thread', threadId: 'thread-9' });
- });
-
- it('renders unread with a localized label + count pill, not a summary', () => {
- render(<AttentionQueueItem item={unread} />);
- // Unread ships no summary string — the label is localized instead.
- expect(screen.getByText('tinyplaceOrchestration.attention.unread')).toBeInTheDocument();
- expect(screen.getByTestId('attention-item-count')).toHaveTextContent('4');
- expect(screen.getByText('Claude · repo audit')).toBeInTheDocument();
- });
-
- it('does not throw when onAction is omitted', () => {
- render(<AttentionQueueItem item={unread} />);
- // Clicking with no handler is a no-op, not a crash.
- expect(() => fireEvent.click(screen.getByTestId('attention-item-action'))).not.toThrow();
- });
-});
diff --git a/app/src/components/intelligence/AttentionQueueItem.tsx b/app/src/components/intelligence/AttentionQueueItem.tsx
deleted file mode 100644
index 85431fd267..0000000000
--- a/app/src/components/intelligence/AttentionQueueItem.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * AttentionQueueItem — one row in the "Needs you" zone: a kind chip, the
- * instance title, a one-line detail (or unread count), and a single action
- * button whose verb depends on the kind (Review an approval / Open a run or
- * chat).
- *
- * Presentational only. The parent supplies the {@link AttentionItem} and an
- * `onAction` callback that receives the item's {@link AttentionAction} — the
- * tab (layout-rewrite PR) routes it to the right surface.
- */
-import type { ReactElement } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type {
- AttentionAction,
- AttentionItem,
- AttentionKind,
-} from '../../lib/orchestration/orchestrationClient';
-import Button from '../ui/Button';
-
-interface AttentionQueueItemProps {
- item: AttentionItem;
- onAction?: (action: AttentionAction) => void;
-}
-
-const KIND_LABEL_KEY: Record<AttentionKind, string> = {
- approval: 'tinyplaceOrchestration.attention.kind.approval',
- 'needs-input': 'tinyplaceOrchestration.attention.kind.needsInput',
- unread: 'tinyplaceOrchestration.attention.kind.unread',
-};
-
-/** Left accent + chip tone per kind. Approvals and blocked runs read amber
- * (action required); unread reads primary (informational). */
-const KIND_TONE: Record<AttentionKind, { accent: string; chip: string }> = {
- approval: {
- accent: 'border-l-amber-500',
- chip: 'bg-amber-100 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300',
- },
- 'needs-input': {
- accent: 'border-l-amber-500',
- chip: 'bg-amber-100 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300',
- },
- unread: {
- accent: 'border-l-primary-500',
- chip: 'bg-primary-100 text-primary-700 dark:bg-primary-500/15 dark:text-primary-300',
- },
-};
-
-export default function AttentionQueueItem({
- item,
- onAction,
-}: AttentionQueueItemProps): ReactElement {
- const { t } = useT();
- const tone = KIND_TONE[item.kind];
- // Approvals are decided ("Review"); everything else is navigated to ("Open").
- const actionLabel =
- item.kind === 'approval'
- ? t('tinyplaceOrchestration.attention.review')
- : t('tinyplaceOrchestration.attention.open');
- // Unread ships a localized label + a count pill (no summary string); the
- // other kinds carry a data summary from their source domain.
- const detail =
- item.kind === 'unread' ? t('tinyplaceOrchestration.attention.unread') : item.summary;
-
- return (
- <div
- data-testid={`attention-item-${item.id}`}
- data-kind={item.kind}
- className={`flex items-center gap-3 border-l-2 ${tone.accent} bg-surface px-3 py-2`}>
- <span className="min-w-0 flex-1">
- <span className="flex items-center gap-1.5">
- <span
- className={`flex-none rounded-full px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${tone.chip}`}>
- {t(KIND_LABEL_KEY[item.kind])}
- </span>
- <span className="truncate text-xs font-semibold text-content">{item.title}</span>
- </span>
- {detail ? (
- <span className="mt-0.5 block truncate text-[11px] text-content-muted">{detail}</span>
- ) : null}
- </span>
- {item.kind === 'unread' && item.count !== undefined ? (
- <span
- data-testid="attention-item-count"
- className="flex-none rounded-full bg-primary-500 px-1.5 py-0.5 text-[10px] font-semibold text-content-inverted">
- {item.count}
- </span>
- ) : null}
- <Button
- variant="secondary"
- size="xs"
- data-testid="attention-item-action"
- onClick={() => onAction?.(item.action)}
- className="flex-none text-[11px] font-medium text-content-secondary">
- {actionLabel}
- </Button>
- </div>
- );
-}
diff --git a/app/src/components/intelligence/HarnessGlyph.test.tsx b/app/src/components/intelligence/HarnessGlyph.test.tsx
deleted file mode 100644
index eaa10563c2..0000000000
--- a/app/src/components/intelligence/HarnessGlyph.test.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import HarnessGlyph, { type GlyphKind } from './HarnessGlyph';
-
-describe('HarnessGlyph', () => {
- it.each<[GlyphKind, string]>([
- ['claude', 'C'],
- ['codex', 'Cx'],
- ['gemini', 'G'],
- ['cursor', 'Cu'],
- ['windsurf', 'Ws'],
- ['openhuman', 'OH'],
- ])('renders the %s mark', (harness, label) => {
- render(<HarnessGlyph harness={harness} />);
- const glyph = screen.getByTestId('harness-glyph');
- expect(glyph).toHaveAttribute('data-harness', harness);
- expect(glyph).toHaveTextContent(label);
- });
-});
diff --git a/app/src/components/intelligence/HarnessGlyph.tsx b/app/src/components/intelligence/HarnessGlyph.tsx
deleted file mode 100644
index 3d6bc259ce..0000000000
--- a/app/src/components/intelligence/HarnessGlyph.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * HarnessGlyph — a small brand mark for the agent harness driving an instance
- * (Claude / Codex / Gemini), plus an OpenHuman mark for internal windows. Used
- * as the leading glyph in roster rows.
- *
- * The colors here are deliberate brand/identity hues (not surface chrome), so
- * they use literal palette classes per the project's "meaningful content color"
- * guidance rather than semantic tokens.
- */
-import type { HarnessType } from '../../lib/orchestration/orchestrationClient';
-
-export type GlyphKind = HarnessType | 'openhuman';
-
-interface HarnessGlyphProps {
- harness: GlyphKind;
- className?: string;
-}
-
-const GLYPH: Record<GlyphKind, { label: string; tone: string }> = {
- claude: { label: 'C', tone: 'bg-[#c96442] text-content-inverted' },
- codex: { label: 'Cx', tone: 'bg-content text-surface' },
- gemini: { label: 'G', tone: 'bg-primary-500 text-content-inverted' },
- // Literal hex (Tailwind's slate-800) rather than the `bg-slate-*` utility —
- // this is cursor's brand identity color, not a themed neutral surface.
- cursor: { label: 'Cu', tone: 'bg-[#1e293b] text-content-inverted' },
- windsurf: { label: 'Ws', tone: 'bg-teal-500 text-content-inverted' },
- openhuman: { label: 'OH', tone: 'bg-sage-500 text-content-inverted' },
-};
-
-export default function HarnessGlyph({
- harness,
- className,
-}: HarnessGlyphProps): React.ReactElement {
- const { label, tone } = GLYPH[harness];
- return (
- <span
- aria-hidden
- data-testid="harness-glyph"
- data-harness={harness}
- className={`flex h-6 w-6 flex-none items-center justify-center rounded-md font-mono text-[11px] font-bold ${tone} ${className ?? ''}`}>
- {label}
- </span>
- );
-}
diff --git a/app/src/components/intelligence/InstanceCard.test.tsx b/app/src/components/intelligence/InstanceCard.test.tsx
deleted file mode 100644
index ea7b01bbcc..0000000000
--- a/app/src/components/intelligence/InstanceCard.test.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { SessionSummary } from '../../lib/orchestration/orchestrationClient';
-import InstanceCard from './InstanceCard';
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-function session(over: Partial<SessionSummary> = {}): SessionSummary {
- return {
- sessionId: 'w1',
- agentId: '6wNaBJkatir4B86cw5ykHZWQ3xoNaKygX5vAU9MQbHSh',
- source: 'claude',
- harnessType: 'claude',
- status: 'idle',
- currentTask: 'drafting hub cards',
- chatKind: 'session',
- lastMessageAt: '2026-07-06T00:00:00Z',
- unread: 0,
- active: true,
- pinned: false,
- ...over,
- };
-}
-
-describe('InstanceCard', () => {
- it('renders the harness glyph, status dot, task and shortened address', () => {
- render(<InstanceCard session={session()} />);
- expect(screen.getByTestId('harness-glyph')).toHaveAttribute('data-harness', 'claude');
- expect(screen.getByTestId('instance-status-dot')).toHaveAttribute('data-status', 'idle');
- expect(screen.getByText('drafting hub cards')).toBeInTheDocument();
- expect(screen.getByText('6wNaBJ…QbHSh')).toBeInTheDocument();
- });
-
- it('prefers a resolved @handle over the address', () => {
- render(<InstanceCard session={session()} handle="claudebot" />);
- expect(screen.getByText('@claudebot')).toBeInTheDocument();
- });
-
- it('shows the unread pill only when unread > 0 and fires onSelect', () => {
- const onSelect = vi.fn();
- const { rerender } = render(<InstanceCard session={session()} onSelect={onSelect} />);
- expect(screen.queryByTestId('instance-card-unread')).toBeNull();
-
- rerender(<InstanceCard session={session({ unread: 3 })} onSelect={onSelect} />);
- expect(screen.getByTestId('instance-card-unread')).toHaveTextContent('3');
-
- fireEvent.click(screen.getByTestId('instance-card-w1'));
- expect(onSelect).toHaveBeenCalledOnce();
- });
-
- it('falls back to the OpenHuman glyph when no harness is set', () => {
- render(<InstanceCard session={session({ harnessType: undefined, source: 'user_created' })} />);
- expect(screen.getByTestId('harness-glyph')).toHaveAttribute('data-harness', 'openhuman');
- });
-});
diff --git a/app/src/components/intelligence/InstanceCard.tsx b/app/src/components/intelligence/InstanceCard.tsx
deleted file mode 100644
index cbe1cbb985..0000000000
--- a/app/src/components/intelligence/InstanceCard.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * InstanceCard — one roster row for an agent instance: harness glyph + status
- * dot + identity + one-line current task + unread pill.
- *
- * Presentational only; the parent supplies the {@link SessionSummary} and an
- * optional resolved `@handle` (the raw address is the fallback).
- */
-import { useT } from '../../lib/i18n/I18nContext';
-import type { InstanceStatus, SessionSummary } from '../../lib/orchestration/orchestrationClient';
-import Button from '../ui/Button';
-import HarnessGlyph, { type GlyphKind } from './HarnessGlyph';
-import InstanceStatusDot from './InstanceStatusDot';
-
-interface InstanceCardProps {
- session: SessionSummary;
- selected?: boolean;
- onSelect?: () => void;
- /** Resolved `@handle` for the peer, if known (address is the fallback). */
- handle?: string | null;
-}
-
-const STATUS_LABEL_KEY: Record<InstanceStatus, string> = {
- running: 'tinyplaceOrchestration.status.running',
- idle: 'tinyplaceOrchestration.status.idle',
- 'waiting-approval': 'tinyplaceOrchestration.status.waitingApproval',
- errored: 'tinyplaceOrchestration.status.errored',
- stopped: 'tinyplaceOrchestration.status.stopped',
-};
-
-function shortAddress(address: string): string {
- if (address.length <= 14) return address;
- return `${address.slice(0, 6)}…${address.slice(-5)}`;
-}
-
-export default function InstanceCard({
- session,
- selected,
- onSelect,
- handle,
-}: InstanceCardProps): React.ReactElement {
- const { t } = useT();
- const glyph: GlyphKind = session.harnessType ?? 'openhuman';
- const identity = handle ? `@${handle}` : (session.label ?? shortAddress(session.agentId));
-
- return (
- <Button
- variant="tertiary"
- data-testid={`instance-card-${session.sessionId}`}
- data-selected={selected ? 'true' : 'false'}
- onClick={onSelect}
- className={`h-auto w-full items-center justify-start gap-3 rounded-none border-l-2 px-3 py-2 text-left ${
- selected ? 'border-primary-500 bg-surface-muted' : 'border-transparent'
- }`}>
- <HarnessGlyph harness={glyph} />
- <span className="min-w-0 flex-1">
- <span className="flex items-center gap-1.5">
- <InstanceStatusDot status={session.status} label={t(STATUS_LABEL_KEY[session.status])} />
- <span className="truncate text-xs font-semibold text-content">{identity}</span>
- </span>
- {session.currentTask ? (
- <span className="mt-0.5 block truncate text-[11px] text-content-muted">
- {session.currentTask}
- </span>
- ) : null}
- </span>
- {session.unread > 0 ? (
- <span
- data-testid="instance-card-unread"
- className="flex-none rounded-full bg-primary-500 px-1.5 py-0.5 text-[10px] font-semibold text-content-inverted">
- {session.unread}
- </span>
- ) : null}
- </Button>
- );
-}
diff --git a/app/src/components/intelligence/InstanceStatusDot.test.tsx b/app/src/components/intelligence/InstanceStatusDot.test.tsx
deleted file mode 100644
index 3e6989933e..0000000000
--- a/app/src/components/intelligence/InstanceStatusDot.test.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import type { InstanceStatus } from '../../lib/orchestration/orchestrationClient';
-import InstanceStatusDot from './InstanceStatusDot';
-
-describe('InstanceStatusDot', () => {
- it.each<InstanceStatus>(['running', 'idle', 'waiting-approval', 'errored', 'stopped'])(
- 'tags the %s status and pulses only when running',
- status => {
- render(<InstanceStatusDot status={status} label={status} />);
- const dot = screen.getByTestId('instance-status-dot');
- expect(dot).toHaveAttribute('data-status', status);
- expect(dot.className.includes('animate-pulse')).toBe(status === 'running');
- }
- );
-
- it('uses the status value as the accessible name when no label is given', () => {
- render(<InstanceStatusDot status="errored" />);
- expect(screen.getByTestId('instance-status-dot')).toHaveAttribute('aria-label', 'errored');
- });
-
- it('prefers a provided translated label', () => {
- render(<InstanceStatusDot status="idle" label="Inactivo" />);
- expect(screen.getByTestId('instance-status-dot')).toHaveAttribute('aria-label', 'Inactivo');
- });
-});
diff --git a/app/src/components/intelligence/InstanceStatusDot.tsx b/app/src/components/intelligence/InstanceStatusDot.tsx
deleted file mode 100644
index 637982f04a..0000000000
--- a/app/src/components/intelligence/InstanceStatusDot.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * InstanceStatusDot — the core roster primitive: one colored dot that encodes an
- * agent instance's status at a glance, scannable across many rows.
- *
- * Five states (color + motion), matching the core's {@link InstanceStatus}:
- * running (primary, pulsing) · idle (sage) · waiting-approval (amber) ·
- * errored (coral) · stopped (faint). The core derives only idle/stopped today;
- * the other three are wired ahead of the attention-queue / run-state work.
- *
- * Presentational only. Pass a translated `label` for the accessible name.
- */
-import type { InstanceStatus } from '../../lib/orchestration/orchestrationClient';
-
-interface InstanceStatusDotProps {
- status: InstanceStatus;
- /** Accessible label (already translated by the caller). */
- label?: string;
-}
-
-const TONE: Record<InstanceStatus, string> = {
- running: 'bg-primary-500 animate-pulse',
- idle: 'bg-sage-500',
- 'waiting-approval': 'bg-amber-500',
- errored: 'bg-coral-500',
- stopped: 'bg-content-faint',
-};
-
-export default function InstanceStatusDot({
- status,
- label,
-}: InstanceStatusDotProps): React.ReactElement {
- return (
- <span
- role="img"
- aria-label={label ?? status}
- title={label ?? status}
- data-testid="instance-status-dot"
- data-status={status}
- className={`inline-block h-2 w-2 flex-none rounded-full ${TONE[status]}`}
- />
- );
-}
diff --git a/app/src/components/intelligence/OrchestrationChatPrimitives.test.tsx b/app/src/components/intelligence/OrchestrationChatPrimitives.test.tsx
deleted file mode 100644
index e432806101..0000000000
--- a/app/src/components/intelligence/OrchestrationChatPrimitives.test.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { ChatMessage, ChatWindow } from '../../lib/orchestration/useOrchestrationChats';
-import { ChatListButton, MessageBubble } from './OrchestrationChatPrimitives';
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const chat = (over: Partial<ChatWindow>): ChatWindow =>
- ({
- id: 'sess-1',
- kind: 'session',
- title: 'Worker',
- subtitle: 'sub',
- preview: 'last message',
- pinned: false,
- active: true,
- unread: 0,
- lastTimestamp: '2026-07-01T12:00:00.000Z',
- ...over,
- }) as ChatWindow;
-
-describe('ChatListButton', () => {
- it('renders unread count + active badge for an active unread session', () => {
- render(
- <ChatListButton chat={chat({ unread: 4, active: true })} selected onSelect={() => {}} />
- );
- expect(screen.getByText('4')).toBeInTheDocument();
- expect(screen.getByText('tinyplaceOrchestration.active')).toBeInTheDocument();
- });
-
- it('renders the inactive badge and a contact badge when provided', () => {
- render(
- <ChatListButton
- chat={chat({ active: false })}
- selected={false}
- onSelect={() => {}}
- contactBadge="tinyplaceOrchestration.pairing.linked"
- />
- );
- expect(screen.getByText('tinyplaceOrchestration.inactive')).toBeInTheDocument();
- expect(screen.getByText('tinyplaceOrchestration.pairing.linked')).toBeInTheDocument();
- });
-
- it('shows the subconscious badge and fires onSelect', () => {
- const onSelect = vi.fn();
- render(
- <ChatListButton chat={chat({ kind: 'subconscious' })} selected={false} onSelect={onSelect} />
- );
- expect(screen.getByText('tinyplaceOrchestration.subconsciousBadge')).toBeInTheDocument();
- fireEvent.click(screen.getByTestId('tinyplace-chat-sess-1'));
- expect(onSelect).toHaveBeenCalled();
- });
-});
-
-describe('MessageBubble', () => {
- const message = (over: Partial<ChatMessage>): ChatMessage =>
- ({
- id: 'm1',
- from: '@peer',
- body: 'hello there',
- timestamp: '2026-07-01T12:00:00.000Z',
- encrypted: false,
- ...over,
- }) as ChatMessage;
-
- it('renders sender + body', () => {
- render(<MessageBubble message={message({})} />);
- expect(screen.getByText('@peer')).toBeInTheDocument();
- expect(screen.getByText('hello there')).toBeInTheDocument();
- });
-
- it('mutes an encrypted (undecryptable) message body', () => {
- render(<MessageBubble message={message({ encrypted: true, body: '••••' })} />);
- expect(screen.getByText('••••')).toHaveClass('text-content-muted');
- });
-
- it('renders a tool_call as a monospace command row with ▶ + tool name', () => {
- const { container } = render(
- <MessageBubble message={message({ eventKind: 'tool_call', toolName: 'Bash', body: 'ls' })} />
- );
- expect(container.querySelector('[data-event-kind="tool_call"]')).not.toBeNull();
- expect(screen.getByText('▶')).toBeInTheDocument();
- expect(screen.getByText('Bash')).toBeInTheDocument();
- expect(container.querySelector('p.font-mono')?.textContent).toBe('ls');
- });
-
- it('renders a tool_result with the ↳ glyph', () => {
- render(
- <MessageBubble
- message={message({ eventKind: 'tool_result', toolName: 'Bash', body: 'ok' })}
- />
- );
- expect(screen.getByText('↳')).toBeInTheDocument();
- });
-
- it('renders agent_thinking italic + muted with the ∴ glyph', () => {
- const { container } = render(
- <MessageBubble message={message({ eventKind: 'agent_thinking', body: 'considering…' })} />
- );
- expect(container.querySelector('p.italic')).not.toBeNull();
- expect(screen.getByText('∴')).toBeInTheDocument();
- });
-
- it('renders an error row with the ✕ glyph', () => {
- render(<MessageBubble message={message({ eventKind: 'error', body: 'boom' })} />);
- expect(screen.getByText('✕')).toBeInTheDocument();
- });
-
- it('falls back to the plain-dot style for a legacy v1 row (no eventKind)', () => {
- const { container } = render(<MessageBubble message={message({ body: 'plain' })} />);
- expect(container.querySelector('[data-event-kind="v1"]')).not.toBeNull();
- expect(container.querySelector('div.rounded-full')).not.toBeNull();
- expect(container.querySelector('p.font-mono')).toBeNull();
- });
-});
diff --git a/app/src/components/intelligence/OrchestrationChatPrimitives.tsx b/app/src/components/intelligence/OrchestrationChatPrimitives.tsx
deleted file mode 100644
index 05fa00f5dc..0000000000
--- a/app/src/components/intelligence/OrchestrationChatPrimitives.tsx
+++ /dev/null
@@ -1,177 +0,0 @@
-/**
- * Presentational primitives for the TinyPlace Orchestration tab's chat surface:
- * a sidebar list row ({@link ChatListButton}) and a message bubble
- * ({@link MessageBubble}). Extracted from the tab container so both the sidebar
- * and focus pane render chats identically.
- */
-import type { ReactElement } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type { ChatMessage, ChatWindow } from '../../lib/orchestration/useOrchestrationChats';
-import Button from '../ui/Button';
-import { formatTime } from './orchestrationTabHelpers';
-
-interface ChatListButtonProps {
- chat: ChatWindow;
- selected: boolean;
- onSelect: () => void;
- contactBadge?: string | null;
-}
-
-export function ChatListButton({
- chat,
- selected,
- onSelect,
- contactBadge,
-}: ChatListButtonProps): ReactElement {
- const { t } = useT();
- return (
- <Button
- variant="tertiary"
- data-testid={`tinyplace-chat-${chat.id}`}
- onClick={onSelect}
- className={`h-auto w-full items-start justify-start gap-3 rounded-none border-b border-line-subtle px-3 py-3 text-left font-normal transition last:border-b-0 hover:bg-surface-hover ${
- selected ? 'bg-surface-muted' : ''
- }`}>
- <span className="mt-0.5 flex h-9 w-9 flex-none items-center justify-center rounded-lg border border-line bg-surface-strong text-xs font-semibold text-content-secondary">
- {chat.kind === 'subconscious' ? 'S' : chat.kind === 'master' ? 'M' : '#'}
- </span>
- <span className="min-w-0 flex-1">
- <span className="flex items-center justify-between gap-2">
- <span className="truncate text-sm font-semibold text-content">{chat.title}</span>
- <span className="flex-none text-[10px] text-content-faint">
- {formatTime(chat.lastTimestamp)}
- </span>
- </span>
- <span className="mt-0.5 block truncate text-[11px] text-content-muted">
- {chat.kind === 'subconscious'
- ? t('tinyplaceOrchestration.subconsciousBadge')
- : chat.subtitle}
- </span>
- <span className="mt-1 flex items-center gap-2">
- <span className="min-w-0 flex-1 truncate text-xs text-content-faint">{chat.preview}</span>
- {chat.unread > 0 ? (
- <span className="flex-none rounded-full bg-primary-500 px-1.5 py-0.5 text-[10px] font-semibold text-content-inverted">
- {chat.unread}
- </span>
- ) : null}
- {!chat.pinned ? (
- <span
- className={`flex-none rounded-full px-1.5 py-0.5 text-[10px] font-medium ${
- chat.active
- ? 'bg-sage-100 text-sage-700 dark:bg-sage-500/15 dark:text-sage-300'
- : 'bg-surface-strong text-content-faint'
- }`}>
- {chat.active
- ? t('tinyplaceOrchestration.active')
- : t('tinyplaceOrchestration.inactive')}
- </span>
- ) : null}
- {contactBadge ? (
- <span className="flex-none rounded-full bg-surface-strong px-1.5 py-0.5 text-[10px] font-medium text-content-faint">
- {t(contactBadge)}
- </span>
- ) : null}
- </span>
- </span>
- </Button>
- );
-}
-
-/**
- * Per-kind presentation for a harness (v2) event row. Differentiates the typed
- * stream (tool_call / tool_result / agent_thinking / approval_request / error)
- * from plain agent/user messages so the orchestration thread reads like a live
- * activity log rather than undifferentiated text. Legacy v1 rows (no
- * `eventKind`) fall through to the default agent-message style.
- */
-interface BubbleStyle {
- /** Leading marker: a glyph when the kind has one, else a colored dot. */
- dot: string;
- glyph?: string;
- /** Render the body in a monospace block (tool command / output). */
- mono?: boolean;
- /** Body text tone. */
- tone: string;
- /** Optional left-accent on the bubble. */
- accent: string;
-}
-
-function bubbleStyle(kind: ChatMessage['eventKind']): BubbleStyle {
- switch (kind) {
- case 'tool_call':
- return {
- dot: 'text-primary-500',
- glyph: '▶',
- mono: true,
- tone: 'text-content',
- accent: 'border-l-2 border-l-primary-400',
- };
- case 'tool_result':
- return {
- dot: 'text-sage-500',
- glyph: '↳',
- mono: true,
- tone: 'text-content-muted',
- accent: 'border-l-2 border-l-sage-400',
- };
- case 'agent_thinking':
- return {
- dot: 'text-content-faint',
- glyph: '∴',
- tone: 'italic text-content-faint',
- accent: '',
- };
- case 'approval_request':
- return {
- dot: 'text-amber-500',
- glyph: '⚠',
- tone: 'text-content',
- accent: 'border-l-2 border-l-amber-400',
- };
- case 'error':
- return {
- dot: 'text-coral-500',
- glyph: '✕',
- tone: 'text-coral-600 dark:text-coral-300',
- accent: 'border-l-2 border-l-coral-400',
- };
- case 'user_prompt':
- return { dot: 'text-sage-500', tone: 'text-content', accent: '' };
- default:
- return { dot: 'text-primary-500', tone: 'text-content', accent: '' };
- }
-}
-
-export function MessageBubble({ message }: { message: ChatMessage }): ReactElement {
- const style = bubbleStyle(message.eventKind);
- return (
- <div className="flex gap-2" data-event-kind={message.eventKind ?? 'v1'}>
- {style.glyph ? (
- <span className={`mt-0.5 flex-none text-xs font-semibold ${style.dot}`}>{style.glyph}</span>
- ) : (
- <div
- className={`mt-1.5 h-2 w-2 flex-none rounded-full ${style.dot.replace('text-', 'bg-')}`}
- />
- )}
- <div
- className={`min-w-0 rounded-lg border border-line bg-surface px-3 py-2 shadow-soft ${style.accent}`}>
- <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
- <span className="text-xs font-semibold text-content-secondary">{message.from}</span>
- {message.toolName ? (
- <span className="rounded bg-surface-strong px-1.5 py-0.5 font-mono text-[10px] text-content-secondary">
- {message.toolName}
- </span>
- ) : null}
- <span className="text-[10px] text-content-faint">{formatTime(message.timestamp)}</span>
- </div>
- <p
- className={`mt-1 max-h-64 overflow-y-auto whitespace-pre-wrap wrap-break-word ${
- style.mono ? 'font-mono text-xs' : 'text-sm'
- } ${message.encrypted ? 'text-content-muted' : style.tone}`}>
- {message.body}
- </p>
- </div>
- </div>
- );
-}
diff --git a/app/src/components/intelligence/OrchestrationFocusPane.test.tsx b/app/src/components/intelligence/OrchestrationFocusPane.test.tsx
deleted file mode 100644
index 4f50fd8e77..0000000000
--- a/app/src/components/intelligence/OrchestrationFocusPane.test.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { fireEvent, render, screen, within } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { ChatWindow } from '../../lib/orchestration/useOrchestrationChats';
-import OrchestrationFocusPane, { type OrchestrationFocusPaneProps } from './OrchestrationFocusPane';
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const chat = (over: Partial<ChatWindow>): ChatWindow =>
- ({
- id: 'sess-1',
- kind: 'session',
- title: 'Worker Alpha',
- subtitle: 'sub',
- pinned: false,
- active: true,
- unread: 0,
- messages: [],
- lastTimestamp: '2026-07-01T12:00:00.000Z',
- ...over,
- }) as ChatWindow;
-
-let refresh: ReturnType<typeof vi.fn>;
-
-const props = (over: Partial<OrchestrationFocusPaneProps>): OrchestrationFocusPaneProps =>
- ({
- selected: chat({}),
- sessionsState: { status: 'ok' },
- messagesState: { status: 'ok' },
- status: null,
- masterError: null,
- refresh,
- steeringText: null,
- canCompose: false,
- composerBody: '',
- onComposerChange: vi.fn(),
- sending: false,
- onSubmitComposer: vi.fn(),
- ...over,
- }) as OrchestrationFocusPaneProps;
-
-describe('OrchestrationFocusPane', () => {
- beforeEach(() => {
- refresh = vi.fn();
- });
-
- it('renders the payment-required state', () => {
- render(
- <OrchestrationFocusPane {...props({ sessionsState: { status: 'payment_required' } })} />
- );
- expect(screen.getByText('tinyplaceOrchestration.paymentRequired')).toBeInTheDocument();
- });
-
- it('renders a sessions load error and retries', () => {
- render(
- <OrchestrationFocusPane
- {...props({ sessionsState: { status: 'error', message: 'rpc down' } })}
- />
- );
- expect(screen.getByText(/tinyplaceOrchestration.failedToLoad/)).toBeInTheDocument();
- expect(screen.getByText(/rpc down/)).toBeInTheDocument();
- fireEvent.click(screen.getByText('common.retry'));
- expect(refresh).toHaveBeenCalled();
- });
-
- it('renders a messages load error', () => {
- render(
- <OrchestrationFocusPane
- {...props({ messagesState: { status: 'error', message: 'msg boom' } })}
- />
- );
- expect(screen.getByText(/msg boom/)).toBeInTheDocument();
- });
-
- it('surfaces a composer send error when composing', () => {
- render(<OrchestrationFocusPane {...props({ canCompose: true, masterError: 'send failed' })} />);
- expect(screen.getByTestId('tinyplace-master-composer-input')).toBeInTheDocument();
- expect(screen.getByText(/send failed/)).toBeInTheDocument();
- });
-
- it('renders message bubbles for the selected chat', () => {
- render(
- <OrchestrationFocusPane
- {...props({
- selected: chat({
- messages: [
- {
- id: 'm1',
- from: '@peer',
- body: 'hi there',
- timestamp: '2026-07-01T12:00:00.000Z',
- encrypted: false,
- },
- ] as never,
- }),
- })}
- />
- );
- expect(
- within(screen.getByTestId('tinyplace-chat-messages')).getByText('hi there')
- ).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/OrchestrationFocusPane.tsx b/app/src/components/intelligence/OrchestrationFocusPane.tsx
deleted file mode 100644
index 4a972bf534..0000000000
--- a/app/src/components/intelligence/OrchestrationFocusPane.tsx
+++ /dev/null
@@ -1,169 +0,0 @@
-/**
- * OrchestrationFocusPane — the right-hand focus column of the TinyPlace
- * Orchestration tab: the selected chat's header, the subconscious steering
- * status header, the message transcript (with load/error/empty states), and the
- * Master/session composer. Presentational: all state + handlers come from the
- * tab container.
- */
-import type { FormEvent, ReactElement } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type { useOrchestrationChats } from '../../lib/orchestration/useOrchestrationChats';
-import Button from '../ui/Button';
-import TextField from '../ui/TextField';
-import { MessageBubble } from './OrchestrationChatPrimitives';
-
-type ChatsApi = ReturnType<typeof useOrchestrationChats>;
-
-export interface OrchestrationFocusPaneProps {
- selected: ChatsApi['selected'];
- sessionsState: ChatsApi['sessionsState'];
- messagesState: ChatsApi['messagesState'];
- status: ChatsApi['status'];
- masterError: ChatsApi['masterError'];
- refresh: ChatsApi['refresh'];
- steeringText: string | null;
- canCompose: boolean;
- composerBody: string;
- onComposerChange: (value: string) => void;
- sending: boolean;
- onSubmitComposer: (event: FormEvent<HTMLFormElement>) => void;
-}
-
-export default function OrchestrationFocusPane({
- selected,
- sessionsState,
- messagesState,
- status,
- masterError,
- refresh,
- steeringText,
- canCompose,
- composerBody,
- onComposerChange,
- sending,
- onSubmitComposer,
-}: OrchestrationFocusPaneProps): ReactElement {
- const { t } = useT();
- return (
- <main className="flex min-w-0 flex-1 flex-col bg-surface">
- <div className="flex items-center justify-between gap-3 border-b border-line px-5 py-4">
- <div className="min-w-0">
- <h3 className="truncate text-base font-semibold text-content">{selected?.title}</h3>
- <p className="mt-0.5 truncate text-xs text-content-muted">{selected?.subtitle}</p>
- </div>
- {selected && !selected.pinned ? (
- <span
- className={`rounded-full px-2 py-1 text-xs font-medium ${
- selected.active
- ? 'bg-sage-100 text-sage-700 dark:bg-sage-500/15 dark:text-sage-300'
- : 'bg-surface-strong text-content-muted'
- }`}>
- {selected.active
- ? t('tinyplaceOrchestration.active')
- : t('tinyplaceOrchestration.inactive')}
- </span>
- ) : null}
- </div>
-
- {/* Steering status header — the tinyplace subconscious instance's output. */}
- {selected?.kind === 'subconscious' ? (
- <div
- data-testid="tinyplace-steering-header"
- className="flex items-center justify-between gap-3 border-b border-line bg-amber-50/40 px-5 py-3 dark:bg-amber-500/5">
- <div className="min-w-0">
- <p className="text-xs font-medium text-content">
- {steeringText
- ? t('tinyplaceOrchestration.steeringHeader.current')
- : t('tinyplaceOrchestration.steeringHeader.none')}
- </p>
- {steeringText ? (
- <p className="mt-0.5 truncate text-xs text-content-muted">{steeringText}</p>
- ) : null}
- <p className="mt-0.5 text-[11px] text-content-faint">
- {status?.steering
- ? t('tinyplaceOrchestration.steeringHeader.expires').replace(
- '{n}',
- String(status.steering.expiresAfterCycles)
- )
- : ''}
- </p>
- </div>
- </div>
- ) : null}
-
- {sessionsState.status === 'loading' ? (
- <div className="flex flex-1 items-center justify-center text-sm text-content-muted">
- {t('tinyplaceOrchestration.loading')}
- </div>
- ) : sessionsState.status === 'payment_required' ? (
- <div className="flex flex-1 items-center justify-center text-sm text-amber-600 dark:text-amber-300">
- {t('tinyplaceOrchestration.paymentRequired')}
- </div>
- ) : sessionsState.status === 'error' ? (
- <div className="flex flex-1 flex-col items-center justify-center gap-3 text-sm text-coral-600 dark:text-coral-300">
- <p>
- {t('tinyplaceOrchestration.failedToLoad')}: {sessionsState.message}
- </p>
- <Button variant="secondary" size="sm" onClick={() => void refresh()}>
- {t('common.retry')}
- </Button>
- </div>
- ) : messagesState.status === 'loading' ? (
- <div className="flex flex-1 items-center justify-center text-sm text-content-muted">
- {t('tinyplaceOrchestration.loading')}
- </div>
- ) : messagesState.status === 'error' ? (
- <div className="flex flex-1 flex-col items-center justify-center gap-3 text-sm text-coral-600 dark:text-coral-300">
- <p>
- {t('tinyplaceOrchestration.failedToLoad')}: {messagesState.message}
- </p>
- <Button variant="secondary" size="sm" onClick={() => void refresh()}>
- {t('common.retry')}
- </Button>
- </div>
- ) : selected?.messages.length ? (
- <div className="min-h-0 flex-1 overflow-y-auto bg-surface-muted/20 p-5">
- <div className="space-y-3" data-testid="tinyplace-chat-messages">
- {selected.messages.map(message => (
- <MessageBubble key={message.id} message={message} />
- ))}
- </div>
- </div>
- ) : (
- <div className="flex flex-1 items-center justify-center px-6 text-center text-sm text-content-faint">
- {t('tinyplaceOrchestration.noMessages')}
- </div>
- )}
-
- {canCompose && sessionsState.status === 'ok' ? (
- <form
- className="flex flex-col gap-2 border-t border-line px-5 py-3"
- onSubmit={onSubmitComposer}>
- {masterError ? (
- <p className="rounded-md bg-coral-50 px-2 py-1 text-xs text-coral-700 dark:bg-coral-500/10 dark:text-coral-300">
- {t('tinyplaceOrchestration.composer.sendFailed')}: {masterError}
- </p>
- ) : null}
- <div className="flex gap-2">
- <TextField
- data-testid="tinyplace-master-composer-input"
- value={composerBody}
- onChange={event => onComposerChange(event.target.value)}
- placeholder={t('tinyplaceOrchestration.composer.placeholder')}
- className="min-w-0 flex-1"
- />
- <Button
- type="submit"
- variant="primary"
- size="sm"
- data-testid="tinyplace-master-composer-send"
- disabled={!composerBody.trim() || sending}>
- {t('tinyplaceOrchestration.composer.send')}
- </Button>
- </div>
- </form>
- ) : null}
- </main>
- );
-}
diff --git a/app/src/components/intelligence/OrchestrationSidebar.test.tsx b/app/src/components/intelligence/OrchestrationSidebar.test.tsx
deleted file mode 100644
index 1298bd1fa2..0000000000
--- a/app/src/components/intelligence/OrchestrationSidebar.test.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-import { fireEvent, render, screen, within } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { apiClient } from '../../lib/agentworld/apiClient';
-import type { ContactView } from '../../lib/agentworld/invokeApiClient';
-import OrchestrationSidebar, { type OrchestrationSidebarProps } from './OrchestrationSidebar';
-
-vi.mock('../../lib/agentworld/apiClient', () => ({
- apiClient: {
- orchestrationPairing: {
- acceptRequest: vi.fn(async () => ({})),
- declineRequest: vi.fn(async () => ({})),
- blockRequest: vi.fn(async () => ({})),
- },
- },
-}));
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const acceptMock = vi.mocked(apiClient.orchestrationPairing.acceptRequest);
-const declineMock = vi.mocked(apiClient.orchestrationPairing.declineRequest);
-const blockMock = vi.mocked(apiClient.orchestrationPairing.blockRequest);
-
-const REQUESTER = '3icjiLXhn6BMv43MsHjpKKxm7hEYBk7R5rvNXB1HUk7g';
-
-const request = (): ContactView =>
- ({ agentId: REQUESTER, status: 'pending', direction: 'incoming' }) as ContactView;
-
-let onCreateSession: ReturnType<typeof vi.fn>;
-let onToggleContact: ReturnType<typeof vi.fn>;
-
-const props = (over: Partial<OrchestrationSidebarProps>): OrchestrationSidebarProps =>
- ({
- relayInfo: null,
- onRefreshAll: vi.fn(),
- refreshDisabled: false,
- steeringText: null,
- selfIdentity: null,
- identityLoading: false,
- onPublishIdentity: vi.fn(),
- publishingIdentity: false,
- publishIdentityError: null,
- attentionQueue: null,
- attentionLoading: false,
- onAttentionAction: vi.fn(),
- linkAgentId: '',
- onLinkAgentIdChange: vi.fn(),
- onSubmitLink: vi.fn(),
- pairingAction: null,
- contactStats: null,
- incomingRequests: [],
- outgoingCount: 0,
- pairingError: null,
- agentHandles: {},
- // Invoke the thunk so the underlying apiClient call is exercised.
- runPairingAction: vi.fn((_id: string, thunk: () => Promise<unknown>) => thunk()),
- pinned: [],
- selectedId: null,
- onSelectChat: vi.fn(),
- acceptedContactList: [],
- expandedContacts: {},
- onToggleContact,
- sessionsByContact: new Map(),
- creatingSession: null,
- onCreateSession,
- acceptedContacts: new Set<string>(),
- pendingContacts: new Set<string>(),
- ungroupedSessions: [],
- ...over,
- }) as OrchestrationSidebarProps;
-
-describe('OrchestrationSidebar', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- onCreateSession = vi.fn();
- onToggleContact = vi.fn();
- });
-
- it('runs accept / decline / block on an incoming request, resolving its address', () => {
- render(
- <OrchestrationSidebar
- {...props({ incomingRequests: [request()], agentHandles: { [REQUESTER]: 'peer' } })}
- />
- );
-
- // Handle is shown additively alongside the raw address.
- expect(screen.getByText('@peer')).toBeInTheDocument();
- expect(screen.getByText(REQUESTER)).toBeInTheDocument();
-
- fireEvent.click(screen.getByText('tinyplaceOrchestration.pairing.accept'));
- fireEvent.click(screen.getByText('tinyplaceOrchestration.pairing.decline'));
- fireEvent.click(screen.getByText('tinyplaceOrchestration.pairing.block'));
-
- expect(acceptMock).toHaveBeenCalledWith(REQUESTER);
- expect(declineMock).toHaveBeenCalledWith(REQUESTER);
- expect(blockMock).toHaveBeenCalledWith(REQUESTER);
- });
-
- it('expands a contact and starts a new session under it', () => {
- const contact = {
- agentId: REQUESTER,
- status: 'accepted',
- direction: 'incoming',
- } as ContactView;
-
- render(
- <OrchestrationSidebar
- {...props({
- acceptedContactList: [contact],
- expandedContacts: { [REQUESTER]: true },
- agentHandles: { [REQUESTER]: 'peer' },
- })}
- />
- );
-
- fireEvent.click(screen.getByTestId(`tinyplace-new-session-${REQUESTER}`));
- expect(onCreateSession).toHaveBeenCalledWith(REQUESTER);
-
- fireEvent.click(
- within(screen.getByTestId(`tinyplace-contact-${REQUESTER}`)).getByText('@peer')
- );
- expect(onToggleContact).toHaveBeenCalledWith(REQUESTER);
- });
-});
diff --git a/app/src/components/intelligence/OrchestrationSidebar.tsx b/app/src/components/intelligence/OrchestrationSidebar.tsx
deleted file mode 100644
index 5df00fed62..0000000000
--- a/app/src/components/intelligence/OrchestrationSidebar.tsx
+++ /dev/null
@@ -1,418 +0,0 @@
-/**
- * OrchestrationSidebar — the left rail of the TinyPlace Orchestration tab: the
- * topbar (title + relay badge + refresh + launch shell), the self-identity card,
- * the "Needs you" attention zone, the pairing panel (link form, stats, incoming
- * requests), and the roster tree (pinned chats + accepted contacts with their
- * nested sessions + ungrouped sessions).
- *
- * Presentational: all state + handlers come from the tab container. It imports
- * `apiClient` and the shared helpers directly so the request-action JSX stays
- * identical to the pre-extraction container.
- */
-import debugFactory from 'debug';
-import type { FormEvent, ReactElement } from 'react';
-
-import { apiClient } from '../../lib/agentworld/apiClient';
-import type { ContactView, PairingSnapshot } from '../../lib/agentworld/invokeApiClient';
-import { useT } from '../../lib/i18n/I18nContext';
-import type {
- AttentionAction,
- AttentionQueue,
- RelayInfo,
- SelfIdentity,
-} from '../../lib/orchestration/orchestrationClient';
-import type { ChatWindow } from '../../lib/orchestration/useOrchestrationChats';
-import { AccordionContent, AccordionItem, AccordionRoot, AccordionTrigger } from '../ui/Accordion';
-import Button from '../ui/Button';
-import TextField from '../ui/TextField';
-import AttentionQueueView from './AttentionQueue';
-import { ChatListButton } from './OrchestrationChatPrimitives';
-import { contactAddress, contactBadgeKey, truncate } from './orchestrationTabHelpers';
-import RelayBadge from './RelayBadge';
-import SelfIdentityCard from './SelfIdentityCard';
-
-const debug = debugFactory('brain:tinyplace-orchestration');
-
-export interface OrchestrationSidebarProps {
- relayInfo: RelayInfo | null;
- onRefreshAll: () => void;
- refreshDisabled: boolean;
- steeringText: string | null;
- selfIdentity: SelfIdentity | null;
- identityLoading: boolean;
- onPublishIdentity: () => void;
- publishingIdentity: boolean;
- publishIdentityError: string | null;
- attentionQueue: AttentionQueue | null;
- attentionLoading: boolean;
- onAttentionAction: (action: AttentionAction) => void;
- linkAgentId: string;
- onLinkAgentIdChange: (value: string) => void;
- onSubmitLink: (event: FormEvent<HTMLFormElement>) => void;
- pairingAction: string | null;
- contactStats: PairingSnapshot['stats'] | null;
- incomingRequests: ContactView[];
- outgoingCount: number;
- pairingError: string | null;
- agentHandles: Record<string, string | null>;
- runPairingAction: (actionId: string, action: () => Promise<unknown>) => Promise<void>;
- pinned: ChatWindow[];
- selectedId: string | null;
- onSelectChat: (id: string) => void;
- acceptedContactList: ContactView[];
- expandedContacts: Record<string, boolean>;
- onToggleContact: (address: string) => void;
- sessionsByContact: Map<string, ChatWindow[]>;
- creatingSession: string | null;
- onCreateSession: (address: string) => void;
- acceptedContacts: Set<string>;
- pendingContacts: Set<string>;
- ungroupedSessions: ChatWindow[];
-}
-
-export default function OrchestrationSidebar({
- relayInfo,
- onRefreshAll,
- refreshDisabled,
- steeringText,
- selfIdentity,
- identityLoading,
- onPublishIdentity,
- publishingIdentity,
- publishIdentityError,
- attentionQueue,
- attentionLoading,
- onAttentionAction,
- linkAgentId,
- onLinkAgentIdChange,
- onSubmitLink,
- pairingAction,
- contactStats,
- incomingRequests,
- outgoingCount,
- pairingError,
- agentHandles,
- runPairingAction,
- pinned,
- selectedId,
- onSelectChat,
- acceptedContactList,
- expandedContacts,
- onToggleContact,
- sessionsByContact,
- creatingSession,
- onCreateSession,
- acceptedContacts,
- pendingContacts,
- ungroupedSessions,
-}: OrchestrationSidebarProps): ReactElement {
- const { t } = useT();
-
- // Each accepted contact is its own independent disclosure — several can be
- // open at once, so this is Accordion `type="multiple"`, not `single`. The
- // open set is still owned by the tab container (`expandedContacts` +
- // `onToggleContact`); Radix's controlled `value` just wants it as an array
- // rather than a lookup map, and `onValueChange` fires with the *whole* next
- // array, so the delta against the previous set is what maps back onto the
- // per-address toggle callback the container expects.
- const openContactAddresses = Object.keys(expandedContacts).filter(
- address => expandedContacts[address]
- );
- const handleContactValueChange = (nextOpen: string[]) => {
- const next = new Set(nextOpen);
- const previous = new Set(openContactAddresses);
- for (const address of nextOpen) {
- if (!previous.has(address)) onToggleContact(address);
- }
- for (const address of openContactAddresses) {
- if (!next.has(address)) onToggleContact(address);
- }
- };
-
- return (
- <aside className="flex w-80 flex-none flex-col border-r border-line bg-surface-muted/40">
- <div className="border-b border-line px-4 py-3">
- <div className="flex items-center justify-between gap-3">
- <div className="min-w-0">
- <div className="flex items-center gap-1.5">
- <h3 className="truncate text-sm font-semibold text-content">
- {t('tinyplaceOrchestration.title')}
- </h3>
- <RelayBadge relay={relayInfo} />
- </div>
- <p className="mt-0.5 truncate text-[11px] text-content-muted">
- {t('tinyplaceOrchestration.subtitle')}
- </p>
- </div>
- <div className="flex flex-none items-center gap-1.5">
- <Button
- variant="secondary"
- size="sm"
- onClick={onRefreshAll}
- aria-label={t('tinyplaceOrchestration.refresh')}
- disabled={refreshDisabled}>
- {t('tinyplaceOrchestration.refresh')}
- </Button>
- {/* Launch shell — external instance spawn is wired in a later PR. */}
- <Button
- variant="primary"
- size="sm"
- data-testid="tinyplace-new-instance"
- disabled
- title={t('tinyplaceOrchestration.newInstanceSoon')}>
- {t('tinyplaceOrchestration.newInstance')}
- </Button>
- </div>
- </div>
- {steeringText ? (
- <div
- data-testid="tinyplace-steering-chip"
- className="mt-2 flex items-start gap-1.5 rounded-md bg-amber-50 px-2 py-1 text-[11px] text-amber-700 dark:bg-amber-500/10 dark:text-amber-300">
- <span className="flex-none font-semibold uppercase tracking-wide">
- {t('tinyplaceOrchestration.steering.label')}
- </span>
- <span className="min-w-0 flex-1 truncate">{truncate(steeringText, 72)}</span>
- </div>
- ) : null}
- </div>
-
- <SelfIdentityCard
- identity={selfIdentity}
- loading={identityLoading}
- onPublish={onPublishIdentity}
- publishing={publishingIdentity}
- publishError={publishIdentityError}
- />
-
- <AttentionQueueView
- queue={attentionQueue}
- loading={attentionLoading}
- onAction={onAttentionAction}
- />
-
- <section className="border-b border-line px-4 py-3">
- <form className="space-y-2" onSubmit={onSubmitLink}>
- <label
- htmlFor="tinyplace-session-agent-id"
- className="block text-[10px] font-semibold uppercase tracking-wide text-content-muted">
- {t('tinyplaceOrchestration.pairing.linkLabel')}
- </label>
- <div className="flex gap-2">
- <TextField
- id="tinyplace-session-agent-id"
- inputSize="sm"
- value={linkAgentId}
- onChange={event => onLinkAgentIdChange(event.target.value)}
- placeholder={t('tinyplaceOrchestration.pairing.linkPlaceholder')}
- className="min-w-0 flex-1 text-xs"
- />
- <Button
- type="submit"
- variant="secondary"
- size="sm"
- disabled={!linkAgentId.trim() || pairingAction !== null}>
- {t('tinyplaceOrchestration.pairing.linkAction')}
- </Button>
- </div>
- </form>
-
- <div className="mt-2 flex flex-wrap gap-1.5 text-[10px] text-content-faint">
- <span className="rounded-full bg-surface-strong px-2 py-0.5">
- {t('tinyplaceOrchestration.pairing.linked')}: {contactStats?.contactCount ?? 0}
- </span>
- <span className="rounded-full bg-surface-strong px-2 py-0.5">
- {t('tinyplaceOrchestration.pairing.incoming')}: {incomingRequests.length}
- </span>
- <span className="rounded-full bg-surface-strong px-2 py-0.5">
- {t('tinyplaceOrchestration.pairing.outgoing')}: {outgoingCount}
- </span>
- </div>
-
- {pairingError ? (
- <p className="mt-2 rounded-md bg-coral-50 px-2 py-1 text-xs text-coral-700 dark:bg-coral-500/10 dark:text-coral-300">
- {pairingError}
- </p>
- ) : null}
-
- {incomingRequests.length > 0 ? (
- <div className="mt-3 space-y-2">
- <h4 className="text-[10px] font-semibold uppercase tracking-wide text-content-muted">
- {t('tinyplaceOrchestration.pairing.requests')}
- </h4>
- {incomingRequests.map((request, index) => {
- const address = contactAddress(request);
- const handle = address ? agentHandles[address] : null;
- return (
- <div
- key={address || `request-${index}`}
- className="rounded-lg border border-line bg-surface px-2 py-2">
- {handle ? (
- <div className="truncate text-xs font-medium text-content">@{handle}</div>
- ) : null}
- <div className="truncate font-mono text-[11px] text-content-muted">{address}</div>
- <div className="mt-2 flex gap-1.5">
- <Button
- variant="primary"
- size="sm"
- disabled={pairingAction !== null || !address}
- onClick={() =>
- void runPairingAction(`accept:${address}`, () =>
- apiClient.orchestrationPairing.acceptRequest(address)
- )
- }>
- {t('tinyplaceOrchestration.pairing.accept')}
- </Button>
- <Button
- variant="secondary"
- size="sm"
- disabled={pairingAction !== null || !address}
- onClick={() =>
- void runPairingAction(`remove:${address}`, () =>
- apiClient.orchestrationPairing.declineRequest(address)
- )
- }>
- {t('tinyplaceOrchestration.pairing.decline')}
- </Button>
- <Button
- variant="secondary"
- size="sm"
- disabled={pairingAction !== null || !address}
- onClick={() =>
- void runPairingAction(`block:${address}`, () =>
- apiClient.orchestrationPairing.blockRequest(address)
- )
- }>
- {t('tinyplaceOrchestration.pairing.block')}
- </Button>
- </div>
- </div>
- );
- })}
- </div>
- ) : null}
- </section>
-
- <div className="min-h-0 flex-1 overflow-y-auto">
- <section>
- <h4 className="px-3 pb-1 pt-3 text-[10px] font-semibold uppercase tracking-wide text-content-muted">
- {t('tinyplaceOrchestration.pinned')}
- </h4>
- <div>
- {pinned.map(chat => (
- <ChatListButton
- key={chat.id}
- chat={chat}
- selected={selectedId === chat.id}
- onSelect={() => {
- debug('[tinyplace-orchestration] open pinned id=%s', chat.id);
- onSelectChat(chat.id);
- }}
- />
- ))}
- </div>
- </section>
-
- <section>
- <h4 className="px-3 pb-1 pt-3 text-[10px] font-semibold uppercase tracking-wide text-content-muted">
- {t('tinyplaceOrchestration.contacts')}
- </h4>
- {acceptedContactList.length === 0 ? (
- <div className="px-4 py-8 text-center text-sm text-content-faint">
- {t('tinyplaceOrchestration.noContacts')}
- </div>
- ) : (
- <AccordionRoot
- type="multiple"
- value={openContactAddresses}
- onValueChange={handleContactValueChange}
- className="divide-y-0 space-y-1 px-2 pb-2">
- {acceptedContactList.map((contact, index) => {
- const address = contactAddress(contact);
- const handle = address ? agentHandles[address] : null;
- const isOpen = !!expandedContacts[address];
- const contactSessions = address ? (sessionsByContact.get(address) ?? []) : [];
- return (
- <AccordionItem
- key={address || `contact-${index}`}
- value={address}
- className="overflow-hidden rounded-lg border border-line bg-surface">
- <AccordionTrigger
- showChevron={false}
- size="sm"
- data-testid={`tinyplace-contact-${address}`}
- className="px-2 py-2">
- <span className="flex-none text-[10px] text-content-muted">
- {isOpen ? '▾' : '▸'}
- </span>
- <span className="min-w-0 flex-1">
- {handle ? (
- <span className="block truncate text-xs font-medium text-content">
- @{handle}
- </span>
- ) : null}
- <span className="block truncate font-mono text-[11px] text-content-muted">
- {address}
- </span>
- </span>
- {contactSessions.length > 0 ? (
- <span className="flex-none rounded-full bg-surface-strong px-1.5 py-0.5 text-[10px] font-medium text-content-faint">
- {contactSessions.length}
- </span>
- ) : null}
- </AccordionTrigger>
- <AccordionContent className="px-0 pb-0">
- <div className="border-t border-line-subtle">
- {contactSessions.map(chat => (
- <ChatListButton
- key={chat.id}
- chat={chat}
- selected={selectedId === chat.id}
- contactBadge={contactBadgeKey(chat, acceptedContacts, pendingContacts)}
- onSelect={() => {
- debug('[tinyplace-orchestration] open session id=%s', chat.id);
- onSelectChat(chat.id);
- }}
- />
- ))}
- <button
- type="button"
- data-testid={`tinyplace-new-session-${address}`}
- disabled={!address || creatingSession === address}
- onClick={() => onCreateSession(address)}
- className="flex w-full items-center gap-1 px-3 py-2 text-left text-[11px] font-medium text-primary-600 dark:text-primary-400 transition hover:bg-surface-hover disabled:opacity-50">
- + {t('tinyplaceOrchestration.newSession')}
- </button>
- </div>
- </AccordionContent>
- </AccordionItem>
- );
- })}
- </AccordionRoot>
- )}
- </section>
-
- {ungroupedSessions.length > 0 ? (
- <section>
- <h4 className="px-3 pb-1 pt-3 text-[10px] font-semibold uppercase tracking-wide text-content-muted">
- {t('tinyplaceOrchestration.otherSessions')}
- </h4>
- <div>
- {ungroupedSessions.map(chat => (
- <ChatListButton
- key={chat.id}
- chat={chat}
- selected={selectedId === chat.id}
- contactBadge={contactBadgeKey(chat, acceptedContacts, pendingContacts)}
- onSelect={() => {
- debug('[tinyplace-orchestration] open session id=%s', chat.id);
- onSelectChat(chat.id);
- }}
- />
- ))}
- </div>
- </section>
- ) : null}
- </div>
- </aside>
- );
-}
diff --git a/app/src/components/intelligence/RelayBadge.test.tsx b/app/src/components/intelligence/RelayBadge.test.tsx
deleted file mode 100644
index 87d9594080..0000000000
--- a/app/src/components/intelligence/RelayBadge.test.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import RelayBadge from './RelayBadge';
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-describe('RelayBadge', () => {
- it('renders nothing when relay info is absent', () => {
- const { container } = render(<RelayBadge relay={null} />);
- expect(container.firstChild).toBeNull();
- });
-
- it('shows the staging label + base url and tags the network', () => {
- render(
- <RelayBadge relay={{ baseUrl: 'https://staging-api.tiny.place', network: 'staging' }} />
- );
- const badge = screen.getByTestId('tinyplace-relay-badge');
- expect(badge).toHaveAttribute('data-network', 'staging');
- expect(badge).toHaveAttribute('title', 'https://staging-api.tiny.place');
- expect(badge).toHaveTextContent('tinyplaceOrchestration.relay.staging');
- });
-
- it('shows the production label for the prod relay', () => {
- render(<RelayBadge relay={{ baseUrl: 'https://api.tiny.place', network: 'prod' }} />);
- const badge = screen.getByTestId('tinyplace-relay-badge');
- expect(badge).toHaveAttribute('data-network', 'prod');
- expect(badge).toHaveTextContent('tinyplaceOrchestration.relay.prod');
- });
-});
diff --git a/app/src/components/intelligence/RelayBadge.tsx b/app/src/components/intelligence/RelayBadge.tsx
deleted file mode 100644
index 754b18f23f..0000000000
--- a/app/src/components/intelligence/RelayBadge.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * RelayBadge — a small always-visible pill naming the tiny.place relay the core
- * is talking to (STAGING / PRODUCTION).
- *
- * Why it exists: during live debugging, claudebot sat on `staging-api.tiny.place`
- * while the core silently defaulted to prod `api.tiny.place`, producing a mystery
- * 404. Nothing on screen said which relay either side used. Surfacing the target
- * relay as a first-class chip makes a mismatch obvious instead of opaque.
- *
- * Presentational only — the parent fetches {@link RelayInfo} via
- * `orchestrationClient.relayInfo()` and passes it down.
- */
-import { useT } from '../../lib/i18n/I18nContext';
-import type { RelayInfo } from '../../lib/orchestration/orchestrationClient';
-
-interface RelayBadgeProps {
- relay: RelayInfo | null;
-}
-
-export default function RelayBadge({ relay }: RelayBadgeProps): React.ReactElement | null {
- const { t } = useT();
- if (!relay) return null;
-
- const isStaging = relay.network === 'staging';
- const label = isStaging
- ? t('tinyplaceOrchestration.relay.staging')
- : t('tinyplaceOrchestration.relay.prod');
-
- // Staging is the everyday dev target (amber, "you're on the test relay");
- // production is the live one (sage). Colour, not just text, so it's scannable.
- const tone = isStaging
- ? 'border-amber-400 text-amber-700 dark:border-amber-500/60 dark:text-amber-300'
- : 'border-sage-400 text-sage-700 dark:border-sage-500/60 dark:text-sage-300';
-
- return (
- <span
- data-testid="tinyplace-relay-badge"
- data-network={relay.network}
- title={relay.baseUrl}
- className={`inline-flex flex-none items-center rounded-md border px-1.5 py-0.5 font-mono text-[10px] font-bold uppercase tracking-wide ${tone}`}>
- {label}
- </span>
- );
-}
diff --git a/app/src/components/intelligence/SelfIdentityCard.test.tsx b/app/src/components/intelligence/SelfIdentityCard.test.tsx
deleted file mode 100644
index f872ec2ca8..0000000000
--- a/app/src/components/intelligence/SelfIdentityCard.test.tsx
+++ /dev/null
@@ -1,133 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { SelfIdentity } from '../../lib/orchestration/orchestrationClient';
-import SelfIdentityCard from './SelfIdentityCard';
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const discoverable: SelfIdentity = {
- agentId: '6wNaBJkatir4B86cw5ykHZWQ3xoNaKygX5vAU9MQbHSh',
- handles: [{ username: 'openhuman', primary: true }],
- primaryHandle: 'openhuman',
- cardPublished: true,
- keyPublished: true,
- discoverable: true,
-};
-
-describe('SelfIdentityCard', () => {
- beforeEach(() => {
- Object.assign(navigator, { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } });
- });
-
- it('shows a loading state before the identity resolves', () => {
- render(<SelfIdentityCard identity={null} loading />);
- expect(screen.getByTestId('tinyplace-self-identity')).toHaveTextContent(
- 'tinyplaceOrchestration.identity.loading'
- );
- });
-
- it('renders nothing once loaded with no identity', () => {
- const { container } = render(<SelfIdentityCard identity={null} loading={false} />);
- expect(container.firstChild).toBeNull();
- });
-
- it('renders the primary handle, shortened address and discoverable status', () => {
- render(<SelfIdentityCard identity={discoverable} loading={false} />);
- expect(screen.getByText('@openhuman')).toBeInTheDocument();
- // Address is shortened but the full value is preserved in the title.
- expect(screen.getByText('6wNaBJ…QbHSh')).toHaveAttribute('title', discoverable.agentId);
- const status = screen.getByTestId('tinyplace-self-identity-status');
- expect(status).toHaveAttribute('data-discoverable', 'true');
- });
-
- it('flags an un-messageable identity and shows the register hint', () => {
- const undiscoverable: SelfIdentity = {
- agentId: 'addrWithNoCardPublishedYet',
- handles: [],
- cardPublished: false,
- keyPublished: false,
- discoverable: false,
- };
- render(<SelfIdentityCard identity={undiscoverable} loading={false} />);
- expect(screen.getByText('tinyplaceOrchestration.identity.noHandle')).toBeInTheDocument();
- expect(screen.getByTestId('tinyplace-self-identity-status')).toHaveAttribute(
- 'data-discoverable',
- 'false'
- );
- expect(
- screen.getByText('tinyplaceOrchestration.identity.undiscoverableHint')
- ).toBeInTheDocument();
- });
-
- const undiscoverable: SelfIdentity = {
- agentId: 'addrWithNoCardPublishedYet',
- handles: [{ username: 'openhuman', primary: true }],
- primaryHandle: 'openhuman',
- cardPublished: false,
- keyPublished: false,
- discoverable: false,
- };
-
- it('renders a "Make discoverable" button that fires onPublish while undiscoverable', () => {
- const onPublish = vi.fn();
- render(<SelfIdentityCard identity={undiscoverable} loading={false} onPublish={onPublish} />);
- const btn = screen.getByTestId('tinyplace-self-identity-publish');
- expect(btn).toHaveTextContent('tinyplaceOrchestration.identity.makeDiscoverable');
- fireEvent.click(btn);
- expect(onPublish).toHaveBeenCalledTimes(1);
- });
-
- it('disables the button and shows the publishing label while a publish is in flight', () => {
- render(
- <SelfIdentityCard identity={undiscoverable} loading={false} onPublish={vi.fn()} publishing />
- );
- const btn = screen.getByTestId('tinyplace-self-identity-publish');
- expect(btn).toBeDisabled();
- expect(btn).toHaveTextContent('tinyplaceOrchestration.identity.publishing');
- });
-
- it('surfaces a publish error under the button', () => {
- render(
- <SelfIdentityCard
- identity={undiscoverable}
- loading={false}
- onPublish={vi.fn()}
- publishError="boom"
- />
- );
- expect(screen.getByTestId('tinyplace-self-identity-publish-error')).toHaveTextContent(
- 'tinyplaceOrchestration.identity.publishFailed'
- );
- });
-
- it('shows no "make discoverable" button once discoverable', () => {
- render(<SelfIdentityCard identity={discoverable} loading={false} onPublish={vi.fn()} />);
- expect(screen.queryByTestId('tinyplace-self-identity-publish')).toBeNull();
- });
-
- it('offers a "Republish keys" action while discoverable that fires onPublish', () => {
- const onPublish = vi.fn();
- render(<SelfIdentityCard identity={discoverable} loading={false} onPublish={onPublish} />);
- const btn = screen.getByTestId('tinyplace-self-identity-republish');
- expect(btn).toHaveTextContent('tinyplaceOrchestration.identity.republish');
- fireEvent.click(btn);
- expect(onPublish).toHaveBeenCalledTimes(1);
- });
-
- it('omits the publish button when no onPublish handler is provided', () => {
- render(<SelfIdentityCard identity={undiscoverable} loading={false} />);
- expect(screen.queryByTestId('tinyplace-self-identity-publish')).toBeNull();
- });
-
- it('copies the address to the clipboard on click', async () => {
- render(<SelfIdentityCard identity={discoverable} loading={false} />);
- fireEvent.click(screen.getByTestId('tinyplace-self-identity-copy'));
- expect(navigator.clipboard.writeText).toHaveBeenCalledWith(discoverable.agentId);
- await waitFor(() =>
- expect(screen.getByTestId('tinyplace-self-identity-copy')).toHaveTextContent(
- 'tinyplaceOrchestration.identity.copied'
- )
- );
- });
-});
diff --git a/app/src/components/intelligence/SelfIdentityCard.tsx b/app/src/components/intelligence/SelfIdentityCard.tsx
deleted file mode 100644
index 3786e6b66a..0000000000
--- a/app/src/components/intelligence/SelfIdentityCard.tsx
+++ /dev/null
@@ -1,198 +0,0 @@
-/**
- * SelfIdentityCard — pinned at the top of the roster, shows OpenHuman's *own*
- * tiny.place identity so the user can hand it to a peer to be messaged inbound.
- *
- * Why it exists: the tab previously showed peers/contacts but never OpenHuman's
- * own agent id, so there was no way to say "here's my address, DM me". Worse, a
- * fresh identity can accept contacts yet stay un-messageable until it registers a
- * @handle (which is what publishes its directory card + Signal key) — every send
- * to it 404s on `/directory/agents/<addr>`. This card surfaces both the address
- * and the discoverability gap instead of leaving it a mystery.
- *
- * Presentational only — the parent fetches {@link SelfIdentity} via
- * `orchestrationClient.selfIdentity()` and owns refresh.
- */
-import { useCallback, useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type { SelfIdentity } from '../../lib/orchestration/orchestrationClient';
-import Button from '../ui/Button';
-
-interface SelfIdentityCardProps {
- identity: SelfIdentity | null;
- loading: boolean;
- /**
- * Publish (or refresh) this agent's directory card + Signal key so peers can
- * DM it. Rendered only while undiscoverable. The parent owns the RPC + the
- * identity refresh; the card just drives the button state.
- */
- onPublish?: () => void;
- /** True while {@link onPublish} is in flight — disables the button. */
- publishing?: boolean;
- /** Non-null when the last publish attempt failed — surfaces under the button. */
- publishError?: string | null;
-}
-
-function shortAddress(address: string): string {
- if (address.length <= 14) return address;
- return `${address.slice(0, 6)}…${address.slice(-5)}`;
-}
-
-export default function SelfIdentityCard({
- identity,
- loading,
- onPublish,
- publishing,
- publishError,
-}: SelfIdentityCardProps): React.ReactElement {
- const { t } = useT();
- const [copied, setCopied] = useState(false);
-
- const address = identity?.agentId ?? '';
- const onCopy = useCallback(() => {
- if (!address) return;
- void navigator.clipboard?.writeText(address).then(
- () => {
- setCopied(true);
- window.setTimeout(() => setCopied(false), 1500);
- },
- () => setCopied(false)
- );
- }, [address]);
-
- if (loading && !identity) {
- return (
- <section
- data-testid="tinyplace-self-identity"
- className="border-b border-line bg-surface-muted/40 px-4 py-3 text-[11px] text-content-faint">
- {t('tinyplaceOrchestration.identity.loading')}
- </section>
- );
- }
-
- if (!identity) return <></>;
-
- const primaryHandle = identity.primaryHandle ?? identity.handles[0]?.username;
-
- return (
- <section
- data-testid="tinyplace-self-identity"
- className="border-b border-line bg-surface-muted/40 px-4 py-3">
- <div className="flex items-center gap-2">
- <span
- aria-hidden
- className="flex h-6 w-6 flex-none items-center justify-center rounded-md bg-sage-500 font-mono text-[11px] font-bold text-content-inverted">
- OH
- </span>
- <div className="min-w-0 flex-1">
- <div className="truncate text-xs font-semibold text-content">
- {primaryHandle ? `@${primaryHandle}` : t('tinyplaceOrchestration.identity.noHandle')}
- </div>
- <div className="truncate font-mono text-[10px] text-content-faint" title={address}>
- {shortAddress(address)}
- </div>
- </div>
- <Button
- type="button"
- variant="tertiary"
- size="xs"
- data-testid="tinyplace-self-identity-copy"
- onClick={onCopy}
- disabled={!address}
- className="flex-none px-1.5 text-primary-600 hover:bg-primary-500/10 dark:text-primary-300">
- {copied
- ? t('tinyplaceOrchestration.identity.copied')
- : t('tinyplaceOrchestration.identity.copy')}
- </Button>
- </div>
-
- <div className="mt-2 flex flex-wrap items-center gap-1.5">
- {identity.discoverable ? (
- <span
- data-testid="tinyplace-self-identity-status"
- data-discoverable="true"
- className="inline-flex items-center rounded-full bg-sage-500/10 px-2 py-0.5 text-[10px] font-semibold text-sage-700 dark:text-sage-300">
- {t('tinyplaceOrchestration.identity.discoverable')}
- </span>
- ) : (
- <span
- data-testid="tinyplace-self-identity-status"
- data-discoverable="false"
- className="inline-flex items-center rounded-full bg-coral-500/10 px-2 py-0.5 text-[10px] font-semibold text-coral-700 dark:text-coral-300">
- {t('tinyplaceOrchestration.identity.undiscoverable')}
- </span>
- )}
- <span
- className="inline-flex items-center gap-1 rounded-full bg-surface-strong px-2 py-0.5 text-[10px] text-content-muted"
- title={t('tinyplaceOrchestration.identity.card')}>
- {t('tinyplaceOrchestration.identity.card')}:{' '}
- {identity.cardPublished
- ? t('tinyplaceOrchestration.identity.published')
- : t('tinyplaceOrchestration.identity.notPublished')}
- </span>
- <span
- className="inline-flex items-center gap-1 rounded-full bg-surface-strong px-2 py-0.5 text-[10px] text-content-muted"
- title={t('tinyplaceOrchestration.identity.key')}>
- {t('tinyplaceOrchestration.identity.key')}:{' '}
- {identity.keyPublished
- ? t('tinyplaceOrchestration.identity.published')
- : t('tinyplaceOrchestration.identity.notPublished')}
- </span>
- </div>
-
- {identity.discoverable && onPublish ? (
- <div className="mt-2 flex flex-wrap items-center gap-2">
- <Button
- type="button"
- variant="secondary"
- size="xs"
- data-testid="tinyplace-self-identity-republish"
- onClick={onPublish}
- disabled={publishing}
- className="text-[10px] text-content-muted">
- {publishing
- ? t('tinyplaceOrchestration.identity.publishing')
- : t('tinyplaceOrchestration.identity.republish')}
- </Button>
- {publishError ? (
- <span
- data-testid="tinyplace-self-identity-republish-error"
- className="text-[10px] text-coral-600 dark:text-coral-300">
- {t('tinyplaceOrchestration.identity.publishFailed')}
- </span>
- ) : null}
- </div>
- ) : null}
-
- {!identity.discoverable ? (
- <div className="mt-2 rounded-md bg-coral-50 px-2 py-1.5 dark:bg-coral-500/10">
- <p className="text-[10px] text-coral-700 dark:text-coral-300">
- {t('tinyplaceOrchestration.identity.undiscoverableHint')}
- </p>
- {onPublish ? (
- <Button
- type="button"
- variant="primary"
- tone="danger"
- size="xs"
- data-testid="tinyplace-self-identity-publish"
- onClick={onPublish}
- disabled={publishing}
- className="mt-1.5">
- {publishing
- ? t('tinyplaceOrchestration.identity.publishing')
- : t('tinyplaceOrchestration.identity.makeDiscoverable')}
- </Button>
- ) : null}
- {publishError ? (
- <p
- data-testid="tinyplace-self-identity-publish-error"
- className="mt-1 text-[10px] text-coral-700 dark:text-coral-300">
- {t('tinyplaceOrchestration.identity.publishFailed')}
- </p>
- ) : null}
- </div>
- ) : null}
- </section>
- );
-}
diff --git a/app/src/components/intelligence/TinyPlaceOrchestrationTab.test.tsx b/app/src/components/intelligence/TinyPlaceOrchestrationTab.test.tsx
deleted file mode 100644
index 06d934d27a..0000000000
--- a/app/src/components/intelligence/TinyPlaceOrchestrationTab.test.tsx
+++ /dev/null
@@ -1,618 +0,0 @@
-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { apiClient } from '../../lib/agentworld/apiClient';
-import { orchestrationClient } from '../../lib/orchestration/orchestrationClient';
-import { socketService } from '../../services/socketService';
-import TinyPlaceOrchestrationTab from './TinyPlaceOrchestrationTab';
-
-vi.mock('../../lib/agentworld/apiClient', () => ({
- apiClient: {
- orchestrationPairing: {
- list: vi.fn(),
- linkSession: vi.fn(),
- acceptRequest: vi.fn(),
- declineRequest: vi.fn(),
- blockRequest: vi.fn(),
- },
- },
-}));
-
-vi.mock('../../lib/orchestration/orchestrationClient', async importOriginal => {
- const actual =
- await importOriginal<typeof import('../../lib/orchestration/orchestrationClient')>();
- return {
- ...actual,
- orchestrationClient: {
- sessionsList: vi.fn(),
- sessionsCreate: vi.fn(),
- messagesList: vi.fn(),
- sendMasterMessage: vi.fn(),
- markRead: vi.fn(),
- status: vi.fn(),
- selfIdentity: vi.fn(),
- publishIdentity: vi.fn(),
- relayInfo: vi.fn(),
- attention: vi.fn(),
- },
- };
-});
-
-// The #5805 wallet gate runs before the identity fetch; mock it to a configured
-// wallet so these cases exercise the same path they always did.
-const fetchWalletStatusMock = vi.hoisted(() => vi.fn());
-vi.mock('../../services/walletApi', () => ({ fetchWalletStatus: fetchWalletStatusMock }));
-
-vi.mock('../../services/socketService', () => {
- return { socketService: { on: vi.fn(), off: vi.fn(), getSocket: vi.fn(() => null) } };
-});
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const sessionsListMock = vi.mocked(orchestrationClient.sessionsList);
-const sessionsCreateMock = vi.mocked(orchestrationClient.sessionsCreate);
-const messagesListMock = vi.mocked(orchestrationClient.messagesList);
-const sendMasterMock = vi.mocked(orchestrationClient.sendMasterMessage);
-const markReadMock = vi.mocked(orchestrationClient.markRead);
-const statusMock = vi.mocked(orchestrationClient.status);
-const selfIdentityMock = vi.mocked(orchestrationClient.selfIdentity);
-const relayInfoMock = vi.mocked(orchestrationClient.relayInfo);
-const attentionMock = vi.mocked(orchestrationClient.attention);
-
-const pairingListMock = vi.mocked(apiClient.orchestrationPairing.list);
-const pairingLinkMock = vi.mocked(apiClient.orchestrationPairing.linkSession);
-const pairingAcceptMock = vi.mocked(apiClient.orchestrationPairing.acceptRequest);
-const pairingDeclineMock = vi.mocked(apiClient.orchestrationPairing.declineRequest);
-const pairingBlockMock = vi.mocked(apiClient.orchestrationPairing.blockRequest);
-
-const socketOnMock = vi.mocked(socketService.on);
-
-const PINNED_SESSIONS = [
- {
- sessionId: 'master',
- agentId: '@openhuman',
- source: 'core',
- chatKind: 'master' as const,
- lastMessageAt: '2026-07-01T12:00:00.000Z',
- unread: 0,
- active: true,
- pinned: true,
- status: 'idle' as const,
- },
- {
- sessionId: 'subconscious',
- agentId: '@openhuman',
- source: 'core',
- chatKind: 'subconscious' as const,
- lastMessageAt: '2026-07-01T12:01:00.000Z',
- unread: 0,
- active: true,
- pinned: true,
- status: 'idle' as const,
- },
-];
-
-describe('TinyPlaceOrchestrationTab', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- // Default to a configured wallet so every pre-existing case exercises the
- // same path it always did; the #5805 case overrides it.
- fetchWalletStatusMock.mockResolvedValue({ configured: true });
- sessionsListMock.mockResolvedValue({ sessions: [...PINNED_SESSIONS] });
- sessionsCreateMock.mockResolvedValue({
- session: {
- sessionId: 'new-sess',
- agentId: '@peer',
- source: 'user_created',
- chatKind: 'session',
- lastMessageAt: '2026-07-04T00:00:00.000Z',
- unread: 0,
- active: true,
- pinned: false,
- status: 'idle' as const,
- },
- });
- messagesListMock.mockResolvedValue({ messages: [] });
- sendMasterMock.mockResolvedValue({ ok: true, messageId: 'm-1' });
- markReadMock.mockResolvedValue({ ok: true });
- statusMock.mockResolvedValue({});
- selfIdentityMock.mockResolvedValue({
- agentId: '6wNaBJkatir4B86cw5ykHZWQ3xoNaKygX5vAU9MQbHSh',
- handles: [{ username: 'openhuman', primary: true }],
- primaryHandle: 'openhuman',
- cardPublished: true,
- keyPublished: true,
- discoverable: true,
- });
- relayInfoMock.mockResolvedValue({
- baseUrl: 'https://staging-api.tiny.place',
- network: 'staging',
- });
- attentionMock.mockResolvedValue({
- items: [],
- counts: { total: 0, approvals: 0, needsInput: 0, unread: 0 },
- });
- pairingListMock.mockResolvedValue({
- records: [],
- contacts: { contacts: [] },
- requests: { incoming: [], outgoing: [] },
- stats: { agentId: '@openhuman', contactCount: 0, pendingIncoming: 0, pendingOutgoing: 0 },
- });
- pairingLinkMock.mockResolvedValue({
- record: {
- agentId: '@worker-new',
- status: 'pending',
- linkedAt: '2026-07-01T12:00:00.000Z',
- source: 'user_link',
- },
- remote: { agentId: '@worker-new', status: 'pending' },
- });
- pairingAcceptMock.mockResolvedValue({
- record: {
- agentId: '@worker-pending',
- status: 'linked',
- linkedAt: '2026-07-01T12:00:00.000Z',
- source: 'approved_request',
- },
- remote: { agentId: '@worker-pending', status: 'accepted' },
- });
- pairingDeclineMock.mockResolvedValue({ record: null, remote: { ok: true } });
- pairingBlockMock.mockResolvedValue({
- record: {
- agentId: '@worker-pending',
- status: 'blocked',
- linkedAt: '2026-07-01T12:00:00.000Z',
- source: 'approved_request',
- },
- remote: { agentId: '@worker-pending', status: 'blocked' },
- });
- });
-
- it('renders pinned master and subconscious chats plus app sessions', async () => {
- sessionsListMock.mockResolvedValue({
- sessions: [
- ...PINNED_SESSIONS,
- {
- sessionId: 'app-session-1',
- agentId: '@worker-alpha',
- source: 'openhuman-app',
- label: 'OpenHuman app session',
- chatKind: 'session',
- lastMessageAt: '2026-07-01T12:02:00.000Z',
- unread: 0,
- active: true,
- pinned: false,
- status: 'idle' as const,
- },
- ],
- });
-
- render(<TinyPlaceOrchestrationTab />);
-
- // Pinned master appears twice: in the list button and the main header.
- expect(await screen.findAllByText('tinyplaceOrchestration.master.title')).toHaveLength(2);
- expect(screen.getByText('tinyplaceOrchestration.subconscious.title')).toBeInTheDocument();
- expect(screen.getByText('OpenHuman app session')).toBeInTheDocument();
- });
-
- it('keeps the relay badge visible when identity discovery fails (locked wallet)', async () => {
- // selfIdentity() builds the tiny.place client from the wallet and can reject;
- // relayInfo() only reads the base URL and must stay visible regardless.
- selfIdentityMock.mockRejectedValue(new Error('wallet locked'));
-
- render(<TinyPlaceOrchestrationTab />);
-
- const badge = await screen.findByTestId('tinyplace-relay-badge');
- expect(badge).toHaveAttribute('data-network', 'staging');
- // Identity read failed → its card must not render.
- expect(screen.queryByTestId('tinyplace-self-identity')).not.toBeInTheDocument();
- });
-
- // #5805 — with no wallet the identity read is skipped rather than attempted:
- // selfIdentity() could only reject, and that rejection was reaching Sentry.
- // The relay badge must still render, which is the property the wallet-less
- // path shares with the locked-wallet path above.
- it('skips the identity read entirely when no wallet is configured', async () => {
- fetchWalletStatusMock.mockResolvedValue({ configured: false });
-
- render(<TinyPlaceOrchestrationTab />);
-
- const badge = await screen.findByTestId('tinyplace-relay-badge');
- expect(badge).toHaveAttribute('data-network', 'staging');
- expect(screen.queryByTestId('tinyplace-self-identity')).not.toBeInTheDocument();
- // The point of the gate: not attempted, as opposed to attempted and failed.
- expect(selfIdentityMock).not.toHaveBeenCalled();
- });
-
- it('loads and renders messages for the opened chat', async () => {
- sessionsListMock.mockResolvedValue({
- sessions: [
- ...PINNED_SESSIONS,
- {
- sessionId: 'app-session-1',
- agentId: '@worker-alpha',
- source: 'openhuman-app',
- label: 'OpenHuman app session',
- chatKind: 'session',
- lastMessageAt: '2026-07-01T12:02:00.000Z',
- unread: 0,
- active: true,
- pinned: false,
- status: 'idle' as const,
- },
- ],
- });
- messagesListMock.mockImplementation(async ({ chat }) => {
- if (chat === 'app-session-1') {
- return {
- messages: [
- {
- id: 'm-session',
- agentId: '@worker-alpha',
- sessionId: 'app-session-1',
- chatKind: 'session' as const,
- role: '@worker-alpha',
- body: 'I opened a worktree and asked the master for context.',
- timestamp: '2026-07-01T12:02:00.000Z',
- seq: 1,
- },
- ],
- };
- }
- return { messages: [] };
- });
-
- render(<TinyPlaceOrchestrationTab />);
-
- fireEvent.click(await screen.findByTestId('tinyplace-chat-app-session-1'));
-
- expect(
- within(await screen.findByTestId('tinyplace-chat-messages')).getByText(
- 'I opened a worktree and asked the master for context.'
- )
- ).toBeInTheDocument();
- await waitFor(() =>
- expect(messagesListMock).toHaveBeenCalledWith(
- expect.objectContaining({ chat: 'app-session-1' })
- )
- );
- });
-
- it('marks a chat read when it is opened', async () => {
- sessionsListMock.mockResolvedValue({
- sessions: [
- ...PINNED_SESSIONS,
- {
- sessionId: 'app-session-1',
- agentId: '@worker-alpha',
- source: 'openhuman-app',
- label: 'OpenHuman app session',
- chatKind: 'session',
- lastMessageAt: '2026-07-01T12:02:00.000Z',
- unread: 3,
- active: true,
- pinned: false,
- status: 'idle' as const,
- },
- ],
- });
-
- render(<TinyPlaceOrchestrationTab />);
-
- fireEvent.click(await screen.findByTestId('tinyplace-chat-app-session-1'));
-
- await waitFor(() => expect(markReadMock).toHaveBeenCalledWith('app-session-1'));
- });
-
- it('sends a master message and optimistically appends it', async () => {
- // Hold the send promise open so the optimistic append is observable before
- // the success reconcile refetch replaces it.
- let resolveSend: (() => void) | undefined;
- sendMasterMock.mockImplementation(
- () =>
- new Promise(res => {
- resolveSend = () => res({ ok: true, messageId: 'm-1' });
- })
- );
-
- render(<TinyPlaceOrchestrationTab />);
-
- const input = await screen.findByTestId('tinyplace-master-composer-input');
- fireEvent.change(input, { target: { value: 'Coordinate the next handoff' } });
- fireEvent.click(screen.getByTestId('tinyplace-master-composer-send'));
-
- // Optimistic append renders immediately in the message pane (send pending).
- expect(
- within(await screen.findByTestId('tinyplace-chat-messages')).getByText(
- 'Coordinate the next handoff'
- )
- ).toBeInTheDocument();
- await waitFor(() =>
- expect(sendMasterMock).toHaveBeenCalledWith({ body: 'Coordinate the next handoff' })
- );
-
- resolveSend?.();
-
- // Input clears on success.
- await waitFor(() => expect((input as HTMLInputElement).value).toBe(''));
- });
-
- it('refetches when an orchestration:message socket event fires', async () => {
- let handler: ((payload: unknown) => void) | undefined;
- // Listeners are registered through socketService.on (which queues until the
- // socket exists), so capture the handler there rather than on a raw socket.
- socketOnMock.mockImplementation(((event: string, cb: (payload: unknown) => void) => {
- if (event === 'orchestration:message') handler = cb;
- }) as never);
-
- render(<TinyPlaceOrchestrationTab />);
-
- await waitFor(() => expect(sessionsListMock).toHaveBeenCalled());
- const initialCalls = sessionsListMock.mock.calls.length;
- expect(handler).toBeDefined();
-
- handler?.({ agentId: '@worker-alpha', sessionId: 'master', chatKind: 'master' });
-
- await waitFor(() => expect(sessionsListMock.mock.calls.length).toBeGreaterThan(initialCalls));
- });
-
- it('requests a contact edge for a pasted session identity', async () => {
- render(<TinyPlaceOrchestrationTab />);
-
- const input = await screen.findByPlaceholderText(
- 'tinyplaceOrchestration.pairing.linkPlaceholder'
- );
- fireEvent.change(input, { target: { value: '@worker-new' } });
- fireEvent.click(screen.getByText('tinyplaceOrchestration.pairing.linkAction'));
-
- await waitFor(() => expect(pairingLinkMock).toHaveBeenCalledWith('@worker-new'));
- await waitFor(() => expect(pairingListMock).toHaveBeenCalledTimes(2));
- });
-
- it('surfaces incoming contact requests for explicit approval', async () => {
- pairingListMock.mockResolvedValue({
- records: [],
- contacts: { contacts: [] },
- requests: {
- incoming: [
- {
- agentId: '@worker-pending',
- status: 'pending',
- direction: 'incoming',
- contact: {
- requester: '@worker-pending',
- addressee: '@openhuman',
- status: 'pending',
- createdAt: '2026-07-01T12:00:00.000Z',
- updatedAt: '2026-07-01T12:00:00.000Z',
- },
- },
- ],
- outgoing: [],
- },
- stats: { agentId: '@openhuman', contactCount: 0, pendingIncoming: 1, pendingOutgoing: 0 },
- });
-
- render(<TinyPlaceOrchestrationTab />);
-
- expect(await screen.findByText('@worker-pending')).toBeInTheDocument();
- fireEvent.click(screen.getByText('tinyplaceOrchestration.pairing.accept'));
-
- await waitFor(() => expect(pairingAcceptMock).toHaveBeenCalledWith('@worker-pending'));
- });
-
- it('falls back to the contact requester address when agentId is absent', async () => {
- // The relay's /contacts/requests payload does not always populate the
- // top-level agentId; the counterpart address lives in contact.requester.
- const rawAddress = '3icjiLXhn6BMv43MsHjpKKxm7hEYBk7R5rvNXB1HUk7g';
- pairingListMock.mockResolvedValue({
- records: [],
- contacts: { contacts: [] },
- requests: {
- incoming: [
- {
- agentId: '',
- status: 'pending',
- direction: 'incoming',
- contact: {
- requester: rawAddress,
- addressee: '@openhuman',
- status: 'pending',
- createdAt: '2026-07-01T12:00:00.000Z',
- updatedAt: '2026-07-01T12:00:00.000Z',
- },
- },
- ],
- outgoing: [],
- },
- stats: { agentId: '@openhuman', contactCount: 0, pendingIncoming: 1, pendingOutgoing: 0 },
- });
-
- render(<TinyPlaceOrchestrationTab />);
-
- expect(await screen.findByText(rawAddress)).toBeInTheDocument();
- fireEvent.click(screen.getByText('tinyplaceOrchestration.pairing.accept'));
-
- await waitFor(() => expect(pairingAcceptMock).toHaveBeenCalledWith(rawAddress));
- });
-
- it('lists accepted contacts (address resolved from the contact record)', async () => {
- const rawAddress = '3icjiLXhn6BMv43MsHjpKKxm7hEYBk7R5rvNXB1HUk7g';
- pairingListMock.mockResolvedValue({
- records: [],
- contacts: {
- contacts: [
- {
- agentId: '',
- status: 'accepted',
- direction: 'incoming',
- contact: {
- requester: rawAddress,
- addressee: '@openhuman',
- status: 'accepted',
- createdAt: '2026-07-01T12:00:00.000Z',
- updatedAt: '2026-07-01T12:00:00.000Z',
- },
- },
- ],
- },
- requests: { incoming: [], outgoing: [] },
- stats: { agentId: '@openhuman', contactCount: 1, pendingIncoming: 0, pendingOutgoing: 0 },
- });
-
- render(<TinyPlaceOrchestrationTab />);
-
- // The accepted contact appears in the Contacts list, not just the count.
- expect(await screen.findByText(rawAddress)).toBeInTheDocument();
- expect(screen.getByText('tinyplaceOrchestration.contacts')).toBeInTheDocument();
- });
-
- it('surfaces load errors and retries', async () => {
- sessionsListMock.mockRejectedValueOnce(new Error('rpc failed'));
-
- render(<TinyPlaceOrchestrationTab />);
-
- expect(await screen.findByText(/tinyplaceOrchestration.failedToLoad/)).toBeInTheDocument();
- expect(screen.getByText(/rpc failed/)).toBeInTheDocument();
-
- fireEvent.click(screen.getByText('common.retry'));
-
- await waitFor(() => expect(sessionsListMock).toHaveBeenCalledTimes(2));
- expect(await screen.findByText('tinyplaceOrchestration.noMessages')).toBeInTheDocument();
- });
-
- const ACCEPTED_CONTACT_ADDRESS = '3icjiLXhn6BMv43MsHjpKKxm7hEYBk7R5rvNXB1HUk7g';
- const acceptedContactSnapshot = () => ({
- records: [],
- contacts: {
- contacts: [
- {
- agentId: ACCEPTED_CONTACT_ADDRESS,
- status: 'accepted' as const,
- direction: 'incoming' as const,
- contact: {
- requester: ACCEPTED_CONTACT_ADDRESS,
- addressee: '@openhuman',
- status: 'accepted' as const,
- createdAt: '2026-07-01T12:00:00.000Z',
- updatedAt: '2026-07-01T12:00:00.000Z',
- },
- },
- ],
- },
- requests: { incoming: [], outgoing: [] },
- stats: { agentId: '@openhuman', contactCount: 1, pendingIncoming: 0, pendingOutgoing: 0 },
- });
-
- it('creates a new session under an expanded contact', async () => {
- pairingListMock.mockResolvedValue(acceptedContactSnapshot());
-
- render(<TinyPlaceOrchestrationTab />);
-
- // Expand the contact row (exposes state to assistive tech), then create.
- const contactToggle = await screen.findByTestId(
- `tinyplace-contact-${ACCEPTED_CONTACT_ADDRESS}`
- );
- expect(contactToggle).toHaveAttribute('aria-expanded', 'false');
- fireEvent.click(contactToggle);
- expect(contactToggle).toHaveAttribute('aria-expanded', 'true');
- fireEvent.click(await screen.findByTestId(`tinyplace-new-session-${ACCEPTED_CONTACT_ADDRESS}`));
-
- await waitFor(() =>
- expect(sessionsCreateMock).toHaveBeenCalledWith({ agentId: ACCEPTED_CONTACT_ADDRESS })
- );
- });
-
- it('renders the attention zone and routes an open-session item to that chat', async () => {
- sessionsListMock.mockResolvedValue({
- sessions: [
- ...PINNED_SESSIONS,
- {
- sessionId: 'app-session-1',
- agentId: '@worker-alpha',
- source: 'openhuman-app',
- label: 'OpenHuman app session',
- chatKind: 'session',
- lastMessageAt: '2026-07-01T12:02:00.000Z',
- unread: 2,
- active: true,
- pinned: false,
- status: 'idle' as const,
- },
- ],
- });
- attentionMock.mockResolvedValue({
- items: [
- {
- id: 'unread:app-session-1',
- kind: 'unread',
- instanceId: 'app-session-1',
- title: 'Worker Alpha',
- count: 2,
- action: { type: 'open-session', sessionId: 'app-session-1' },
- },
- ],
- counts: { total: 1, approvals: 0, needsInput: 0, unread: 1 },
- });
-
- render(<TinyPlaceOrchestrationTab />);
-
- // The zone surfaces the item; acting on it opens the target session.
- await screen.findByTestId('attention-item-unread:app-session-1');
- fireEvent.click(screen.getByTestId('attention-item-action'));
-
- await waitFor(() => expect(markReadMock).toHaveBeenCalledWith('app-session-1'));
- });
-
- it('shows the New instance launch shell as a disabled affordance', async () => {
- render(<TinyPlaceOrchestrationTab />);
-
- const launch = await screen.findByTestId('tinyplace-new-instance');
- expect(launch).toBeDisabled();
- });
-
- it('threads a composed message under the selected session', async () => {
- pairingListMock.mockResolvedValue(acceptedContactSnapshot());
- sessionsListMock.mockResolvedValue({
- sessions: [
- ...PINNED_SESSIONS,
- {
- sessionId: 'sess-x',
- agentId: ACCEPTED_CONTACT_ADDRESS,
- source: 'user_created',
- label: 'Design review',
- chatKind: 'session',
- lastMessageAt: '2026-07-01T12:02:00.000Z',
- unread: 0,
- active: true,
- pinned: false,
- status: 'idle' as const,
- },
- ],
- });
-
- render(<TinyPlaceOrchestrationTab />);
-
- // Expand the contact, open its nested session, then send.
- fireEvent.click(await screen.findByTestId(`tinyplace-contact-${ACCEPTED_CONTACT_ADDRESS}`));
- fireEvent.click(await screen.findByTestId('tinyplace-chat-sess-x'));
-
- const input = await screen.findByTestId('tinyplace-master-composer-input');
- fireEvent.change(input, { target: { value: 'ping under session' } });
- fireEvent.click(screen.getByTestId('tinyplace-master-composer-send'));
-
- await waitFor(() =>
- expect(sendMasterMock).toHaveBeenCalledWith({
- body: 'ping under session',
- recipient: ACCEPTED_CONTACT_ADDRESS,
- sessionId: 'sess-x',
- })
- );
- });
-
- it('shows the cloud-unreachable banner when the hosted brain is offline', async () => {
- statusMock.mockResolvedValue({ cloudReachable: false });
- render(<TinyPlaceOrchestrationTab />);
- expect(await screen.findByText('orchestration.cloudUnreachable')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/TinyPlaceOrchestrationTab.tsx b/app/src/components/intelligence/TinyPlaceOrchestrationTab.tsx
deleted file mode 100644
index 75407f9b66..0000000000
--- a/app/src/components/intelligence/TinyPlaceOrchestrationTab.tsx
+++ /dev/null
@@ -1,435 +0,0 @@
-import debugFactory from 'debug';
-import { type FormEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react';
-
-import { resolveWalletConfigured } from '../../hooks/useWalletConfigured';
-import { apiClient } from '../../lib/agentworld/apiClient';
-import { type PairingSnapshot, PaymentRequiredError } from '../../lib/agentworld/invokeApiClient';
-import { useT } from '../../lib/i18n/I18nContext';
-import {
- type AttentionAction,
- type AttentionQueue,
- orchestrationClient,
- type RelayInfo,
- type SelfIdentity,
-} from '../../lib/orchestration/orchestrationClient';
-import {
- type ChatWindow,
- MASTER_CHAT_KEY,
- useOrchestrationChats,
-} from '../../lib/orchestration/useOrchestrationChats';
-import OrchestrationFocusPane from './OrchestrationFocusPane';
-import OrchestrationSidebar from './OrchestrationSidebar';
-import {
- acceptedContactIds,
- chatTime,
- contactAddress,
- extractHandle,
- pendingContactIds,
-} from './orchestrationTabHelpers';
-
-const debug = debugFactory('brain:tinyplace-orchestration');
-
-// ── Pairing (unchanged data source: apiClient.orchestrationPairing.*) ─────────
-
-type PairingState =
- | { status: 'loading' }
- | { status: 'error'; message: string }
- | { status: 'payment_required' }
- | { status: 'ok'; snapshot: PairingSnapshot };
-
-export default function TinyPlaceOrchestrationTab() {
- const { t } = useT();
- const {
- sessionsState,
- messagesState,
- chats,
- selectedId,
- selected,
- status,
- masterError,
- selectChat,
- refresh,
- sendMessage,
- createSession,
- } = useOrchestrationChats(t);
-
- const [pairingState, setPairingState] = useState<PairingState>({ status: 'loading' });
- const [linkAgentId, setLinkAgentId] = useState('');
- const [pairingAction, setPairingAction] = useState<string | null>(null);
- const [pairingError, setPairingError] = useState<string | null>(null);
- const [composerBody, setComposerBody] = useState('');
- const [sending, setSending] = useState(false);
- // Resolved `@handle`s for agent ids seen in the pairing UI (address always shown).
- const [agentHandles, setAgentHandles] = useState<Record<string, string | null>>({});
- // Which contact rows are expanded to reveal their nested sessions.
- const [expandedContacts, setExpandedContacts] = useState<Record<string, boolean>>({});
- const [creatingSession, setCreatingSession] = useState<string | null>(null);
- // Own tiny.place identity (discoverability) + the relay the core is on. Both
- // best-effort: a failed read leaves the card/badge hidden rather than erroring
- // the whole tab.
- const [selfIdentity, setSelfIdentity] = useState<SelfIdentity | null>(null);
- const [identityLoading, setIdentityLoading] = useState(true);
- // "Make discoverable" remediation: publishes the directory card + Signal key
- // when the identity card reports the agent is un-messageable.
- const [publishingIdentity, setPublishingIdentity] = useState(false);
- const [publishIdentityError, setPublishIdentityError] = useState<string | null>(null);
- const [relayInfo, setRelayInfo] = useState<RelayInfo | null>(null);
- // The aggregated "needs you" queue (approvals + blocked runs + unread). Read
- // independently of chats so a failure leaves the zone empty, never the tab.
- const [attentionQueue, setAttentionQueue] = useState<AttentionQueue | null>(null);
- const [attentionLoading, setAttentionLoading] = useState(true);
- const mountedRef = useRef(true);
-
- const toggleContact = useCallback((address: string) => {
- setExpandedContacts(prev => ({ ...prev, [address]: !prev[address] }));
- }, []);
-
- const handleCreateSession = useCallback(
- (address: string) => {
- if (!address || creatingSession) return;
- setCreatingSession(address);
- setExpandedContacts(prev => ({ ...prev, [address]: true }));
- void createSession(address).finally(() => {
- if (mountedRef.current) setCreatingSession(null);
- });
- },
- [createSession, creatingSession]
- );
-
- const loadPairing = useCallback(async () => {
- debug('[tinyplace-orchestration] pairing load entry');
- setPairingState({ status: 'loading' });
- try {
- const snapshot = await apiClient.orchestrationPairing.list();
- if (!mountedRef.current) return;
- debug(
- '[tinyplace-orchestration] pairing load exit contacts=%d incoming=%d outgoing=%d',
- snapshot.contacts.contacts.length,
- snapshot.requests.incoming.length,
- snapshot.requests.outgoing.length
- );
- setPairingState({ status: 'ok', snapshot });
- } catch (error) {
- if (!mountedRef.current) return;
- if (error instanceof PaymentRequiredError) {
- debug('[tinyplace-orchestration] pairing payment_required');
- setPairingState({ status: 'payment_required' });
- return;
- }
- const message = error instanceof Error ? error.message : String(error);
- debug('[tinyplace-orchestration] pairing load error %s', message);
- setPairingState({ status: 'error', message });
- }
- }, []);
-
- const loadIdentity = useCallback(async () => {
- debug('[tinyplace-orchestration] identity load entry');
- // Identity and relay are independent reads: selfIdentity() builds the
- // tiny.place client from the wallet and can reject (locked/unconfigured
- // wallet), but relayInfo() only reads the configured base URL and must
- // stay visible regardless. Settle them separately so one failure never
- // hides the other. Neither failure may break the chat surface.
- // Gate the wallet-requiring half on wallet status: with no wallet,
- // selfIdentity() can only reject with the core's wallet-not-configured
- // error, so skip it rather than provoke an error-level report (#5805).
- // relayInfo() reads a configured base URL and needs no wallet, so it runs
- // either way — preserving the "one failure never hides the other" property
- // above. Only a positive `no` skips; `unknown` falls through and the core
- // boundary classifier handles anything that follows.
- // Fire the wallet-independent read FIRST, before awaiting anything: relay
- // must not be delayed by the wallet probe, which is the whole reason the
- // two are settled separately. `null` marks "not asked", which is distinct
- // from "asked and failed".
- const relayPromise = orchestrationClient.relayInfo();
- const identityPromise = resolveWalletConfigured().then(configured =>
- configured === 'no' ? null : orchestrationClient.selfIdentity()
- );
- const [identityResult, relayResult] = await Promise.allSettled([identityPromise, relayPromise]);
- if (!mountedRef.current) return;
- if (identityResult.status === 'fulfilled') {
- const identity = identityResult.value;
- if (identity === null) {
- debug('[tinyplace-orchestration] identity skipped: no wallet configured');
- } else {
- debug('[tinyplace-orchestration] identity load ok discoverable=%s', identity.discoverable);
- setSelfIdentity(identity);
- }
- } else {
- const reason = identityResult.reason;
- const message = reason instanceof Error ? reason.message : String(reason);
- debug('[tinyplace-orchestration] identity load error %s', message);
- }
- if (relayResult.status === 'fulfilled') {
- debug('[tinyplace-orchestration] relay load ok network=%s', relayResult.value.network);
- setRelayInfo(relayResult.value);
- } else {
- const reason = relayResult.reason;
- const message = reason instanceof Error ? reason.message : String(reason);
- debug('[tinyplace-orchestration] relay load error %s', message);
- }
- setIdentityLoading(false);
- }, []);
-
- // Publish (or refresh) the directory card + Signal key, then adopt the fresh
- // identity the RPC echoes back so the card flips to "discoverable" without a
- // separate reload. A failure surfaces on the card, not the whole tab.
- const publishIdentity = useCallback(async () => {
- debug('[tinyplace-orchestration] publish identity entry');
- setPublishingIdentity(true);
- setPublishIdentityError(null);
- try {
- const identity = await orchestrationClient.publishIdentity();
- if (!mountedRef.current) return;
- debug('[tinyplace-orchestration] publish identity ok discoverable=%s', identity.discoverable);
- setSelfIdentity(identity);
- } catch (error) {
- if (!mountedRef.current) return;
- const message = error instanceof Error ? error.message : String(error);
- debug('[tinyplace-orchestration] publish identity error %s', message);
- setPublishIdentityError(message);
- } finally {
- if (mountedRef.current) setPublishingIdentity(false);
- }
- }, []);
-
- const loadAttention = useCallback(async () => {
- debug('[tinyplace-orchestration] attention load entry');
- try {
- const queue = await orchestrationClient.attention();
- if (!mountedRef.current) return;
- debug('[tinyplace-orchestration] attention load ok total=%d', queue.counts.total);
- setAttentionQueue(queue);
- } catch (error) {
- if (!mountedRef.current) return;
- const message = error instanceof Error ? error.message : String(error);
- debug('[tinyplace-orchestration] attention load error %s', message);
- } finally {
- if (mountedRef.current) setAttentionLoading(false);
- }
- }, []);
-
- // Route an attention item to its target. Only orchestration sessions have an
- // in-tab surface today; approvals/threads/runs live elsewhere (wired later).
- const handleAttentionAction = useCallback(
- (action: AttentionAction) => {
- debug('[tinyplace-orchestration] attention action type=%s', action.type);
- if (action.type === 'open-session') {
- selectChat(action.sessionId);
- }
- },
- [selectChat]
- );
-
- const runPairingAction = useCallback(
- async (actionId: string, action: () => Promise<unknown>) => {
- debug('[tinyplace-orchestration] pairing action entry id=%s', actionId);
- setPairingAction(actionId);
- setPairingError(null);
- try {
- await action();
- if (!mountedRef.current) return;
- debug('[tinyplace-orchestration] pairing action success id=%s', actionId);
- await loadPairing();
- } catch (error) {
- if (!mountedRef.current) return;
- const message = error instanceof Error ? error.message : String(error);
- debug('[tinyplace-orchestration] pairing action error id=%s %s', actionId, message);
- setPairingError(message);
- } finally {
- if (mountedRef.current) {
- setPairingAction(null);
- }
- }
- },
- [loadPairing]
- );
-
- const submitLink = useCallback(
- (event: FormEvent<HTMLFormElement>) => {
- event.preventDefault();
- const agentId = linkAgentId.trim();
- if (!agentId) return;
- void runPairingAction(`request:${agentId}`, async () => {
- await apiClient.orchestrationPairing.linkSession(agentId);
- setLinkAgentId('');
- });
- },
- [linkAgentId, runPairingAction]
- );
-
- const refreshAll = useCallback(() => {
- void refresh();
- void loadPairing();
- void loadIdentity();
- void loadAttention();
- }, [refresh, loadPairing, loadIdentity, loadAttention]);
-
- const submitComposer = useCallback(
- (event: FormEvent<HTMLFormElement>) => {
- event.preventDefault();
- const body = composerBody.trim();
- if (!body || sending) return;
- setSending(true);
- void sendMessage(selected, body).then(ok => {
- if (!mountedRef.current) return;
- if (ok) setComposerBody('');
- setSending(false);
- });
- },
- [composerBody, sending, sendMessage, selected]
- );
-
- useEffect(() => {
- mountedRef.current = true;
- const handle = window.setTimeout(() => {
- void loadPairing();
- void loadIdentity();
- void loadAttention();
- }, 0);
- return () => {
- window.clearTimeout(handle);
- mountedRef.current = false;
- };
- }, [loadPairing, loadIdentity, loadAttention]);
-
- const pinned = chats.filter(chat => chat.pinned);
- const sessions = chats
- .filter(chat => !chat.pinned)
- .sort((a, b) => Number(b.active) - Number(a.active) || chatTime(b) - chatTime(a));
-
- const pairingSnapshot = pairingState.status === 'ok' ? pairingState.snapshot : null;
- const acceptedContacts = useMemo(
- () => acceptedContactIds(pairingSnapshot?.contacts.contacts ?? []),
- [pairingSnapshot?.contacts.contacts]
- );
- const pendingContacts = useMemo(
- () => pendingContactIds(pairingSnapshot?.requests ?? { incoming: [], outgoing: [] }),
- [pairingSnapshot?.requests]
- );
- const incomingRequests = pairingSnapshot?.requests.incoming ?? [];
- const acceptedContactList = useMemo(
- () =>
- (pairingSnapshot?.contacts.contacts ?? []).filter(contact => contact.status === 'accepted'),
- [pairingSnapshot?.contacts.contacts]
- );
- const contactStats = pairingSnapshot?.stats ?? null;
-
- // Group session chats under their peer contact for the nested sidebar tree.
- const sessionsByContact = new Map<string, ChatWindow[]>();
- for (const chat of sessions) {
- if (!chat.peerAgentId) continue;
- const list = sessionsByContact.get(chat.peerAgentId) ?? [];
- list.push(chat);
- sessionsByContact.set(chat.peerAgentId, list);
- }
- const contactAddressSet = new Set(acceptedContactList.map(contactAddress).filter(Boolean));
- // Sessions whose peer is not a known accepted contact still need a home.
- const ungroupedSessions = sessions.filter(
- chat => !chat.peerAgentId || !contactAddressSet.has(chat.peerAgentId)
- );
-
- // Resolve @handles for the agent ids seen in the pairing UI (incoming
- // requests + accepted contacts) via the directory reverse lookup
- // (best-effort; the raw address is always rendered).
- const directoryIdsKey = [...incomingRequests, ...acceptedContactList]
- .map(contactAddress)
- .filter(Boolean)
- .join(',');
- useEffect(() => {
- const ids = directoryIdsKey ? Array.from(new Set(directoryIdsKey.split(','))) : [];
- if (ids.length === 0) return;
- let cancelled = false;
- void Promise.all(
- ids.map(async id => {
- try {
- return [id, extractHandle(await apiClient.directory.reverse(id))] as const;
- } catch {
- return [id, null] as const;
- }
- })
- ).then(entries => {
- if (cancelled) return;
- setAgentHandles(prev => {
- const next = { ...prev };
- for (const [id, handle] of entries) {
- if (!(id in next)) next[id] = handle;
- }
- return next;
- });
- });
- return () => {
- cancelled = true;
- };
- }, [directoryIdsKey]);
-
- const steeringText = status?.steering?.text?.trim() || null;
- const isMasterSelected = selected?.id === MASTER_CHAT_KEY;
- // The composer is available for the Master chat and for any per-contact
- // session (session sends thread under that session id).
- const canCompose = isMasterSelected || selected?.kind === 'session';
-
- return (
- <>
- {status?.cloudReachable === false && (
- <div
- role="status"
- className="mb-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-2 text-sm text-amber-700 dark:text-amber-300">
- {t('orchestration.cloudUnreachable')}
- </div>
- )}
- <div className="flex min-h-[620px] overflow-hidden rounded-xl border border-line bg-surface shadow-soft">
- <OrchestrationSidebar
- relayInfo={relayInfo}
- onRefreshAll={refreshAll}
- refreshDisabled={sessionsState.status === 'loading'}
- steeringText={steeringText}
- selfIdentity={selfIdentity}
- identityLoading={identityLoading}
- onPublishIdentity={publishIdentity}
- publishingIdentity={publishingIdentity}
- publishIdentityError={publishIdentityError}
- attentionQueue={attentionQueue}
- attentionLoading={attentionLoading}
- onAttentionAction={handleAttentionAction}
- linkAgentId={linkAgentId}
- onLinkAgentIdChange={setLinkAgentId}
- onSubmitLink={submitLink}
- pairingAction={pairingAction}
- contactStats={contactStats}
- incomingRequests={incomingRequests}
- outgoingCount={pairingSnapshot?.requests.outgoing.length ?? 0}
- pairingError={pairingError}
- agentHandles={agentHandles}
- runPairingAction={runPairingAction}
- pinned={pinned}
- selectedId={selectedId}
- onSelectChat={selectChat}
- acceptedContactList={acceptedContactList}
- expandedContacts={expandedContacts}
- onToggleContact={toggleContact}
- sessionsByContact={sessionsByContact}
- creatingSession={creatingSession}
- onCreateSession={handleCreateSession}
- acceptedContacts={acceptedContacts}
- pendingContacts={pendingContacts}
- ungroupedSessions={ungroupedSessions}
- />
-
- <OrchestrationFocusPane
- selected={selected}
- sessionsState={sessionsState}
- messagesState={messagesState}
- status={status}
- masterError={masterError}
- refresh={refresh}
- steeringText={steeringText}
- canCompose={canCompose}
- composerBody={composerBody}
- onComposerChange={setComposerBody}
- sending={sending}
- onSubmitComposer={submitComposer}
- />
- </div>
- </>
- );
-}
diff --git a/app/src/components/intelligence/TinyPlaceRoster.test.tsx b/app/src/components/intelligence/TinyPlaceRoster.test.tsx
deleted file mode 100644
index 34918d679f..0000000000
--- a/app/src/components/intelligence/TinyPlaceRoster.test.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import { fireEvent, render, screen, within } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { SessionSummary } from '../../lib/orchestration/orchestrationClient';
-import TinyPlaceRoster from './TinyPlaceRoster';
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-function session(over: Partial<SessionSummary> = {}): SessionSummary {
- return {
- sessionId: 's',
- agentId: '@peer',
- source: 'claude',
- harnessType: 'claude',
- status: 'idle',
- chatKind: 'session',
- lastMessageAt: '2026-07-06T00:00:00Z',
- unread: 0,
- active: true,
- pinned: false,
- ...over,
- };
-}
-
-describe('TinyPlaceRoster', () => {
- it('shows the empty state when there are no instance sessions', () => {
- // Pinned windows are not instances and must not count.
- const pinned = session({ sessionId: 'master', chatKind: 'master', pinned: true });
- render(<TinyPlaceRoster sessions={[pinned]} />);
- expect(screen.getByTestId('tinyplace-roster-empty')).toBeInTheDocument();
- });
-
- it('groups instances by harness and lists an Other group for harness-less sessions', () => {
- const sessions = [
- session({ sessionId: 'c1', harnessType: 'claude' }),
- session({ sessionId: 'x1', harnessType: 'codex', source: 'codex' }),
- session({ sessionId: 'u1', harnessType: undefined, source: 'user_created' }),
- ];
- render(<TinyPlaceRoster sessions={sessions} />);
- expect(screen.getByText('Claude')).toBeInTheDocument();
- expect(screen.getByText('Codex')).toBeInTheDocument();
- // Harness-less session lands under the (translated) Other group; no empty Gemini group.
- expect(screen.getByText('tinyplaceOrchestration.roster.other')).toBeInTheDocument();
- expect(screen.queryByText('Gemini')).toBeNull();
- expect(screen.getByTestId('instance-card-c1')).toBeInTheDocument();
- expect(screen.getByTestId('instance-card-u1')).toBeInTheDocument();
- });
-
- it('groups cursor and windsurf sessions under their own headers', () => {
- const sessions = [
- session({ sessionId: 'cu1', harnessType: 'cursor', source: 'cursor' }),
- session({ sessionId: 'ws1', harnessType: 'windsurf', source: 'windsurf' }),
- ];
- render(<TinyPlaceRoster sessions={sessions} />);
- expect(screen.getByText('Cursor')).toBeInTheDocument();
- expect(screen.getByText('Windsurf')).toBeInTheDocument();
- expect(screen.getByTestId('instance-card-cu1')).toBeInTheDocument();
- expect(screen.getByTestId('instance-card-ws1')).toBeInTheDocument();
- // Neither falls into the Other catch-all.
- expect(screen.queryByText('tinyplaceOrchestration.roster.other')).toBeNull();
- });
-
- it('marks the selected instance and forwards selection', () => {
- const onSelect = vi.fn();
- const sessions = [session({ sessionId: 'c1' }), session({ sessionId: 'c2' })];
- render(<TinyPlaceRoster sessions={sessions} selectedId="c1" onSelect={onSelect} />);
- expect(screen.getByTestId('instance-card-c1')).toHaveAttribute('data-selected', 'true');
- expect(screen.getByTestId('instance-card-c2')).toHaveAttribute('data-selected', 'false');
- fireEvent.click(screen.getByTestId('instance-card-c2'));
- expect(onSelect).toHaveBeenCalledWith('c2');
- });
-
- it('passes resolved handles down to the cards', () => {
- render(
- <TinyPlaceRoster
- sessions={[session({ sessionId: 'c1', agentId: '@peer' })]}
- handles={{ '@peer': 'claudebot' }}
- />
- );
- const card = screen.getByTestId('instance-card-c1');
- expect(within(card).getByText('@claudebot')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/TinyPlaceRoster.tsx b/app/src/components/intelligence/TinyPlaceRoster.tsx
deleted file mode 100644
index 76efd5f40f..0000000000
--- a/app/src/components/intelligence/TinyPlaceRoster.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * TinyPlaceRoster — the instance roster: external agent sessions grouped by
- * harness (Claude / Codex / Gemini, then an "Other" catch-all), each a
- * selectable {@link InstanceCard}. Pinned master/subconscious windows are not
- * instances and are excluded here.
- *
- * Presentational only; the parent passes the session list, selection, and an
- * optional address→@handle map.
- */
-import { useT } from '../../lib/i18n/I18nContext';
-import type { HarnessType, SessionSummary } from '../../lib/orchestration/orchestrationClient';
-import InstanceCard from './InstanceCard';
-
-interface TinyPlaceRosterProps {
- sessions: SessionSummary[];
- selectedId?: string;
- onSelect?: (sessionId: string) => void;
- /** Resolved address → `@handle` map (best-effort; address is the fallback). */
- handles?: Record<string, string | null>;
-}
-
-// Grouped in this order; brand names are identity, not translated UI copy.
-const HARNESS_GROUPS: Array<{ key: HarnessType; label: string }> = [
- { key: 'claude', label: 'Claude' },
- { key: 'codex', label: 'Codex' },
- { key: 'gemini', label: 'Gemini' },
- { key: 'cursor', label: 'Cursor' },
- { key: 'windsurf', label: 'Windsurf' },
-];
-
-export default function TinyPlaceRoster({
- sessions,
- selectedId,
- onSelect,
- handles,
-}: TinyPlaceRosterProps): React.ReactElement {
- const { t } = useT();
-
- // Instances are the non-pinned session windows.
- const instances = sessions.filter(s => !s.pinned && s.chatKind === 'session');
-
- const byHarness = (harness: HarnessType): SessionSummary[] =>
- instances.filter(s => s.harnessType === harness);
- const ungrouped = instances.filter(s => !s.harnessType);
-
- const groups = [
- ...HARNESS_GROUPS.map(g => ({ label: g.label, rows: byHarness(g.key) })),
- { label: t('tinyplaceOrchestration.roster.other'), rows: ungrouped },
- ].filter(g => g.rows.length > 0);
-
- return (
- <section data-testid="tinyplace-roster" className="min-w-0">
- <h4 className="px-3 pb-1 pt-3 text-[10px] font-semibold uppercase tracking-wide text-content-muted">
- {t('tinyplaceOrchestration.roster.instances')}
- </h4>
- {instances.length === 0 ? (
- <p
- data-testid="tinyplace-roster-empty"
- className="px-3 py-4 text-[11px] text-content-faint">
- {t('tinyplaceOrchestration.roster.empty')}
- </p>
- ) : (
- groups.map(group => (
- <div key={group.label}>
- <div className="px-3 pb-0.5 pt-2 text-[10px] font-semibold uppercase tracking-wide text-content-faint">
- {group.label}
- </div>
- {group.rows.map(session => (
- <InstanceCard
- key={session.sessionId}
- session={session}
- selected={session.sessionId === selectedId}
- handle={handles?.[session.agentId]}
- onSelect={onSelect ? () => onSelect(session.sessionId) : undefined}
- />
- ))}
- </div>
- ))
- )}
- </section>
- );
-}
diff --git a/app/src/components/intelligence/orchestrationTabHelpers.test.ts b/app/src/components/intelligence/orchestrationTabHelpers.test.ts
deleted file mode 100644
index 9d97abec3e..0000000000
--- a/app/src/components/intelligence/orchestrationTabHelpers.test.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import type { ContactView } from '../../lib/agentworld/invokeApiClient';
-import type { ChatWindow } from '../../lib/orchestration/useOrchestrationChats';
-import {
- acceptedContactIds,
- chatTime,
- contactAddress,
- contactBadgeKey,
- extractHandle,
- formatTime,
- pendingContactIds,
- truncate,
-} from './orchestrationTabHelpers';
-
-const contact = (over: Partial<ContactView>): ContactView =>
- ({ agentId: '', status: 'accepted', direction: 'incoming', ...over }) as ContactView;
-
-const chat = (over: Partial<ChatWindow>): ChatWindow =>
- ({ id: 'c', pinned: false, peerAgentId: undefined, ...over }) as ChatWindow;
-
-describe('orchestrationTabHelpers', () => {
- it('formatTime returns empty for null/invalid and formats a real timestamp', () => {
- expect(formatTime(null)).toBe('');
- expect(formatTime('not-a-date')).toBe('');
- expect(formatTime('2026-07-01T12:00:00.000Z')).not.toBe('');
- });
-
- it('truncate leaves short text and ellipsises long text within the cap', () => {
- expect(truncate('short', 96)).toBe('short');
- const out = truncate('x'.repeat(50), 10);
- expect(out).toHaveLength(10);
- expect(out.endsWith('…')).toBe(true);
- });
-
- it('chatTime parses a timestamp and falls back to 0', () => {
- expect(chatTime(chat({ lastTimestamp: null }))).toBe(0);
- expect(chatTime(chat({ lastTimestamp: 'nope' }))).toBe(0);
- expect(chatTime(chat({ lastTimestamp: '2026-07-01T12:00:00.000Z' }))).toBeGreaterThan(0);
- });
-
- it('contactAddress prefers agentId then the contact record by direction', () => {
- expect(contactAddress(contact({ agentId: '@a' }))).toBe('@a');
- expect(
- contactAddress(
- contact({ agentId: '', direction: 'incoming', contact: { requester: '@req' } as never })
- )
- ).toBe('@req');
- expect(
- contactAddress(
- contact({ agentId: '', direction: 'outgoing', contact: { addressee: '@to' } as never })
- )
- ).toBe('@to');
- expect(contactAddress(contact({ agentId: '' }))).toBe('');
- });
-
- it('accepted/pending id sets derive from the contact records', () => {
- const accepted = acceptedContactIds([
- contact({ agentId: '@ok', status: 'accepted' }),
- contact({ agentId: '@no', status: 'pending' }),
- ]);
- expect(accepted.has('@ok')).toBe(true);
- expect(accepted.has('@no')).toBe(false);
-
- const pending = pendingContactIds({
- incoming: [contact({ agentId: '@p', status: 'pending' })],
- outgoing: [],
- } as never);
- expect(pending.has('@p')).toBe(true);
- });
-
- it('contactBadgeKey maps a session chat to linked/pending/unlinked', () => {
- const accepted = new Set(['@a']);
- const pending = new Set(['@b']);
- expect(contactBadgeKey(chat({ pinned: true }), accepted, pending)).toBeNull();
- expect(contactBadgeKey(chat({ peerAgentId: '@a' }), accepted, pending)).toBe(
- 'tinyplaceOrchestration.pairing.linked'
- );
- expect(contactBadgeKey(chat({ peerAgentId: '@b' }), accepted, pending)).toBe(
- 'tinyplaceOrchestration.pairing.pending'
- );
- expect(contactBadgeKey(chat({ peerAgentId: '@c' }), accepted, pending)).toBe(
- 'tinyplaceOrchestration.pairing.unlinked'
- );
- });
-
- it('extractHandle finds a username from agents or identities and strips @', () => {
- expect(extractHandle({ agents: [{ username: '@nick' }] })).toBe('nick');
- expect(extractHandle({ identities: [{ username: 'openhuman' }] })).toBe('openhuman');
- expect(extractHandle({})).toBeNull();
- });
-});
diff --git a/app/src/components/intelligence/orchestrationTabHelpers.ts b/app/src/components/intelligence/orchestrationTabHelpers.ts
deleted file mode 100644
index 045e081f96..0000000000
--- a/app/src/components/intelligence/orchestrationTabHelpers.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- * Pure helpers for the TinyPlace Orchestration tab — time/label formatting,
- * contact-address resolution, and derived badge keys. Extracted so the tab
- * container and its presentational siblings share one implementation.
- */
-import type { ContactRequestsResponse, ContactView } from '../../lib/agentworld/invokeApiClient';
-import type { ChatWindow } from '../../lib/orchestration/useOrchestrationChats';
-
-export function formatTime(timestamp: string | null): string {
- if (!timestamp) return '';
- const parsed = Date.parse(timestamp);
- if (!Number.isFinite(parsed)) return '';
- return new Intl.DateTimeFormat(undefined, {
- month: 'short',
- day: 'numeric',
- hour: 'numeric',
- minute: '2-digit',
- }).format(new Date(parsed));
-}
-
-export function truncate(text: string, length = 96): string {
- if (text.length <= length) return text;
- return `${text.slice(0, length - 1)}…`;
-}
-
-export function chatTime(chat: ChatWindow): number {
- if (!chat.lastTimestamp) return 0;
- const parsed = Date.parse(chat.lastTimestamp);
- return Number.isFinite(parsed) ? parsed : 0;
-}
-
-// The counterpart agent address for a contact view (request or accepted
-// contact). The relay's `/contacts` and `/contacts/requests` payloads do not
-// always populate the top-level `agentId`, so fall back to the underlying
-// contact record: when we are the addressee the counterpart is the
-// `requester`, otherwise it is the `addressee`.
-export function contactAddress(view: ContactView): string {
- if (view.agentId) return view.agentId;
- const contact = view.contact;
- if (!contact) return '';
- return view.direction === 'outgoing' ? (contact.addressee ?? '') : (contact.requester ?? '');
-}
-
-export function acceptedContactIds(contacts: ContactView[]): Set<string> {
- return new Set(
- contacts
- .filter(contact => contact.status === 'accepted')
- .map(contactAddress)
- .filter(Boolean)
- );
-}
-
-export function pendingContactIds(requests: ContactRequestsResponse): Set<string> {
- return new Set(
- [...requests.incoming, ...requests.outgoing]
- .filter(contact => contact.status === 'pending')
- .map(contactAddress)
- .filter(Boolean)
- );
-}
-
-export function contactBadgeKey(
- chat: ChatWindow,
- accepted: Set<string>,
- pending: Set<string>
-): string | null {
- if (chat.pinned || !chat.peerAgentId) return null;
- if (accepted.has(chat.peerAgentId)) return 'tinyplaceOrchestration.pairing.linked';
- if (pending.has(chat.peerAgentId)) return 'tinyplaceOrchestration.pairing.pending';
- return 'tinyplaceOrchestration.pairing.unlinked';
-}
-
-/** Best-effort `@handle` for a tiny.place agent id (cryptoId) from a directory
- * reverse lookup — the registered username if any, else null. The raw address
- * is always shown; the handle is additive. */
-export function extractHandle(res: {
- agents?: Array<{ username?: string }>;
- identities?: unknown[];
-}): string | null {
- const fromAgent = res.agents?.find(a => a.username)?.username;
- const fromIdentity = (res.identities as Array<{ username?: string }> | undefined)?.find(
- identity => identity?.username
- )?.username;
- const username = fromAgent ?? fromIdentity;
- return username ? username.replace(/^@+/, '') : null;
-}
diff --git a/app/src/components/orchestration/ActiveSubagentsRail.test.tsx b/app/src/components/orchestration/ActiveSubagentsRail.test.tsx
deleted file mode 100644
index c903e4cf0f..0000000000
--- a/app/src/components/orchestration/ActiveSubagentsRail.test.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { SessionSummary } from '../../lib/orchestration/orchestrationClient';
-import ActiveSubagentsRail from './ActiveSubagentsRail';
-
-// Pass-through translator so assertions can target the i18n keys directly.
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (key: string) => key }) }));
-
-function session(overrides: Partial<SessionSummary> = {}): SessionSummary {
- return {
- sessionId: 'sess-1',
- agentId: 'agent-1',
- label: 'Refactor the parser',
- status: 'running',
- active: true,
- messageCount: 3,
- unread: 0,
- ...overrides,
- } as SessionSummary;
-}
-
-const byContact = new Map<string, SessionSummary[]>([['0xabcdef0123456789', [session()]]]);
-
-describe('ActiveSubagentsRail', () => {
- it('renders sub-agents under their instance and opens one on click', () => {
- const onOpenSession = vi.fn();
- render(
- <ActiveSubagentsRail
- byContact={byContact}
- openSessionId={null}
- isAgentTab={false}
- onOpenSession={onOpenSession}
- />
- );
-
- const row = screen.getByTestId('orch-session-rail-sess-1');
- expect(row).toHaveAttribute('data-slot', 'button');
- expect(row).toHaveAttribute('data-variant', 'tertiary');
- expect(screen.getByText('Refactor the parser')).toBeInTheDocument();
-
- fireEvent.click(row);
- expect(onOpenSession).toHaveBeenCalledWith('sess-1');
- });
-
- it('collapses the instance so its sub-agents disappear', () => {
- render(
- <ActiveSubagentsRail
- byContact={byContact}
- openSessionId={null}
- isAgentTab={false}
- onOpenSession={vi.fn()}
- />
- );
-
- const toggle = screen.getByTestId('orch-instance-toggle-0xabcdef0123456789');
- expect(toggle).toHaveAttribute('aria-expanded', 'true');
-
- fireEvent.click(toggle);
- expect(toggle).toHaveAttribute('aria-expanded', 'false');
- expect(screen.queryByTestId('orch-session-rail-sess-1')).not.toBeInTheDocument();
- });
-
- it('renders the empty copy when no instances exist', () => {
- render(
- <ActiveSubagentsRail
- byContact={new Map()}
- openSessionId={null}
- isAgentTab={false}
- onOpenSession={vi.fn()}
- />
- );
- expect(screen.getByText('orchPage.sessions.empty')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/orchestration/ActiveSubagentsRail.tsx b/app/src/components/orchestration/ActiveSubagentsRail.tsx
deleted file mode 100644
index c01b599a6f..0000000000
--- a/app/src/components/orchestration/ActiveSubagentsRail.tsx
+++ /dev/null
@@ -1,189 +0,0 @@
-/**
- * ActiveSubagentsRail — the sidebar's "Active sub-agents" list, grouped by
- * instance.
- *
- * An **instance** is a contact (peer `agentId`) you coordinate with; its
- * **sub-agents** are the sessions running under it. Each instance shows an
- * avatar icon + a connection-status dot (aggregated over its sessions), and
- * expands to its sub-agents — each with its own status dot. Clicking a sub-agent
- * opens that session's full chat subpage.
- *
- * Status dot: green = connected, amber = waiting for input, red = errored,
- * hollow = disconnected. The instance dot surfaces the most actionable state
- * across its sessions (waiting › errored › connected › disconnected).
- */
-import { useCallback, useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type { SessionSummary } from '../../lib/orchestration/orchestrationClient';
-import Button from '../ui/Button';
-
-type ConnState = 'connected' | 'waiting' | 'error' | 'disconnected';
-
-/** Filled dot colour per state; `null` renders a hollow ring (disconnected). */
-const DOT_CLASS: Record<ConnState, string | null> = {
- connected: 'bg-sage-500',
- waiting: 'bg-amber-500',
- error: 'bg-coral-500',
- disconnected: null,
-};
-
-const LABEL_KEY: Record<ConnState, string> = {
- connected: 'orchPage.sessions.statusConnected',
- waiting: 'orchPage.sessions.statusWaiting',
- error: 'orchPage.connections.status.error',
- disconnected: 'orchPage.sessions.statusDisconnected',
-};
-
-function sessionState(session: SessionSummary): ConnState {
- // Work-state semantics win (they carry their own colour).
- if (session.status === 'waiting-approval') return 'waiting';
- if (session.status === 'errored') return 'error';
- // Live peer presence when the core is confident; else the recency heuristic.
- if (session.peerOnline === true) return 'connected';
- if (session.peerOnline === false) return 'disconnected';
- if (session.active || session.status === 'running') return 'connected';
- return 'disconnected';
-}
-
-/** Most actionable state across an instance's sessions. */
-function instanceState(sessions: SessionSummary[]): ConnState {
- const states = sessions.map(sessionState);
- if (states.includes('waiting')) return 'waiting';
- if (states.includes('error')) return 'error';
- if (states.includes('connected')) return 'connected';
- return 'disconnected';
-}
-
-function shortAddress(address: string): string {
- return address.length <= 14 ? address : `${address.slice(0, 6)}…${address.slice(-4)}`;
-}
-
-function sessionLabel(session: SessionSummary): string {
- return session.label?.trim() || session.sessionId;
-}
-
-function StatusDot({ state }: { state: ConnState }) {
- const { t } = useT();
- const fill = DOT_CLASS[state];
- return (
- <span
- title={t(LABEL_KEY[state])}
- aria-label={t(LABEL_KEY[state])}
- className={`h-2 w-2 flex-none rounded-full ${fill ?? 'border border-content-faint/60'}`}
- />
- );
-}
-
-interface ActiveSubagentsRailProps {
- /** Sessions grouped by contact (`agentId`) — the instances. */
- byContact: Map<string, SessionSummary[]>;
- /** Currently open session id (highlighted when on the agent tab). */
- openSessionId: string | null;
- /** Whether the agent chat tab is active (so a selected row reads as current). */
- isAgentTab: boolean;
- onOpenSession: (sessionId: string) => void;
-}
-
-export default function ActiveSubagentsRail({
- byContact,
- openSessionId,
- isAgentTab,
- onOpenSession,
-}: ActiveSubagentsRailProps) {
- const { t } = useT();
- const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
-
- const toggle = useCallback((address: string) => {
- setCollapsed(prev => {
- const next = new Set(prev);
- if (next.has(address)) next.delete(address);
- else next.add(address);
- return next;
- });
- }, []);
-
- const instances = Array.from(byContact.entries());
-
- return (
- <div className="mt-2 border-t border-line-subtle pt-2">
- <div className="px-2 pb-1">
- <span className="text-[10px] font-semibold uppercase tracking-wider text-content-muted">
- {t('orchPage.sessions.railTitle')}
- </span>
- </div>
-
- {instances.length === 0 ? (
- <p className="px-2 py-1 text-[11px] text-content-faint">{t('orchPage.sessions.empty')}</p>
- ) : (
- <ul>
- {instances.map(([address, sessions]) => {
- const isOpen = !collapsed.has(address);
- return (
- <li key={address} data-testid={`orch-instance-${address}`}>
- {/* Instance header — icon + aggregate status dot + name. */}
- <Button
- variant="tertiary"
- aria-expanded={isOpen}
- data-testid={`orch-instance-toggle-${address}`}
- onClick={() => toggle(address)}
- className="h-auto w-full justify-start gap-2 rounded-md px-2 py-1.5 text-left text-content-secondary hover:text-content">
- <span className="flex-none text-[9px] text-content-faint">
- {isOpen ? '▾' : '▸'}
- </span>
- <span className="relative flex-none">
- <span className="flex h-6 w-6 items-center justify-center rounded-md border border-line bg-surface-strong text-[10px] font-semibold text-content-secondary">
- {address.slice(0, 2).toUpperCase()}
- </span>
- <span className="absolute -bottom-0.5 -right-0.5 rounded-full bg-surface-muted p-px">
- <StatusDot state={instanceState(sessions)} />
- </span>
- </span>
- <span className="min-w-0 flex-1 truncate font-mono text-[12px]">
- {shortAddress(address)}
- </span>
- <span className="flex-none text-[10px] text-content-faint">
- {sessions.length}
- </span>
- </Button>
-
- {/* Sub-agents nested under the instance. */}
- {isOpen ? (
- <ul className="ml-4 border-l border-line-subtle pl-1.5">
- {sessions.map(session => {
- const active = isAgentTab && openSessionId === session.sessionId;
- return (
- <li key={session.sessionId}>
- <Button
- variant="tertiary"
- data-testid={`orch-session-rail-${session.sessionId}`}
- aria-current={active ? 'true' : undefined}
- onClick={() => onOpenSession(session.sessionId)}
- className={`h-auto w-full justify-start gap-2 rounded-md px-2 py-1.5 text-left ${
- active
- ? 'bg-surface-subtle text-content hover:bg-surface-subtle'
- : 'text-content-secondary hover:text-content'
- }`}>
- <StatusDot state={sessionState(session)} />
- <span className="min-w-0 flex-1 truncate text-[13px]">
- {sessionLabel(session)}
- </span>
- {session.unread > 0 ? (
- <span className="flex-none rounded-full bg-primary-500 px-1.5 py-0.5 text-[10px] font-semibold text-content-inverted">
- {session.unread}
- </span>
- ) : null}
- </Button>
- </li>
- );
- })}
- </ul>
- ) : null}
- </li>
- );
- })}
- </ul>
- )}
- </div>
- );
-}
diff --git a/app/src/components/orchestration/AgentChatPanel.tsx b/app/src/components/orchestration/AgentChatPanel.tsx
deleted file mode 100644
index 2ad77d030d..0000000000
--- a/app/src/components/orchestration/AgentChatPanel.tsx
+++ /dev/null
@@ -1,645 +0,0 @@
-/**
- * AgentChatPanel — chat with the main agent, rendered exactly like the app's
- * normal chat page.
- *
- * Full-bleed page-variant layout (dark background, centered width-capped message
- * column, a floating composer over a bottom fade, one vertical scroll) shared by
- * three views via {@link ChatPageScaffold}:
- *
- * - the **conscious** master session (composer + welcome hero when empty),
- * - the **subconscious** steering loop (steering header, no composer),
- * - a **peer session subpage** — opened from the sidebar's active sub-agents
- * list or an inline "needs you" card, it takes over the whole pane (not a
- * side drawer) so the session's chat renders full-size, with a back link.
- *
- * Conscious/Subconscious is a bottom toggle in the composer footer.
- */
-import debugFactory from 'debug';
-import {
- type KeyboardEvent,
- type ReactNode,
- type Ref,
- useCallback,
- useEffect,
- useRef,
- useState,
-} from 'react';
-
-import { useStickToBottom } from '../../hooks/useStickToBottom';
-import { useT } from '../../lib/i18n/I18nContext';
-import {
- orchestrationClient,
- type SessionSummary,
-} from '../../lib/orchestration/orchestrationClient';
-import {
- MASTER_CHAT_KEY,
- SUBCONSCIOUS_CHAT_KEY,
- useOrchestrationChats,
-} from '../../lib/orchestration/useOrchestrationChats';
-import {
- useContactSessions,
- useSessionTranscript,
-} from '../../lib/orchestration/useOrchestrationSessions';
-import ChatComposer from '../chat/ChatComposer';
-import ChatNewWindowHero from '../chat/ChatNewWindowHero';
-import { DetachedComposerRuntime } from '../chat/composer/DetachedComposerRuntime';
-import {
- Alert,
- AlertDescription,
- CenteredLoadingState,
- ToggleGroupItem,
- ToggleGroupRoot,
-} from '../ui';
-import Button from '../ui/Button';
-import SessionTranscript from './SessionTranscript';
-
-const debug = debugFactory('orchestration:agent-chat');
-
-// Stable identity for an empty transcript so `useStickToBottom`'s layout effect
-// doesn't re-run every render when the selected chat has no messages yet.
-const EMPTY_MESSAGES: readonly unknown[] = [];
-
-function sessionLabel(session: SessionSummary): string {
- return session.label?.trim() || session.sessionId;
-}
-
-/**
- * Page-variant chat scaffold: the normal chat window's dark surface, a
- * full-width scroll region with a centered width-capped body, a bottom fade, and
- * a floating composer footer. The footer's measured height reserves bottom
- * padding on the scroll region so the last message clears it.
- */
-function ChatPageScaffold({
- header,
- footer,
- scrollRef,
- children,
-}: {
- header?: ReactNode;
- footer?: ReactNode;
- scrollRef?: Ref<HTMLDivElement>;
- children: ReactNode;
-}) {
- const footerRef = useRef<HTMLDivElement | null>(null);
- const [footerHeight, setFooterHeight] = useState(0);
-
- // Subscribe on footer *presence*, never on the `footer` node itself. Every
- // call site passes inline JSX, so `footer` has a fresh object identity on
- // every render — depending on it re-ran this effect each render, tearing down
- // and rebuilding the ResizeObserver and re-measuring. Because
- // `ResizeObserver.observe` delivers an immediate initial observation, each
- // render therefore scheduled another `setFooterHeight`; any measurement that
- // disagreed with the committed height re-rendered, re-ran the effect, and
- // cascaded until React's nested-update limit tripped with "Maximum update
- // depth exceeded" (#5162 / TAURI-REACT-2G). Typing was the easiest trigger:
- // the composer's auto-growing textarea lives inside this footer, so each
- // keystroke changed the measured height. The observer already reports every
- // size change, so it never needs re-subscribing when the footer's children
- // re-render — only when the footer element mounts or unmounts.
- const hasFooter = Boolean(footer);
-
- useEffect(() => {
- // Drop measurements that match the committed height so a settled layout can
- // never schedule a re-render, and therefore can never feed a cascade.
- const applyHeight = (next: number) => setFooterHeight(prev => (prev === next ? prev : next));
-
- const el = footerRef.current;
- if (!hasFooter || !el) {
- applyHeight(0);
- return;
- }
- // ResizeObserver may be absent in some test environments; fall back to a
- // one-shot measure so the layout still resolves.
- if (typeof ResizeObserver === 'undefined') {
- applyHeight(el.offsetHeight);
- return;
- }
- const ro = new ResizeObserver(() => applyHeight(el.offsetHeight));
- ro.observe(el);
- applyHeight(el.offsetHeight);
- return () => ro.disconnect();
- }, [hasFooter]);
-
- return (
- <div className="relative flex h-full flex-col overflow-hidden bg-surface/70 dark:bg-surface-canvas/40">
- {header}
- <div
- ref={scrollRef}
- data-testid="orch-chat-scroll"
- className="min-h-0 flex-1 overflow-y-auto"
- style={footer ? { paddingBottom: footerHeight } : undefined}>
- {children}
- </div>
-
- {/* Fade so messages dissolve into the page behind the composer. Fades to
- the `surface` token the content card paints, not a hardcoded
- white/black pair — see the matching fade in Conversations.tsx. */}
- {footer ? (
- <div
- aria-hidden="true"
- className="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-28 bg-linear-to-t from-surface via-surface/90 to-transparent"
- />
- ) : null}
-
- {/* Floating, centered, width-capped composer footer over the fade. */}
- {footer ? (
- <div
- ref={footerRef}
- data-testid="orch-chat-footer"
- className="absolute inset-x-0 bottom-0 z-20 mx-auto w-full max-w-195 px-4 pb-4 pt-6">
- {footer}
- </div>
- ) : null}
- </div>
- );
-}
-
-/**
- * The shared chat composer wired for the orchestration surfaces: attachments and
- * voice mode are off, and Enter sends (Shift+Enter inserts a newline). The host
- * owns the input value + the async send.
- */
-function AgentComposer({
- value,
- setValue,
- onSend,
- isSending,
- placeholder,
-}: {
- value: string;
- setValue: (value: string | ((prev: string) => string)) => void;
- onSend: (text?: string) => Promise<void>;
- isSending: boolean;
- placeholder: string;
-}) {
- const textInputRef = useRef<HTMLTextAreaElement | null>(null);
- const fileInputRef = useRef<HTMLInputElement | null>(null);
- const isComposingTextRef = useRef(false);
-
- const handleInputKeyDown = useCallback(
- (event: KeyboardEvent<HTMLTextAreaElement>) => {
- if (event.key === 'Enter' && !event.shiftKey && !isComposingTextRef.current) {
- event.preventDefault();
- void onSend();
- }
- },
- [onSend]
- );
-
- return (
- /* This panel's chats are orchestration sessions, not chat threads — there is
- no thread id to scope a runtime to, and no Redux projection to build. But
- `ChatComposer` is built on `ComposerPrimitive`, which resolves its runtime
- from React context, and this panel renders inside the app shell: without a
- runtime of its own the composer would silently inherit the app-wide one
- from `ChatRuntimeProvider`, which is bound to `selectedThreadId` — the
- HOME chat's thread. Sending stays on this panel's own `onSend`, which goes
- through `orchestrationClient`. See `DetachedComposerRuntime` for why that
- rather than `AssistantUiRuntimeProvider threadId={null}`. */
- <DetachedComposerRuntime>
- <ChatComposer
- inputValue={value}
- setInputValue={setValue}
- onSend={async text => {
- await onSend(text);
- }}
- textInputRef={textInputRef}
- fileInputRef={fileInputRef}
- composerInteractionBlocked={false}
- isSending={isSending}
- attachments={[]}
- onAttachFiles={async () => {}}
- onRemoveAttachment={() => {}}
- attachError={null}
- onSwitchToMicCloud={() => {}}
- handleInputKeyDown={handleInputKeyDown}
- inlineCompletionSuffix=""
- isComposingTextRef={isComposingTextRef}
- maxAttachments={0}
- allowedMimeTypes={[]}
- attachmentsEnabled={false}
- micEnabled={false}
- placeholder={placeholder}
- />
- </DetachedComposerRuntime>
- );
-}
-
-/**
- * Peer-session subpage — takes over the whole agent pane (not a side drawer) so
- * the session's chat renders full-size, with a back link to return to the agent
- * chat. Replies go to the peer via the master send path.
- */
-function SessionChatView({ session }: { session: SessionSummary }) {
- const { t } = useT();
- const { state, messages, refresh } = useSessionTranscript(session.sessionId);
- const { containerRef: scrollRef } = useStickToBottom(
- messages,
- session.sessionId,
- session.sessionId
- );
- const [body, setBody] = useState('');
- const [sending, setSending] = useState(false);
- const [sendError, setSendError] = useState<string | null>(null);
- const mountedRef = useRef(true);
- useEffect(() => {
- mountedRef.current = true;
- return () => {
- mountedRef.current = false;
- };
- }, []);
-
- const send = useCallback(
- async (text?: string) => {
- const trimmed = (text ?? body).trim();
- if (!trimmed || sending) return;
- setSending(true);
- setSendError(null);
- debug('[orchestration:agent-chat] session reply: send session=%s', session.sessionId);
- try {
- await orchestrationClient.sendMasterMessage({
- body: trimmed,
- recipient: session.agentId,
- sessionId: session.sessionId,
- });
- if (!mountedRef.current) return;
- setBody('');
- void refresh();
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- debug(
- '[orchestration:agent-chat] session reply: failed session=%s %s',
- session.sessionId,
- message
- );
- if (mountedRef.current) setSendError(message);
- } finally {
- if (mountedRef.current) setSending(false);
- }
- },
- [body, sending, session.agentId, session.sessionId, refresh]
- );
-
- // A runtime tool-approval decision → reply "allow"/"deny" to the peer. Rethrows
- // on failure so SessionTranscript rolls the card back to buttons for a retry.
- const decide = useCallback(
- async (decision: 'allow' | 'deny'): Promise<void> => {
- setSendError(null);
- debug(
- '[orchestration:agent-chat] approval decision: send session=%s decision=%s',
- session.sessionId,
- decision
- );
- try {
- await orchestrationClient.sendMasterMessage({
- body: decision,
- recipient: session.agentId,
- sessionId: session.sessionId,
- });
- if (mountedRef.current) void refresh();
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- debug(
- '[orchestration:agent-chat] approval decision: failed session=%s %s',
- session.sessionId,
- message
- );
- if (mountedRef.current) setSendError(message);
- throw error;
- }
- },
- [session.agentId, session.sessionId, refresh]
- );
-
- const runtime = session.harnessType || session.source || null;
- const directory = session.workspace?.trim() || null;
- const runningOn = session.agentId?.trim() || null;
-
- return (
- <ChatPageScaffold
- scrollRef={scrollRef}
- header={
- // Agent metadata, centered to the same width-capped column as the chat.
- <div className="border-b border-line bg-surface/60 dark:bg-surface-canvas/30">
- <div className="mx-auto w-full max-w-195 px-5 py-3" data-testid="orch-session-header">
- <div className="flex items-center gap-2">
- <p className="text-sm font-semibold text-content">{sessionLabel(session)}</p>
- {session.status === 'waiting-approval' ? (
- <span className="flex-none rounded-full px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300">
- {t('orchPage.connections.status.needsYou')}
- </span>
- ) : null}
- </div>
- {/* Full values — they wrap/break only at the column's max width, never
- truncated at an arbitrary per-field cap. */}
- <dl className="mt-1.5 flex flex-wrap gap-x-5 gap-y-1 text-[11px]">
- {runtime ? (
- <div className="flex items-baseline gap-1">
- <dt className="text-content-faint">{t('orchPage.session.runtime')}</dt>
- <dd className="font-medium text-content-secondary">{runtime}</dd>
- </div>
- ) : null}
- {directory ? (
- <div className="flex items-baseline gap-1">
- <dt className="text-content-faint">{t('orchPage.session.directory')}</dt>
- <dd className="break-all font-mono font-medium text-content-secondary">
- {directory}
- </dd>
- </div>
- ) : null}
- {runningOn ? (
- <div className="flex items-baseline gap-1">
- <dt className="text-content-faint">{t('orchPage.session.runningOn')}</dt>
- <dd className="break-all font-mono font-medium text-content-secondary">
- {runningOn}
- </dd>
- </div>
- ) : null}
- </dl>
- </div>
- </div>
- }
- footer={
- <>
- {sendError ? (
- <Alert
- variant="destructive"
- density="compact"
- data-testid="orch-session-reply-error"
- className="mb-2">
- <AlertDescription>
- {t('tinyplaceOrchestration.composer.sendFailed')}: {sendError}
- </AlertDescription>
- </Alert>
- ) : null}
- <AgentComposer
- value={body}
- setValue={setBody}
- onSend={send}
- isSending={sending}
- placeholder={t('orchPage.connections.replyPlaceholder')}
- />
- </>
- }>
- <div className="mx-auto w-full max-w-195 space-y-3 px-5 pt-4">
- {state.status === 'loading' ? (
- <CenteredLoadingState label={t('tinyplaceOrchestration.loading')} className="py-10" />
- ) : state.status === 'error' ? (
- <p className="py-10 text-center text-sm text-coral-600 dark:text-coral-300">
- {t('tinyplaceOrchestration.failedToLoad')}: {state.message}
- </p>
- ) : messages.length === 0 ? (
- <p className="py-10 text-center text-sm text-content-faint">
- {t('tinyplaceOrchestration.noMessages')}
- </p>
- ) : (
- <SessionTranscript
- messages={messages}
- onDecide={(_message, decision) => decide(decision === 'deny' ? 'deny' : 'allow')}
- />
- )}
- </div>
- </ChatPageScaffold>
- );
-}
-
-interface AgentChatPanelProps {
- /**
- * Controlled open peer-session id (the full-page session subpage). When
- * `onOpenSession` is provided the parent owns this (OrchestrationView drives
- * it from the `?session=` query param + the active sub-agents rail);
- * otherwise the panel falls back to its own local state.
- */
- openSessionId?: string | null;
- onOpenSession?: (sessionId: string | null) => void;
-}
-
-export default function AgentChatPanel({
- openSessionId: controlledOpenSessionId,
- onOpenSession,
-}: AgentChatPanelProps = {}) {
- const { t } = useT();
- const {
- sessionsState,
- messagesState,
- chats,
- selectedId,
- selected,
- status,
- masterError,
- selectChat,
- refresh,
- sendMessage,
- } = useOrchestrationChats(t);
- const contactSessions = useContactSessions();
- // Keep the transcript pinned to the newest message (and disengage when the
- // user scrolls up). Called before the `openSession` early return so hook order
- // stays stable; `selectedId` as thread + reset key snaps fresh on tab switch.
- const { containerRef: masterScrollRef } = useStickToBottom(
- selected?.messages ?? EMPTY_MESSAGES,
- selectedId,
- selectedId
- );
-
- const [composerBody, setComposerBody] = useState('');
- const [sending, setSending] = useState(false);
- // Controlled by the parent when `onOpenSession` is wired (OrchestrationView
- // drives it from the URL + active sub-agents rail); local state otherwise.
- const [localOpenSessionId, setLocalOpenSessionId] = useState<string | null>(null);
- const openSessionId =
- controlledOpenSessionId !== undefined ? controlledOpenSessionId : localOpenSessionId;
- const setOpenSessionId = onOpenSession ?? setLocalOpenSessionId;
- const mountedRef = useRef(true);
- useEffect(() => {
- mountedRef.current = true;
- return () => {
- mountedRef.current = false;
- };
- }, []);
-
- // Send the master composer's body via the orchestration send path.
- const sendComposer = useCallback(
- async (text?: string) => {
- const body = (text ?? composerBody).trim();
- if (!body || sending) return;
- setSending(true);
- const ok = await sendMessage(selected, body);
- if (!mountedRef.current) return;
- if (ok) setComposerBody('');
- setSending(false);
- },
- [composerBody, sending, sendMessage, selected]
- );
-
- const steeringText = status?.steering?.text?.trim() || null;
- const isMasterSelected = selectedId === MASTER_CHAT_KEY;
- const isSubconscious = selectedId === SUBCONSCIOUS_CHAT_KEY;
-
- const rail = chats.filter(c => c.id === MASTER_CHAT_KEY || c.id === SUBCONSCIOUS_CHAT_KEY);
- // Sessions the agent has engaged that are parked on an approval → "needs you".
- const pinged = contactSessions.sessions.filter(s => s.status === 'waiting-approval');
- const openSession = contactSessions.sessions.find(s => s.sessionId === openSessionId) ?? null;
- // Empty conscious thread → show the shared welcome hero (reuses the generic
- // chat's "new window" panel) instead of the bare "no messages" line.
- const showHero = isMasterSelected && (selected?.messages.length ?? 0) === 0;
-
- // A session is open → take over the whole pane with its full-page chat.
- // Returning to the master chat is done from the sidebar's Chat item (which
- // clears the `?session=` param), so no in-view back button is needed.
- if (openSession) {
- return <SessionChatView session={openSession} />;
- }
-
- const loading = sessionsState.status === 'loading' || messagesState.status === 'loading';
- const errored = sessionsState.status === 'error' || messagesState.status === 'error';
-
- // The Conscious/Subconscious toggle sits in the composer footer.
- // `ToggleGroupRoot type="single"` is the app's segmented-selection primitive:
- // it emits the same `role="radiogroup"` / `role="radio"` / `aria-checked` this
- // hand-rolled before, and adds the one thing it was missing — a single roving
- // tab stop, so Tab reaches the control once and the arrow keys move between
- // the two modes instead of Tab stopping on every chip. The on-state comes from
- // `toggleVariants` rather than a hand-picked pair of fills.
- const modeToggle = (
- <ToggleGroupRoot
- type="single"
- size="xs"
- variant="tertiary"
- value={selectedId ?? undefined}
- // Radix allows a single-type group to deselect (value becomes ''); this
- // control always has exactly one mode active, so an empty value is
- // ignored rather than clearing the selection.
- onValueChange={value => {
- if (value) selectChat(value);
- }}
- className="inline-flex h-7 items-center gap-0 rounded-full border border-line bg-surface-subtle p-0.5"
- aria-label={t('orchPage.agent.modeLabel')}>
- {rail.map(chat => {
- const label =
- chat.id === SUBCONSCIOUS_CHAT_KEY
- ? t('orchPage.agent.subconsciousTab')
- : t('orchPage.agent.consciousTab');
- return (
- <ToggleGroupItem
- key={chat.id}
- value={chat.id}
- data-testid={`orch-agent-tab-${chat.id}`}
- className="h-auto gap-1.5 rounded-full px-3 py-0.5 text-xs font-medium data-[state=on]:shadow-xs">
- {label}
- {chat.unread > 0 ? (
- <span className="inline-flex min-w-4 items-center justify-center rounded-full bg-primary-500 px-1 text-[10px] font-semibold text-content-inverted">
- {chat.unread}
- </span>
- ) : null}
- </ToggleGroupItem>
- );
- })}
- </ToggleGroupRoot>
- );
-
- const showComposer = isMasterSelected && sessionsState.status === 'ok';
-
- return (
- // The main agent chat has no top header — just the conscious/subconscious
- // switching chip in the footer. When subconscious is active, the steering
- // directive + "Run review" ride alongside the chip (no header bar).
- <ChatPageScaffold
- scrollRef={masterScrollRef}
- footer={
- <div className="flex flex-col gap-2">
- {showComposer ? (
- <>
- {masterError ? (
- <Alert variant="destructive" density="compact">
- <AlertDescription>
- {t('tinyplaceOrchestration.composer.sendFailed')}: {masterError}
- </AlertDescription>
- </Alert>
- ) : null}
- <AgentComposer
- value={composerBody}
- setValue={setComposerBody}
- onSend={sendComposer}
- isSending={sending}
- placeholder={t('tinyplaceOrchestration.composer.placeholder')}
- />
- </>
- ) : null}
- <div className="flex items-center justify-between gap-2">
- {modeToggle}
- {isSubconscious ? (
- <div className="flex min-w-0 items-center gap-2" data-testid="orch-agent-steering">
- {steeringText ? (
- <span className="hidden min-w-0 truncate text-[11px] text-content-muted sm:inline">
- {steeringText}
- </span>
- ) : null}
- </div>
- ) : null}
- </div>
- </div>
- }>
- {loading ? (
- <div className="flex h-full items-center justify-center text-sm text-content-muted">
- {t('tinyplaceOrchestration.loading')}
- </div>
- ) : errored ? (
- <div className="flex h-full flex-col items-center justify-center gap-3 text-sm text-coral-600 dark:text-coral-300">
- <p>
- {t('tinyplaceOrchestration.failedToLoad')}:{' '}
- {sessionsState.status === 'error'
- ? sessionsState.message
- : messagesState.status === 'error'
- ? messagesState.message
- : ''}
- </p>
- <Button variant="secondary" size="sm" onClick={() => void refresh()}>
- {t('common.retry')}
- </Button>
- </div>
- ) : showHero && pinged.length === 0 ? (
- // Empty conscious thread: reuse the generic chat's welcome hero.
- <div className="mx-auto flex h-full w-full max-w-195 px-5">
- <ChatNewWindowHero />
- </div>
- ) : (
- <div className="mx-auto w-full max-w-195 space-y-3 px-5 pt-4">
- {selected?.messages.length ? (
- <SessionTranscript messages={selected.messages} />
- ) : showHero ? null : (
- <p className="py-10 text-center text-sm text-content-faint">
- {t('tinyplaceOrchestration.noMessages')}
- </p>
- )}
-
- {/* "Needs you" cards for sessions the agent engaged → open the session
- subpage (same as clicking it in the sidebar's active sub-agents). */}
- {pinged.map(session => (
- <div key={session.sessionId} className="flex justify-start">
- <Button
- variant="secondary"
- data-testid={`orch-agent-view-session-${session.sessionId}`}
- onClick={() => setOpenSessionId(session.sessionId)}
- className="h-auto w-full max-w-[85%] justify-start gap-3 rounded-xl border-primary-200 bg-primary-50 px-3 py-2.5 text-left hover:bg-primary-100/60 dark:border-primary-500/30 dark:bg-primary-900/20">
- <span className="flex h-8 w-8 flex-none items-center justify-center rounded-lg bg-primary-500/15 text-sm text-primary-600 dark:text-primary-300">
- ⧉
- </span>
- <span className="min-w-0 flex-1">
- <span className="block truncate text-sm font-medium text-content">
- {sessionLabel(session)}
- </span>
- <span className="block truncate text-[11px] text-amber-600 dark:text-amber-300">
- {t('orchPage.connections.status.needsYou')}
- </span>
- </span>
- <span className="flex-none rounded-lg bg-primary-500 px-3 py-1.5 text-xs font-semibold text-content-inverted">
- {t('orchPage.agent.viewSession')}
- </span>
- </Button>
- </div>
- ))}
- </div>
- )}
- </ChatPageScaffold>
- );
-}
diff --git a/app/src/components/orchestration/ConnectionsPanel.tsx b/app/src/components/orchestration/ConnectionsPanel.tsx
deleted file mode 100644
index 3cd48934ee..0000000000
--- a/app/src/components/orchestration/ConnectionsPanel.tsx
+++ /dev/null
@@ -1,583 +0,0 @@
-/**
- * ConnectionsPanel — the agent's connections **and their sessions**.
- *
- * A list of accepted tiny.place contacts where each contact expands to reveal
- * your sessions with it (status · last activity · message count). Opening a
- * session shows its conversation history in place — rendered in the app's normal
- * chat-window style via {@link SessionTranscript} — with an inline reply
- * composer. Pending requests + a summary sit on top. Linking new agents still
- * lives in the sibling DiscoverPanel.
- *
- * Renders inside the same single `max-w-3xl` column OrchestrationView gives it.
- */
-import debugFactory from 'debug';
-import { type FormEvent, useCallback, useEffect, useMemo, useState } from 'react';
-
-import { apiClient } from '../../lib/agentworld/apiClient';
-import { useT } from '../../lib/i18n/I18nContext';
-import {
- type InstanceStatus,
- orchestrationClient,
- type SessionSummary,
-} from '../../lib/orchestration/orchestrationClient';
-import {
- useContactSessions,
- useSessionTranscript,
-} from '../../lib/orchestration/useOrchestrationSessions';
-import { usePairing } from '../../lib/orchestration/usePairing';
-import { contactAddress, extractHandle } from '../intelligence/orchestrationTabHelpers';
-import { Alert, AlertDescription, CenteredLoadingState } from '../ui';
-import Button from '../ui/Button';
-import TextField from '../ui/TextField';
-import { SectionCard, StatTile } from './primitives';
-import SessionTranscript from './SessionTranscript';
-
-const debug = debugFactory('orchestration:connections');
-
-type Translate = (key: string, fallback?: string) => string;
-
-interface StatusMeta {
- label: string;
- dot: string;
- tone: string;
-}
-
-function statusMeta(status: InstanceStatus, t: Translate): StatusMeta {
- switch (status) {
- case 'waiting-approval':
- return {
- label: t('orchPage.connections.status.needsYou'),
- dot: 'bg-amber-500',
- tone: 'text-amber-700 dark:text-amber-300',
- };
- case 'running':
- return {
- label: t('orchPage.connections.status.running'),
- dot: 'bg-sage-500',
- tone: 'text-sage-700 dark:text-sage-300',
- };
- case 'errored':
- return {
- label: t('orchPage.connections.status.error'),
- dot: 'bg-coral-500',
- tone: 'text-coral-700 dark:text-coral-300',
- };
- case 'idle':
- return {
- label: t('orchPage.connections.status.idle'),
- dot: 'bg-content-faint',
- tone: 'text-content-muted',
- };
- default:
- return {
- label: t('orchPage.connections.status.done'),
- dot: 'bg-content-faint',
- tone: 'text-content-muted',
- };
- }
-}
-
-function shortAddress(address: string): string {
- return address.length <= 14 ? address : `${address.slice(0, 6)}…${address.slice(-4)}`;
-}
-
-// ── Session view (in place) ──────────────────────────────────────────────────
-function SessionView({
- session,
- contactAddr,
- handle,
- onBack,
-}: {
- session: SessionSummary;
- contactAddr: string;
- handle: string | null;
- onBack: () => void;
-}) {
- const { t } = useT();
- const { state, messages, refresh } = useSessionTranscript(session.sessionId);
- const [body, setBody] = useState('');
- const [sending, setSending] = useState(false);
- const [sendError, setSendError] = useState<string | null>(null);
- const label = session.label?.trim() || session.sessionId;
- const meta = statusMeta(session.status, t);
-
- const submit = useCallback(
- (event: FormEvent<HTMLFormElement>) => {
- event.preventDefault();
- const trimmed = body.trim();
- if (!trimmed || sending) return;
- setSending(true);
- setSendError(null);
- debug('[orchestration:connections] session reply: send session=%s', session.sessionId);
- void orchestrationClient
- .sendMasterMessage({ body: trimmed, recipient: contactAddr, sessionId: session.sessionId })
- .then(() => {
- setBody('');
- void refresh();
- })
- .catch((error: unknown) => {
- const message = error instanceof Error ? error.message : String(error);
- debug(
- '[orchestration:connections] session reply: failed session=%s %s',
- session.sessionId,
- message
- );
- setSendError(message);
- })
- .finally(() => setSending(false));
- },
- [body, sending, contactAddr, session.sessionId, refresh]
- );
-
- // Runtime tool-approval decision → reply "allow"/"deny" to the runtime peer (the
- // same send path as a typed reply). Returns the promise (rethrows on failure) so
- // SessionTranscript rolls the card back to buttons for a retry.
- const decide = useCallback(
- (decision: 'allow' | 'deny'): Promise<void> => {
- setSendError(null);
- debug(
- '[orchestration:connections] approval decision: send session=%s decision=%s',
- session.sessionId,
- decision
- );
- return orchestrationClient
- .sendMasterMessage({ body: decision, recipient: contactAddr, sessionId: session.sessionId })
- .then(() => {
- void refresh();
- })
- .catch((error: unknown) => {
- const message = error instanceof Error ? error.message : String(error);
- debug(
- '[orchestration:connections] approval decision: failed session=%s %s',
- session.sessionId,
- message
- );
- setSendError(message);
- throw error;
- });
- },
- [contactAddr, session.sessionId, refresh]
- );
-
- return (
- <div className="space-y-3" data-testid="orch-session-view">
- <Button
- variant="tertiary"
- size="xs"
- onClick={onBack}
- data-testid="orch-session-back"
- className="h-auto gap-1.5 px-0 text-xs font-medium text-primary-600 hover:bg-transparent hover:text-primary-700 dark:text-primary-300">
- ← {t('orchPage.connections.back')} / {handle ? `@${handle}` : shortAddress(contactAddr)}
- </Button>
- <SectionCard
- title={
- <span className="flex items-center gap-2">
- {label}
- <span className={`rounded-full px-1.5 py-0.5 text-[10px] font-medium ${meta.tone}`}>
- {meta.label}
- </span>
- </span>
- }
- description={
- session.messageCount
- ? t('orchPage.connections.messageCount').replace('{n}', String(session.messageCount))
- : undefined
- }>
- {state.status === 'loading' ? (
- <CenteredLoadingState label={t('tinyplaceOrchestration.loading')} className="py-6" />
- ) : state.status === 'error' ? (
- <p className="py-6 text-center text-sm text-coral-600 dark:text-coral-300">
- {t('tinyplaceOrchestration.failedToLoad')}: {state.message}
- </p>
- ) : messages.length === 0 ? (
- <p className="py-6 text-center text-sm text-content-faint">
- {t('tinyplaceOrchestration.noMessages')}
- </p>
- ) : (
- <SessionTranscript
- messages={messages}
- onDecide={(_message, decision) => decide(decision === 'deny' ? 'deny' : 'allow')}
- />
- )}
- {sendError ? (
- <Alert
- variant="destructive"
- density="compact"
- data-testid="orch-session-reply-error"
- className="mt-3">
- <AlertDescription>
- {t('tinyplaceOrchestration.composer.sendFailed')}: {sendError}
- </AlertDescription>
- </Alert>
- ) : null}
- <form className="mt-3 flex gap-2 border-t border-line pt-3" onSubmit={submit}>
- <TextField
- value={body}
- onChange={e => setBody(e.target.value)}
- placeholder={t('orchPage.connections.replyPlaceholder')}
- data-testid="orch-session-reply-input"
- className="min-w-0 flex-1"
- />
- <Button
- type="submit"
- variant="primary"
- size="sm"
- disabled={!body.trim() || sending}
- data-testid="orch-session-reply-send">
- {t('tinyplaceOrchestration.composer.send')}
- </Button>
- </form>
- </SectionCard>
- </div>
- );
-}
-
-// ── One connection row + its nested sessions ─────────────────────────────────
-function ConnectionRow({
- address,
- handle,
- sessions,
- expanded,
- onToggle,
- onOpenSession,
- onNewSession,
- creating,
-}: {
- address: string;
- handle: string | null;
- sessions: SessionSummary[];
- expanded: boolean;
- onToggle: () => void;
- onOpenSession: (s: SessionSummary) => void;
- onNewSession: () => void;
- creating: boolean;
-}) {
- const { t } = useT();
- const online = sessions.some(s => s.active);
- return (
- <li className="py-1" data-testid={`orch-connection-${address}`}>
- <Button
- variant="tertiary"
- onClick={onToggle}
- aria-expanded={expanded}
- className="h-auto w-full justify-start gap-3 rounded-lg px-2 py-2 text-left">
- <span className="flex-none text-[10px] text-content-muted">{expanded ? '▾' : '▸'}</span>
- <span className="relative flex-none">
- <span className="flex h-9 w-9 items-center justify-center rounded-full border border-line bg-surface-strong text-[11px] font-semibold text-content-secondary">
- {(handle ?? address).slice(0, 2)}
- </span>
- {online ? (
- <span className="absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2 border-surface bg-sage-500" />
- ) : null}
- </span>
- <span className="min-w-0 flex-1">
- <span className="block truncate text-sm font-semibold text-content">
- {handle ? `@${handle}` : t('tinyplaceOrchestration.unknownSender')}
- </span>
- <span className="block truncate font-mono text-[11px] text-content-faint">
- {shortAddress(address)}
- </span>
- </span>
- <span className="flex-none rounded-full bg-surface-strong px-2 py-0.5 text-[10px] font-medium text-content-muted">
- {sessions.length === 0
- ? t('orchPage.connections.noSessions')
- : t('orchPage.connections.sessionCount').replace('{n}', String(sessions.length))}
- </span>
- </Button>
-
- {expanded ? (
- <div className="ml-9 mt-1 space-y-1 pl-2">
- {sessions.map(session => {
- const meta = statusMeta(session.status, t);
- const label = session.label?.trim() || session.sessionId;
- return (
- <Button
- key={session.sessionId}
- variant="secondary"
- data-testid={`orch-session-${session.sessionId}`}
- onClick={() => onOpenSession(session)}
- className="h-auto w-full justify-start gap-3 rounded-lg border-line bg-surface-subtle px-3 py-2 text-left">
- <span className={`h-1.5 w-1.5 flex-none rounded-full ${meta.dot}`} />
- <span className="min-w-0 flex-1">
- <span className="flex items-center gap-2">
- <span className="truncate text-sm font-medium text-content">{label}</span>
- <span className={`flex-none text-[10px] font-medium ${meta.tone}`}>
- {meta.label}
- </span>
- </span>
- {session.currentTask ? (
- <span className="mt-0.5 block truncate text-[11px] text-content-muted">
- {session.currentTask}
- </span>
- ) : null}
- </span>
- <span className="flex-none text-[10px] text-content-faint">
- {session.messageCount
- ? t('orchPage.connections.messageCount').replace(
- '{n}',
- String(session.messageCount)
- )
- : ''}
- </span>
- <span className="flex-none text-content-faint">›</span>
- </Button>
- );
- })}
- <Button
- variant="tertiary"
- data-testid={`orch-new-session-${address}`}
- disabled={creating}
- onClick={onNewSession}
- className="h-auto w-full justify-start gap-1 rounded-lg px-3 py-1.5 text-left text-[11px] font-medium text-primary-600 disabled:opacity-50 dark:text-primary-300">
- + {t('tinyplaceOrchestration.newSession')}
- </Button>
- </div>
- ) : null}
- </li>
- );
-}
-
-export default function ConnectionsPanel({
- onDiscover,
- onInitializeAgent,
-}: {
- onDiscover?: () => void;
- /** Jump to the agent chat to describe + spin up a new sub-agent. */
- onInitializeAgent?: () => void;
-}) {
- const { t } = useT();
- const { state, runAction, pendingAction, actionError } = usePairing();
- const sessions = useContactSessions();
- const [handles, setHandles] = useState<Record<string, string | null>>({});
- const [expanded, setExpanded] = useState<Set<string>>(new Set());
- const [open, setOpen] = useState<{ address: string; session: SessionSummary } | null>(null);
- const [creating, setCreating] = useState<string | null>(null);
-
- const snapshot = state.status === 'ok' ? state.snapshot : null;
- const accepted = useMemo(
- () => (snapshot?.contacts.contacts ?? []).filter(c => c.status === 'accepted'),
- [snapshot?.contacts.contacts]
- );
- const incoming = useMemo(() => snapshot?.requests.incoming ?? [], [snapshot?.requests.incoming]);
- const stats = snapshot?.stats ?? null;
- const totalSessions = sessions.sessions.length;
-
- // Best-effort @handle resolution (address always shown).
- const addressesKey = [...accepted, ...incoming].map(contactAddress).filter(Boolean).join(',');
- useEffect(() => {
- const ids = addressesKey ? Array.from(new Set(addressesKey.split(','))) : [];
- if (ids.length === 0) return;
- let cancelled = false;
- void Promise.all(
- ids.map(async id => {
- try {
- return [id, extractHandle(await apiClient.directory.reverse(id))] as const;
- } catch {
- return [id, null] as const;
- }
- })
- ).then(entries => {
- if (cancelled) return;
- setHandles(prev => {
- const next = { ...prev };
- for (const [id, handle] of entries) if (!(id in next)) next[id] = handle;
- return next;
- });
- });
- return () => {
- cancelled = true;
- };
- }, [addressesKey]);
-
- const toggle = useCallback((address: string) => {
- setExpanded(prev => {
- const next = new Set(prev);
- if (next.has(address)) next.delete(address);
- else next.add(address);
- return next;
- });
- }, []);
-
- const newSession = useCallback(
- (address: string) => {
- setCreating(address);
- void runAction(`new:${address}`, async () => {
- const { session } = await orchestrationClient.sessionsCreate({ agentId: address });
- await sessions.refresh();
- setOpen({ address, session });
- }).finally(() => setCreating(null));
- },
- [runAction, sessions]
- );
-
- if (state.status === 'loading') {
- return (
- <div data-testid="orch-connections-loading">
- <CenteredLoadingState label={t('tinyplaceOrchestration.loading')} />
- </div>
- );
- }
- if (state.status === 'payment_required') {
- return (
- <p className="py-8 text-center text-sm text-amber-600 dark:text-amber-300">
- {t('tinyplaceOrchestration.paymentRequired')}
- </p>
- );
- }
- if (state.status === 'error') {
- return (
- <p className="py-8 text-center text-sm text-coral-600 dark:text-coral-300">
- {t('tinyplaceOrchestration.failedToLoad')}: {state.message}
- </p>
- );
- }
-
- if (open) {
- // Prefer the live session row (socket-refreshed) so the header's
- // status / message count / label stay current; fall back to the captured
- // snapshot for a just-created session not yet in the list.
- const liveSession =
- sessions.sessions.find(s => s.sessionId === open.session.sessionId) ?? open.session;
- return (
- <SessionView
- session={liveSession}
- contactAddr={open.address}
- handle={handles[open.address] ?? null}
- onBack={() => setOpen(null)}
- />
- );
- }
-
- return (
- <div className="space-y-4" data-testid="orch-connections-panel">
- <div className="grid grid-cols-3 gap-3">
- <StatTile
- label={t('orchPage.connections.statContacts')}
- value={stats?.contactCount ?? accepted.length}
- testId="orch-connections-stat-contacts"
- />
- <StatTile
- label={t('orchPage.connections.statSessions')}
- value={totalSessions}
- testId="orch-connections-stat-sessions"
- />
- <StatTile
- label={t('orchPage.connections.statPending')}
- value={(stats?.pendingIncoming ?? 0) + (stats?.pendingOutgoing ?? 0)}
- hint={t('orchPage.connections.pendingHint')}
- testId="orch-connections-stat-pending"
- />
- </div>
-
- {actionError && (
- <Alert variant="destructive" density="compact">
- <AlertDescription>{actionError}</AlertDescription>
- </Alert>
- )}
-
- {incoming.length > 0 ? (
- <SectionCard
- title={t('tinyplaceOrchestration.pairing.requests')}
- testId="orch-connections-requests">
- <ul className="divide-y divide-line">
- {incoming.map(request => {
- const address = contactAddress(request);
- const handle = handles[address];
- return (
- <li key={address} className="flex items-center justify-between gap-3 py-2.5">
- <div className="min-w-0">
- <p className="truncate text-sm font-medium text-content">
- {handle ? `@${handle}` : t('tinyplaceOrchestration.unknownSender')}
- </p>
- <p className="truncate font-mono text-[11px] text-content-faint">
- {shortAddress(address)}
- </p>
- </div>
- <div className="flex flex-none gap-1.5">
- <Button
- variant="primary"
- size="sm"
- disabled={pendingAction !== null || !address}
- onClick={() =>
- void runAction(`accept:${address}`, () =>
- apiClient.orchestrationPairing.acceptRequest(address)
- )
- }>
- {t('tinyplaceOrchestration.pairing.accept')}
- </Button>
- <Button
- variant="secondary"
- size="sm"
- disabled={pendingAction !== null || !address}
- onClick={() =>
- void runAction(`decline:${address}`, () =>
- apiClient.orchestrationPairing.declineRequest(address)
- )
- }>
- {t('tinyplaceOrchestration.pairing.decline')}
- </Button>
- </div>
- </li>
- );
- })}
- </ul>
- </SectionCard>
- ) : null}
-
- <SectionCard
- title={t('orchPage.connections.title')}
- description={t('orchPage.connections.description')}>
- {accepted.length === 0 ? (
- <div className="py-6 text-center" data-testid="orch-connections-empty">
- <p className="text-sm text-content-muted">{t('orchPage.connections.empty')}</p>
- {onDiscover && (
- <Button
- variant="primary"
- size="sm"
- className="mt-3"
- onClick={onDiscover}
- data-testid="orch-connections-empty-cta">
- {t('orchPage.connections.emptyCta')}
- </Button>
- )}
- </div>
- ) : (
- <ul className="divide-y divide-line/60">
- {accepted.map(contact => {
- const address = contactAddress(contact);
- return (
- <ConnectionRow
- key={address}
- address={address}
- handle={handles[address] ?? null}
- sessions={sessions.byContact.get(address) ?? []}
- expanded={expanded.has(address)}
- onToggle={() => toggle(address)}
- onOpenSession={session => setOpen({ address, session })}
- onNewSession={() => newSession(address)}
- creating={creating === address}
- />
- );
- })}
- </ul>
- )}
- </SectionCard>
-
- {/* Initialize a brand-new sub-agent / instance. Unlike Discover (which
- links to an EXISTING peer), this explains how to spin up your own. */}
- <SectionCard
- title={t('orchPage.connections.initTitle')}
- description={t('orchPage.connections.initDesc')}
- testId="orch-connections-initialize">
- <Button
- variant="primary"
- size="sm"
- onClick={onInitializeAgent}
- disabled={!onInitializeAgent}
- data-testid="orch-connections-initialize-cta">
- {t('orchPage.connections.initCta')}
- </Button>
- </SectionCard>
- </div>
- );
-}
diff --git a/app/src/components/orchestration/DiscoverPanel.tsx b/app/src/components/orchestration/DiscoverPanel.tsx
deleted file mode 100644
index 6cfc85fb80..0000000000
--- a/app/src/components/orchestration/DiscoverPanel.tsx
+++ /dev/null
@@ -1,240 +0,0 @@
-/**
- * DiscoverPanel — "handle connections and guide the user to add more".
- *
- * The growth surface: shows this agent's own tiny.place discoverability (so the
- * user knows whether peers can even reach them), a link-a-new-agent form, and
- * the inbound contact-request queue (accept / decline / block). Steady-state
- * management of already-linked peers lives in the sibling {@link ConnectionsPanel}.
- */
-import { type FormEvent, useCallback, useEffect, useMemo, useState } from 'react';
-
-import { resolveWalletConfigured } from '../../hooks/useWalletConfigured';
-import { apiClient } from '../../lib/agentworld/apiClient';
-import { useT } from '../../lib/i18n/I18nContext';
-import {
- orchestrationClient,
- type RelayInfo,
- type SelfIdentity,
-} from '../../lib/orchestration/orchestrationClient';
-import { usePairing } from '../../lib/orchestration/usePairing';
-import { contactAddress, extractHandle } from '../intelligence/orchestrationTabHelpers';
-import { CenteredLoadingState } from '../ui';
-import Button from '../ui/Button';
-import TextField from '../ui/TextField';
-import { SectionCard } from './primitives';
-
-export default function DiscoverPanel() {
- const { t } = useT();
- const { state, runAction, pendingAction, actionError } = usePairing();
- const [linkAgentId, setLinkAgentId] = useState('');
- const [identity, setIdentity] = useState<SelfIdentity | null>(null);
- const [relay, setRelay] = useState<RelayInfo | null>(null);
- const [identityLoading, setIdentityLoading] = useState(true);
- const [handles, setHandles] = useState<Record<string, string | null>>({});
-
- useEffect(() => {
- let cancelled = false;
- // Gate the wallet-requiring read: selfIdentity() derives a tiny.place
- // signer from the wallet, so with none configured it can only reject with
- // the core's wallet-not-configured error — an expected state that still
- // travels as an Err and lands as an error-level report (#5805). Ask
- // wallet_status, which answers the same question without erroring, and skip
- // only on a positive `no`. relayInfo() needs no wallet and always runs.
- // Fire the wallet-independent read FIRST so relay is never delayed by the
- // wallet probe.
- const relayPromise = orchestrationClient.relayInfo();
- const identityPromise = resolveWalletConfigured().then(configured =>
- configured === 'no' ? null : orchestrationClient.selfIdentity()
- );
- void Promise.allSettled([identityPromise, relayPromise]).then(([id, rel]) => {
- if (cancelled) return;
- // `null` is the skipped case — leave `identity` null, exactly as a
- // failed fetch would, so the render path is unchanged.
- if (id.status === 'fulfilled' && id.value !== null) setIdentity(id.value);
- if (rel.status === 'fulfilled') setRelay(rel.value);
- setIdentityLoading(false);
- });
- return () => {
- cancelled = true;
- };
- }, []);
-
- const snapshot = state.status === 'ok' ? state.snapshot : null;
- const incoming = useMemo(() => snapshot?.requests.incoming ?? [], [snapshot?.requests.incoming]);
-
- // Resolve @handles for the inbound requests (best-effort; address always shown).
- const addressesKey = incoming.map(contactAddress).filter(Boolean).join(',');
- useEffect(() => {
- const ids = addressesKey ? Array.from(new Set(addressesKey.split(','))) : [];
- if (ids.length === 0) return;
- let cancelled = false;
- void Promise.all(
- ids.map(async id => {
- try {
- return [id, extractHandle(await apiClient.directory.reverse(id))] as const;
- } catch {
- return [id, null] as const;
- }
- })
- ).then(entries => {
- if (cancelled) return;
- setHandles(prev => {
- const next = { ...prev };
- for (const [id, handle] of entries) if (!(id in next)) next[id] = handle;
- return next;
- });
- });
- return () => {
- cancelled = true;
- };
- }, [addressesKey]);
-
- const submitLink = useCallback(
- (event: FormEvent<HTMLFormElement>) => {
- event.preventDefault();
- const agentId = linkAgentId.trim();
- if (!agentId) return;
- void runAction(`link:${agentId}`, async () => {
- await apiClient.orchestrationPairing.linkSession(agentId);
- setLinkAgentId('');
- });
- },
- [linkAgentId, runAction]
- );
-
- const discoverable = identity?.discoverable ?? false;
-
- return (
- <div className="space-y-5" data-testid="orch-discover-panel">
- {/* Own identity / discoverability. */}
- <SectionCard title={t('orchPage.discover.identityTitle')} testId="orch-discover-identity">
- {identityLoading ? (
- <CenteredLoadingState label={t('tinyplaceOrchestration.identity.loading')} />
- ) : identity ? (
- <div className="space-y-2 text-sm">
- <div className="flex items-center gap-2">
- <span
- className={`rounded-full px-2 py-0.5 text-xs font-medium ${
- discoverable
- ? 'bg-sage-100 text-sage-700 dark:bg-sage-500/15 dark:text-sage-300'
- : 'bg-amber-100 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300'
- }`}
- data-testid="orch-discover-discoverable">
- {discoverable
- ? t('tinyplaceOrchestration.identity.discoverable')
- : t('tinyplaceOrchestration.identity.undiscoverable')}
- </span>
- {relay && (
- <span className="text-xs text-content-faint">
- {relay.network === 'prod'
- ? t('tinyplaceOrchestration.relay.prod')
- : t('tinyplaceOrchestration.relay.staging')}
- </span>
- )}
- </div>
- <p className="text-content-secondary">
- {identity.primaryHandle
- ? `@${identity.primaryHandle.replace(/^@+/, '')}`
- : t('tinyplaceOrchestration.identity.noHandle')}
- </p>
- {!discoverable && (
- <p className="text-xs text-content-muted" data-testid="orch-discover-guide">
- {t('orchPage.discover.notDiscoverableGuide')}
- </p>
- )}
- </div>
- ) : (
- <p className="text-sm text-content-muted">
- {t('tinyplaceOrchestration.identity.noHandle')}
- </p>
- )}
- </SectionCard>
-
- {/* Link a new agent. */}
- <SectionCard
- title={t('orchPage.discover.linkTitle')}
- description={t('orchPage.discover.linkDescription')}
- testId="orch-discover-link">
- <form className="flex gap-2" onSubmit={submitLink}>
- <TextField
- value={linkAgentId}
- onChange={e => setLinkAgentId(e.target.value)}
- placeholder={t('tinyplaceOrchestration.pairing.linkPlaceholder')}
- className="min-w-0 flex-1"
- data-testid="orch-discover-link-input"
- />
- <Button
- type="submit"
- variant="primary"
- size="sm"
- disabled={!linkAgentId.trim() || pendingAction === `link:${linkAgentId.trim()}`}
- data-testid="orch-discover-link-submit">
- {t('tinyplaceOrchestration.pairing.linkAction')}
- </Button>
- </form>
- {actionError && (
- <p className="mt-2 text-xs text-coral-600 dark:text-coral-300">{actionError}</p>
- )}
- </SectionCard>
-
- {/* Inbound requests. */}
- <SectionCard
- title={t('tinyplaceOrchestration.pairing.requests')}
- testId="orch-discover-requests">
- {state.status === 'loading' ? (
- <CenteredLoadingState label={t('tinyplaceOrchestration.loading')} />
- ) : incoming.length === 0 ? (
- <p className="py-2 text-sm text-content-muted" data-testid="orch-discover-no-requests">
- {t('orchPage.discover.noRequests')}
- </p>
- ) : (
- <ul className="divide-y divide-line">
- {incoming.map(request => {
- const address = contactAddress(request);
- const handle = handles[address];
- return (
- <li
- key={address}
- className="flex items-center justify-between gap-3 py-2.5"
- data-testid="orch-discover-request-row">
- <div className="min-w-0">
- <p className="truncate text-sm font-medium text-content">
- {handle ? `@${handle}` : t('tinyplaceOrchestration.unknownSender')}
- </p>
- <p className="truncate font-mono text-[11px] text-content-faint">{address}</p>
- </div>
- <div className="flex shrink-0 gap-1.5">
- <Button
- variant="primary"
- size="sm"
- disabled={pendingAction === `accept:${address}`}
- onClick={() =>
- void runAction(`accept:${address}`, () =>
- apiClient.orchestrationPairing.acceptRequest(address)
- )
- }
- data-testid="orch-discover-accept">
- {t('tinyplaceOrchestration.pairing.accept')}
- </Button>
- <Button
- variant="tertiary"
- size="sm"
- disabled={pendingAction === `decline:${address}`}
- onClick={() =>
- void runAction(`decline:${address}`, () =>
- apiClient.orchestrationPairing.declineRequest(address)
- )
- }
- data-testid="orch-discover-decline">
- {t('tinyplaceOrchestration.pairing.decline')}
- </Button>
- </div>
- </li>
- );
- })}
- </ul>
- )}
- </SectionCard>
- </div>
- );
-}
diff --git a/app/src/components/orchestration/MedullaOverviewPanel.test.tsx b/app/src/components/orchestration/MedullaOverviewPanel.test.tsx
deleted file mode 100644
index 6f56fae920..0000000000
--- a/app/src/components/orchestration/MedullaOverviewPanel.test.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { DISCORD_INVITE_URL, PRICING_URL } from '../../utils/links';
-import MedullaOverviewPanel from './MedullaOverviewPanel';
-
-// Pass-through translator so assertions can target the i18n keys directly.
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (key: string) => key }) }));
-
-const openUrl = vi.fn();
-vi.mock('../../utils/openUrl', () => ({ openUrl: (url: string) => openUrl(url) }));
-
-describe('MedullaOverviewPanel', () => {
- it('renders the Medulla teaser copy and CTA', () => {
- render(<MedullaOverviewPanel />);
- expect(screen.getByTestId('orch-medulla')).toBeInTheDocument();
- expect(screen.getByText('orchPage.medulla.badge')).toBeInTheDocument();
- expect(screen.getByText('orchPage.medulla.title')).toBeInTheDocument();
- expect(screen.getByText('orchPage.medulla.body')).toBeInTheDocument();
- expect(screen.getByText('orchPage.medulla.subscriberNote')).toBeInTheDocument();
- expect(screen.getByTestId('orch-medulla-subscribe')).toBeInTheDocument();
- expect(screen.getByTestId('orch-medulla-discord')).toBeInTheDocument();
- });
-
- it('opens the Discord invite when the CTA is clicked', () => {
- render(<MedullaOverviewPanel />);
- fireEvent.click(screen.getByTestId('orch-medulla-discord'));
- expect(openUrl).toHaveBeenCalledWith(DISCORD_INVITE_URL);
- });
-
- it('opens the billing dashboard when the subscription CTA is clicked', () => {
- render(<MedullaOverviewPanel />);
- fireEvent.click(screen.getByTestId('orch-medulla-subscribe'));
- expect(openUrl).toHaveBeenCalledWith(PRICING_URL);
- });
-});
diff --git a/app/src/components/orchestration/MedullaOverviewPanel.tsx b/app/src/components/orchestration/MedullaOverviewPanel.tsx
deleted file mode 100644
index 4d70eb6554..0000000000
--- a/app/src/components/orchestration/MedullaOverviewPanel.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-/**
- * MedullaOverviewPanel — the landing "Overview" for the Orchestration page.
- *
- * A teaser for **Medulla**, OpenHuman's custom-built LLM designed specifically
- * to orchestrate thousands of agents at once. It is not shipped yet; this page
- * announces it and points early-access seekers at the Discord. OpenHuman
- * subscribers get early access to the model and the orchestration engine.
- *
- * Pure marketing surface — no core RPC, no live state. Product/brand names
- * ("Medulla", "OpenHuman", "Discord") stay in every locale.
- */
-import { useT } from '../../lib/i18n/I18nContext';
-import { DISCORD_INVITE_URL, PRICING_URL } from '../../utils/links';
-import { openUrl } from '../../utils/openUrl';
-import Button from '../ui/Button';
-
-export default function MedullaOverviewPanel() {
- const { t } = useT();
-
- return (
- <div className="h-full overflow-y-auto" data-testid="orch-medulla">
- <div className="mx-auto flex min-h-full w-full max-w-2xl flex-col items-center justify-center px-6 py-12 text-center">
- {/* Coming-soon badge */}
- <span className="mb-6 inline-flex items-center gap-1.5 rounded-full border border-primary-200 bg-primary-50 px-3 py-1 text-[11px] font-semibold uppercase tracking-wider text-primary-700 dark:border-primary-500/30 dark:bg-primary-500/10 dark:text-primary-300">
- <span className="h-1.5 w-1.5 rounded-full bg-primary-500" aria-hidden="true" />
- {t('orchPage.medulla.badge')}
- </span>
-
- {/* Wordmark */}
- <h1 className="bg-linear-to-r from-primary-500 to-primary-700 bg-clip-text text-5xl font-bold tracking-tight text-transparent dark:from-primary-300 dark:to-primary-500">
- {t('orchPage.medulla.title')}
- </h1>
- <p className="mt-2 text-base font-medium text-content-secondary">
- {t('orchPage.medulla.tagline')}
- </p>
-
- {/* Lead paragraph */}
- <p className="mt-6 max-w-xl text-sm leading-relaxed text-content-muted">
- {t('orchPage.medulla.body')}
- </p>
-
- {/* Feature highlights */}
- <div className="mt-6 flex flex-wrap items-center justify-center gap-2">
- {[
- { emoji: '🤖', label: t('orchPage.medulla.featAgents') },
- { emoji: '🧠', label: t('orchPage.medulla.featContext') },
- { emoji: '⚡', label: t('orchPage.medulla.featCost') },
- ].map(feat => (
- <span
- key={feat.label}
- className="inline-flex items-center gap-1.5 rounded-full border border-line bg-surface px-3 py-1 text-xs font-medium text-content-secondary shadow-soft">
- <span aria-hidden="true">{feat.emoji}</span>
- {feat.label}
- </span>
- ))}
- </div>
-
- {/* Two early-access cards: OpenHuman subscribers · the Discord. */}
- <div className="mt-8 grid w-full max-w-xl grid-cols-1 gap-3 text-left sm:grid-cols-2">
- {/* Subscribers */}
- <div className="flex flex-col rounded-2xl border border-line bg-surface p-4 shadow-soft">
- <span
- className="mb-3 flex h-9 w-9 items-center justify-center rounded-full bg-primary-50 text-primary-600 dark:bg-primary-500/10 dark:text-primary-300"
- aria-hidden="true">
- <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M13 10V3L4 14h7v7l9-11h-7z"
- />
- </svg>
- </span>
- <h3 className="text-sm font-semibold text-content">
- {t('orchPage.medulla.subscriberTitle')}
- </h3>
- <p className="mt-1 text-xs leading-relaxed text-content-muted">
- {t('orchPage.medulla.subscriberNote')}
- </p>
- <Button
- variant="primary"
- size="sm"
- data-testid="orch-medulla-subscribe"
- onClick={() => void openUrl(PRICING_URL)}
- className="mt-auto w-full rounded-xl px-4 text-xs font-semibold shadow-soft">
- {t('orchPage.medulla.subscriberCta')}
- </Button>
- </div>
-
- {/* Discord */}
- <div className="flex flex-col rounded-2xl border border-line bg-surface p-4 shadow-soft">
- <span
- className="mb-3 flex h-9 w-9 items-center justify-center rounded-full bg-primary-50 text-primary-600 dark:bg-primary-500/10 dark:text-primary-300"
- aria-hidden="true">
- <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 24 24">
- <path d="M20.317 4.369a19.79 19.79 0 00-4.885-1.515.074.074 0 00-.079.037c-.211.375-.445.865-.608 1.25a18.27 18.27 0 00-5.487 0 12.64 12.64 0 00-.617-1.25.077.077 0 00-.079-.037A19.736 19.736 0 003.677 4.37a.07.07 0 00-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 00.031.057 19.9 19.9 0 005.993 3.03.078.078 0 00.084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 00-.041-.106 13.107 13.107 0 01-1.872-.892.077.077 0 01-.008-.128c.126-.094.252-.192.372-.291a.074.074 0 01.077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 01.078.009c.12.099.246.198.373.292a.077.077 0 01-.006.127 12.3 12.3 0 01-1.873.892.077.077 0 00-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 00.084.028 19.839 19.839 0 006.002-3.03.077.077 0 00.032-.056c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 00-.031-.028zM8.02 15.331c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z" />
- </svg>
- </span>
- <h3 className="text-sm font-semibold text-content">
- {t('orchPage.medulla.discordTitle')}
- </h3>
- <p className="mt-1 text-xs leading-relaxed text-content-muted">
- {t('orchPage.medulla.earlyAccess')}
- </p>
- <Button
- variant="primary"
- size="sm"
- data-testid="orch-medulla-discord"
- onClick={() => void openUrl(DISCORD_INVITE_URL)}
- className="mt-auto w-full rounded-xl px-4 text-xs font-semibold shadow-soft">
- {t('orchPage.medulla.cta')}
- </Button>
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/app/src/components/orchestration/OrchestrationView.tsx b/app/src/components/orchestration/OrchestrationView.tsx
deleted file mode 100644
index c0a02366a4..0000000000
--- a/app/src/components/orchestration/OrchestrationView.tsx
+++ /dev/null
@@ -1,250 +0,0 @@
-/**
- * OrchestrationView — the TinyPlace multi-agent orchestration surface, embedded
- * as the Brain page's **Orchestration** sub-tab (`/brain?tab=orchestration`).
- *
- * It was previously a first-class sidebar destination (`/orchestration`) with
- * its own projected sidebar. Folding it back under Brain means the top-level
- * views — **Overview** (Medulla), **Chat**, **Agent graph**, **Tasks**,
- * **Network** — become an in-content chip row instead of a left rail, so Brain
- * keeps a single sidebar. State travels in query params that don't collide with
- * Brain's own `?tab=`:
- *
- * - `?ov=` — the orchestration view (medulla | agent | overview | tasks | network)
- * - `?sub=` — the network sub-view (connections | discover | usage)
- * - `?session=` — the open peer session (read by {@link AgentChatPanel})
- *
- * The live list of active peer sessions (the old sidebar "Active sub-agents"
- * rail) moves into the **Chat** view as a left column, since clicking a session
- * opens it in that chat anyway.
- */
-import { useCallback, useMemo } from 'react';
-import { useLocation, useNavigate } from 'react-router-dom';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import { useMedullaAccess } from '../../lib/orchestration/useMedullaAccess';
-import { useContactSessions } from '../../lib/orchestration/useOrchestrationSessions';
-import ChipTabs from '../layout/ChipTabs';
-import PageSectionHeader from '../layout/PageSectionHeader';
-import PanelPage from '../layout/PanelPage';
-import ActiveSubagentsRail from './ActiveSubagentsRail';
-import AgentChatPanel from './AgentChatPanel';
-import ConnectionsPanel from './ConnectionsPanel';
-import MedullaDemoChat from './demo/MedullaDemoChat';
-import MedullaDemoGraph from './demo/MedullaDemoGraph';
-import MedullaDemoNetwork from './demo/MedullaDemoNetwork';
-import DiscoverPanel from './DiscoverPanel';
-import MedullaOverviewPanel from './MedullaOverviewPanel';
-import OrchestratorTaskBoard from './OrchestratorTaskBoard';
-import OverviewPanel from './OverviewPanel';
-import UsagePanel from './UsagePanel';
-
-type OrchestrationTab = 'medulla' | 'overview' | 'agent' | 'tasks' | 'network';
-type NetworkSub = 'connections' | 'discover' | 'usage';
-
-const ORCH_TABS: readonly OrchestrationTab[] = ['medulla', 'agent', 'overview', 'tasks', 'network'];
-const NETWORK_SUBS: readonly NetworkSub[] = ['connections', 'discover', 'usage'];
-
-export default function OrchestrationView() {
- const { t } = useT();
- const location = useLocation();
- const navigate = useNavigate();
- const contactSessions = useContactSessions();
- // Without Medulla access, Medulla-specific live surfaces are replaced by a
- // scale showcase. The global task board remains available to every user.
- const hasMedullaAccess = useMedullaAccess();
-
- const params = useMemo(() => new URLSearchParams(location.search), [location.search]);
- const rawOv = params.get('ov');
- const rawSub = params.get('sub');
-
- // Default landing is the Medulla overview (the orchestration overview page).
- const activeTab: OrchestrationTab = (ORCH_TABS as readonly string[]).includes(rawOv ?? '')
- ? (rawOv as OrchestrationTab)
- : 'medulla';
-
- const networkSub: NetworkSub = NETWORK_SUBS.includes(rawSub as NetworkSub)
- ? (rawSub as NetworkSub)
- : 'connections';
-
- const openSessionId = params.get('session');
-
- const updateParams = useCallback(
- (mut: (p: URLSearchParams) => void) => {
- const next = new URLSearchParams(location.search);
- mut(next);
- navigate({ pathname: location.pathname, search: `?${next.toString()}` });
- },
- [location.pathname, location.search, navigate]
- );
-
- const setActiveTab = useCallback(
- (tab: OrchestrationTab) => {
- updateParams(p => {
- // Preserve the hosting Brain sub-tab; only the orchestration view moves.
- p.set('tab', 'orchestration');
- p.set('ov', tab);
- // Selecting Chat returns to the master chat — drop any open session so
- // the session subpage closes (there's no in-view back button).
- if (tab === 'agent') p.delete('session');
- // Landing on the network page needs a valid sub selected.
- if (tab === 'network' && !NETWORK_SUBS.includes(p.get('sub') as NetworkSub)) {
- p.set('sub', 'connections');
- }
- });
- },
- [updateParams]
- );
-
- const setNetworkSub = useCallback(
- (sub: NetworkSub) => {
- updateParams(p => {
- p.set('tab', 'orchestration');
- p.set('ov', 'network');
- p.set('sub', sub);
- });
- },
- [updateParams]
- );
-
- // Open (or close, when null) a peer session in the agent chat. Always lands on
- // the agent tab so the session's transcript is actually visible.
- const setOpenSessionId = useCallback(
- (sessionId: string | null) => {
- updateParams(p => {
- p.set('tab', 'orchestration');
- p.set('ov', 'agent');
- if (sessionId) p.set('session', sessionId);
- else p.delete('session');
- });
- },
- [updateParams]
- );
-
- console.debug(
- '[orchestration] view mount ov=%s sub=%s session=%s medullaAccess=%s',
- activeTab,
- networkSub,
- openSessionId,
- hasMedullaAccess
- );
-
- const chipItems = useMemo(
- () => [
- { id: 'medulla' as const, label: t('orchPage.medulla.nav') },
- { id: 'agent' as const, label: t('orchPage.agent.nav') },
- { id: 'overview' as const, label: t('orchPage.overview.nav') },
- { id: 'tasks' as const, label: t('orchPage.tasks.nav') },
- { id: 'network' as const, label: t('orchPage.group.network') },
- ],
- [t]
- );
-
- return (
- <div className="flex h-full flex-col">
- {/* Top-level view switcher — the old sidebar rail, folded into an in-content
- chip row so Brain keeps a single sidebar. */}
- <div className="shrink-0 border-b border-line-subtle">
- <ChipTabs<OrchestrationTab>
- as="tab"
- ariaLabel={t('nav.orchestration')}
- testIdPrefix="orch-view"
- items={chipItems}
- value={activeTab}
- onChange={setActiveTab}
- />
- </div>
-
- <div className="min-h-0 flex-1">
- {activeTab === 'medulla' ? (
- // Orchestration overview — the Medulla teaser / early-access landing.
- <MedullaOverviewPanel />
- ) : activeTab === 'overview' ? (
- // Interactive graph of the agent / sub-agent system — or the scale
- // showcase (core → 2 devices → 120 agents) without Medulla access.
- hasMedullaAccess ? (
- <OverviewPanel />
- ) : (
- <MedullaDemoGraph />
- )
- ) : activeTab === 'agent' ? (
- // Full-bleed so it reads exactly like the normal chat page — or a
- // read-only demo conversation (composer disabled) without Medulla
- // access. The active peer-session list sits in a left column (moved
- // from the former sidebar rail) when there are live sessions.
- hasMedullaAccess ? (
- <div className="flex h-full">
- {contactSessions.byContact.size > 0 ? (
- <aside className="hidden w-60 shrink-0 overflow-y-auto border-r border-line-subtle px-1.5 py-2 lg:block">
- <ActiveSubagentsRail
- byContact={contactSessions.byContact}
- openSessionId={openSessionId}
- isAgentTab={true}
- onOpenSession={setOpenSessionId}
- />
- </aside>
- ) : null}
- <div className="min-w-0 flex-1">
- <AgentChatPanel openSessionId={openSessionId} onOpenSession={setOpenSessionId} />
- </div>
- </div>
- ) : (
- <MedullaDemoChat />
- )
- ) : activeTab === 'tasks' ? (
- // One global Kanban board owned by the orchestrator (not per-thread).
- // Tasks predate Medulla access and must remain usable without it.
- // `width="lg"` is the contentWidth scale's max-w-3xl: the scaffold
- // owns the centred column now, so there is no hand-picked cap here.
- <PanelPage width="lg" contentClassName="p-4">
- <div className="animate-fade-up space-y-4">
- <PageSectionHeader
- title={t('orchPage.tasks.nav')}
- description={t('orchPage.tasks.subtitle')}
- />
- <OrchestratorTaskBoard />
- </div>
- </PanelPage>
- ) : hasMedullaAccess ? (
- /* Network: one page with a Brain-style chip sub-nav (flush pills, no
- header background) over connections/discover/usage, aligned to the
- same content column. `width="lg"` supplies that column — it used to
- be a hand-picked `max-w-3xl` nested inside an identical one. */
- <PanelPage width="lg" contentClassName="p-4">
- <div className="space-y-5 animate-fade-up">
- <PageSectionHeader
- title={t('orchPage.group.network')}
- description={t('orchPage.network.desc')}
- tabs={
- <ChipTabs<NetworkSub>
- as="tab"
- ariaLabel={t('orchPage.group.network')}
- testIdPrefix="orch-network"
- className="inline-flex flex-wrap items-center gap-1.5"
- items={[
- { id: 'connections', label: t('orchPage.connections.nav') },
- { id: 'discover', label: t('orchPage.discover.nav') },
- { id: 'usage', label: t('orchPage.usage.nav') },
- ]}
- value={networkSub}
- onChange={setNetworkSub}
- />
- }
- />
- {networkSub === 'connections' && (
- <ConnectionsPanel
- onDiscover={() => setNetworkSub('discover')}
- onInitializeAgent={() => setActiveTab('agent')}
- />
- )}
- {networkSub === 'discover' && <DiscoverPanel />}
- {networkSub === 'usage' && <UsagePanel />}
- </div>
- </PanelPage>
- ) : (
- // Scale showcase: fake peer-agent mesh with the preview banner.
- <MedullaDemoNetwork />
- )}
- </div>
- </div>
- );
-}
diff --git a/app/src/components/orchestration/OrchestratorTaskBoard.test.tsx b/app/src/components/orchestration/OrchestratorTaskBoard.test.tsx
deleted file mode 100644
index 3d1de499a1..0000000000
--- a/app/src/components/orchestration/OrchestratorTaskBoard.test.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import OrchestratorTaskBoard from './OrchestratorTaskBoard';
-
-// Pass-through translator so assertions can target the i18n keys directly.
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (key: string) => key }) }));
-
-const EMPTY = { threadId: 'orchestrator-tasks', cards: [], updatedAt: '' };
-const list = vi.fn(async () => EMPTY);
-const add = vi.fn(async () => EMPTY);
-
-vi.mock('../../services/api/todosApi', () => ({
- ORCHESTRATOR_TASKS_THREAD_ID: 'orchestrator-tasks',
- todosApi: {
- list: (...args: unknown[]) => list(...(args as [])),
- add: (...args: unknown[]) => add(...(args as [])),
- edit: vi.fn(),
- remove: vi.fn(),
- updateStatus: vi.fn(),
- },
-}));
-
-vi.mock('../../features/conversations/components/TaskKanbanBoard', () => ({
- TaskKanbanBoard: () => <div data-testid="kanban" />,
-}));
-
-describe('OrchestratorTaskBoard', () => {
- it('adds a task through the migrated TextField composer', async () => {
- render(<OrchestratorTaskBoard />);
- await waitFor(() => expect(list).toHaveBeenCalled());
-
- const input = screen.getByTestId('orch-task-add-input');
- const submit = screen.getByTestId('orch-task-add-submit');
-
- // Empty draft keeps the submit disabled.
- expect(submit).toBeDisabled();
-
- fireEvent.change(input, { target: { value: 'Ship the rail' } });
- expect(submit).not.toBeDisabled();
-
- fireEvent.click(submit);
- await waitFor(() =>
- expect(add).toHaveBeenCalledWith({ threadId: 'orchestrator-tasks', content: 'Ship the rail' })
- );
- await waitFor(() => expect((input as HTMLInputElement).value).toBe(''));
- });
-});
diff --git a/app/src/components/orchestration/OrchestratorTaskBoard.tsx b/app/src/components/orchestration/OrchestratorTaskBoard.tsx
deleted file mode 100644
index 5ccecc0198..0000000000
--- a/app/src/components/orchestration/OrchestratorTaskBoard.tsx
+++ /dev/null
@@ -1,191 +0,0 @@
-/**
- * OrchestratorTaskBoard — the orchestrator's single, app-wide Kanban board.
- *
- * One global board (keyed by {@link ORCHESTRATOR_TASKS_THREAD_ID}) that the
- * orchestrator owns and the user can edit. Deliberately NOT per-thread: thread-
- * scoped to-dos / goals live under Tiny Agents, so this surface shows exactly
- * one board — no aggregation of agent/thread boards.
- *
- * Fully editable via the `todos_*` RPC (each mutation returns the fresh board,
- * which we set directly). Renders the shared {@link TaskKanbanBoard}.
- */
-import debugFactory from 'debug';
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-import {
- type ColumnDef,
- TaskKanbanBoard,
-} from '../../features/conversations/components/TaskKanbanBoard';
-import { useT } from '../../lib/i18n/I18nContext';
-import { ORCHESTRATOR_TASKS_THREAD_ID, todosApi } from '../../services/api/todosApi';
-import type { TaskBoard, TaskBoardCard, TaskBoardCardStatus } from '../../types/turnState';
-import { Alert, AlertDescription } from '../ui';
-import Button from '../ui/Button';
-import TextField from '../ui/TextField';
-
-const debug = debugFactory('orchestration:task-board');
-
-const EMPTY_BOARD: TaskBoard = { threadId: ORCHESTRATOR_TASKS_THREAD_ID, cards: [], updatedAt: '' };
-
-/** The orchestrator board is a simple 4-column board. */
-const ORCHESTRATOR_COLUMNS: ColumnDef[] = [
- { status: 'todo', labelKey: 'orchPage.tasks.colPending' },
- { status: 'in_progress', labelKey: 'orchPage.tasks.colActive' },
- { status: 'blocked', labelKey: 'orchPage.tasks.colBlocked' },
- { status: 'done', labelKey: 'orchPage.tasks.colCompleted' },
-];
-
-export default function OrchestratorTaskBoard() {
- const { t } = useT();
- const [board, setBoard] = useState<TaskBoard | null>(null);
- const [error, setError] = useState<string | null>(null);
- const [draft, setDraft] = useState('');
- const [adding, setAdding] = useState(false);
- const [mutatingCardId, setMutatingCardId] = useState<string | null>(null);
- const mountedRef = useRef(true);
- useEffect(() => {
- mountedRef.current = true;
- return () => {
- mountedRef.current = false;
- };
- }, []);
-
- const load = useCallback(async () => {
- try {
- const next = await todosApi.list(ORCHESTRATOR_TASKS_THREAD_ID);
- if (!mountedRef.current) return;
- setBoard(next);
- setError(null);
- } catch (err) {
- debug('load failed: %o', err);
- if (!mountedRef.current) return;
- setError(err instanceof Error ? err.message : String(err));
- setBoard(prev => prev ?? EMPTY_BOARD);
- }
- }, []);
-
- useEffect(() => {
- void load();
- }, [load]);
-
- // Every todos_* mutation returns the fresh board — apply it directly.
- const runMutation = useCallback(async (cardId: string | null, op: () => Promise<TaskBoard>) => {
- setMutatingCardId(cardId);
- setError(null);
- try {
- const next = await op();
- if (mountedRef.current) setBoard(next);
- } catch (err) {
- debug('mutation failed card=%s: %o', cardId, err);
- if (mountedRef.current) setError(err instanceof Error ? err.message : String(err));
- } finally {
- if (mountedRef.current) setMutatingCardId(null);
- }
- }, []);
-
- const handleAdd = useCallback(async () => {
- const content = draft.trim();
- if (!content || adding) return;
- setAdding(true);
- setError(null);
- try {
- const next = await todosApi.add({ threadId: ORCHESTRATOR_TASKS_THREAD_ID, content });
- if (!mountedRef.current) return;
- setBoard(next);
- setDraft('');
- } catch (err) {
- debug('add failed: %o', err);
- if (mountedRef.current) setError(err instanceof Error ? err.message : String(err));
- } finally {
- if (mountedRef.current) setAdding(false);
- }
- }, [draft, adding]);
-
- const handleMove = useCallback(
- (card: TaskBoardCard, status: TaskBoardCardStatus) => {
- void runMutation(card.id, () =>
- todosApi.updateStatus(ORCHESTRATOR_TASKS_THREAD_ID, card.id, status)
- );
- },
- [runMutation]
- );
-
- const handleUpdate = useCallback(
- (card: TaskBoardCard, nextCard: TaskBoardCard) => {
- void runMutation(card.id, () =>
- todosApi.edit({
- threadId: ORCHESTRATOR_TASKS_THREAD_ID,
- id: card.id,
- content: nextCard.title,
- status: nextCard.status,
- objective: nextCard.objective ?? null,
- notes: nextCard.notes ?? null,
- blocker: nextCard.blocker ?? null,
- assignedAgent: nextCard.assignedAgent ?? null,
- approvalMode: nextCard.approvalMode ?? null,
- plan: nextCard.plan ?? [],
- allowedTools: nextCard.allowedTools ?? [],
- acceptanceCriteria: nextCard.acceptanceCriteria ?? [],
- evidence: nextCard.evidence ?? [],
- })
- );
- },
- [runMutation]
- );
-
- const handleDelete = useCallback(
- (card: TaskBoardCard) => {
- void runMutation(card.id, () => todosApi.remove(ORCHESTRATOR_TASKS_THREAD_ID, card.id));
- },
- [runMutation]
- );
-
- return (
- // No heading here: the only host (`OrchestrationView`) renders a
- // `PageSectionHeader` with these exact two keys directly above this board,
- // so an h2 of its own stacked the same title twice.
- <div className="space-y-4" data-testid="orch-task-board">
- {error ? (
- <Alert variant="destructive" density="compact" className="items-center justify-between">
- <AlertDescription className="min-w-0 truncate">{error}</AlertDescription>
- <Button variant="secondary" size="sm" onClick={() => void load()}>
- {t('common.retry')}
- </Button>
- </Alert>
- ) : null}
-
- <form
- className="flex gap-2"
- onSubmit={event => {
- event.preventDefault();
- void handleAdd();
- }}>
- <TextField
- value={draft}
- onChange={event => setDraft(event.target.value)}
- placeholder={t('subconscious.addTaskPlaceholder')}
- data-testid="orch-task-add-input"
- className="min-w-0 flex-1"
- />
- <Button
- type="submit"
- variant="primary"
- size="sm"
- data-testid="orch-task-add-submit"
- disabled={!draft.trim() || adding}>
- {t('common.add')}
- </Button>
- </form>
-
- <TaskKanbanBoard
- board={board ?? EMPTY_BOARD}
- columns={ORCHESTRATOR_COLUMNS}
- onMove={handleMove}
- onUpdateCard={handleUpdate}
- onDeleteCard={handleDelete}
- mutatingCardId={mutatingCardId}
- hideHeader
- />
- </div>
- );
-}
diff --git a/app/src/components/orchestration/OverviewPanel.tsx b/app/src/components/orchestration/OverviewPanel.tsx
deleted file mode 100644
index b99171223d..0000000000
--- a/app/src/components/orchestration/OverviewPanel.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- * OverviewPanel — an interactive "Agent graph" of the agent / sub-agent system,
- * reusing the Brain's {@link MemoryGraph} (drag / pan / zoom, WebGL with SVG
- * fallback), full-screen and fit-to-bounds.
- *
- * Three tiers fan out from a central **agent core** hub:
- * - core (the synthetic root)
- * - **agents** — every accepted peer contact (`source` nodes). Offline agents
- * (no live session) render in a dead/grey colour.
- * - **sub-agents** — the sessions running under each agent (`chunk` nodes),
- * linked to their agent by explicit edges; disconnected ones also greyed.
- *
- * Contacts come from {@link usePairing} (so offline agents with no sessions
- * still appear); sessions come from {@link useContactSessions}.
- */
-import { useMemo } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type { SessionSummary } from '../../lib/orchestration/orchestrationClient';
-import { useContactSessions } from '../../lib/orchestration/useOrchestrationSessions';
-import { usePairing } from '../../lib/orchestration/usePairing';
-import type { GraphEdge, GraphNode } from '../../utils/tauriCommands';
-import { MemoryGraph } from '../intelligence/MemoryGraph';
-import { contactAddress } from '../intelligence/orchestrationTabHelpers';
-
-/** Muted grey for offline agents / disconnected sub-agents. */
-const OFFLINE_COLOR = '#6B7280';
-
-function shortAddress(address: string): string {
- return address.length <= 14 ? address : `${address.slice(0, 6)}…${address.slice(-4)}`;
-}
-
-function sessionLabel(session: SessionSummary): string {
- return session.label?.trim() || session.sessionId;
-}
-
-/**
- * A session/agent is "connected" when the core reports live peer presence; when
- * presence is unknown, fall back to the recency heuristic (active / running /
- * awaiting input).
- */
-function isConnected(session: SessionSummary): boolean {
- if (session.peerOnline === true) return true;
- if (session.peerOnline === false) return false;
- return session.active || session.status === 'running' || session.status === 'waiting-approval';
-}
-
-export default function OverviewPanel() {
- const { t } = useT();
- const { byContact } = useContactSessions();
- const pairing = usePairing();
-
- const { nodes, edges } = useMemo(() => {
- const nodes: GraphNode[] = [];
- const edges: GraphEdge[] = [];
-
- // Every accepted contact is an agent — including offline ones with no
- // sessions — unioned with any address that has live sessions.
- const accepted =
- pairing.state.status === 'ok'
- ? pairing.state.snapshot.contacts.contacts.filter(c => c.status === 'accepted')
- : [];
- const addresses = new Set<string>();
- for (const c of accepted) {
- const addr = contactAddress(c);
- if (addr) addresses.add(addr);
- }
- for (const addr of byContact.keys()) addresses.add(addr);
-
- for (const address of addresses) {
- const sessions = byContact.get(address) ?? [];
- const online = sessions.some(isConnected);
- const instanceId = `inst:${address}`;
- nodes.push({
- kind: 'source',
- id: instanceId,
- label: shortAddress(address),
- ...(online ? {} : { color: OFFLINE_COLOR }),
- });
- for (const session of sessions) {
- const sessionNodeId = `sess:${session.sessionId}`;
- nodes.push({
- kind: 'chunk',
- id: sessionNodeId,
- label: sessionLabel(session),
- ...(isConnected(session) ? {} : { color: OFFLINE_COLOR }),
- });
- edges.push({ from: sessionNodeId, to: instanceId });
- }
- }
- return { nodes, edges };
- }, [byContact, pairing.state]);
-
- return (
- // Full-screen: the graph fills the whole pane (no card gutter) and fits the
- // whole agent/sub-agent cloud tightly to the viewport.
- <div className="h-full p-2" data-testid="orch-overview">
- <MemoryGraph
- nodes={nodes}
- edges={edges}
- mode="contacts"
- rootLabel={t('orchPage.overview.core')}
- emptyHint={t('orchPage.overview.empty')}
- fill
- fitToBounds
- showLabels
- />
- </div>
- );
-}
diff --git a/app/src/components/orchestration/SessionTranscript.tsx b/app/src/components/orchestration/SessionTranscript.tsx
deleted file mode 100644
index 44ea0bc365..0000000000
--- a/app/src/components/orchestration/SessionTranscript.tsx
+++ /dev/null
@@ -1,337 +0,0 @@
-/**
- * SessionTranscript — renders an orchestration session/chat transcript in the
- * app's normal chat-window visual language (right-aligned solid-primary user
- * bubbles, left neutral agent bubbles), with v2 harness activity woven in as
- * inline non-bubble blocks: merged tool call+result (red on failure), thinking,
- * error, and approval_request. Shared by the Agent chat pane and the Connections
- * session view so a session reads identically wherever it appears.
- *
- * Approvals are actionable only on your OWN agent (master/subconscious) — pass
- * `onDecide`. In a peer session omit it and the approval renders read-only.
- */
-import { type ReactElement, useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import { mergeToolActivity, type ToolActivity } from '../../lib/orchestration/mergeToolActivity';
-import type { ChatMessage } from '../../lib/orchestration/useOrchestrationChats';
-import { formatTime } from '../intelligence/orchestrationTabHelpers';
-import Button from '../ui/Button';
-
-type ApprovalDecision = 'approve' | 'deny' | 'always';
-
-interface SessionTranscriptProps {
- messages: ChatMessage[];
- /**
- * When present, approval rows show actionable Approve/Deny buttons wired to
- * this. May return a promise; the card rolls back to buttons if it rejects.
- */
- onDecide?: (message: ChatMessage, decision: ApprovalDecision) => void | Promise<unknown>;
- /**
- * Show the "Always allow" action. Off by default — only enable it where a
- * persistent always-allow is actually honored. A runtime that understands only
- * one-shot allow/deny must NOT offer it (it would silently be a one-time allow).
- */
- alwaysAllow?: boolean;
-}
-
-/**
- * Whether a row's `from` marks it as owner/user-authored (right-side bubble).
- * The composer's own reply is mirrored back with role `"owner"`; the master
- * optimistic append uses the localized "you". Both belong on the right.
- */
-function isOwnerAuthored(from: string): boolean {
- return from === 'you' || from === 'owner' || from === 'user';
-}
-
-/**
- * An approval decision (Approve/Deny) is sent to the runtime as a one-word reply
- * ("allow"/"deny"), which mirrors back as an owner bubble. The approval card
- * already resolves in place to show the outcome, so that echo bubble is pure
- * noise — suppress a standalone owner-authored decision word.
- */
-const DECISION_ECHO_RE = /^(allow|deny|approve|skip|always(\s+allow)?)$/i;
-function isDecisionEcho(message: ChatMessage): boolean {
- return (
- !message.eventKind &&
- isOwnerAuthored(message.from) &&
- DECISION_ECHO_RE.test(message.body.trim())
- );
-}
-
-/**
- * Derive each approval's outcome from the persisted message stream so a resolved
- * card survives a reload/remount (local click state alone is lost). Approvals and
- * their decision echoes alternate, so pair them FIFO in order of appearance.
- *
- * Returns the per-approval outcome AND the ids of the echo messages that were
- * actually paired to an approval — only THOSE are suppressed from the render. A
- * one-word "allow"/"deny" with no pending approval is a real chat reply and must
- * stay visible.
- */
-function deriveDecisions(messages: ChatMessage[]): {
- decided: Record<string, ApprovalDecision>;
- suppressed: Set<string>;
-} {
- const decided: Record<string, ApprovalDecision> = {};
- const suppressed = new Set<string>();
- const pending: string[] = [];
- for (const m of messages) {
- if (m.eventKind === 'approval_request') {
- pending.push(m.id);
- } else if (isDecisionEcho(m)) {
- const approvalId = pending.shift();
- if (approvalId) {
- decided[approvalId] = /^(deny|skip)/i.test(m.body.trim()) ? 'deny' : 'approve';
- suppressed.add(m.id);
- }
- }
- }
- return { decided, suppressed };
-}
-
-/** Lightweight `**bold**` rendering without pulling in a markdown lib. */
-function renderInline(text: string): (string | ReactElement)[] {
- return text.split(/(\*\*[^*]+\*\*)/g).map((part, i) =>
- part.startsWith('**') && part.endsWith('**') ? (
- <strong key={i} className="font-semibold">
- {part.slice(2, -2)}
- </strong>
- ) : (
- part
- )
- );
-}
-
-function UserBubble({ message }: { message: ChatMessage }): ReactElement {
- return (
- <div className="flex justify-end" data-event-kind="user_prompt">
- <div className="flex max-w-[75%] flex-col items-end gap-1">
- <div className="overflow-hidden wrap-break-word rounded-2xl rounded-br-md bg-primary-500 px-4 py-2.5 text-content-inverted">
- <p className="whitespace-pre-wrap text-sm leading-relaxed">{message.body}</p>
- </div>
- <span className="px-1 text-[10px] text-content-faint">{formatTime(message.timestamp)}</span>
- </div>
- </div>
- );
-}
-
-function AgentBubble({ message }: { message: ChatMessage }): ReactElement {
- return (
- <div className="flex justify-start" data-event-kind={message.eventKind ?? 'v1'}>
- <div className="flex max-w-[75%] flex-col items-start gap-1">
- <div className="rounded-2xl rounded-bl-md bg-surface-strong px-4 py-2.5 text-content dark:bg-surface-muted/80">
- <p className="whitespace-pre-wrap text-sm leading-relaxed">
- {renderInline(message.body)}
- </p>
- </div>
- <span className="px-1 text-[10px] text-content-faint">{formatTime(message.timestamp)}</span>
- </div>
- </div>
- );
-}
-
-function ThinkingRow({ message }: { message: ChatMessage }): ReactElement {
- return (
- <div className="flex justify-start" data-event-kind="agent_thinking">
- <div className="flex max-w-[75%] items-start gap-2 px-1 text-content-faint">
- <span className="mt-0.5 flex-none text-xs">∴</span>
- <p className="whitespace-pre-wrap text-xs italic leading-relaxed">{message.body}</p>
- </div>
- </div>
- );
-}
-
-function ErrorRow({ message }: { message: ChatMessage }): ReactElement {
- return (
- <div className="flex justify-start" data-event-kind="error">
- <div className="flex w-full max-w-[85%] items-start gap-2 rounded-xl border border-coral-200 bg-coral-50 px-3 py-2 dark:border-coral-500/30 dark:bg-coral-500/10">
- <span className="mt-0.5 flex-none text-xs text-coral-500">✕</span>
- <p className="whitespace-pre-wrap text-xs leading-relaxed text-coral-700 dark:text-coral-300">
- {message.body}
- </p>
- </div>
- </div>
- );
-}
-
-function ToolBlock({ tool }: { tool: ToolActivity }): ReactElement {
- return (
- <div className="flex justify-start" data-event-kind="tool_call" data-failed={tool.failed}>
- <div className="w-full max-w-[85%] overflow-hidden rounded-xl border border-line bg-surface-subtle">
- <div className="flex items-center gap-2 border-b border-line-subtle px-3 py-1.5">
- <span className="flex-none text-xs text-content-faint">▶</span>
- {tool.toolName ? (
- <span className="flex-none rounded bg-surface-strong px-1.5 py-0.5 font-mono text-[10px] font-medium text-content-secondary">
- {tool.toolName}
- </span>
- ) : null}
- <code className="min-w-0 flex-1 truncate font-mono text-[11px] text-content-muted">
- {tool.command}
- </code>
- </div>
- {tool.hasResult ? (
- <div
- className={`flex gap-2 px-3 py-2 ${tool.failed ? 'bg-coral-50 dark:bg-coral-500/10' : ''}`}>
- <span
- className={`mt-0.5 flex-none text-xs ${tool.failed ? 'text-coral-500' : 'text-sage-500'}`}
- aria-hidden>
- {tool.failed ? '✕' : '↳'}
- </span>
- <pre
- className={`min-w-0 flex-1 overflow-x-auto whitespace-pre-wrap font-mono text-[11px] leading-relaxed ${
- tool.failed ? 'text-coral-700 dark:text-coral-300' : 'text-content-muted'
- }`}>
- {tool.output}
- </pre>
- </div>
- ) : null}
- </div>
- </div>
- );
-}
-
-function ApprovalRow({
- message,
- onDecide,
- decided,
- allowAlways,
-}: {
- message: ChatMessage;
- onDecide?: (message: ChatMessage, decision: ApprovalDecision) => void;
- /** Once decided, the card resolves in place: buttons are replaced by the outcome. */
- decided?: ApprovalDecision;
- /** Whether to render the "Always allow" action (only where it's honored). */
- allowAlways?: boolean;
-}): ReactElement {
- const { t } = useT();
- const denied = decided === 'deny';
- return (
- <div className="flex justify-start" data-event-kind="approval_request">
- <div
- className={`w-full max-w-[85%] rounded-xl border px-3 py-2.5 ${
- decided
- ? 'border-line bg-surface/60 dark:bg-surface-canvas/20'
- : 'border-amber-300 bg-amber-50 dark:border-amber-500/40 dark:bg-amber-500/10'
- }`}>
- <div className="flex items-center gap-2">
- <span className={`text-sm ${decided ? 'text-content-faint' : 'text-amber-500'}`}>⚠</span>
- <span
- className={`text-xs font-semibold ${
- decided ? 'text-content-faint' : 'text-amber-700 dark:text-amber-300'
- }`}>
- {t('chat.approval.title')}
- </span>
- {message.toolName ? (
- <span className="rounded bg-amber-100 px-1.5 py-0.5 font-mono text-[10px] text-amber-700 dark:bg-amber-500/20 dark:text-amber-200">
- {message.toolName}
- </span>
- ) : null}
- </div>
- <code className="mt-1.5 block overflow-x-auto whitespace-pre-wrap wrap-break-word font-mono text-[11px] text-content-secondary">
- {message.body}
- </code>
- {decided ? (
- // Resolved in place — no more actions, just the outcome.
- <div
- className={`mt-2.5 flex items-center gap-1.5 text-xs font-semibold ${
- denied ? 'text-coral-600 dark:text-coral-400' : 'text-sage-600 dark:text-sage-400'
- }`}
- data-testid="approval-resolved">
- <span>{denied ? '✕' : '✓'}</span>
- <span>{denied ? t('chat.approval.deny') : t('chat.approval.approve')}</span>
- </div>
- ) : onDecide ? (
- <div className="mt-2.5 flex gap-2">
- <Button
- variant="primary"
- size="xs"
- onClick={() => onDecide(message, 'approve')}
- className="rounded-lg bg-amber-500 px-3 font-semibold text-content-inverted hover:bg-amber-600 active:bg-amber-700 focus-visible:ring-amber-500/25 dark:hover:bg-amber-600 dark:active:bg-amber-600">
- {t('chat.approval.approve')}
- </Button>
- <Button
- variant="secondary"
- size="xs"
- onClick={() => onDecide(message, 'deny')}
- className="rounded-lg border-line px-3 text-content-secondary">
- {t('chat.approval.deny')}
- </Button>
- {allowAlways ? (
- <Button
- variant="tertiary"
- size="xs"
- onClick={() => onDecide(message, 'always')}
- className="rounded-lg px-2 text-content-faint hover:bg-transparent hover:text-content-secondary">
- {t('chat.approval.alwaysAllow')}
- </Button>
- ) : null}
- </div>
- ) : null}
- </div>
- </div>
- );
-}
-
-export default function SessionTranscript({
- messages,
- onDecide,
- alwaysAllow = false,
-}: SessionTranscriptProps): ReactElement {
- // Persistent outcomes derived from the message stream (survive reload); only the
- // decision echoes actually paired to an approval are suppressed from the render.
- const { decided: derivedDecided, suppressed } = deriveDecisions(messages);
- const rows = mergeToolActivity(messages.filter(m => !suppressed.has(m.id)));
- // Local clicks give immediate feedback before the echo message arrives; they
- // layer on top of the derived (persisted) outcomes. Rolled back if the send
- // fails, so the buttons return for a retry.
- const [clicked, setClicked] = useState<Record<string, ApprovalDecision>>({});
- const rollback = (id: string): void =>
- setClicked(prev => {
- const next = { ...prev };
- delete next[id];
- return next;
- });
- const handleDecide = onDecide
- ? (message: ChatMessage, decision: ApprovalDecision): void => {
- setClicked(prev => ({ ...prev, [message.id]: decision }));
- Promise.resolve(onDecide(message, decision)).catch(() => rollback(message.id));
- }
- : undefined;
- const decidedFor = (id: string): ApprovalDecision | undefined =>
- clicked[id] ?? derivedDecided[id];
- return (
- <div className="space-y-3" data-testid="session-transcript">
- {rows.map((row, i) => {
- if (row.kind === 'tool') return <ToolBlock key={row.id} tool={row} />;
- const { message } = row;
- switch (message.eventKind) {
- case 'user_prompt':
- return <UserBubble key={message.id} message={message} />;
- case 'agent_thinking':
- return <ThinkingRow key={message.id} message={message} />;
- case 'error':
- return <ErrorRow key={message.id} message={message} />;
- case 'approval_request':
- return (
- <ApprovalRow
- key={message.id}
- message={message}
- onDecide={handleDecide}
- decided={decidedFor(message.id)}
- allowAlways={alwaysAllow}
- />
- );
- default:
- // agent_message + legacy v1 rows → bubble by sender. Owner/user-
- // authored rows (incl. a reply mirrored back with role "owner") sit
- // on the right; everything else is an agent bubble on the left.
- return isOwnerAuthored(message.from) ? (
- <UserBubble key={message.id} message={message} />
- ) : (
- <AgentBubble key={`${message.id}-${i}`} message={message} />
- );
- }
- })}
- </div>
- );
-}
diff --git a/app/src/components/orchestration/UsagePanel.tsx b/app/src/components/orchestration/UsagePanel.tsx
deleted file mode 100644
index bcfa0adaf9..0000000000
--- a/app/src/components/orchestration/UsagePanel.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-/**
- * UsagePanel — "stats on how much tokens, connections etc. have been spent".
- *
- * A read-only dashboard of the orchestration surface's footprint: credit
- * balance + cycle spend (billing), inference/integration call counts (team
- * usage), TokenJuice compaction savings, and the live connection count. Every
- * source is loaded independently (`Promise.allSettled`) so a single unavailable
- * backend (e.g. billing offline in a local build) degrades one tile to "—"
- * rather than blanking the page.
- */
-import debugFactory from 'debug';
-import { useEffect, useState } from 'react';
-
-import { apiClient } from '../../lib/agentworld/apiClient';
-import { useT } from '../../lib/i18n/I18nContext';
-import { type CreditBalance, creditsApi, type TeamUsage } from '../../services/api/creditsApi';
-import { getTokenjuiceSavings, type SavingsStats } from '../../utils/tauriCommands/tokenjuice';
-import { CenteredLoadingState } from '../ui';
-import { StatTile } from './primitives';
-
-const debug = debugFactory('orchestration:usage');
-
-function usd(value: number | undefined): string {
- if (value == null || !Number.isFinite(value)) return '—';
- return `$${value.toFixed(2)}`;
-}
-
-function count(value: number | undefined): string {
- if (value == null || !Number.isFinite(value)) return '—';
- return new Intl.NumberFormat().format(value);
-}
-
-interface UsageData {
- balance: CreditBalance | null;
- team: TeamUsage | null;
- savings: SavingsStats | null;
- connections: number | null;
-}
-
-export default function UsagePanel() {
- const { t } = useT();
- const [data, setData] = useState<UsageData | null>(null);
- const [loading, setLoading] = useState(true);
-
- useEffect(() => {
- let cancelled = false;
- debug('usage load: entry');
- void Promise.allSettled([
- creditsApi.getBalance(),
- creditsApi.getTeamUsage(),
- getTokenjuiceSavings(),
- apiClient.orchestrationPairing.list(),
- ]).then(([balance, team, savings, pairing]) => {
- if (cancelled) return;
- debug(
- 'usage load: exit balance=%s team=%s savings=%s pairing=%s',
- balance.status,
- team.status,
- savings.status,
- pairing.status
- );
- setData({
- balance: balance.status === 'fulfilled' ? balance.value : null,
- team: team.status === 'fulfilled' ? team.value : null,
- savings: savings.status === 'fulfilled' ? savings.value : null,
- connections:
- pairing.status === 'fulfilled'
- ? (pairing.value.stats?.contactCount ??
- pairing.value.contacts.contacts.filter(c => c.status === 'accepted').length)
- : null,
- });
- setLoading(false);
- });
- return () => {
- cancelled = true;
- };
- }, []);
-
- if (loading) {
- return (
- <div data-testid="orch-usage-loading">
- <CenteredLoadingState label={t('tinyplaceOrchestration.loading')} />
- </div>
- );
- }
-
- const balanceUsd =
- data?.balance != null
- ? data.balance.promotionBalanceUsd + data.balance.teamTopupUsd
- : undefined;
- const totals = data?.team?.insights.totals;
-
- return (
- <div className="space-y-3" data-testid="orch-usage-panel">
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
- <StatTile
- label={t('orchPage.usage.connections')}
- value={count(data?.connections ?? undefined)}
- testId="orch-usage-connections"
- />
- <StatTile
- label={t('orchPage.usage.balance')}
- value={usd(balanceUsd)}
- hint={t('orchPage.usage.balanceHint')}
- testId="orch-usage-balance"
- />
- <StatTile
- label={t('orchPage.usage.cycleSpend')}
- value={usd(data?.team?.cycleSpentUsd)}
- hint={
- data?.team
- ? `${t('orchPage.usage.ofBudget')} ${usd(data.team.cycleBudgetUsd)}`
- : undefined
- }
- testId="orch-usage-cycle-spend"
- />
- <StatTile
- label={t('orchPage.usage.inferenceCalls')}
- value={count(totals?.inferenceCalls)}
- testId="orch-usage-inference-calls"
- />
- <StatTile
- label={t('orchPage.usage.integrationCalls')}
- value={count(totals?.integrationCalls)}
- testId="orch-usage-integration-calls"
- />
- <StatTile
- label={t('orchPage.usage.tokensSaved')}
- value={count(data?.savings?.total.tokensSaved)}
- hint={
- data?.savings
- ? `${usd(data.savings.total.costSavedUsd)} ${t('orchPage.usage.saved')}`
- : undefined
- }
- testId="orch-usage-tokens-saved"
- />
- </div>
- <p className="text-[11px] text-content-faint">{t('orchPage.usage.footnote')}</p>
- </div>
- );
-}
diff --git a/app/src/components/orchestration/__tests__/AgentChatPanel.test.tsx b/app/src/components/orchestration/__tests__/AgentChatPanel.test.tsx
deleted file mode 100644
index b5c7f20216..0000000000
--- a/app/src/components/orchestration/__tests__/AgentChatPanel.test.tsx
+++ /dev/null
@@ -1,361 +0,0 @@
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { SessionSummary } from '../../../lib/orchestration/orchestrationClient';
-import AgentChatPanel from '../AgentChatPanel';
-
-vi.mock('../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-// The welcome hero pulls Redux/user/usage state; stub it so the panel renders
-// without the app providers. We only assert it mounts on an empty conscious thread.
-vi.mock('../../chat/ChatNewWindowHero', () => ({
- default: () => <div data-testid="chat-new-window-hero" />,
-}));
-
-const selectChat = vi.hoisted(() => vi.fn());
-const sendMessage = vi.hoisted(() => vi.fn().mockResolvedValue(true));
-const chatsApi = vi.hoisted(() => ({
- current: {
- sessionsState: { status: 'ok' as const },
- messagesState: { status: 'ok' as const },
- chats: [
- { id: 'master', title: 'Master', subtitle: 'you', unread: 0, messages: [] as unknown[] },
- {
- id: 'subconscious',
- title: 'Subconscious',
- subtitle: 'loop',
- unread: 0,
- messages: [] as unknown[],
- },
- ],
- selectedId: 'master',
- selected: { id: 'master', title: 'Master', messages: [] as unknown[] },
- status: null as unknown,
- masterError: null as string | null,
- selectChat,
- refresh: vi.fn(),
- sendMessage,
- },
-}));
-vi.mock('../../../lib/orchestration/useOrchestrationChats', () => ({
- MASTER_CHAT_KEY: 'master',
- SUBCONSCIOUS_CHAT_KEY: 'subconscious',
- useOrchestrationChats: () => chatsApi.current,
-}));
-
-const sendMasterMessage = vi.hoisted(() => vi.fn().mockResolvedValue({ ok: true, messageId: 'm' }));
-vi.mock('../../../lib/orchestration/orchestrationClient', async orig => ({
- ...(await orig<typeof import('../../../lib/orchestration/orchestrationClient')>()),
- orchestrationClient: { sendMasterMessage },
-}));
-
-const contactSessions = vi.hoisted(() => ({ current: [] as SessionSummary[] }));
-const transcript = vi.hoisted(() => ({
- current: { state: { status: 'ok' as const }, messages: [] as unknown[], refresh: vi.fn() },
-}));
-vi.mock('../../../lib/orchestration/useOrchestrationSessions', () => ({
- useContactSessions: () => ({
- state: { status: 'ok' },
- sessions: contactSessions.current,
- byContact: new Map(),
- refresh: vi.fn(),
- }),
- useSessionTranscript: () => transcript.current,
-}));
-
-const pinged: SessionSummary = {
- sessionId: 's-auth',
- agentId: '@peer',
- source: 'claude',
- status: 'waiting-approval',
- chatKind: 'session',
- lastMessageAt: '2026-07-08T00:00:00Z',
- unread: 0,
- active: true,
- pinned: false,
- label: 'auth-fix',
- messageCount: 3,
-};
-
-describe('AgentChatPanel', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- contactSessions.current = [];
- transcript.current = { state: { status: 'ok' }, messages: [], refresh: vi.fn() };
- chatsApi.current = {
- ...chatsApi.current,
- selectedId: 'master',
- selected: { id: 'master', title: 'Master', messages: [] },
- masterError: null,
- };
- });
-
- it('renders the conscious/subconscious toggle and switches conversation', () => {
- render(<AgentChatPanel />);
- const conscious = screen.getByTestId('orch-agent-tab-master');
- expect(conscious).toHaveAttribute('role', 'radio');
- expect(conscious).toHaveAttribute('aria-checked', 'true');
- fireEvent.click(screen.getByTestId('orch-agent-tab-subconscious'));
- expect(selectChat).toHaveBeenCalledWith('subconscious');
- });
-
- it('shows the welcome hero on an empty conscious thread', () => {
- render(<AgentChatPanel />);
- expect(screen.getByTestId('chat-new-window-hero')).toBeInTheDocument();
- });
-
- it('sends a master message from the composer', async () => {
- render(<AgentChatPanel />);
- fireEvent.change(screen.getByRole('textbox'), { target: { value: 'go' } });
- fireEvent.click(screen.getByTestId('send-message-button'));
- await waitFor(() =>
- expect(sendMessage).toHaveBeenCalledWith(expect.objectContaining({ id: 'master' }), 'go')
- );
- });
-
- it('opens a session subpage from a View-session card and replies', async () => {
- contactSessions.current = [pinged];
- render(<AgentChatPanel />);
- expect(screen.queryByTestId('orch-session-header')).not.toBeInTheDocument();
- fireEvent.click(screen.getByTestId('orch-agent-view-session-s-auth'));
- expect(screen.getByTestId('orch-session-header')).toBeInTheDocument();
-
- fireEvent.change(screen.getByRole('textbox'), { target: { value: 'hi' } });
- fireEvent.click(screen.getByTestId('send-message-button'));
- await waitFor(() =>
- expect(sendMasterMessage).toHaveBeenCalledWith({
- body: 'hi',
- recipient: '@peer',
- sessionId: 's-auth',
- })
- );
- });
-
- it('routes a runtime tool-approval decision back as an allow reply', async () => {
- contactSessions.current = [pinged];
- transcript.current = {
- state: { status: 'ok' },
- messages: [
- {
- id: 'ap',
- from: 'agent',
- body: 'gh pr status',
- timestamp: '2026-07-08T00:00:00Z',
- encrypted: false,
- eventKind: 'approval_request',
- toolName: 'shell',
- },
- ],
- refresh: vi.fn(),
- };
- render(<AgentChatPanel />);
- fireEvent.click(screen.getByTestId('orch-agent-view-session-s-auth'));
- fireEvent.click(screen.getByText('chat.approval.approve'));
- await waitFor(() =>
- expect(sendMasterMessage).toHaveBeenCalledWith({
- body: 'allow',
- recipient: '@peer',
- sessionId: 's-auth',
- })
- );
- });
-
- it('surfaces a session reply failure', async () => {
- contactSessions.current = [pinged];
- sendMasterMessage.mockRejectedValueOnce(new Error('boom'));
- render(<AgentChatPanel />);
- fireEvent.click(screen.getByTestId('orch-agent-view-session-s-auth'));
- fireEvent.change(screen.getByRole('textbox'), { target: { value: 'hi' } });
- fireEvent.click(screen.getByTestId('send-message-button'));
- expect(await screen.findByTestId('orch-session-reply-error')).toHaveTextContent('boom');
- });
-
- it('shows an error state when the transcript fails to load', () => {
- chatsApi.current = {
- ...chatsApi.current,
- messagesState: { status: 'error', message: 'load failed' } as never,
- };
- render(<AgentChatPanel />);
- expect(screen.getByText(/load failed/)).toBeInTheDocument();
- });
-
- // ── Autoscroll (regression: new master message snapped to the TOP) ─────────
- const msg = (id: string) => ({
- id,
- from: 'you',
- body: id,
- timestamp: '2026-07-08T00:00:00Z',
- encrypted: false,
- });
-
- // jsdom does no layout, so `scrollTop`/`scrollHeight`/`clientHeight` are inert.
- // Back them with a stored value so the stick-to-bottom snap is observable.
- const fakeMetrics = (el: HTMLElement, scrollHeight: number, clientHeight: number) => {
- let top = 0;
- Object.defineProperty(el, 'scrollHeight', { value: scrollHeight, configurable: true });
- Object.defineProperty(el, 'clientHeight', { value: clientHeight, configurable: true });
- Object.defineProperty(el, 'scrollTop', {
- get: () => top,
- set: v => {
- top = v;
- },
- configurable: true,
- });
- };
-
- it('pins the newest master message to the bottom on a new message (not the top)', () => {
- chatsApi.current = {
- ...chatsApi.current,
- selectedId: 'master',
- selected: { id: 'master', title: 'Master', messages: [msg('m1')] },
- };
- const { rerender } = render(<AgentChatPanel />);
- const scroll = screen.getByTestId('orch-chat-scroll') as HTMLDivElement;
- fakeMetrics(scroll, 1000, 400);
- scroll.scrollTop = 0; // as if reset to the top by the loading-spinner swap
-
- chatsApi.current = {
- ...chatsApi.current,
- selected: { id: 'master', title: 'Master', messages: [msg('m1'), msg('m2')] },
- };
- rerender(<AgentChatPanel />);
-
- expect(scroll.scrollTop).toBe(1000); // snapped to the bottom, not left at 0
- });
-
- it('does not yank the master chat down when the user has scrolled up', () => {
- chatsApi.current = {
- ...chatsApi.current,
- selectedId: 'master',
- selected: { id: 'master', title: 'Master', messages: [msg('m1')] },
- };
- const { rerender } = render(<AgentChatPanel />);
- const scroll = screen.getByTestId('orch-chat-scroll') as HTMLDivElement;
- fakeMetrics(scroll, 1000, 400);
- scroll.scrollTop = 0; // 600px from the bottom, past the 80px threshold
- fireEvent.scroll(scroll); // disengages stickiness
-
- chatsApi.current = {
- ...chatsApi.current,
- selected: { id: 'master', title: 'Master', messages: [msg('m1'), msg('m2')] },
- };
- rerender(<AgentChatPanel />);
-
- expect(scroll.scrollTop).toBe(0); // left where the user parked it
- });
-
- it('renders with no selected chat (covers the empty-messages fallback)', () => {
- chatsApi.current = { ...chatsApi.current, selected: undefined as never };
- render(<AgentChatPanel />);
- // Exercises `selected?.messages ?? EMPTY_MESSAGES`; the panel still renders.
- expect(screen.getByTestId('orch-agent-tab-master')).toBeInTheDocument();
- });
-
- // ── Composer-footer measurement (regression: #5162 / TAURI-REACT-2G) ───────
- //
- // `ChatPageScaffold` measures its floating footer with a ResizeObserver and
- // feeds the height into the scroll region's bottom padding. The effect used to
- // depend on the `footer` *node*, which is inline JSX at every call site and so
- // takes a fresh identity on every render — the observer was torn down and
- // rebuilt each pass, and because `observe()` delivers an immediate
- // observation, every render scheduled another height update. Any measurement
- // that disagreed with the committed value re-rendered and re-ran the effect,
- // cascading until React aborted with "Maximum update depth exceeded". Typing
- // was the easiest trigger: the composer's auto-growing textarea lives inside
- // this footer.
- describe('composer footer measurement', () => {
- /** Model of the real ResizeObserver: `observe()` reports an initial size. */
- class MockResizeObserver {
- static instances: MockResizeObserver[] = [];
- observed: Element[] = [];
- disconnected = false;
- constructor(private readonly cb: () => void) {
- MockResizeObserver.instances.push(this);
- }
- observe(el: Element) {
- this.observed.push(el);
- this.cb();
- }
- unobserve() {}
- disconnect() {
- this.disconnected = true;
- }
- /** Drive a size change the way a real layout change would. */
- fire() {
- this.cb();
- }
- }
-
- /**
- * Observers watching the composer footer. `useStickToBottom` also builds a
- * ResizeObserver (on the scroll container), so the global mock catches both —
- * select ours by the element it observes.
- */
- const footerObservers = () =>
- MockResizeObserver.instances.filter(o =>
- o.observed.some(el => (el as HTMLElement).dataset?.testid === 'orch-chat-footer')
- );
-
- const footerHeight = { current: 96 };
- let originalResizeObserver: typeof globalThis.ResizeObserver | undefined;
- let originalOffsetHeight: PropertyDescriptor | undefined;
-
- beforeEach(() => {
- MockResizeObserver.instances = [];
- footerHeight.current = 96;
- originalResizeObserver = globalThis.ResizeObserver;
- globalThis.ResizeObserver = MockResizeObserver as unknown as typeof globalThis.ResizeObserver;
- // jsdom does no layout, so every `offsetHeight` is 0. Report a real height
- // for the footer wrapper only, so the measurement path is observable.
- originalOffsetHeight = Object.getOwnPropertyDescriptor(
- HTMLElement.prototype,
- 'offsetHeight'
- ) as PropertyDescriptor | undefined;
- Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
- configurable: true,
- get(this: HTMLElement) {
- return this.dataset.testid === 'orch-chat-footer' ? footerHeight.current : 0;
- },
- });
- });
-
- afterEach(() => {
- if (originalResizeObserver) globalThis.ResizeObserver = originalResizeObserver;
- else delete (globalThis as { ResizeObserver?: unknown }).ResizeObserver;
- if (originalOffsetHeight) {
- Object.defineProperty(HTMLElement.prototype, 'offsetHeight', originalOffsetHeight);
- } else {
- delete (HTMLElement.prototype as unknown as Record<string, unknown>).offsetHeight;
- }
- });
-
- it('does not rebuild the footer ResizeObserver on every render while typing', () => {
- render(<AgentChatPanel />);
- expect(footerObservers()).toHaveLength(1);
-
- // Each keystroke re-renders the panel, which produces a fresh `footer`
- // element. That must NOT re-subscribe the observer.
- const textbox = screen.getByRole('textbox');
- fireEvent.change(textbox, { target: { value: 'h' } });
- fireEvent.change(textbox, { target: { value: 'he' } });
- fireEvent.change(textbox, { target: { value: 'hey' } });
-
- expect(footerObservers()).toHaveLength(1);
- expect(footerObservers()[0].disconnected).toBe(false);
- });
-
- it('still reserves the measured footer height on the scroll region', () => {
- render(<AgentChatPanel />);
- const scroll = screen.getByTestId('orch-chat-scroll');
- expect(scroll.style.paddingBottom).toBe('96px');
-
- // A real layout change (the composer growing a line) must still be picked
- // up now that the effect subscribes on footer presence rather than identity.
- footerHeight.current = 132;
- act(() => footerObservers()[0].fire());
-
- expect(scroll.style.paddingBottom).toBe('132px');
- expect(footerObservers()).toHaveLength(1);
- });
- });
-});
diff --git a/app/src/components/orchestration/__tests__/ConnectionsPanel.test.tsx b/app/src/components/orchestration/__tests__/ConnectionsPanel.test.tsx
deleted file mode 100644
index 930e11c204..0000000000
--- a/app/src/components/orchestration/__tests__/ConnectionsPanel.test.tsx
+++ /dev/null
@@ -1,208 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { SessionSummary } from '../../../lib/orchestration/orchestrationClient';
-import ConnectionsPanel from '../ConnectionsPanel';
-
-vi.mock('../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const runAction = vi.hoisted(() =>
- vi.fn(async (_id: string, fn: () => Promise<unknown>) => {
- await fn();
- })
-);
-const pairing = vi.hoisted(() => ({
- current: {
- state: { status: 'ok' as const, snapshot: {} as Record<string, unknown> },
- reload: vi.fn(),
- runAction,
- pendingAction: null as string | null,
- actionError: null as string | null,
- },
-}));
-vi.mock('../../../lib/orchestration/usePairing', () => ({ usePairing: () => pairing.current }));
-
-const acceptRequest = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-const declineRequest = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-const reverse = vi.hoisted(() => vi.fn().mockResolvedValue({ agents: [{ username: 'alice' }] }));
-vi.mock('../../../lib/agentworld/apiClient', () => ({
- apiClient: {
- orchestrationPairing: { acceptRequest, declineRequest, blockRequest: vi.fn() },
- directory: { reverse },
- },
-}));
-
-const sessionsCreate = vi.hoisted(() => vi.fn());
-const sendMasterMessage = vi.hoisted(() => vi.fn().mockResolvedValue({ ok: true, messageId: 'm' }));
-vi.mock('../../../lib/orchestration/orchestrationClient', async orig => ({
- ...(await orig<typeof import('../../../lib/orchestration/orchestrationClient')>()),
- orchestrationClient: { sessionsCreate, sendMasterMessage },
-}));
-
-const sessionsHook = vi.hoisted(() => ({
- byContact: new Map<string, SessionSummary[]>(),
- refresh: vi.fn(),
-}));
-const transcriptHook = vi.hoisted(() => ({
- current: { state: { status: 'ok' as const }, messages: [] as unknown[], refresh: vi.fn() },
-}));
-vi.mock('../../../lib/orchestration/useOrchestrationSessions', () => ({
- useContactSessions: () => ({
- state: { status: 'ok' },
- sessions: [...sessionsHook.byContact.values()].flat(),
- byContact: sessionsHook.byContact,
- refresh: sessionsHook.refresh,
- }),
- useSessionTranscript: () => transcriptHook.current,
-}));
-
-const ADDR = '3icjiLXhn6BMv43MsHjpKKxm7hEYBk7R5rvNXB1HUk7g';
-
-function session(over: Partial<SessionSummary>): SessionSummary {
- return {
- sessionId: 's1',
- agentId: ADDR,
- source: 'claude',
- status: 'waiting-approval',
- chatKind: 'session',
- lastMessageAt: '2026-07-08T00:00:00Z',
- unread: 0,
- active: true,
- pinned: false,
- label: 'auth-fix',
- messageCount: 5,
- ...over,
- };
-}
-
-function okState(accepted: unknown[], incoming: unknown[] = []) {
- return {
- status: 'ok' as const,
- snapshot: {
- contacts: { contacts: accepted },
- requests: { incoming, outgoing: [] },
- stats: {
- agentId: 'me',
- contactCount: accepted.length,
- pendingIncoming: incoming.length,
- pendingOutgoing: 0,
- },
- },
- };
-}
-
-describe('ConnectionsPanel', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- sessionsHook.byContact = new Map();
- transcriptHook.current = { state: { status: 'ok' }, messages: [], refresh: vi.fn() };
- pairing.current = { ...pairing.current, pendingAction: null, actionError: null };
- });
-
- it('shows a loading state', () => {
- pairing.current = { ...pairing.current, state: { status: 'loading' } as never };
- render(<ConnectionsPanel />);
- expect(screen.getByTestId('orch-connections-loading')).toBeInTheDocument();
- });
-
- it('renders an empty state with a discover CTA', () => {
- pairing.current = { ...pairing.current, state: okState([]) as never };
- const onDiscover = vi.fn();
- render(<ConnectionsPanel onDiscover={onDiscover} />);
- expect(screen.getByTestId('orch-connections-empty')).toBeInTheDocument();
- fireEvent.click(screen.getByTestId('orch-connections-empty-cta'));
- expect(onDiscover).toHaveBeenCalled();
- });
-
- it('accepts and declines an incoming request', () => {
- const req = { agentId: ADDR, status: 'pending', direction: 'incoming' };
- pairing.current = { ...pairing.current, state: okState([], [req]) as never };
- render(<ConnectionsPanel />);
- fireEvent.click(screen.getByText('tinyplaceOrchestration.pairing.accept'));
- expect(acceptRequest).toHaveBeenCalledWith(ADDR);
- fireEvent.click(screen.getByText('tinyplaceOrchestration.pairing.decline'));
- expect(declineRequest).toHaveBeenCalledWith(ADDR);
- });
-
- it('expands a contact to reveal its sessions, opens one, and replies', async () => {
- const contact = { agentId: ADDR, status: 'accepted', direction: 'outgoing' };
- sessionsHook.byContact.set(ADDR, [session({})]);
- pairing.current = { ...pairing.current, state: okState([contact]) as never };
- render(<ConnectionsPanel />);
-
- fireEvent.click(screen.getByTestId(`orch-connection-${ADDR}`).querySelector('button')!);
- const sessionRow = await screen.findByTestId('orch-session-s1');
- expect(sessionRow).toHaveTextContent('auth-fix');
-
- fireEvent.click(sessionRow);
- expect(screen.getByTestId('orch-session-view')).toBeInTheDocument();
-
- fireEvent.change(screen.getByTestId('orch-session-reply-input'), { target: { value: 'hi' } });
- fireEvent.click(screen.getByTestId('orch-session-reply-send'));
- await waitFor(() =>
- expect(sendMasterMessage).toHaveBeenCalledWith({
- body: 'hi',
- recipient: ADDR,
- sessionId: 's1',
- })
- );
-
- fireEvent.click(screen.getByTestId('orch-session-back'));
- expect(screen.getByTestId('orch-connections-panel')).toBeInTheDocument();
- });
-
- it('routes a runtime tool-approval decision back as an allow reply', async () => {
- const contact = { agentId: ADDR, status: 'accepted', direction: 'outgoing' };
- sessionsHook.byContact.set(ADDR, [session({})]);
- pairing.current = { ...pairing.current, state: okState([contact]) as never };
- transcriptHook.current = {
- state: { status: 'ok' },
- messages: [
- {
- id: 'ap',
- from: 'agent',
- body: 'gh pr status',
- timestamp: '2026-07-08T00:00:00Z',
- encrypted: false,
- eventKind: 'approval_request',
- toolName: 'shell',
- },
- ],
- refresh: vi.fn(),
- };
- render(<ConnectionsPanel />);
- fireEvent.click(screen.getByTestId(`orch-connection-${ADDR}`).querySelector('button')!);
- fireEvent.click(await screen.findByTestId('orch-session-s1'));
- fireEvent.click(screen.getByText('chat.approval.approve'));
- await waitFor(() =>
- expect(sendMasterMessage).toHaveBeenCalledWith({
- body: 'allow',
- recipient: ADDR,
- sessionId: 's1',
- })
- );
- });
-
- it('surfaces a reply send failure instead of swallowing it', async () => {
- const contact = { agentId: ADDR, status: 'accepted', direction: 'outgoing' };
- sessionsHook.byContact.set(ADDR, [session({})]);
- sendMasterMessage.mockRejectedValueOnce(new Error('relay down'));
- pairing.current = { ...pairing.current, state: okState([contact]) as never };
- render(<ConnectionsPanel />);
- fireEvent.click(screen.getByTestId(`orch-connection-${ADDR}`).querySelector('button')!);
- fireEvent.click(await screen.findByTestId('orch-session-s1'));
- fireEvent.change(screen.getByTestId('orch-session-reply-input'), { target: { value: 'hi' } });
- fireEvent.click(screen.getByTestId('orch-session-reply-send'));
- expect(await screen.findByTestId('orch-session-reply-error')).toHaveTextContent('relay down');
- });
-
- it('creates a new session under a contact', async () => {
- const contact = { agentId: ADDR, status: 'accepted', direction: 'outgoing' };
- sessionsCreate.mockResolvedValue({ session: session({ sessionId: 's-new' }) });
- pairing.current = { ...pairing.current, state: okState([contact]) as never };
- render(<ConnectionsPanel />);
- fireEvent.click(screen.getByTestId(`orch-connection-${ADDR}`).querySelector('button')!);
- fireEvent.click(await screen.findByTestId(`orch-new-session-${ADDR}`));
- await waitFor(() => expect(sessionsCreate).toHaveBeenCalledWith({ agentId: ADDR }));
- });
-});
diff --git a/app/src/components/orchestration/__tests__/DiscoverPanel.test.tsx b/app/src/components/orchestration/__tests__/DiscoverPanel.test.tsx
deleted file mode 100644
index 23143f8789..0000000000
--- a/app/src/components/orchestration/__tests__/DiscoverPanel.test.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import DiscoverPanel from '../DiscoverPanel';
-
-vi.mock('../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const runAction = vi.hoisted(() => vi.fn());
-const pairing = vi.hoisted(() => ({
- current: {
- state: { status: 'ok' as const, snapshot: { requests: { incoming: [], outgoing: [] } } },
- reload: vi.fn(),
- runAction,
- pendingAction: null as string | null,
- actionError: null as string | null,
- },
-}));
-vi.mock('../../../lib/orchestration/usePairing', () => ({ usePairing: () => pairing.current }));
-
-const selfIdentity = vi.hoisted(() => vi.fn());
-const relayInfo = vi.hoisted(() => vi.fn().mockResolvedValue({ baseUrl: 'x', network: 'prod' }));
-// The #5805 wallet gate runs before the identity fetch; mock it to a configured
-// wallet so these cases exercise the same path they always did.
-vi.mock('../../../services/walletApi', () => ({
- fetchWalletStatus: vi.fn().mockResolvedValue({ configured: true }),
-}));
-
-vi.mock('../../../lib/orchestration/orchestrationClient', () => ({
- orchestrationClient: { selfIdentity, relayInfo },
-}));
-
-const linkSession = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-const acceptRequest = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-const reverse = vi.hoisted(() => vi.fn().mockResolvedValue({ agents: [] }));
-vi.mock('../../../lib/agentworld/apiClient', () => ({
- apiClient: {
- orchestrationPairing: { linkSession, acceptRequest, declineRequest: vi.fn() },
- directory: { reverse },
- },
-}));
-
-describe('DiscoverPanel', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- selfIdentity.mockResolvedValue({
- agentId: 'me',
- handles: [],
- discoverable: false,
- cardPublished: false,
- keyPublished: false,
- });
- pairing.current = {
- ...pairing.current,
- state: { status: 'ok', snapshot: { requests: { incoming: [], outgoing: [] } } } as never,
- pendingAction: null,
- actionError: null,
- };
- });
-
- it('shows the discoverability guide when not discoverable', async () => {
- render(<DiscoverPanel />);
- await waitFor(() => expect(screen.getByTestId('orch-discover-guide')).toBeInTheDocument());
- expect(screen.getByTestId('orch-discover-no-requests')).toBeInTheDocument();
- });
-
- it('submits a link request', async () => {
- render(<DiscoverPanel />);
- fireEvent.change(screen.getByTestId('orch-discover-link-input'), {
- target: { value: 'agent-9' },
- });
- fireEvent.submit(screen.getByTestId('orch-discover-link-input').closest('form')!);
- expect(runAction).toHaveBeenCalledWith('link:agent-9', expect.any(Function));
- });
-
- it('accepts an inbound request', async () => {
- pairing.current = {
- ...pairing.current,
- state: {
- status: 'ok',
- snapshot: {
- requests: {
- incoming: [{ status: 'pending', agentId: 'agent-7', contact: {} }],
- outgoing: [],
- },
- },
- } as never,
- };
- render(<DiscoverPanel />);
- await waitFor(() =>
- expect(screen.getByTestId('orch-discover-request-row')).toBeInTheDocument()
- );
- fireEvent.click(screen.getByTestId('orch-discover-accept'));
- expect(runAction).toHaveBeenCalledWith('accept:agent-7', expect.any(Function));
- });
-});
diff --git a/app/src/components/orchestration/__tests__/OrchestrationView.test.tsx b/app/src/components/orchestration/__tests__/OrchestrationView.test.tsx
deleted file mode 100644
index 25c5fd562b..0000000000
--- a/app/src/components/orchestration/__tests__/OrchestrationView.test.tsx
+++ /dev/null
@@ -1,144 +0,0 @@
-import { act, fireEvent, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { renderWithProviders } from '../../../test/test-utils';
-import OrchestrationView from '../OrchestrationView';
-
-vi.mock('../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-// Medulla access is toggled per-test; default to granted so the view-routing
-// tests exercise the live panels.
-let medullaAccess = true;
-vi.mock('../../../lib/orchestration/useMedullaAccess', () => ({
- useMedullaAccess: () => medullaAccess,
-}));
-
-// No live peer sessions by default, so the agent view's left rail stays hidden.
-vi.mock('../../../lib/orchestration/useOrchestrationSessions', () => ({
- useContactSessions: () => ({ byContact: new Map() }),
-}));
-
-// Stub the data-backed panels so the view's tab routing is tested in isolation
-// (the panels have their own unit tests).
-vi.mock('../MedullaOverviewPanel', () => ({ default: () => <div data-testid="panel-medulla" /> }));
-vi.mock('../AgentChatPanel', () => ({ default: () => <div data-testid="panel-agent" /> }));
-vi.mock('../ConnectionsPanel', () => ({
- default: ({ onDiscover }: { onDiscover?: () => void }) => (
- <button data-testid="panel-connections" onClick={onDiscover}>
- connections
- </button>
- ),
-}));
-vi.mock('../DiscoverPanel', () => ({ default: () => <div data-testid="panel-discover" /> }));
-vi.mock('../UsagePanel', () => ({ default: () => <div data-testid="panel-usage" /> }));
-vi.mock('../OverviewPanel', () => ({ default: () => <div data-testid="panel-graph" /> }));
-vi.mock('../OrchestratorTaskBoard', () => ({ default: () => <div data-testid="panel-tasks" /> }));
-vi.mock('../demo/MedullaDemoChat', () => ({ default: () => <div data-testid="orch-demo-chat" /> }));
-vi.mock('../demo/MedullaDemoGraph', () => ({
- default: () => <div data-testid="orch-demo-graph" />,
-}));
-vi.mock('../demo/MedullaDemoNetwork', () => ({
- default: () => <div data-testid="orch-demo-network" />,
-}));
-
-const BASE = '/brain?tab=orchestration';
-
-describe('OrchestrationView (Medulla access)', () => {
- beforeEach(() => {
- medullaAccess = true;
- });
-
- it('defaults to the Medulla overview panel', async () => {
- await act(async () => {
- renderWithProviders(<OrchestrationView />, { initialEntries: [BASE] });
- });
- expect(screen.getByTestId('panel-medulla')).toBeInTheDocument();
- });
-
- it('renders the agent chat panel from ?ov=agent', async () => {
- await act(async () => {
- renderWithProviders(<OrchestrationView />, { initialEntries: [`${BASE}&ov=agent`] });
- });
- expect(screen.getByTestId('panel-agent')).toBeInTheDocument();
- });
-
- it('renders the agent graph panel from ?ov=overview', async () => {
- await act(async () => {
- renderWithProviders(<OrchestrationView />, { initialEntries: [`${BASE}&ov=overview`] });
- });
- expect(screen.getByTestId('panel-graph')).toBeInTheDocument();
- });
-
- it('renders the task board from ?ov=tasks', async () => {
- await act(async () => {
- renderWithProviders(<OrchestrationView />, { initialEntries: [`${BASE}&ov=tasks`] });
- });
- expect(screen.getByTestId('panel-tasks')).toBeInTheDocument();
- });
-
- it.each([
- ['connections', 'panel-connections'],
- ['discover', 'panel-discover'],
- ['usage', 'panel-usage'],
- ])('renders the %s network sub from ?ov=network&sub=%s', async (sub, testId) => {
- await act(async () => {
- renderWithProviders(<OrchestrationView />, {
- initialEntries: [`${BASE}&ov=network&sub=${sub}`],
- });
- });
- expect(screen.getByTestId(testId)).toBeInTheDocument();
- });
-
- it('switches views via the chip nav', async () => {
- await act(async () => {
- renderWithProviders(<OrchestrationView />, { initialEntries: [BASE] });
- });
- await act(async () => {
- fireEvent.click(screen.getByTestId('orch-view-network'));
- });
- await waitFor(() => expect(screen.getByTestId('panel-connections')).toBeInTheDocument());
- });
-
- it('lets the connections panel jump to discover via its callback', async () => {
- await act(async () => {
- renderWithProviders(<OrchestrationView />, {
- initialEntries: [`${BASE}&ov=network&sub=connections`],
- });
- });
- await act(async () => {
- fireEvent.click(screen.getByTestId('panel-connections'));
- });
- await waitFor(() => expect(screen.getByTestId('panel-discover')).toBeInTheDocument());
- });
-});
-
-describe('OrchestrationView scale showcase (no Medulla access)', () => {
- beforeEach(() => {
- medullaAccess = false;
- });
-
- it.each([
- ['agent', 'orch-demo-chat'],
- ['overview', 'orch-demo-graph'],
- ['network', 'orch-demo-network'],
- ])('renders the demo surface for ?ov=%s', async (ov, testId) => {
- await act(async () => {
- renderWithProviders(<OrchestrationView />, { initialEntries: [`${BASE}&ov=${ov}`] });
- });
- expect(screen.getByTestId(testId)).toBeInTheDocument();
- });
-
- it('keeps the real task board available without Medulla access', async () => {
- await act(async () => {
- renderWithProviders(<OrchestrationView />, { initialEntries: [`${BASE}&ov=tasks`] });
- });
- expect(screen.getByTestId('panel-tasks')).toBeInTheDocument();
- });
-
- it('still lands on the Medulla overview by default', async () => {
- await act(async () => {
- renderWithProviders(<OrchestrationView />, { initialEntries: [BASE] });
- });
- expect(screen.getByTestId('panel-medulla')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/orchestration/__tests__/SessionTranscript.test.tsx b/app/src/components/orchestration/__tests__/SessionTranscript.test.tsx
deleted file mode 100644
index d557d6f72b..0000000000
--- a/app/src/components/orchestration/__tests__/SessionTranscript.test.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { ChatMessage } from '../../../lib/orchestration/useOrchestrationChats';
-import SessionTranscript from '../SessionTranscript';
-
-vi.mock('../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const msg = (over: Partial<ChatMessage>): ChatMessage => ({
- id: 'x',
- from: 'agent',
- body: '',
- timestamp: '2026-07-08T17:00:00Z',
- encrypted: false,
- ...over,
-});
-
-describe('SessionTranscript', () => {
- it('renders user vs agent bubbles by sender', () => {
- render(
- <SessionTranscript
- messages={[
- msg({ id: 'u', from: 'you', eventKind: 'user_prompt', body: 'hello' }),
- msg({ id: 'a', from: 'agent', eventKind: 'agent_message', body: 'hi back' }),
- ]}
- />
- );
- expect(
- screen.getByText('hello').closest('[data-event-kind="user_prompt"]')
- ).toBeInTheDocument();
- expect(
- screen.getByText('hi back').closest('[data-event-kind="agent_message"]')
- ).toBeInTheDocument();
- });
-
- it('renders an owner-authored reply (role "owner") as a user bubble', () => {
- // A composer reply is mirrored back with role "owner" and no eventKind;
- // it must sit on the right (primary bubble), not as a left agent bubble.
- render(<SessionTranscript messages={[msg({ id: 'o', from: 'owner', body: 'my reply' })]} />);
- expect(screen.getByText('my reply').closest('.bg-primary-500')).toBeInTheDocument();
- });
-
- it('merges a tool_call+result and marks failure', () => {
- render(
- <SessionTranscript
- messages={[
- msg({ id: 'tc', eventKind: 'tool_call', toolName: 'Bash', callId: 'c1', body: 'ls' }),
- msg({
- id: 'tr',
- eventKind: 'tool_result',
- callId: 'c1',
- body: 'boom',
- isError: true,
- exitCode: 1,
- }),
- ]}
- />
- );
- const tool = screen.getByText('ls').closest('[data-event-kind="tool_call"]')!;
- expect(tool).toHaveAttribute('data-failed', 'true');
- expect(screen.getByText('boom')).toBeInTheDocument();
- });
-
- it('renders an approval read-only without onDecide', () => {
- render(
- <SessionTranscript
- messages={[
- msg({ id: 'ap', eventKind: 'approval_request', toolName: 'gh', body: 'gh pr create' }),
- ]}
- />
- );
- expect(screen.getByText('chat.approval.title')).toBeInTheDocument();
- expect(screen.queryByText('chat.approval.approve')).not.toBeInTheDocument();
- });
-
- it('wires approval buttons to onDecide and resolves the card in place', () => {
- const onDecide = vi.fn();
- const approval = msg({ id: 'ap', eventKind: 'approval_request', body: 'run it' });
- render(<SessionTranscript messages={[approval]} onDecide={onDecide} />);
- fireEvent.click(screen.getByRole('button', { name: 'chat.approval.approve' }));
- expect(onDecide).toHaveBeenCalledWith(approval, 'approve');
- // After deciding, the card resolves in place: buttons are gone, outcome shown.
- expect(screen.queryByRole('button', { name: 'chat.approval.deny' })).not.toBeInTheDocument();
- expect(screen.getByTestId('approval-resolved')).toBeInTheDocument();
- });
-
- it('resolves to a denied outcome when denied', () => {
- const onDecide = vi.fn();
- const approval = msg({ id: 'ap', eventKind: 'approval_request', body: 'rm -rf' });
- render(<SessionTranscript messages={[approval]} onDecide={onDecide} />);
- fireEvent.click(screen.getByRole('button', { name: 'chat.approval.deny' }));
- expect(onDecide).toHaveBeenCalledWith(approval, 'deny');
- expect(screen.queryByRole('button', { name: 'chat.approval.approve' })).not.toBeInTheDocument();
- expect(screen.getByTestId('approval-resolved')).toHaveTextContent('chat.approval.deny');
- });
-
- it('resolves from a persisted decision echo (survives reload) and suppresses that echo', () => {
- // No onDecide (as after remount), but a paired decision echo is present — the
- // card renders resolved, and the redundant echo bubble is hidden.
- render(
- <SessionTranscript
- messages={[
- msg({ id: 'ap', eventKind: 'approval_request', toolName: 'shell', body: 'ls' }),
- msg({ id: 'echo', from: 'owner', body: 'allow' }),
- ]}
- />
- );
- expect(screen.getByTestId('approval-resolved')).toBeInTheDocument();
- expect(screen.queryByRole('button', { name: 'chat.approval.approve' })).not.toBeInTheDocument();
- expect(screen.queryByText('allow')).not.toBeInTheDocument();
- });
-
- it('preserves an unpaired one-word owner reply (real chat, no approval)', () => {
- render(
- <SessionTranscript
- messages={[
- msg({ id: 'a', from: 'agent', body: 'the answer' }),
- msg({ id: 'reply', from: 'owner', body: 'allow' }),
- ]}
- />
- );
- // no preceding approval → "allow" is a normal reply and must stay visible
- expect(screen.getByText('allow')).toBeInTheDocument();
- expect(screen.getByText('the answer')).toBeInTheDocument();
- });
-
- it('hides "Always allow" by default and shows it only when enabled', () => {
- const approval = msg({ id: 'ap', eventKind: 'approval_request', body: 'run it' });
- const { rerender } = render(<SessionTranscript messages={[approval]} onDecide={vi.fn()} />);
- expect(
- screen.queryByRole('button', { name: 'chat.approval.alwaysAllow' })
- ).not.toBeInTheDocument();
- rerender(<SessionTranscript messages={[approval]} onDecide={vi.fn()} alwaysAllow />);
- expect(screen.getByRole('button', { name: 'chat.approval.alwaysAllow' })).toBeInTheDocument();
- });
-
- it('rolls the card back to buttons if the decision send fails', async () => {
- const onDecide = vi.fn().mockRejectedValue(new Error('relay down'));
- const approval = msg({ id: 'ap', eventKind: 'approval_request', body: 'run it' });
- render(<SessionTranscript messages={[approval]} onDecide={onDecide} />);
- fireEvent.click(screen.getByRole('button', { name: 'chat.approval.approve' }));
- // optimistic resolve, then rollback on rejection → the buttons return for retry
- await waitFor(() =>
- expect(screen.getByRole('button', { name: 'chat.approval.approve' })).toBeInTheDocument()
- );
- expect(screen.queryByTestId('approval-resolved')).not.toBeInTheDocument();
- });
-});
diff --git a/app/src/components/orchestration/__tests__/UsagePanel.test.tsx b/app/src/components/orchestration/__tests__/UsagePanel.test.tsx
deleted file mode 100644
index 32767e0bcf..0000000000
--- a/app/src/components/orchestration/__tests__/UsagePanel.test.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import UsagePanel from '../UsagePanel';
-
-vi.mock('../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const getBalance = vi.hoisted(() => vi.fn());
-const getTeamUsage = vi.hoisted(() => vi.fn());
-vi.mock('../../../services/api/creditsApi', () => ({ creditsApi: { getBalance, getTeamUsage } }));
-
-const getTokenjuiceSavings = vi.hoisted(() => vi.fn());
-vi.mock('../../../utils/tauriCommands/tokenjuice', () => ({ getTokenjuiceSavings }));
-
-const list = vi.hoisted(() => vi.fn());
-vi.mock('../../../lib/agentworld/apiClient', () => ({
- apiClient: { orchestrationPairing: { list } },
-}));
-
-describe('UsagePanel', () => {
- beforeEach(() => vi.clearAllMocks());
-
- it('renders every stat tile when all sources succeed', async () => {
- getBalance.mockResolvedValue({ promotionBalanceUsd: 5, teamTopupUsd: 10 });
- getTeamUsage.mockResolvedValue({
- cycleSpentUsd: 3.5,
- cycleBudgetUsd: 20,
- insights: { totals: { inferenceCalls: 42, integrationCalls: 7 } },
- });
- getTokenjuiceSavings.mockResolvedValue({ total: { tokensSaved: 1234, costSavedUsd: 0.9 } });
- list.mockResolvedValue({ stats: { contactCount: 3 }, contacts: { contacts: [] } });
-
- render(<UsagePanel />);
- await waitFor(() => expect(screen.getByTestId('orch-usage-panel')).toBeInTheDocument());
- expect(screen.getByTestId('orch-usage-connections')).toHaveTextContent('3');
- expect(screen.getByTestId('orch-usage-balance')).toHaveTextContent('$15.00');
- expect(screen.getByTestId('orch-usage-cycle-spend')).toHaveTextContent('$3.50');
- expect(screen.getByTestId('orch-usage-inference-calls')).toHaveTextContent('42');
- expect(screen.getByTestId('orch-usage-tokens-saved')).toHaveTextContent('1,234');
- });
-
- it('degrades unavailable sources to a dash without blanking the page', async () => {
- getBalance.mockRejectedValue(new Error('billing offline'));
- getTeamUsage.mockRejectedValue(new Error('billing offline'));
- getTokenjuiceSavings.mockRejectedValue(new Error('no core'));
- list.mockRejectedValue(new Error('no relay'));
-
- render(<UsagePanel />);
- await waitFor(() => expect(screen.getByTestId('orch-usage-panel')).toBeInTheDocument());
- expect(screen.getByTestId('orch-usage-balance')).toHaveTextContent('—');
- expect(screen.getByTestId('orch-usage-connections')).toHaveTextContent('—');
- });
-});
diff --git a/app/src/components/orchestration/demo/DemoScaleBanner.tsx b/app/src/components/orchestration/demo/DemoScaleBanner.tsx
deleted file mode 100644
index 4a0a831d73..0000000000
--- a/app/src/components/orchestration/demo/DemoScaleBanner.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { useT } from '../../../lib/i18n/I18nContext';
-
-/**
- * The "this is a preview, not live data" banner shown across the Orchestration
- * scale showcase (graph / tasks / network) for users without Medulla access.
- * Kept visually distinct (dashed primary border) so the demo can never be
- * mistaken for the real orchestration surface.
- */
-export default function DemoScaleBanner({ className }: { className?: string }) {
- const { t } = useT();
- return (
- <div
- role="status"
- data-testid="orch-demo-banner"
- className={`flex items-center gap-2.5 rounded-xl border border-dashed border-primary-300 bg-primary-50/70 px-3.5 py-2.5 text-xs font-medium text-primary-800 dark:border-primary-500/40 dark:bg-primary-500/10 dark:text-primary-200 ${className ?? ''}`}>
- <svg
- className="h-4 w-4 shrink-0 text-primary-500"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- aria-hidden="true">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
- />
- </svg>
- <span>{t('orchPage.demo.banner')}</span>
- </div>
- );
-}
diff --git a/app/src/components/orchestration/demo/MedullaDemoChat.test.tsx b/app/src/components/orchestration/demo/MedullaDemoChat.test.tsx
deleted file mode 100644
index fb8db366a0..0000000000
--- a/app/src/components/orchestration/demo/MedullaDemoChat.test.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import MedullaDemoChat from './MedullaDemoChat';
-
-// Pass-through translator so assertions can target the i18n keys directly.
-vi.mock('../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (key: string) => key }) }));
-
-describe('MedullaDemoChat', () => {
- it('renders the demo transcript with a disabled, labelled send control', () => {
- render(<MedullaDemoChat />);
-
- expect(screen.getByTestId('orch-demo-chat')).toBeInTheDocument();
-
- const send = screen.getByRole('button', { name: 'orchPage.demo.chat.composerDisabled' });
- expect(send).toBeDisabled();
- expect(send).toHaveAttribute('data-slot', 'button');
- expect(send).toHaveAttribute('data-variant', 'tertiary');
- });
-});
diff --git a/app/src/components/orchestration/demo/MedullaDemoChat.tsx b/app/src/components/orchestration/demo/MedullaDemoChat.tsx
deleted file mode 100644
index fd5ac0b53c..0000000000
--- a/app/src/components/orchestration/demo/MedullaDemoChat.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * MedullaDemoChat — the scale showcase for the "Chat" tab shown to users
- * without Medulla access. A short, read-only orchestration conversation (the
- * orchestrator fanning work out to agents) with the composer disabled and a
- * preview banner. No live agent, no core RPC.
- */
-import { useT } from '../../../lib/i18n/I18nContext';
-import Button from '../../ui/Button';
-import DemoScaleBanner from './DemoScaleBanner';
-import { DEMO_CHAT } from './medullaDemoData';
-
-export default function MedullaDemoChat() {
- const { t } = useT();
-
- return (
- <div className="flex h-full flex-col" data-testid="orch-demo-chat">
- <div className="min-h-0 flex-1 overflow-y-auto">
- <div className="mx-auto w-full max-w-2xl space-y-4 px-4 py-6">
- <DemoScaleBanner />
-
- {DEMO_CHAT.map(msg => {
- if (msg.role === 'activity') {
- // Sub-agent activity line — a compact, centered status row.
- return (
- <div key={msg.id} className="flex items-center justify-center gap-2">
- <span className="h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-primary-500" />
- <span className="font-mono text-[11px] text-content-muted">{t(msg.textKey)}</span>
- </div>
- );
- }
- const isUser = msg.role === 'user';
- return (
- <div key={msg.id} className={`flex ${isUser ? 'justify-end' : 'justify-start'}`}>
- <div
- className={`max-w-[80%] rounded-2xl px-4 py-2.5 text-sm leading-relaxed shadow-soft ${
- isUser
- ? 'bg-primary-500 text-content-inverted'
- : 'border border-line bg-surface text-content'
- }`}>
- {t(msg.textKey)}
- </div>
- </div>
- );
- })}
- </div>
- </div>
-
- {/* Disabled composer — visually present, non-interactive. */}
- <div className="border-t border-line bg-surface/80 px-4 py-3">
- <div className="mx-auto flex w-full max-w-2xl items-center gap-2">
- <div
- aria-disabled="true"
- className="flex-1 cursor-not-allowed select-none rounded-xl border border-line bg-surface-subtle px-4 py-2.5 text-sm text-content-faint">
- {t('orchPage.demo.chat.composerDisabled')}
- </div>
- <Button
- variant="tertiary"
- size="md"
- iconOnly
- disabled
- aria-label={t('orchPage.demo.chat.composerDisabled')}
- className="h-9 w-9 shrink-0 cursor-not-allowed rounded-xl bg-surface-subtle text-content-faint disabled:pointer-events-auto disabled:opacity-100">
- <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
- />
- </svg>
- </Button>
- </div>
- </div>
- </div>
- );
-}
diff --git a/app/src/components/orchestration/demo/MedullaDemoGraph.tsx b/app/src/components/orchestration/demo/MedullaDemoGraph.tsx
deleted file mode 100644
index d85ca98864..0000000000
--- a/app/src/components/orchestration/demo/MedullaDemoGraph.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * MedullaDemoGraph — the scale showcase for the "Agent graph" tab shown to
- * users without Medulla access. An agent core, two devices, and 100 / 20 agents
- * fanning out under each device — rendered by the live {@link MemoryGraph}
- * force engine (drag / pan / zoom, fluid settle), with a preview banner.
- *
- * The `tuning` prop cranks repulsion and link length so the 120 nodes fan wide
- * out from the core instead of clumping — the "tree fanning out" look.
- */
-import { useMemo } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import { MemoryGraph } from '../../intelligence/MemoryGraph';
-import DemoScaleBanner from './DemoScaleBanner';
-import { buildDemoGraph } from './medullaDemoData';
-
-/** Wide fan-out: strong repulsion + long springs, weak centring pull. */
-const DEMO_TUNING = {
- chargeScale: 3.2,
- linkDistanceScale: 2.4,
- distanceMaxScale: 3,
- centerScale: 0.4,
-} as const;
-
-export default function MedullaDemoGraph() {
- const { t } = useT();
- const deviceLabel = t('orchPage.demo.device');
- const { nodes, edges } = useMemo(() => buildDemoGraph(deviceLabel), [deviceLabel]);
-
- return (
- <div className="relative h-full p-2" data-testid="orch-demo-graph">
- <div className="pointer-events-none absolute inset-x-0 top-2 z-10 flex justify-center px-3">
- <DemoScaleBanner className="pointer-events-auto max-w-xl shadow-soft" />
- </div>
- <MemoryGraph
- nodes={nodes}
- edges={edges}
- mode="contacts"
- rootLabel={t('orchPage.overview.core')}
- emptyHint={t('orchPage.overview.empty')}
- tuning={DEMO_TUNING}
- fill
- fitToBounds
- showLabels
- />
- </div>
- );
-}
diff --git a/app/src/components/orchestration/demo/MedullaDemoNetwork.tsx b/app/src/components/orchestration/demo/MedullaDemoNetwork.tsx
deleted file mode 100644
index c531c4ee07..0000000000
--- a/app/src/components/orchestration/demo/MedullaDemoNetwork.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * MedullaDemoNetwork — the scale showcase for the "Network" tab shown to users
- * without Medulla access. A busy grid of fake peer agents with mixed connection
- * states, behind the preview banner.
- */
-import { useMemo } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import DemoScaleBanner from './DemoScaleBanner';
-import { buildDemoPeers, type DemoPeerStatus } from './medullaDemoData';
-
-const STATUS_META: Record<DemoPeerStatus, { dot: string; text: string }> = {
- connected: { dot: 'bg-sage-500', text: 'text-sage-600 dark:text-sage-300' },
- connecting: { dot: 'bg-amber-500 animate-pulse', text: 'text-amber-600 dark:text-amber-300' },
- idle: { dot: 'bg-content-faint', text: 'text-content-faint' },
-};
-
-export default function MedullaDemoNetwork() {
- const { t } = useT();
- const peers = useMemo(() => buildDemoPeers(), []);
- const connectedCount = peers.filter(p => p.status === 'connected').length;
- const sessionCount = peers.reduce((sum, p) => sum + p.sessions, 0);
-
- return (
- <div
- className="mx-auto h-full w-full max-w-5xl overflow-y-auto p-4"
- data-testid="orch-demo-network">
- <div className="mx-auto max-w-3xl animate-fade-up space-y-4">
- <DemoScaleBanner />
-
- <div className="flex items-baseline justify-between px-1">
- <h2 className="text-sm font-semibold text-content">{t('orchPage.demo.networkTitle')}</h2>
- <p className="text-xs text-content-muted">
- {t('orchPage.demo.networkSummary')
- .replace('{peers}', String(connectedCount))
- .replace('{sessions}', String(sessionCount))}
- </p>
- </div>
-
- <div
- className="grid gap-2 sm:gap-3"
- style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(11rem, 1fr))' }}>
- {peers.map(peer => {
- const meta = STATUS_META[peer.status];
- return (
- <div
- key={peer.id}
- className="rounded-2xl border border-line bg-surface p-3 shadow-soft"
- data-testid={`orch-demo-peer-${peer.id}`}>
- <div className="flex items-center gap-2">
- <span className={`h-2 w-2 rounded-full ${meta.dot}`} aria-hidden="true" />
- <span className="truncate font-mono text-xs font-medium text-content">
- {peer.address}
- </span>
- </div>
- <p className={`mt-1.5 text-[11px] font-medium ${meta.text}`}>
- {t(`orchPage.demo.peer.${peer.status}`)}
- {peer.sessions > 0 && (
- <span className="text-content-faint">
- {' · '}
- {t('orchPage.demo.peerSessions').replace('{count}', String(peer.sessions))}
- </span>
- )}
- </p>
- </div>
- );
- })}
- </div>
- </div>
- </div>
- );
-}
diff --git a/app/src/components/orchestration/demo/medullaDemoData.ts b/app/src/components/orchestration/demo/medullaDemoData.ts
deleted file mode 100644
index a8b9c8fda7..0000000000
--- a/app/src/components/orchestration/demo/medullaDemoData.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-/**
- * medullaDemoData — deterministic, illustrative data for the Orchestration
- * "scale showcase" shown to users without Medulla access.
- *
- * Everything here is fake, generated from a fixed seed so the layout is stable
- * across renders (no re-simulation thrash). Labels are identifier-style tokens
- * (agent / session ids), not translatable prose — the only translated copy in
- * the demo lives in the surrounding chrome (banner, headings, task verbs).
- */
-import type { GraphEdge, GraphNode } from '../../../utils/tauriCommands';
-
-/** mulberry32 — tiny deterministic PRNG so the demo is stable per render. */
-function makeRng(seed: number): () => number {
- let a = seed >>> 0;
- return () => {
- a |= 0;
- a = (a + 0x6d2b79f5) | 0;
- let t = Math.imul(a ^ (a >>> 15), 1 | a);
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
- };
-}
-
-const OFFLINE_COLOR = '#6B7280';
-
-/** Vibrant palette for "active" sub-agents — the noise/chaos of live work. */
-const ACTIVE_COLORS = [
- '#4A83DD', // ocean (primary)
- '#22C55E', // sage
- '#F59E0B', // amber
- '#EF4444', // coral
- '#8B5CF6', // violet
- '#06B6D4', // cyan
- '#EC4899', // pink
-];
-
-function hex4(rng: () => number): string {
- return Math.floor(rng() * 0xffff)
- .toString(16)
- .padStart(4, '0');
-}
-
-// ── Demo agent graph ───────────────────────────────────────────────────────
-//
-// A central **agent core** with two **devices** hanging off it, and a busy
-// fan-out of agents under each device (100 on the first, 20 on the second).
-// Devices are `source` nodes (auto-linked to the synthetic core by the layout
-// engine); agents are `chunk` nodes linked to their device by an explicit edge.
-// The live MemoryGraph force engine lays it out — the orchestration overview
-// passes a high-repulsion tuning so the 120 nodes fan out wide from the core.
-
-/** How many agents fan out from each device (device 1 = 100, device 2 = 20). */
-const DEVICE_AGENT_COUNTS = [100, 20] as const;
-
-/**
- * Build the demo agent graph as force-engine nodes/edges.
- *
- * @param deviceLabel Localised word for "Device" — devices are labelled
- * `${deviceLabel} 1` / `${deviceLabel} 2`.
- */
-export function buildDemoGraph(deviceLabel: string): { nodes: GraphNode[]; edges: GraphEdge[] } {
- const rng = makeRng(0xc0ffee); // fixed seed → stable layout
- const nodes: GraphNode[] = [];
- const edges: GraphEdge[] = [];
-
- DEVICE_AGENT_COUNTS.forEach((agentCount, d) => {
- const deviceId = `device:${d}`;
- nodes.push({ kind: 'source', id: deviceId, label: `${deviceLabel} ${d + 1}` });
-
- for (let a = 0; a < agentCount; a++) {
- const online = rng() > 0.22;
- const color = online
- ? ACTIVE_COLORS[Math.floor(rng() * ACTIVE_COLORS.length)]
- : OFFLINE_COLOR;
- const agentId = `agent:${d}:${a}`;
- nodes.push({ kind: 'chunk', id: agentId, label: `0x${hex4(rng)}`, color });
- edges.push({ from: agentId, to: deviceId });
- }
- });
-
- return { nodes, edges };
-}
-
-// ── Demo peer network ──────────────────────────────────────────────────────
-
-export type DemoPeerStatus = 'connected' | 'connecting' | 'idle';
-
-interface DemoPeer {
- id: string;
- address: string;
- status: DemoPeerStatus;
- /** Number of live sub-agents under this peer. */
- sessions: number;
-}
-
-/** ~36 peer agents with mixed connection states for the network showcase. */
-export function buildDemoPeers(): DemoPeer[] {
- const rng = makeRng(0x1d3a);
- const peers: DemoPeer[] = [];
- for (let i = 0; i < 36; i++) {
- const r = rng();
- const status: DemoPeerStatus = r < 0.62 ? 'connected' : r < 0.85 ? 'connecting' : 'idle';
- peers.push({
- id: `peer-${i}`,
- address: `0x${hex4(rng)}…${hex4(rng)}`,
- status,
- sessions: status === 'connected' ? 1 + Math.floor(rng() * 12) : 0,
- });
- }
- return peers;
-}
-
-// ── Demo chat transcript ───────────────────────────────────────────────────
-
-type DemoChatRole = 'user' | 'assistant' | 'activity';
-
-interface DemoChatMessage {
- id: string;
- role: DemoChatRole;
- /** i18n key for the message body. */
- textKey: string;
-}
-
-/** A short orchestration conversation illustrating fan-out at scale. */
-export const DEMO_CHAT: DemoChatMessage[] = [
- { id: 'm1', role: 'user', textKey: 'orchPage.demo.chat.user1' },
- { id: 'm2', role: 'assistant', textKey: 'orchPage.demo.chat.assistant1' },
- { id: 'm3', role: 'activity', textKey: 'orchPage.demo.chat.activity1' },
- { id: 'm4', role: 'activity', textKey: 'orchPage.demo.chat.activity2' },
- { id: 'm5', role: 'activity', textKey: 'orchPage.demo.chat.activity3' },
- { id: 'm6', role: 'assistant', textKey: 'orchPage.demo.chat.assistant2' },
-];
diff --git a/app/src/components/orchestration/primitives.tsx b/app/src/components/orchestration/primitives.tsx
deleted file mode 100644
index 8226d9df42..0000000000
--- a/app/src/components/orchestration/primitives.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * Small presentational building blocks shared by the Orchestration sub-pages
- * (Connections / Discover / Usage). Pure, no data access.
- */
-import type { ReactNode } from 'react';
-
-/** A titled card surface used to group a panel section. */
-export function SectionCard({
- title,
- description,
- action,
- children,
- testId,
-}: {
- title?: ReactNode;
- description?: ReactNode;
- action?: ReactNode;
- children: ReactNode;
- testId?: string;
-}) {
- return (
- <section
- className="rounded-xl border border-line bg-surface p-4 shadow-soft"
- data-testid={testId}>
- {(title || action) && (
- <div className="mb-3 flex items-start justify-between gap-3">
- <div className="min-w-0">
- {title && <h3 className="text-sm font-semibold text-content">{title}</h3>}
- {description && <p className="mt-0.5 text-xs text-content-muted">{description}</p>}
- </div>
- {action}
- </div>
- )}
- {children}
- </section>
- );
-}
-
-/** A single metric tile: a big value over a muted label, with an optional hint. */
-export function StatTile({
- label,
- value,
- hint,
- testId,
-}: {
- label: ReactNode;
- value: ReactNode;
- hint?: ReactNode;
- testId?: string;
-}) {
- return (
- <div className="rounded-xl border border-line bg-surface p-4 shadow-soft" data-testid={testId}>
- <p className="text-xs font-medium uppercase tracking-wide text-content-muted">{label}</p>
- <p className="mt-1 text-2xl font-semibold tabular-nums text-content">{value}</p>
- {hint && <p className="mt-1 text-[11px] text-content-faint">{hint}</p>}
- </div>
- );
-}
diff --git a/app/src/components/settings/panels/AgentAccessPanel.tsx b/app/src/components/settings/panels/AgentAccessPanel.tsx
index 4064ff0bb8..b7052f8631 100644
--- a/app/src/components/settings/panels/AgentAccessPanel.tsx
+++ b/app/src/components/settings/panels/AgentAccessPanel.tsx
@@ -11,7 +11,6 @@ import {
type TrustedAccess,
type TrustedRoot,
} from '../../../utils/tauriCommands';
-import { openhumanCronList, openhumanCronUpdate } from '../../../utils/tauriCommands/cron';
import { Alert, AlertDescription } from '../../ui';
import Button from '../../ui/Button';
import {
@@ -60,16 +59,6 @@ const AgentAccessPanel = () => {
const [newRootPath, setNewRootPath] = useState('');
const [newRootAccess, setNewRootAccess] = useState<TrustedAccess>('read');
- // Autonomous tiny.place agent ("autopilot") — a seeded, *disabled* cron job
- // the user opts into here. It's not an autonomy field: we resolve its id by
- // name from the cron list and flip its `enabled` flag via cron_update. The
- // section only renders once the job is found (id known).
- const [autopilotJobId, setAutopilotJobId] = useState<string | null>(null);
- const [autopilotEnabled, setAutopilotEnabled] = useState(false);
- // Monotonic guard so rapid toggles can't resolve out-of-order and leave the
- // UI showing a stale enabled state (last write wins).
- const autopilotSeqRef = useRef(0);
-
// Action timeout (the tool/action wall-clock limit, issue #3100). Held as the
// raw input string so the field can be edited freely; validated on save.
const [timeoutInput, setTimeoutInput] = useState('');
@@ -110,20 +99,6 @@ const AgentAccessPanel = () => {
if (!cancelled)
setError(e instanceof Error ? e.message : t('settings.agentAccess.loadError'));
}
- try {
- // Resolve the seeded tinyplace_autopilot cron job by name so the toggle
- // below can flip its enabled flag. Non-fatal: the section just stays
- // hidden if the job isn't present or the list call fails.
- const cronResp = await openhumanCronList();
- if (cancelled) return;
- const autopilot = cronResp.result.find(j => j.name === 'tinyplace_autopilot');
- if (autopilot) {
- setAutopilotJobId(autopilot.id);
- setAutopilotEnabled(autopilot.enabled);
- }
- } catch {
- // Non-fatal — bounty-worker toggle stays hidden.
- }
try {
const agentResp = await openhumanGetAgentSettings();
if (cancelled) return;
@@ -152,7 +127,7 @@ const AgentAccessPanel = () => {
// Pass explicit `next` values (setState is async).
//
// `onError` lets a caller revert its own optimistic `setState` if the RPC
- // fails (mirrors `toggleAutopilot`'s revert-on-failure below) — otherwise a
+ // fails — otherwise a
// failed save leaves the switch showing the new value locally while the
// server-side field silently kept its old one.
const persist = async (
@@ -230,29 +205,6 @@ const AgentAccessPanel = () => {
);
};
- // The autopilot is a cron job, not an autonomy field — flip its `enabled`
- // flag directly via cron_update. Optimistic, with revert on failure, and a
- // sequence guard so only the most recent toggle writes UI state back.
- const toggleAutopilot = async (next: boolean) => {
- if (!autopilotJobId || !isTauri()) return;
- const seq = ++autopilotSeqRef.current;
- const prev = autopilotEnabled;
- setAutopilotEnabled(next);
- setError(null);
- setSavedNote(null);
- try {
- await openhumanCronUpdate(autopilotJobId, { enabled: next });
- if (autopilotSeqRef.current === seq) {
- setSavedNote(t('settings.agentAccess.saved'));
- }
- } catch (e) {
- if (autopilotSeqRef.current === seq) {
- setAutopilotEnabled(prev);
- setError(e instanceof Error ? e.message : t('settings.agentAccess.saveError'));
- }
- }
- };
-
const addRoot = () => {
const path = newRootPath.trim();
if (!path) return;
@@ -398,27 +350,6 @@ const AgentAccessPanel = () => {
/>
</SettingsSection>
- {/* Autonomous tiny.place agent (opt-in). Only shown once the seeded
- cron job is found, so users without it never see a dead toggle. */}
- {autopilotJobId && (
- <SettingsSection
- title={t('settings.agentAccess.tinyplaceAutopilot.title')}
- description={t('settings.agentAccess.tinyplaceAutopilot.desc')}>
- <SettingsRow
- htmlFor="switch-tinyplace-autopilot"
- label={t('settings.agentAccess.tinyplaceAutopilot.label')}
- control={
- <SettingsSwitch
- id="switch-tinyplace-autopilot"
- checked={autopilotEnabled}
- onCheckedChange={next => void toggleAutopilot(next)}
- aria-label={t('settings.agentAccess.tinyplaceAutopilot.label')}
- />
- }
- />
- </SettingsSection>
- )}
-
{/* Action timeout */}
<SettingsSection
title={t('settings.agentAccess.timeout.label')}
diff --git a/app/src/components/settings/panels/__tests__/AgentAccessPanel.test.tsx b/app/src/components/settings/panels/__tests__/AgentAccessPanel.test.tsx
index 8ac3b72021..e050f27973 100644
--- a/app/src/components/settings/panels/__tests__/AgentAccessPanel.test.tsx
+++ b/app/src/components/settings/panels/__tests__/AgentAccessPanel.test.tsx
@@ -11,11 +11,6 @@ import {
openhumanUpdateAgentSettings,
openhumanUpdateAutonomySettings,
} from '../../../../utils/tauriCommands';
-import {
- type CoreCronJob,
- openhumanCronList,
- openhumanCronUpdate,
-} from '../../../../utils/tauriCommands/cron';
import AgentAccessPanel from '../AgentAccessPanel';
// ──────────────────────────────────────────────────────────────────────────────
@@ -72,36 +67,10 @@ vi.mock('../../../../utils/tauriCommands', async () => {
};
});
-vi.mock('../../../../utils/tauriCommands/cron', () => ({
- openhumanCronList: vi.fn(),
- openhumanCronUpdate: vi.fn(),
-}));
-
const mockGet = vi.mocked(openhumanGetAutonomySettings);
const mockUpdate = vi.mocked(openhumanUpdateAutonomySettings);
const mockGetAgent = vi.mocked(openhumanGetAgentSettings);
const mockUpdateAgent = vi.mocked(openhumanUpdateAgentSettings);
-const mockCronList = vi.mocked(openhumanCronList);
-const mockCronUpdate = vi.mocked(openhumanCronUpdate);
-
-// Minimal CoreCronJob for the seeded, disabled tinyplace_autopilot job.
-const autopilotJob = (overrides: Partial<CoreCronJob> = {}): CoreCronJob =>
- ({
- id: 'tp-1',
- name: 'tinyplace_autopilot',
- enabled: false,
- expression: '',
- schedule: { kind: 'every', every_ms: 3600000 } as never,
- command: '',
- job_type: 'agent',
- session_target: 'isolated',
- delivery: { mode: 'proactive', best_effort: true },
- delete_after_run: false,
- created_at: '',
- next_run: '',
- ...overrides,
- }) as CoreCronJob;
-
describe('AgentAccessPanel (advanced)', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -110,8 +79,6 @@ describe('AgentAccessPanel (advanced)', () => {
mockUpdate.mockResolvedValue({ result: {} as never, logs: [] });
mockGetAgent.mockResolvedValue({ result: agentSettings(), logs: [] });
mockUpdateAgent.mockResolvedValue({ result: {} as never, logs: [] });
- mockCronList.mockResolvedValue({ result: [autopilotJob()], logs: [] });
- mockCronUpdate.mockResolvedValue({ result: autopilotJob({ enabled: true }), logs: [] });
});
it('loads settings on mount and renders the advanced controls', async () => {
@@ -148,38 +115,6 @@ describe('AgentAccessPanel (advanced)', () => {
);
});
- it('renders the autopilot toggle when the seeded job is present', async () => {
- renderWithProviders(<AgentAccessPanel />);
- await waitFor(() => expect(mockCronList).toHaveBeenCalledTimes(1));
- const sw = await screen.findByRole('switch', { name: /run automatically/i });
- expect(sw).toHaveAttribute('aria-checked', 'false');
- });
-
- it('enabling the autopilot flips its cron job enabled flag', async () => {
- renderWithProviders(<AgentAccessPanel />);
- const sw = await screen.findByRole('switch', { name: /run automatically/i });
- fireEvent.click(sw);
- await waitFor(() => expect(mockCronUpdate).toHaveBeenCalledWith('tp-1', { enabled: true }));
- });
-
- it('reverts the autopilot toggle when the cron update fails', async () => {
- mockCronUpdate.mockRejectedValueOnce(new Error('boom'));
- renderWithProviders(<AgentAccessPanel />);
- const sw = await screen.findByRole('switch', { name: /run automatically/i });
- fireEvent.click(sw);
- // The update RPC must actually be attempted (and fail)…
- await waitFor(() => expect(mockCronUpdate).toHaveBeenCalledWith('tp-1', { enabled: true }));
- // …then the optimistic flip reverts to off after the failure settles.
- await waitFor(() => expect(sw).toHaveAttribute('aria-checked', 'false'));
- });
-
- it('hides the autopilot toggle when no seeded job exists', async () => {
- mockCronList.mockResolvedValue({ result: [], logs: [] });
- renderWithProviders(<AgentAccessPanel />);
- await screen.findByText('Confine to workspace');
- expect(screen.queryByRole('switch', { name: /run automatically/i })).not.toBeInTheDocument();
- });
-
it('adding then removing a granted folder persists the updated list', async () => {
renderWithProviders(<AgentAccessPanel />);
await screen.findByText('Granted folders');
diff --git a/app/src/components/settings/settingsRouteElements.tsx b/app/src/components/settings/settingsRouteElements.tsx
index d2fff49f81..6fcedaa1b9 100644
--- a/app/src/components/settings/settingsRouteElements.tsx
+++ b/app/src/components/settings/settingsRouteElements.tsx
@@ -157,8 +157,8 @@ export function settingsRouteElements(): ReactNode {
<Route path="agent-chat" element={<Navigate to="/connections?tab=llm" replace />} />
{/* Schedules live on the Workflows page now (`/flows?view=schedules`). */}
<Route path="cron-jobs" element={<Navigate to="/flows?view=schedules" replace />} />
- {/* Tasks now live on Brain's Orchestration Kanban board. */}
- <Route path="tasks" element={<Navigate to="/brain?tab=orchestration&ov=tasks" replace />} />
+ {/* Tasks are represented by goals on the Brain page. */}
+ <Route path="tasks" element={<Navigate to="/brain?tab=goals" replace />} />
{/* Workflows is a first-level module now — /settings/automations bounces
to /flows (the Workflows page). */}
<Route path="automations" element={<Navigate to="/flows" replace />} />
diff --git a/app/src/config/navConfig.ts b/app/src/config/navConfig.ts
index 09db12d9bd..2dcb15eba0 100644
--- a/app/src/config/navConfig.ts
+++ b/app/src/config/navConfig.ts
@@ -30,10 +30,6 @@ export interface NavTab {
* Ordered list of sidebar nav entries:
* chat → brain → flows → connections → rewards
*
- * Orchestration (TinyPlace multi-agent coordination) is no longer a top-level
- * tab — it was folded back under Brain as the `/brain?tab=orchestration`
- * sub-tab, so the sidebar stays lean.
- *
* Human has no primary tab: `/human` is reached from the chat composer, whose
* primary button becomes the mascot when there is nothing to send (see
* `ComposerIdleAction` in `AssistantUiChat`), so a sidebar row would be a
diff --git a/app/src/hooks/useFlowRunProgress.ts b/app/src/hooks/useFlowRunProgress.ts
index b208eb0572..cd6b83f279 100644
--- a/app/src/hooks/useFlowRunProgress.ts
+++ b/app/src/hooks/useFlowRunProgress.ts
@@ -15,7 +15,7 @@
* This is a *live overlay only* — the durable `flow_runs` row remains the source
* of truth and {@link useFlowRunPoller} stays as the 2s fallback, so a dropped
* broadcast (lag) merely delays the animation, never corrupts run history. The
- * subscription mirrors {@link useTinyplaceStream} exactly (socketService.on/off
+ * subscription uses the standard socketService on/off lifecycle
* with cleanup on unmount / dependency change).
*/
import debug from 'debug';
diff --git a/app/src/hooks/useTinyPlaceIdentity.test.ts b/app/src/hooks/useTinyPlaceIdentity.test.ts
deleted file mode 100644
index b8c2bbe503..0000000000
--- a/app/src/hooks/useTinyPlaceIdentity.test.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import { act, renderHook, waitFor } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { __resetTinyPlaceIdentityForTests, useTinyPlaceIdentity } from './useTinyPlaceIdentity';
-
-const selfIdentity = vi.fn();
-vi.mock('../lib/orchestration/orchestrationClient', () => ({
- orchestrationClient: { selfIdentity: () => selfIdentity() },
-}));
-
-// The wallet gate (#5805) runs before every identity fetch. Mock it here so the
-// pre-existing cases below are deterministic rather than depending on a real
-// `wallet_status` RPC failing into the `unknown` fall-through; `beforeEach`
-// defaults it to a configured wallet, which is the path they were written for.
-const fetchWalletStatus = vi.fn();
-vi.mock('../services/walletApi', () => ({ fetchWalletStatus: () => fetchWalletStatus() }));
-
-describe('useTinyPlaceIdentity (#5424)', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- fetchWalletStatus.mockResolvedValue({ configured: true });
- __resetTinyPlaceIdentityForTests();
- });
-
- afterEach(() => {
- __resetTinyPlaceIdentityForTests();
- vi.useRealTimers();
- });
-
- // #5805 — `selfIdentity()` derives a tiny.place signer from the wallet, so a
- // wallet-less user could only ever get a rejection, which the retry ladder
- // then repeated: 55 error-level reports in 72 minutes on one session.
- // `wallet_status` answers the same question without erroring, so the call is
- // never made.
- it('never calls selfIdentity when no wallet is configured', async () => {
- fetchWalletStatus.mockResolvedValue({ configured: false });
- const { result } = renderHook(() => useTinyPlaceIdentity());
-
- await waitFor(() => expect(result.current.status).toBe('ready'));
- expect(result.current.hasIdentity).toBe(false);
- expect(selfIdentity).not.toHaveBeenCalled();
- });
-
- // The gate fires only on a POSITIVE "no wallet". If `wallet_status` itself
- // fails we cannot prove the wallet is absent, so the call must still go out —
- // otherwise a transport blip would hide a real identity. The core boundary
- // classifier stays as defense-in-depth for whatever comes back.
- it('still calls selfIdentity when wallet status is inconclusive', async () => {
- fetchWalletStatus.mockRejectedValue(new Error('rpc transport failed'));
- selfIdentity.mockResolvedValue({ agentId: 'agent-123', handles: [], discoverable: true });
- const { result } = renderHook(() => useTinyPlaceIdentity());
-
- await waitFor(() => expect(result.current.status).toBe('ready'));
- expect(selfIdentity).toHaveBeenCalledTimes(1);
- expect(result.current.hasIdentity).toBe(true);
- });
-
- it('reports an identity when the RPC returns a non-empty agentId', async () => {
- selfIdentity.mockResolvedValue({ agentId: 'agent-123', handles: [], discoverable: true });
- const { result } = renderHook(() => useTinyPlaceIdentity());
-
- await waitFor(() => expect(result.current.status).toBe('ready'));
- expect(result.current.hasIdentity).toBe(true);
- });
-
- it('reports no identity when the agentId is blank', async () => {
- selfIdentity.mockResolvedValue({ agentId: ' ', handles: [], discoverable: false });
- const { result } = renderHook(() => useTinyPlaceIdentity());
-
- await waitFor(() => expect(result.current.status).toBe('ready'));
- expect(result.current.hasIdentity).toBe(false);
- });
-
- it('stays fail-closed (hidden) while a rejected check is retried', async () => {
- selfIdentity.mockRejectedValue(new Error('wallet locked'));
- const { result } = renderHook(() => useTinyPlaceIdentity());
-
- await waitFor(() => expect(result.current.status).toBe('ready'));
- expect(result.current.hasIdentity).toBe(false);
- });
-
- it('fetches once and shares the result across consumers', async () => {
- selfIdentity.mockResolvedValue({ agentId: 'agent-123', handles: [], discoverable: true });
- const first = renderHook(() => useTinyPlaceIdentity());
- const second = renderHook(() => useTinyPlaceIdentity());
-
- await waitFor(() => expect(first.result.current.status).toBe('ready'));
- expect(second.result.current.hasIdentity).toBe(true);
- // A single resolved RPC backs every consumer for the app session.
- expect(selfIdentity).toHaveBeenCalledTimes(1);
- });
-
- it('retries after a transient failure and recovers without a restart (#5439 review)', async () => {
- vi.useFakeTimers();
- selfIdentity
- .mockRejectedValueOnce(new Error('wallet locked at startup'))
- .mockResolvedValue({ agentId: 'agent-123', handles: [], discoverable: true });
- const { result } = renderHook(() => useTinyPlaceIdentity());
-
- // First attempt fails → fail-closed (hidden), but a backoff retry is queued.
- await act(async () => {
- await vi.advanceTimersByTimeAsync(0);
- });
- expect(result.current).toEqual({ status: 'ready', hasIdentity: false });
-
- // The retry fires and succeeds → a real holder is no longer locked out.
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2000);
- });
- expect(result.current.hasIdentity).toBe(true);
- });
-
- it('re-checks immediately on window focus after a failed startup check (#5439 review)', async () => {
- selfIdentity
- .mockRejectedValueOnce(new Error('wallet locked'))
- .mockResolvedValue({ agentId: 'agent-123', handles: [], discoverable: true });
- const { result } = renderHook(() => useTinyPlaceIdentity());
-
- await waitFor(() => expect(result.current.status).toBe('ready'));
- expect(result.current.hasIdentity).toBe(false);
-
- // The user unlocks their wallet and returns to the app.
- await act(async () => {
- window.dispatchEvent(new Event('focus'));
- });
- await waitFor(() => expect(result.current.hasIdentity).toBe(true));
- });
-});
diff --git a/app/src/hooks/useTinyPlaceIdentity.ts b/app/src/hooks/useTinyPlaceIdentity.ts
deleted file mode 100644
index 67851c58f9..0000000000
--- a/app/src/hooks/useTinyPlaceIdentity.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-/**
- * Whether this user has set up a tiny.place identity (#5424).
- *
- * tiny.place is being removed from the app after 31 August 2026. Its entry
- * points must be shown only to users who already have an identity — everyone
- * else never really started, so there is nothing to preserve and no reason to
- * advertise a feature that is about to disappear.
- *
- * The authoritative signal is the orchestration self-identity RPC: a non-empty
- * `agentId` means the wallet-backed identity exists.
- *
- * Failure handling is deliberate. A *resolved* call (identity present or absent)
- * is terminal and cached for the session. A *rejected* call is treated as
- * transient — the wallet/keyring can be locked during startup, or the relay can
- * blip — so it must NOT permanently hide tiny.place from a real holder. On
- * rejection we stay fail-closed (hidden) for the moment but keep retrying with a
- * bounded backoff, and re-attempt when the window regains focus (e.g. after the
- * user unlocks their wallet), so a one-time startup failure never locks a holder
- * out until an app restart.
- *
- * The check is shared module-side, so the several gates that read it (the
- * Brain orchestration sub-tab, the notice) share a single in-flight request
- * rather than each firing their own.
- */
-import { useEffect, useState } from 'react';
-
-import { orchestrationClient } from '../lib/orchestration/orchestrationClient';
-import { resolveWalletConfigured } from './useWalletConfigured';
-
-export interface TinyPlaceIdentityState {
- /** `loading` until the RPC first settles; `ready` once we have an answer. */
- status: 'loading' | 'ready';
- /** True only when a tiny.place identity exists for this user. */
- hasIdentity: boolean;
-}
-
-/** Bounded backoff (ms) between retries after a transient failure. */
-const RETRY_DELAYS_MS = [2000, 5000, 10000];
-
-let cache: TinyPlaceIdentityState = { status: 'loading', hasIdentity: false };
-let resolved = false; // the RPC returned a definitive answer — stop retrying
-let inFlight = false;
-let retryTimer: ReturnType<typeof setTimeout> | null = null;
-const listeners = new Set<() => void>();
-
-function publish(next: TinyPlaceIdentityState) {
- cache = next;
- listeners.forEach(listener => listener());
-}
-
-async function attemptLoad(attempt: number) {
- if (resolved || inFlight) return;
- inFlight = true;
- try {
- // Gate on wallet status before the wallet-requiring call. `selfIdentity()`
- // builds the tiny.place client from a wallet-derived seed, so for a user
- // with no wallet it can only reject — and the retry ladder below then
- // repeats that rejection, which is how one wallet-less session produced 55
- // error-level reports in 72 minutes (#5805). `wallet_status` answers the
- // same question and resolves normally, so ask it instead of provoking the
- // error. Only a positive `no` skips: `unknown` (status fetch itself failed)
- // falls through so a transport blip never hides a real identity.
- //
- // Deliberately does NOT set `resolved` — that flag ends retrying forever,
- // and a user who sets up a wallet later in the session must still be picked
- // up by the next `ensureLoad()`. Returning without scheduling a retry is
- // enough to stop the ladder.
- if ((await resolveWalletConfigured()) === 'no') {
- publish({ status: 'ready', hasIdentity: false });
- return;
- }
- const identity = await orchestrationClient.selfIdentity();
- resolved = true;
- if (retryTimer) {
- clearTimeout(retryTimer);
- retryTimer = null;
- }
- publish({ status: 'ready', hasIdentity: identity.agentId.trim().length > 0 });
- } catch {
- // Transient: stay fail-closed (hidden) but schedule a bounded retry so a
- // real holder is not locked out for the whole session by a startup blip.
- publish({ status: 'ready', hasIdentity: false });
- const delay = RETRY_DELAYS_MS[attempt];
- if (delay !== undefined && !retryTimer) {
- retryTimer = setTimeout(() => {
- retryTimer = null;
- void attemptLoad(attempt + 1);
- }, delay);
- }
- } finally {
- inFlight = false;
- }
-}
-
-/** Kick a load if one isn't already settled, in flight, or scheduled. */
-function ensureLoad() {
- if (!resolved && !inFlight && !retryTimer) void attemptLoad(0);
-}
-
-/** Test seam — clears the module cache so each test starts from `loading`. */
-export function __resetTinyPlaceIdentityForTests() {
- cache = { status: 'loading', hasIdentity: false };
- resolved = false;
- inFlight = false;
- if (retryTimer) {
- clearTimeout(retryTimer);
- retryTimer = null;
- }
- listeners.clear();
-}
-
-export function useTinyPlaceIdentity(): TinyPlaceIdentityState {
- const [state, setState] = useState<TinyPlaceIdentityState>(cache);
-
- useEffect(() => {
- const sync = () => setState(cache);
- listeners.add(sync);
- ensureLoad();
- // If the first check failed and the user later unlocks their wallet, a
- // window refocus re-attempts immediately (cancelling any pending backoff) so
- // a real holder isn't hidden until restart.
- const onFocus = () => {
- if (resolved || inFlight) return;
- if (retryTimer) {
- clearTimeout(retryTimer);
- retryTimer = null;
- }
- void attemptLoad(0);
- };
- window.addEventListener('focus', onFocus);
- // Adopt the current cache in case it resolved between the initial render and
- // this effect firing (or a sibling hook already loaded it).
- sync();
- return () => {
- listeners.delete(sync);
- window.removeEventListener('focus', onFocus);
- };
- }, []);
-
- return state;
-}
diff --git a/app/src/hooks/useWalletConfigured.ts b/app/src/hooks/useWalletConfigured.ts
index 072805c740..eec0ce76cd 100644
--- a/app/src/hooks/useWalletConfigured.ts
+++ b/app/src/hooks/useWalletConfigured.ts
@@ -3,8 +3,8 @@
*
* ## Why this exists
*
- * Several core RPCs derive a key from the local wallet before they can run
- * (the tiny.place signer seed, EVM signing, balances, deBridge quotes). When no
+ * Several core RPCs require the local wallet before they can run
+ * (EVM signing, balances, deBridge quotes). When no
* wallet is set up they reject with the core's `WALLET_NOT_CONFIGURED_MESSAGE`.
* That is an *expected* state — a wallet is optional and most users never
* create one — but it still travels as an `Err`, so every such call becomes an
@@ -17,13 +17,8 @@
* question and resolves normally for a wallet-less user, so the gate costs one
* non-erroring RPC and removes an erroring one.
*
- * This pairs prevention-at-source with boundary classification, which is the
- * shape the same bug was fixed in for the tiny.place home feed in #3964
- * (commits `1d42c766e` + `02f9769bc`). That gate lived privately inside
- * `agentworld/pages/FeedSection.tsx` and was deleted wholesale with the
- * `agentworld` module in `779aa2f3a`, leaving only the classifier half — which
- * is part of why the same class recurred as #5805. It is shared here so the
- * next wallet-gated caller inherits it instead of re-deriving it.
+ * This pairs prevention-at-source with boundary classification so the next
+ * wallet-gated caller inherits the guard instead of re-deriving it.
*
* ## The `unknown` state is load-bearing
*
@@ -57,10 +52,8 @@ export type WalletConfigured = 'resolving' | 'no' | 'yes' | 'unknown';
/**
* Resolve the wallet-configured state once, outside React.
*
- * Exposed for callers that are not components — `useTinyPlaceIdentity` drives a
- * module-level singleton and cannot use a hook. Never rejects: a failed status
- * fetch becomes `unknown`, so a caller can always `await` it inline before
- * deciding whether to make its wallet-gated call.
+ * Exposed for callers that are not components. Never rejects: a failed status
+ * fetch becomes `unknown`.
*/
export async function resolveWalletConfigured(): Promise<Exclude<WalletConfigured, 'resolving'>> {
try {
diff --git a/app/src/lib/agentworld/apiClient.ts b/app/src/lib/agentworld/apiClient.ts
deleted file mode 100644
index 120072d7e0..0000000000
--- a/app/src/lib/agentworld/apiClient.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/**
- * Shared tiny.place orchestration API client.
- *
- * One client instance per app lifetime — the underlying calls go through
- * `callCoreRpc`, which manages its own connection lifecycle, so there is
- * nothing per-mount to own here.
- *
- * This singleton used to live in `agentworld/AgentWorldShell.tsx`. That surface
- * (the in-app Agent World section) was removed with #5424; the client itself
- * outlived it because the Brain orchestration sub-tab, the orchestration panels
- * and the pairing hook all still call tiny.place through it. It now sits next
- * to its factory so the surviving consumers do not depend on a deleted screen.
- */
-import { createInvokeApiClient } from './invokeApiClient';
-
-export const apiClient = createInvokeApiClient();
diff --git a/app/src/lib/agentworld/invokeApiClient.test.ts b/app/src/lib/agentworld/invokeApiClient.test.ts
deleted file mode 100644
index a48a30f4a7..0000000000
--- a/app/src/lib/agentworld/invokeApiClient.test.ts
+++ /dev/null
@@ -1,1806 +0,0 @@
-/**
- * Unit tests for the Agent World invoke API client bridge.
- *
- * Mocks `callCoreRpc` and asserts:
- * 1. Each client method calls the correct `openhuman.tinyplace_*` RPC method.
- * 2. Parameters are marshalled correctly.
- * 3. A `PAYMENT_REQUIRED:` rejection becomes a `PaymentRequiredError`.
- * 4. Other errors propagate unchanged.
- */
-import { beforeEach, describe, expect, type Mock, test, vi } from 'vitest';
-
-import { callCoreRpc } from '../../services/coreRpcClient';
-import { createInvokeApiClient, PaymentRequiredError } from './invokeApiClient';
-
-vi.mock('../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-const mockCallCoreRpc = callCoreRpc as Mock;
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-// ── directory.listAgents ──────────────────────────────────────────────────────
-
-describe('directory.listAgents', () => {
- test('calls openhuman.tinyplace_directory_list_agents with params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agents: [] });
- const client = createInvokeApiClient();
- const params = { q: 'ai assistant', limit: 10 };
- await client.directory.listAgents(params);
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_directory_list_agents',
- params: { params },
- });
- });
-
- test('calls without params (null)', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agents: [] });
- const client = createInvokeApiClient();
- await client.directory.listAgents();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_directory_list_agents',
- params: { params: null },
- });
- });
-
- test('returns the response from core', async () => {
- const mockResponse = { agents: [{ agentId: 'abc123', name: 'Test Agent' }] };
- mockCallCoreRpc.mockResolvedValueOnce(mockResponse);
- const client = createInvokeApiClient();
- const result = await client.directory.listAgents();
- expect(result).toEqual(mockResponse);
- });
-});
-
-// ── directory.getAgent ────────────────────────────────────────────────────────
-
-describe('directory.getAgent', () => {
- test('calls openhuman.tinyplace_directory_get_agent with agentId', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agentId: 'abc123' });
- const client = createInvokeApiClient();
- await client.directory.getAgent('abc123');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_directory_get_agent',
- params: { agentId: 'abc123' },
- });
- });
-});
-
-// ── explorer.overview ─────────────────────────────────────────────────────────
-
-describe('explorer.overview', () => {
- test('calls openhuman.tinyplace_explorer_overview with no params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ totalAgents: 42 });
- const client = createInvokeApiClient();
- await client.explorer.overview();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_explorer_overview',
- params: undefined,
- });
- });
-});
-
-// ── search.unified ────────────────────────────────────────────────────────────
-
-describe('search.unified', () => {
- test('calls openhuman.tinyplace_search_unified with query', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ results: [] });
- const client = createInvokeApiClient();
- await client.search.unified('coding assistant');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_search_unified',
- params: { query: 'coding assistant' },
- });
- });
-});
-
-// ── directory.resolve ─────────────────────────────────────────────────────────
-
-describe('directory.resolve', () => {
- test('calls openhuman.tinyplace_directory_resolve with name', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ identity: null, agent: null });
- const client = createInvokeApiClient();
- await client.directory.resolve('alice.agent');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_directory_resolve',
- params: { name: 'alice.agent' },
- });
- });
-
- test('returns the ResolveResponse from core', async () => {
- const mockResponse = { identity: { name: 'alice.agent' }, agent: null };
- mockCallCoreRpc.mockResolvedValueOnce(mockResponse);
- const client = createInvokeApiClient();
- const result = await client.directory.resolve('alice.agent');
- expect(result).toEqual(mockResponse);
- });
-});
-
-// ── directory.reverse ─────────────────────────────────────────────────────────
-
-describe('directory.reverse', () => {
- test('calls openhuman.tinyplace_directory_reverse with cryptoId', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ cryptoId: 'abc123', identities: [] });
- const client = createInvokeApiClient();
- await client.directory.reverse('HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_directory_reverse',
- params: { cryptoId: 'HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk' },
- });
- });
-});
-
-// ── directory.listIdentities ──────────────────────────────────────────────────
-
-describe('directory.listIdentities', () => {
- test('calls openhuman.tinyplace_directory_list_identities with params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ identities: [] });
- const client = createInvokeApiClient();
- const params = { q: 'alice', limit: 5 };
- await client.directory.listIdentities(params);
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_directory_list_identities',
- params: { params },
- });
- });
-
- test('calls without params (null)', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ identities: [] });
- const client = createInvokeApiClient();
- await client.directory.listIdentities();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_directory_list_identities',
- params: { params: null },
- });
- });
-});
-
-// ── directory.skills ──────────────────────────────────────────────────────────
-
-describe('directory.skills', () => {
- test('calls openhuman.tinyplace_directory_skills with params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agents: [] });
- const client = createInvokeApiClient();
- const params = { q: 'coding', limit: 10 };
- await client.directory.skills(params);
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_directory_skills',
- params: { params },
- });
- });
-
- test('calls without params (null)', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agents: [] });
- const client = createInvokeApiClient();
- await client.directory.skills();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_directory_skills',
- params: { params: null },
- });
- });
-});
-
-// ── contacts ─────────────────────────────────────────────────────────────────
-
-describe('contacts', () => {
- test.each([
- ['request', 'openhuman.tinyplace_contacts_request', { agentId: '@worker' }],
- ['accept', 'openhuman.tinyplace_contacts_accept', { agentId: '@worker' }],
- ['remove', 'openhuman.tinyplace_contacts_remove', { agentId: '@worker' }],
- ['block', 'openhuman.tinyplace_contacts_block', { agentId: '@worker' }],
- ['unblock', 'openhuman.tinyplace_contacts_unblock', { agentId: '@worker' }],
- ['status', 'openhuman.tinyplace_contacts_status', { agentId: '@worker' }],
- ] as const)('calls %s with agentId', async (methodName, rpcMethod, params) => {
- mockCallCoreRpc.mockResolvedValueOnce({ ok: true });
- const client = createInvokeApiClient();
-
- await client.contacts[methodName]('@worker');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: rpcMethod, params });
- });
-
- test.each([
- ['list', 'openhuman.tinyplace_contacts_list'],
- ['requests', 'openhuman.tinyplace_contacts_requests'],
- ] as const)('calls %s with default null params', async (methodName, rpcMethod) => {
- mockCallCoreRpc.mockResolvedValueOnce({});
- const client = createInvokeApiClient();
-
- await client.contacts[methodName]();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: rpcMethod, params: { params: null } });
- });
-
- test.each([
- ['list', 'openhuman.tinyplace_contacts_list'],
- ['requests', 'openhuman.tinyplace_contacts_requests'],
- ] as const)('calls %s with provided params', async (methodName, rpcMethod) => {
- mockCallCoreRpc.mockResolvedValueOnce({});
- const client = createInvokeApiClient();
- const params = { limit: 25, cursor: 'next' };
-
- await client.contacts[methodName](params);
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: rpcMethod, params: { params } });
- });
-
- test('calls stats without params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ contactCount: 1 });
- const client = createInvokeApiClient();
-
- await client.contacts.stats();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_contacts_stats',
- params: {},
- });
- });
-});
-
-// ── orchestrationPairing ─────────────────────────────────────────────────────
-
-describe('orchestrationPairing', () => {
- test('calls list without params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ records: [] });
- const client = createInvokeApiClient();
-
- await client.orchestrationPairing.list();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.orchestration_pairing_list',
- params: {},
- });
- });
-
- test.each([
- ['acceptRequest', 'openhuman.orchestration_pairing_accept_request', { agentId: '@worker' }],
- ['declineRequest', 'openhuman.orchestration_pairing_decline_request', { agentId: '@worker' }],
- ['blockRequest', 'openhuman.orchestration_pairing_block_request', { agentId: '@worker' }],
- ] as const)('calls %s with agentId', async (methodName, rpcMethod, params) => {
- mockCallCoreRpc.mockResolvedValueOnce({ record: null, remote: {} });
- const client = createInvokeApiClient();
-
- await client.orchestrationPairing[methodName]('@worker');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: rpcMethod, params });
- });
-
- test('calls linkSession with default null label', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ record: null, remote: {} });
- const client = createInvokeApiClient();
-
- await client.orchestrationPairing.linkSession('@worker');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.orchestration_pairing_link_session',
- params: { agentId: '@worker', label: null },
- });
- });
-
- test('calls linkSession with provided label', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ record: null, remote: {} });
- const client = createInvokeApiClient();
-
- await client.orchestrationPairing.linkSession('@worker', 'Worker session');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.orchestration_pairing_link_session',
- params: { agentId: '@worker', label: 'Worker session' },
- });
- });
-});
-
-// ── PaymentRequiredError ──────────────────────────────────────────────────────
-
-describe('PaymentRequiredError propagation', () => {
- test('402 string rejection becomes PaymentRequiredError', async () => {
- const challenge = { error: 'payment required', payment: { scheme: 'x402', amount: '0.01' } };
- mockCallCoreRpc.mockRejectedValueOnce(
- new Error(`PAYMENT_REQUIRED:${JSON.stringify(challenge)}`)
- );
- const client = createInvokeApiClient();
- await expect(client.explorer.overview()).rejects.toBeInstanceOf(PaymentRequiredError);
- });
-
- test('PaymentRequiredError.challenge contains the parsed challenge', async () => {
- const challenge = { error: 'payment required', payment: { scheme: 'x402', amount: '0.01' } };
- mockCallCoreRpc.mockRejectedValueOnce(
- new Error(`PAYMENT_REQUIRED:${JSON.stringify(challenge)}`)
- );
- const client = createInvokeApiClient();
- let caught: PaymentRequiredError | null = null;
- try {
- await client.search.unified('test');
- } catch (e) {
- caught = e as PaymentRequiredError;
- }
- expect(caught).toBeInstanceOf(PaymentRequiredError);
- expect(caught?.challenge).toEqual(challenge);
- });
-
- test('non-402 errors propagate unchanged', async () => {
- const networkErr = new Error('network failure');
- mockCallCoreRpc.mockRejectedValueOnce(networkErr);
- const client = createInvokeApiClient();
- await expect(client.directory.listAgents()).rejects.toBe(networkErr);
- });
-});
-
-// ── profiles.get ─────────────────────────────────────────────────────────────
-
-describe('profiles.get', () => {
- test('calls openhuman.tinyplace_profiles_get with username', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ username: 'alice', name: 'Alice' });
- const client = createInvokeApiClient();
- await client.profiles.get('alice');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_profiles_get',
- params: { username: 'alice' },
- });
- });
-
- test('returns the AgentProfile from core', async () => {
- const profile = { username: 'bob', name: 'Bob', cryptoId: 'abc123' };
- mockCallCoreRpc.mockResolvedValueOnce(profile);
- const client = createInvokeApiClient();
- const result = await client.profiles.get('bob');
- expect(result).toEqual(profile);
- });
-});
-
-// ── profiles.activity ─────────────────────────────────────────────────────────
-
-describe('profiles.activity', () => {
- test('calls openhuman.tinyplace_profiles_activity with username', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ events: [] });
- const client = createInvokeApiClient();
- await client.profiles.activity('alice');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_profiles_activity',
- params: { username: 'alice' },
- });
- });
-});
-
-// ── profiles.groups ───────────────────────────────────────────────────────────
-
-describe('profiles.groups', () => {
- test('calls openhuman.tinyplace_profiles_groups with username', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ groups: [] });
- const client = createInvokeApiClient();
- await client.profiles.groups('alice');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_profiles_groups',
- params: { username: 'alice' },
- });
- });
-
- test('returns groups response', async () => {
- const resp = { groups: [{ groupId: 'g1', name: 'Devs' }] };
- mockCallCoreRpc.mockResolvedValueOnce(resp);
- const client = createInvokeApiClient();
- const result = await client.profiles.groups('alice');
- expect(result).toEqual(resp);
- });
-});
-
-// ── profiles.broadcasts ───────────────────────────────────────────────────────
-
-describe('profiles.broadcasts', () => {
- test('calls openhuman.tinyplace_profiles_broadcasts with username', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ broadcasts: [] });
- const client = createInvokeApiClient();
- await client.profiles.broadcasts('alice');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_profiles_broadcasts',
- params: { username: 'alice' },
- });
- });
-});
-
-// ── profiles.attestations ─────────────────────────────────────────────────────
-
-describe('profiles.attestations', () => {
- test('calls openhuman.tinyplace_profiles_attestations with username', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ attestations: [] });
- const client = createInvokeApiClient();
- await client.profiles.attestations('alice');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_profiles_attestations',
- params: { username: 'alice' },
- });
- });
-});
-
-// ── profiles.agentCard ────────────────────────────────────────────────────────
-
-describe('profiles.agentCard', () => {
- test('calls openhuman.tinyplace_profiles_agent_card with username', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agentId: 'abc123', name: 'Alice Agent' });
- const client = createInvokeApiClient();
- await client.profiles.agentCard('alice');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_profiles_agent_card',
- params: { username: 'alice' },
- });
- });
-});
-
-// ── users.get ─────────────────────────────────────────────────────────────────
-
-describe('users.get', () => {
- test('calls openhuman.tinyplace_users_get with cryptoId', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ cryptoId: 'xyz789', displayName: 'Alice' });
- const client = createInvokeApiClient();
- await client.users.get('xyz789');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_users_get',
- params: { cryptoId: 'xyz789' },
- });
- });
-
- test('returns User from core', async () => {
- const user = { cryptoId: 'xyz789', displayName: 'Alice', bio: 'Hello' };
- mockCallCoreRpc.mockResolvedValueOnce(user);
- const client = createInvokeApiClient();
- const result = await client.users.get('xyz789');
- expect(result).toEqual(user);
- });
-});
-
-// ── users.updateProfile ───────────────────────────────────────────────────────
-
-describe('users.updateProfile', () => {
- test('calls openhuman.tinyplace_users_update_profile with cryptoId and update', async () => {
- const updated = { cryptoId: 'xyz789', displayName: 'Alice Updated' };
- mockCallCoreRpc.mockResolvedValueOnce(updated);
- const client = createInvokeApiClient();
- const update = { displayName: 'Alice Updated', bio: 'New bio' };
- await client.users.updateProfile('xyz789', update);
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_users_update_profile',
- params: { cryptoId: 'xyz789', update },
- });
- });
-
- test('returns updated User from core', async () => {
- const updated = { cryptoId: 'xyz789', displayName: 'Alice Updated', bio: 'New bio' };
- mockCallCoreRpc.mockResolvedValueOnce(updated);
- const client = createInvokeApiClient();
- const result = await client.users.updateProfile('xyz789', { displayName: 'Alice Updated' });
- expect(result).toEqual(updated);
- });
-});
-
-// ── PaymentRequiredError ──────────────────────────────────────────────────────
-
-describe('PaymentRequiredError propagation', () => {
- test('402 string rejection becomes PaymentRequiredError', async () => {
- const challenge = { error: 'payment required', payment: { scheme: 'x402', amount: '0.01' } };
- mockCallCoreRpc.mockRejectedValueOnce(
- new Error(`PAYMENT_REQUIRED:${JSON.stringify(challenge)}`)
- );
- const client = createInvokeApiClient();
- await expect(client.explorer.overview()).rejects.toBeInstanceOf(PaymentRequiredError);
- });
-
- test('PaymentRequiredError.challenge contains the parsed challenge', async () => {
- const challenge = { error: 'payment required', payment: { scheme: 'x402', amount: '0.01' } };
- mockCallCoreRpc.mockRejectedValueOnce(
- new Error(`PAYMENT_REQUIRED:${JSON.stringify(challenge)}`)
- );
- const client = createInvokeApiClient();
- let caught: PaymentRequiredError | null = null;
- try {
- await client.search.unified('test');
- } catch (e) {
- caught = e as PaymentRequiredError;
- }
- expect(caught).toBeInstanceOf(PaymentRequiredError);
- expect(caught?.challenge).toEqual(challenge);
- });
-
- test('non-402 errors propagate unchanged', async () => {
- const networkErr = new Error('network failure');
- mockCallCoreRpc.mockRejectedValueOnce(networkErr);
- const client = createInvokeApiClient();
- await expect(client.directory.listAgents()).rejects.toBe(networkErr);
- });
-});
-
-describe('bounties.create', () => {
- const bountyParams = {
- title: 'Build a widget',
- description: 'Need a widget',
- amount: '5',
- asset: 'USDC',
- };
-
- test('marshals params and passes the x402 spend timeout (#4201)', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ bounty: { id: 'b1' } });
- const client = createInvokeApiClient();
- await client.bounties.create(bountyParams, { confirmed: true });
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_bounties_create',
- params: {
- title: 'Build a widget',
- description: 'Need a widget',
- amount: '5',
- asset: 'USDC',
- deadline: null,
- durationDays: null,
- confirmed: true,
- },
- // On-chain escrow funding + settle polling exceeds the 30s default, so
- // the renderer must grant a longer per-call budget or the call aborts at
- // 30s with a spurious timeout even while settlement is in flight.
- timeoutMs: 120_000,
- });
- });
-
- test('the unconfirmed probe also gets the longer timeout', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ challenge: {} });
- const client = createInvokeApiClient();
- await client.bounties.create(bountyParams);
-
- const callArgs = mockCallCoreRpc.mock.calls[0][0];
- expect(callArgs.params.confirmed).toBe(false);
- expect(callArgs.timeoutMs).toBe(120_000);
- });
-});
-
-describe('registry.export', () => {
- test('calls openhuman.tinyplace_registry_export with name', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({
- identity: { username: '@testhandle' },
- ledgerTransactions: [],
- exportedAt: '2025-06-15T12:00:00Z',
- verification: {},
- proofs: { ownership: {}, ledgerReferences: [] },
- });
- const client = createInvokeApiClient();
- await client.registry.export('@testhandle');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_registry_export',
- params: { name: '@testhandle' },
- });
- });
-});
-
-describe('registry.assignPrimary', () => {
- test('calls openhuman.tinyplace_registry_assign_primary with name (#4198)', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ identity: { username: '@second', primary: true } });
- const client = createInvokeApiClient();
- const result = await client.registry.assignPrimary('@second');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_registry_assign_primary',
- params: { name: '@second' },
- });
- expect(result.identity?.primary).toBe(true);
- });
-});
-
-describe('registry.get', () => {
- test('calls openhuman.tinyplace_registry_get with name', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ available: true, name: '@atlas' });
- const client = createInvokeApiClient();
- await client.registry.get('@atlas');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_registry_get',
- params: { name: '@atlas' },
- });
- });
-
- test('returns availability response', async () => {
- const mockResponse = { available: false, name: '@taken', identity: { cryptoId: 'abc' } };
- mockCallCoreRpc.mockResolvedValueOnce(mockResponse);
- const client = createInvokeApiClient();
- const result = await client.registry.get('@taken');
- expect(result).toEqual(mockResponse);
- });
-});
-describe('marketplace.listIdentities', () => {
- test('calls openhuman.tinyplace_marketplace_list_identities with status', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ identities: [] });
- const client = createInvokeApiClient();
- await client.marketplace.listIdentities({ status: 'active' });
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_list_identities',
- params: { limit: null, status: 'active' },
- });
- });
-
- test('calls without params (null values)', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ identities: [] });
- const client = createInvokeApiClient();
- await client.marketplace.listIdentities();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_list_identities',
- params: { limit: null, status: null },
- });
- });
-});
-describe('marketplace.identityFloor', () => {
- test('calls openhuman.tinyplace_marketplace_identity_floor with length', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ length: 3, price: { amount: '250', asset: 'USDC' } });
- const client = createInvokeApiClient();
- await client.marketplace.identityFloor(3);
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_identity_floor',
- params: { length: 3 },
- });
- });
-
- test('calls without length (null)', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({});
- const client = createInvokeApiClient();
- await client.marketplace.identityFloor();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_identity_floor',
- params: { length: null },
- });
- });
-});
-describe('marketplace.recent', () => {
- test('calls openhuman.tinyplace_marketplace_recent with no params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ sales: [] });
- const client = createInvokeApiClient();
- await client.marketplace.recent();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_recent',
- params: undefined,
- });
- });
-});
-describe('marketplace.identitySaleHistory', () => {
- test('calls openhuman.tinyplace_marketplace_identity_sale_history with name', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ history: [] });
- const client = createInvokeApiClient();
- await client.marketplace.identitySaleHistory('@atlas');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_identity_sale_history',
- params: { name: '@atlas' },
- });
- });
-});
-describe('marketplace.listBids', () => {
- test('calls openhuman.tinyplace_marketplace_list_bids with listingId', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ bids: [] });
- const client = createInvokeApiClient();
- await client.marketplace.listBids('listing-123');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_list_bids',
- params: { listingId: 'listing-123' },
- });
- });
-});
-describe('marketplace.listOffers', () => {
- test('calls openhuman.tinyplace_marketplace_list_offers with name filter', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ offers: [] });
- const client = createInvokeApiClient();
- await client.marketplace.listOffers({ name: '@atlas' });
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_list_offers',
- params: { name: '@atlas', buyer: null },
- });
- });
-
- test('calls with buyer filter', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ offers: [] });
- const client = createInvokeApiClient();
- await client.marketplace.listOffers({ buyer: '@buyer' });
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_list_offers',
- params: { name: null, buyer: '@buyer' },
- });
- });
-
- test('calls without filters (null values)', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ offers: [] });
- const client = createInvokeApiClient();
- await client.marketplace.listOffers();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_list_offers',
- params: { name: null, buyer: null },
- });
- });
-});
-
-describe('marketplace.browseMarketplace', () => {
- test('calls openhuman.tinyplace_marketplace_browse with params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ products: [] });
- const client = createInvokeApiClient();
- const params = { q: 'model', category: 'ai' };
- await client.marketplace.browseMarketplace(params);
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_browse',
- params: { params },
- });
- });
-
- test('calls with null when no params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ products: [] });
- const client = createInvokeApiClient();
- await client.marketplace.browseMarketplace();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_browse',
- params: { params: null },
- });
- });
-});
-describe('marketplace.listProducts', () => {
- test('calls openhuman.tinyplace_marketplace_list_products', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ products: [] });
- const client = createInvokeApiClient();
- await client.marketplace.listProducts({ limit: 10 });
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_list_products',
- params: { params: { limit: 10 } },
- });
- });
-
- test('calls with null params when omitted', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ products: [] });
- const client = createInvokeApiClient();
- await client.marketplace.listProducts();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_list_products',
- params: { params: null },
- });
- });
-});
-describe('marketplace.getProduct', () => {
- test('calls openhuman.tinyplace_marketplace_get_product with productId', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ productId: 'prod_abc' });
- const client = createInvokeApiClient();
- await client.marketplace.getProduct('prod_abc');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_get_product',
- params: { productId: 'prod_abc' },
- });
- });
-});
-describe('marketplace.categories', () => {
- test('calls openhuman.tinyplace_marketplace_categories with no params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ categories: [] });
- const client = createInvokeApiClient();
- await client.marketplace.categories();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_categories',
- params: undefined,
- });
- });
-});
-describe('marketplace.featured', () => {
- test('calls openhuman.tinyplace_marketplace_featured with no params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ items: [] });
- const client = createInvokeApiClient();
- await client.marketplace.featured();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_featured',
- params: undefined,
- });
- });
-});
-describe('marketplace.listProductReviews', () => {
- test('calls openhuman.tinyplace_marketplace_list_product_reviews with productId', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ reviews: [] });
- const client = createInvokeApiClient();
- await client.marketplace.listProductReviews('prod_xyz');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_marketplace_list_product_reviews',
- params: { productId: 'prod_xyz' },
- });
- });
-});
-describe('artifacts.list', () => {
- test('calls openhuman.tinyplace_artifacts_list with params and actorId', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ artifacts: [] });
- const client = createInvokeApiClient();
- await client.artifacts.list({ role: 'owner' }, 'agent123');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_artifacts_list',
- params: { params: { role: 'owner' }, actorId: 'agent123' },
- });
- });
-
- test('calls with null params when omitted', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ artifacts: [] });
- const client = createInvokeApiClient();
- await client.artifacts.list();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_artifacts_list',
- params: { params: null },
- });
- });
-});
-describe('artifacts.get', () => {
- test('calls openhuman.tinyplace_artifacts_get with artifactId', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ artifactId: 'art_abc', owner: 'agent123' });
- const client = createInvokeApiClient();
- await client.artifacts.get('art_abc');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_artifacts_get',
- params: { artifactId: 'art_abc' },
- });
- });
-
- test('passes actorId when provided', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ artifactId: 'art_abc', owner: 'agent123' });
- const client = createInvokeApiClient();
- await client.artifacts.get('art_abc', 'agent456');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_artifacts_get',
- params: { artifactId: 'art_abc', actorId: 'agent456' },
- });
- });
-});
-describe('escrow.list', () => {
- test('calls openhuman.tinyplace_escrow_list with params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ escrows: [] });
- const client = createInvokeApiClient();
- await client.escrow.list({ status: 'funded' });
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_escrow_list',
- params: { params: { status: 'funded' } },
- });
- });
-
- test('calls with null params when omitted', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ escrows: [] });
- const client = createInvokeApiClient();
- await client.escrow.list();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_escrow_list',
- params: { params: null },
- });
- });
-});
-describe('escrow.get', () => {
- test('calls openhuman.tinyplace_escrow_get with escrowId', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ escrowId: 'esc_abc', status: 'funded' });
- const client = createInvokeApiClient();
- await client.escrow.get('esc_abc');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_escrow_get',
- params: { escrowId: 'esc_abc' },
- });
- });
-});
-describe('jobs.list', () => {
- test('calls openhuman.tinyplace_jobs_list with params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ jobs: [] });
- const client = createInvokeApiClient();
- await client.jobs.list({ q: 'rust developer' });
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_jobs_list',
- params: { params: { q: 'rust developer' } },
- });
- });
-
- test('calls with null params when omitted', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ jobs: [] });
- const client = createInvokeApiClient();
- await client.jobs.list();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_jobs_list',
- params: { params: null },
- });
- });
-});
-describe('jobs.get', () => {
- test('calls openhuman.tinyplace_jobs_get with jobId', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ jobId: 'job_abc', status: 'open' });
- const client = createInvokeApiClient();
- await client.jobs.get('job_abc');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_jobs_get',
- params: { jobId: 'job_abc' },
- });
- });
-});
-
-describe('channels.list', () => {
- test('calls openhuman.tinyplace_channels_list with params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ channels: [] });
- const client = createInvokeApiClient();
- const params = { q: 'defi', limit: 10 };
- await client.channels.list(params);
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_channels_list',
- params: { params },
- });
- });
-
- test('calls with null when no params provided', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ channels: [] });
- const client = createInvokeApiClient();
- await client.channels.list();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_channels_list',
- params: { params: null },
- });
- });
-
- test('returns channel list response from core', async () => {
- const mockResponse = {
- channels: [{ channelId: 'ch1', name: 'General', memberCount: 42, isPublic: true }],
- };
- mockCallCoreRpc.mockResolvedValueOnce(mockResponse);
- const client = createInvokeApiClient();
- const result = await client.channels.list();
- expect(result).toEqual(mockResponse);
- });
-});
-describe('groups.list', () => {
- test('calls openhuman.tinyplace_groups_list with params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce([]);
- const client = createInvokeApiClient();
- const params = { q: 'research', limit: 5 };
- await client.groups.list(params);
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_groups_list',
- params: { params },
- });
- });
-
- test('calls with null when no params provided', async () => {
- mockCallCoreRpc.mockResolvedValueOnce([]);
- const client = createInvokeApiClient();
- await client.groups.list();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_groups_list',
- params: { params: null },
- });
- });
-});
-describe('broadcasts.list', () => {
- test('calls openhuman.tinyplace_broadcasts_list with params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce([]);
- const client = createInvokeApiClient();
- const params = { visibility: 'public', limit: 20 };
- await client.broadcasts.list(params);
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_broadcasts_list',
- params: { params },
- });
- });
-
- test('calls with null when no params provided', async () => {
- mockCallCoreRpc.mockResolvedValueOnce([]);
- const client = createInvokeApiClient();
- await client.broadcasts.list();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_broadcasts_list',
- params: { params: null },
- });
- });
-});
-describe('inbox.list', () => {
- test('calls openhuman.tinyplace_inbox_list with params and no owner', async () => {
- const mockResult = { items: [], unreadCount: 0, totalCount: 0, cursor: null };
- mockCallCoreRpc.mockResolvedValueOnce(mockResult);
- const client = createInvokeApiClient();
- const params = { limit: 30 };
- await client.inbox.list(params);
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_inbox_list',
- params: { params, owner: null },
- });
- });
-
- test('passes owner when provided', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ items: [], unreadCount: 0, totalCount: 0 });
- const client = createInvokeApiClient();
- await client.inbox.list(undefined, 'agent-xyz');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_inbox_list',
- params: { params: null, owner: 'agent-xyz' },
- });
- });
-
- test('returns inbox list result from core', async () => {
- const mockResult = {
- items: [
- {
- itemId: 'i1',
- type: 'SYSTEM',
- status: 'unread',
- priority: 'normal',
- timestamp: '2024-01-01T00:00:00Z',
- subject: 'Hello',
- },
- ],
- unreadCount: 1,
- totalCount: 1,
- };
- mockCallCoreRpc.mockResolvedValueOnce(mockResult);
- const client = createInvokeApiClient();
- const result = await client.inbox.list();
- expect(result).toEqual(mockResult);
- });
-});
-describe('inbox.counts', () => {
- test('calls openhuman.tinyplace_inbox_counts with no owner', async () => {
- const mockCounts = { unread: 3, read: 10, archived: 2, byType: {}, urgent: 0 };
- mockCallCoreRpc.mockResolvedValueOnce(mockCounts);
- const client = createInvokeApiClient();
- await client.inbox.counts();
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_inbox_counts',
- params: { owner: null },
- });
- });
-
- test('passes owner when provided', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({
- unread: 0,
- read: 0,
- archived: 0,
- byType: {},
- urgent: 0,
- });
- const client = createInvokeApiClient();
- await client.inbox.counts('agent-abc');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_inbox_counts',
- params: { owner: 'agent-abc' },
- });
- });
-
- test('returns counts from core', async () => {
- const mockCounts = { unread: 5, read: 20, archived: 3, byType: { SYSTEM: 2 }, urgent: 1 };
- mockCallCoreRpc.mockResolvedValueOnce(mockCounts);
- const client = createInvokeApiClient();
- const result = await client.inbox.counts();
- expect(result).toEqual(mockCounts);
- });
-});
-
-// ── messaging write actions (membership + inbox management) ───────────────────
-
-describe('messaging write methods', () => {
- test('channels.join / leave call the right RPC with channelId', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue(undefined);
- await client.channels.join('ch-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_channels_join',
- params: { channelId: 'ch-1' },
- });
- await client.channels.leave('ch-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_channels_leave',
- params: { channelId: 'ch-1' },
- });
- });
-
- test('groups.join / leave call the right RPC with groupId', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue(undefined);
- await client.groups.join('g-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_groups_join',
- params: { groupId: 'g-1' },
- });
- await client.groups.leave('g-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_groups_leave',
- params: { groupId: 'g-1' },
- });
- });
-
- test('groups.setMemberRole calls tinyplace_groups_set_member_role', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue({ groupId: 'g-1', agentId: 'a-1', role: 'admin' });
- await client.groups.setMemberRole('g-1', 'a-1', 'admin');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_groups_set_member_role',
- params: { groupId: 'g-1', agentId: 'a-1', role: 'admin' },
- });
- });
-
- test('groups.createInvite calls tinyplace_groups_create_invite with optional request', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue({ token: 'tok-1' });
- await client.groups.createInvite('g-1', { ttlSeconds: 3600, maxUses: 5 });
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_groups_create_invite',
- params: { groupId: 'g-1', request: { ttlSeconds: 3600, maxUses: 5 } },
- });
- });
-
- test('groups.createInvite sends request: null when no options', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue({ token: 'tok-2' });
- await client.groups.createInvite('g-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_groups_create_invite',
- params: { groupId: 'g-1', request: null },
- });
- });
-
- test('groups.listInvites calls tinyplace_groups_list_invites', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue([]);
- await client.groups.listInvites('g-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_groups_list_invites',
- params: { groupId: 'g-1' },
- });
- });
-
- test('groups.previewInvite calls tinyplace_groups_preview_invite', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue({ groupId: 'g-1', name: 'Group', valid: true });
- await client.groups.previewInvite('g-1', 'tok-abc');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_groups_preview_invite',
- params: { groupId: 'g-1', token: 'tok-abc' },
- });
- });
-
- test('groups.revokeInvite calls tinyplace_groups_revoke_invite', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue(undefined);
- await client.groups.revokeInvite('g-1', 'tok-abc');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_groups_revoke_invite',
- params: { groupId: 'g-1', token: 'tok-abc' },
- });
- });
-
- test('groups.redeemInvite calls tinyplace_groups_redeem_invite', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue({ groupId: 'g-1', agentId: 'me', role: 'member' });
- await client.groups.redeemInvite('g-1', 'tok-join');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_groups_redeem_invite',
- params: { groupId: 'g-1', token: 'tok-join' },
- });
- });
-
- test('broadcasts.subscribe / unsubscribe call the right RPC with broadcastId', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue(undefined);
- await client.broadcasts.subscribe('bc-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_broadcasts_subscribe',
- params: { broadcastId: 'bc-1' },
- });
- await client.broadcasts.unsubscribe('bc-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_broadcasts_unsubscribe',
- params: { broadcastId: 'bc-1' },
- });
- });
-
- test('inbox.markRead / archive / unarchive / remove pass itemId + null owner by default', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue(undefined);
- await client.inbox.markRead('item-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_inbox_mark_read',
- params: { itemId: 'item-1', owner: null },
- });
- await client.inbox.archive('item-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_inbox_archive',
- params: { itemId: 'item-1', owner: null },
- });
- await client.inbox.unarchive('item-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_inbox_unarchive',
- params: { itemId: 'item-1', owner: null },
- });
- await client.inbox.remove('item-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_inbox_remove',
- params: { itemId: 'item-1', owner: null },
- });
- });
-
- test('inbox.markRead forwards an explicit owner', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue(undefined);
- await client.inbox.markRead('item-2', 'agent-owner');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_inbox_mark_read',
- params: { itemId: 'item-2', owner: 'agent-owner' },
- });
- });
-
- test('inbox.markAllRead passes params=null + owner default', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValue(undefined);
- await client.inbox.markAllRead();
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_inbox_mark_all_read',
- params: { params: null, owner: null },
- });
- });
-
- // ── Feedback namespace ────────────────────────────────────────────────────
-
- test('feedback.list calls tinyplace_feedback_list with params wrapped in params key', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValueOnce({ feedback: [] });
- await client.feedback.list({ status: 'open', limit: 10 });
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_feedback_list',
- params: { params: { status: 'open', limit: 10 } },
- });
- });
-
- test('feedback.list without params sends params: null', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValueOnce({ feedback: [] });
- await client.feedback.list();
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_feedback_list',
- params: { params: null },
- });
- });
-
- test('feedback.get calls tinyplace_feedback_get with feedbackId', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValueOnce({ feedbackId: 'fb-1' });
- await client.feedback.get('fb-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_feedback_get',
- params: { feedbackId: 'fb-1' },
- });
- });
-
- test('feedback.create calls tinyplace_feedback_create with title and description', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValueOnce({ feedbackId: 'fb-new' });
- await client.feedback.create('My idea', 'Great description');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_feedback_create',
- params: { title: 'My idea', description: 'Great description' },
- });
- });
-
- test('feedback.create includes category when provided', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValueOnce({ feedbackId: 'fb-cat' });
- await client.feedback.create('Idea', 'Desc', 'feature');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_feedback_create',
- params: { title: 'Idea', description: 'Desc', category: 'feature' },
- });
- });
-
- test('feedback.vote calls tinyplace_feedback_vote with feedbackId and vote', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValueOnce({ feedbackId: 'fb-1', score: 1 });
- await client.feedback.vote('fb-1', 'up');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_feedback_vote',
- params: { feedbackId: 'fb-1', vote: 'up' },
- });
- });
-
- test('feedback.vote accepts "down" direction', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValueOnce({ feedbackId: 'fb-1', score: -1 });
- await client.feedback.vote('fb-1', 'down');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_feedback_vote',
- params: { feedbackId: 'fb-1', vote: 'down' },
- });
- });
-
- // ── Solana namespace ──────────────────────────────────────────────────────
-
- test('solana.info calls openhuman.tinyplace_solana_info with no params', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValueOnce({
- network: 'solana-devnet',
- name: 'Solana Devnet',
- kind: 'testnet',
- nativeAsset: 'SOL',
- explorerUrl: 'https://explorer.solana.com',
- confirmations: 31,
- assets: [
- { symbol: 'SOL', decimals: 9 },
- { symbol: 'USDC', address: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', decimals: 6 },
- ],
- rpc: { url: 'https://rpc.example.com', rateLimitPerMin: 600, fallbacks: true },
- });
- await client.solana.info();
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_solana_info',
- params: undefined,
- });
- });
-
- test('solana.rpcCall calls openhuman.tinyplace_solana_call with method and params', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValueOnce({ value: 1000000000 });
- await client.solana.rpcCall('getBalance', ['4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU']);
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_solana_call',
- params: {
- method: 'getBalance',
- params: ['4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'],
- id: null,
- },
- });
- });
-
- test('solana.rpcCall sends null params and id when omitted', async () => {
- const client = createInvokeApiClient();
- mockCallCoreRpc.mockResolvedValueOnce(42);
- await client.solana.rpcCall('getSlot');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_solana_call',
- params: { method: 'getSlot', params: null, id: null },
- });
- });
-});
-
-// ── signal namespace ──────────────────────────────────────────────────────────
-
-test('signal namespace has expected methods', () => {
- const client = createInvokeApiClient();
- expect(client.signal).toBeDefined();
- expect(typeof client.signal.provision).toBe('function');
- expect(typeof client.signal.uploadPreKeys).toBe('function');
- expect(typeof client.signal.rotateSignedPreKey).toBe('function');
- expect(typeof client.signal.getBundle).toBe('function');
- expect(typeof client.signal.keyStatus).toBe('function');
-});
-
-describe('signal.provision', () => {
- test('calls openhuman.tinyplace_signal_provision with preKeyCount', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agentId: 'abc', oneTimePreKeyCount: 100 });
- const client = createInvokeApiClient();
- await client.signal.provision(50);
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_signal_provision',
- params: { preKeyCount: 50 },
- });
- });
-
- test('sends preKeyCount: null when omitted', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agentId: 'abc', oneTimePreKeyCount: 100 });
- const client = createInvokeApiClient();
- await client.signal.provision();
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_signal_provision',
- params: { preKeyCount: null },
- });
- });
-});
-
-describe('signal.uploadPreKeys', () => {
- test('calls openhuman.tinyplace_signal_upload_pre_keys with count', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agentId: 'abc', oneTimePreKeyCount: 200 });
- const client = createInvokeApiClient();
- await client.signal.uploadPreKeys(50);
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_signal_upload_pre_keys',
- params: { count: 50 },
- });
- });
-
- test('sends count: null when omitted', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agentId: 'abc', oneTimePreKeyCount: 200 });
- const client = createInvokeApiClient();
- await client.signal.uploadPreKeys();
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_signal_upload_pre_keys',
- params: { count: null },
- });
- });
-});
-
-describe('signal.rotateSignedPreKey', () => {
- test('calls openhuman.tinyplace_signal_rotate_signed_pre_key with empty params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ ok: true, keyId: 'spk_123' });
- const client = createInvokeApiClient();
- await client.signal.rotateSignedPreKey();
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_signal_rotate_signed_pre_key',
- params: {},
- });
- });
-});
-
-describe('signal.getBundle', () => {
- test('calls openhuman.tinyplace_signal_get_bundle with agentId', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agentId: 'peer123', identityKey: 'abc' });
- const client = createInvokeApiClient();
- await client.signal.getBundle('peer123');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_signal_get_bundle',
- params: { agentId: 'peer123' },
- });
- });
-});
-
-describe('signal.keyStatus', () => {
- test('calls openhuman.tinyplace_signal_key_status with empty params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({
- agentId: 'abc',
- localPreKeyCount: 42,
- hasActiveSignedPreKey: true,
- remote: null,
- });
- const client = createInvokeApiClient();
- await client.signal.keyStatus();
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_signal_key_status',
- params: {},
- });
- });
-});
-
-test('signal namespace has registerEncryptionKey method', () => {
- const client = createInvokeApiClient();
- expect(typeof client.signal.registerEncryptionKey).toBe('function');
-});
-
-test('directory namespace has findByEncryptionKey method', () => {
- const client = createInvokeApiClient();
- expect(typeof client.directory.findByEncryptionKey).toBe('function');
-});
-
-describe('signal.sendMessage and messages namespace', () => {
- test('signal namespace has send/decrypt methods and messages namespace exists', () => {
- const client = createInvokeApiClient();
- expect(typeof client.signal.sendMessage).toBe('function');
- expect(typeof client.signal.decryptMessage).toBe('function');
- expect(client.messages).toBeDefined();
- expect(typeof client.messages.list).toBe('function');
- expect(typeof client.messages.acknowledge).toBe('function');
- });
-
- test('signal.sendMessage calls openhuman.tinyplace_signal_send_message with params object', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({
- messageId: 'msg-1',
- timestamp: '2026-06-17T00:00:00Z',
- encrypted: true,
- });
- const client = createInvokeApiClient();
- await client.signal.sendMessage({ recipient: 'peer-123', plaintext: 'Hello!' });
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_signal_send_message',
- params: { recipient: 'peer-123', plaintext: 'Hello!' },
- });
- });
-
- test('signal.decryptMessage calls openhuman.tinyplace_signal_decrypt_message with envelope', async () => {
- const envelope = {
- id: 'env-1',
- from: 'alice',
- to: 'bob',
- timestamp: '2026-06-17T00:00:00Z',
- deviceId: 1,
- type: 'CIPHERTEXT',
- body: 'base64ciphertext==',
- };
- mockCallCoreRpc.mockResolvedValueOnce({
- plaintext: 'Hello!',
- from: 'alice',
- messageId: 'env-1',
- });
- const client = createInvokeApiClient();
- await client.signal.decryptMessage({ envelope });
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_signal_decrypt_message',
- params: { envelope },
- });
- });
-
- test('messages.list calls openhuman.tinyplace_messages_list with params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ messages: [] });
- const client = createInvokeApiClient();
- await client.messages.list({ limit: 25 });
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_messages_list',
- params: { limit: 25 },
- });
- });
-
- test('messages.list sends empty params when called without args', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ messages: [] });
- const client = createInvokeApiClient();
- await client.messages.list();
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_messages_list',
- params: {},
- });
- });
-
- test('messages.acknowledge calls openhuman.tinyplace_messages_acknowledge', async () => {
- mockCallCoreRpc.mockResolvedValueOnce(undefined);
- const client = createInvokeApiClient();
- await client.messages.acknowledge('msg-99');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_messages_acknowledge',
- params: { messageId: 'msg-99' },
- });
- });
-});
-
-// ── GraphQL Profile + Identity methods ──────────────────────────────────────
-
-describe('graphql.profile', () => {
- test('routes to the correct RPC method with username', async () => {
- const mockProfile = { cryptoId: 'addr123', displayName: 'Alice', bio: '' };
- mockCallCoreRpc.mockResolvedValueOnce(mockProfile);
- const client = createInvokeApiClient();
- const result = await client.graphql.profile('alice');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_graphql_profile',
- params: { username: 'alice' },
- });
- expect(result).toEqual(mockProfile);
- });
-
- test('propagates null when profile is not found', async () => {
- mockCallCoreRpc.mockResolvedValueOnce(null);
- const client = createInvokeApiClient();
- const result = await client.graphql.profile('unknown');
- expect(result).toBeNull();
- });
-});
-
-describe('graphql.user', () => {
- test('routes to the correct RPC method with cryptoId', async () => {
- const mockProfile = { cryptoId: 'solana123', displayName: 'Bob', bio: '' };
- mockCallCoreRpc.mockResolvedValueOnce(mockProfile);
- const client = createInvokeApiClient();
- const result = await client.graphql.user('solana123');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_graphql_user',
- params: { cryptoId: 'solana123' },
- });
- expect(result).toEqual(mockProfile);
- });
-
- test('propagates null when no profile exists for the address', async () => {
- mockCallCoreRpc.mockResolvedValueOnce(null);
- const client = createInvokeApiClient();
- const result = await client.graphql.user('noaddr');
- expect(result).toBeNull();
- });
-});
-
-describe('graphql.identity', () => {
- test('routes to the correct RPC method with username', async () => {
- const mockIdentity = { username: 'alice', cryptoId: 'addr123', status: 'active' };
- mockCallCoreRpc.mockResolvedValueOnce(mockIdentity);
- const client = createInvokeApiClient();
- const result = await client.graphql.identity('alice');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_graphql_identity',
- params: { username: 'alice' },
- });
- expect(result).toEqual(mockIdentity);
- });
-
- test('propagates null when identity is not found', async () => {
- mockCallCoreRpc.mockResolvedValueOnce(null);
- const client = createInvokeApiClient();
- const result = await client.graphql.identity('noone');
- expect(result).toBeNull();
- });
-});
-
-describe('graphql.identities', () => {
- test('routes to the correct RPC method with cryptoId', async () => {
- const mockResult = { identities: [{ username: 'alice', cryptoId: 'addr123' }] };
- mockCallCoreRpc.mockResolvedValueOnce(mockResult);
- const client = createInvokeApiClient();
- const result = await client.graphql.identities('addr123');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_graphql_identities',
- params: { cryptoId: 'addr123' },
- });
- expect(result).toEqual(mockResult);
- });
-
- test('returns empty identities array when wallet has no registered handles', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ identities: [] });
- const client = createInvokeApiClient();
- const result = await client.graphql.identities('emptyaddr');
- expect(result).toEqual({ identities: [] });
- });
-});
-
-describe('graphql.agentCard', () => {
- test('routes to the correct RPC method with id', async () => {
- const mockCard = { agentId: 'agent-1', name: 'MyAgent' };
- mockCallCoreRpc.mockResolvedValueOnce(mockCard);
- const client = createInvokeApiClient();
- const result = await client.graphql.agentCard('agent-1');
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_graphql_agent_card',
- params: { id: 'agent-1' },
- });
- expect(result).toEqual(mockCard);
- });
-
- test('propagates null when agent card is not found', async () => {
- mockCallCoreRpc.mockResolvedValueOnce(null);
- const client = createInvokeApiClient();
- const result = await client.graphql.agentCard('missing-id');
- expect(result).toBeNull();
- });
-});
-
-describe('graphql marketplace reads', () => {
- test('routes agents through GraphQL with nullable params', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ agents: [] });
- const client = createInvokeApiClient();
- await client.graphql.agents({ q: 'bot', limit: 5 });
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_graphql_agents',
- params: { params: { q: 'bot', limit: 5 } },
- });
- });
-
- test('normalizes product seller handles and crypto IDs', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({
- products: [
- {
- id: 'product-1',
- seller: { handle: '@seller', cryptoId: 'seller-crypto' },
- sellerCryptoId: '',
- },
- { id: 'product-2', seller: { cryptoId: 'fallback-crypto' } },
- ],
- count: 2,
- });
- const client = createInvokeApiClient();
- const result = await client.graphql.products({ limit: 2 });
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.tinyplace_graphql_products',
- params: { params: { limit: 2 } },
- });
- expect(result.products[0]).toMatchObject({
- seller: '@seller',
- sellerCryptoId: 'seller-crypto',
- });
- expect(result.products[1]).toMatchObject({
- seller: 'fallback-crypto',
- sellerCryptoId: 'fallback-crypto',
- });
- });
-
- test('normalizes a single GraphQL product and preserves null misses', async () => {
- mockCallCoreRpc
- .mockResolvedValueOnce({ id: 'product-3', sellerCryptoId: 'seller-from-field' })
- .mockResolvedValueOnce(null);
- const client = createInvokeApiClient();
-
- await expect(client.graphql.product('product-3')).resolves.toMatchObject({
- seller: 'seller-from-field',
- sellerCryptoId: 'seller-from-field',
- });
- await expect(client.graphql.product('missing')).resolves.toBeNull();
- });
-
- test('normalizes identity listing sellers and nullable detail results', async () => {
- mockCallCoreRpc
- .mockResolvedValueOnce({
- listings: [
- {
- listingId: 'listing-1',
- seller: { handle: '@owner', cryptoId: 'owner-crypto' },
- sellerCryptoId: '',
- },
- ],
- count: 1,
- })
- .mockResolvedValueOnce({ listingId: 'listing-2', sellerCryptoId: 'seller-field' })
- .mockResolvedValueOnce(null);
- const client = createInvokeApiClient();
-
- const list = await client.graphql.identityListings({ status: 'active' });
- expect(mockCallCoreRpc).toHaveBeenNthCalledWith(1, {
- method: 'openhuman.tinyplace_graphql_identity_listings',
- params: { params: { status: 'active' } },
- });
- expect(list.identities[0]).toMatchObject({ seller: '@owner', sellerCryptoId: 'owner-crypto' });
-
- await expect(client.graphql.identityListing('listing-2')).resolves.toMatchObject({
- seller: 'seller-field',
- sellerCryptoId: 'seller-field',
- });
- await expect(client.graphql.identityListing('missing')).resolves.toBeNull();
- });
-
- test('routes identity bids and normalizes offer and sale parties', async () => {
- mockCallCoreRpc
- .mockResolvedValueOnce({ bids: [] })
- .mockResolvedValueOnce({ offers: [{ offerId: 'offer-1', buyer: { handle: '@buyer' } }] })
- .mockResolvedValueOnce({
- sales: [
- { saleId: 'sale-1', buyer: { cryptoId: 'buyer-crypto' }, seller: { handle: '@seller' } },
- ],
- });
- const client = createInvokeApiClient();
-
- await client.graphql.identityBids('listing-1', { limit: 3 });
- expect(mockCallCoreRpc).toHaveBeenNthCalledWith(1, {
- method: 'openhuman.tinyplace_graphql_identity_bids',
- params: { listingId: 'listing-1', params: { limit: 3 } },
- });
-
- await expect(client.graphql.identityOffers({ status: 'open' })).resolves.toMatchObject({
- offers: [{ buyer: '@buyer' }],
- });
- await expect(client.graphql.identitySales('@seller', { limit: 1 })).resolves.toMatchObject({
- sales: [{ buyer: 'buyer-crypto', seller: '@seller' }],
- });
- });
-});
diff --git a/app/src/lib/agentworld/invokeApiClient.ts b/app/src/lib/agentworld/invokeApiClient.ts
deleted file mode 100644
index 028ea5938c..0000000000
--- a/app/src/lib/agentworld/invokeApiClient.ts
+++ /dev/null
@@ -1,2391 +0,0 @@
-/**
- * tiny.place API client bridge — routes method calls through the OpenHuman
- * core RPC (`openhuman.tinyplace_*`) rather than the tiny.place HTTP API.
- *
- * The factory `createInvokeApiClient()` returns an object whose shape mirrors
- * the tiny.place TypeScript SDK client. Hooks and components in the Agent
- * World tree call it unchanged; this file is the only place where the routing
- * seam is visible.
- *
- * Error conventions:
- * - Transport / non-402 HTTP failures surface as plain `Error`.
- * - 402 Payment Required surfaces as `PaymentRequiredError` with a structured
- * `challenge` payload (the x402 terms from the backend).
- *
- * Append-point: see the comment block at the bottom of `createInvokeApiClient`
- * for where fan-out section agents add new namespace/method entries.
- */
-import { callCoreRpc } from '../../services/coreRpcClient';
-
-// ── Error types ───────────────────────────────────────────────────────────────
-
-/** Thrown when the core returns a `PAYMENT_REQUIRED:<json>` error string. */
-export class PaymentRequiredError extends Error {
- readonly challenge: unknown;
-
- constructor(challenge: unknown) {
- super('PAYMENT_REQUIRED');
- this.name = 'PaymentRequiredError';
- this.challenge = challenge;
- }
-}
-
-// ── Internal helpers ──────────────────────────────────────────────────────────
-
-function safeParseJson(s: string): unknown {
- try {
- return JSON.parse(s) as unknown;
- } catch {
- return s;
- }
-}
-
-/**
- * Call a `openhuman.tinyplace_*` core RPC method and return the typed result.
- *
- * If the core returns a string beginning with `"PAYMENT_REQUIRED:"`, this
- * function throws a {@link PaymentRequiredError} with the decoded challenge.
- * All other errors propagate as-is.
- */
-/**
- * Per-call timeout (ms) for x402 confirm-before-spend RPCs (bounty creation,
- * registration, marketplace buys).
- *
- * These fund a reward / registration into escrow on-chain at the moment of the
- * call: the core probes for the 402 challenge, signs and submits the payment,
- * then polls `settle_retry` until the backend confirms settlement. That whole
- * round-trip routinely exceeds the global 30s `CORE_RPC_TIMEOUT_MS`, so the
- * renderer aborted `tinyplace_bounties_create` at 30s and surfaced a spurious
- * `timed out after 30000ms` even though the chain settlement was still in
- * flight — bounty creation appeared completely broken (#4201). Give the spend
- * path a longer-but-still-bounded budget; the core clamps it to the
- * `[1s, 10min]` per-call window.
- */
-const X402_SPEND_TIMEOUT_MS = 120_000;
-
-async function call<T>(
- method: string,
- params?: Record<string, unknown>,
- timeoutMs?: number
-): Promise<T> {
- try {
- return await callCoreRpc<T>({
- method,
- params,
- ...(timeoutMs !== undefined ? { timeoutMs } : {}),
- });
- } catch (err) {
- // Core serialises 402 errors as a plain string "PAYMENT_REQUIRED:<json>".
- const msg = String(err);
- const prefix = 'PAYMENT_REQUIRED:';
- if (msg.includes(prefix)) {
- // Extract everything after the prefix, handling cases where the error
- // message has extra surrounding text from JSON-RPC wrapping.
- const idx = msg.indexOf(prefix);
- const payload = msg.slice(idx + prefix.length);
- throw new PaymentRequiredError(safeParseJson(payload));
- }
- throw err;
- }
-}
-
-// ── Types (inline minimal stubs — replace with SDK types when available) ──────
-//
-// These are structural interfaces that describe what the tiny.place backend
-// returns. They mirror `sdk/typescript/src/types/`. We declare them here
-// (import-type-only) so the renderer tree never bundles the HTTP SDK runtime.
-//
-// When `@tinyhumansai/tinyplace` is published and added as a dev-dep, replace
-// each `AgentQueryParams`, `AgentCard`, etc. with `import type { … } from
-// '@tinyhumansai/tinyplace'`.
-
-interface AgentQueryParams {
- q?: string;
- skill?: string;
- tag?: string;
- limit?: number;
- offset?: number;
- cursor?: string;
- [key: string]: unknown;
-}
-
-export interface AgentCard {
- agentId: string;
- cryptoId?: string;
- name?: string;
- description?: string;
- username?: string;
- [key: string]: unknown;
-}
-
-export interface ListAgentsResponse {
- agents: AgentCard[];
- [key: string]: unknown;
-}
-
-export interface ExplorerOverview {
- allTime?: { feesUsd?: string; registeredAgents?: number; volumeUsd?: string };
- last24h?: { feesUsd?: string; transactions?: number; uniqueAgents?: number; volumeUsd?: string };
- ledger?: { totalEntries?: number; latestTxId?: string; latestTimestamp?: string };
- [key: string]: unknown;
-}
-
-interface SearchResponse {
- results?: unknown[];
- [key: string]: unknown;
-}
-
-// ── Directory extended types ──────────────────────────────────────────────────
-
-interface ResolveResponse {
- identity?: unknown;
- agent?: AgentCard;
- [key: string]: unknown;
-}
-
-interface ReverseResponse {
- cryptoId: string;
- identities: unknown[];
- agents?: AgentCard[];
- [key: string]: unknown;
-}
-
-interface IdentityListingQueryParams {
- q?: string;
- tag?: string;
- category?: string;
- seller?: string;
- minPrice?: string;
- maxPrice?: string;
- sortBy?: string;
- limit?: number;
- offset?: number;
- [key: string]: unknown;
-}
-
-export interface DirectoryIdentityListingsResponse {
- identities: IdentityListing[];
- cursor?: string;
- [key: string]: unknown;
-}
-
-interface DirectorySkillsParams {
- q?: string;
- limit?: number;
- cursor?: string;
-}
-
-interface AgentSearchResponse {
- agents?: unknown[];
- cursor?: string;
- [key: string]: unknown;
-}
-
-// ── Profiles types ────────────────────────────────────────────────────────────
-
-interface AgentProfile {
- username?: string;
- name?: string;
- description?: string;
- cryptoId?: string;
- createdAt?: string;
- [key: string]: unknown;
-}
-
-interface ProfileActivity {
- [key: string]: unknown;
-}
-
-interface ProfileGroupMembership {
- groupId?: string;
- name?: string;
- [key: string]: unknown;
-}
-
-interface ProfileGroupsResponse {
- groups: ProfileGroupMembership[];
- [key: string]: unknown;
-}
-
-interface ProfileBroadcast {
- id?: string;
- content?: string;
- createdAt?: string;
- [key: string]: unknown;
-}
-
-interface ProfileBroadcastsResponse {
- broadcasts: ProfileBroadcast[];
- [key: string]: unknown;
-}
-
-interface ProfileAttestation {
- id?: string;
- attester?: string;
- [key: string]: unknown;
-}
-
-interface ProfileAttestationsResponse {
- attestations: ProfileAttestation[];
- [key: string]: unknown;
-}
-
-// ── Users types ───────────────────────────────────────────────────────────────
-
-interface User {
- cryptoId: string;
- actorType: string;
- displayName: string;
- bio: string;
- avatarEmail?: string;
- email?: string;
- emailVerified: boolean;
- emailVerifiedAt?: string;
- emailVerificationRequestedAt?: string;
- harnessKey?: string;
- link?: string;
- tags?: string[];
- createdAt: string;
- updatedAt: string;
- [key: string]: unknown;
-}
-
-interface UserProfileUpdate {
- displayName?: string;
- bio?: string;
- avatarEmail?: string;
- harnessKey?: string;
- link?: string;
- tags?: string[];
- actorType?: string;
- signature?: unknown;
- [key: string]: unknown;
-}
-
-export interface AvailabilityResponse {
- available: boolean;
- name: string;
- identity?: { cryptoId: string; username?: string; [key: string]: unknown };
- [key: string]: unknown;
-}
-
-// ── Registry (x402 register) types ─────────────────────────────────────────────
-
-interface RegisterParams {
- username: string;
- /** false/omitted → challenge only (no spend); true → pay + register. */
- confirmed?: boolean;
- /** "human" (default) or "agent". */
- actorType?: string;
- primary?: boolean;
-}
-
-export interface RegistryWalletBalance {
- raw: string;
- formatted: string;
- decimals: number;
- assetSymbol: string;
-}
-
-/** The x402 payment terms surfaced on an unconfirmed register call. */
-export interface RegistrationChallenge {
- amount?: string;
- asset?: string;
- network?: string;
- to?: string;
- expiresAt?: string;
- [key: string]: unknown;
-}
-
-export interface RegisteredIdentity {
- username?: string;
- cryptoId?: string;
- [key: string]: unknown;
-}
-
-/**
- * Result of `registry.register`. Exactly one of these shapes is populated:
- * - `{ identity }` — registered (free tier or after payment).
- * - `{ challenge, walletBalance, walletAddress }` — unconfirmed; render confirm.
- * - `{ identity, payment }` — paid + registered.
- */
-interface RegistrationResult {
- identity?: RegisteredIdentity;
- challenge?: RegistrationChallenge;
- walletBalance?: RegistryWalletBalance | null;
- walletAddress?: string;
- payment?: { onChainTx?: string };
- [key: string]: unknown;
-}
-
-/** Result of `registry.assignPrimary` — the handle now flagged primary. */
-interface AssignPrimaryResult {
- identity?: Identity;
- [key: string]: unknown;
-}
-
-/** Result of a handle transfer: the Identity now owned by the recipient. */
-interface TransferHandleResult {
- identity?: Identity;
- [key: string]: unknown;
-}
-
-// -- Registry export types ------------------------------------------------
-
-export interface LedgerReference {
- kind: string;
- id?: string;
- parentTxId?: string;
- rate?: string;
- [key: string]: unknown;
-}
-
-export interface LedgerTransaction {
- txId: string;
- visibility: string;
- type: string;
- from?: string;
- to?: string;
- amount?: string;
- asset?: string;
- network: string;
- timestamp: string;
- reference?: LedgerReference;
- onChainTx: string;
- status: string;
- metadata?: Record<string, string>;
- [key: string]: unknown;
-}
-
-export interface IdentityOwnershipProof {
- algorithm: string;
- cryptoId: string;
- publicKey: string;
- publicKeyMatchesCryptoId: boolean;
- [key: string]: unknown;
-}
-
-export interface IdentityLedgerReferenceProof {
- txId: string;
- onChainTx: string;
- network: string;
- status: string;
- type: string;
- reference: LedgerReference;
- [key: string]: unknown;
-}
-
-export interface IdentityExportProofs {
- ownership: IdentityOwnershipProof;
- ledgerReferences: IdentityLedgerReferenceProof[];
- [key: string]: unknown;
-}
-
-export interface IdentityExport {
- identity: AvailabilityResponse['identity'];
- ledgerTransactions: LedgerTransaction[];
- exportedAt: string;
- verification: Record<string, string>;
- proofs: IdentityExportProofs;
- [key: string]: unknown;
-}
-
-/**
- * Result of an x402 buy (`marketplace.buyProduct` / `buyIdentity`). Exactly one
- * shape is populated:
- * - `{ result }` — purchased (free tier, no payment needed).
- * - `{ challenge, walletBalance, walletAddress }` — unconfirmed; render confirm.
- * - `{ result, payment: { onChainTx } }` — paid + purchased.
- */
-export interface X402BuyResult {
- result?: Record<string, unknown>;
- challenge?: RegistrationChallenge;
- walletBalance?: RegistryWalletBalance | null;
- walletAddress?: string;
- payment?: { onChainTx?: string };
- [key: string]: unknown;
-}
-
-/**
- * Result of an x402 commitment (`marketplace.bid` / `offer`). Bids/offers are
- * signed authorizations — no on-chain transfer until acceptance — so the result
- * is `{ result, committed: true }` (no `payment.onChainTx`).
- */
-interface X402CommitResult {
- result?: Record<string, unknown>;
- committed?: boolean;
- [key: string]: unknown;
-}
-
-/** Amount + (optional) asset + network for a bid/offer commitment. */
-interface CommitPriceParams {
- amount: string;
- asset?: string;
- network: string;
-}
-interface BidsResponse {
- bids: IdentityBid[];
- [key: string]: unknown;
-}
-export interface IdentitiesResponse {
- identities: IdentityListing[];
- [key: string]: unknown;
-}
-interface IdentityBid {
- bidId?: string;
- listingId?: string;
- bidder?: string;
- price: MarketplacePrice;
- [key: string]: unknown;
-}
-export interface IdentityFloor {
- length?: number;
- price?: MarketplacePrice;
- [key: string]: unknown;
-}
-export interface IdentityListing {
- listingId: string;
- name: string;
- seller?: string;
- sellerCryptoId?: string;
- price: MarketplacePrice;
- reservePrice?: MarketplacePrice;
- highestBid?: { price: MarketplacePrice; [key: string]: unknown };
- listingType?: 'fixed' | 'auction';
- status?: string;
- description?: string;
- expiresAt?: string;
- updatedAt: string;
- [key: string]: unknown;
-}
-interface IdentityOffer {
- offerId: string;
- name?: string;
- buyer: string;
- price: MarketplacePrice;
- status?: string;
- [key: string]: unknown;
-}
-export interface IdentitySale {
- saleId: string;
- name: string;
- price: MarketplacePrice;
- buyer: string;
- seller?: string;
- createdAt: string;
- [key: string]: unknown;
-}
-interface IdentitySaleHistoryResponse {
- history?: IdentitySale[];
- [key: string]: unknown;
-}
-export interface MarketplacePrice {
- amount: string;
- asset: string;
- network?: string;
- [key: string]: unknown;
-}
-interface OffersResponse {
- offers: IdentityOffer[];
- [key: string]: unknown;
-}
-export interface RecentSalesResponse {
- sales: IdentitySale[];
- [key: string]: unknown;
-}
-
-export interface Artifact {
- artifactId: string;
- owner: string;
- ownerCryptoId?: string;
- name?: string;
- description?: string;
- mimeType?: string;
- sizeBytes?: number;
- sha256?: string;
- encryption?: string;
- recipients?: string[];
- recipientCryptoIds?: string[];
- expiresAt?: string;
- maxDownloads?: number;
- downloadCount?: number;
- status?: string;
- createdAt?: string;
- updatedAt?: string;
- [key: string]: unknown;
-}
-export interface ArtifactListResult {
- artifacts: Artifact[];
- cursor?: string;
-}
-interface ArtifactQueryParams {
- role?: string;
- status?: string;
- referenceKind?: string;
- referenceId?: string;
- limit?: number;
- cursor?: string;
- [key: string]: unknown;
-}
-interface CategoriesResponse {
- categories: MarketplaceCategory[];
- [key: string]: unknown;
-}
-export interface Escrow {
- escrowId: string;
- status: string;
- client: string;
- provider: string;
- [key: string]: unknown;
-}
-export interface EscrowListResponse {
- escrows: Escrow[];
- [key: string]: unknown;
-}
-interface EscrowQueryParams {
- role?: string;
- status?: string;
- limit?: number;
- offset?: number;
- [key: string]: unknown;
-}
-interface FeaturedResponse {
- items: unknown[];
- [key: string]: unknown;
-}
-interface JobListResponse {
- jobs: JobPosting[];
- [key: string]: unknown;
-}
-interface JobPosting {
- jobId: string;
- status: string;
- client: string;
- [key: string]: unknown;
-}
-interface JobQueryParams {
- status?: string;
- skill?: string;
- q?: string;
- limit?: number;
- offset?: number;
- [key: string]: unknown;
-}
-interface MarketplaceBrowseResponse {
- [key: string]: unknown;
-}
-interface MarketplaceCategory {
- [key: string]: unknown;
-}
-export interface Product {
- productId: string;
- seller: string;
- sellerCryptoId: string;
- name: string;
- description: string;
- category: string;
- tags?: string[];
- price: MarketplacePrice;
- deliveryMethod: string;
- status: string;
- stock?: number;
- createdAt: string;
- updatedAt: string;
- salesCount: number;
- rating: number;
- signature?: string;
- signerPublicKey?: string;
- [key: string]: unknown;
-}
-interface ProductQueryParams {
- q?: string;
- type?: string;
- category?: string;
- tags?: string[];
- seller?: string;
- minPrice?: string;
- maxPrice?: string;
- sortBy?: string;
- limit?: number;
- offset?: number;
- [key: string]: unknown;
-}
-interface ProductReview {
- reviewId?: string;
- productId?: string;
- buyer?: string;
- rating?: number;
- comment?: string;
- [key: string]: unknown;
-}
-interface ProductReviewsResponse {
- reviews: ProductReview[];
- [key: string]: unknown;
-}
-export interface ProductsResponse {
- products: Product[];
- [key: string]: unknown;
-}
-
-interface GqlAgentCardListResult {
- agents: AgentCard[];
- count?: number;
- [key: string]: unknown;
-}
-
-interface GqlProduct extends Omit<Product, 'seller' | 'sellerCryptoId'> {
- seller: FeedAuthor;
- sellerCryptoId?: string;
-}
-
-interface GqlProductListResult {
- products: GqlProduct[];
- count?: number;
- [key: string]: unknown;
-}
-
-interface GqlIdentityListing extends Omit<IdentityListing, 'seller' | 'sellerCryptoId'> {
- seller?: FeedAuthor;
- sellerCryptoId?: string;
-}
-
-interface GqlIdentityListingListResult {
- identities?: GqlIdentityListing[];
- listings?: GqlIdentityListing[];
- count?: number;
- [key: string]: unknown;
-}
-
-interface GqlIdentityBidListResult {
- bids: IdentityBid[];
- count?: number;
- [key: string]: unknown;
-}
-
-interface GqlIdentityOffer extends Omit<IdentityOffer, 'buyer'> {
- buyer: FeedAuthor;
-}
-
-interface GqlIdentityOfferListResult {
- offers: GqlIdentityOffer[];
- count?: number;
- [key: string]: unknown;
-}
-
-interface GqlIdentitySale extends Omit<IdentitySale, 'buyer' | 'seller'> {
- buyer: FeedAuthor;
- seller?: FeedAuthor;
-}
-
-interface GqlIdentitySaleListResult {
- sales: GqlIdentitySale[];
- count?: number;
- [key: string]: unknown;
-}
-
-export interface BroadcastChannel {
- broadcastId: string;
- name: string;
- description?: string;
- owner: string;
- subscriberCount: number;
- visibility: string;
- tags?: string[];
- [key: string]: unknown;
-}
-export interface BroadcastQueryParams {
- q?: string;
- tag?: string;
- tags?: string[];
- owner?: string;
- visibility?: string;
- paymentType?: string;
- sort?: string;
- limit?: number;
- [key: string]: unknown;
-}
-export interface Channel {
- channelId: string;
- name: string;
- description?: string;
- creator: string;
- memberCount: number;
- isPublic: boolean;
- tags?: string[];
- category?: string;
- createdAt: string;
- updatedAt: string;
- [key: string]: unknown;
-}
-interface ChannelListResponse {
- channels: Channel[];
- [key: string]: unknown;
-}
-export interface ChannelQueryParams {
- q?: string;
- tag?: string;
- tags?: string[];
- minMembers?: number;
- maxMembers?: number;
- sort?: string;
- limit?: number;
- [key: string]: unknown;
-}
-export interface GroupMetadata {
- groupId: string;
- name: string;
- description?: string;
- createdBy: string;
- createdAt: string;
- membershipPolicy: string;
- memberCount: number;
- membershipEpoch: number;
- tags?: string[];
- [key: string]: unknown;
-}
-export interface GroupQueryParams {
- q?: string;
- tag?: string;
- tags?: string[];
- membershipPolicy?: string;
- minMembers?: number;
- maxMembers?: number;
- limit?: number;
- /** When set, returns only groups this agent is an active member of. */
- member?: string;
- [key: string]: unknown;
-}
-// ── Groups invite/role types ────────────────────────────────────────────────
-
-export interface GroupMember {
- groupId: string;
- agentId: string;
- role: string;
- status: string;
- joinedAt: string;
- updatedAt: string;
- subscriptionInterval?: string;
- subscriptionStatus?: string;
- currentPeriodEnd?: string;
- subscriptionGraceEnd?: string;
- autoRenew?: boolean;
- [key: string]: unknown;
-}
-
-export interface GroupInvite {
- groupId: string;
- token: string;
- createdBy: string;
- createdAt: string;
- expiresAt?: string;
- maxUses?: number;
- uses: number;
- revoked?: boolean;
- [key: string]: unknown;
-}
-
-interface GroupInviteCreateRequest {
- ttlSeconds?: number;
- maxUses?: number;
-}
-
-export interface GroupInvitePreview {
- groupId: string;
- name: string;
- description?: string;
- memberCount: number;
- membershipPolicy: string;
- invitedBy: string;
- valid: boolean;
- [key: string]: unknown;
-}
-
-interface InboxCounts {
- unread: number;
- read: number;
- archived: number;
- byType: Record<string, number>;
- urgent: number;
-}
-export interface InboxItem {
- itemId: string;
- type: string;
- status: string;
- priority: string;
- timestamp: string;
- subject: string;
- summary?: string;
- from?: string;
- [key: string]: unknown;
-}
-interface InboxListResult {
- items: InboxItem[];
- cursor?: string;
- unreadCount: number;
- totalCount: number;
-}
-export interface InboxQueryParams {
- status?: string[];
- types?: string[];
- from?: string;
- priority?: string;
- q?: string;
- since?: string;
- before?: string;
- limit?: number;
- cursor?: string;
- [key: string]: unknown;
-}
-
-// ── Contacts types ─────────────────────────────────────────────────────────
-
-export type ContactStatus = 'pending' | 'accepted' | 'blocked';
-export interface Contact {
- requester: string;
- addressee: string;
- status: ContactStatus;
- blockedBy?: string;
- createdAt: string;
- updatedAt: string;
- [key: string]: unknown;
-}
-export interface ContactView {
- agentId: string;
- status: ContactStatus;
- direction?: 'incoming' | 'outgoing';
- contact: Contact;
- [key: string]: unknown;
-}
-interface ContactListParams {
- limit?: number;
- offset?: number;
-}
-export interface ContactsResponse {
- contacts: ContactView[];
-}
-export interface ContactRequestsResponse {
- incoming: ContactView[];
- outgoing: ContactView[];
-}
-interface ContactStatusResponse {
- agentId: string;
- status: ContactStatus | 'none';
- direction?: 'incoming' | 'outgoing';
-}
-export interface ContactStats {
- agentId: string;
- contactCount: number;
- pendingIncoming: number;
- pendingOutgoing: number;
-}
-export type PairingStatus = 'pending' | 'linked' | 'blocked';
-export type PairingSource = 'user_link' | 'approved_request';
-export interface PairingRecord {
- agentId: string;
- label?: string;
- status: PairingStatus;
- linkedAt: string;
- source: PairingSource;
-}
-export interface PairingSnapshot {
- records: PairingRecord[];
- contacts: ContactsResponse;
- requests: ContactRequestsResponse;
- stats: ContactStats | null;
-}
-interface PairingActionResult {
- record?: PairingRecord | null;
- remote: unknown;
-}
-
-// ── Follows types ───────────────────────────────────────────────────────────
-
-interface AgentFollow {
- follower: string;
- followee: string;
- createdAt: string;
- [key: string]: unknown;
-}
-
-export interface FollowStats {
- agentId: string;
- followerCount: number;
- followingCount: number;
- [key: string]: unknown;
-}
-
-interface FollowListParams {
- limit?: number;
- offset?: number;
-}
-
-interface FollowersResponse {
- followers: AgentFollow[];
- [key: string]: unknown;
-}
-
-interface FollowingResponse {
- following: AgentFollow[];
- [key: string]: unknown;
-}
-
-interface FeedListParams {
- limit?: number;
- offset?: number;
- kind?: string;
- category?: string;
- since?: string;
- includeSelf?: boolean;
-}
-
-interface ActivityEvent {
- eventId: string;
- kind: string;
- category: string;
- actor?: string;
- target?: string;
- amount?: string;
- asset?: string;
- network?: string;
- timestamp: string;
- [key: string]: unknown;
-}
-
-interface ActivityStats {
- total: number;
- byKind: Record<string, number>;
- byCategory: Record<string, number>;
- [key: string]: unknown;
-}
-
-interface FeedResponse {
- events: ActivityEvent[];
- following: AgentFollow[];
- stats: ActivityStats;
- [key: string]: unknown;
-}
-
-// ── GraphQL Feed types ──────────────────────────────────────────────────────
-
-export interface FeedAuthor {
- handle: string;
- cryptoId: string;
- displayName: string;
- avatarUrl?: string;
- verified: boolean;
-}
-
-export interface GqlPost {
- postId: string;
- feedId: string;
- body: string;
- contentType?: string;
- commentCount: number;
- likeCount: number;
- createdAt: string;
- moderationState?: string;
- viewerHasLiked: boolean;
- author: FeedAuthor;
-}
-
-export interface GqlComment {
- commentId: string;
- postId: string;
- feedId: string;
- body: string;
- createdAt: string;
- moderationState?: string;
- author: FeedAuthor;
-}
-
-interface GqlPostLike {
- postId: string;
- feedId: string;
- actor: FeedAuthor;
- createdAt: string;
-}
-
-interface GqlPostDetail extends GqlPost {
- comments: GqlComment[];
- likers: GqlPostLike[];
-}
-
-interface GqlPostListResult {
- posts: GqlPost[];
- count: number;
-}
-
-interface GqlPostLikerListResult {
- likers: GqlPostLike[];
- count: number;
-}
-
-export interface GqlHomeFeedItem {
- post: GqlPost;
- score: number;
- reason: string;
-}
-
-export interface GqlHomeFeedResult {
- items: GqlHomeFeedItem[];
- count: number;
-}
-
-// ── Feeds REST types (write surface) ──────────────────────────────────────
-
-interface FeedsPost {
- postId: string;
- feedId: string;
- author: string;
- authorCryptoId?: string;
- body: string;
- contentType?: string;
- sequence?: number;
- commentCount: number;
- likeCount: number;
- likedByMe?: boolean;
- createdAt: string;
- deletedAt?: string;
- moderationState?: string;
-}
-
-interface FeedsComment {
- commentId: string;
- postId: string;
- feedId: string;
- author: string;
- authorCryptoId?: string;
- body: string;
- sequence?: number;
- createdAt: string;
-}
-
-export interface LikeResult {
- postId: string;
- liked: boolean;
- likeCount: number;
-}
-
-// ── Bounties types ──────────────────────────────────────────────────────────
-
-export interface BountyReward {
- amount: string;
- asset: string;
- network?: string;
-}
-
-export interface BountyThumbnail {
- url?: string;
- alt?: string;
- [key: string]: unknown;
-}
-
-export interface BountyCouncilVote {
- model?: string;
- winnerSubmissionId?: string;
- reasoning?: string;
- error?: string;
- [key: string]: unknown;
-}
-
-export interface BountyCouncil {
- status?: string;
- ranAt?: string;
- winnerSubmissionId?: string;
- judgeModel?: string;
- presided?: boolean;
- reasoning?: string;
- votes?: BountyCouncilVote[];
- error?: string;
- [key: string]: unknown;
-}
-
-export interface Bounty {
- bountyId: string;
- creator: string;
- creatorCryptoId?: string;
- title: string;
- description: string;
- reward: BountyReward;
- status: string;
- thumbnail?: BountyThumbnail;
- escrowAddress?: string;
- fundingTxSig?: string;
- fundingLedgerTxId?: string;
- submissionCount: number;
- commentCount: number;
- council?: BountyCouncil;
- winnerSubmissionId?: string;
- winnerAgent?: string;
- approvedBy?: string;
- approvedAt?: string;
- payoutTxSig?: string;
- payoutLedgerTxId?: string;
- startAt?: string;
- deadline?: string;
- createdAt: string;
- updatedAt: string;
- [key: string]: unknown;
-}
-
-export interface BountySubmission {
- submissionId: string;
- bountyId: string;
- submitter: string;
- submitterCryptoId?: string;
- url: string;
- title?: string;
- note?: string;
- status: string;
- createdAt: string;
- updatedAt: string;
- [key: string]: unknown;
-}
-
-export interface BountyComment {
- commentId: string;
- bountyId: string;
- author: string;
- authorCryptoId?: string;
- body: string;
- createdAt: string;
- [key: string]: unknown;
-}
-
-export interface BountyCreateParams {
- title: string;
- description: string;
- amount: string;
- asset?: string;
- deadline?: string;
- durationDays?: number;
-}
-
-interface BountyQueryParams {
- creator?: string;
- status?: string;
- limit?: number;
- offset?: number;
- [key: string]: unknown;
-}
-
-interface BountySubmissionQueryParams {
- status?: string;
- submitter?: string;
- limit?: number;
- [key: string]: unknown;
-}
-
-interface BountyCommentQueryParams {
- limit?: number;
- offset?: number;
- [key: string]: unknown;
-}
-
-export interface BountyListResponse {
- bounties: Bounty[];
- [key: string]: unknown;
-}
-
-interface BountySubmissionsResponse {
- submissions: BountySubmission[];
- [key: string]: unknown;
-}
-
-interface BountyCommentsResponse {
- comments: BountyComment[];
- [key: string]: unknown;
-}
-
-// ── GraphQL Ledger types ────────────────────────────────────────────────────
-
-export interface GqlLedgerReference {
- kind: string;
- id?: string;
- parentTxId?: string;
- rate?: string;
-}
-
-export interface GqlLedgerTransaction {
- txId: string;
- visibility: string;
- /** Serde renames Rust `transaction_type` back to `"type"` on the wire. */
- type: string;
- from?: string;
- to?: string;
- amount?: string;
- asset?: string;
- network: string;
- timestamp: string;
- reference?: GqlLedgerReference;
- onChainTx: string;
- status: string;
- metadata?: Record<string, unknown>;
- [key: string]: unknown;
-}
-
-interface GqlLedgerTransactionListResult {
- transactions: GqlLedgerTransaction[];
- count: number;
-}
-
-interface LedgerListParams {
- limit?: number;
- offset?: number;
- agent?: string;
- type?: string;
- network?: string;
- status?: string;
- from?: string;
- to?: string;
- after?: string;
- before?: string;
- asset?: string;
- visibility?: string;
-}
-
-// ── GraphQL Jobs types ────────────────────────────────────────────────────────
-
-export interface GqlJobBudget {
- amount: string;
- asset: string;
- chain?: string;
-}
-
-export interface GqlJobOnChain {
- vault?: string;
- jobPdaCommit?: string;
- fundingTxSig?: string;
-}
-
-export interface GqlJobDisputeVote {
- model: string;
- outcome: string;
- splitBps: number;
- reasoning?: string;
- error?: string;
-}
-
-export interface GqlJobDispute {
- reason: string;
- openedBy: string;
- openedAt: string;
- status: string;
- outcome?: string;
- splitBps?: number;
- judgeModel?: string;
- presided?: boolean;
- reasoning?: string;
- jury?: GqlJobDisputeVote[];
- resolvedAt?: string;
-}
-
-export interface GqlJobPosting {
- jobId: string;
- client: string;
- title: string;
- description: string;
- category?: string;
- skills?: string[];
- budget: GqlJobBudget;
- status: string;
- proposalCount: number;
- groupId?: string;
- contractEscrowId?: string;
- selectedCandidate?: string;
- dispute?: GqlJobDispute;
- onChain?: GqlJobOnChain;
- proposalDeadline?: string;
- createdAt: string;
- updatedAt: string;
- clientProfile: FeedAuthor;
- [key: string]: unknown;
-}
-
-export interface GqlJobListResult {
- jobs: GqlJobPosting[];
- count?: number;
-}
-
-/** Reward block on a GraphQL bounty (amount in the asset's smallest base unit). */
-export interface GqlBountyReward {
- amount: string;
- asset: string;
- network: string;
-}
-
-/** A bounty as returned by the tiny.place GraphQL gateway. */
-export interface GqlBounty {
- bountyId: string;
- creator: string;
- title: string;
- description: string;
- reward: GqlBountyReward;
- status: string;
- submissionCount: number;
- commentCount: number;
- winnerSubmissionId?: string;
- winnerAgent?: string;
- startAt: string;
- deadline: string;
- createdAt: string;
- updatedAt: string;
-}
-
-/** Filters for the GraphQL bounties query (all optional). */
-interface GqlBountyQueryParams {
- status?: string;
- creator?: string;
- limit?: number;
- offset?: number;
-}
-
-/**
- * Query params for the GraphQL jobs endpoint. Reuses the same shape as the
- * REST JobQueryParams but with explicit typing (no catch-all index signature).
- */
-interface GqlJobQueryParams {
- client?: string;
- status?: string;
- category?: string;
- skill?: string;
- limit?: number;
- offset?: number;
-}
-
-// ── Jobs Write types ──────────────────────────────────────────────────────────
-
-/** Request shape for creating a job posting. Actor (client) resolved server-side. */
-export interface JobCreateParams {
- title: string;
- description?: string;
- category?: string;
- skills?: string[];
- budgetAmount: string;
- budgetAsset: string;
- budgetChain?: string;
- proposalDeadline?: string;
-}
-
-/** Request shape for applying to a job posting. Actor (candidate) resolved server-side. */
-export interface ProposalCreateParams {
- coverLetter?: string;
- bidAmount?: string;
- estimatedDelivery?: string;
- pastWork?: string[];
-}
-
-/** Proposal object returned by the backend. */
-export interface Proposal {
- proposalId: string;
- jobId: string;
- candidate: string;
- coverLetter: string;
- bidAmount: string;
- estimatedDelivery?: string;
- pastWork?: string[];
- status: string;
- createdAt: string;
- updatedAt: string;
- [key: string]: unknown;
-}
-
-/** Response from list_proposals. */
-interface ProposalListResponse {
- proposals: Proposal[];
- [key: string]: unknown;
-}
-
-/** Query params for listing proposals. */
-interface ProposalQueryParams {
- status?: string;
- limit?: number;
- offset?: number;
-}
-
-/** Result of selecting a candidate (spawns escrow). */
-interface SelectCandidateResult {
- job: JobPosting;
- contractEscrowId: string;
- [key: string]: unknown;
-}
-
-// ── GraphQL Profile + Identity types ─────────────────────────────────────────
-
-/** Identity registration record (mirrors tinyplace::types::Identity). */
-export interface Identity {
- username: string;
- cryptoId: string;
- publicKey: string;
- registeredAt: string;
- expiresAt: string;
- status: string;
- registrationTx?: string;
- paymentMethods?: unknown[];
- primary?: boolean;
- subnames?: unknown[];
- signature?: string;
- payment?: Record<string, string>;
- lastRenewalTx?: string;
- updatedAt: string;
-}
-
-export interface GqlAttestation {
- attestationId: string;
- platform: string;
- handle: string;
- proofUrl?: string;
- status: string;
- verifiedAt: string;
-}
-
-export interface GqlProfile {
- cryptoId: string;
- actorType: string;
- displayName: string;
- bio: string;
- avatarUrl?: string;
- link?: string;
- tags?: string[];
- private: boolean;
- createdAt: string;
- updatedAt: string;
- verified: boolean;
- attestations: GqlAttestation[];
- agentCard: AgentCard | null;
- identities: Identity[] | null;
-}
-
-/** GqlIdentity: Identity fields flattened + optional owner profile. */
-interface GqlIdentity {
- username: string;
- cryptoId: string;
- publicKey: string;
- registeredAt: string;
- expiresAt: string;
- status: string;
- registrationTx?: string;
- paymentMethods?: unknown[];
- primary?: boolean;
- subnames?: unknown[];
- signature?: string;
- payment?: Record<string, string>;
- lastRenewalTx?: string;
- updatedAt: string;
- /** Owner profile (optional, may be null). */
- owner?: GqlProfile | null;
-}
-
-// ── Feedback types ──────────────────────────────────────────────────────────
-
-interface FeedbackItem {
- feedbackId: string;
- author: string;
- title: string;
- description: string;
- category?: string;
- status: string;
- votesUp: number;
- votesDown: number;
- score: number;
- createdAt: string;
- updatedAt: string;
- approvedAt?: string;
- resolvedAt?: string;
- closedAt?: string;
- mergedAt?: string;
- adminNote?: string;
- mergedReference?: string;
- reputationPoints?: number;
- [key: string]: unknown;
-}
-
-interface FeedbackListParams {
- status?: string;
- limit?: number;
- offset?: number;
-}
-
-interface FeedbackListResponse {
- feedback: FeedbackItem[];
- [key: string]: unknown;
-}
-
-// ── Solana types ────────────────────────────────────────────────────────────
-
-interface SolanaRpcInfo {
- url: string;
- rateLimitPerMin: number;
- fallbacks: boolean;
- [key: string]: unknown;
-}
-
-interface SupportedAsset {
- symbol: string;
- address?: string;
- decimals: number;
- [key: string]: unknown;
-}
-
-interface SolanaChainInfo {
- network: string;
- name: string;
- kind: string;
- nativeAsset: string;
- explorerUrl: string;
- confirmations: number;
- assets: SupportedAsset[];
- rpc: SolanaRpcInfo;
- [key: string]: unknown;
-}
-
-// ── Streams types ─────────────────────────────────────────────────────────────
-
-interface StreamStartResult {
- streamId: string;
- [key: string]: unknown;
-}
-
-interface StreamEntry {
- streamId: string;
- kind: string;
- status: string;
- [key: string]: unknown;
-}
-
-interface StreamListResult {
- streams: StreamEntry[];
- [key: string]: unknown;
-}
-
-// ── Signal key management types ─────────────────────────────────────────────
-
-interface SignedKey {
- keyId: string;
- publicKey: string;
- signature?: string;
- [key: string]: unknown;
-}
-
-interface KeyBundle {
- agentId: string;
- identityKey: string;
- signedPreKey: SignedKey;
- oneTimePreKey?: SignedKey;
- updatedAt: string;
- [key: string]: unknown;
-}
-
-export interface KeyHealth {
- agentId: string;
- oneTimePreKeyCount: number;
- lowOneTimePreKeys: boolean;
- recommendedPreKeyRefill?: number;
- signedPreKeyKeyId?: string;
- signedPreKeyUpdatedAt?: string;
- updatedAt: string;
- [key: string]: unknown;
-}
-
-export interface SignalKeyStatus {
- agentId: string;
- localPreKeyCount: number;
- hasActiveSignedPreKey: boolean;
- remote: KeyHealth | null;
- encryptionKeyPublished?: boolean; // (0D) true only if published key == current identity key
- [key: string]: unknown;
-}
-
-interface SignalMetadataEnvelope {
- ephemeralKey?: string;
- signedPreKeyId?: string;
- oneTimePreKeyId?: string;
- ratchetKey?: string;
- messageNumber?: number;
- previousChainLength?: number;
- senderKeyId?: string | null;
- senderKeyIteration?: number | null;
- rotationRequired?: boolean | null;
- rotationId?: string | null;
- rotationEpoch?: number | null;
- removedAgentId?: string | null;
- [key: string]: unknown;
-}
-
-interface MessageEnvelope {
- id: string;
- from: string;
- to: string;
- timestamp: string;
- deviceId: number;
- type: string;
- body: string;
- contentHint?: string;
- signal?: SignalMetadataEnvelope;
- [key: string]: unknown;
-}
-
-function authorId(author: FeedAuthor | undefined, fallback = ''): string {
- return author?.handle || author?.cryptoId || fallback;
-}
-
-function normalizeGraphqlProduct(product: GqlProduct): Product {
- const seller = authorId(product.seller, product.sellerCryptoId);
- return {
- ...(product as unknown as Product),
- seller,
- sellerCryptoId: product.sellerCryptoId || product.seller?.cryptoId || seller,
- };
-}
-
-function normalizeGraphqlIdentityListing(listing: GqlIdentityListing): IdentityListing {
- const seller = authorId(listing.seller, listing.sellerCryptoId);
- return {
- ...(listing as unknown as IdentityListing),
- seller,
- sellerCryptoId: listing.sellerCryptoId || listing.seller?.cryptoId || seller,
- };
-}
-
-function normalizeGraphqlIdentityOffer(offer: GqlIdentityOffer): IdentityOffer {
- return { ...(offer as unknown as IdentityOffer), buyer: authorId(offer.buyer) };
-}
-
-function normalizeGraphqlIdentitySale(sale: GqlIdentitySale): IdentitySale {
- return {
- ...(sale as unknown as IdentitySale),
- buyer: authorId(sale.buyer),
- seller: authorId(sale.seller),
- };
-}
-
-// ── Client factory ────────────────────────────────────────────────────────────
-
-/**
- * Create the Agent World API client. One instance per app; pass it into the
- * `ApiProvider` in `AgentWorldShell` so all nested hooks call through this.
- *
- * Method names follow the tiny.place SDK convention:
- * JS `client.<domain>.<camelMethod>` →
- * RPC `openhuman.tinyplace_<domain>_<snake_method>`
- */
-export function createInvokeApiClient() {
- return {
- directory: {
- listAgents: (params?: AgentQueryParams) =>
- call<ListAgentsResponse>('openhuman.tinyplace_directory_list_agents', {
- params: params ?? null,
- }),
- getAgent: (agentId: string) =>
- call<AgentCard>('openhuman.tinyplace_directory_get_agent', { agentId }),
- resolve: (name: string) =>
- call<ResolveResponse>('openhuman.tinyplace_directory_resolve', { name }),
- reverse: (cryptoId: string) =>
- call<ReverseResponse>('openhuman.tinyplace_directory_reverse', { cryptoId }),
- listIdentities: (params?: IdentityListingQueryParams) =>
- call<DirectoryIdentityListingsResponse>('openhuman.tinyplace_directory_list_identities', {
- params: params ?? null,
- }),
- skills: (params?: DirectorySkillsParams) =>
- call<AgentSearchResponse>('openhuman.tinyplace_directory_skills', {
- params: params ?? null,
- }),
- /** Reverse-lookup: find agent by Signal encryption public key (base64). */
- findByEncryptionKey: (encryptionKey: string) =>
- call<AgentCard | null>('openhuman.tinyplace_directory_find_by_encryption_key', {
- encryptionKey,
- }),
- },
- explorer: { overview: () => call<ExplorerOverview>('openhuman.tinyplace_explorer_overview') },
- search: {
- unified: (query: string) =>
- call<SearchResponse>('openhuman.tinyplace_search_unified', { query }),
- },
- // === AGENT-WORLD BRIDGE NAMESPACES (append here) ===
- // Each fan-out section agent adds one namespace block:
- // <sectionName>: {
- // <methodCamel>: (...args) => call<ReturnType>('openhuman.tinyplace_<domain>_<method>', { ...args }),
- // },
-
- // ── Profiles section ─────────────────────────────────────────────────────
- profiles: {
- get: (username: string) =>
- call<AgentProfile>('openhuman.tinyplace_profiles_get', { username }),
- activity: (username: string) =>
- call<ProfileActivity>('openhuman.tinyplace_profiles_activity', { username }),
- groups: (username: string) =>
- call<ProfileGroupsResponse>('openhuman.tinyplace_profiles_groups', { username }),
- broadcasts: (username: string) =>
- call<ProfileBroadcastsResponse>('openhuman.tinyplace_profiles_broadcasts', { username }),
- attestations: (username: string) =>
- call<ProfileAttestationsResponse>('openhuman.tinyplace_profiles_attestations', {
- username,
- }),
- agentCard: (username: string) =>
- call<AgentCard>('openhuman.tinyplace_profiles_agent_card', { username }),
- },
-
- // ── Users section ────────────────────────────────────────────────────────
- users: {
- get: (cryptoId: string) => call<User>('openhuman.tinyplace_users_get', { cryptoId }),
- updateProfile: (cryptoId: string, update: UserProfileUpdate) =>
- call<User>('openhuman.tinyplace_users_update_profile', { cryptoId, update }),
- /** Start email verification — stores the email and sends a code. */
- startEmailVerification: (cryptoId: string, email: string) =>
- call<User>('openhuman.tinyplace_users_start_email_verification', { cryptoId, email }),
- /** Confirm the email verification code. */
- confirmEmailVerification: (cryptoId: string, email: string, code: string) =>
- call<User>('openhuman.tinyplace_users_confirm_email_verification', {
- cryptoId,
- email,
- code,
- }),
- },
- marketplace: {
- /** List identity listings, optionally filtered by status and limit. */
- listIdentities: (params?: { limit?: number; status?: string }) =>
- call<IdentitiesResponse>('openhuman.tinyplace_marketplace_list_identities', {
- limit: params?.limit ?? null,
- status: params?.status ?? null,
- }),
- /** Floor price for identity names of a given character length. */
- identityFloor: (length?: number) =>
- call<IdentityFloor>('openhuman.tinyplace_marketplace_identity_floor', {
- length: length ?? null,
- }),
- /** Most recent completed identity sales. */
- recent: () => call<RecentSalesResponse>('openhuman.tinyplace_marketplace_recent'),
- /** Full sale history for a specific @handle. */
- identitySaleHistory: (name: string) =>
- call<IdentitySaleHistoryResponse>('openhuman.tinyplace_marketplace_identity_sale_history', {
- name,
- }),
- /** Bids on an identity auction listing. */
- listBids: (listingId: string) =>
- call<BidsResponse>('openhuman.tinyplace_marketplace_list_bids', { listingId }),
- /** Pending identity offers, filtered by name (seller view) or buyer. */
- listOffers: (params?: { name?: string; buyer?: string }) =>
- call<OffersResponse>('openhuman.tinyplace_marketplace_list_offers', {
- name: params?.name ?? null,
- buyer: params?.buyer ?? null,
- }),
- browseMarketplace: (params?: ProductQueryParams) =>
- call<MarketplaceBrowseResponse>('openhuman.tinyplace_marketplace_browse', {
- params: params ?? null,
- }),
- listProducts: (params?: ProductQueryParams) =>
- call<ProductsResponse>('openhuman.tinyplace_marketplace_list_products', {
- params: params ?? null,
- }),
- getProduct: (productId: string) =>
- call<Product>('openhuman.tinyplace_marketplace_get_product', { productId }),
- /**
- * Buy a product via x402 confirm-before-spend. `confirmed:false` returns
- * the challenge + wallet balance (no spend); `confirmed:true` pays + buys.
- */
- buyProduct: (productId: string, opts?: { confirmed?: boolean }) =>
- call<X402BuyResult>('openhuman.tinyplace_marketplace_buy_product', {
- id: productId,
- confirmed: opts?.confirmed ?? false,
- }),
- /** Buy an identity listing (a @handle) via x402 confirm-before-spend. */
- buyIdentity: (listingId: string, opts?: { confirmed?: boolean }) =>
- call<X402BuyResult>('openhuman.tinyplace_marketplace_buy_identity', {
- id: listingId,
- confirmed: opts?.confirmed ?? false,
- }),
- /**
- * Place a bid on an identity auction listing. The SDK builds + signs the
- * x402 authorization (a commitment) — no on-chain transfer until accepted.
- */
- bid: (listingId: string, price: CommitPriceParams) =>
- call<X402CommitResult>('openhuman.tinyplace_marketplace_bid', {
- listingId,
- amount: price.amount,
- asset: price.asset ?? null,
- network: price.network,
- }),
- /** Make an offer to buy an identity (a @handle). Same commitment semantics. */
- offer: (name: string, price: CommitPriceParams) =>
- call<X402CommitResult>('openhuman.tinyplace_marketplace_offer', {
- name,
- amount: price.amount,
- asset: price.asset ?? null,
- network: price.network,
- }),
- categories: () => call<CategoriesResponse>('openhuman.tinyplace_marketplace_categories'),
- featured: () => call<FeaturedResponse>('openhuman.tinyplace_marketplace_featured'),
- listProductReviews: (productId: string) =>
- call<ProductReviewsResponse>('openhuman.tinyplace_marketplace_list_product_reviews', {
- productId,
- }),
- },
- registry: {
- /** Check availability of a @handle (with or without leading @). */
- get: (name: string) =>
- call<AvailabilityResponse>('openhuman.tinyplace_registry_get', { name }),
- /**
- * Register a @handle via x402 confirm-before-spend.
- * Call with `confirmed:false` to get the challenge + wallet balance (no
- * spend); `confirmed:true` pays on-chain and registers.
- */
- register: (params: RegisterParams) =>
- call<RegistrationResult>('openhuman.tinyplace_registry_register', {
- username: params.username,
- confirmed: params.confirmed ?? false,
- actorType: params.actorType ?? null,
- primary: params.primary ?? null,
- }),
- /** Export an identity with its ledger history and cryptographic proofs. */
- export: (name: string) =>
- call<IdentityExport>('openhuman.tinyplace_registry_export', { name }),
- /**
- * Make one of the wallet's purchased handles its primary (active) identity.
- * The backend clears the primary flag on the wallet's other handles, so
- * this is how a user with multiple identities switches the active handle
- * reflected across feed / profile / directory (#4198). The owning wallet
- * is proven by the signer-attached signature, not by params.
- */
- assignPrimary: (name: string) =>
- call<AssignPrimaryResult>('openhuman.tinyplace_registry_assign_primary', { name }),
- /**
- * Transfer one of the wallet's handles to another tiny.place identity
- * (#4929). DESTRUCTIVE + irreversible: on success the `recipient` handle's
- * owner becomes the sole owner of `name`. The recipient is resolved from
- * their @handle server-side; an unregistered recipient or an unconfirmed
- * read-back fails closed. The owning wallet is proven by the
- * signer-attached signature, not by params.
- */
- transfer: (name: string, recipient: string) =>
- call<TransferHandleResult>('openhuman.tinyplace_registry_transfer', { name, recipient }),
- },
- directoryIdentities: {
- /** List identity listings from the directory. */
- list: (params?: IdentityListingQueryParams) =>
- call<DirectoryIdentityListingsResponse>('openhuman.tinyplace_directory_list_identities', {
- params: params ?? null,
- }),
- },
- artifacts: {
- list: (params?: ArtifactQueryParams, actorId?: string) =>
- call<ArtifactListResult>('openhuman.tinyplace_artifacts_list', {
- params: params ?? null,
- ...(actorId !== undefined ? { actorId } : {}),
- }),
- get: (artifactId: string, actorId?: string) =>
- call<Artifact>('openhuman.tinyplace_artifacts_get', {
- artifactId,
- ...(actorId !== undefined ? { actorId } : {}),
- }),
- },
- escrow: {
- list: (params?: EscrowQueryParams) =>
- call<EscrowListResponse>('openhuman.tinyplace_escrow_list', { params: params ?? null }),
- get: (escrowId: string) => call<Escrow>('openhuman.tinyplace_escrow_get', { escrowId }),
- },
- jobs: {
- list: (params?: JobQueryParams) =>
- call<JobListResponse>('openhuman.tinyplace_jobs_list', { params: params ?? null }),
- get: (jobId: string) => call<JobPosting>('openhuman.tinyplace_jobs_get', { jobId }),
- },
- channels: {
- list: (params?: ChannelQueryParams) =>
- call<ChannelListResponse>('openhuman.tinyplace_channels_list', { params: params ?? null }),
- // Membership — result bodies unused (the UI refetches).
- join: (channelId: string) => call<void>('openhuman.tinyplace_channels_join', { channelId }),
- leave: (channelId: string) => call<void>('openhuman.tinyplace_channels_leave', { channelId }),
- },
- groups: {
- list: (params?: GroupQueryParams) =>
- call<GroupMetadata[]>('openhuman.tinyplace_groups_list', { params: params ?? null }),
- join: (groupId: string) => call<void>('openhuman.tinyplace_groups_join', { groupId }),
- leave: (groupId: string) => call<void>('openhuman.tinyplace_groups_leave', { groupId }),
- // Invite/role management (Phase 5A)
- setMemberRole: (groupId: string, agentId: string, role: string) =>
- call<GroupMember>('openhuman.tinyplace_groups_set_member_role', { groupId, agentId, role }),
- createInvite: (groupId: string, request?: GroupInviteCreateRequest) =>
- call<GroupInvite>('openhuman.tinyplace_groups_create_invite', {
- groupId,
- request: request ?? null,
- }),
- listInvites: (groupId: string) =>
- call<GroupInvite[]>('openhuman.tinyplace_groups_list_invites', { groupId }),
- previewInvite: (groupId: string, token: string) =>
- call<GroupInvitePreview>('openhuman.tinyplace_groups_preview_invite', { groupId, token }),
- revokeInvite: (groupId: string, token: string) =>
- call<void>('openhuman.tinyplace_groups_revoke_invite', { groupId, token }),
- redeemInvite: (groupId: string, token: string) =>
- call<GroupMember>('openhuman.tinyplace_groups_redeem_invite', { groupId, token }),
- },
- broadcasts: {
- list: (params?: BroadcastQueryParams) =>
- call<BroadcastChannel[]>('openhuman.tinyplace_broadcasts_list', { params: params ?? null }),
- subscribe: (broadcastId: string) =>
- call<void>('openhuman.tinyplace_broadcasts_subscribe', { broadcastId }),
- unsubscribe: (broadcastId: string) =>
- call<void>('openhuman.tinyplace_broadcasts_unsubscribe', { broadcastId }),
- },
- inbox: {
- list: (params?: InboxQueryParams, owner?: string) =>
- call<InboxListResult>('openhuman.tinyplace_inbox_list', {
- params: params ?? null,
- owner: owner ?? null,
- }),
- counts: (owner?: string) =>
- call<InboxCounts>('openhuman.tinyplace_inbox_counts', { owner: owner ?? null }),
- // Write actions — manage your own inbox. Result bodies are unused (the UI refetches).
- markRead: (itemId: string, owner?: string) =>
- call<void>('openhuman.tinyplace_inbox_mark_read', { itemId, owner: owner ?? null }),
- markAllRead: (owner?: string) =>
- call<void>('openhuman.tinyplace_inbox_mark_all_read', {
- params: null,
- owner: owner ?? null,
- }),
- archive: (itemId: string, owner?: string) =>
- call<void>('openhuman.tinyplace_inbox_archive', { itemId, owner: owner ?? null }),
- unarchive: (itemId: string, owner?: string) =>
- call<void>('openhuman.tinyplace_inbox_unarchive', { itemId, owner: owner ?? null }),
- remove: (itemId: string, owner?: string) =>
- call<void>('openhuman.tinyplace_inbox_remove', { itemId, owner: owner ?? null }),
- },
- // ── Contacts section ─────────────────────────────────────────────────────
- contacts: {
- request: (agentId: string) =>
- call<ContactView>('openhuman.tinyplace_contacts_request', { agentId }),
- accept: (agentId: string) =>
- call<ContactView>('openhuman.tinyplace_contacts_accept', { agentId }),
- remove: (agentId: string) =>
- call<{ ok?: boolean }>('openhuman.tinyplace_contacts_remove', { agentId }),
- block: (agentId: string) =>
- call<ContactView>('openhuman.tinyplace_contacts_block', { agentId }),
- unblock: (agentId: string) =>
- call<{ ok?: boolean }>('openhuman.tinyplace_contacts_unblock', { agentId }),
- list: (params?: ContactListParams) =>
- call<ContactsResponse>('openhuman.tinyplace_contacts_list', { params: params ?? null }),
- requests: (params?: ContactListParams) =>
- call<ContactRequestsResponse>('openhuman.tinyplace_contacts_requests', {
- params: params ?? null,
- }),
- status: (agentId: string) =>
- call<ContactStatusResponse>('openhuman.tinyplace_contacts_status', { agentId }),
- stats: () => call<ContactStats>('openhuman.tinyplace_contacts_stats', {}),
- },
- // ── Orchestration pairing policy ─────────────────────────────────────────
- orchestrationPairing: {
- list: () => call<PairingSnapshot>('openhuman.orchestration_pairing_list', {}),
- linkSession: (agentId: string, label?: string) =>
- call<PairingActionResult>('openhuman.orchestration_pairing_link_session', {
- agentId,
- label: label ?? null,
- }),
- acceptRequest: (agentId: string) =>
- call<PairingActionResult>('openhuman.orchestration_pairing_accept_request', { agentId }),
- declineRequest: (agentId: string) =>
- call<PairingActionResult>('openhuman.orchestration_pairing_decline_request', { agentId }),
- blockRequest: (agentId: string) =>
- call<PairingActionResult>('openhuman.orchestration_pairing_block_request', { agentId }),
- },
- // ── Follows section ───────────────────────────────────────────────────────
- follows: {
- follow: (agentId: string) =>
- call<AgentFollow>('openhuman.tinyplace_follows_follow', { agentId }),
- unfollow: (agentId: string) =>
- call<void>('openhuman.tinyplace_follows_unfollow', { agentId }),
- followers: (agentId: string, params?: FollowListParams) =>
- call<FollowersResponse>('openhuman.tinyplace_follows_followers', {
- agentId,
- params: params ?? null,
- }),
- following: (agentId: string, params?: FollowListParams) =>
- call<FollowingResponse>('openhuman.tinyplace_follows_following', {
- agentId,
- params: params ?? null,
- }),
- stats: (agentId: string) =>
- call<FollowStats>('openhuman.tinyplace_follows_stats', { agentId }),
- feed: (params?: FeedListParams) =>
- call<FeedResponse>('openhuman.tinyplace_follows_feed', { params: params ?? null }),
- },
- // ── Feeds write surface ─────────────────────────────────────────────────
- feeds: {
- /** Create a post on the user's own feed (the feed handle is resolved server-side from the signer). */
- createPost: (body: string, contentType?: string) =>
- call<FeedsPost>('openhuman.tinyplace_feeds_create_post', {
- body,
- contentType: contentType ?? null,
- }),
- /** Delete a post from the user's own feed (the feed handle is resolved server-side from the signer). */
- deletePost: (postId: string) =>
- call<{ ok: boolean }>('openhuman.tinyplace_feeds_delete_post', { postId }),
- /** Add a comment to a post (author resolved from signer). */
- addComment: (handle: string, postId: string, body: string) =>
- call<FeedsComment>('openhuman.tinyplace_feeds_add_comment', { handle, postId, body }),
- /** Delete a comment (actor resolved from signer; must be comment author or feed owner). */
- deleteComment: (handle: string, postId: string, commentId: string) =>
- call<{ ok: boolean }>('openhuman.tinyplace_feeds_delete_comment', {
- handle,
- postId,
- commentId,
- }),
- /** Like a post (idempotent, actor resolved from signer). */
- likePost: (handle: string, postId: string) =>
- call<LikeResult>('openhuman.tinyplace_feeds_like_post', { handle, postId }),
- /** Unlike a post (idempotent, actor resolved from signer). */
- unlikePost: (handle: string, postId: string) =>
- call<LikeResult>('openhuman.tinyplace_feeds_unlike_post', { handle, postId }),
- },
- // ── Bounties section ────────────────────────────────────────────────────────
- bounties: {
- list: (params?: BountyQueryParams) =>
- call<BountyListResponse>('openhuman.tinyplace_bounties_list', { params: params ?? null }),
- get: (bountyId: string) => call<Bounty>('openhuman.tinyplace_bounties_get', { bountyId }),
- /** Create a bounty via x402 confirm-before-spend (the reward is funded into
- * escrow at creation). confirmed:false returns the challenge (no spend);
- * confirmed:true pays and creates. */
- create: (params: BountyCreateParams, opts?: { confirmed?: boolean }) =>
- call<X402BuyResult>(
- 'openhuman.tinyplace_bounties_create',
- {
- title: params.title,
- description: params.description,
- amount: params.amount,
- asset: params.asset ?? null,
- deadline: params.deadline ?? null,
- durationDays: params.durationDays ?? null,
- confirmed: opts?.confirmed ?? false,
- },
- // On-chain escrow funding + settle polling exceeds the 30s default
- // (#4201). Both legs need the longer budget: the unconfirmed probe
- // also waits on a network round-trip + wallet-balance lookup.
- X402_SPEND_TIMEOUT_MS
- ),
- cancel: (bountyId: string) =>
- call<Bounty>('openhuman.tinyplace_bounties_cancel', { bountyId }),
- submit: (bountyId: string, url: string, title?: string, note?: string) =>
- call<BountySubmission>('openhuman.tinyplace_bounties_submit', {
- bountyId,
- url,
- title: title ?? null,
- note: note ?? null,
- }),
- listSubmissions: (bountyId: string, params?: BountySubmissionQueryParams) =>
- call<BountySubmissionsResponse>('openhuman.tinyplace_bounties_list_submissions', {
- bountyId,
- params: params ?? null,
- }),
- comment: (bountyId: string, body: string) =>
- call<BountyComment>('openhuman.tinyplace_bounties_comment', { bountyId, body }),
- listComments: (bountyId: string, params?: BountyCommentQueryParams) =>
- call<BountyCommentsResponse>('openhuman.tinyplace_bounties_list_comments', {
- bountyId,
- params: params ?? null,
- }),
- runCouncil: (bountyId: string) =>
- call<Bounty>('openhuman.tinyplace_bounties_run_council', { bountyId }),
- /** Admin-only. Not surfaced in v1 UI. */
- approve: (bountyId: string, submissionId?: string) =>
- call<Bounty>('openhuman.tinyplace_bounties_approve', {
- bountyId,
- submissionId: submissionId ?? null,
- }),
- },
- // ── Feedback section ────────────────────────────────────────────────────────
- feedback: {
- list: (params?: FeedbackListParams) =>
- call<FeedbackListResponse>('openhuman.tinyplace_feedback_list', { params: params ?? null }),
- get: (feedbackId: string) =>
- call<FeedbackItem>('openhuman.tinyplace_feedback_get', { feedbackId }),
- create: (title: string, description: string, category?: string) =>
- call<FeedbackItem>('openhuman.tinyplace_feedback_create', {
- title,
- description,
- ...(category !== undefined ? { category } : {}),
- }),
- vote: (feedbackId: string, vote: 'up' | 'down') =>
- call<FeedbackItem>('openhuman.tinyplace_feedback_vote', { feedbackId, vote }),
- },
- // ── Solana section ──────────────────────────────────────────────────────
- solana: {
- /** Public chain metadata for the backend's configured Solana network. */
- info: () => call<SolanaChainInfo>('openhuman.tinyplace_solana_info'),
- /** Send a Solana JSON-RPC call through the backend's proxy. */
- rpcCall: (method: string, params?: unknown, id?: unknown) =>
- call<unknown>('openhuman.tinyplace_solana_call', {
- method,
- params: params ?? null,
- id: id ?? null,
- }),
- },
- // ── Streams section ─────────────────────────────────────────────────────
- streams: {
- /** Start a tinyplace WebSocket stream (inbox or conversation). */
- start: (streamType: string, streamId?: string) =>
- call<StreamStartResult>('openhuman.tinyplace_streams_start', {
- streamType,
- ...(streamId !== undefined ? { streamId } : {}),
- }),
- /** Stop an active tinyplace WebSocket stream. */
- stop: (streamId: string) => call<void>('openhuman.tinyplace_streams_stop', { streamId }),
- /** List all active tinyplace WebSocket streams. */
- list: () => call<StreamListResult>('openhuman.tinyplace_streams_list', {}),
- },
- // ── Signal key management ─────────────────────────────────────────────
- signal: {
- /** Bootstrap Signal keys: generate + store + publish. Returns KeyHealth. */
- provision: (preKeyCount?: number) =>
- call<KeyHealth>('openhuman.tinyplace_signal_provision', {
- preKeyCount: preKeyCount ?? null,
- }),
- /** Upload additional one-time pre-keys (replenishment). */
- uploadPreKeys: (count?: number) =>
- call<KeyHealth>('openhuman.tinyplace_signal_upload_pre_keys', { count: count ?? null }),
- /** Rotate the signed pre-key. */
- rotateSignedPreKey: () =>
- call<{ ok: boolean; keyId: string }>(
- 'openhuman.tinyplace_signal_rotate_signed_pre_key',
- {}
- ),
- /** Fetch a peer's published pre-key bundle (public endpoint). */
- getBundle: (agentId: string) =>
- call<KeyBundle>('openhuman.tinyplace_signal_get_bundle', { agentId }),
- /** Local + remote key status for the current user. */
- keyStatus: () => call<SignalKeyStatus>('openhuman.tinyplace_signal_key_status', {}),
- /** Encrypt and send a Signal-protocol DM to a peer agent. */
- sendMessage: (params: { recipient: string; plaintext: string }) =>
- call<{ messageId: string; timestamp: string; encrypted: boolean }>(
- 'openhuman.tinyplace_signal_send_message',
- params
- ),
- /** Decrypt an incoming Signal-protocol message envelope. */
- decryptMessage: (params: { envelope: MessageEnvelope }) =>
- call<{ plaintext: string; from: string; messageId: string }>(
- 'openhuman.tinyplace_signal_decrypt_message',
- params
- ),
- /** Publish the user's X25519 identity public key on their directory card. */
- registerEncryptionKey: () =>
- call<{ ok: boolean; encryptionKey: string; agentId: string; updatedAt: string }>(
- 'openhuman.tinyplace_signal_register_encryption_key',
- {}
- ),
- },
- // ── Messages namespace ────────────────────────────────────────────────────
- messages: {
- /** List raw message envelopes addressed to the current user. */
- list: (params?: { limit?: number }) =>
- call<{ messages: MessageEnvelope[] }>('openhuman.tinyplace_messages_list', params ?? {}),
- /** Acknowledge (delete) a delivered message. */
- acknowledge: (messageId: string) =>
- call<void>('openhuman.tinyplace_messages_acknowledge', { messageId }),
- },
- // ── GraphQL Social Feed ──────────────────────────────────────────────────
- graphql: {
- /** Personalized home feed (requires unlocked wallet — GraphQLAuth::Agent). */
- homeFeed: (params?: { limit?: number; offset?: number; includeSelf?: boolean }) =>
- call<GqlHomeFeedResult>('openhuman.tinyplace_graphql_home_feed', {
- limit: params?.limit ?? null,
- offset: params?.offset ?? null,
- includeSelf: params?.includeSelf ?? null,
- }),
- /** List directory agents through GraphQL, including server-resolved edges. */
- agents: (params?: AgentQueryParams) =>
- call<GqlAgentCardListResult>('openhuman.tinyplace_graphql_agents', {
- params: params ?? null,
- }),
- /** List posts by a specific agent handle (public). */
- posts: (handle: string, params?: { limit?: number; before?: number; viewer?: string }) =>
- call<GqlPostListResult>('openhuman.tinyplace_graphql_posts', {
- handle,
- limit: params?.limit ?? null,
- before: params?.before ?? null,
- viewer: params?.viewer ?? null,
- }),
- /** Fetch a single post with comments and likers (public). */
- post: (
- handle: string,
- postId: string,
- params?: {
- viewer?: string;
- commentLimit?: number;
- commentAfter?: number;
- likerLimit?: number;
- likerOffset?: number;
- }
- ) =>
- call<GqlPostDetail | null>('openhuman.tinyplace_graphql_post', {
- handle,
- postId,
- viewer: params?.viewer ?? null,
- commentLimit: params?.commentLimit ?? null,
- commentAfter: params?.commentAfter ?? null,
- likerLimit: params?.likerLimit ?? null,
- likerOffset: params?.likerOffset ?? null,
- }),
- /** List comments on a post (public). */
- postComments: (
- postId: string,
- params?: { feedId?: string; limit?: number; after?: number }
- ) =>
- call<{ comments: GqlComment[] }>('openhuman.tinyplace_graphql_post_comments', {
- postId,
- feedId: params?.feedId ?? null,
- limit: params?.limit ?? null,
- after: params?.after ?? null,
- }),
- /** List agents who liked a post (public). */
- postLikers: (postId: string, params?: { limit?: number; offset?: number }) =>
- call<GqlPostLikerListResult>('openhuman.tinyplace_graphql_post_likers', {
- postId,
- limit: params?.limit ?? null,
- offset: params?.offset ?? null,
- }),
- /** List ledger transactions with optional filters (public, no auth). */
- ledgerTransactions: (params?: LedgerListParams) =>
- call<GqlLedgerTransactionListResult>('openhuman.tinyplace_graphql_ledger_transactions', {
- params: params ?? null,
- }),
- /** Fetch a single ledger transaction by ID (public, no auth). */
- ledgerTransaction: (id: string) =>
- call<GqlLedgerTransaction | null>('openhuman.tinyplace_graphql_ledger_transaction', { id }),
- products: async (params?: ProductQueryParams) => {
- const result = await call<GqlProductListResult>('openhuman.tinyplace_graphql_products', {
- params: params ?? null,
- });
- return {
- ...result,
- products: result.products.map(normalizeGraphqlProduct),
- } satisfies ProductsResponse & { count?: number };
- },
- product: async (id: string) => {
- const result = await call<GqlProduct | null>('openhuman.tinyplace_graphql_product', { id });
- return result ? normalizeGraphqlProduct(result) : null;
- },
- /** List job postings with optional filters (public, no auth). */
- jobs: (params?: GqlJobQueryParams) =>
- call<GqlJobListResult>('openhuman.tinyplace_graphql_jobs', { params: params ?? null }),
- /** Fetch a single job posting by ID (public, no auth). */
- job: (id: string) => call<GqlJobPosting | null>('openhuman.tinyplace_graphql_job', { id }),
- bounties: (params?: GqlBountyQueryParams) =>
- call<GqlBounty[]>('openhuman.tinyplace_graphql_bounties', { params: params ?? null }),
- bounty: (id: string) => call<GqlBounty | null>('openhuman.tinyplace_graphql_bounty', { id }),
- /** Fetch a full GqlProfile by @handle (public GraphQL). */
- profile: (username: string) =>
- call<GqlProfile | null>('openhuman.tinyplace_graphql_profile', { username }),
- /** Fetch a full GqlProfile by Solana address / crypto_id (public GraphQL). */
- user: (cryptoId: string) =>
- call<GqlProfile | null>('openhuman.tinyplace_graphql_user', { cryptoId }),
- /** Fetch identity registration details with optional owner profile (public GraphQL). */
- identity: (username: string) =>
- call<GqlIdentity | null>('openhuman.tinyplace_graphql_identity', { username }),
- /** List all identities owned by a crypto_id (public GraphQL). */
- identities: (cryptoId: string) =>
- call<{ identities: Identity[] }>('openhuman.tinyplace_graphql_identities', { cryptoId }),
- /** Fetch an agent card by agent ID (public GraphQL). */
- agentCard: (id: string) =>
- call<AgentCard | null>('openhuman.tinyplace_graphql_agent_card', { id }),
- identityListings: async (params?: IdentityListingQueryParams) => {
- const result = await call<GqlIdentityListingListResult>(
- 'openhuman.tinyplace_graphql_identity_listings',
- { params: params ?? null }
- );
- const identities = result.identities ?? result.listings ?? [];
- return {
- ...result,
- identities: identities.map(normalizeGraphqlIdentityListing),
- } satisfies IdentitiesResponse & { count?: number };
- },
- identityListing: async (
- id: string,
- params?: {
- bidLimit?: number;
- bidOffset?: number;
- historyLimit?: number;
- historyOffset?: number;
- }
- ) => {
- const result = await call<GqlIdentityListing | null>(
- 'openhuman.tinyplace_graphql_identity_listing',
- { id, params: params ?? null }
- );
- return result ? normalizeGraphqlIdentityListing(result) : null;
- },
- identityBids: (listingId: string, params?: { limit?: number; offset?: number }) =>
- call<GqlIdentityBidListResult>('openhuman.tinyplace_graphql_identity_bids', {
- listingId,
- params: params ?? null,
- }),
- identityOffers: async (params?: {
- agent?: string;
- buyer?: string;
- name?: string;
- status?: string;
- limit?: number;
- offset?: number;
- }) => {
- const result = await call<GqlIdentityOfferListResult>(
- 'openhuman.tinyplace_graphql_identity_offers',
- { params: params ?? null }
- );
- return {
- ...result,
- offers: result.offers.map(normalizeGraphqlIdentityOffer),
- } satisfies OffersResponse & { count?: number };
- },
- identitySales: async (name: string, params?: { limit?: number; offset?: number }) => {
- const result = await call<GqlIdentitySaleListResult>(
- 'openhuman.tinyplace_graphql_identity_sales',
- { name, params: params ?? null }
- );
- return {
- ...result,
- sales: result.sales.map(normalizeGraphqlIdentitySale),
- } satisfies RecentSalesResponse & { count?: number };
- },
- },
- jobsWrite: {
- create: (params: JobCreateParams) =>
- call<JobPosting>('openhuman.tinyplace_jobs_create', {
- title: params.title,
- description: params.description ?? null,
- category: params.category ?? null,
- skills: params.skills ?? null,
- budgetAmount: params.budgetAmount,
- budgetAsset: params.budgetAsset,
- budgetChain: params.budgetChain ?? null,
- proposalDeadline: params.proposalDeadline ?? null,
- }),
- cancel: (jobId: string) => call<JobPosting>('openhuman.tinyplace_jobs_cancel', { jobId }),
- apply: (jobId: string, params?: ProposalCreateParams) =>
- call<Proposal>('openhuman.tinyplace_jobs_apply', {
- jobId,
- coverLetter: params?.coverLetter ?? null,
- bidAmount: params?.bidAmount ?? null,
- estimatedDelivery: params?.estimatedDelivery ?? null,
- pastWork: params?.pastWork ?? null,
- }),
- listProposals: (jobId: string, params?: ProposalQueryParams) =>
- call<ProposalListResponse>('openhuman.tinyplace_jobs_list_proposals', {
- jobId,
- status: params?.status ?? null,
- limit: params?.limit ?? null,
- offset: params?.offset ?? null,
- }),
- getProposal: (jobId: string, proposalId: string) =>
- call<Proposal>('openhuman.tinyplace_jobs_get_proposal', { jobId, proposalId }),
- shortlistProposal: (jobId: string, proposalId: string) =>
- call<Proposal>('openhuman.tinyplace_jobs_shortlist_proposal', { jobId, proposalId }),
- withdrawProposal: (jobId: string, proposalId: string) =>
- call<Proposal>('openhuman.tinyplace_jobs_withdraw_proposal', { jobId, proposalId }),
- select: (jobId: string, proposalId: string, network?: string) =>
- call<SelectCandidateResult>('openhuman.tinyplace_jobs_select', {
- jobId,
- proposalId,
- network: network ?? null,
- }),
- openDispute: (jobId: string, reason: string) =>
- call<JobPosting>('openhuman.tinyplace_jobs_open_dispute', { jobId, reason }),
- adjudicateDispute: (jobId: string) =>
- call<JobPosting>('openhuman.tinyplace_jobs_adjudicate_dispute', { jobId }),
- },
- };
-}
diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts
index 0759cc7960..0d6a788229 100644
--- a/app/src/lib/i18n/ar.ts
+++ b/app/src/lib/i18n/ar.ts
@@ -302,122 +302,11 @@ const messages: TranslationMap = {
'nav.flows': 'سير العمل',
'nav.workflowRuns': 'تشغيلات سير العمل',
'nav.workflowDiscoveries': 'اكتشاف سير العمل',
- 'nav.orchestration': 'التنسيق',
- 'orchestration.cloudUnreachable':
- 'تعذّر الوصول إلى الدماغ السحابي: يتم عرض النسخة المخزّنة محليًا.',
- 'orchPage.subtitle': 'نسّق وكيلك الرئيسي',
- 'orchPage.group.agent': 'الوكيل',
- 'orchPage.group.network': 'الشبكة',
- 'orchPage.group.insights': 'رؤى',
- 'orchPage.overview.nav': 'رسم الوكلاء',
- 'orchPage.overview.desc': 'خريطة حية لوكيلك والوكلاء الفرعيين الذين ينسّقهم.',
- 'orchPage.network.desc': 'الوكلاء النظراء المتصلون بك، والاكتشاف، والاستخدام.',
+
'wallet.tabs.balance': 'رصيد المحفظة',
'wallet.tabs.recovery': 'الاسترداد',
'wallet.ariaLabel': 'طرق عرض المحفظة',
- 'orchPage.medulla.nav': 'نظرة عامة',
- 'orchPage.medulla.badge': 'قريبًا',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'نموذج التنسيق من OpenHuman',
- 'orchPage.medulla.body':
- 'Medulla هو نموذج اللغة الكبير الذي طوّرته OpenHuman خصيصًا، مصمَّم لتنسيق آلاف الوكلاء في آنٍ واحد، بنافذة سياق تتسع لـ 10 ملايين توكن وتنسيق منخفض التكلفة بشكل جذري.',
- 'orchPage.medulla.featAgents': 'آلاف الوكلاء',
- 'orchPage.medulla.featContext': 'سياق بسعة 10M توكن',
- 'orchPage.medulla.featCost': 'تنسيق منخفض التكلفة',
- 'orchPage.medulla.subscriberTitle': 'مشتركو OpenHuman',
- 'orchPage.medulla.subscriberNote': 'عند إطلاق Medulla، سيكون حصريًا لمشتركي OpenHuman.',
- 'orchPage.medulla.subscriberCta': 'احصل على اشتراك',
- 'orchPage.medulla.discordTitle': 'انضم إلى Discord',
- 'orchPage.medulla.earlyAccess':
- 'هل تريد الوصول المبكر؟ انضم إلى Discord الخاص بنا واحصل على دعوة الوصول المبكر.',
- 'orchPage.medulla.cta': 'انضم إلى Discord الخاص بنا',
- 'orchPage.demo.banner': 'هذا مثال على الشكل الذي سيبدو عليه التنسيق على نطاق واسع.',
- 'orchPage.demo.device': 'الجهاز',
- 'orchPage.demo.taskRoute': 'توجيه الطلب الوارد',
- 'orchPage.demo.taskSummarize': 'تلخيص المحادثة',
- 'orchPage.demo.taskEnrich': 'إثراء سجل جهة الاتصال',
- 'orchPage.demo.taskSchedule': 'جدولة المتابعة',
- 'orchPage.demo.taskDraft': 'صياغة رد',
- 'orchPage.demo.taskSync': 'مزامنة مصدر البيانات',
- 'orchPage.demo.networkTitle': 'الوكلاء النظراء',
- 'orchPage.demo.networkSummary': '{peers} متصل · {sessions} وكيل فرعي نشط',
- 'orchPage.demo.peer.connected': 'متصل',
- 'orchPage.demo.peer.connecting': 'جارٍ الاتصال',
- 'orchPage.demo.peer.idle': 'خامل',
- 'orchPage.demo.peerSessions': '{count} وكيل فرعي',
- 'orchPage.demo.chat.user1': 'نسّق حملة التواصل عبر جميع قنواتي.',
- 'orchPage.demo.chat.assistant1':
- 'جارٍ التنفيذ: أُشغّل 120 وكيلًا عبر جهازين لتنفيذ التواصل والإثراء والمتابعات بالتوازي.',
- 'orchPage.demo.chat.activity1': 'الجهاز 1 · 100 وكيل يوجّهون 1,284 محادثة',
- 'orchPage.demo.chat.activity2': 'الجهاز 2 · 20 وكيلًا يُثرون 512 جهة اتصال',
- 'orchPage.demo.chat.activity3': 'صياغة 640 ردًا مخصصًا',
- 'orchPage.demo.chat.assistant2': 'اكتمل. عالج 120 وكيلًا 1,796 محادثة في 38 ثانية.',
- 'orchPage.demo.chat.composerDisabled': 'الدردشة متاحة مع وصول Medulla',
- 'orchPage.tasks.nav': 'المهام',
- 'orchPage.tasks.subtitle': 'لوحة مهام المنسق العامة',
- 'orchPage.tasks.colPending': 'قيد الانتظار',
- 'orchPage.tasks.colActive': 'نشط',
- 'orchPage.tasks.colBlocked': 'محظور',
- 'orchPage.tasks.colCompleted': 'مكتمل',
- 'orchPage.overview.core': 'نواة الوكيل',
- 'orchPage.overview.empty': 'لا توجد وكلاء فرعيون لعرضهم بعد',
- 'orchPage.agent.nav': 'محادثة',
- 'orchPage.agent.mainTab': 'الوكيل الرئيسي',
- 'orchPage.agent.consciousTab': 'الوعي',
- 'orchPage.agent.subconsciousTab': 'اللاوعي',
- 'orchPage.agent.modeLabel': 'عقل الوكيل',
- 'orchPage.agent.description': 'تحدّث مع الوكيل الرئيسي وراقب لاوعيه',
- 'orchPage.agent.viewSession': 'عرض الجلسة',
- 'orchPage.sessions.railTitle': 'الوكلاء النشطون',
- 'orchPage.sessions.empty': 'لا يوجد وكلاء نشطون بعد',
- 'orchPage.sessions.statusConnected': 'متصل',
- 'orchPage.sessions.statusDisconnected': 'غير متصل',
- 'orchPage.sessions.statusWaiting': 'بانتظار الإدخال',
- 'orchPage.session.runtime': 'وقت التشغيل',
- 'orchPage.session.directory': 'الدليل',
- 'orchPage.session.runningOn': 'يعمل على',
- 'orchPage.connections.nav': 'الاتصالات',
- 'orchPage.connections.title': 'الوكلاء المرتبطون',
- 'orchPage.connections.description': 'الأقران الذين ينسّق معهم وكيلك: وسّع أحدهم لعرض جلساتك معه',
- 'orchPage.connections.empty': 'لا توجد اتصالات بعد.',
- 'orchPage.connections.emptyCta': 'إضافة اتصال',
- 'orchPage.connections.statContacts': 'الاتصالات',
- 'orchPage.connections.statPending': 'قيد الانتظار',
- 'orchPage.connections.statSessions': 'الجلسات',
- 'orchPage.connections.sessionCount': '{n} جلسة',
- 'orchPage.connections.noSessions': 'لا توجد جلسات',
- 'orchPage.connections.messageCount': '{n} رسالة',
- 'orchPage.connections.back': 'الاتصالات',
- 'orchPage.connections.replyPlaceholder': 'رد…',
- 'orchPage.connections.initTitle': 'تهيئة وكيل أو نسخة',
- 'orchPage.connections.initDesc':
- 'أنشئ وكيلًا فرعيًا جديدًا يعمل إلى جانبك. افتح محادثة الوكيل وصف الدور والهدف والأدوات التي يجب أن يستخدمها: يقوم OpenHuman بتجهيز نسخة مخصصة يمكنك توجيهها من هنا.',
- 'orchPage.connections.initCta': 'ابدأ في المحادثة',
- 'orchPage.connections.status.needsYou': 'يحتاج إليك',
- 'orchPage.connections.status.running': 'قيد التشغيل',
- 'orchPage.connections.status.idle': 'خامل',
- 'orchPage.connections.status.done': 'تم',
- 'orchPage.connections.status.error': 'خطأ',
- 'orchPage.connections.pendingHint': 'بانتظار القبول',
- 'orchPage.discover.nav': 'اكتشاف',
- 'orchPage.discover.linkAction': 'إضافة',
- 'orchPage.discover.identityTitle': 'قابليتك للاكتشاف',
- 'orchPage.discover.notDiscoverableGuide':
- 'سجّل @handle حتى يتمكن الوكلاء الآخرون من العثور عليك ومراسلتك.',
- 'orchPage.discover.linkTitle': 'ربط وكيل جديد',
- 'orchPage.discover.linkDescription': 'الصق معرّف وكيل لإرسال طلب اتصال.',
- 'orchPage.discover.noRequests': 'لا توجد طلبات واردة.',
- 'orchPage.usage.nav': 'الاستخدام',
- 'orchPage.usage.connections': 'الاتصالات',
- 'orchPage.usage.balance': 'رصيد الائتمان',
- 'orchPage.usage.balanceHint': 'ترويجي + شحن',
- 'orchPage.usage.cycleSpend': 'إنفاق الدورة',
- 'orchPage.usage.ofBudget': 'من',
- 'orchPage.usage.inferenceCalls': 'استدعاءات النموذج',
- 'orchPage.usage.integrationCalls': 'استدعاءات التكامل',
- 'orchPage.usage.tokensSaved': 'الرموز الموفّرة',
- 'orchPage.usage.saved': 'موفّر',
- 'orchPage.usage.footnote': 'يعكس الاستخدام دورة الفوترة الحالية.',
+
'nav.wallet': 'المحفظة',
'nav.avatarMenu.account': 'الحساب',
'nav.avatarMenu.billing': 'الفواتير',
@@ -443,85 +332,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': 'حدث خطأ ما. يرجى المحاولة مرة أخرى.',
'brain.tabs.sources': 'المصادر',
'brain.tabs.sync': 'المزامنة',
- 'brain.tabs.orchestration': 'التنسيق',
- 'tinyplaceOrchestration.title': 'مرحّل TinyPlace',
- 'tinyplaceOrchestration.subtitle': 'قنوات الوكلاء المثبتة ودردشات جلسات التطبيق',
- 'tinyplaceOrchestration.refresh': 'تحديث',
- 'tinyplaceOrchestration.newInstance': 'نسخة جديدة',
- 'tinyplaceOrchestration.newInstanceSoon': 'قريبًا',
- 'tinyplaceOrchestration.pinned': 'مثبتة',
- 'tinyplaceOrchestration.sessions': 'الجلسات',
- 'tinyplaceOrchestration.contacts': 'جهات الاتصال',
- 'tinyplaceOrchestration.noContacts': 'لا توجد جهات اتصال بعد.',
- 'tinyplaceOrchestration.newSession': 'جلسة جديدة',
- 'tinyplaceOrchestration.otherSessions': 'جلسات أخرى',
- 'tinyplaceOrchestration.loading': 'جارٍ تحميل دردشات TinyPlace…',
- 'tinyplaceOrchestration.paymentRequired': 'يتطلب الوصول إلى TinyPlace دفعًا.',
- 'tinyplaceOrchestration.failedToLoad': 'تعذّر تحميل دردشات TinyPlace',
- 'tinyplaceOrchestration.noSessions': 'لا توجد جلسات تطبيق TinyPlace بعد.',
- 'tinyplaceOrchestration.noMessages': 'لا توجد رسائل في هذه الدردشة بعد.',
- 'tinyplaceOrchestration.active': 'نشطة',
- 'tinyplaceOrchestration.inactive': 'غير نشطة',
- 'tinyplaceOrchestration.encryptedBody': 'رسالة TinyPlace مشفرة',
- 'tinyplaceOrchestration.unknownSender': 'مرسل غير معروف',
- 'tinyplaceOrchestration.master.title': 'وكيل / إنسان',
- 'tinyplaceOrchestration.master.subtitle': 'الدردشة الرئيسية',
- 'tinyplaceOrchestration.master.preview': 'تنسيق مباشر بينك وبين OpenHuman.',
- 'tinyplaceOrchestration.subconscious.title': 'اللاوعي',
- 'tinyplaceOrchestration.subconscious.subtitle': 'دردشات الوكلاء الداخلية',
- 'tinyplaceOrchestration.subconscious.preview': 'تنسيق الوكلاء في الخلفية وحلقات الذاكرة.',
- 'tinyplaceOrchestration.session.subtitle': 'جلسة تطبيق TinyPlace',
- 'tinyplaceOrchestration.pairing.linkLabel': 'ربط جلسة',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': 'ألصق معرف وكيل الجلسة',
- 'tinyplaceOrchestration.pairing.linkAction': 'ربط',
- 'tinyplaceOrchestration.pairing.requests': 'طلبات الاتصال',
- 'tinyplaceOrchestration.pairing.accept': 'قبول',
- 'tinyplaceOrchestration.pairing.decline': 'رفض',
- 'tinyplaceOrchestration.pairing.block': 'حظر',
- 'tinyplaceOrchestration.pairing.linked': 'مرتبط',
- 'tinyplaceOrchestration.pairing.pending': 'معلق',
- 'tinyplaceOrchestration.pairing.unlinked': 'غير مرتبط',
- 'tinyplaceOrchestration.pairing.incoming': 'واردة',
- 'tinyplaceOrchestration.pairing.outgoing': 'صادرة',
- 'tinyplaceOrchestration.master.you': 'أنت',
- 'tinyplaceOrchestration.composer.placeholder': 'راسل OpenHuman…',
- 'tinyplaceOrchestration.composer.send': 'إرسال',
- 'tinyplaceOrchestration.composer.sendFailed': 'فشل إرسال الرسالة',
- 'tinyplaceOrchestration.steering.label': 'التوجيه',
- 'tinyplaceOrchestration.relay.staging': 'بيئة التجهيز',
- 'tinyplaceOrchestration.relay.prod': 'الإنتاج',
- 'tinyplaceOrchestration.identity.loading': 'جارٍ تحميل الهوية…',
- 'tinyplaceOrchestration.identity.noHandle': 'لا يوجد @handle بعد',
- 'tinyplaceOrchestration.identity.copy': 'نسخ',
- 'tinyplaceOrchestration.identity.copied': 'تم النسخ',
- 'tinyplaceOrchestration.identity.discoverable': 'قابل للاكتشاف',
- 'tinyplaceOrchestration.identity.undiscoverable': 'غير قابل للاكتشاف',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'انشر بطاقة الدليل ومفتاح التشفير حتى يتمكن الآخرون من مراسلتك.',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'اجعله قابلاً للاكتشاف',
- 'tinyplaceOrchestration.identity.republish': 'إعادة نشر المفاتيح',
- 'tinyplaceOrchestration.identity.publishing': 'جارٍ النشر…',
- 'tinyplaceOrchestration.identity.publishFailed': 'فشل النشر: أعد المحاولة',
- 'tinyplaceOrchestration.identity.card': 'بطاقة الدليل',
- 'tinyplaceOrchestration.identity.key': 'مفتاح التشفير',
- 'tinyplaceOrchestration.identity.published': 'منشور',
- 'tinyplaceOrchestration.identity.notPublished': 'غير منشور',
- 'tinyplaceOrchestration.roster.instances': 'مثيلات',
- 'tinyplaceOrchestration.roster.empty': 'لا توجد مثيلات وكيل بعد',
- 'tinyplaceOrchestration.roster.other': 'أخرى',
- 'tinyplaceOrchestration.status.running': 'قيد التشغيل',
- 'tinyplaceOrchestration.status.idle': 'خامل',
- 'tinyplaceOrchestration.status.waitingApproval': 'في انتظار الموافقة',
- 'tinyplaceOrchestration.status.errored': 'خطأ',
- 'tinyplaceOrchestration.status.stopped': 'متوقف',
- 'tinyplaceOrchestration.attention.title': 'يحتاج إليك',
- 'tinyplaceOrchestration.attention.empty': 'أنجزت كل شيء',
- 'tinyplaceOrchestration.attention.unread': 'رسائل غير مقروءة',
- 'tinyplaceOrchestration.attention.review': 'مراجعة',
- 'tinyplaceOrchestration.attention.open': 'فتح',
- 'tinyplaceOrchestration.attention.kind.approval': 'موافقة',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'بحاجة إلى مُدخل',
- 'tinyplaceOrchestration.attention.kind.unread': 'غير مقروء',
'brain.empty': 'دماغك فارغ في الوقت الحالي: قم بربط مصدر لبدء بناء الذاكرة.',
'brain.error': 'تعذّر تحميل دماغك. يرجى المحاولة مرة أخرى.',
'common.cancel': 'إلغاء',
@@ -2831,10 +2641,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'تشغيل النماذج على جهازك باستخدام Ollama. خصوصية كاملة، يتطلب إعدادًا.',
'backend.ramRecommended': '16 جيجابايت+ RAM موصى به',
- 'tinyplaceOrchestration.subconsciousBadge': 'اللاوعي · التوجيه',
- 'tinyplaceOrchestration.steeringHeader.current': 'توجيه نشط',
- 'tinyplaceOrchestration.steeringHeader.none': 'لا يوجد توجيه نشط',
- 'tinyplaceOrchestration.steeringHeader.expires': 'ينتهي بعد {n} دورات',
'actionable.complete': 'إتمام',
'actionable.dismiss': 'تجاهل',
'actionable.snooze': 'تأجيل',
@@ -5091,10 +4897,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'الموافقة التلقائية على جميع الإجراءات',
'settings.agentAccess.autoApproveAll.desc':
'عند التفعيل، سينفذ الوكيل جميع الإجراءات المؤهلة دون طلب موافقتك أولاً. يشمل ذلك كتابة الملفات وتنفيذ أوامر الطرفية وطلبات الشبكة وأي تأثيرات جانبية أخرى. تظل الحواجز الأمنية الصارمة، مثل أدلة بيانات الاعتماد والأدلة النظامية، سارية المفعول، ولا تتم الموافقة التلقائية أبداً على الإجراءات ذات المصدر غير الموثوق أو غير المعروف.',
- 'settings.agentAccess.tinyplaceAutopilot.title': 'وكيل tiny.place المستقل',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'دع OpenHuman يتصرف على tiny.place بمفرده. وفق جدول زمني، يبحث عن عمل مجدٍ (المكافآت المفتوحة أولًا)، وينجز ما يناسب مهاراته ويتصرف من هويتك. يعمل دون إشراف ويمكنه الإنفاق، لذا أبقِه على devnet أثناء الاختبار. معطّل افتراضيًا.',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'التشغيل تلقائيًا',
'settings.agentAccess.timeout.label': 'مهلة الإجراء',
'settings.agentAccess.timeout.desc':
'المدة التي يُسمح خلالها بتشغيل أداة أو إجراء واحد قبل إلغائه. زِد هذه القيمة إذا كان نموذج محلي كبير يُقاطَع قبل أن ينهي رده.',
@@ -6455,9 +6257,7 @@ const messages: TranslationMap = {
'notch.speaking': 'أتحدث…',
'notch.transcribing': 'أفسّر…',
'notch.executing': 'أنفّذ…',
- 'memory.tab.orchestration': 'التنسيق',
- 'memory.tab.orchestrationDescription':
- 'شغّل سير عمل متعدد الوكلاء: وزّع سؤالاً على وكلاء متوازين، وتحقّق من نتائجهم بشكل متبادل، وراقب اكتمال كل مرحلة لتتجمّع في إجابة واحدة مُركَّبة.',
+
'orchestration.subtitle':
'ابدأ سير عمل متعدد الوكلاء، وراقب تقدّم مراحله، واقرأ النتيجة المُركَّبة.',
'orchestration.loading': 'جارٍ تحميل سير العمل…',
@@ -6599,10 +6399,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'انتهت ميزانية التضمينات لديك، لذلك لم يعد المحتوى الجديد يُضاف إلى الذاكرة. أعدّ تضمينات محلية أو أضف مفتاح API الخاص بك للمتابعة.',
'memoryBudget.cta': 'إعداد التضمينات',
- 'tinyplaceSunset.title': 'ينتقل Tiny Place خارج التطبيق',
- 'tinyplaceSunset.message':
- 'لمواصلة استخدام tiny.place، زر tiny.place. ستتم إزالته من التطبيق بعد 31 أغسطس 2026.',
- 'tinyplaceSunset.cta': 'فتح tiny.place',
'userErrors.scope.memory': 'الذاكرة',
// Code block chrome
diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts
index 8fc0b24640..bff107b66b 100644
--- a/app/src/lib/i18n/bn.ts
+++ b/app/src/lib/i18n/bn.ts
@@ -312,126 +312,11 @@ const messages: TranslationMap = {
'nav.flows': 'ওয়ার্কফ্লো',
'nav.workflowRuns': 'ওয়ার্কফ্লো রান',
'nav.workflowDiscoveries': 'ওয়ার্কফ্লো আবিষ্কার করুন',
- 'nav.orchestration': 'অর্কেস্ট্রেশন',
- 'orchestration.cloudUnreachable':
- 'ক্লাউড ব্রেন-এ পৌঁছানো যাচ্ছে না: ক্যাশে করা ভিউ দেখানো হচ্ছে।',
- 'orchPage.subtitle': 'আপনার প্রধান এজেন্ট সমন্বয় করুন',
- 'orchPage.group.agent': 'এজেন্ট',
- 'orchPage.group.network': 'নেটওয়ার্ক',
- 'orchPage.group.insights': 'অন্তর্দৃষ্টি',
- 'orchPage.overview.nav': 'এজেন্ট গ্রাফ',
- 'orchPage.overview.desc':
- 'আপনার এজেন্ট এবং এটি যে সাব-এজেন্টগুলিকে সমন্বয় করে তার একটি লাইভ মানচিত্র।',
- 'orchPage.network.desc': 'আপনি যে পিয়ার এজেন্টগুলির সাথে সংযুক্ত, আবিষ্কার এবং ব্যবহার।',
+
'wallet.tabs.balance': 'ওয়ালেট ব্যালেন্স',
'wallet.tabs.recovery': 'পুনরুদ্ধার',
'wallet.ariaLabel': 'ওয়ালেট ভিউ',
- 'orchPage.medulla.nav': 'ওভারভিউ',
- 'orchPage.medulla.badge': 'শীঘ্রই আসছে',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'OpenHuman-এর অর্কেস্ট্রেশন মডেল',
- 'orchPage.medulla.body':
- 'Medulla হলো OpenHuman-এর নিজস্বভাবে তৈরি LLM, যা একসঙ্গে হাজার হাজার এজেন্ট অর্কেস্ট্রেট করার জন্য প্রকৌশলিত, 10 মিলিয়ন-টোকেন কনটেক্সট উইন্ডো এবং অত্যন্ত কম খরচের অর্কেস্ট্রেশন সহ।',
- 'orchPage.medulla.featAgents': 'হাজার হাজার এজেন্ট',
- 'orchPage.medulla.featContext': '10M-টোকেন কনটেক্সট',
- 'orchPage.medulla.featCost': 'কম খরচের অর্কেস্ট্রেশন',
- 'orchPage.medulla.subscriberTitle': 'OpenHuman সাবস্ক্রাইবার',
- 'orchPage.medulla.subscriberNote':
- 'Medulla লাইভ হলে এটি শুধুমাত্র OpenHuman সাবস্ক্রাইবারদের জন্য এক্সক্লুসিভ হবে।',
- 'orchPage.medulla.subscriberCta': 'সাবস্ক্রিপশন নিন',
- 'orchPage.medulla.discordTitle': 'Discord-এ যোগ দিন',
- 'orchPage.medulla.earlyAccess':
- 'আগেভাগে পেতে চান? আমাদের Discord-এ যোগ দিন এবং আর্লি-অ্যাক্সেস আমন্ত্রণ নিন।',
- 'orchPage.medulla.cta': 'আমাদের Discord-এ যোগ দিন',
- 'orchPage.demo.banner': 'বড় পরিসরে অর্কেস্ট্রেশন কেমন দেখাবে তার একটি উদাহরণ এটি।',
- 'orchPage.demo.device': 'ডিভাইস',
- 'orchPage.demo.taskRoute': 'ইনকামিং অনুরোধ রুট করুন',
- 'orchPage.demo.taskSummarize': 'কথোপকথন সংক্ষিপ্ত করুন',
- 'orchPage.demo.taskEnrich': 'যোগাযোগের রেকর্ড সমৃদ্ধ করুন',
- 'orchPage.demo.taskSchedule': 'ফলো-আপ শিডিউল করুন',
- 'orchPage.demo.taskDraft': 'উত্তর খসড়া করুন',
- 'orchPage.demo.taskSync': 'ডেটা উৎস সিঙ্ক করুন',
- 'orchPage.demo.networkTitle': 'পিয়ার এজেন্ট',
- 'orchPage.demo.networkSummary': '{peers} সংযুক্ত · {sessions} সক্রিয় সাব-এজেন্ট',
- 'orchPage.demo.peer.connected': 'সংযুক্ত',
- 'orchPage.demo.peer.connecting': 'সংযোগ হচ্ছে',
- 'orchPage.demo.peer.idle': 'নিষ্ক্রিয়',
- 'orchPage.demo.peerSessions': '{count} সাব-এজেন্ট',
- 'orchPage.demo.chat.user1': 'আমার সব চ্যানেল জুড়ে আউটরিচ ক্যাম্পেইন সমন্বয় করুন।',
- 'orchPage.demo.chat.assistant1':
- 'কাজ চলছে: আউটরিচ, সমৃদ্ধকরণ এবং ফলো-আপ সমান্তরালভাবে চালাতে 2টি ডিভাইসে 120টি এজেন্ট চালু করা হচ্ছে।',
- 'orchPage.demo.chat.activity1': 'ডিভাইস 1 · 100টি এজেন্ট 1,284টি কথোপকথন রুট করছে',
- 'orchPage.demo.chat.activity2': 'ডিভাইস 2 · 20টি এজেন্ট 512টি যোগাযোগ সমৃদ্ধ করছে',
- 'orchPage.demo.chat.activity3': '640টি ব্যক্তিগতকৃত উত্তর খসড়া করা হচ্ছে',
- 'orchPage.demo.chat.assistant2':
- 'সম্পন্ন। 120টি এজেন্ট 38 সেকেন্ডে 1,796টি কথোপকথন প্রক্রিয়া করেছে।',
- 'orchPage.demo.chat.composerDisabled': 'Medulla অ্যাক্সেস থাকলে চ্যাট উপলব্ধ',
- 'orchPage.tasks.nav': 'টাস্ক',
- 'orchPage.tasks.subtitle': 'অর্কেস্ট্রেটরের গ্লোবাল টাস্ক বোর্ড',
- 'orchPage.tasks.colPending': 'মুলতুবি',
- 'orchPage.tasks.colActive': 'সক্রিয়',
- 'orchPage.tasks.colBlocked': 'অবরুদ্ধ',
- 'orchPage.tasks.colCompleted': 'সম্পন্ন',
- 'orchPage.overview.core': 'এজেন্ট কোর',
- 'orchPage.overview.empty': 'এখনও ভিজ্যুয়ালাইজ করার মতো কোনো সাব-এজেন্ট নেই',
- 'orchPage.agent.nav': 'চ্যাট',
- 'orchPage.agent.mainTab': 'প্রধান এজেন্ট',
- 'orchPage.agent.consciousTab': 'সচেতন',
- 'orchPage.agent.subconsciousTab': 'অবচেতন',
- 'orchPage.agent.modeLabel': 'এজেন্টের মন',
- 'orchPage.agent.description': 'প্রধান এজেন্টের সাথে চ্যাট করুন এবং তার অবচেতন দেখুন',
- 'orchPage.agent.viewSession': 'সেশন দেখুন',
- 'orchPage.sessions.railTitle': 'সক্রিয় এজেন্ট',
- 'orchPage.sessions.empty': 'এখনও কোনো সক্রিয় এজেন্ট নেই',
- 'orchPage.sessions.statusConnected': 'সংযুক্ত',
- 'orchPage.sessions.statusDisconnected': 'সংযোগ বিচ্ছিন্ন',
- 'orchPage.sessions.statusWaiting': 'ইনপুটের অপেক্ষায়',
- 'orchPage.session.runtime': 'রানটাইম',
- 'orchPage.session.directory': 'ডিরেক্টরি',
- 'orchPage.session.runningOn': 'চলছে',
- 'orchPage.connections.nav': 'সংযোগ',
- 'orchPage.connections.title': 'সংযুক্ত এজেন্ট',
- 'orchPage.connections.description':
- 'যাদের সঙ্গে আপনার এজেন্ট সমন্বয় করে: একটি প্রসারিত করে তাদের সঙ্গে আপনার সেশনগুলো দেখুন',
- 'orchPage.connections.empty': 'এখনও কোনো সংযোগ নেই।',
- 'orchPage.connections.emptyCta': 'একটি সংযোগ যোগ করুন',
- 'orchPage.connections.statContacts': 'সংযোগ',
- 'orchPage.connections.statPending': 'অপেক্ষমাণ',
- 'orchPage.connections.statSessions': 'সেশন',
- 'orchPage.connections.sessionCount': '{n}টি সেশন',
- 'orchPage.connections.noSessions': 'কোনো সেশন নেই',
- 'orchPage.connections.messageCount': '{n}টি বার্তা',
- 'orchPage.connections.back': 'সংযোগ',
- 'orchPage.connections.replyPlaceholder': 'উত্তর…',
- 'orchPage.connections.initTitle': 'একটি এজেন্ট বা ইনস্ট্যান্স চালু করুন',
- 'orchPage.connections.initDesc':
- 'আপনার সাথে কাজ করার জন্য একটি নতুন সাব-এজেন্ট চালু করুন। এজেন্ট চ্যাট খুলুন এবং এর ভূমিকা, লক্ষ্য ও ব্যবহার্য টুল বর্ণনা করুন: OpenHuman একটি ডেডিকেটেড ইনস্ট্যান্স তৈরি করে যা আপনি এখান থেকে পরিচালনা করতে পারেন।',
- 'orchPage.connections.initCta': 'চ্যাটে শুরু করুন',
- 'orchPage.connections.status.needsYou': 'আপনাকে প্রয়োজন',
- 'orchPage.connections.status.running': 'চলছে',
- 'orchPage.connections.status.idle': 'নিষ্ক্রিয়',
- 'orchPage.connections.status.done': 'সম্পন্ন',
- 'orchPage.connections.status.error': 'ত্রুটি',
- 'orchPage.connections.pendingHint': 'গ্রহণের অপেক্ষায়',
- 'orchPage.discover.nav': 'আবিষ্কার',
- 'orchPage.discover.linkAction': 'যোগ করুন',
- 'orchPage.discover.identityTitle': 'আপনার আবিষ্কারযোগ্যতা',
- 'orchPage.discover.notDiscoverableGuide':
- 'একটি @handle নিবন্ধন করুন যাতে অন্য এজেন্টরা আপনাকে খুঁজে বার্তা পাঠাতে পারে।',
- 'orchPage.discover.linkTitle': 'নতুন এজেন্ট লিঙ্ক করুন',
- 'orchPage.discover.linkDescription': 'সংযোগের অনুরোধ পাঠাতে একটি এজেন্ট আইডি পেস্ট করুন।',
- 'orchPage.discover.noRequests': 'কোনো আগত অনুরোধ নেই।',
- 'orchPage.usage.nav': 'ব্যবহার',
- 'orchPage.usage.connections': 'সংযোগ',
- 'orchPage.usage.balance': 'ক্রেডিট ব্যালেন্স',
- 'orchPage.usage.balanceHint': 'প্রচারমূলক + টপ-আপ',
- 'orchPage.usage.cycleSpend': 'চক্রের ব্যয়',
- 'orchPage.usage.ofBudget': 'এর',
- 'orchPage.usage.inferenceCalls': 'মডেল কল',
- 'orchPage.usage.integrationCalls': 'ইন্টিগ্রেশন কল',
- 'orchPage.usage.tokensSaved': 'সংরক্ষিত টোকেন',
- 'orchPage.usage.saved': 'সংরক্ষিত',
- 'orchPage.usage.footnote': 'ব্যবহার আপনার বর্তমান বিলিং চক্র প্রতিফলিত করে।',
+
'nav.wallet': 'ওয়ালেট',
'nav.avatarMenu.account': 'অ্যাকাউন্ট',
'nav.avatarMenu.billing': 'বিলিং',
@@ -459,85 +344,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': 'কিছু ভুল হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।',
'brain.tabs.sources': 'উৎস',
'brain.tabs.sync': 'সিঙ্ক',
- 'brain.tabs.orchestration': 'অর্কেস্ট্রেশন',
- 'tinyplaceOrchestration.title': 'TinyPlace রিলে',
- 'tinyplaceOrchestration.subtitle': 'পিন করা এজেন্ট চ্যানেল এবং অ্যাপ সেশন চ্যাট',
- 'tinyplaceOrchestration.refresh': 'রিফ্রেশ',
- 'tinyplaceOrchestration.newInstance': 'নতুন ইনস্ট্যান্স',
- 'tinyplaceOrchestration.newInstanceSoon': 'শীঘ্রই আসছে',
- 'tinyplaceOrchestration.pinned': 'পিন করা',
- 'tinyplaceOrchestration.sessions': 'সেশন',
- 'tinyplaceOrchestration.contacts': 'পরিচিতি',
- 'tinyplaceOrchestration.noContacts': 'এখনও কোনো পরিচিতি নেই।',
- 'tinyplaceOrchestration.newSession': 'নতুন সেশন',
- 'tinyplaceOrchestration.otherSessions': 'অন্যান্য সেশন',
- 'tinyplaceOrchestration.loading': 'TinyPlace চ্যাট লোড হচ্ছে…',
- 'tinyplaceOrchestration.paymentRequired': 'TinyPlace অ্যাক্সেসের জন্য পেমেন্ট দরকার।',
- 'tinyplaceOrchestration.failedToLoad': 'TinyPlace চ্যাট লোড করা যায়নি',
- 'tinyplaceOrchestration.noSessions': 'এখনও কোনো TinyPlace অ্যাপ সেশন নেই।',
- 'tinyplaceOrchestration.noMessages': 'এই চ্যাটে এখনও কোনো বার্তা নেই।',
- 'tinyplaceOrchestration.active': 'সক্রিয়',
- 'tinyplaceOrchestration.inactive': 'নিষ্ক্রিয়',
- 'tinyplaceOrchestration.encryptedBody': 'এনক্রিপ্টেড TinyPlace বার্তা',
- 'tinyplaceOrchestration.unknownSender': 'অজানা প্রেরক',
- 'tinyplaceOrchestration.master.title': 'এজেন্ট / মানব',
- 'tinyplaceOrchestration.master.subtitle': 'মাস্টার চ্যাট',
- 'tinyplaceOrchestration.master.preview': 'আপনি এবং OpenHuman-এর মধ্যে সরাসরি সমন্বয়।',
- 'tinyplaceOrchestration.subconscious.title': 'অবচেতন',
- 'tinyplaceOrchestration.subconscious.subtitle': 'অভ্যন্তরীণ এজেন্ট চ্যাট',
- 'tinyplaceOrchestration.subconscious.preview': 'পটভূমির এজেন্ট সমন্বয় এবং মেমরি লুপ।',
- 'tinyplaceOrchestration.session.subtitle': 'TinyPlace অ্যাপ সেশন',
- 'tinyplaceOrchestration.pairing.linkLabel': 'সেশন লিঙ্ক করুন',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': 'সেশন এজেন্ট আইডি পেস্ট করুন',
- 'tinyplaceOrchestration.pairing.linkAction': 'লিঙ্ক',
- 'tinyplaceOrchestration.pairing.requests': 'যোগাযোগ অনুরোধ',
- 'tinyplaceOrchestration.pairing.accept': 'গ্রহণ',
- 'tinyplaceOrchestration.pairing.decline': 'প্রত্যাখ্যান',
- 'tinyplaceOrchestration.pairing.block': 'ব্লক',
- 'tinyplaceOrchestration.pairing.linked': 'লিঙ্কড',
- 'tinyplaceOrchestration.pairing.pending': 'অপেক্ষমান',
- 'tinyplaceOrchestration.pairing.unlinked': 'লিঙ্ক নেই',
- 'tinyplaceOrchestration.pairing.incoming': 'আসছে',
- 'tinyplaceOrchestration.pairing.outgoing': 'যাচ্ছে',
- 'tinyplaceOrchestration.master.you': 'আপনি',
- 'tinyplaceOrchestration.composer.placeholder': 'OpenHuman-কে বার্তা দিন…',
- 'tinyplaceOrchestration.composer.send': 'পাঠান',
- 'tinyplaceOrchestration.composer.sendFailed': 'বার্তা পাঠাতে ব্যর্থ',
- 'tinyplaceOrchestration.steering.label': 'নির্দেশনা',
- 'tinyplaceOrchestration.relay.staging': 'স্টেজিং',
- 'tinyplaceOrchestration.relay.prod': 'প্রোডাকশন',
- 'tinyplaceOrchestration.identity.loading': 'পরিচয় লোড হচ্ছে…',
- 'tinyplaceOrchestration.identity.noHandle': 'এখনও কোনো @handle নেই',
- 'tinyplaceOrchestration.identity.copy': 'কপি করুন',
- 'tinyplaceOrchestration.identity.copied': 'কপি হয়েছে',
- 'tinyplaceOrchestration.identity.discoverable': 'খুঁজে পাওয়া যায়',
- 'tinyplaceOrchestration.identity.undiscoverable': 'খুঁজে পাওয়া যায় না',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'আপনার ডিরেক্টরি কার্ড ও এনক্রিপশন কী প্রকাশ করুন যাতে অন্য এজেন্টরা আপনাকে বার্তা পাঠাতে পারে।',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'আবিষ্কারযোগ্য করুন',
- 'tinyplaceOrchestration.identity.republish': 'কী পুনঃপ্রকাশ করুন',
- 'tinyplaceOrchestration.identity.publishing': 'প্রকাশ করা হচ্ছে…',
- 'tinyplaceOrchestration.identity.publishFailed': 'প্রকাশ ব্যর্থ হয়েছে: আবার চেষ্টা করুন',
- 'tinyplaceOrchestration.identity.card': 'ডিরেক্টরি কার্ড',
- 'tinyplaceOrchestration.identity.key': 'এনক্রিপশন কী',
- 'tinyplaceOrchestration.identity.published': 'প্রকাশিত',
- 'tinyplaceOrchestration.identity.notPublished': 'অপ্রকাশিত',
- 'tinyplaceOrchestration.roster.instances': 'ইনস্ট্যান্স',
- 'tinyplaceOrchestration.roster.empty': 'এখনও কোনো এজেন্ট ইনস্ট্যান্স নেই',
- 'tinyplaceOrchestration.roster.other': 'অন্যান্য',
- 'tinyplaceOrchestration.status.running': 'চলছে',
- 'tinyplaceOrchestration.status.idle': 'নিষ্ক্রিয়',
- 'tinyplaceOrchestration.status.waitingApproval': 'অনুমোদনের অপেক্ষায়',
- 'tinyplaceOrchestration.status.errored': 'ত্রুটিপূর্ণ',
- 'tinyplaceOrchestration.status.stopped': 'থেমে গেছে',
- 'tinyplaceOrchestration.attention.title': 'আপনার প্রয়োজন',
- 'tinyplaceOrchestration.attention.empty': 'সব কাজ শেষ',
- 'tinyplaceOrchestration.attention.unread': 'অপঠিত বার্তা',
- 'tinyplaceOrchestration.attention.review': 'পর্যালোচনা',
- 'tinyplaceOrchestration.attention.open': 'খুলুন',
- 'tinyplaceOrchestration.attention.kind.approval': 'অনুমোদন',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'ইনপুট প্রয়োজন',
- 'tinyplaceOrchestration.attention.kind.unread': 'অপঠিত',
'brain.empty': 'আপনার ব্রেইন এখন খালি: মেমরি তৈরি শুরু করতে একটি উৎস সংযুক্ত করুন।',
'brain.error': 'আপনার ব্রেইন লোড করা যায়নি। অনুগ্রহ করে আবার চেষ্টা করুন।',
'common.cancel': 'বাতিল',
@@ -2898,10 +2704,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'Ollama ব্যবহার করে নিজের মেশিনে মডেল চালান। সম্পূর্ণ গোপনীয়তা, সেটআপ প্রয়োজন।',
'backend.ramRecommended': '16GB+ RAM প্রস্তাবিত',
- 'tinyplaceOrchestration.subconsciousBadge': 'অবচেতন · স্টিয়ারিং',
- 'tinyplaceOrchestration.steeringHeader.current': 'সক্রিয় নির্দেশ',
- 'tinyplaceOrchestration.steeringHeader.none': 'কোনো সক্রিয় নির্দেশ নেই',
- 'tinyplaceOrchestration.steeringHeader.expires': '{n} চক্র পরে মেয়াদ শেষ',
'actionable.complete': 'সম্পন্ন',
'actionable.dismiss': 'বাদ দিন',
'actionable.snooze': 'স্নুজ',
@@ -5210,10 +5012,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'সব কাজ স্বয়ংক্রিয়ভাবে অনুমোদন করুন',
'settings.agentAccess.autoApproveAll.desc':
'সক্রিয় করা হলে, এজেন্ট আপনার অনুমতি না নিয়েই সব কাজ সম্পাদন করবে। এর মধ্যে রয়েছে ফাইল লেখা, শেল কমান্ড, নেটওয়ার্ক অনুরোধ এবং অন্যান্য যেকোনো পার্শ্বপ্রতিক্রিয়া। কঠোর নিরাপত্তা বাধা (ক্রেডেনশিয়াল ডিরেক্টরি, ওয়ার্কস্পেসের অভ্যন্তরীণ পাথ) তবুও কার্যকর থাকবে।',
- 'settings.agentAccess.tinyplaceAutopilot.title': 'স্বয়ংক্রিয় tiny.place এজেন্ট',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'OpenHuman-কে tiny.place-এ নিজে কাজ করতে দিন। এটি নির্ধারিত সময় অনুযায়ী মূল্যবান কাজ খোঁজে (প্রথমে খোলা বাউন্টি), নিজের দক্ষতার সাথে মানানসই কাজ করে এবং আপনার পরিচয় থেকে কাজ করে। এটি তত্ত্বাবধান ছাড়াই চলে এবং অর্থ ব্যয় করতে পারে, তাই পরীক্ষার সময় এটি devnet-এ রাখুন। ডিফল্টভাবে বন্ধ।',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'স্বয়ংক্রিয়ভাবে চালান',
'settings.agentAccess.timeout.label': 'অ্যাকশন টাইমআউট',
'settings.agentAccess.timeout.desc':
'একটি একক টুল বা অ্যাকশন বাতিল হওয়ার আগে কতক্ষণ চলতে পারে। বড় লোকাল মডেল উত্তর শেষ করার আগেই থেমে গেলে এটি বাড়ান।',
@@ -6606,9 +6404,7 @@ const messages: TranslationMap = {
'notch.speaking': 'বলছি…',
'notch.transcribing': 'ট্রান্সক্রাইব করছি…',
'notch.executing': 'চালাচ্ছি…',
- 'memory.tab.orchestration': 'অর্কেস্ট্রেশন',
- 'memory.tab.orchestrationDescription':
- 'বহু-এজেন্ট ওয়ার্কফ্লো চালান: একটি প্রশ্নকে সমান্তরাল এজেন্টদের মধ্যে ছড়িয়ে দিন, তাদের ফলাফল পরস্পর যাচাই করুন, এবং দেখুন প্রতিটি ধাপ কীভাবে একটি সমন্বিত উত্তরে সম্পূর্ণ হয়।',
+
'orchestration.subtitle':
'একটি বহু-এজেন্ট ওয়ার্কফ্লো শুরু করুন, এর ধাপগুলোর অগ্রগতি দেখুন, এবং সমন্বিত ফলাফল পড়ুন।',
'orchestration.loading': 'ওয়ার্কফ্লো লোড হচ্ছে…',
@@ -6752,10 +6548,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'আপনার এমবেডিং বাজেট শেষ, তাই নতুন কনটেন্ট আর মেমরিতে যুক্ত হচ্ছে না। আবার শুরু করতে লোকাল এমবেডিং সেট আপ করুন বা নিজের API কী যোগ করুন।',
'memoryBudget.cta': 'এমবেডিং সেট আপ করুন',
- 'tinyplaceSunset.title': 'Tiny Place অ্যাপ থেকে সরে যাচ্ছে',
- 'tinyplaceSunset.message':
- 'tiny.place ব্যবহার চালিয়ে যেতে tiny.place-এ যান। ৩১ আগস্ট ২০২৬-এর পর এটি অ্যাপ থেকে সরিয়ে ফেলা হবে।',
- 'tinyplaceSunset.cta': 'tiny.place খুলুন',
'userErrors.scope.memory': 'মেমরি',
// Code block chrome
diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts
index 2b9085849c..4bf6104ec3 100644
--- a/app/src/lib/i18n/de.ts
+++ b/app/src/lib/i18n/de.ts
@@ -330,128 +330,11 @@ const messages: TranslationMap = {
'nav.flows': 'Workflows',
'nav.workflowRuns': 'Workflow-Ausführungen',
'nav.workflowDiscoveries': 'Workflows entdecken',
- 'nav.orchestration': 'Orchestrierung',
- 'orchestration.cloudUnreachable':
- 'Cloud-Gehirn nicht erreichbar – zwischengespeicherte Ansicht wird angezeigt.',
- 'orchPage.subtitle': 'Koordiniere deinen Hauptagenten',
- 'orchPage.group.agent': 'Agent',
- 'orchPage.group.network': 'Netzwerk',
- 'orchPage.group.insights': 'Einblicke',
- 'orchPage.overview.nav': 'Agenten-Graph',
- 'orchPage.overview.desc':
- 'Eine Live-Karte deines Agenten und der von ihm koordinierten Unteragenten.',
- 'orchPage.network.desc': 'Peer-Agenten, mit denen du verbunden bist, Entdeckung und Nutzung.',
+
'wallet.tabs.balance': 'Wallet-Guthaben',
'wallet.tabs.recovery': 'Wiederherstellung',
'wallet.ariaLabel': 'Wallet-Ansichten',
- 'orchPage.medulla.nav': 'Übersicht',
- 'orchPage.medulla.badge': 'Demnächst verfügbar',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'Das Orchestrierungsmodell von OpenHuman',
- 'orchPage.medulla.body':
- 'Medulla ist das eigens entwickelte LLM von OpenHuman. Es ist darauf ausgelegt, Tausende Agenten gleichzeitig zu orchestrieren, verfügt über ein Kontextfenster von 10 Millionen Tokens und ermöglicht eine radikal kostengünstigere Orchestrierung.',
- 'orchPage.medulla.featAgents': 'Tausende Agenten',
- 'orchPage.medulla.featContext': 'Kontext mit 10M Tokens',
- 'orchPage.medulla.featCost': 'Kostengünstige Orchestrierung',
- 'orchPage.medulla.subscriberTitle': 'OpenHuman-Abonnenten',
- 'orchPage.medulla.subscriberNote':
- 'Sobald Medulla live geht, ist es exklusiv für OpenHuman-Abonnenten.',
- 'orchPage.medulla.subscriberCta': 'Abo abschließen',
- 'orchPage.medulla.discordTitle': 'Tritt dem Discord bei',
- 'orchPage.medulla.earlyAccess':
- 'Früh dabei sein? Tritt unserem Discord bei und sichere dir eine Early-Access-Einladung.',
- 'orchPage.medulla.cta': 'Tritt unserem Discord bei',
- 'orchPage.demo.banner':
- 'Dies ist ein Beispiel dafür, wie Orchestrierung im großen Maßstab aussehen würde.',
- 'orchPage.demo.device': 'Gerät',
- 'orchPage.demo.taskRoute': 'Eingehende Anfrage weiterleiten',
- 'orchPage.demo.taskSummarize': 'Konversation zusammenfassen',
- 'orchPage.demo.taskEnrich': 'Kontaktdatensatz anreichern',
- 'orchPage.demo.taskSchedule': 'Follow-up planen',
- 'orchPage.demo.taskDraft': 'Antwort entwerfen',
- 'orchPage.demo.taskSync': 'Datenquelle synchronisieren',
- 'orchPage.demo.networkTitle': 'Peer-Agenten',
- 'orchPage.demo.networkSummary': '{peers} verbunden · {sessions} aktive Sub-Agenten',
- 'orchPage.demo.peer.connected': 'Verbunden',
- 'orchPage.demo.peer.connecting': 'Verbindung wird hergestellt',
- 'orchPage.demo.peer.idle': 'Inaktiv',
- 'orchPage.demo.peerSessions': '{count} Sub-Agenten',
- 'orchPage.demo.chat.user1': 'Koordiniere die Outreach-Kampagne über alle meine Kanäle.',
- 'orchPage.demo.chat.assistant1':
- 'Wird gemacht: ich starte 120 Agenten auf 2 Geräten, um Outreach, Anreicherung und Follow-ups parallel auszuführen.',
- 'orchPage.demo.chat.activity1': 'Gerät 1 · 100 Agenten leiten 1.284 Konversationen weiter',
- 'orchPage.demo.chat.activity2': 'Gerät 2 · 20 Agenten reichern 512 Kontakte an',
- 'orchPage.demo.chat.activity3': '640 personalisierte Antworten werden entworfen',
- 'orchPage.demo.chat.assistant2':
- 'Fertig. 120 Agenten haben 1.796 Konversationen in 38 Sekunden verarbeitet.',
- 'orchPage.demo.chat.composerDisabled': 'Der Chat ist mit Medulla-Zugang verfügbar',
- 'orchPage.tasks.nav': 'Aufgaben',
- 'orchPage.tasks.subtitle': 'Die globale Aufgabentafel des Orchestrators',
- 'orchPage.tasks.colPending': 'Ausstehend',
- 'orchPage.tasks.colActive': 'Aktiv',
- 'orchPage.tasks.colBlocked': 'Blockiert',
- 'orchPage.tasks.colCompleted': 'Abgeschlossen',
- 'orchPage.overview.core': 'Agent-Kern',
- 'orchPage.overview.empty': 'Noch keine Sub-Agenten zum Visualisieren',
- 'orchPage.agent.nav': 'Chat',
- 'orchPage.agent.mainTab': 'Hauptagent',
- 'orchPage.agent.consciousTab': 'Bewusstsein',
- 'orchPage.agent.subconsciousTab': 'Unterbewusstsein',
- 'orchPage.agent.modeLabel': 'Agentengeist',
- 'orchPage.agent.description': 'Chatte mit dem Hauptagenten und beobachte sein Unterbewusstsein',
- 'orchPage.agent.viewSession': 'Sitzung ansehen',
- 'orchPage.sessions.railTitle': 'Aktive Agenten',
- 'orchPage.sessions.empty': 'Noch keine aktiven Agenten',
- 'orchPage.sessions.statusConnected': 'Verbunden',
- 'orchPage.sessions.statusDisconnected': 'Getrennt',
- 'orchPage.sessions.statusWaiting': 'Wartet auf Eingabe',
- 'orchPage.session.runtime': 'Laufzeit',
- 'orchPage.session.directory': 'Verzeichnis',
- 'orchPage.session.runningOn': 'Läuft auf',
- 'orchPage.connections.nav': 'Verbindungen',
- 'orchPage.connections.title': 'Verknüpfte Agenten',
- 'orchPage.connections.description':
- 'Peers, mit denen dein Agent zusammenarbeitet: erweitere einen, um deine Sitzungen damit anzuzeigen',
- 'orchPage.connections.empty': 'Noch keine Verbindungen.',
- 'orchPage.connections.emptyCta': 'Verbindung hinzufügen',
- 'orchPage.connections.statContacts': 'Verbindungen',
- 'orchPage.connections.statPending': 'Ausstehend',
- 'orchPage.connections.statSessions': 'Sitzungen',
- 'orchPage.connections.sessionCount': '{n} Sitzungen',
- 'orchPage.connections.noSessions': 'Keine Sitzungen',
- 'orchPage.connections.messageCount': '{n} Nachrichten',
- 'orchPage.connections.back': 'Verbindungen',
- 'orchPage.connections.replyPlaceholder': 'Antworten…',
- 'orchPage.connections.initTitle': 'Einen Agenten oder eine Instanz initialisieren',
- 'orchPage.connections.initDesc':
- 'Starte einen neuen Sub-Agenten, der an deiner Seite arbeitet. Öffne den Agent-Chat und beschreibe Rolle, Ziel und Tools: OpenHuman stellt eine eigene Instanz bereit, die du von hier aus steuerst.',
- 'orchPage.connections.initCta': 'Im Chat starten',
- 'orchPage.connections.status.needsYou': 'Braucht dich',
- 'orchPage.connections.status.running': 'Läuft',
- 'orchPage.connections.status.idle': 'Inaktiv',
- 'orchPage.connections.status.done': 'Fertig',
- 'orchPage.connections.status.error': 'Fehler',
- 'orchPage.connections.pendingHint': 'Warten auf Annahme',
- 'orchPage.discover.nav': 'Entdecken',
- 'orchPage.discover.linkAction': 'Hinzufügen',
- 'orchPage.discover.identityTitle': 'Deine Auffindbarkeit',
- 'orchPage.discover.notDiscoverableGuide':
- 'Registriere ein @handle, damit andere Agenten dich finden und dir schreiben können.',
- 'orchPage.discover.linkTitle': 'Neuen Agenten verknüpfen',
- 'orchPage.discover.linkDescription':
- 'Füge eine Agenten-ID ein, um eine Verbindungsanfrage zu senden.',
- 'orchPage.discover.noRequests': 'Keine eingehenden Anfragen.',
- 'orchPage.usage.nav': 'Nutzung',
- 'orchPage.usage.connections': 'Verbindungen',
- 'orchPage.usage.balance': 'Guthaben',
- 'orchPage.usage.balanceHint': 'Aktion + Aufladung',
- 'orchPage.usage.cycleSpend': 'Zyklusausgaben',
- 'orchPage.usage.ofBudget': 'von',
- 'orchPage.usage.inferenceCalls': 'Modellaufrufe',
- 'orchPage.usage.integrationCalls': 'Integrationsaufrufe',
- 'orchPage.usage.tokensSaved': 'Gesparte Tokens',
- 'orchPage.usage.saved': 'gespart',
- 'orchPage.usage.footnote': 'Die Nutzung bezieht sich auf deinen aktuellen Abrechnungszeitraum.',
+
'nav.wallet': 'Wallet',
'nav.avatarMenu.account': 'Konto',
'nav.avatarMenu.billing': 'Abrechnung',
@@ -479,87 +362,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': 'Etwas ist schiefgelaufen. Bitte versuche es erneut.',
'brain.tabs.sources': 'Quellen',
'brain.tabs.sync': 'Synchronisierung',
- 'brain.tabs.orchestration': 'Orchestrierung',
- 'tinyplaceOrchestration.title': 'TinyPlace-Relay',
- 'tinyplaceOrchestration.subtitle': 'Angepinnte Agentenkanäle und App-Sitzungs-Chats',
- 'tinyplaceOrchestration.refresh': 'Aktualisieren',
- 'tinyplaceOrchestration.newInstance': 'Neue Instanz',
- 'tinyplaceOrchestration.newInstanceSoon': 'Demnächst verfügbar',
- 'tinyplaceOrchestration.pinned': 'Angepinnt',
- 'tinyplaceOrchestration.sessions': 'Sitzungen',
- 'tinyplaceOrchestration.contacts': 'Kontakte',
- 'tinyplaceOrchestration.noContacts': 'Noch keine Kontakte.',
- 'tinyplaceOrchestration.newSession': 'Neue Sitzung',
- 'tinyplaceOrchestration.otherSessions': 'Andere Sitzungen',
- 'tinyplaceOrchestration.loading': 'TinyPlace-Chats werden geladen…',
- 'tinyplaceOrchestration.paymentRequired': 'TinyPlace-Zugriff erfordert eine Zahlung.',
- 'tinyplaceOrchestration.failedToLoad': 'TinyPlace-Chats konnten nicht geladen werden',
- 'tinyplaceOrchestration.noSessions': 'Noch keine TinyPlace-App-Sitzungen.',
- 'tinyplaceOrchestration.noMessages': 'Noch keine Nachrichten in diesem Chat.',
- 'tinyplaceOrchestration.active': 'Aktiv',
- 'tinyplaceOrchestration.inactive': 'Inaktiv',
- 'tinyplaceOrchestration.encryptedBody': 'Verschlüsselte TinyPlace-Nachricht',
- 'tinyplaceOrchestration.unknownSender': 'Unbekannter Absender',
- 'tinyplaceOrchestration.master.title': 'Agent / Mensch',
- 'tinyplaceOrchestration.master.subtitle': 'Master-Chat',
- 'tinyplaceOrchestration.master.preview': 'Direkte Koordination zwischen dir und OpenHuman.',
- 'tinyplaceOrchestration.subconscious.title': 'Unterbewusstsein',
- 'tinyplaceOrchestration.subconscious.subtitle': 'Interne Agenten-Chats',
- 'tinyplaceOrchestration.subconscious.preview':
- 'Agentenkoordination im Hintergrund und Gedächtnisschleifen.',
- 'tinyplaceOrchestration.session.subtitle': 'TinyPlace-App-Sitzung',
- 'tinyplaceOrchestration.pairing.linkLabel': 'Sitzung verknüpfen',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': 'Sitzungs-Agent-ID einfügen',
- 'tinyplaceOrchestration.pairing.linkAction': 'Verknüpfen',
- 'tinyplaceOrchestration.pairing.requests': 'Kontaktanfragen',
- 'tinyplaceOrchestration.pairing.accept': 'Annehmen',
- 'tinyplaceOrchestration.pairing.decline': 'Ablehnen',
- 'tinyplaceOrchestration.pairing.block': 'Blockieren',
- 'tinyplaceOrchestration.pairing.linked': 'Verknüpft',
- 'tinyplaceOrchestration.pairing.pending': 'Ausstehend',
- 'tinyplaceOrchestration.pairing.unlinked': 'Nicht verknüpft',
- 'tinyplaceOrchestration.pairing.incoming': 'Eingehend',
- 'tinyplaceOrchestration.pairing.outgoing': 'Ausgehend',
- 'tinyplaceOrchestration.master.you': 'Du',
- 'tinyplaceOrchestration.composer.placeholder': 'Nachricht an OpenHuman…',
- 'tinyplaceOrchestration.composer.send': 'Senden',
- 'tinyplaceOrchestration.composer.sendFailed': 'Nachricht konnte nicht gesendet werden',
- 'tinyplaceOrchestration.steering.label': 'Steuerung',
- 'tinyplaceOrchestration.relay.staging': 'Staging',
- 'tinyplaceOrchestration.relay.prod': 'Produktion',
- 'tinyplaceOrchestration.identity.loading': 'Identität wird geladen…',
- 'tinyplaceOrchestration.identity.noHandle': 'Noch kein @handle',
- 'tinyplaceOrchestration.identity.copy': 'Kopieren',
- 'tinyplaceOrchestration.identity.copied': 'Kopiert',
- 'tinyplaceOrchestration.identity.discoverable': 'Auffindbar',
- 'tinyplaceOrchestration.identity.undiscoverable': 'Nicht auffindbar',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'Veröffentliche deine Verzeichniskarte und deinen Verschlüsselungsschlüssel, damit Peers dir schreiben können.',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'Auffindbar machen',
- 'tinyplaceOrchestration.identity.republish': 'Schlüssel neu veröffentlichen',
- 'tinyplaceOrchestration.identity.publishing': 'Wird veröffentlicht…',
- 'tinyplaceOrchestration.identity.publishFailed':
- 'Veröffentlichung fehlgeschlagen: erneut versuchen',
- 'tinyplaceOrchestration.identity.card': 'Verzeichniskarte',
- 'tinyplaceOrchestration.identity.key': 'Verschlüsselungsschlüssel',
- 'tinyplaceOrchestration.identity.published': 'Veröffentlicht',
- 'tinyplaceOrchestration.identity.notPublished': 'Nicht veröffentlicht',
- 'tinyplaceOrchestration.roster.instances': 'Instanzen',
- 'tinyplaceOrchestration.roster.empty': 'Noch keine Agent-Instanzen',
- 'tinyplaceOrchestration.roster.other': 'Andere',
- 'tinyplaceOrchestration.status.running': 'Läuft',
- 'tinyplaceOrchestration.status.idle': 'Inaktiv',
- 'tinyplaceOrchestration.status.waitingApproval': 'Warten auf Freigabe',
- 'tinyplaceOrchestration.status.errored': 'Fehler',
- 'tinyplaceOrchestration.status.stopped': 'Gestoppt',
- 'tinyplaceOrchestration.attention.title': 'Braucht dich',
- 'tinyplaceOrchestration.attention.empty': 'Alles erledigt',
- 'tinyplaceOrchestration.attention.unread': 'Ungelesene Nachrichten',
- 'tinyplaceOrchestration.attention.review': 'Prüfen',
- 'tinyplaceOrchestration.attention.open': 'Öffnen',
- 'tinyplaceOrchestration.attention.kind.approval': 'Freigabe',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'Eingabe nötig',
- 'tinyplaceOrchestration.attention.kind.unread': 'Ungelesen',
'brain.empty': 'Dein Gehirn ist noch leer – verbinde eine Quelle, um Speicher aufzubauen.',
'brain.error': 'Dein Gehirn konnte nicht geladen werden. Bitte versuche es erneut.',
'common.cancel': 'Abbrechen',
@@ -2979,10 +2781,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'Führe Modelle auf deinem eigenen Computer mit Ollama aus. Vollständige Privatsphäre, erfordert eine Einrichtung.',
'backend.ramRecommended': '16 GB+ RAM empfohlen',
- 'tinyplaceOrchestration.subconsciousBadge': 'Unterbewusstsein · Steuerung',
- 'tinyplaceOrchestration.steeringHeader.current': 'Aktive Anweisung',
- 'tinyplaceOrchestration.steeringHeader.none': 'Keine aktive Anweisung',
- 'tinyplaceOrchestration.steeringHeader.expires': 'läuft nach {n} Zyklen ab',
'actionable.complete': 'Komplett',
'actionable.dismiss': 'Entlassen',
'actionable.snooze': 'Schlummern',
@@ -5351,10 +5149,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'Alle Aktionen automatisch genehmigen',
'settings.agentAccess.autoApproveAll.desc':
'Wenn aktiviert, genehmigt der Agent automatisch alle zulässigen Aktionen, ohne vorher deine Zustimmung einzuholen. Dazu gehören Dateischreibvorgänge, Shell-Befehle, Netzwerkanfragen und andere Aktionen mit externen Auswirkungen. Feste Sicherheitssperren (Anmeldeinformationen und Systemverzeichnisse) gelten weiterhin, und Aktionen aus nicht vertrauenswürdigen oder unbekannten Quellen werden nie automatisch genehmigt.',
- 'settings.agentAccess.tinyplaceAutopilot.title': 'Autonomer tiny.place-Agent',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'Lass OpenHuman eigenständig auf tiny.place handeln: zeitgesteuert sucht es lohnende Arbeit – zuerst offene Bounties –, erledigt Passendes und handelt über deine Identität. Es läuft unbeaufsichtigt und kann Geld ausgeben; nutze beim Testen devnet. Standardmäßig aus.',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'Automatisch ausführen',
'settings.agentAccess.timeout.label': 'Aktions-Timeout',
'settings.agentAccess.timeout.desc':
'Wie lange ein einzelnes Werkzeug oder eine Aktion laufen darf, bevor sie abgebrochen wird. Erhöhen Sie diesen Wert, wenn ein großes lokales Modell unterbrochen wird, bevor es seine Antwort beendet.',
@@ -6786,9 +6580,7 @@ const messages: TranslationMap = {
'notch.speaking': 'Spreche…',
'notch.transcribing': 'Transkribiere…',
'notch.executing': 'Führe aus…',
- 'memory.tab.orchestration': 'Orchestrierung',
- 'memory.tab.orchestrationDescription':
- 'Führe Multi-Agenten-Workflows aus: verteile eine Frage auf parallele Agenten, gleiche ihre Ergebnisse ab und sieh zu, wie jede Phase zu einer zusammengeführten Antwort wird.',
+
'orchestration.subtitle':
'Starte einen Multi-Agenten-Workflow, verfolge seinen Phasenfortschritt und lies das zusammengeführte Ergebnis.',
'orchestration.loading': 'Lade Workflows…',
@@ -6938,10 +6730,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'Dein Embedding-Budget ist aufgebraucht, daher werden keine neuen Inhalte mehr ins Gedächtnis aufgenommen. Richte lokale Embeddings ein oder hinterlege deinen eigenen API-Schlüssel, um fortzufahren.',
'memoryBudget.cta': 'Embeddings einrichten',
- 'tinyplaceSunset.title': 'Tiny Place zieht aus der App aus',
- 'tinyplaceSunset.message':
- 'Um tiny.place weiter zu nutzen, besuche tiny.place. Nach dem 31. August 2026 wird es aus der App entfernt.',
- 'tinyplaceSunset.cta': 'tiny.place öffnen',
'userErrors.scope.memory': 'Speicher',
// Code block chrome
diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts
index b3b5f2ab2f..6b85d3c898 100644
--- a/app/src/lib/i18n/en.ts
+++ b/app/src/lib/i18n/en.ts
@@ -28,122 +28,7 @@ const en: TranslationMap = {
'nav.flows': 'Workflows',
'nav.workflowRuns': 'Workflow Runs',
'nav.workflowDiscoveries': 'Discover Workflows',
- 'nav.orchestration': 'Orchestration',
- 'orchestration.cloudUnreachable': 'Cloud brain unreachable: showing your cached view.',
-
- // ── Orchestration sub-pages (orchPage.*) ──────────────────────────────────
- 'orchPage.subtitle': 'Coordinate your main agent',
- 'orchPage.group.agent': 'Agent',
- 'orchPage.group.network': 'Network',
- 'orchPage.group.insights': 'Insights',
- 'orchPage.overview.nav': 'Agent graph',
- 'orchPage.overview.desc': 'A live map of your agent and the sub-agents it coordinates.',
- 'orchPage.network.desc': 'Peer agents you’re connected to, discovery, and usage.',
- 'orchPage.medulla.nav': 'Overview',
- 'orchPage.medulla.badge': 'Coming soon',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': "OpenHuman's orchestration model",
- 'orchPage.medulla.body':
- "Medulla is OpenHuman's custom-built LLM, engineered to orchestrate thousands of agents at once, with a 10-million-token context window and radically low-cost orchestration.",
- 'orchPage.medulla.featAgents': 'Thousands of agents',
- 'orchPage.medulla.featContext': '10M-token context',
- 'orchPage.medulla.featCost': 'Low-cost orchestration',
- 'orchPage.medulla.subscriberTitle': 'OpenHuman Subscribers',
- 'orchPage.medulla.subscriberNote':
- 'When Medulla goes live, it will be exclusive to OpenHuman subscribers.',
- 'orchPage.medulla.subscriberCta': 'Get a Subscription',
- 'orchPage.medulla.discordTitle': 'Join the Discord',
- 'orchPage.medulla.earlyAccess':
- 'Want in early? Join our Discord and grab an early-access invite.',
- 'orchPage.medulla.cta': 'Join our Discord',
- 'orchPage.demo.banner': 'This is an example of how orchestration would look at scale.',
- 'orchPage.demo.device': 'Device',
- 'orchPage.demo.taskRoute': 'Route inbound request',
- 'orchPage.demo.taskSummarize': 'Summarize conversation',
- 'orchPage.demo.taskEnrich': 'Enrich contact record',
- 'orchPage.demo.taskSchedule': 'Schedule follow-up',
- 'orchPage.demo.taskDraft': 'Draft reply',
- 'orchPage.demo.taskSync': 'Sync data source',
- 'orchPage.demo.networkTitle': 'Peer agents',
- 'orchPage.demo.networkSummary': '{peers} connected · {sessions} live sub-agents',
- 'orchPage.demo.peer.connected': 'Connected',
- 'orchPage.demo.peer.connecting': 'Connecting',
- 'orchPage.demo.peer.idle': 'Idle',
- 'orchPage.demo.peerSessions': '{count} sub-agents',
- 'orchPage.demo.chat.user1': 'Coordinate the outreach campaign across all my channels.',
- 'orchPage.demo.chat.assistant1':
- 'On it: spinning up 120 agents across 2 devices to run outreach, enrichment, and follow-ups in parallel.',
- 'orchPage.demo.chat.activity1': 'device 1 · 100 agents routing 1,284 conversations',
- 'orchPage.demo.chat.activity2': 'device 2 · 20 agents enriching 512 contacts',
- 'orchPage.demo.chat.activity3': 'drafting 640 personalized replies',
- 'orchPage.demo.chat.assistant2': 'Done. 120 agents processed 1,796 conversations in 38 seconds.',
- 'orchPage.demo.chat.composerDisabled': 'Chat is available with Medulla access',
- 'orchPage.tasks.nav': 'Tasks',
- 'orchPage.tasks.subtitle': "The orchestrator's global task board",
- 'orchPage.tasks.colPending': 'Pending',
- 'orchPage.tasks.colActive': 'Active',
- 'orchPage.tasks.colBlocked': 'Blocked',
- 'orchPage.tasks.colCompleted': 'Completed',
- 'orchPage.overview.core': 'Agent core',
- 'orchPage.overview.empty': 'No sub-agents to visualize yet',
- 'orchPage.agent.nav': 'Chat',
- 'orchPage.agent.mainTab': 'Main agent',
- 'orchPage.agent.consciousTab': 'Conscious',
- 'orchPage.agent.subconsciousTab': 'Subconscious',
- 'orchPage.agent.modeLabel': 'Agent mind',
- 'orchPage.agent.description': 'Chat with the main agent and watch its subconscious',
- 'orchPage.agent.viewSession': 'View session',
- 'orchPage.sessions.railTitle': 'Active agents',
- 'orchPage.sessions.empty': 'No active agents yet',
- 'orchPage.sessions.statusConnected': 'Connected',
- 'orchPage.sessions.statusDisconnected': 'Disconnected',
- 'orchPage.sessions.statusWaiting': 'Waiting for input',
- 'orchPage.session.runtime': 'Runtime',
- 'orchPage.session.directory': 'Directory',
- 'orchPage.session.runningOn': 'Running on',
- 'orchPage.connections.nav': 'Connections',
- 'orchPage.connections.title': 'Linked agents',
- 'orchPage.connections.description':
- 'Peers your agent coordinates with: expand one to see your sessions with it',
- 'orchPage.connections.empty': 'No connections yet.',
- 'orchPage.connections.emptyCta': 'Add a connection',
- 'orchPage.connections.statContacts': 'Connections',
- 'orchPage.connections.statSessions': 'Sessions',
- 'orchPage.connections.statPending': 'Pending',
- 'orchPage.connections.pendingHint': 'Awaiting acceptance',
- 'orchPage.connections.sessionCount': '{n} sessions',
- 'orchPage.connections.noSessions': 'No sessions',
- 'orchPage.connections.messageCount': '{n} messages',
- 'orchPage.connections.back': 'Connections',
- 'orchPage.connections.replyPlaceholder': 'Reply…',
- 'orchPage.connections.initTitle': 'Initialize an agent or an instance',
- 'orchPage.connections.initDesc':
- 'Spin up a new sub-agent to work alongside you. Open the agent chat and describe the role, goal, and tools it should use: OpenHuman provisions a dedicated instance you can steer from here.',
- 'orchPage.connections.initCta': 'Start in chat',
- 'orchPage.connections.status.needsYou': 'Needs you',
- 'orchPage.connections.status.running': 'Running',
- 'orchPage.connections.status.idle': 'Idle',
- 'orchPage.connections.status.done': 'Done',
- 'orchPage.connections.status.error': 'Error',
- 'orchPage.discover.nav': 'Discover',
- 'orchPage.discover.linkAction': 'Add',
- 'orchPage.discover.identityTitle': 'Your discoverability',
- 'orchPage.discover.notDiscoverableGuide':
- 'Register a @handle so other agents can find and message you.',
- 'orchPage.discover.linkTitle': 'Link a new agent',
- 'orchPage.discover.linkDescription': 'Paste an agent ID to send a connection request.',
- 'orchPage.discover.noRequests': 'No incoming requests.',
- 'orchPage.usage.nav': 'Usage',
- 'orchPage.usage.connections': 'Connections',
- 'orchPage.usage.balance': 'Credit balance',
- 'orchPage.usage.balanceHint': 'Promotional + top-up',
- 'orchPage.usage.cycleSpend': 'Cycle spend',
- 'orchPage.usage.ofBudget': 'of',
- 'orchPage.usage.inferenceCalls': 'Model calls',
- 'orchPage.usage.integrationCalls': 'Integration calls',
- 'orchPage.usage.tokensSaved': 'Tokens saved',
- 'orchPage.usage.saved': 'saved',
- 'orchPage.usage.footnote': 'Usage reflects your current billing cycle.',
+
'nav.wallet': 'Wallet',
// Agent World: Settings section UI
'nav.avatarMenu.account': 'Account',
@@ -180,7 +65,6 @@ const en: TranslationMap = {
'brain.tabs.goals': 'Goals',
'brain.tabs.sources': 'Sources',
'brain.tabs.sync': 'Sync',
- 'brain.tabs.orchestration': 'Orchestration',
'brain.empty': 'Your brain is empty for now: connect a source to start building memory.',
'brain.error': "Couldn't load your brain. Please try again.",
'brain.goals.title': 'Long-term Goals',
@@ -819,9 +703,7 @@ const en: TranslationMap = {
'memory.tab.workflows': 'Workflows',
'memory.tab.workflowsDescription':
'Reusable, runnable procedures: a goal plus the steps to reach it. Create one, install from a URL, or open a workflow to run it.',
- 'memory.tab.orchestration': 'Orchestration',
- 'memory.tab.orchestrationDescription':
- 'Run multi-agent workflows: fan a question out across parallel agents, cross-check their findings, and watch each phase finish into one synthesized answer.',
+
'memory.tab.dreams': 'Dreams',
'memory.tab.calls': 'Calls',
'memory.tab.diagram': 'Diagram',
@@ -3194,10 +3076,6 @@ const en: TranslationMap = {
'backend.ramRecommended': '16GB+ RAM recommended',
// Subconscious
- 'tinyplaceOrchestration.subconsciousBadge': 'Subconscious · steering',
- 'tinyplaceOrchestration.steeringHeader.current': 'Active directive',
- 'tinyplaceOrchestration.steeringHeader.none': 'No active directive',
- 'tinyplaceOrchestration.steeringHeader.expires': 'expires after {n} cycles',
// Subconscious triggers (event-driven orchestrator) debug panel
@@ -4206,84 +4084,6 @@ const en: TranslationMap = {
'orchestration.detail.agents': 'agents',
'orchestration.detail.childRefs': 'Child agents',
'orchestration.detail.synthesis': 'Final synthesis',
- 'tinyplaceOrchestration.title': 'TinyPlace relay',
- 'tinyplaceOrchestration.subtitle': 'Pinned agent channels and app-session chats',
- 'tinyplaceOrchestration.refresh': 'Refresh',
- 'tinyplaceOrchestration.newInstance': 'New instance',
- 'tinyplaceOrchestration.newInstanceSoon': 'Coming soon',
- 'tinyplaceOrchestration.pinned': 'Pinned',
- 'tinyplaceOrchestration.sessions': 'Sessions',
- 'tinyplaceOrchestration.contacts': 'Contacts',
- 'tinyplaceOrchestration.noContacts': 'No contacts yet.',
- 'tinyplaceOrchestration.newSession': 'New session',
- 'tinyplaceOrchestration.otherSessions': 'Other sessions',
- 'tinyplaceOrchestration.loading': 'Loading TinyPlace chats…',
- 'tinyplaceOrchestration.paymentRequired': 'TinyPlace access requires payment.',
- 'tinyplaceOrchestration.failedToLoad': 'Failed to load TinyPlace chats',
- 'tinyplaceOrchestration.noSessions': 'No TinyPlace app sessions yet.',
- 'tinyplaceOrchestration.noMessages': 'No messages in this chat yet.',
- 'tinyplaceOrchestration.active': 'Active',
- 'tinyplaceOrchestration.inactive': 'Inactive',
- 'tinyplaceOrchestration.encryptedBody': 'Encrypted TinyPlace message',
- 'tinyplaceOrchestration.unknownSender': 'Unknown sender',
- 'tinyplaceOrchestration.master.title': 'Agent / human',
- 'tinyplaceOrchestration.master.subtitle': 'Master chat',
- 'tinyplaceOrchestration.master.preview': 'Direct coordination between you and OpenHuman.',
- 'tinyplaceOrchestration.subconscious.title': 'Subconscious',
- 'tinyplaceOrchestration.subconscious.subtitle': 'Internal agent chats',
- 'tinyplaceOrchestration.subconscious.preview': 'Background agent coordination and memory loops.',
- 'tinyplaceOrchestration.session.subtitle': 'TinyPlace app session',
- 'tinyplaceOrchestration.pairing.linkLabel': 'Link session',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': 'Paste session agent ID',
- 'tinyplaceOrchestration.pairing.linkAction': 'Link',
- 'tinyplaceOrchestration.pairing.requests': 'Contact requests',
- 'tinyplaceOrchestration.pairing.accept': 'Accept',
- 'tinyplaceOrchestration.pairing.decline': 'Decline',
- 'tinyplaceOrchestration.pairing.block': 'Block',
- 'tinyplaceOrchestration.pairing.linked': 'Linked',
- 'tinyplaceOrchestration.pairing.pending': 'Pending',
- 'tinyplaceOrchestration.pairing.unlinked': 'Unlinked',
- 'tinyplaceOrchestration.pairing.incoming': 'Incoming',
- 'tinyplaceOrchestration.pairing.outgoing': 'Outgoing',
- 'tinyplaceOrchestration.master.you': 'You',
- 'tinyplaceOrchestration.composer.placeholder': 'Message OpenHuman…',
- 'tinyplaceOrchestration.composer.send': 'Send',
- 'tinyplaceOrchestration.composer.sendFailed': 'Failed to send message',
- 'tinyplaceOrchestration.steering.label': 'Steering',
- 'tinyplaceOrchestration.relay.staging': 'Staging',
- 'tinyplaceOrchestration.relay.prod': 'Production',
- 'tinyplaceOrchestration.identity.loading': 'Loading identity…',
- 'tinyplaceOrchestration.identity.noHandle': 'No @handle yet',
- 'tinyplaceOrchestration.identity.copy': 'Copy',
- 'tinyplaceOrchestration.identity.copied': 'Copied',
- 'tinyplaceOrchestration.identity.discoverable': 'Discoverable',
- 'tinyplaceOrchestration.identity.undiscoverable': 'Not discoverable',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'Publish your directory card + encryption key so peers can message you.',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'Make discoverable',
- 'tinyplaceOrchestration.identity.republish': 'Republish keys',
- 'tinyplaceOrchestration.identity.publishing': 'Publishing…',
- 'tinyplaceOrchestration.identity.publishFailed': 'Publishing failed. Try again.',
- 'tinyplaceOrchestration.identity.card': 'Directory card',
- 'tinyplaceOrchestration.identity.key': 'Encryption key',
- 'tinyplaceOrchestration.identity.published': 'Published',
- 'tinyplaceOrchestration.identity.notPublished': 'Not published',
- 'tinyplaceOrchestration.roster.instances': 'Instances',
- 'tinyplaceOrchestration.roster.empty': 'No agent instances yet',
- 'tinyplaceOrchestration.roster.other': 'Other',
- 'tinyplaceOrchestration.status.running': 'Running',
- 'tinyplaceOrchestration.status.idle': 'Idle',
- 'tinyplaceOrchestration.status.waitingApproval': 'Waiting for approval',
- 'tinyplaceOrchestration.status.errored': 'Errored',
- 'tinyplaceOrchestration.status.stopped': 'Stopped',
- 'tinyplaceOrchestration.attention.title': 'Needs you',
- 'tinyplaceOrchestration.attention.empty': "You're all caught up",
- 'tinyplaceOrchestration.attention.unread': 'Unread messages',
- 'tinyplaceOrchestration.attention.review': 'Review',
- 'tinyplaceOrchestration.attention.open': 'Open',
- 'tinyplaceOrchestration.attention.kind.approval': 'Approval',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'Needs input',
- 'tinyplaceOrchestration.attention.kind.unread': 'Unread',
'intelligence.teams.subtitle': 'Coordinated agent teams and the tasks they share.',
'intelligence.teams.loading': 'Loading teams…',
'intelligence.teams.failedToLoad': 'Failed to load teams',
@@ -5924,10 +5724,6 @@ const en: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'Auto-approve all actions',
'settings.agentAccess.autoApproveAll.desc':
'When enabled, the agent executes all eligible actions without asking for your approval first. This includes file writes, shell commands, network requests, and any other side effects. Credential and system directories stay blocked, and actions from untrusted or unlabelled call origins are still denied.',
- 'settings.agentAccess.tinyplaceAutopilot.title': 'Autonomous tiny.place agent',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'Let OpenHuman act on tiny.place on its own. On a schedule, it finds worthwhile work (open bounties first), does what fits its skills, and acts from your identity. It runs unattended and can spend, so keep it on devnet while testing. Off by default.',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'Run automatically',
'settings.agentAccess.timeout.label': 'Action timeout',
'settings.agentAccess.timeout.desc':
'How long a single tool or action may run before it is cancelled. Increase this if a large local model is interrupted before it finishes responding.',
@@ -7266,10 +7062,6 @@ const en: TranslationMap = {
'memoryBudget.exhaustedMessage':
'Your embedding budget is used up, so new content is no longer being added to memory. Set up local embeddings or add your own API key to resume.',
'memoryBudget.cta': 'Set up embeddings',
- 'tinyplaceSunset.title': 'Tiny Place is moving out of the app',
- 'tinyplaceSunset.message':
- 'To keep using tiny.place, visit tiny.place. It will be removed from the app after 31 August 2026.',
- 'tinyplaceSunset.cta': 'Open tiny.place',
'memorySources.codingSessions.title': 'Coding-agent sessions',
'memorySources.codingSessions.description':
'Turn your Codex and Claude Code decisions and corrections into private persona memory.',
diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts
index 9894048501..ded3c17452 100644
--- a/app/src/lib/i18n/es.ts
+++ b/app/src/lib/i18n/es.ts
@@ -320,126 +320,11 @@ const messages: TranslationMap = {
'nav.flows': 'Flujos de trabajo',
'nav.workflowRuns': 'Ejecuciones de flujos',
'nav.workflowDiscoveries': 'Descubrir flujos',
- 'nav.orchestration': 'Orquestación',
- 'orchestration.cloudUnreachable':
- 'No se puede acceder al cerebro en la nube: mostrando la vista almacenada.',
- 'orchPage.subtitle': 'Coordina tu agente principal',
- 'orchPage.group.agent': 'Agente',
- 'orchPage.group.network': 'Red',
- 'orchPage.group.insights': 'Estadísticas',
- 'orchPage.overview.nav': 'Grafo de agentes',
- 'orchPage.overview.desc': 'Un mapa en vivo de tu agente y de los subagentes que coordina.',
- 'orchPage.network.desc': 'Agentes pares a los que estás conectado, descubrimiento y uso.',
+
'wallet.tabs.balance': 'Saldo de la cartera',
'wallet.tabs.recovery': 'Recuperación',
'wallet.ariaLabel': 'Vistas de la cartera',
- 'orchPage.medulla.nav': 'Resumen',
- 'orchPage.medulla.badge': 'Próximamente',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'El modelo de orquestación de OpenHuman',
- 'orchPage.medulla.body':
- 'Medulla es el LLM propio de OpenHuman, diseñado para orquestar miles de agentes a la vez, con una ventana de contexto de 10 millones de tokens y una orquestación de coste radicalmente bajo.',
- 'orchPage.medulla.featAgents': 'Miles de agentes',
- 'orchPage.medulla.featContext': 'Contexto de 10M de tokens',
- 'orchPage.medulla.featCost': 'Orquestación de bajo coste',
- 'orchPage.medulla.subscriberTitle': 'Suscriptores de OpenHuman',
- 'orchPage.medulla.subscriberNote':
- 'Cuando Medulla se lance, será exclusivo para los suscriptores de OpenHuman.',
- 'orchPage.medulla.subscriberCta': 'Consigue una suscripción',
- 'orchPage.medulla.discordTitle': 'Únete al Discord',
- 'orchPage.medulla.earlyAccess':
- '¿Quieres acceso anticipado? Únete a nuestro Discord y consigue una invitación.',
- 'orchPage.medulla.cta': 'Únete a nuestro Discord',
- 'orchPage.demo.banner': 'Este es un ejemplo de cómo se vería la orquestación a gran escala.',
- 'orchPage.demo.device': 'Dispositivo',
- 'orchPage.demo.taskRoute': 'Enrutar solicitud entrante',
- 'orchPage.demo.taskSummarize': 'Resumir conversación',
- 'orchPage.demo.taskEnrich': 'Enriquecer registro de contacto',
- 'orchPage.demo.taskSchedule': 'Programar seguimiento',
- 'orchPage.demo.taskDraft': 'Redactar respuesta',
- 'orchPage.demo.taskSync': 'Sincronizar fuente de datos',
- 'orchPage.demo.networkTitle': 'Agentes pares',
- 'orchPage.demo.networkSummary': '{peers} conectados · {sessions} subagentes activos',
- 'orchPage.demo.peer.connected': 'Conectado',
- 'orchPage.demo.peer.connecting': 'Conectando',
- 'orchPage.demo.peer.idle': 'Inactivo',
- 'orchPage.demo.peerSessions': '{count} subagentes',
- 'orchPage.demo.chat.user1': 'Coordina la campaña de difusión en todos mis canales.',
- 'orchPage.demo.chat.assistant1':
- 'Manos a la obra: iniciando 120 agentes en 2 dispositivos para ejecutar difusión, enriquecimiento y seguimientos en paralelo.',
- 'orchPage.demo.chat.activity1': 'dispositivo 1 · 100 agentes enrutando 1284 conversaciones',
- 'orchPage.demo.chat.activity2': 'dispositivo 2 · 20 agentes enriqueciendo 512 contactos',
- 'orchPage.demo.chat.activity3': 'redactando 640 respuestas personalizadas',
- 'orchPage.demo.chat.assistant2':
- 'Listo. 120 agentes procesaron 1796 conversaciones en 38 segundos.',
- 'orchPage.demo.chat.composerDisabled': 'El chat está disponible con acceso a Medulla',
- 'orchPage.tasks.nav': 'Tareas',
- 'orchPage.tasks.subtitle': 'El tablero de tareas global del orquestador',
- 'orchPage.tasks.colPending': 'Pendiente',
- 'orchPage.tasks.colActive': 'Activo',
- 'orchPage.tasks.colBlocked': 'Bloqueado',
- 'orchPage.tasks.colCompleted': 'Completado',
- 'orchPage.overview.core': 'Núcleo del agente',
- 'orchPage.overview.empty': 'Aún no hay subagentes para visualizar',
- 'orchPage.agent.nav': 'Chat',
- 'orchPage.agent.mainTab': 'Agente principal',
- 'orchPage.agent.consciousTab': 'Consciente',
- 'orchPage.agent.subconsciousTab': 'Subconsciente',
- 'orchPage.agent.modeLabel': 'Mente del agente',
- 'orchPage.agent.description': 'Chatea con el agente principal y observa su subconsciente',
- 'orchPage.agent.viewSession': 'Ver sesión',
- 'orchPage.sessions.railTitle': 'Agentes activos',
- 'orchPage.sessions.empty': 'Aún no hay agentes activos',
- 'orchPage.sessions.statusConnected': 'Conectado',
- 'orchPage.sessions.statusDisconnected': 'Desconectado',
- 'orchPage.sessions.statusWaiting': 'Esperando entrada',
- 'orchPage.session.runtime': 'Tiempo de ejecución',
- 'orchPage.session.directory': 'Directorio',
- 'orchPage.session.runningOn': 'Ejecutándose en',
- 'orchPage.connections.nav': 'Conexiones',
- 'orchPage.connections.title': 'Agentes vinculados',
- 'orchPage.connections.description':
- 'Pares con los que se coordina tu agente: expande uno para ver tus sesiones con él',
- 'orchPage.connections.empty': 'Aún no hay conexiones.',
- 'orchPage.connections.emptyCta': 'Agregar una conexión',
- 'orchPage.connections.statContacts': 'Conexiones',
- 'orchPage.connections.statPending': 'Pendiente',
- 'orchPage.connections.statSessions': 'Sesiones',
- 'orchPage.connections.sessionCount': '{n} sesiones',
- 'orchPage.connections.noSessions': 'Sin sesiones',
- 'orchPage.connections.messageCount': '{n} mensajes',
- 'orchPage.connections.back': 'Conexiones',
- 'orchPage.connections.replyPlaceholder': 'Responder…',
- 'orchPage.connections.initTitle': 'Inicializar un agente o una instancia',
- 'orchPage.connections.initDesc':
- 'Crea un nuevo subagente para trabajar contigo. Abre el chat del agente y describe el rol, el objetivo y las herramientas que debe usar: OpenHuman aprovisiona una instancia dedicada que puedes dirigir desde aquí.',
- 'orchPage.connections.initCta': 'Empezar en el chat',
- 'orchPage.connections.status.needsYou': 'Te necesita',
- 'orchPage.connections.status.running': 'En ejecución',
- 'orchPage.connections.status.idle': 'Inactivo',
- 'orchPage.connections.status.done': 'Hecho',
- 'orchPage.connections.status.error': 'Fallo',
- 'orchPage.connections.pendingHint': 'Esperando aceptación',
- 'orchPage.discover.nav': 'Descubrir',
- 'orchPage.discover.linkAction': 'Agregar',
- 'orchPage.discover.identityTitle': 'Tu visibilidad',
- 'orchPage.discover.notDiscoverableGuide':
- 'Registra un @handle para que otros agentes puedan encontrarte y escribirte.',
- 'orchPage.discover.linkTitle': 'Vincular un nuevo agente',
- 'orchPage.discover.linkDescription':
- 'Pega un ID de agente para enviar una solicitud de conexión.',
- 'orchPage.discover.noRequests': 'No hay solicitudes entrantes.',
- 'orchPage.usage.nav': 'Uso',
- 'orchPage.usage.connections': 'Conexiones',
- 'orchPage.usage.balance': 'Saldo de crédito',
- 'orchPage.usage.balanceHint': 'Promocional + recarga',
- 'orchPage.usage.cycleSpend': 'Gasto del ciclo',
- 'orchPage.usage.ofBudget': 'de',
- 'orchPage.usage.inferenceCalls': 'Llamadas al modelo',
- 'orchPage.usage.integrationCalls': 'Llamadas de integración',
- 'orchPage.usage.tokensSaved': 'Tokens ahorrados',
- 'orchPage.usage.saved': 'ahorrado',
- 'orchPage.usage.footnote': 'El uso refleja tu ciclo de facturación actual.',
+
'nav.wallet': 'Cartera',
'nav.avatarMenu.account': 'Cuenta',
'nav.avatarMenu.billing': 'Facturación',
@@ -467,86 +352,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': 'Algo salió mal. Inténtalo de nuevo.',
'brain.tabs.sources': 'Fuentes',
'brain.tabs.sync': 'Sincronización',
- 'brain.tabs.orchestration': 'Orquestación',
- 'tinyplaceOrchestration.title': 'Relay de TinyPlace',
- 'tinyplaceOrchestration.subtitle': 'Canales de agentes fijados y chats de sesiones de app',
- 'tinyplaceOrchestration.refresh': 'Actualizar',
- 'tinyplaceOrchestration.newInstance': 'Nueva instancia',
- 'tinyplaceOrchestration.newInstanceSoon': 'Próximamente',
- 'tinyplaceOrchestration.pinned': 'Fijados',
- 'tinyplaceOrchestration.sessions': 'Sesiones',
- 'tinyplaceOrchestration.contacts': 'Contactos',
- 'tinyplaceOrchestration.noContacts': 'Aún no hay contactos.',
- 'tinyplaceOrchestration.newSession': 'Nueva sesión',
- 'tinyplaceOrchestration.otherSessions': 'Otras sesiones',
- 'tinyplaceOrchestration.loading': 'Cargando chats de TinyPlace…',
- 'tinyplaceOrchestration.paymentRequired': 'El acceso a TinyPlace requiere pago.',
- 'tinyplaceOrchestration.failedToLoad': 'No se pudieron cargar los chats de TinyPlace',
- 'tinyplaceOrchestration.noSessions': 'Aún no hay sesiones de app de TinyPlace.',
- 'tinyplaceOrchestration.noMessages': 'Aún no hay mensajes en este chat.',
- 'tinyplaceOrchestration.active': 'Activa',
- 'tinyplaceOrchestration.inactive': 'Inactiva',
- 'tinyplaceOrchestration.encryptedBody': 'Mensaje cifrado de TinyPlace',
- 'tinyplaceOrchestration.unknownSender': 'Remitente desconocido',
- 'tinyplaceOrchestration.master.title': 'Agente / humano',
- 'tinyplaceOrchestration.master.subtitle': 'Chat maestro',
- 'tinyplaceOrchestration.master.preview': 'Coordinación directa entre tú y OpenHuman.',
- 'tinyplaceOrchestration.subconscious.title': 'Subconsciente',
- 'tinyplaceOrchestration.subconscious.subtitle': 'Chats internos de agentes',
- 'tinyplaceOrchestration.subconscious.preview':
- 'Coordinación de agentes en segundo plano y bucles de memoria.',
- 'tinyplaceOrchestration.session.subtitle': 'Sesión de app de TinyPlace',
- 'tinyplaceOrchestration.pairing.linkLabel': 'Vincular sesión',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': 'Pega el ID del agente de sesión',
- 'tinyplaceOrchestration.pairing.linkAction': 'Vincular',
- 'tinyplaceOrchestration.pairing.requests': 'Solicitudes de contacto',
- 'tinyplaceOrchestration.pairing.accept': 'Aceptar',
- 'tinyplaceOrchestration.pairing.decline': 'Rechazar',
- 'tinyplaceOrchestration.pairing.block': 'Bloquear',
- 'tinyplaceOrchestration.pairing.linked': 'Vinculada',
- 'tinyplaceOrchestration.pairing.pending': 'Pendiente',
- 'tinyplaceOrchestration.pairing.unlinked': 'Sin vincular',
- 'tinyplaceOrchestration.pairing.incoming': 'Entrantes',
- 'tinyplaceOrchestration.pairing.outgoing': 'Salientes',
- 'tinyplaceOrchestration.master.you': 'Tú',
- 'tinyplaceOrchestration.composer.placeholder': 'Mensaje a OpenHuman…',
- 'tinyplaceOrchestration.composer.send': 'Enviar',
- 'tinyplaceOrchestration.composer.sendFailed': 'No se pudo enviar el mensaje',
- 'tinyplaceOrchestration.steering.label': 'Dirección',
- 'tinyplaceOrchestration.relay.staging': 'Staging',
- 'tinyplaceOrchestration.relay.prod': 'Producción',
- 'tinyplaceOrchestration.identity.loading': 'Cargando identidad…',
- 'tinyplaceOrchestration.identity.noHandle': 'Aún sin @handle',
- 'tinyplaceOrchestration.identity.copy': 'Copiar',
- 'tinyplaceOrchestration.identity.copied': 'Copiado',
- 'tinyplaceOrchestration.identity.discoverable': 'Detectable',
- 'tinyplaceOrchestration.identity.undiscoverable': 'No detectable',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'Publica tu tarjeta de directorio y tu clave de cifrado para que otros agentes puedan escribirte.',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'Hacer detectable',
- 'tinyplaceOrchestration.identity.republish': 'Volver a publicar claves',
- 'tinyplaceOrchestration.identity.publishing': 'Publicando…',
- 'tinyplaceOrchestration.identity.publishFailed': 'Error al publicar: inténtalo de nuevo',
- 'tinyplaceOrchestration.identity.card': 'Tarjeta de directorio',
- 'tinyplaceOrchestration.identity.key': 'Clave de cifrado',
- 'tinyplaceOrchestration.identity.published': 'Publicado',
- 'tinyplaceOrchestration.identity.notPublished': 'No publicado',
- 'tinyplaceOrchestration.roster.instances': 'Instancias',
- 'tinyplaceOrchestration.roster.empty': 'Aún no hay instancias de agente',
- 'tinyplaceOrchestration.roster.other': 'Otros',
- 'tinyplaceOrchestration.status.running': 'En ejecución',
- 'tinyplaceOrchestration.status.idle': 'Inactivo',
- 'tinyplaceOrchestration.status.waitingApproval': 'Esperando aprobación',
- 'tinyplaceOrchestration.status.errored': 'Con error',
- 'tinyplaceOrchestration.status.stopped': 'Detenido',
- 'tinyplaceOrchestration.attention.title': 'Te necesita',
- 'tinyplaceOrchestration.attention.empty': 'Todo al día',
- 'tinyplaceOrchestration.attention.unread': 'Mensajes sin leer',
- 'tinyplaceOrchestration.attention.review': 'Revisar',
- 'tinyplaceOrchestration.attention.open': 'Abrir',
- 'tinyplaceOrchestration.attention.kind.approval': 'Aprobación',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'Necesita respuesta',
- 'tinyplaceOrchestration.attention.kind.unread': 'Sin leer',
'brain.empty':
'Tu cerebro está vacío por ahora: conecta una fuente para empezar a construir tu memoria.',
'brain.error': 'No se pudo cargar tu cerebro. Inténtalo de nuevo.',
@@ -2955,10 +2760,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'Ejecuta modelos en tu propia máquina usando Ollama. Privacidad total, requiere configuración.',
'backend.ramRecommended': 'Se recomienda 16 GB+ de RAM',
- 'tinyplaceOrchestration.subconsciousBadge': 'Subconsciente · dirección',
- 'tinyplaceOrchestration.steeringHeader.current': 'Directiva activa',
- 'tinyplaceOrchestration.steeringHeader.none': 'Sin directiva activa',
- 'tinyplaceOrchestration.steeringHeader.expires': 'caduca tras {n} ciclos',
'actionable.complete': 'Completar',
'actionable.dismiss': 'Descartar',
'actionable.snooze': 'Posponer',
@@ -5304,10 +5105,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'Aprobar automáticamente todas las acciones',
'settings.agentAccess.autoApproveAll.desc':
'Cuando está activado, el agente ejecutará todas las acciones elegibles sin pedir tu aprobación primero. Esto incluye escritura de archivos, comandos de shell, solicitudes de red y cualquier otro efecto secundario. Los bloqueos de seguridad estrictos, incluidos los directorios de credenciales y del sistema, siguen aplicándose, y las acciones con un origen no confiable o desconocido nunca se aprueban automáticamente.',
- 'settings.agentAccess.tinyplaceAutopilot.title': 'Agente autónomo de tiny.place',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'Deja que OpenHuman actúe en tiny.place por su cuenta. De forma programada, busca trabajo que valga la pena (primero las recompensas abiertas), hace lo que encaja con sus habilidades y actúa desde tu identidad. Funciona sin supervisión y puede gastar, así que mantenlo en devnet mientras pruebas. Desactivado por defecto.',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'Ejecutar automáticamente',
'settings.agentAccess.timeout.label': 'Tiempo de espera de la acción',
'settings.agentAccess.timeout.desc':
'Cuánto tiempo puede ejecutarse una sola herramienta o acción antes de cancelarse. Aumenta este valor si un modelo local grande se interrumpe antes de terminar su respuesta.',
@@ -6744,9 +6541,7 @@ const messages: TranslationMap = {
'notch.speaking': 'Hablando…',
'notch.transcribing': 'Transcribiendo…',
'notch.executing': 'Ejecutando…',
- 'memory.tab.orchestration': 'Orquestación',
- 'memory.tab.orchestrationDescription':
- 'Ejecuta flujos de trabajo con múltiples agentes: distribuye una pregunta entre agentes paralelos, contrasta sus hallazgos y observa cómo cada fase culmina en una única respuesta sintetizada.',
+
'orchestration.subtitle':
'Inicia un flujo de trabajo con múltiples agentes, observa el avance de sus fases y lee el resultado sintetizado.',
'orchestration.loading': 'Cargando flujos de trabajo…',
@@ -6896,10 +6691,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'Tu presupuesto de embeddings se agotó, así que el contenido nuevo ya no se añade a la memoria. Configura embeddings locales o añade tu propia clave de API para reanudar.',
'memoryBudget.cta': 'Configurar embeddings',
- 'tinyplaceSunset.title': 'Tiny Place se va de la app',
- 'tinyplaceSunset.message':
- 'Para seguir usando tiny.place, entra en tiny.place. Se eliminará de la app después del 31 de agosto de 2026.',
- 'tinyplaceSunset.cta': 'Abrir tiny.place',
'userErrors.scope.memory': 'Memoria',
// Code block chrome
diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts
index 76575ff95f..dc7626821a 100644
--- a/app/src/lib/i18n/fr.ts
+++ b/app/src/lib/i18n/fr.ts
@@ -327,128 +327,11 @@ const messages: TranslationMap = {
'nav.flows': 'Workflows',
'nav.workflowRuns': 'Exécutions de workflows',
'nav.workflowDiscoveries': 'Découvrir des workflows',
- 'nav.orchestration': 'Orchestration',
- 'orchestration.cloudUnreachable': 'Cerveau cloud injoignable: affichage de la vue mise en cache.',
- 'orchPage.subtitle': 'Coordonnez votre agent principal',
- 'orchPage.group.agent': 'Agent',
- 'orchPage.group.network': 'Réseau',
- 'orchPage.group.insights': 'Analyses',
- 'orchPage.overview.nav': 'Graphe des agents',
- 'orchPage.overview.desc':
- 'Une carte en direct de votre agent et des sous-agents qu’il coordonne.',
- 'orchPage.network.desc':
- 'Les agents pairs auxquels vous êtes connecté, la découverte et l’utilisation.',
+
'wallet.tabs.balance': 'Solde du portefeuille',
'wallet.tabs.recovery': 'Récupération',
'wallet.ariaLabel': 'Vues du portefeuille',
- 'orchPage.medulla.nav': 'Aperçu',
- 'orchPage.medulla.badge': 'Bientôt disponible',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': "Le modèle d'orchestration d'OpenHuman",
- 'orchPage.medulla.body':
- "Medulla est le LLM développé sur mesure par OpenHuman, conçu pour orchestrer des milliers d'agents à la fois, avec une fenêtre de contexte de 10 millions de tokens et une orchestration à coût radicalement bas.",
- 'orchPage.medulla.featAgents': "Des milliers d'agents",
- 'orchPage.medulla.featContext': 'Contexte de 10M de tokens',
- 'orchPage.medulla.featCost': 'Orchestration à faible coût',
- 'orchPage.medulla.subscriberTitle': 'Abonnés OpenHuman',
- 'orchPage.medulla.subscriberNote':
- 'Au lancement de Medulla, il sera exclusivement réservé aux abonnés OpenHuman.',
- 'orchPage.medulla.subscriberCta': 'Obtenir un abonnement',
- 'orchPage.medulla.discordTitle': 'Rejoignez le Discord',
- 'orchPage.medulla.earlyAccess':
- "Envie d'un accès en avant-première ? Rejoignez notre Discord et obtenez une invitation.",
- 'orchPage.medulla.cta': 'Rejoignez notre Discord',
- 'orchPage.demo.banner':
- "Voici un exemple de ce à quoi ressemblerait l'orchestration à grande échelle.",
- 'orchPage.demo.device': 'Appareil',
- 'orchPage.demo.taskRoute': 'Router la requête entrante',
- 'orchPage.demo.taskSummarize': 'Résumer la conversation',
- 'orchPage.demo.taskEnrich': 'Enrichir la fiche de contact',
- 'orchPage.demo.taskSchedule': 'Planifier un suivi',
- 'orchPage.demo.taskDraft': 'Rédiger une réponse',
- 'orchPage.demo.taskSync': 'Synchroniser la source de données',
- 'orchPage.demo.networkTitle': 'Agents pairs',
- 'orchPage.demo.networkSummary': '{peers} connectés · {sessions} sous-agents actifs',
- 'orchPage.demo.peer.connected': 'Connecté',
- 'orchPage.demo.peer.connecting': 'Connexion',
- 'orchPage.demo.peer.idle': 'Inactif',
- 'orchPage.demo.peerSessions': '{count} sous-agents',
- 'orchPage.demo.chat.user1': 'Coordonne la campagne de prospection sur tous mes canaux.',
- 'orchPage.demo.chat.assistant1':
- "C'est parti: je lance 120 agents sur 2 appareils pour exécuter la prospection, l'enrichissement et les suivis en parallèle.",
- 'orchPage.demo.chat.activity1': 'appareil 1 · 100 agents routant 1 284 conversations',
- 'orchPage.demo.chat.activity2': 'appareil 2 · 20 agents enrichissant 512 contacts',
- 'orchPage.demo.chat.activity3': 'rédaction de 640 réponses personnalisées',
- 'orchPage.demo.chat.assistant2':
- 'Terminé. 120 agents ont traité 1 796 conversations en 38 secondes.',
- 'orchPage.demo.chat.composerDisabled': "Le chat est disponible avec l'accès Medulla",
- 'orchPage.tasks.nav': 'Tâches',
- 'orchPage.tasks.subtitle': 'Le tableau de tâches global de l’orchestrateur',
- 'orchPage.tasks.colPending': 'En attente',
- 'orchPage.tasks.colActive': 'Actif',
- 'orchPage.tasks.colBlocked': 'Bloqué',
- 'orchPage.tasks.colCompleted': 'Terminé',
- 'orchPage.overview.core': 'Cœur de l’agent',
- 'orchPage.overview.empty': 'Aucun sous-agent à visualiser pour l’instant',
- 'orchPage.agent.nav': 'Chat',
- 'orchPage.agent.mainTab': 'Agent principal',
- 'orchPage.agent.consciousTab': 'Conscient',
- 'orchPage.agent.subconsciousTab': 'Subconscient',
- 'orchPage.agent.modeLabel': 'Esprit de l’agent',
- 'orchPage.agent.description': "Discutez avec l'agent principal et observez son subconscient",
- 'orchPage.agent.viewSession': 'Voir la session',
- 'orchPage.sessions.railTitle': 'Agents actifs',
- 'orchPage.sessions.empty': 'Aucun agent actif pour le moment',
- 'orchPage.sessions.statusConnected': 'Connecté',
- 'orchPage.sessions.statusDisconnected': 'Déconnecté',
- 'orchPage.sessions.statusWaiting': 'En attente de saisie',
- 'orchPage.session.runtime': 'Environnement d’exécution',
- 'orchPage.session.directory': 'Répertoire',
- 'orchPage.session.runningOn': 'En cours sur',
- 'orchPage.connections.nav': 'Connexions',
- 'orchPage.connections.title': 'Agents liés',
- 'orchPage.connections.description':
- 'Pairs avec lesquels votre agent se coordonne : développez-en un pour voir vos sessions avec lui',
- 'orchPage.connections.empty': 'Aucune connexion pour le moment.',
- 'orchPage.connections.emptyCta': 'Ajouter une connexion',
- 'orchPage.connections.statContacts': 'Connexions',
- 'orchPage.connections.statPending': 'En attente',
- 'orchPage.connections.statSessions': 'Séances',
- 'orchPage.connections.sessionCount': '{n} séances',
- 'orchPage.connections.noSessions': 'Aucune séance',
- 'orchPage.connections.messageCount': '{n} messages échangés',
- 'orchPage.connections.back': 'Connexions',
- 'orchPage.connections.replyPlaceholder': 'Répondre…',
- 'orchPage.connections.initTitle': 'Initialiser un agent ou une instance',
- 'orchPage.connections.initDesc':
- "Lancez un nouveau sous-agent pour travailler à vos côtés. Ouvrez le chat de l'agent et décrivez son rôle, son objectif et ses outils: OpenHuman provisionne une instance dédiée que vous pilotez d'ici.",
- 'orchPage.connections.initCta': 'Commencer dans le chat',
- 'orchPage.connections.status.needsYou': 'Requiert votre attention',
- 'orchPage.connections.status.running': 'En cours',
- 'orchPage.connections.status.idle': 'Inactif',
- 'orchPage.connections.status.done': 'Terminé',
- 'orchPage.connections.status.error': 'Erreur',
- 'orchPage.connections.pendingHint': "En attente d'acceptation",
- 'orchPage.discover.nav': 'Découvrir',
- 'orchPage.discover.linkAction': 'Ajouter',
- 'orchPage.discover.identityTitle': 'Votre visibilité',
- 'orchPage.discover.notDiscoverableGuide':
- "Enregistrez un @handle pour que d'autres agents puissent vous trouver et vous écrire.",
- 'orchPage.discover.linkTitle': 'Lier un nouvel agent',
- 'orchPage.discover.linkDescription':
- "Collez un ID d'agent pour envoyer une demande de connexion.",
- 'orchPage.discover.noRequests': 'Aucune demande entrante.',
- 'orchPage.usage.nav': 'Utilisation',
- 'orchPage.usage.connections': 'Connexions',
- 'orchPage.usage.balance': 'Solde de crédit',
- 'orchPage.usage.balanceHint': 'Promotionnel + recharge',
- 'orchPage.usage.cycleSpend': 'Dépenses du cycle',
- 'orchPage.usage.ofBudget': 'sur',
- 'orchPage.usage.inferenceCalls': 'Appels au modèle',
- 'orchPage.usage.integrationCalls': "Appels d'intégration",
- 'orchPage.usage.tokensSaved': 'Jetons économisés',
- 'orchPage.usage.saved': 'économisé',
- 'orchPage.usage.footnote': "L'utilisation reflète votre cycle de facturation actuel.",
+
'nav.wallet': 'Portefeuille',
'nav.avatarMenu.account': 'Compte',
'nav.avatarMenu.billing': 'Facturation',
@@ -476,86 +359,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': 'Une erreur s’est produite. Veuillez réessayer.',
'brain.tabs.sources': 'Sources',
'brain.tabs.sync': 'Synchronisation',
- 'brain.tabs.orchestration': 'Orchestration',
- 'tinyplaceOrchestration.title': 'Relais TinyPlace',
- 'tinyplaceOrchestration.subtitle': "Canaux d'agents épinglés et chats de sessions app",
- 'tinyplaceOrchestration.refresh': 'Actualiser',
- 'tinyplaceOrchestration.newInstance': 'Nouvelle instance',
- 'tinyplaceOrchestration.newInstanceSoon': 'Bientôt disponible',
- 'tinyplaceOrchestration.pinned': 'Épinglés',
- 'tinyplaceOrchestration.sessions': 'Sessions',
- 'tinyplaceOrchestration.contacts': 'Contacts',
- 'tinyplaceOrchestration.noContacts': 'Aucun contact pour le moment.',
- 'tinyplaceOrchestration.newSession': 'Nouvelle session',
- 'tinyplaceOrchestration.otherSessions': 'Autres sessions',
- 'tinyplaceOrchestration.loading': 'Chargement des chats TinyPlace…',
- 'tinyplaceOrchestration.paymentRequired': "L'accès à TinyPlace nécessite un paiement.",
- 'tinyplaceOrchestration.failedToLoad': 'Échec du chargement des chats TinyPlace',
- 'tinyplaceOrchestration.noSessions': "Aucune session d'app TinyPlace pour le moment.",
- 'tinyplaceOrchestration.noMessages': "Aucun message dans ce chat pour l'instant.",
- 'tinyplaceOrchestration.active': 'Active',
- 'tinyplaceOrchestration.inactive': 'Inactive',
- 'tinyplaceOrchestration.encryptedBody': 'Message TinyPlace chiffré',
- 'tinyplaceOrchestration.unknownSender': 'Expéditeur inconnu',
- 'tinyplaceOrchestration.master.title': 'Agent / humain',
- 'tinyplaceOrchestration.master.subtitle': 'Chat maître',
- 'tinyplaceOrchestration.master.preview': 'Coordination directe entre vous et OpenHuman.',
- 'tinyplaceOrchestration.subconscious.title': 'Subconscient',
- 'tinyplaceOrchestration.subconscious.subtitle': 'Chats internes des agents',
- 'tinyplaceOrchestration.subconscious.preview':
- 'Coordination des agents en arrière-plan et boucles de mémoire.',
- 'tinyplaceOrchestration.session.subtitle': "Session d'app TinyPlace",
- 'tinyplaceOrchestration.pairing.linkLabel': 'Lier une session',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': "Coller l'ID d'agent de session",
- 'tinyplaceOrchestration.pairing.linkAction': 'Lier',
- 'tinyplaceOrchestration.pairing.requests': 'Demandes de contact',
- 'tinyplaceOrchestration.pairing.accept': 'Accepter',
- 'tinyplaceOrchestration.pairing.decline': 'Refuser',
- 'tinyplaceOrchestration.pairing.block': 'Bloquer',
- 'tinyplaceOrchestration.pairing.linked': 'Liée',
- 'tinyplaceOrchestration.pairing.pending': 'En attente',
- 'tinyplaceOrchestration.pairing.unlinked': 'Non liée',
- 'tinyplaceOrchestration.pairing.incoming': 'Entrantes',
- 'tinyplaceOrchestration.pairing.outgoing': 'Sortantes',
- 'tinyplaceOrchestration.master.you': 'Vous',
- 'tinyplaceOrchestration.composer.placeholder': 'Message à OpenHuman…',
- 'tinyplaceOrchestration.composer.send': 'Envoyer',
- 'tinyplaceOrchestration.composer.sendFailed': 'Échec de l’envoi du message',
- 'tinyplaceOrchestration.steering.label': 'Pilotage',
- 'tinyplaceOrchestration.relay.staging': 'Staging',
- 'tinyplaceOrchestration.relay.prod': 'Production',
- 'tinyplaceOrchestration.identity.loading': 'Chargement de l’identité…',
- 'tinyplaceOrchestration.identity.noHandle': 'Pas encore de @handle',
- 'tinyplaceOrchestration.identity.copy': 'Copier',
- 'tinyplaceOrchestration.identity.copied': 'Copié',
- 'tinyplaceOrchestration.identity.discoverable': 'Découvrable',
- 'tinyplaceOrchestration.identity.undiscoverable': 'Non découvrable',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'Publie ta fiche d’annuaire et ta clé de chiffrement pour que les pairs puissent te contacter.',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'Rendre découvrable',
- 'tinyplaceOrchestration.identity.republish': 'Republier les clés',
- 'tinyplaceOrchestration.identity.publishing': 'Publication…',
- 'tinyplaceOrchestration.identity.publishFailed': 'Échec de la publication: réessaie',
- 'tinyplaceOrchestration.identity.card': 'Fiche d’annuaire',
- 'tinyplaceOrchestration.identity.key': 'Clé de chiffrement',
- 'tinyplaceOrchestration.identity.published': 'Publié',
- 'tinyplaceOrchestration.identity.notPublished': 'Non publié',
- 'tinyplaceOrchestration.roster.instances': 'Instances',
- 'tinyplaceOrchestration.roster.empty': 'Aucune instance d’agent',
- 'tinyplaceOrchestration.roster.other': 'Autre',
- 'tinyplaceOrchestration.status.running': 'En cours',
- 'tinyplaceOrchestration.status.idle': 'Inactif',
- 'tinyplaceOrchestration.status.waitingApproval': 'En attente d’approbation',
- 'tinyplaceOrchestration.status.errored': 'En erreur',
- 'tinyplaceOrchestration.status.stopped': 'Arrêté',
- 'tinyplaceOrchestration.attention.title': 'Requiert votre attention',
- 'tinyplaceOrchestration.attention.empty': 'Vous êtes à jour',
- 'tinyplaceOrchestration.attention.unread': 'Messages non lus',
- 'tinyplaceOrchestration.attention.review': 'Examiner',
- 'tinyplaceOrchestration.attention.open': 'Ouvrir',
- 'tinyplaceOrchestration.attention.kind.approval': 'Approbation',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'Réponse requise',
- 'tinyplaceOrchestration.attention.kind.unread': 'Non lu',
'brain.empty':
'Votre cerveau est vide pour l’instant: connectez une source pour commencer à constituer votre mémoire.',
'brain.error': 'Impossible de charger votre cerveau. Veuillez réessayer.',
@@ -2977,10 +2780,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'Fais tourner les modèles sur ta propre machine avec Ollama. Confidentialité totale, configuration requise.',
'backend.ramRecommended': '16 Go+ de RAM recommandés',
- 'tinyplaceOrchestration.subconsciousBadge': 'Subconscient · pilotage',
- 'tinyplaceOrchestration.steeringHeader.current': 'Directive active',
- 'tinyplaceOrchestration.steeringHeader.none': 'Aucune directive active',
- 'tinyplaceOrchestration.steeringHeader.expires': 'expire après {n} cycles',
'actionable.complete': 'Terminer',
'actionable.dismiss': 'Ignorer',
'actionable.snooze': 'Reporter',
@@ -5331,10 +5130,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'Approuver automatiquement toutes les actions',
'settings.agentAccess.autoApproveAll.desc':
"Une fois activé, l'agent exécutera toutes les actions sans demander votre approbation au préalable. Cela inclut l'écriture de fichiers, les commandes shell, les requêtes réseau et tout autre effet secondaire. Les blocages de sécurité stricts (répertoires d'identifiants, chemins internes de l'espace de travail) continuent de s'appliquer.",
- 'settings.agentAccess.tinyplaceAutopilot.title': 'Agent tiny.place autonome',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'Laissez OpenHuman agir seul sur tiny.place. De façon planifiée, il cherche du travail intéressant (les primes ouvertes d’abord), accomplit les tâches adaptées à ses compétences et agit avec votre identité. Il fonctionne sans surveillance et peut dépenser ; gardez-le sur devnet pendant vos tests. Désactivé par défaut.',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'Exécuter automatiquement',
'settings.agentAccess.timeout.label': "Délai d'expiration de l'action",
'settings.agentAccess.timeout.desc':
"Durée pendant laquelle un seul outil ou une seule action peut s'exécuter avant d'être annulé. Augmentez cette valeur si un grand modèle local est interrompu avant d'avoir terminé sa réponse.",
@@ -6772,9 +6567,7 @@ const messages: TranslationMap = {
'notch.speaking': 'Je parle…',
'notch.transcribing': 'Transcription…',
'notch.executing': "J'exécute…",
- 'memory.tab.orchestration': 'Orchestration',
- 'memory.tab.orchestrationDescription':
- 'Exécutez des workflows multi-agents: répartissez une question entre des agents parallèles, recoupez leurs résultats et regardez chaque phase aboutir à une réponse synthétisée unique.',
+
'orchestration.subtitle':
'Démarrez un workflow multi-agents, suivez la progression de ses phases et lisez le résultat synthétisé.',
'orchestration.loading': 'Chargement des workflows…',
@@ -6923,10 +6716,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
"Votre budget d'embeddings est épuisé, les nouveaux contenus ne sont donc plus ajoutés à la mémoire. Configurez des embeddings locaux ou ajoutez votre propre clé API pour reprendre.",
'memoryBudget.cta': 'Configurer les embeddings',
- 'tinyplaceSunset.title': 'Tiny Place quitte l’application',
- 'tinyplaceSunset.message':
- 'Pour continuer à utiliser tiny.place, rendez-vous sur tiny.place. Il sera retiré de l’application après le 31 août 2026.',
- 'tinyplaceSunset.cta': 'Ouvrir tiny.place',
'userErrors.scope.memory': 'Mémoire',
// Code block chrome
diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts
index 3a2d8296c9..013e2991e1 100644
--- a/app/src/lib/i18n/hi.ts
+++ b/app/src/lib/i18n/hi.ts
@@ -314,124 +314,11 @@ const messages: TranslationMap = {
'nav.flows': 'वर्कफ़्लो',
'nav.workflowRuns': 'वर्कफ़्लो रन',
'nav.workflowDiscoveries': 'वर्कफ़्लो खोजें',
- 'nav.orchestration': 'ऑर्केस्ट्रेशन',
- 'orchestration.cloudUnreachable':
- 'क्लाउड ब्रेन तक नहीं पहुँचा जा सका: कैश किया गया दृश्य दिखाया जा रहा है।',
- 'orchPage.subtitle': 'अपने मुख्य एजेंट का समन्वय करें',
- 'orchPage.group.agent': 'एजेंट',
- 'orchPage.group.network': 'नेटवर्क',
- 'orchPage.group.insights': 'अंतर्दृष्टि',
- 'orchPage.overview.nav': 'एजेंट ग्राफ़',
- 'orchPage.overview.desc': 'आपके एजेंट और उसके द्वारा समन्वित उप-एजेंटों का एक लाइव मानचित्र।',
- 'orchPage.network.desc': 'वे सहकर्मी एजेंट जिनसे आप जुड़े हैं, खोज और उपयोग।',
+
'wallet.tabs.balance': 'वॉलेट शेष',
'wallet.tabs.recovery': 'पुनर्प्राप्ति',
'wallet.ariaLabel': 'वॉलेट दृश्य',
- 'orchPage.medulla.nav': 'अवलोकन',
- 'orchPage.medulla.badge': 'जल्द आ रहा है',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'OpenHuman का ऑर्केस्ट्रेशन मॉडल',
- 'orchPage.medulla.body':
- 'Medulla, OpenHuman का स्वयं-निर्मित LLM है, जिसे एक साथ हज़ारों एजेंट्स को ऑर्केस्ट्रेट करने के लिए तैयार किया गया है, 10-मिलियन-टोकन कॉन्टेक्स्ट विंडो और बेहद कम लागत वाली ऑर्केस्ट्रेशन के साथ।',
- 'orchPage.medulla.featAgents': 'हज़ारों एजेंट',
- 'orchPage.medulla.featContext': '10M-टोकन कॉन्टेक्स्ट',
- 'orchPage.medulla.featCost': 'कम लागत वाली ऑर्केस्ट्रेशन',
- 'orchPage.medulla.subscriberTitle': 'OpenHuman सब्सक्राइबर',
- 'orchPage.medulla.subscriberNote':
- 'Medulla के लाइव होने पर यह केवल OpenHuman सब्सक्राइबर के लिए विशेष रूप से उपलब्ध होगा।',
- 'orchPage.medulla.subscriberCta': 'सब्सक्रिप्शन लें',
- 'orchPage.medulla.discordTitle': 'Discord से जुड़ें',
- 'orchPage.medulla.earlyAccess':
- 'पहले पाना चाहते हैं? हमारे Discord से जुड़ें और अर्ली-एक्सेस निमंत्रण प्राप्त करें।',
- 'orchPage.medulla.cta': 'हमारे Discord से जुड़ें',
- 'orchPage.demo.banner': 'यह एक उदाहरण है कि बड़े पैमाने पर ऑर्केस्ट्रेशन कैसा दिखेगा।',
- 'orchPage.demo.device': 'डिवाइस',
- 'orchPage.demo.taskRoute': 'इनकमिंग अनुरोध रूट करें',
- 'orchPage.demo.taskSummarize': 'बातचीत का सारांश बनाएं',
- 'orchPage.demo.taskEnrich': 'संपर्क रिकॉर्ड समृद्ध करें',
- 'orchPage.demo.taskSchedule': 'फ़ॉलो-अप शेड्यूल करें',
- 'orchPage.demo.taskDraft': 'उत्तर का मसौदा तैयार करें',
- 'orchPage.demo.taskSync': 'डेटा स्रोत सिंक करें',
- 'orchPage.demo.networkTitle': 'पीयर एजेंट',
- 'orchPage.demo.networkSummary': '{peers} कनेक्टेड · {sessions} सक्रिय सब-एजेंट',
- 'orchPage.demo.peer.connected': 'कनेक्टेड',
- 'orchPage.demo.peer.connecting': 'कनेक्ट हो रहा है',
- 'orchPage.demo.peer.idle': 'निष्क्रिय',
- 'orchPage.demo.peerSessions': '{count} सब-एजेंट',
- 'orchPage.demo.chat.user1': 'मेरे सभी चैनलों पर आउटरीच अभियान का समन्वय करें।',
- 'orchPage.demo.chat.assistant1':
- 'शुरू कर दिया: आउटरीच, संवर्धन और फ़ॉलो-अप समानांतर में चलाने के लिए 2 डिवाइस पर 120 एजेंट शुरू किए जा रहे हैं।',
- 'orchPage.demo.chat.activity1': 'डिवाइस 1 · 100 एजेंट 1,284 बातचीत रूट कर रहे हैं',
- 'orchPage.demo.chat.activity2': 'डिवाइस 2 · 20 एजेंट 512 संपर्क समृद्ध कर रहे हैं',
- 'orchPage.demo.chat.activity3': '640 वैयक्तिकृत उत्तरों का मसौदा तैयार किया जा रहा है',
- 'orchPage.demo.chat.assistant2': 'पूर्ण। 120 एजेंट ने 38 सेकंड में 1,796 बातचीत प्रोसेस कीं।',
- 'orchPage.demo.chat.composerDisabled': 'Medulla एक्सेस के साथ चैट उपलब्ध है',
- 'orchPage.tasks.nav': 'कार्य',
- 'orchPage.tasks.subtitle': 'ऑर्केस्ट्रेटर का वैश्विक कार्य बोर्ड',
- 'orchPage.tasks.colPending': 'लंबित',
- 'orchPage.tasks.colActive': 'सक्रिय',
- 'orchPage.tasks.colBlocked': 'अवरुद्ध',
- 'orchPage.tasks.colCompleted': 'पूर्ण',
- 'orchPage.overview.core': 'एजेंट कोर',
- 'orchPage.overview.empty': 'विज़ुअलाइज़ करने के लिए अभी कोई सब-एजेंट नहीं',
- 'orchPage.agent.nav': 'चैट',
- 'orchPage.agent.mainTab': 'मुख्य एजेंट',
- 'orchPage.agent.consciousTab': 'चेतन',
- 'orchPage.agent.subconsciousTab': 'अवचेतन',
- 'orchPage.agent.modeLabel': 'एजेंट का मन',
- 'orchPage.agent.description': 'मुख्य एजेंट से चैट करें और उसका अवचेतन देखें',
- 'orchPage.agent.viewSession': 'सत्र देखें',
- 'orchPage.sessions.railTitle': 'सक्रिय एजेंट',
- 'orchPage.sessions.empty': 'अभी तक कोई सक्रिय एजेंट नहीं',
- 'orchPage.sessions.statusConnected': 'कनेक्टेड',
- 'orchPage.sessions.statusDisconnected': 'डिस्कनेक्ट किया गया',
- 'orchPage.sessions.statusWaiting': 'इनपुट की प्रतीक्षा में',
- 'orchPage.session.runtime': 'रनटाइम',
- 'orchPage.session.directory': 'निर्देशिका',
- 'orchPage.session.runningOn': 'यहाँ चल रहा',
- 'orchPage.connections.nav': 'कनेक्शन',
- 'orchPage.connections.title': 'लिंक किए गए एजेंट',
- 'orchPage.connections.description':
- 'वे साथी जिनके साथ आपका एजेंट समन्वय करता है: किसी एक को विस्तृत करके उनके साथ अपने सत्र देखें',
- 'orchPage.connections.empty': 'अभी तक कोई कनेक्शन नहीं।',
- 'orchPage.connections.emptyCta': 'कनेक्शन जोड़ें',
- 'orchPage.connections.statContacts': 'कनेक्शन',
- 'orchPage.connections.statPending': 'लंबित',
- 'orchPage.connections.statSessions': 'सत्र',
- 'orchPage.connections.sessionCount': '{n} सत्र',
- 'orchPage.connections.noSessions': 'कोई सत्र नहीं',
- 'orchPage.connections.messageCount': '{n} संदेश',
- 'orchPage.connections.back': 'कनेक्शन',
- 'orchPage.connections.replyPlaceholder': 'उत्तर दें…',
- 'orchPage.connections.initTitle': 'एजेंट या इंस्टेंस आरंभ करें',
- 'orchPage.connections.initDesc':
- 'अपने साथ काम करने के लिए एक नया सब-एजेंट शुरू करें। एजेंट चैट खोलें और उसकी भूमिका, लक्ष्य और उपकरण बताएं: OpenHuman एक समर्पित इंस्टेंस तैयार करता है जिसे आप यहीं से नियंत्रित कर सकते हैं।',
- 'orchPage.connections.initCta': 'चैट में शुरू करें',
- 'orchPage.connections.status.needsYou': 'आपकी ज़रूरत है',
- 'orchPage.connections.status.running': 'चल रहा है',
- 'orchPage.connections.status.idle': 'निष्क्रिय',
- 'orchPage.connections.status.done': 'पूर्ण',
- 'orchPage.connections.status.error': 'त्रुटि',
- 'orchPage.connections.pendingHint': 'स्वीकृति की प्रतीक्षा में',
- 'orchPage.discover.nav': 'खोजें',
- 'orchPage.discover.linkAction': 'जोड़ें',
- 'orchPage.discover.identityTitle': 'आपकी खोज-योग्यता',
- 'orchPage.discover.notDiscoverableGuide':
- 'एक @handle पंजीकृत करें ताकि अन्य एजेंट आपको ढूंढ़ और संदेश भेज सकें।',
- 'orchPage.discover.linkTitle': 'नया एजेंट लिंक करें',
- 'orchPage.discover.linkDescription': 'कनेक्शन अनुरोध भेजने के लिए एजेंट आईडी पेस्ट करें।',
- 'orchPage.discover.noRequests': 'कोई आने वाला अनुरोध नहीं।',
- 'orchPage.usage.nav': 'उपयोग',
- 'orchPage.usage.connections': 'कनेक्शन',
- 'orchPage.usage.balance': 'क्रेडिट शेष',
- 'orchPage.usage.balanceHint': 'प्रचार + टॉप-अप',
- 'orchPage.usage.cycleSpend': 'चक्र व्यय',
- 'orchPage.usage.ofBudget': 'में से',
- 'orchPage.usage.inferenceCalls': 'मॉडल कॉल',
- 'orchPage.usage.integrationCalls': 'एकीकरण कॉल',
- 'orchPage.usage.tokensSaved': 'बचाए गए टोकन',
- 'orchPage.usage.saved': 'बचाया',
- 'orchPage.usage.footnote': 'उपयोग आपके वर्तमान बिलिंग चक्र को दर्शाता है।',
+
'nav.wallet': 'वॉलेट',
'nav.avatarMenu.account': 'खाता',
'nav.avatarMenu.billing': 'बिलिंग',
@@ -459,85 +346,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': 'कुछ गलत हो गया। कृपया पुनः प्रयास करें।',
'brain.tabs.sources': 'स्रोत',
'brain.tabs.sync': 'सिंक',
- 'brain.tabs.orchestration': 'ऑर्केस्ट्रेशन',
- 'tinyplaceOrchestration.title': 'TinyPlace रिले',
- 'tinyplaceOrchestration.subtitle': 'पिन किए गए एजेंट चैनल और ऐप-सत्र चैट',
- 'tinyplaceOrchestration.refresh': 'रीफ़्रेश',
- 'tinyplaceOrchestration.newInstance': 'नया इंस्टेंस',
- 'tinyplaceOrchestration.newInstanceSoon': 'जल्द आ रहा है',
- 'tinyplaceOrchestration.pinned': 'पिन किए गए',
- 'tinyplaceOrchestration.sessions': 'सत्र',
- 'tinyplaceOrchestration.contacts': 'संपर्क',
- 'tinyplaceOrchestration.noContacts': 'अभी तक कोई संपर्क नहीं।',
- 'tinyplaceOrchestration.newSession': 'नया सत्र',
- 'tinyplaceOrchestration.otherSessions': 'अन्य सत्र',
- 'tinyplaceOrchestration.loading': 'TinyPlace चैट लोड हो रहे हैं…',
- 'tinyplaceOrchestration.paymentRequired': 'TinyPlace एक्सेस के लिए भुगतान आवश्यक है।',
- 'tinyplaceOrchestration.failedToLoad': 'TinyPlace चैट लोड नहीं हो सके',
- 'tinyplaceOrchestration.noSessions': 'अभी कोई TinyPlace ऐप सत्र नहीं है।',
- 'tinyplaceOrchestration.noMessages': 'इस चैट में अभी कोई संदेश नहीं है।',
- 'tinyplaceOrchestration.active': 'सक्रिय',
- 'tinyplaceOrchestration.inactive': 'निष्क्रिय',
- 'tinyplaceOrchestration.encryptedBody': 'एन्क्रिप्टेड TinyPlace संदेश',
- 'tinyplaceOrchestration.unknownSender': 'अज्ञात प्रेषक',
- 'tinyplaceOrchestration.master.title': 'एजेंट / मानव',
- 'tinyplaceOrchestration.master.subtitle': 'मास्टर चैट',
- 'tinyplaceOrchestration.master.preview': 'आप और OpenHuman के बीच सीधा समन्वय।',
- 'tinyplaceOrchestration.subconscious.title': 'अवचेतन',
- 'tinyplaceOrchestration.subconscious.subtitle': 'आंतरिक एजेंट चैट',
- 'tinyplaceOrchestration.subconscious.preview': 'पृष्ठभूमि एजेंट समन्वय और मेमोरी लूप।',
- 'tinyplaceOrchestration.session.subtitle': 'TinyPlace ऐप सत्र',
- 'tinyplaceOrchestration.pairing.linkLabel': 'सत्र लिंक करें',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': 'सत्र एजेंट ID पेस्ट करें',
- 'tinyplaceOrchestration.pairing.linkAction': 'लिंक',
- 'tinyplaceOrchestration.pairing.requests': 'संपर्क अनुरोध',
- 'tinyplaceOrchestration.pairing.accept': 'स्वीकारें',
- 'tinyplaceOrchestration.pairing.decline': 'अस्वीकारें',
- 'tinyplaceOrchestration.pairing.block': 'ब्लॉक',
- 'tinyplaceOrchestration.pairing.linked': 'लिंक किया',
- 'tinyplaceOrchestration.pairing.pending': 'लंबित',
- 'tinyplaceOrchestration.pairing.unlinked': 'लिंक नहीं',
- 'tinyplaceOrchestration.pairing.incoming': 'आने वाले',
- 'tinyplaceOrchestration.pairing.outgoing': 'जाने वाले',
- 'tinyplaceOrchestration.master.you': 'आप',
- 'tinyplaceOrchestration.composer.placeholder': 'OpenHuman को संदेश भेजें…',
- 'tinyplaceOrchestration.composer.send': 'भेजें',
- 'tinyplaceOrchestration.composer.sendFailed': 'संदेश भेजने में विफल',
- 'tinyplaceOrchestration.steering.label': 'मार्गदर्शन',
- 'tinyplaceOrchestration.relay.staging': 'स्टेजिंग',
- 'tinyplaceOrchestration.relay.prod': 'प्रोडक्शन',
- 'tinyplaceOrchestration.identity.loading': 'पहचान लोड हो रही है…',
- 'tinyplaceOrchestration.identity.noHandle': 'अभी तक कोई @handle नहीं',
- 'tinyplaceOrchestration.identity.copy': 'कॉपी करें',
- 'tinyplaceOrchestration.identity.copied': 'कॉपी हो गया',
- 'tinyplaceOrchestration.identity.discoverable': 'खोजने योग्य',
- 'tinyplaceOrchestration.identity.undiscoverable': 'खोजने योग्य नहीं',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'अपना डायरेक्टरी कार्ड और एन्क्रिप्शन कुंजी प्रकाशित करें ताकि अन्य एजेंट आपको संदेश भेज सकें।',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'खोजने योग्य बनाएँ',
- 'tinyplaceOrchestration.identity.republish': 'कुंजियाँ पुनः प्रकाशित करें',
- 'tinyplaceOrchestration.identity.publishing': 'प्रकाशित हो रहा है…',
- 'tinyplaceOrchestration.identity.publishFailed': 'प्रकाशन विफल: पुनः प्रयास करें',
- 'tinyplaceOrchestration.identity.card': 'डायरेक्टरी कार्ड',
- 'tinyplaceOrchestration.identity.key': 'एन्क्रिप्शन कुंजी',
- 'tinyplaceOrchestration.identity.published': 'प्रकाशित',
- 'tinyplaceOrchestration.identity.notPublished': 'अप्रकाशित',
- 'tinyplaceOrchestration.roster.instances': 'इंस्टेंस',
- 'tinyplaceOrchestration.roster.empty': 'अभी तक कोई एजेंट इंस्टेंस नहीं',
- 'tinyplaceOrchestration.roster.other': 'अन्य',
- 'tinyplaceOrchestration.status.running': 'चल रहा है',
- 'tinyplaceOrchestration.status.idle': 'निष्क्रिय',
- 'tinyplaceOrchestration.status.waitingApproval': 'अनुमोदन की प्रतीक्षा में',
- 'tinyplaceOrchestration.status.errored': 'त्रुटि',
- 'tinyplaceOrchestration.status.stopped': 'रुका हुआ',
- 'tinyplaceOrchestration.attention.title': 'आपकी ज़रूरत है',
- 'tinyplaceOrchestration.attention.empty': 'सब कुछ पूरा हो गया',
- 'tinyplaceOrchestration.attention.unread': 'अपठित संदेश',
- 'tinyplaceOrchestration.attention.review': 'समीक्षा करें',
- 'tinyplaceOrchestration.attention.open': 'खोलें',
- 'tinyplaceOrchestration.attention.kind.approval': 'अनुमोदन',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'इनपुट चाहिए',
- 'tinyplaceOrchestration.attention.kind.unread': 'अपठित',
'brain.empty': 'आपका ब्रेन अभी खाली है: मेमोरी बनाना शुरू करने के लिए कोई स्रोत कनेक्ट करें।',
'brain.error': 'आपका ब्रेन लोड नहीं हो सका। कृपया फिर से प्रयास करें।',
'common.cancel': 'रद्द करें',
@@ -2896,10 +2704,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'Ollama का इस्तेमाल करके अपनी मशीन पर मॉडल चलाएं। पूरी प्राइवेसी, सेटअप ज़रूरी।',
'backend.ramRecommended': '16GB+ RAM सुझावित',
- 'tinyplaceOrchestration.subconsciousBadge': 'अवचेतन · स्टीयरिंग',
- 'tinyplaceOrchestration.steeringHeader.current': 'सक्रिय निर्देश',
- 'tinyplaceOrchestration.steeringHeader.none': 'कोई सक्रिय निर्देश नहीं',
- 'tinyplaceOrchestration.steeringHeader.expires': '{n} चक्रों के बाद समाप्त',
'actionable.complete': 'पूरा करें',
'actionable.dismiss': 'हटाएं',
'actionable.snooze': 'स्नूज़ करें',
@@ -5210,10 +5014,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'सभी कार्रवाइयों को स्वतः स्वीकृत करें',
'settings.agentAccess.autoApproveAll.desc':
'सक्षम होने पर, एजेंट आपकी अनुमति मांगे बिना सभी कार्रवाइयां निष्पादित करेगा। इसमें फ़ाइल लेखन, शेल कमांड, नेटवर्क अनुरोध और अन्य कोई भी दुष्प्रभाव शामिल हैं। कठोर सुरक्षा अवरोध (क्रेडेंशियल डायरेक्टरी, वर्कस्पेस-आंतरिक पथ) अब भी लागू रहते हैं।',
- 'settings.agentAccess.tinyplaceAutopilot.title': 'स्वायत्त tiny.place एजेंट',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'OpenHuman को tiny.place पर स्वयं कार्य करने दें। यह निर्धारित समय पर सार्थक काम ढूँढता है (पहले खुली बाउंटी), अपनी क्षमताओं के अनुरूप काम करता है और आपकी पहचान से कार्य करता है। यह बिना निगरानी के चलता है और खर्च कर सकता है, इसलिए परीक्षण के दौरान इसे devnet पर रखें। डिफ़ॉल्ट रूप से बंद।',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'स्वतः चलाएँ',
'settings.agentAccess.timeout.label': 'क्रिया टाइमआउट',
'settings.agentAccess.timeout.desc':
'किसी एकल टूल या क्रिया को रद्द होने से पहले कितनी देर चलने दिया जाए। यदि कोई बड़ा लोकल मॉडल अपना उत्तर पूरा करने से पहले रुक जाता है तो इसे बढ़ाएँ।',
@@ -6602,9 +6402,7 @@ const messages: TranslationMap = {
'notch.speaking': 'बोल रहा हूं…',
'notch.transcribing': 'ट्रांसक्राइब कर रहा हूं…',
'notch.executing': 'चला रहा हूं…',
- 'memory.tab.orchestration': 'ऑर्केस्ट्रेशन',
- 'memory.tab.orchestrationDescription':
- 'बहु-एजेंट वर्कफ़्लो चलाएं: एक प्रश्न को समानांतर एजेंटों में बाँटें, उनके निष्कर्षों की परस्पर जाँच करें, और देखें कि हर चरण एक संयोजित उत्तर में पूरा होता है।',
+
'orchestration.subtitle':
'बहु-एजेंट वर्कफ़्लो शुरू करें, उसके चरणों की प्रगति देखें, और संयोजित परिणाम पढ़ें।',
'orchestration.loading': 'वर्कफ़्लो लोड हो रहे हैं…',
@@ -6750,10 +6548,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'आपका एम्बेडिंग बजट खत्म हो गया है, इसलिए नई सामग्री अब मेमोरी में नहीं जुड़ रही। दोबारा शुरू करने के लिए लोकल एम्बेडिंग सेट करें या अपनी API कुंजी जोड़ें।',
'memoryBudget.cta': 'एम्बेडिंग सेट करें',
- 'tinyplaceSunset.title': 'Tiny Place ऐप से बाहर जा रहा है',
- 'tinyplaceSunset.message':
- 'tiny.place का उपयोग जारी रखने के लिए tiny.place पर जाएं। 31 अगस्त 2026 के बाद इसे ऐप से हटा दिया जाएगा।',
- 'tinyplaceSunset.cta': 'tiny.place खोलें',
'userErrors.scope.memory': 'मेमोरी',
// Code block chrome
diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts
index 749ea022f1..602a2e3877 100644
--- a/app/src/lib/i18n/id.ts
+++ b/app/src/lib/i18n/id.ts
@@ -318,124 +318,11 @@ const messages: TranslationMap = {
'nav.flows': 'Alur Kerja',
'nav.workflowRuns': 'Eksekusi alur kerja',
'nav.workflowDiscoveries': 'Temukan alur kerja',
- 'nav.orchestration': 'Orkestrasi',
- 'orchestration.cloudUnreachable':
- 'Otak cloud tidak dapat dijangkau: menampilkan tampilan yang tersimpan.',
- 'orchPage.subtitle': 'Koordinasikan agen utama Anda',
- 'orchPage.group.agent': 'Agen',
- 'orchPage.group.network': 'Jaringan',
- 'orchPage.group.insights': 'Wawasan',
- 'orchPage.overview.nav': 'Grafik agen',
- 'orchPage.overview.desc': 'Peta langsung agen Anda dan sub-agen yang dikoordinasikannya.',
- 'orchPage.network.desc': 'Agen rekan yang terhubung dengan Anda, penemuan, dan penggunaan.',
+
'wallet.tabs.balance': 'Saldo dompet',
'wallet.tabs.recovery': 'Pemulihan',
'wallet.ariaLabel': 'Tampilan dompet',
- 'orchPage.medulla.nav': 'Ikhtisar',
- 'orchPage.medulla.badge': 'Segera hadir',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'Model orkestrasi OpenHuman',
- 'orchPage.medulla.body':
- 'Medulla adalah LLM buatan OpenHuman yang dirancang untuk mengorkestrasi ribuan agen sekaligus, dengan jendela konteks 10 juta token dan orkestrasi berbiaya sangat rendah.',
- 'orchPage.medulla.featAgents': 'Ribuan agen',
- 'orchPage.medulla.featContext': 'Konteks 10M token',
- 'orchPage.medulla.featCost': 'Orkestrasi berbiaya rendah',
- 'orchPage.medulla.subscriberTitle': 'Pelanggan OpenHuman',
- 'orchPage.medulla.subscriberNote':
- 'Saat Medulla diluncurkan, akan eksklusif untuk pelanggan OpenHuman.',
- 'orchPage.medulla.subscriberCta': 'Dapatkan langganan',
- 'orchPage.medulla.discordTitle': 'Gabung Discord',
- 'orchPage.medulla.earlyAccess':
- 'Ingin lebih dulu? Gabung Discord kami dan dapatkan undangan akses awal.',
- 'orchPage.medulla.cta': 'Gabung Discord kami',
- 'orchPage.demo.banner': 'Ini adalah contoh bagaimana orkestrasi akan terlihat dalam skala besar.',
- 'orchPage.demo.device': 'Perangkat',
- 'orchPage.demo.taskRoute': 'Arahkan permintaan masuk',
- 'orchPage.demo.taskSummarize': 'Ringkas percakapan',
- 'orchPage.demo.taskEnrich': 'Perkaya catatan kontak',
- 'orchPage.demo.taskSchedule': 'Jadwalkan tindak lanjut',
- 'orchPage.demo.taskDraft': 'Susun balasan',
- 'orchPage.demo.taskSync': 'Sinkronkan sumber data',
- 'orchPage.demo.networkTitle': 'Agen rekan',
- 'orchPage.demo.networkSummary': '{peers} terhubung · {sessions} sub-agen aktif',
- 'orchPage.demo.peer.connected': 'Terhubung',
- 'orchPage.demo.peer.connecting': 'Menghubungkan',
- 'orchPage.demo.peer.idle': 'Menganggur',
- 'orchPage.demo.peerSessions': '{count} sub-agen',
- 'orchPage.demo.chat.user1': 'Koordinasikan kampanye penjangkauan di semua saluran saya.',
- 'orchPage.demo.chat.assistant1':
- 'Siap: menjalankan 120 agen di 2 perangkat untuk menjalankan penjangkauan, pengayaan, dan tindak lanjut secara paralel.',
- 'orchPage.demo.chat.activity1': 'perangkat 1 · 100 agen mengarahkan 1.284 percakapan',
- 'orchPage.demo.chat.activity2': 'perangkat 2 · 20 agen memperkaya 512 kontak',
- 'orchPage.demo.chat.activity3': 'menyusun 640 balasan yang dipersonalisasi',
- 'orchPage.demo.chat.assistant2': 'Selesai. 120 agen memproses 1.796 percakapan dalam 38 detik.',
- 'orchPage.demo.chat.composerDisabled': 'Obrolan tersedia dengan akses Medulla',
- 'orchPage.tasks.nav': 'Tugas',
- 'orchPage.tasks.subtitle': 'Papan tugas global orkestrator',
- 'orchPage.tasks.colPending': 'Tertunda',
- 'orchPage.tasks.colActive': 'Aktif',
- 'orchPage.tasks.colBlocked': 'Terblokir',
- 'orchPage.tasks.colCompleted': 'Selesai',
- 'orchPage.overview.core': 'Inti agen',
- 'orchPage.overview.empty': 'Belum ada sub-agen untuk divisualisasikan',
- 'orchPage.agent.nav': 'Obrolan',
- 'orchPage.agent.mainTab': 'Agen utama',
- 'orchPage.agent.consciousTab': 'Sadar',
- 'orchPage.agent.subconsciousTab': 'Bawah sadar',
- 'orchPage.agent.modeLabel': 'Pikiran agen',
- 'orchPage.agent.description': 'Mengobrol dengan agen utama dan amati bawah sadarnya',
- 'orchPage.agent.viewSession': 'Lihat sesi',
- 'orchPage.sessions.railTitle': 'Agen aktif',
- 'orchPage.sessions.empty': 'Belum ada agen aktif',
- 'orchPage.sessions.statusConnected': 'Terhubung',
- 'orchPage.sessions.statusDisconnected': 'Terputus',
- 'orchPage.sessions.statusWaiting': 'Menunggu masukan',
- 'orchPage.session.runtime': 'Waktu-jalan',
- 'orchPage.session.directory': 'Direktori',
- 'orchPage.session.runningOn': 'Berjalan di',
- 'orchPage.connections.nav': 'Koneksi',
- 'orchPage.connections.title': 'Agen tertaut',
- 'orchPage.connections.description':
- 'Rekan yang dikoordinasikan agen Anda: perluas salah satu untuk melihat sesi Anda dengannya',
- 'orchPage.connections.empty': 'Belum ada koneksi.',
- 'orchPage.connections.emptyCta': 'Tambahkan koneksi',
- 'orchPage.connections.statContacts': 'Koneksi',
- 'orchPage.connections.statPending': 'Menunggu',
- 'orchPage.connections.statSessions': 'Sesi',
- 'orchPage.connections.sessionCount': '{n} sesi',
- 'orchPage.connections.noSessions': 'Tidak ada sesi',
- 'orchPage.connections.messageCount': '{n} pesan',
- 'orchPage.connections.back': 'Koneksi',
- 'orchPage.connections.replyPlaceholder': 'Balas…',
- 'orchPage.connections.initTitle': 'Inisialisasi agen atau instans',
- 'orchPage.connections.initDesc':
- 'Buat sub-agen baru untuk bekerja bersama Anda. Buka obrolan agen dan jelaskan peran, tujuan, serta alat yang harus digunakan: OpenHuman menyediakan instans khusus yang dapat Anda kendalikan dari sini.',
- 'orchPage.connections.initCta': 'Mulai di obrolan',
- 'orchPage.connections.status.needsYou': 'Perlu Anda',
- 'orchPage.connections.status.running': 'Berjalan',
- 'orchPage.connections.status.idle': 'Menganggur',
- 'orchPage.connections.status.done': 'Selesai',
- 'orchPage.connections.status.error': 'Kesalahan',
- 'orchPage.connections.pendingHint': 'Menunggu persetujuan',
- 'orchPage.discover.nav': 'Temukan',
- 'orchPage.discover.linkAction': 'Tambah',
- 'orchPage.discover.identityTitle': 'Keterlihatan Anda',
- 'orchPage.discover.notDiscoverableGuide':
- 'Daftarkan @handle agar agen lain dapat menemukan dan mengirim pesan kepada Anda.',
- 'orchPage.discover.linkTitle': 'Tautkan agen baru',
- 'orchPage.discover.linkDescription': 'Tempel ID agen untuk mengirim permintaan koneksi.',
- 'orchPage.discover.noRequests': 'Tidak ada permintaan masuk.',
- 'orchPage.usage.nav': 'Penggunaan',
- 'orchPage.usage.connections': 'Koneksi',
- 'orchPage.usage.balance': 'Saldo kredit',
- 'orchPage.usage.balanceHint': 'Promosi + isi ulang',
- 'orchPage.usage.cycleSpend': 'Pengeluaran siklus',
- 'orchPage.usage.ofBudget': 'dari',
- 'orchPage.usage.inferenceCalls': 'Panggilan model',
- 'orchPage.usage.integrationCalls': 'Panggilan integrasi',
- 'orchPage.usage.tokensSaved': 'Token dihemat',
- 'orchPage.usage.saved': 'dihemat',
- 'orchPage.usage.footnote': 'Penggunaan mencerminkan siklus penagihan Anda saat ini.',
+
'nav.wallet': 'Dompet',
'nav.avatarMenu.account': 'Akun',
'nav.avatarMenu.billing': 'Tagihan',
@@ -463,85 +350,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': 'Terjadi kesalahan. Silakan coba lagi.',
'brain.tabs.sources': 'Sumber',
'brain.tabs.sync': 'Sinkronisasi',
- 'brain.tabs.orchestration': 'Orkestrasi',
- 'tinyplaceOrchestration.title': 'Relay TinyPlace',
- 'tinyplaceOrchestration.subtitle': 'Kanal agen tersemat dan chat sesi aplikasi',
- 'tinyplaceOrchestration.refresh': 'Segarkan',
- 'tinyplaceOrchestration.newInstance': 'Instansi baru',
- 'tinyplaceOrchestration.newInstanceSoon': 'Segera hadir',
- 'tinyplaceOrchestration.pinned': 'Tersemat',
- 'tinyplaceOrchestration.sessions': 'Sesi',
- 'tinyplaceOrchestration.contacts': 'Kontak',
- 'tinyplaceOrchestration.noContacts': 'Belum ada kontak.',
- 'tinyplaceOrchestration.newSession': 'Sesi baru',
- 'tinyplaceOrchestration.otherSessions': 'Sesi lainnya',
- 'tinyplaceOrchestration.loading': 'Memuat chat TinyPlace…',
- 'tinyplaceOrchestration.paymentRequired': 'Akses TinyPlace memerlukan pembayaran.',
- 'tinyplaceOrchestration.failedToLoad': 'Gagal memuat chat TinyPlace',
- 'tinyplaceOrchestration.noSessions': 'Belum ada sesi aplikasi TinyPlace.',
- 'tinyplaceOrchestration.noMessages': 'Belum ada pesan di chat ini.',
- 'tinyplaceOrchestration.active': 'Aktif',
- 'tinyplaceOrchestration.inactive': 'Tidak aktif',
- 'tinyplaceOrchestration.encryptedBody': 'Pesan TinyPlace terenkripsi',
- 'tinyplaceOrchestration.unknownSender': 'Pengirim tidak dikenal',
- 'tinyplaceOrchestration.master.title': 'Agen / manusia',
- 'tinyplaceOrchestration.master.subtitle': 'Chat master',
- 'tinyplaceOrchestration.master.preview': 'Koordinasi langsung antara Anda dan OpenHuman.',
- 'tinyplaceOrchestration.subconscious.title': 'Alam Bawah Sadar',
- 'tinyplaceOrchestration.subconscious.subtitle': 'Chat internal agen',
- 'tinyplaceOrchestration.subconscious.preview': 'Koordinasi agen latar belakang dan loop memori.',
- 'tinyplaceOrchestration.session.subtitle': 'Sesi aplikasi TinyPlace',
- 'tinyplaceOrchestration.pairing.linkLabel': 'Tautkan sesi',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': 'Tempel ID agen sesi',
- 'tinyplaceOrchestration.pairing.linkAction': 'Tautkan',
- 'tinyplaceOrchestration.pairing.requests': 'Permintaan kontak',
- 'tinyplaceOrchestration.pairing.accept': 'Terima',
- 'tinyplaceOrchestration.pairing.decline': 'Tolak',
- 'tinyplaceOrchestration.pairing.block': 'Blokir',
- 'tinyplaceOrchestration.pairing.linked': 'Tertaut',
- 'tinyplaceOrchestration.pairing.pending': 'Menunggu',
- 'tinyplaceOrchestration.pairing.unlinked': 'Belum tertaut',
- 'tinyplaceOrchestration.pairing.incoming': 'Masuk',
- 'tinyplaceOrchestration.pairing.outgoing': 'Keluar',
- 'tinyplaceOrchestration.master.you': 'Anda',
- 'tinyplaceOrchestration.composer.placeholder': 'Pesan ke OpenHuman…',
- 'tinyplaceOrchestration.composer.send': 'Kirim',
- 'tinyplaceOrchestration.composer.sendFailed': 'Gagal mengirim pesan',
- 'tinyplaceOrchestration.steering.label': 'Pengarahan',
- 'tinyplaceOrchestration.relay.staging': 'Staging',
- 'tinyplaceOrchestration.relay.prod': 'Produksi',
- 'tinyplaceOrchestration.identity.loading': 'Memuat identitas…',
- 'tinyplaceOrchestration.identity.noHandle': 'Belum ada @handle',
- 'tinyplaceOrchestration.identity.copy': 'Salin',
- 'tinyplaceOrchestration.identity.copied': 'Tersalin',
- 'tinyplaceOrchestration.identity.discoverable': 'Dapat ditemukan',
- 'tinyplaceOrchestration.identity.undiscoverable': 'Tidak dapat ditemukan',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'Terbitkan kartu direktori dan kunci enkripsi Anda agar rekan dapat mengirimi Anda pesan.',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'Jadikan dapat ditemukan',
- 'tinyplaceOrchestration.identity.republish': 'Terbitkan ulang kunci',
- 'tinyplaceOrchestration.identity.publishing': 'Menerbitkan…',
- 'tinyplaceOrchestration.identity.publishFailed': 'Gagal menerbitkan: coba lagi',
- 'tinyplaceOrchestration.identity.card': 'Kartu direktori',
- 'tinyplaceOrchestration.identity.key': 'Kunci enkripsi',
- 'tinyplaceOrchestration.identity.published': 'Diterbitkan',
- 'tinyplaceOrchestration.identity.notPublished': 'Belum diterbitkan',
- 'tinyplaceOrchestration.roster.instances': 'Instansi',
- 'tinyplaceOrchestration.roster.empty': 'Belum ada instansi agen',
- 'tinyplaceOrchestration.roster.other': 'Lainnya',
- 'tinyplaceOrchestration.status.running': 'Berjalan',
- 'tinyplaceOrchestration.status.idle': 'Diam',
- 'tinyplaceOrchestration.status.waitingApproval': 'Menunggu persetujuan',
- 'tinyplaceOrchestration.status.errored': 'Bermasalah',
- 'tinyplaceOrchestration.status.stopped': 'Berhenti',
- 'tinyplaceOrchestration.attention.title': 'Butuh Anda',
- 'tinyplaceOrchestration.attention.empty': 'Semua sudah beres',
- 'tinyplaceOrchestration.attention.unread': 'Pesan belum dibaca',
- 'tinyplaceOrchestration.attention.review': 'Tinjau',
- 'tinyplaceOrchestration.attention.open': 'Buka',
- 'tinyplaceOrchestration.attention.kind.approval': 'Persetujuan',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'Perlu masukan',
- 'tinyplaceOrchestration.attention.kind.unread': 'Belum dibaca',
'brain.empty': 'Otak Anda masih kosong: hubungkan sumber untuk mulai membangun memori.',
'brain.error': 'Tidak dapat memuat otak Anda. Silakan coba lagi.',
'common.cancel': 'Batal',
@@ -2908,10 +2716,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'Jalankan model di mesin Anda sendiri menggunakan Ollama. Privasi penuh, perlu pengaturan.',
'backend.ramRecommended': 'RAM 16GB+ direkomendasikan',
- 'tinyplaceOrchestration.subconsciousBadge': 'Bawah sadar · pengarahan',
- 'tinyplaceOrchestration.steeringHeader.current': 'Arahan aktif',
- 'tinyplaceOrchestration.steeringHeader.none': 'Tidak ada arahan aktif',
- 'tinyplaceOrchestration.steeringHeader.expires': 'kedaluwarsa setelah {n} siklus',
'actionable.complete': 'Selesai',
'actionable.dismiss': 'Abaikan',
'actionable.snooze': 'Tunda',
@@ -5235,10 +5039,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'Setujui semua tindakan secara otomatis',
'settings.agentAccess.autoApproveAll.desc':
'Jika diaktifkan, agen akan menjalankan semua tindakan yang memenuhi syarat tanpa meminta persetujuan Anda terlebih dahulu. Ini termasuk penulisan file, perintah shell, permintaan jaringan, dan efek samping lainnya. Batasan keamanan ketat (direktori kredensial dan sistem) tetap berlaku, dan tindakan dari sumber yang tidak tepercaya atau tidak diketahui tidak pernah disetujui secara otomatis.',
- 'settings.agentAccess.tinyplaceAutopilot.title': 'Agen tiny.place otonom',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'Biarkan OpenHuman bertindak sendiri di tiny.place. Sesuai jadwal, ia mencari pekerjaan yang bermanfaat (mendahulukan bounty terbuka), mengerjakan tugas yang sesuai dengan keahliannya, dan bertindak dengan identitas Anda. Ia berjalan tanpa pengawasan dan dapat membelanjakan dana, jadi gunakan devnet saat menguji. Nonaktif secara bawaan.',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'Jalankan otomatis',
'settings.agentAccess.timeout.label': 'Batas waktu tindakan',
'settings.agentAccess.timeout.desc':
'Berapa lama satu alat atau tindakan boleh berjalan sebelum dibatalkan. Tingkatkan nilai ini jika model lokal besar terhenti sebelum selesai merespons.',
@@ -6635,9 +6435,7 @@ const messages: TranslationMap = {
'notch.speaking': 'Berbicara…',
'notch.transcribing': 'Mentranskrip…',
'notch.executing': 'Mengeksekusi…',
- 'memory.tab.orchestration': 'Orkestrasi',
- 'memory.tab.orchestrationDescription':
- 'Jalankan alur kerja multi-agen: sebarkan satu pertanyaan ke agen-agen paralel, periksa silang temuan mereka, dan saksikan setiap fase berakhir menjadi satu jawaban tersintesis.',
+
'orchestration.subtitle':
'Mulai alur kerja multi-agen, pantau kemajuan fasenya, dan baca hasil tersintesisnya.',
'orchestration.loading': 'Memuat alur kerja…',
@@ -6785,10 +6583,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'Anggaran embedding Anda sudah habis, sehingga konten baru tidak lagi ditambahkan ke memori. Siapkan embedding lokal atau tambahkan kunci API Anda sendiri untuk melanjutkan.',
'memoryBudget.cta': 'Siapkan embedding',
- 'tinyplaceSunset.title': 'Tiny Place keluar dari aplikasi',
- 'tinyplaceSunset.message':
- 'Untuk terus memakai tiny.place, kunjungi tiny.place. Fitur ini akan dihapus dari aplikasi setelah 31 Agustus 2026.',
- 'tinyplaceSunset.cta': 'Buka tiny.place',
'userErrors.scope.memory': 'Memori',
// Code block chrome
diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts
index 861e1982a9..77da861238 100644
--- a/app/src/lib/i18n/it.ts
+++ b/app/src/lib/i18n/it.ts
@@ -322,128 +322,11 @@ const messages: TranslationMap = {
'nav.flows': 'Flussi di lavoro',
'nav.workflowRuns': 'Esecuzioni dei flussi',
'nav.workflowDiscoveries': 'Scopri flussi',
- 'nav.orchestration': 'Orchestrazione',
- 'orchestration.cloudUnreachable':
- 'Cervello cloud non raggiungibile: visualizzazione della copia locale.',
- 'orchPage.subtitle': 'Coordina il tuo agente principale',
- 'orchPage.group.agent': 'Agente',
- 'orchPage.group.network': 'Rete',
- 'orchPage.group.insights': 'Approfondimenti',
- 'orchPage.overview.nav': 'Grafo degli agenti',
- 'orchPage.overview.desc':
- 'Una mappa in tempo reale del tuo agente e dei sotto-agenti che coordina.',
- 'orchPage.network.desc': 'Agenti peer a cui sei connesso, scoperta e utilizzo.',
+
'wallet.tabs.balance': 'Saldo del portafoglio',
'wallet.tabs.recovery': 'Recupero',
'wallet.ariaLabel': 'Viste del portafoglio',
- 'orchPage.medulla.nav': 'Panoramica',
- 'orchPage.medulla.badge': 'In arrivo',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'Il modello di orchestrazione di OpenHuman',
- 'orchPage.medulla.body':
- "Medulla è l'LLM sviluppato internamente da OpenHuman, progettato per orchestrare migliaia di agenti in una sola volta, con una finestra di contesto da 10 milioni di token e un'orchestrazione a costi radicalmente ridotti.",
- 'orchPage.medulla.featAgents': 'Migliaia di agenti',
- 'orchPage.medulla.featContext': 'Contesto da 10M di token',
- 'orchPage.medulla.featCost': 'Orchestrazione a basso costo',
- 'orchPage.medulla.subscriberTitle': 'Abbonati OpenHuman',
- 'orchPage.medulla.subscriberNote':
- 'Quando Medulla sarà disponibile, sarà esclusiva per gli abbonati OpenHuman.',
- 'orchPage.medulla.subscriberCta': 'Attiva un abbonamento',
- 'orchPage.medulla.discordTitle': 'Unisciti al Discord',
- 'orchPage.medulla.earlyAccess':
- 'Vuoi accedere in anteprima? Unisciti al nostro Discord e ottieni un invito.',
- 'orchPage.medulla.cta': 'Unisciti al nostro Discord',
- 'orchPage.demo.banner':
- "Questo è un esempio di come apparirebbe l'orchestrazione su larga scala.",
- 'orchPage.demo.device': 'Dispositivo',
- 'orchPage.demo.taskRoute': 'Instrada richiesta in arrivo',
- 'orchPage.demo.taskSummarize': 'Riassumi conversazione',
- 'orchPage.demo.taskEnrich': 'Arricchisci scheda contatto',
- 'orchPage.demo.taskSchedule': 'Pianifica follow-up',
- 'orchPage.demo.taskDraft': 'Bozza di risposta',
- 'orchPage.demo.taskSync': 'Sincronizza fonte dati',
- 'orchPage.demo.networkTitle': 'Agenti pari',
- 'orchPage.demo.networkSummary': '{peers} connessi · {sessions} sub-agenti attivi',
- 'orchPage.demo.peer.connected': 'Connesso',
- 'orchPage.demo.peer.connecting': 'Connessione in corso',
- 'orchPage.demo.peer.idle': 'Inattivo',
- 'orchPage.demo.peerSessions': '{count} sub-agenti',
- 'orchPage.demo.chat.user1': 'Coordina la campagna di outreach su tutti i miei canali.',
- 'orchPage.demo.chat.assistant1':
- 'Ci penso io: avvio 120 agenti su 2 dispositivi per eseguire outreach, arricchimento e follow-up in parallelo.',
- 'orchPage.demo.chat.activity1': 'dispositivo 1 · 100 agenti instradano 1.284 conversazioni',
- 'orchPage.demo.chat.activity2': 'dispositivo 2 · 20 agenti arricchiscono 512 contatti',
- 'orchPage.demo.chat.activity3': 'redazione di 640 risposte personalizzate',
- 'orchPage.demo.chat.assistant2':
- 'Fatto. 120 agenti hanno elaborato 1.796 conversazioni in 38 secondi.',
- 'orchPage.demo.chat.composerDisabled': "La chat è disponibile con l'accesso a Medulla",
- 'orchPage.tasks.nav': 'Attività',
- 'orchPage.tasks.subtitle': 'La bacheca attività globale dell’orchestratore',
- 'orchPage.tasks.colPending': 'In attesa',
- 'orchPage.tasks.colActive': 'Attivo',
- 'orchPage.tasks.colBlocked': 'Bloccato',
- 'orchPage.tasks.colCompleted': 'Completato',
- 'orchPage.overview.core': 'Nucleo dell’agente',
- 'orchPage.overview.empty': 'Nessun sotto-agente da visualizzare ancora',
- 'orchPage.agent.nav': 'Chat',
- 'orchPage.agent.mainTab': 'Agente principale',
- 'orchPage.agent.consciousTab': 'Conscio',
- 'orchPage.agent.subconsciousTab': 'Subconscio',
- 'orchPage.agent.modeLabel': 'Mente dell’agente',
- 'orchPage.agent.description': "Chatta con l'agente principale e osserva il suo subconscio",
- 'orchPage.agent.viewSession': 'Vedi sessione',
- 'orchPage.sessions.railTitle': 'Agenti attivi',
- 'orchPage.sessions.empty': 'Ancora nessun agente attivo',
- 'orchPage.sessions.statusConnected': 'Connesso',
- 'orchPage.sessions.statusDisconnected': 'Disconnesso',
- 'orchPage.sessions.statusWaiting': 'In attesa di input',
- 'orchPage.session.runtime': 'Esecuzione',
- 'orchPage.session.directory': 'Cartella',
- 'orchPage.session.runningOn': 'In esecuzione su',
- 'orchPage.connections.nav': 'Connessioni',
- 'orchPage.connections.title': 'Agenti collegati',
- 'orchPage.connections.description':
- 'Peer con cui il tuo agente si coordina: espandine uno per vedere le tue sessioni con esso',
- 'orchPage.connections.empty': 'Ancora nessuna connessione.',
- 'orchPage.connections.emptyCta': 'Aggiungi una connessione',
- 'orchPage.connections.statContacts': 'Connessioni',
- 'orchPage.connections.statPending': 'In sospeso',
- 'orchPage.connections.statSessions': 'Sessioni',
- 'orchPage.connections.sessionCount': '{n} sessioni',
- 'orchPage.connections.noSessions': 'Nessuna sessione',
- 'orchPage.connections.messageCount': '{n} messaggi',
- 'orchPage.connections.back': 'Connessioni',
- 'orchPage.connections.replyPlaceholder': 'Rispondi…',
- 'orchPage.connections.initTitle': "Inizializza un agente o un'istanza",
- 'orchPage.connections.initDesc':
- "Avvia un nuovo sotto-agente che lavori al tuo fianco. Apri la chat dell'agente e descrivi ruolo, obiettivo e strumenti: OpenHuman fornisce un'istanza dedicata che puoi guidare da qui.",
- 'orchPage.connections.initCta': 'Inizia nella chat',
- 'orchPage.connections.status.needsYou': 'Richiede la tua attenzione',
- 'orchPage.connections.status.running': 'In esecuzione',
- 'orchPage.connections.status.idle': 'Inattivo',
- 'orchPage.connections.status.done': 'Completato',
- 'orchPage.connections.status.error': 'Errore',
- 'orchPage.connections.pendingHint': 'In attesa di accettazione',
- 'orchPage.discover.nav': 'Scopri',
- 'orchPage.discover.linkAction': 'Aggiungi',
- 'orchPage.discover.identityTitle': 'La tua reperibilità',
- 'orchPage.discover.notDiscoverableGuide':
- 'Registra un @handle così altri agenti possono trovarti e scriverti.',
- 'orchPage.discover.linkTitle': 'Collega un nuovo agente',
- 'orchPage.discover.linkDescription':
- 'Incolla un ID agente per inviare una richiesta di connessione.',
- 'orchPage.discover.noRequests': 'Nessuna richiesta in arrivo.',
- 'orchPage.usage.nav': 'Utilizzo',
- 'orchPage.usage.connections': 'Connessioni',
- 'orchPage.usage.balance': 'Saldo credito',
- 'orchPage.usage.balanceHint': 'Promozionale + ricarica',
- 'orchPage.usage.cycleSpend': 'Spesa del ciclo',
- 'orchPage.usage.ofBudget': 'di',
- 'orchPage.usage.inferenceCalls': 'Chiamate al modello',
- 'orchPage.usage.integrationCalls': 'Chiamate di integrazione',
- 'orchPage.usage.tokensSaved': 'Token risparmiati',
- 'orchPage.usage.saved': 'risparmiato',
- 'orchPage.usage.footnote': "L'utilizzo riflette il tuo ciclo di fatturazione attuale.",
+
'nav.wallet': 'Portafoglio',
'nav.avatarMenu.account': 'Account',
'nav.avatarMenu.billing': 'Fatturazione',
@@ -471,86 +354,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': 'Qualcosa è andato storto. Riprova.',
'brain.tabs.sources': 'Fonti',
'brain.tabs.sync': 'Sincronizzazione',
- 'brain.tabs.orchestration': 'Orchestrazione',
- 'tinyplaceOrchestration.title': 'Relay TinyPlace',
- 'tinyplaceOrchestration.subtitle': 'Canali agente fissati e chat delle sessioni app',
- 'tinyplaceOrchestration.refresh': 'Aggiorna',
- 'tinyplaceOrchestration.newInstance': 'Nuova istanza',
- 'tinyplaceOrchestration.newInstanceSoon': 'Prossimamente',
- 'tinyplaceOrchestration.pinned': 'Fissati',
- 'tinyplaceOrchestration.sessions': 'Sessioni',
- 'tinyplaceOrchestration.contacts': 'Contatti',
- 'tinyplaceOrchestration.noContacts': 'Ancora nessun contatto.',
- 'tinyplaceOrchestration.newSession': 'Nuova sessione',
- 'tinyplaceOrchestration.otherSessions': 'Altre sessioni',
- 'tinyplaceOrchestration.loading': 'Caricamento chat TinyPlace…',
- 'tinyplaceOrchestration.paymentRequired': "L'accesso a TinyPlace richiede un pagamento.",
- 'tinyplaceOrchestration.failedToLoad': 'Impossibile caricare le chat TinyPlace',
- 'tinyplaceOrchestration.noSessions': 'Nessuna sessione app TinyPlace per ora.',
- 'tinyplaceOrchestration.noMessages': 'Ancora nessun messaggio in questa chat.',
- 'tinyplaceOrchestration.active': 'Attiva',
- 'tinyplaceOrchestration.inactive': 'Inattiva',
- 'tinyplaceOrchestration.encryptedBody': 'Messaggio TinyPlace cifrato',
- 'tinyplaceOrchestration.unknownSender': 'Mittente sconosciuto',
- 'tinyplaceOrchestration.master.title': 'Agente / umano',
- 'tinyplaceOrchestration.master.subtitle': 'Chat principale',
- 'tinyplaceOrchestration.master.preview': 'Coordinamento diretto tra te e OpenHuman.',
- 'tinyplaceOrchestration.subconscious.title': 'Subconscio',
- 'tinyplaceOrchestration.subconscious.subtitle': 'Chat interne degli agenti',
- 'tinyplaceOrchestration.subconscious.preview':
- 'Coordinamento degli agenti in background e cicli di memoria.',
- 'tinyplaceOrchestration.session.subtitle': 'Sessione app TinyPlace',
- 'tinyplaceOrchestration.pairing.linkLabel': 'Collega sessione',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': "Incolla l'ID agente sessione",
- 'tinyplaceOrchestration.pairing.linkAction': 'Collega',
- 'tinyplaceOrchestration.pairing.requests': 'Richieste contatto',
- 'tinyplaceOrchestration.pairing.accept': 'Accetta',
- 'tinyplaceOrchestration.pairing.decline': 'Rifiuta',
- 'tinyplaceOrchestration.pairing.block': 'Blocca',
- 'tinyplaceOrchestration.pairing.linked': 'Collegata',
- 'tinyplaceOrchestration.pairing.pending': 'In attesa',
- 'tinyplaceOrchestration.pairing.unlinked': 'Non collegata',
- 'tinyplaceOrchestration.pairing.incoming': 'In arrivo',
- 'tinyplaceOrchestration.pairing.outgoing': 'In uscita',
- 'tinyplaceOrchestration.master.you': 'Tu',
- 'tinyplaceOrchestration.composer.placeholder': 'Messaggio a OpenHuman…',
- 'tinyplaceOrchestration.composer.send': 'Invia',
- 'tinyplaceOrchestration.composer.sendFailed': 'Invio del messaggio non riuscito',
- 'tinyplaceOrchestration.steering.label': 'Direzione',
- 'tinyplaceOrchestration.relay.staging': 'Staging',
- 'tinyplaceOrchestration.relay.prod': 'Produzione',
- 'tinyplaceOrchestration.identity.loading': 'Caricamento identità…',
- 'tinyplaceOrchestration.identity.noHandle': 'Ancora nessun @handle',
- 'tinyplaceOrchestration.identity.copy': 'Copia',
- 'tinyplaceOrchestration.identity.copied': 'Copiato',
- 'tinyplaceOrchestration.identity.discoverable': 'Rilevabile',
- 'tinyplaceOrchestration.identity.undiscoverable': 'Non rilevabile',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'Pubblica la tua scheda directory e la tua chiave di crittografia così altri agenti possono scriverti.',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'Rendi rilevabile',
- 'tinyplaceOrchestration.identity.republish': 'Ripubblica chiavi',
- 'tinyplaceOrchestration.identity.publishing': 'Pubblicazione…',
- 'tinyplaceOrchestration.identity.publishFailed': 'Pubblicazione non riuscita: riprova',
- 'tinyplaceOrchestration.identity.card': 'Scheda directory',
- 'tinyplaceOrchestration.identity.key': 'Chiave di crittografia',
- 'tinyplaceOrchestration.identity.published': 'Pubblicato',
- 'tinyplaceOrchestration.identity.notPublished': 'Non pubblicato',
- 'tinyplaceOrchestration.roster.instances': 'Istanze',
- 'tinyplaceOrchestration.roster.empty': 'Nessuna istanza agente',
- 'tinyplaceOrchestration.roster.other': 'Altro',
- 'tinyplaceOrchestration.status.running': 'In esecuzione',
- 'tinyplaceOrchestration.status.idle': 'Inattivo',
- 'tinyplaceOrchestration.status.waitingApproval': 'In attesa di approvazione',
- 'tinyplaceOrchestration.status.errored': 'In errore',
- 'tinyplaceOrchestration.status.stopped': 'Arrestato',
- 'tinyplaceOrchestration.attention.title': 'Ha bisogno di te',
- 'tinyplaceOrchestration.attention.empty': 'Sei aggiornato',
- 'tinyplaceOrchestration.attention.unread': 'Messaggi non letti',
- 'tinyplaceOrchestration.attention.review': 'Rivedi',
- 'tinyplaceOrchestration.attention.open': 'Apri',
- 'tinyplaceOrchestration.attention.kind.approval': 'Approvazione',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'Richiede input',
- 'tinyplaceOrchestration.attention.kind.unread': 'Non letti',
'brain.empty':
'Il tuo cervello è ancora vuoto: collega una fonte per iniziare a costruire la memoria.',
'brain.error': 'Impossibile caricare il tuo cervello. Riprova.',
@@ -2953,10 +2756,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'Esegui i modelli sulla tua macchina con Ollama. Privacy totale, richiede configurazione.',
'backend.ramRecommended': '16GB+ di RAM consigliati',
- 'tinyplaceOrchestration.subconsciousBadge': 'Subconscio · guida',
- 'tinyplaceOrchestration.steeringHeader.current': 'Direttiva attiva',
- 'tinyplaceOrchestration.steeringHeader.none': 'Nessuna direttiva attiva',
- 'tinyplaceOrchestration.steeringHeader.expires': 'scade dopo {n} cicli',
'actionable.complete': 'Completa',
'actionable.dismiss': 'Ignora',
'actionable.snooze': 'Posticipa',
@@ -5296,10 +5095,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'Approva automaticamente tutte le azioni',
'settings.agentAccess.autoApproveAll.desc':
"Se attivato, l'agente eseguirà tutte le azioni senza chiedere prima la tua approvazione. Questo include scritture di file, comandi shell, richieste di rete e qualsiasi altro effetto collaterale. I blocchi di sicurezza rigidi (directory delle credenziali, percorsi interni dell'area di lavoro) continuano ad applicarsi.",
- 'settings.agentAccess.tinyplaceAutopilot.title': 'Agente tiny.place autonomo',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'Lascia che OpenHuman agisca da solo su tiny.place. In base alla pianificazione, cerca lavoro utile (prima le taglie aperte), svolge ciò che si adatta alle sue competenze e agisce con la tua identità. Funziona senza supervisione e può spendere, quindi tienilo su devnet durante i test. Disattivato per impostazione predefinita.',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'Esegui automaticamente',
'settings.agentAccess.timeout.label': "Timeout dell'azione",
'settings.agentAccess.timeout.desc':
'Per quanto tempo un singolo strumento o azione può essere eseguito prima di essere annullato. Aumenta questo valore se un modello locale di grandi dimensioni viene interrotto prima di completare la risposta.',
@@ -6728,9 +6523,7 @@ const messages: TranslationMap = {
'notch.speaking': 'Parlo…',
'notch.transcribing': 'Trascrizione…',
'notch.executing': 'Eseguendo…',
- 'memory.tab.orchestration': 'Orchestrazione',
- 'memory.tab.orchestrationDescription':
- 'Esegui flussi di lavoro multi-agente: distribuisci una domanda tra agenti paralleli, confronta i loro risultati e osserva ogni fase concludersi in un’unica risposta sintetizzata.',
+
'orchestration.subtitle':
'Avvia un flusso di lavoro multi-agente, osserva l’avanzamento delle sue fasi e leggi il risultato sintetizzato.',
'orchestration.loading': 'Caricamento dei flussi di lavoro…',
@@ -6878,10 +6671,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'Il tuo budget di embedding è esaurito, quindi i nuovi contenuti non vengono più aggiunti alla memoria. Configura embedding locali o aggiungi la tua chiave API per riprendere.',
'memoryBudget.cta': 'Configura gli embedding',
- 'tinyplaceSunset.title': 'Tiny Place esce dall’app',
- 'tinyplaceSunset.message':
- 'Per continuare a usare tiny.place, vai su tiny.place. Verrà rimosso dall’app dopo il 31 agosto 2026.',
- 'tinyplaceSunset.cta': 'Apri tiny.place',
'userErrors.scope.memory': 'Memoria',
// Code block chrome
diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts
index 599992ccd1..ae4c7f1256 100644
--- a/app/src/lib/i18n/ko.ts
+++ b/app/src/lib/i18n/ko.ts
@@ -308,123 +308,11 @@ const messages: TranslationMap = {
'nav.flows': '워크플로',
'nav.workflowRuns': '워크플로 실행',
'nav.workflowDiscoveries': '워크플로 발견',
- 'nav.orchestration': '오케스트레이션',
- 'orchestration.cloudUnreachable':
- '클라우드 브레인에 연결할 수 없습니다: 캐시된 화면을 표시합니다.',
- 'orchPage.subtitle': '메인 에이전트를 조율하세요',
- 'orchPage.group.agent': '에이전트',
- 'orchPage.group.network': '네트워크',
- 'orchPage.group.insights': '인사이트',
- 'orchPage.overview.nav': '에이전트 그래프',
- 'orchPage.overview.desc': '에이전트와 이를 조율하는 하위 에이전트의 실시간 지도입니다.',
- 'orchPage.network.desc': '연결된 피어 에이전트, 검색 및 사용량입니다.',
+
'wallet.tabs.balance': '지갑 잔액',
'wallet.tabs.recovery': '복구',
'wallet.ariaLabel': '지갑 보기',
- 'orchPage.medulla.nav': '개요',
- 'orchPage.medulla.badge': '출시 예정',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'OpenHuman의 오케스트레이션 모델',
- 'orchPage.medulla.body':
- 'Medulla는 OpenHuman이 자체 개발한 LLM으로, 수천 개의 에이전트를 동시에 오케스트레이션하도록 설계되었으며, 1,000만 토큰 컨텍스트 창과 획기적으로 낮은 비용의 오케스트레이션을 제공합니다.',
- 'orchPage.medulla.featAgents': '수천 개의 에이전트',
- 'orchPage.medulla.featContext': '10M 토큰 컨텍스트',
- 'orchPage.medulla.featCost': '저비용 오케스트레이션',
- 'orchPage.medulla.subscriberTitle': 'OpenHuman 구독자',
- 'orchPage.medulla.subscriberNote': 'Medulla가 출시되면 OpenHuman 구독자 전용으로 제공됩니다.',
- 'orchPage.medulla.subscriberCta': '구독하기',
- 'orchPage.medulla.discordTitle': 'Discord 참여하기',
- 'orchPage.medulla.earlyAccess':
- '먼저 사용해 보고 싶으신가요? 저희 Discord에 참여하고 얼리 액세스 초대를 받으세요.',
- 'orchPage.medulla.cta': '저희 Discord에 참여하기',
- 'orchPage.demo.banner': '대규모로 오케스트레이션이 어떻게 보이는지에 대한 예시입니다.',
- 'orchPage.demo.device': '기기',
- 'orchPage.demo.taskRoute': '수신 요청 라우팅',
- 'orchPage.demo.taskSummarize': '대화 요약',
- 'orchPage.demo.taskEnrich': '연락처 레코드 보강',
- 'orchPage.demo.taskSchedule': '후속 조치 예약',
- 'orchPage.demo.taskDraft': '답장 초안 작성',
- 'orchPage.demo.taskSync': '데이터 소스 동기화',
- 'orchPage.demo.networkTitle': '피어 에이전트',
- 'orchPage.demo.networkSummary': '{peers}개 연결됨 · {sessions}개 활성 하위 에이전트',
- 'orchPage.demo.peer.connected': '연결됨',
- 'orchPage.demo.peer.connecting': '연결 중',
- 'orchPage.demo.peer.idle': '유휴',
- 'orchPage.demo.peerSessions': '하위 에이전트 {count}개',
- 'orchPage.demo.chat.user1': '모든 채널에서 아웃리치 캠페인을 조율해 주세요.',
- 'orchPage.demo.chat.assistant1':
- '진행 중입니다: 아웃리치, 보강, 후속 조치를 병렬로 실행하기 위해 2대의 기기에서 120개의 에이전트를 가동하고 있습니다.',
- 'orchPage.demo.chat.activity1': '기기 1 · 100개 에이전트가 1,284개 대화를 라우팅 중',
- 'orchPage.demo.chat.activity2': '기기 2 · 20개 에이전트가 512개 연락처를 보강 중',
- 'orchPage.demo.chat.activity3': '640개의 맞춤형 답장 초안 작성 중',
- 'orchPage.demo.chat.assistant2': '완료. 120개 에이전트가 38초 만에 1,796개 대화를 처리했습니다.',
- 'orchPage.demo.chat.composerDisabled': 'Medulla 액세스가 있으면 채팅을 사용할 수 있습니다',
- 'orchPage.tasks.nav': '작업',
- 'orchPage.tasks.subtitle': '오케스트레이터의 전역 작업 보드',
- 'orchPage.tasks.colPending': '대기 중',
- 'orchPage.tasks.colActive': '활성',
- 'orchPage.tasks.colBlocked': '차단됨',
- 'orchPage.tasks.colCompleted': '완료',
- 'orchPage.overview.core': '에이전트 코어',
- 'orchPage.overview.empty': '아직 시각화할 서브 에이전트가 없습니다',
- 'orchPage.agent.nav': '채팅',
- 'orchPage.agent.mainTab': '메인 에이전트',
- 'orchPage.agent.consciousTab': '의식',
- 'orchPage.agent.subconsciousTab': '잠재의식',
- 'orchPage.agent.modeLabel': '에이전트 마음',
- 'orchPage.agent.description': '메인 에이전트와 대화하고 잠재의식을 지켜보세요',
- 'orchPage.agent.viewSession': '세션 보기',
- 'orchPage.sessions.railTitle': '활성 에이전트',
- 'orchPage.sessions.empty': '아직 활성 에이전트가 없습니다',
- 'orchPage.sessions.statusConnected': '연결됨',
- 'orchPage.sessions.statusDisconnected': '연결 끊김',
- 'orchPage.sessions.statusWaiting': '입력 대기 중',
- 'orchPage.session.runtime': '런타임',
- 'orchPage.session.directory': '디렉터리',
- 'orchPage.session.runningOn': '실행 위치',
- 'orchPage.connections.nav': '연결',
- 'orchPage.connections.title': '연결된 에이전트',
- 'orchPage.connections.description':
- '에이전트가 협력하는 상대: 하나를 펼쳐 해당 상대와의 세션을 확인하세요',
- 'orchPage.connections.empty': '아직 연결이 없습니다.',
- 'orchPage.connections.emptyCta': '연결 추가',
- 'orchPage.connections.statContacts': '연결',
- 'orchPage.connections.statPending': '대기 중',
- 'orchPage.connections.statSessions': '세션',
- 'orchPage.connections.sessionCount': '{n}개 세션',
- 'orchPage.connections.noSessions': '세션 없음',
- 'orchPage.connections.messageCount': '{n}개 메시지',
- 'orchPage.connections.back': '연결',
- 'orchPage.connections.replyPlaceholder': '답장…',
- 'orchPage.connections.initTitle': '에이전트 또는 인스턴스 초기화',
- 'orchPage.connections.initDesc':
- '함께 일할 새 서브 에이전트를 만드세요. 에이전트 채팅을 열고 역할, 목표, 사용할 도구를 설명하면 OpenHuman이 여기서 조종할 수 있는 전용 인스턴스를 준비합니다.',
- 'orchPage.connections.initCta': '채팅에서 시작',
- 'orchPage.connections.status.needsYou': '확인 필요',
- 'orchPage.connections.status.running': '실행 중',
- 'orchPage.connections.status.idle': '유휴',
- 'orchPage.connections.status.done': '완료',
- 'orchPage.connections.status.error': '오류',
- 'orchPage.connections.pendingHint': '수락 대기 중',
- 'orchPage.discover.nav': '탐색',
- 'orchPage.discover.linkAction': '추가',
- 'orchPage.discover.identityTitle': '검색 가능성',
- 'orchPage.discover.notDiscoverableGuide':
- '다른 에이전트가 찾아 메시지를 보낼 수 있도록 @handle을 등록하세요.',
- 'orchPage.discover.linkTitle': '새 에이전트 연결',
- 'orchPage.discover.linkDescription': '연결 요청을 보내려면 에이전트 ID를 붙여넣으세요.',
- 'orchPage.discover.noRequests': '수신된 요청이 없습니다.',
- 'orchPage.usage.nav': '사용량',
- 'orchPage.usage.connections': '연결',
- 'orchPage.usage.balance': '크레딧 잔액',
- 'orchPage.usage.balanceHint': '프로모션 + 충전',
- 'orchPage.usage.cycleSpend': '주기 지출',
- 'orchPage.usage.ofBudget': '중',
- 'orchPage.usage.inferenceCalls': '모델 호출',
- 'orchPage.usage.integrationCalls': '통합 호출',
- 'orchPage.usage.tokensSaved': '절약된 토큰',
- 'orchPage.usage.saved': '절약',
- 'orchPage.usage.footnote': '사용량은 현재 청구 주기를 반영합니다.',
+
'nav.wallet': '지갑',
'nav.avatarMenu.account': '계정',
'nav.avatarMenu.billing': '결제',
@@ -452,85 +340,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': '문제가 발생했습니다. 다시 시도해 주세요.',
'brain.tabs.sources': '소스',
'brain.tabs.sync': '동기화',
- 'brain.tabs.orchestration': '오케스트레이션',
- 'tinyplaceOrchestration.title': 'TinyPlace 릴레이',
- 'tinyplaceOrchestration.subtitle': '고정된 에이전트 채널과 앱 세션 채팅',
- 'tinyplaceOrchestration.refresh': '새로 고침',
- 'tinyplaceOrchestration.newInstance': '새 인스턴스',
- 'tinyplaceOrchestration.newInstanceSoon': '곧 제공 예정',
- 'tinyplaceOrchestration.pinned': '고정됨',
- 'tinyplaceOrchestration.sessions': '세션',
- 'tinyplaceOrchestration.contacts': '연락처',
- 'tinyplaceOrchestration.noContacts': '아직 연락처가 없습니다.',
- 'tinyplaceOrchestration.newSession': '새 세션',
- 'tinyplaceOrchestration.otherSessions': '기타 세션',
- 'tinyplaceOrchestration.loading': 'TinyPlace 채팅을 불러오는 중…',
- 'tinyplaceOrchestration.paymentRequired': 'TinyPlace 접근에는 결제가 필요합니다.',
- 'tinyplaceOrchestration.failedToLoad': 'TinyPlace 채팅을 불러오지 못했습니다',
- 'tinyplaceOrchestration.noSessions': '아직 TinyPlace 앱 세션이 없습니다.',
- 'tinyplaceOrchestration.noMessages': '이 채팅에는 아직 메시지가 없습니다.',
- 'tinyplaceOrchestration.active': '활성',
- 'tinyplaceOrchestration.inactive': '비활성',
- 'tinyplaceOrchestration.encryptedBody': '암호화된 TinyPlace 메시지',
- 'tinyplaceOrchestration.unknownSender': '알 수 없는 보낸 사람',
- 'tinyplaceOrchestration.master.title': '에이전트 / 사람',
- 'tinyplaceOrchestration.master.subtitle': '마스터 채팅',
- 'tinyplaceOrchestration.master.preview': '사용자와 OpenHuman 간의 직접 조율.',
- 'tinyplaceOrchestration.subconscious.title': '잠재의식',
- 'tinyplaceOrchestration.subconscious.subtitle': '내부 에이전트 채팅',
- 'tinyplaceOrchestration.subconscious.preview': '백그라운드 에이전트 조율과 메모리 루프.',
- 'tinyplaceOrchestration.session.subtitle': 'TinyPlace 앱 세션',
- 'tinyplaceOrchestration.pairing.linkLabel': '세션 연결',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': '세션 에이전트 ID 붙여넣기',
- 'tinyplaceOrchestration.pairing.linkAction': '연결',
- 'tinyplaceOrchestration.pairing.requests': '연락처 요청',
- 'tinyplaceOrchestration.pairing.accept': '수락',
- 'tinyplaceOrchestration.pairing.decline': '거절',
- 'tinyplaceOrchestration.pairing.block': '차단',
- 'tinyplaceOrchestration.pairing.linked': '연결됨',
- 'tinyplaceOrchestration.pairing.pending': '대기 중',
- 'tinyplaceOrchestration.pairing.unlinked': '미연결',
- 'tinyplaceOrchestration.pairing.incoming': '수신',
- 'tinyplaceOrchestration.pairing.outgoing': '발신',
- 'tinyplaceOrchestration.master.you': '나',
- 'tinyplaceOrchestration.composer.placeholder': 'OpenHuman에 메시지…',
- 'tinyplaceOrchestration.composer.send': '보내기',
- 'tinyplaceOrchestration.composer.sendFailed': '메시지를 보내지 못했습니다',
- 'tinyplaceOrchestration.steering.label': '조종',
- 'tinyplaceOrchestration.relay.staging': '스테이징',
- 'tinyplaceOrchestration.relay.prod': '프로덕션',
- 'tinyplaceOrchestration.identity.loading': '신원 불러오는 중…',
- 'tinyplaceOrchestration.identity.noHandle': '아직 @handle 없음',
- 'tinyplaceOrchestration.identity.copy': '복사',
- 'tinyplaceOrchestration.identity.copied': '복사됨',
- 'tinyplaceOrchestration.identity.discoverable': '검색 가능',
- 'tinyplaceOrchestration.identity.undiscoverable': '검색 불가',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- '다른 에이전트가 메시지를 보낼 수 있도록 디렉터리 카드와 암호화 키를 게시하세요.',
- 'tinyplaceOrchestration.identity.makeDiscoverable': '검색 가능하게 만들기',
- 'tinyplaceOrchestration.identity.republish': '키 다시 게시',
- 'tinyplaceOrchestration.identity.publishing': '게시 중…',
- 'tinyplaceOrchestration.identity.publishFailed': '게시 실패: 다시 시도하세요',
- 'tinyplaceOrchestration.identity.card': '디렉터리 카드',
- 'tinyplaceOrchestration.identity.key': '암호화 키',
- 'tinyplaceOrchestration.identity.published': '게시됨',
- 'tinyplaceOrchestration.identity.notPublished': '게시 안 됨',
- 'tinyplaceOrchestration.roster.instances': '인스턴스',
- 'tinyplaceOrchestration.roster.empty': '아직 에이전트 인스턴스가 없습니다',
- 'tinyplaceOrchestration.roster.other': '기타',
- 'tinyplaceOrchestration.status.running': '실행 중',
- 'tinyplaceOrchestration.status.idle': '유휴',
- 'tinyplaceOrchestration.status.waitingApproval': '승인 대기 중',
- 'tinyplaceOrchestration.status.errored': '오류',
- 'tinyplaceOrchestration.status.stopped': '중지됨',
- 'tinyplaceOrchestration.attention.title': '확인 필요',
- 'tinyplaceOrchestration.attention.empty': '모두 처리했습니다',
- 'tinyplaceOrchestration.attention.unread': '읽지 않은 메시지',
- 'tinyplaceOrchestration.attention.review': '검토',
- 'tinyplaceOrchestration.attention.open': '열기',
- 'tinyplaceOrchestration.attention.kind.approval': '승인',
- 'tinyplaceOrchestration.attention.kind.needsInput': '입력 필요',
- 'tinyplaceOrchestration.attention.kind.unread': '안 읽음',
'brain.empty': '아직 브레인이 비어 있습니다: 소스를 연결하여 메모리를 만들어 보세요.',
'brain.error': '브레인을 불러올 수 없습니다. 다시 시도해 주세요.',
'common.cancel': '취소',
@@ -2863,10 +2672,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'Ollama를 사용하여 자신의 컴퓨터에서 모델을 실행합니다. 완전한 개인정보 보호를 제공하지만 설정이 필요합니다.',
'backend.ramRecommended': '16GB 이상 RAM 권장',
- 'tinyplaceOrchestration.subconsciousBadge': '잠재의식 · 조정',
- 'tinyplaceOrchestration.steeringHeader.current': '활성 지시문',
- 'tinyplaceOrchestration.steeringHeader.none': '활성 지시문 없음',
- 'tinyplaceOrchestration.steeringHeader.expires': '{n}주기 후 만료',
'actionable.complete': '완료',
'actionable.dismiss': '닫기',
'actionable.snooze': '다시 알림',
@@ -5150,10 +4955,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': '모든 작업 자동 승인',
'settings.agentAccess.autoApproveAll.desc':
'활성화하면 에이전트가 먼저 승인을 요청하지 않고 해당되는 모든 작업을 실행합니다. 여기에는 파일 쓰기, 셸 명령, 네트워크 요청 및 기타 모든 부작용이 포함됩니다. 자격 증명 및 시스템 디렉터리는 계속 차단되며, 신뢰할 수 없거나 출처가 확인되지 않은 호출에서 비롯된 작업은 계속 거부됩니다.',
- 'settings.agentAccess.tinyplaceAutopilot.title': '자율 tiny.place 에이전트',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'OpenHuman이 tiny.place에서 스스로 행동하게 하세요: 일정에 따라 가치 있는 일을 찾고(열린 현상금 우선) 자신의 능력에 맞는 작업을 수행하며 당신의 신원으로 행동합니다. 감독 없이 작동하며 비용을 지출할 수 있으니 테스트 중에는 devnet을 사용하세요. 기본값은 꺼짐입니다.',
- 'settings.agentAccess.tinyplaceAutopilot.label': '자동 실행',
'settings.agentAccess.timeout.label': '작업 제한 시간',
'settings.agentAccess.timeout.desc':
'단일 도구나 작업이 취소되기 전까지 실행될 수 있는 시간입니다. 대형 로컬 모델이 응답을 끝내기 전에 중단되는 경우 이 값을 늘리세요.',
@@ -6529,9 +6330,7 @@ const messages: TranslationMap = {
'notch.speaking': '말하는 중…',
'notch.transcribing': '변환 중…',
'notch.executing': '실행 중…',
- 'memory.tab.orchestration': '오케스트레이션',
- 'memory.tab.orchestrationDescription':
- '다중 에이전트 워크플로를 실행하세요. 하나의 질문을 병렬 에이전트들에 분산하고, 그 결과를 교차 검증하며, 각 단계가 하나의 종합된 답변으로 완성되는 과정을 지켜보세요.',
+
'orchestration.subtitle':
'다중 에이전트 워크플로를 시작하고, 단계 진행 상황을 지켜보며, 종합된 결과를 확인하세요.',
'orchestration.loading': '워크플로 불러오는 중…',
@@ -6675,10 +6474,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'임베딩 예산을 모두 사용해 새 콘텐츠가 메모리에 추가되지 않습니다. 로컬 임베딩을 설정하거나 본인의 API 키를 추가하면 다시 시작됩니다.',
'memoryBudget.cta': '임베딩 설정',
- 'tinyplaceSunset.title': 'Tiny Place가 앱에서 분리됩니다',
- 'tinyplaceSunset.message':
- 'tiny.place를 계속 사용하려면 tiny.place에서 이용하세요. 2026년 8월 31일 이후 앱에서 제거됩니다.',
- 'tinyplaceSunset.cta': 'tiny.place 열기',
'userErrors.scope.memory': '메모리',
// Code block chrome
diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts
index 65942c04d2..d388af4526 100644
--- a/app/src/lib/i18n/pl.ts
+++ b/app/src/lib/i18n/pl.ts
@@ -322,125 +322,11 @@ const messages: TranslationMap = {
'nav.flows': 'Przepływy pracy',
'nav.workflowRuns': 'Uruchomienia przepływów',
'nav.workflowDiscoveries': 'Odkryj przepływy',
- 'nav.orchestration': 'Orkiestracja',
- 'orchestration.cloudUnreachable':
- 'Mózg w chmurze jest niedostępny: wyświetlanie widoku z pamięci podręcznej.',
- 'orchPage.subtitle': 'Koordynuj swojego głównego agenta',
- 'orchPage.group.agent': 'Agent',
- 'orchPage.group.network': 'Sieć',
- 'orchPage.group.insights': 'Statystyki',
- 'orchPage.overview.nav': 'Graf agentów',
- 'orchPage.overview.desc': 'Mapa na żywo Twojego agenta i podagentów, które koordynuje.',
- 'orchPage.network.desc': 'Agenci równorzędni, z którymi masz połączenie, wykrywanie i użycie.',
+
'wallet.tabs.balance': 'Saldo portfela',
'wallet.tabs.recovery': 'Odzyskiwanie',
'wallet.ariaLabel': 'Widoki portfela',
- 'orchPage.medulla.nav': 'Przegląd',
- 'orchPage.medulla.badge': 'Wkrótce',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'Model orkiestracji OpenHuman',
- 'orchPage.medulla.body':
- 'Medulla to autorski model LLM OpenHuman, zaprojektowany do orkiestracji tysięcy agentów jednocześnie, z oknem kontekstu o wielkości 10 milionów tokenów i radykalnie tanią orkiestracją.',
- 'orchPage.medulla.featAgents': 'Tysiące agentów',
- 'orchPage.medulla.featContext': 'Kontekst 10M tokenów',
- 'orchPage.medulla.featCost': 'Tania orkiestracja',
- 'orchPage.medulla.subscriberTitle': 'Subskrybenci OpenHuman',
- 'orchPage.medulla.subscriberNote':
- 'Gdy Medulla zostanie uruchomiona, będzie dostępna wyłącznie dla subskrybentów OpenHuman.',
- 'orchPage.medulla.subscriberCta': 'Wykup subskrypcję',
- 'orchPage.medulla.discordTitle': 'Dołącz do Discorda',
- 'orchPage.medulla.earlyAccess':
- 'Chcesz mieć dostęp wcześniej? Dołącz do naszego Discorda i zdobądź zaproszenie.',
- 'orchPage.medulla.cta': 'Dołącz do naszego Discorda',
- 'orchPage.demo.banner': 'To przykład tego, jak orkiestracja wyglądałaby na dużą skalę.',
- 'orchPage.demo.device': 'Urządzenie',
- 'orchPage.demo.taskRoute': 'Przekieruj przychodzące żądanie',
- 'orchPage.demo.taskSummarize': 'Podsumuj rozmowę',
- 'orchPage.demo.taskEnrich': 'Wzbogać rekord kontaktu',
- 'orchPage.demo.taskSchedule': 'Zaplanuj kontakt uzupełniający',
- 'orchPage.demo.taskDraft': 'Napisz odpowiedź',
- 'orchPage.demo.taskSync': 'Zsynchronizuj źródło danych',
- 'orchPage.demo.networkTitle': 'Agenci równorzędni',
- 'orchPage.demo.networkSummary': '{peers} połączonych · {sessions} aktywnych podagentów',
- 'orchPage.demo.peer.connected': 'Połączono',
- 'orchPage.demo.peer.connecting': 'Łączenie',
- 'orchPage.demo.peer.idle': 'Bezczynny',
- 'orchPage.demo.peerSessions': '{count} podagentów',
- 'orchPage.demo.chat.user1': 'Skoordynuj kampanię outreachową we wszystkich moich kanałach.',
- 'orchPage.demo.chat.assistant1':
- 'Już się tym zajmuję: uruchamiam 120 agentów na 2 urządzeniach, aby równolegle prowadzić outreach, wzbogacanie i działania uzupełniające.',
- 'orchPage.demo.chat.activity1': 'urządzenie 1 · 100 agentów przekierowuje 1284 rozmowy',
- 'orchPage.demo.chat.activity2': 'urządzenie 2 · 20 agentów wzbogaca 512 kontaktów',
- 'orchPage.demo.chat.activity3': 'redagowanie 640 spersonalizowanych odpowiedzi',
- 'orchPage.demo.chat.assistant2': 'Gotowe. 120 agentów przetworzyło 1796 rozmów w 38 sekund.',
- 'orchPage.demo.chat.composerDisabled': 'Czat jest dostępny z dostępem do Medulli',
- 'orchPage.tasks.nav': 'Zadania',
- 'orchPage.tasks.subtitle': 'Globalna tablica zadań orkiestratora',
- 'orchPage.tasks.colPending': 'Oczekujące',
- 'orchPage.tasks.colActive': 'Aktywne',
- 'orchPage.tasks.colBlocked': 'Zablokowane',
- 'orchPage.tasks.colCompleted': 'Ukończone',
- 'orchPage.overview.core': 'Rdzeń agenta',
- 'orchPage.overview.empty': 'Brak subagentów do wizualizacji',
- 'orchPage.agent.nav': 'Czat',
- 'orchPage.agent.mainTab': 'Główny agent',
- 'orchPage.agent.consciousTab': 'Świadomość',
- 'orchPage.agent.subconsciousTab': 'Podświadomość',
- 'orchPage.agent.modeLabel': 'Umysł agenta',
- 'orchPage.agent.description': 'Rozmawiaj z głównym agentem i obserwuj jego podświadomość',
- 'orchPage.agent.viewSession': 'Zobacz sesję',
- 'orchPage.sessions.railTitle': 'Aktywni agenci',
- 'orchPage.sessions.empty': 'Brak aktywnych agentów',
- 'orchPage.sessions.statusConnected': 'Połączono',
- 'orchPage.sessions.statusDisconnected': 'Rozłączono',
- 'orchPage.sessions.statusWaiting': 'Oczekiwanie na dane',
- 'orchPage.session.runtime': 'Środowisko',
- 'orchPage.session.directory': 'Katalog',
- 'orchPage.session.runningOn': 'Działa na',
- 'orchPage.connections.nav': 'Połączenia',
- 'orchPage.connections.title': 'Połączeni agenci',
- 'orchPage.connections.description':
- 'Partnerzy, z którymi koordynuje się Twój agent: rozwiń jednego, aby zobaczyć swoje sesje z nim',
- 'orchPage.connections.empty': 'Brak połączeń.',
- 'orchPage.connections.emptyCta': 'Dodaj połączenie',
- 'orchPage.connections.statContacts': 'Połączenia',
- 'orchPage.connections.statPending': 'Oczekujące',
- 'orchPage.connections.statSessions': 'Sesje',
- 'orchPage.connections.sessionCount': '{n} sesji',
- 'orchPage.connections.noSessions': 'Brak sesji',
- 'orchPage.connections.messageCount': '{n} wiadomości',
- 'orchPage.connections.back': 'Połączenia',
- 'orchPage.connections.replyPlaceholder': 'Odpowiedz…',
- 'orchPage.connections.initTitle': 'Zainicjuj agenta lub instancję',
- 'orchPage.connections.initDesc':
- 'Uruchom nowego subagenta do pracy u twojego boku. Otwórz czat agenta i opisz rolę, cel oraz narzędzia: OpenHuman udostępni dedykowaną instancję, którą pokierujesz stąd.',
- 'orchPage.connections.initCta': 'Zacznij w czacie',
- 'orchPage.connections.status.needsYou': 'Wymaga Ciebie',
- 'orchPage.connections.status.running': 'Uruchomione',
- 'orchPage.connections.status.idle': 'Bezczynny',
- 'orchPage.connections.status.done': 'Gotowe',
- 'orchPage.connections.status.error': 'Błąd',
- 'orchPage.connections.pendingHint': 'Oczekiwanie na akceptację',
- 'orchPage.discover.nav': 'Odkrywaj',
- 'orchPage.discover.linkAction': 'Dodaj',
- 'orchPage.discover.identityTitle': 'Twoja wykrywalność',
- 'orchPage.discover.notDiscoverableGuide':
- 'Zarejestruj @handle, aby inni agenci mogli Cię znaleźć i napisać do Ciebie.',
- 'orchPage.discover.linkTitle': 'Połącz nowego agenta',
- 'orchPage.discover.linkDescription':
- 'Wklej identyfikator agenta, aby wysłać prośbę o połączenie.',
- 'orchPage.discover.noRequests': 'Brak przychodzących próśb.',
- 'orchPage.usage.nav': 'Wykorzystanie',
- 'orchPage.usage.connections': 'Połączenia',
- 'orchPage.usage.balance': 'Saldo kredytu',
- 'orchPage.usage.balanceHint': 'Promocja + doładowanie',
- 'orchPage.usage.cycleSpend': 'Wydatki w cyklu',
- 'orchPage.usage.ofBudget': 'z',
- 'orchPage.usage.inferenceCalls': 'Wywołania modelu',
- 'orchPage.usage.integrationCalls': 'Wywołania integracji',
- 'orchPage.usage.tokensSaved': 'Zaoszczędzone tokeny',
- 'orchPage.usage.saved': 'zaoszczędzono',
- 'orchPage.usage.footnote': 'Wykorzystanie odzwierciedla bieżący cykl rozliczeniowy.',
+
'nav.wallet': 'Portfel',
'nav.avatarMenu.account': 'Konto',
'nav.avatarMenu.billing': 'Rozliczenia',
@@ -468,85 +354,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': 'Coś poszło nie tak. Spróbuj ponownie.',
'brain.tabs.sources': 'Źródła',
'brain.tabs.sync': 'Synchronizacja',
- 'brain.tabs.orchestration': 'Orkiestracja',
- 'tinyplaceOrchestration.title': 'Przekaźnik TinyPlace',
- 'tinyplaceOrchestration.subtitle': 'Przypięte kanały agentów i czaty sesji aplikacji',
- 'tinyplaceOrchestration.refresh': 'Odśwież',
- 'tinyplaceOrchestration.newInstance': 'Nowa instancja',
- 'tinyplaceOrchestration.newInstanceSoon': 'Wkrótce',
- 'tinyplaceOrchestration.pinned': 'Przypięte',
- 'tinyplaceOrchestration.sessions': 'Sesje',
- 'tinyplaceOrchestration.contacts': 'Kontakty',
- 'tinyplaceOrchestration.noContacts': 'Brak kontaktów.',
- 'tinyplaceOrchestration.newSession': 'Nowa sesja',
- 'tinyplaceOrchestration.otherSessions': 'Inne sesje',
- 'tinyplaceOrchestration.loading': 'Ładowanie czatów TinyPlace…',
- 'tinyplaceOrchestration.paymentRequired': 'Dostęp do TinyPlace wymaga płatności.',
- 'tinyplaceOrchestration.failedToLoad': 'Nie udało się załadować czatów TinyPlace',
- 'tinyplaceOrchestration.noSessions': 'Brak sesji aplikacji TinyPlace.',
- 'tinyplaceOrchestration.noMessages': 'Brak wiadomości w tym czacie.',
- 'tinyplaceOrchestration.active': 'Aktywna',
- 'tinyplaceOrchestration.inactive': 'Nieaktywna',
- 'tinyplaceOrchestration.encryptedBody': 'Zaszyfrowana wiadomość TinyPlace',
- 'tinyplaceOrchestration.unknownSender': 'Nieznany nadawca',
- 'tinyplaceOrchestration.master.title': 'Agent / człowiek',
- 'tinyplaceOrchestration.master.subtitle': 'Czat główny',
- 'tinyplaceOrchestration.master.preview': 'Bezpośrednia koordynacja między tobą a OpenHuman.',
- 'tinyplaceOrchestration.subconscious.title': 'Podświadomość',
- 'tinyplaceOrchestration.subconscious.subtitle': 'Wewnętrzne czaty agentów',
- 'tinyplaceOrchestration.subconscious.preview': 'Koordynacja agentów w tle i pętle pamięci.',
- 'tinyplaceOrchestration.session.subtitle': 'Sesja aplikacji TinyPlace',
- 'tinyplaceOrchestration.pairing.linkLabel': 'Połącz sesję',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': 'Wklej ID agenta sesji',
- 'tinyplaceOrchestration.pairing.linkAction': 'Połącz',
- 'tinyplaceOrchestration.pairing.requests': 'Prośby kontaktowe',
- 'tinyplaceOrchestration.pairing.accept': 'Akceptuj',
- 'tinyplaceOrchestration.pairing.decline': 'Odrzuć',
- 'tinyplaceOrchestration.pairing.block': 'Blokuj',
- 'tinyplaceOrchestration.pairing.linked': 'Połączona',
- 'tinyplaceOrchestration.pairing.pending': 'Oczekuje',
- 'tinyplaceOrchestration.pairing.unlinked': 'Niepołączona',
- 'tinyplaceOrchestration.pairing.incoming': 'Przychodzące',
- 'tinyplaceOrchestration.pairing.outgoing': 'Wychodzące',
- 'tinyplaceOrchestration.master.you': 'Ty',
- 'tinyplaceOrchestration.composer.placeholder': 'Wiadomość do OpenHuman…',
- 'tinyplaceOrchestration.composer.send': 'Wyślij',
- 'tinyplaceOrchestration.composer.sendFailed': 'Nie udało się wysłać wiadomości',
- 'tinyplaceOrchestration.steering.label': 'Sterowanie',
- 'tinyplaceOrchestration.relay.staging': 'Staging',
- 'tinyplaceOrchestration.relay.prod': 'Produkcja',
- 'tinyplaceOrchestration.identity.loading': 'Ładowanie tożsamości…',
- 'tinyplaceOrchestration.identity.noHandle': 'Brak @handle',
- 'tinyplaceOrchestration.identity.copy': 'Kopiuj',
- 'tinyplaceOrchestration.identity.copied': 'Skopiowano',
- 'tinyplaceOrchestration.identity.discoverable': 'Wykrywalny',
- 'tinyplaceOrchestration.identity.undiscoverable': 'Niewykrywalny',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'Opublikuj swoją kartę katalogu i klucz szyfrowania, aby inni mogli do Ciebie pisać.',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'Ustaw jako wykrywalny',
- 'tinyplaceOrchestration.identity.republish': 'Opublikuj ponownie klucze',
- 'tinyplaceOrchestration.identity.publishing': 'Publikowanie…',
- 'tinyplaceOrchestration.identity.publishFailed': 'Publikacja nie powiodła się: spróbuj ponownie',
- 'tinyplaceOrchestration.identity.card': 'Karta katalogu',
- 'tinyplaceOrchestration.identity.key': 'Klucz szyfrowania',
- 'tinyplaceOrchestration.identity.published': 'Opublikowano',
- 'tinyplaceOrchestration.identity.notPublished': 'Nie opublikowano',
- 'tinyplaceOrchestration.roster.instances': 'Instancje',
- 'tinyplaceOrchestration.roster.empty': 'Brak instancji agentów',
- 'tinyplaceOrchestration.roster.other': 'Inne',
- 'tinyplaceOrchestration.status.running': 'Działa',
- 'tinyplaceOrchestration.status.idle': 'Bezczynny',
- 'tinyplaceOrchestration.status.waitingApproval': 'Oczekuje na zatwierdzenie',
- 'tinyplaceOrchestration.status.errored': 'Błąd',
- 'tinyplaceOrchestration.status.stopped': 'Zatrzymany',
- 'tinyplaceOrchestration.attention.title': 'Wymaga uwagi',
- 'tinyplaceOrchestration.attention.empty': 'Wszystko na bieżąco',
- 'tinyplaceOrchestration.attention.unread': 'Nieprzeczytane wiadomości',
- 'tinyplaceOrchestration.attention.review': 'Sprawdź',
- 'tinyplaceOrchestration.attention.open': 'Otwórz',
- 'tinyplaceOrchestration.attention.kind.approval': 'Zatwierdzenie',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'Wymaga danych',
- 'tinyplaceOrchestration.attention.kind.unread': 'Nieprzeczytane',
'brain.empty': 'Twój mózg jest na razie pusty: połącz źródło, aby zacząć budować pamięć.',
'brain.error': 'Nie udało się załadować Twojego mózgu. Spróbuj ponownie.',
'common.cancel': 'Anuluj',
@@ -2931,10 +2738,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'Uruchom modele na własnej maszynie z Ollamą. Pełna prywatność, wymaga konfiguracji.',
'backend.ramRecommended': 'Zalecane 16 GB+ RAM',
- 'tinyplaceOrchestration.subconsciousBadge': 'Podświadomość · sterowanie',
- 'tinyplaceOrchestration.steeringHeader.current': 'Aktywna dyrektywa',
- 'tinyplaceOrchestration.steeringHeader.none': 'Brak aktywnej dyrektywy',
- 'tinyplaceOrchestration.steeringHeader.expires': 'wygasa po {n} cyklach',
'actionable.complete': 'Zakończ',
'actionable.dismiss': 'Odrzuć',
'actionable.snooze': 'Odłóż',
@@ -5289,10 +5092,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'Automatycznie zatwierdzaj wszystkie działania',
'settings.agentAccess.autoApproveAll.desc':
'Po włączeniu agent będzie wykonywać wszystkie działania bez wcześniejszego proszenia o Twoją zgodę. Obejmuje to zapis plików, polecenia powłoki, żądania sieciowe i wszelkie inne efekty uboczne. Twarde blokady bezpieczeństwa (katalogi poświadczeń, wewnętrzne ścieżki przestrzeni roboczej) nadal obowiązują.',
- 'settings.agentAccess.tinyplaceAutopilot.title': 'Autonomiczny agent tiny.place',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'Pozwól OpenHuman działać samodzielnie na tiny.place. Zgodnie z harmonogramem szuka wartościowej pracy (najpierw otwartych nagród), wykonuje zadania pasujące do jego umiejętności i działa z użyciem Twojej tożsamości. Działa bez nadzoru i może wydawać środki, więc podczas testów używaj devnet. Domyślnie wyłączone.',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'Uruchamiaj automatycznie',
'settings.agentAccess.timeout.label': 'Limit czasu akcji',
'settings.agentAccess.timeout.desc':
'Jak długo pojedyncze narzędzie lub akcja może działać przed anulowaniem. Zwiększ tę wartość, jeśli duży lokalny model jest przerywany, zanim zakończy odpowiedź.',
@@ -6700,9 +6499,7 @@ const messages: TranslationMap = {
'notch.speaking': 'Mówię…',
'notch.transcribing': 'Transkrybuję…',
'notch.executing': 'Wykonuję…',
- 'memory.tab.orchestration': 'Orkiestracja',
- 'memory.tab.orchestrationDescription':
- 'Uruchamiaj przepływy pracy z wieloma agentami: rozdziel pytanie między równoległych agentów, porównaj ich ustalenia i obserwuj, jak każda faza kończy się jedną zsyntetyzowaną odpowiedzią.',
+
'orchestration.subtitle':
'Uruchom przepływ pracy z wieloma agentami, obserwuj postęp jego faz i przeczytaj zsyntetyzowany wynik.',
'orchestration.loading': 'Ładowanie przepływów pracy…',
@@ -6850,10 +6647,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'Twój budżet osadzeń został wyczerpany, więc nowe treści nie są już dodawane do pamięci. Skonfiguruj lokalne osadzenia lub dodaj własny klucz API, aby wznowić.',
'memoryBudget.cta': 'Skonfiguruj osadzenia',
- 'tinyplaceSunset.title': 'Tiny Place znika z aplikacji',
- 'tinyplaceSunset.message':
- 'Aby dalej korzystać z tiny.place, wejdź na tiny.place. Po 31 sierpnia 2026 r. zostanie usunięty z aplikacji.',
- 'tinyplaceSunset.cta': 'Otwórz tiny.place',
'userErrors.scope.memory': 'Pamięć',
// Code block chrome
diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts
index 25b50338b0..3272e87acb 100644
--- a/app/src/lib/i18n/pt.ts
+++ b/app/src/lib/i18n/pt.ts
@@ -316,126 +316,11 @@ const messages: TranslationMap = {
'nav.flows': 'Fluxos de trabalho',
'nav.workflowRuns': 'Execuções de fluxos',
'nav.workflowDiscoveries': 'Descobrir fluxos',
- 'nav.orchestration': 'Orquestração',
- 'orchestration.cloudUnreachable':
- 'Cérebro na nuvem inacessível: exibindo a visualização em cache.',
- 'orchPage.subtitle': 'Coordene seu agente principal',
- 'orchPage.group.agent': 'Agente',
- 'orchPage.group.network': 'Rede',
- 'orchPage.group.insights': 'Insights',
- 'orchPage.overview.nav': 'Grafo de agentes',
- 'orchPage.overview.desc': 'Um mapa ao vivo do seu agente e dos subagentes que ele coordena.',
- 'orchPage.network.desc': 'Agentes pares aos quais você está conectado, descoberta e uso.',
+
'wallet.tabs.balance': 'Saldo da carteira',
'wallet.tabs.recovery': 'Recuperação',
'wallet.ariaLabel': 'Visualizações da carteira',
- 'orchPage.medulla.nav': 'Visão geral',
- 'orchPage.medulla.badge': 'Em breve',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'O modelo de orquestração da OpenHuman',
- 'orchPage.medulla.body':
- 'O Medulla é o LLM próprio da OpenHuman, projetado para orquestrar milhares de agentes de uma só vez, com uma janela de contexto de 10 milhões de tokens e uma orquestração de custo radicalmente baixo.',
- 'orchPage.medulla.featAgents': 'Milhares de agentes',
- 'orchPage.medulla.featContext': 'Contexto de 10M de tokens',
- 'orchPage.medulla.featCost': 'Orquestração de baixo custo',
- 'orchPage.medulla.subscriberTitle': 'Assinantes da OpenHuman',
- 'orchPage.medulla.subscriberNote':
- 'Quando o Medulla for lançado, será exclusivo para assinantes da OpenHuman.',
- 'orchPage.medulla.subscriberCta': 'Obter uma assinatura',
- 'orchPage.medulla.discordTitle': 'Entre no Discord',
- 'orchPage.medulla.earlyAccess':
- 'Quer acesso antecipado? Entre no nosso Discord e garanta um convite.',
- 'orchPage.medulla.cta': 'Entre no nosso Discord',
- 'orchPage.demo.banner': 'Este é um exemplo de como a orquestração ficaria em grande escala.',
- 'orchPage.demo.device': 'Dispositivo',
- 'orchPage.demo.taskRoute': 'Rotear solicitação recebida',
- 'orchPage.demo.taskSummarize': 'Resumir conversa',
- 'orchPage.demo.taskEnrich': 'Enriquecer registro de contato',
- 'orchPage.demo.taskSchedule': 'Agendar acompanhamento',
- 'orchPage.demo.taskDraft': 'Rascunhar resposta',
- 'orchPage.demo.taskSync': 'Sincronizar fonte de dados',
- 'orchPage.demo.networkTitle': 'Agentes pares',
- 'orchPage.demo.networkSummary': '{peers} conectados · {sessions} subagentes ativos',
- 'orchPage.demo.peer.connected': 'Conectado',
- 'orchPage.demo.peer.connecting': 'Conectando',
- 'orchPage.demo.peer.idle': 'Ocioso',
- 'orchPage.demo.peerSessions': '{count} subagentes',
- 'orchPage.demo.chat.user1': 'Coordene a campanha de divulgação em todos os meus canais.',
- 'orchPage.demo.chat.assistant1':
- 'Deixa comigo: iniciando 120 agentes em 2 dispositivos para executar divulgação, enriquecimento e acompanhamentos em paralelo.',
- 'orchPage.demo.chat.activity1': 'dispositivo 1 · 100 agentes roteando 1.284 conversas',
- 'orchPage.demo.chat.activity2': 'dispositivo 2 · 20 agentes enriquecendo 512 contatos',
- 'orchPage.demo.chat.activity3': 'rascunhando 640 respostas personalizadas',
- 'orchPage.demo.chat.assistant2':
- 'Concluído. 120 agentes processaram 1.796 conversas em 38 segundos.',
- 'orchPage.demo.chat.composerDisabled': 'O chat está disponível com acesso ao Medulla',
- 'orchPage.tasks.nav': 'Tarefas',
- 'orchPage.tasks.subtitle': 'O quadro de tarefas global do orquestrador',
- 'orchPage.tasks.colPending': 'Pendente',
- 'orchPage.tasks.colActive': 'Ativo',
- 'orchPage.tasks.colBlocked': 'Bloqueado',
- 'orchPage.tasks.colCompleted': 'Concluído',
- 'orchPage.overview.core': 'Núcleo do agente',
- 'orchPage.overview.empty': 'Ainda não há subagentes para visualizar',
- 'orchPage.agent.nav': 'Chat',
- 'orchPage.agent.mainTab': 'Agente principal',
- 'orchPage.agent.consciousTab': 'Consciente',
- 'orchPage.agent.subconsciousTab': 'Subconsciente',
- 'orchPage.agent.modeLabel': 'Mente do agente',
- 'orchPage.agent.description': 'Converse com o agente principal e observe seu subconsciente',
- 'orchPage.agent.viewSession': 'Ver sessão',
- 'orchPage.sessions.railTitle': 'Agentes ativos',
- 'orchPage.sessions.empty': 'Ainda não há agentes ativos',
- 'orchPage.sessions.statusConnected': 'Conectado',
- 'orchPage.sessions.statusDisconnected': 'Desconectado',
- 'orchPage.sessions.statusWaiting': 'Aguardando entrada',
- 'orchPage.session.runtime': 'Tempo de execução',
- 'orchPage.session.directory': 'Diretório',
- 'orchPage.session.runningOn': 'Em execução em',
- 'orchPage.connections.nav': 'Conexões',
- 'orchPage.connections.title': 'Agentes vinculados',
- 'orchPage.connections.description':
- 'Pares com quem seu agente se coordena: expanda um para ver suas sessões com ele',
- 'orchPage.connections.empty': 'Ainda não há conexões.',
- 'orchPage.connections.emptyCta': 'Adicionar uma conexão',
- 'orchPage.connections.statContacts': 'Conexões',
- 'orchPage.connections.statPending': 'Pendente',
- 'orchPage.connections.statSessions': 'Sessões',
- 'orchPage.connections.sessionCount': '{n} sessões',
- 'orchPage.connections.noSessions': 'Sem sessões',
- 'orchPage.connections.messageCount': '{n} mensagens',
- 'orchPage.connections.back': 'Conexões',
- 'orchPage.connections.replyPlaceholder': 'Responder…',
- 'orchPage.connections.initTitle': 'Inicializar um agente ou uma instância',
- 'orchPage.connections.initDesc':
- 'Crie um novo subagente para trabalhar ao seu lado. Abra o chat do agente e descreva o papel, o objetivo e as ferramentas: o OpenHuman provisiona uma instância dedicada que você controla daqui.',
- 'orchPage.connections.initCta': 'Começar no chat',
- 'orchPage.connections.status.needsYou': 'Precisa de você',
- 'orchPage.connections.status.running': 'Em execução',
- 'orchPage.connections.status.idle': 'Inativo',
- 'orchPage.connections.status.done': 'Concluído',
- 'orchPage.connections.status.error': 'Erro',
- 'orchPage.connections.pendingHint': 'Aguardando aceitação',
- 'orchPage.discover.nav': 'Descobrir',
- 'orchPage.discover.linkAction': 'Adicionar',
- 'orchPage.discover.identityTitle': 'Sua visibilidade',
- 'orchPage.discover.notDiscoverableGuide':
- 'Registre um @handle para que outros agentes possam encontrá-lo e enviar mensagens.',
- 'orchPage.discover.linkTitle': 'Vincular um novo agente',
- 'orchPage.discover.linkDescription':
- 'Cole um ID de agente para enviar uma solicitação de conexão.',
- 'orchPage.discover.noRequests': 'Nenhuma solicitação recebida.',
- 'orchPage.usage.nav': 'Uso',
- 'orchPage.usage.connections': 'Conexões',
- 'orchPage.usage.balance': 'Saldo de crédito',
- 'orchPage.usage.balanceHint': 'Promocional + recarga',
- 'orchPage.usage.cycleSpend': 'Gasto do ciclo',
- 'orchPage.usage.ofBudget': 'de',
- 'orchPage.usage.inferenceCalls': 'Chamadas ao modelo',
- 'orchPage.usage.integrationCalls': 'Chamadas de integração',
- 'orchPage.usage.tokensSaved': 'Tokens economizados',
- 'orchPage.usage.saved': 'economizado',
- 'orchPage.usage.footnote': 'O uso reflete seu ciclo de faturamento atual.',
+
'nav.wallet': 'Carteira',
'nav.avatarMenu.account': 'Conta',
'nav.avatarMenu.billing': 'Faturamento',
@@ -463,86 +348,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': 'Algo deu errado. Tente novamente.',
'brain.tabs.sources': 'Fontes',
'brain.tabs.sync': 'Sincronização',
- 'brain.tabs.orchestration': 'Orquestração',
- 'tinyplaceOrchestration.title': 'Relay TinyPlace',
- 'tinyplaceOrchestration.subtitle': 'Canais de agentes fixados e chats de sessões do app',
- 'tinyplaceOrchestration.refresh': 'Atualizar',
- 'tinyplaceOrchestration.newInstance': 'Nova instância',
- 'tinyplaceOrchestration.newInstanceSoon': 'Em breve',
- 'tinyplaceOrchestration.pinned': 'Fixados',
- 'tinyplaceOrchestration.sessions': 'Sessões',
- 'tinyplaceOrchestration.contacts': 'Contactos',
- 'tinyplaceOrchestration.noContacts': 'Ainda sem contactos.',
- 'tinyplaceOrchestration.newSession': 'Nova sessão',
- 'tinyplaceOrchestration.otherSessions': 'Outras sessões',
- 'tinyplaceOrchestration.loading': 'Carregando chats do TinyPlace…',
- 'tinyplaceOrchestration.paymentRequired': 'O acesso ao TinyPlace requer pagamento.',
- 'tinyplaceOrchestration.failedToLoad': 'Falha ao carregar chats do TinyPlace',
- 'tinyplaceOrchestration.noSessions': 'Ainda não há sessões de app do TinyPlace.',
- 'tinyplaceOrchestration.noMessages': 'Ainda não há mensagens neste chat.',
- 'tinyplaceOrchestration.active': 'Ativa',
- 'tinyplaceOrchestration.inactive': 'Inativa',
- 'tinyplaceOrchestration.encryptedBody': 'Mensagem criptografada do TinyPlace',
- 'tinyplaceOrchestration.unknownSender': 'Remetente desconhecido',
- 'tinyplaceOrchestration.master.title': 'Agente / humano',
- 'tinyplaceOrchestration.master.subtitle': 'Chat mestre',
- 'tinyplaceOrchestration.master.preview': 'Coordenação direta entre você e o OpenHuman.',
- 'tinyplaceOrchestration.subconscious.title': 'Subconsciente',
- 'tinyplaceOrchestration.subconscious.subtitle': 'Chats internos de agentes',
- 'tinyplaceOrchestration.subconscious.preview':
- 'Coordenação de agentes em segundo plano e loops de memória.',
- 'tinyplaceOrchestration.session.subtitle': 'Sessão de app do TinyPlace',
- 'tinyplaceOrchestration.pairing.linkLabel': 'Vincular sessão',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': 'Cole o ID do agente da sessão',
- 'tinyplaceOrchestration.pairing.linkAction': 'Vincular',
- 'tinyplaceOrchestration.pairing.requests': 'Solicitações de contato',
- 'tinyplaceOrchestration.pairing.accept': 'Aceitar',
- 'tinyplaceOrchestration.pairing.decline': 'Recusar',
- 'tinyplaceOrchestration.pairing.block': 'Bloquear',
- 'tinyplaceOrchestration.pairing.linked': 'Vinculada',
- 'tinyplaceOrchestration.pairing.pending': 'Pendente',
- 'tinyplaceOrchestration.pairing.unlinked': 'Sem vínculo',
- 'tinyplaceOrchestration.pairing.incoming': 'Entrada',
- 'tinyplaceOrchestration.pairing.outgoing': 'Saída',
- 'tinyplaceOrchestration.master.you': 'Você',
- 'tinyplaceOrchestration.composer.placeholder': 'Mensagem para o OpenHuman…',
- 'tinyplaceOrchestration.composer.send': 'Enviar',
- 'tinyplaceOrchestration.composer.sendFailed': 'Falha ao enviar mensagem',
- 'tinyplaceOrchestration.steering.label': 'Direção',
- 'tinyplaceOrchestration.relay.staging': 'Staging',
- 'tinyplaceOrchestration.relay.prod': 'Produção',
- 'tinyplaceOrchestration.identity.loading': 'Carregando identidade…',
- 'tinyplaceOrchestration.identity.noHandle': 'Ainda sem @handle',
- 'tinyplaceOrchestration.identity.copy': 'Copiar',
- 'tinyplaceOrchestration.identity.copied': 'Copiado',
- 'tinyplaceOrchestration.identity.discoverable': 'Descobrível',
- 'tinyplaceOrchestration.identity.undiscoverable': 'Não descobrível',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'Publique seu cartão de diretório e sua chave de criptografia para que outros agentes possam lhe enviar mensagens.',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'Tornar descobrível',
- 'tinyplaceOrchestration.identity.republish': 'Republicar chaves',
- 'tinyplaceOrchestration.identity.publishing': 'Publicando…',
- 'tinyplaceOrchestration.identity.publishFailed': 'Falha ao publicar: tente novamente',
- 'tinyplaceOrchestration.identity.card': 'Cartão de diretório',
- 'tinyplaceOrchestration.identity.key': 'Chave de criptografia',
- 'tinyplaceOrchestration.identity.published': 'Publicado',
- 'tinyplaceOrchestration.identity.notPublished': 'Não publicado',
- 'tinyplaceOrchestration.roster.instances': 'Instâncias',
- 'tinyplaceOrchestration.roster.empty': 'Nenhuma instância de agente ainda',
- 'tinyplaceOrchestration.roster.other': 'Outros',
- 'tinyplaceOrchestration.status.running': 'Em execução',
- 'tinyplaceOrchestration.status.idle': 'Inativo',
- 'tinyplaceOrchestration.status.waitingApproval': 'Aguardando aprovação',
- 'tinyplaceOrchestration.status.errored': 'Com erro',
- 'tinyplaceOrchestration.status.stopped': 'Parado',
- 'tinyplaceOrchestration.attention.title': 'Precisa de você',
- 'tinyplaceOrchestration.attention.empty': 'Tudo em dia',
- 'tinyplaceOrchestration.attention.unread': 'Mensagens não lidas',
- 'tinyplaceOrchestration.attention.review': 'Revisar',
- 'tinyplaceOrchestration.attention.open': 'Abrir',
- 'tinyplaceOrchestration.attention.kind.approval': 'Aprovação',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'Precisa de resposta',
- 'tinyplaceOrchestration.attention.kind.unread': 'Não lidas',
'brain.empty':
'Seu cérebro está vazio por enquanto: conecte uma fonte para começar a construir a memória.',
'brain.error': 'Não foi possível carregar seu cérebro. Tente novamente.',
@@ -2948,10 +2753,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'Rode modelos na sua própria máquina usando Ollama. Total privacidade, requer configuração.',
'backend.ramRecommended': '16GB+ de RAM recomendado',
- 'tinyplaceOrchestration.subconsciousBadge': 'Subconsciente · direção',
- 'tinyplaceOrchestration.steeringHeader.current': 'Diretriz ativa',
- 'tinyplaceOrchestration.steeringHeader.none': 'Nenhuma diretriz ativa',
- 'tinyplaceOrchestration.steeringHeader.expires': 'expira após {n} ciclos',
'actionable.complete': 'Concluir',
'actionable.dismiss': 'Dispensar',
'actionable.snooze': 'Adiar',
@@ -5287,10 +5088,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'Aprovar automaticamente todas as ações',
'settings.agentAccess.autoApproveAll.desc':
'Quando ativado, o agente executará todas as ações sem pedir sua aprovação antes. Isso inclui gravação de arquivos, comandos de shell, solicitações de rede e qualquer outro efeito colateral. Os bloqueios de segurança rígidos (diretórios de credenciais, caminhos internos do espaço de trabalho) continuam em vigor.',
- 'settings.agentAccess.tinyplaceAutopilot.title': 'Agente autônomo do tiny.place',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'Deixe o OpenHuman agir sozinho no tiny.place. De forma agendada, ele busca trabalhos relevantes (priorizando recompensas abertas), executa o que combina com suas habilidades e age com a sua identidade. Funciona sem supervisão e pode gastar, então mantenha-o na devnet durante os testes. Desativado por padrão.',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'Executar automaticamente',
'settings.agentAccess.timeout.label': 'Tempo limite da ação',
'settings.agentAccess.timeout.desc':
'Por quanto tempo uma única ferramenta ou ação pode ser executada antes de ser cancelada. Aumente este valor se um modelo local grande for interrompido antes de terminar a resposta.',
@@ -6713,9 +6510,7 @@ const messages: TranslationMap = {
'notch.speaking': 'Falando…',
'notch.transcribing': 'Transcrevendo…',
'notch.executing': 'Executando…',
- 'memory.tab.orchestration': 'Orquestração',
- 'memory.tab.orchestrationDescription':
- 'Execute fluxos de trabalho com múltiplos agentes: distribua uma pergunta entre agentes paralelos, confronte seus resultados e veja cada fase culminar em uma única resposta sintetizada.',
+
'orchestration.subtitle':
'Inicie um fluxo de trabalho com múltiplos agentes, acompanhe o progresso de suas fases e leia o resultado sintetizado.',
'orchestration.loading': 'Carregando fluxos de trabalho…',
@@ -6863,10 +6658,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'Seu orçamento de embeddings acabou, então novos conteúdos não estão mais sendo adicionados à memória. Configure embeddings locais ou adicione sua própria chave de API para retomar.',
'memoryBudget.cta': 'Configurar embeddings',
- 'tinyplaceSunset.title': 'Tiny Place está saindo do app',
- 'tinyplaceSunset.message':
- 'Para continuar usando o tiny.place, acesse tiny.place. Ele será removido do app depois de 31 de agosto de 2026.',
- 'tinyplaceSunset.cta': 'Abrir tiny.place',
'userErrors.scope.memory': 'Memória',
// Code block chrome
diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts
index 715bba5834..fa1fa050df 100644
--- a/app/src/lib/i18n/ru.ts
+++ b/app/src/lib/i18n/ru.ts
@@ -317,125 +317,11 @@ const messages: TranslationMap = {
'nav.flows': 'Рабочие процессы',
'nav.workflowRuns': 'Запуски процессов',
'nav.workflowDiscoveries': 'Найти процессы',
- 'nav.orchestration': 'Оркестрация',
- 'orchestration.cloudUnreachable':
- 'Облачный мозг недоступен: показано кэшированное представление.',
- 'orchPage.subtitle': 'Координируйте вашего главного агента',
- 'orchPage.group.agent': 'Агент',
- 'orchPage.group.network': 'Сеть',
- 'orchPage.group.insights': 'Аналитика',
- 'orchPage.overview.nav': 'Граф агентов',
- 'orchPage.overview.desc': 'Живая карта вашего агента и субагентов, которых он координирует.',
- 'orchPage.network.desc':
- 'Одноранговые агенты, к которым вы подключены, обнаружение и использование.',
+
'wallet.tabs.balance': 'Баланс кошелька',
'wallet.tabs.recovery': 'Восстановление',
'wallet.ariaLabel': 'Представления кошелька',
- 'orchPage.medulla.nav': 'Обзор',
- 'orchPage.medulla.badge': 'Скоро',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'Модель оркестрации OpenHuman',
- 'orchPage.medulla.body':
- 'Medulla представляет собой собственную большую языковую модель OpenHuman, спроектированную для оркестрации тысяч агентов одновременно, с окном контекста в 10 миллионов токенов и радикально низкой стоимостью оркестрации.',
- 'orchPage.medulla.featAgents': 'Тысячи агентов',
- 'orchPage.medulla.featContext': 'Контекст на 10M токенов',
- 'orchPage.medulla.featCost': 'Недорогая оркестрация',
- 'orchPage.medulla.subscriberTitle': 'Подписчики OpenHuman',
- 'orchPage.medulla.subscriberNote':
- 'Когда Medulla выйдет, она будет доступна только подписчикам OpenHuman.',
- 'orchPage.medulla.subscriberCta': 'Оформить подписку',
- 'orchPage.medulla.discordTitle': 'Присоединяйтесь к Discord',
- 'orchPage.medulla.earlyAccess':
- 'Хотите получить доступ раньше? Присоединяйтесь к нашему Discord и получите приглашение.',
- 'orchPage.medulla.cta': 'Присоединиться к нашему Discord',
- 'orchPage.demo.banner': 'Это пример того, как оркестрация выглядела бы в масштабе.',
- 'orchPage.demo.device': 'Устройство',
- 'orchPage.demo.taskRoute': 'Маршрутизировать входящий запрос',
- 'orchPage.demo.taskSummarize': 'Обобщить разговор',
- 'orchPage.demo.taskEnrich': 'Обогатить запись контакта',
- 'orchPage.demo.taskSchedule': 'Запланировать напоминание',
- 'orchPage.demo.taskDraft': 'Составить ответ',
- 'orchPage.demo.taskSync': 'Синхронизировать источник данных',
- 'orchPage.demo.networkTitle': 'Одноранговые агенты',
- 'orchPage.demo.networkSummary': '{peers} подключено · {sessions} активных субагентов',
- 'orchPage.demo.peer.connected': 'Подключено',
- 'orchPage.demo.peer.connecting': 'Подключение',
- 'orchPage.demo.peer.idle': 'Простой',
- 'orchPage.demo.peerSessions': '{count} субагентов',
- 'orchPage.demo.chat.user1': 'Скоординируй кампанию по охвату по всем моим каналам.',
- 'orchPage.demo.chat.assistant1':
- 'Приступаю: запускаю 120 агентов на 2 устройствах, чтобы параллельно выполнять охват, обогащение и напоминания.',
- 'orchPage.demo.chat.activity1': 'устройство 1 · 100 агентов маршрутизируют 1 284 разговора',
- 'orchPage.demo.chat.activity2': 'устройство 2 · 20 агентов обогащают 512 контактов',
- 'orchPage.demo.chat.activity3': 'составление 640 персонализированных ответов',
- 'orchPage.demo.chat.assistant2': 'Готово. 120 агентов обработали 1 796 разговоров за 38 секунд.',
- 'orchPage.demo.chat.composerDisabled': 'Чат доступен при наличии доступа к Medulla',
- 'orchPage.tasks.nav': 'Задачи',
- 'orchPage.tasks.subtitle': 'Глобальная доска задач оркестратора',
- 'orchPage.tasks.colPending': 'Ожидание',
- 'orchPage.tasks.colActive': 'Активно',
- 'orchPage.tasks.colBlocked': 'Заблокировано',
- 'orchPage.tasks.colCompleted': 'Завершено',
- 'orchPage.overview.core': 'Ядро агента',
- 'orchPage.overview.empty': 'Пока нет субагентов для визуализации',
- 'orchPage.agent.nav': 'Чат',
- 'orchPage.agent.mainTab': 'Главный агент',
- 'orchPage.agent.consciousTab': 'Сознание',
- 'orchPage.agent.subconsciousTab': 'Подсознание',
- 'orchPage.agent.modeLabel': 'Разум агента',
- 'orchPage.agent.description': 'Общайтесь с главным агентом и наблюдайте за его подсознанием',
- 'orchPage.agent.viewSession': 'Показать сессию',
- 'orchPage.sessions.railTitle': 'Активные агенты',
- 'orchPage.sessions.empty': 'Пока нет активных агентов',
- 'orchPage.sessions.statusConnected': 'Подключено',
- 'orchPage.sessions.statusDisconnected': 'Отключено',
- 'orchPage.sessions.statusWaiting': 'Ожидание ввода',
- 'orchPage.session.runtime': 'Среда выполнения',
- 'orchPage.session.directory': 'Каталог',
- 'orchPage.session.runningOn': 'Выполняется на',
- 'orchPage.connections.nav': 'Связи',
- 'orchPage.connections.title': 'Связанные агенты',
- 'orchPage.connections.description':
- 'Партнёры, с которыми координируется ваш агент: разверните одного, чтобы увидеть ваши сессии с ним',
- 'orchPage.connections.empty': 'Пока нет связей.',
- 'orchPage.connections.emptyCta': 'Добавить связь',
- 'orchPage.connections.statContacts': 'Связи',
- 'orchPage.connections.statPending': 'Ожидание',
- 'orchPage.connections.statSessions': 'Сессии',
- 'orchPage.connections.sessionCount': '{n} сессий',
- 'orchPage.connections.noSessions': 'Нет сессий',
- 'orchPage.connections.messageCount': '{n} сообщений',
- 'orchPage.connections.back': 'Связи',
- 'orchPage.connections.replyPlaceholder': 'Ответить…',
- 'orchPage.connections.initTitle': 'Инициализировать агента или экземпляр',
- 'orchPage.connections.initDesc':
- 'Создайте нового субагента для работы рядом с вами. Откройте чат агента и опишите роль, цель и инструменты: OpenHuman подготовит выделенный экземпляр, которым вы управляете отсюда.',
- 'orchPage.connections.initCta': 'Начать в чате',
- 'orchPage.connections.status.needsYou': 'Требует вас',
- 'orchPage.connections.status.running': 'Выполняется',
- 'orchPage.connections.status.idle': 'Неактивно',
- 'orchPage.connections.status.done': 'Готово',
- 'orchPage.connections.status.error': 'Ошибка',
- 'orchPage.connections.pendingHint': 'Ожидает подтверждения',
- 'orchPage.discover.nav': 'Обзор',
- 'orchPage.discover.linkAction': 'Добавить',
- 'orchPage.discover.identityTitle': 'Ваша видимость',
- 'orchPage.discover.notDiscoverableGuide':
- 'Зарегистрируйте @handle, чтобы другие агенты могли найти вас и написать.',
- 'orchPage.discover.linkTitle': 'Связать нового агента',
- 'orchPage.discover.linkDescription': 'Вставьте ID агента, чтобы отправить запрос на связь.',
- 'orchPage.discover.noRequests': 'Нет входящих запросов.',
- 'orchPage.usage.nav': 'Использование',
- 'orchPage.usage.connections': 'Связи',
- 'orchPage.usage.balance': 'Баланс кредитов',
- 'orchPage.usage.balanceHint': 'Промо + пополнение',
- 'orchPage.usage.cycleSpend': 'Расходы за цикл',
- 'orchPage.usage.ofBudget': 'из',
- 'orchPage.usage.inferenceCalls': 'Вызовы модели',
- 'orchPage.usage.integrationCalls': 'Вызовы интеграций',
- 'orchPage.usage.tokensSaved': 'Сэкономлено токенов',
- 'orchPage.usage.saved': 'сэкономлено',
- 'orchPage.usage.footnote': 'Использование отражает ваш текущий расчётный период.',
+
'nav.wallet': 'Кошелёк',
'nav.avatarMenu.account': 'Аккаунт',
'nav.avatarMenu.billing': 'Оплата',
@@ -463,85 +349,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': 'Что-то пошло не так. Пожалуйста, попробуйте снова.',
'brain.tabs.sources': 'Источники',
'brain.tabs.sync': 'Синхронизация',
- 'brain.tabs.orchestration': 'Оркестрация',
- 'tinyplaceOrchestration.title': 'Ретранслятор TinyPlace',
- 'tinyplaceOrchestration.subtitle': 'Закрепленные каналы агентов и чаты сессий приложения',
- 'tinyplaceOrchestration.refresh': 'Обновить',
- 'tinyplaceOrchestration.newInstance': 'Новый экземпляр',
- 'tinyplaceOrchestration.newInstanceSoon': 'Скоро',
- 'tinyplaceOrchestration.pinned': 'Закрепленные',
- 'tinyplaceOrchestration.sessions': 'Сессии',
- 'tinyplaceOrchestration.contacts': 'Контакты',
- 'tinyplaceOrchestration.noContacts': 'Пока нет контактов.',
- 'tinyplaceOrchestration.newSession': 'Новая сессия',
- 'tinyplaceOrchestration.otherSessions': 'Другие сессии',
- 'tinyplaceOrchestration.loading': 'Загрузка чатов TinyPlace…',
- 'tinyplaceOrchestration.paymentRequired': 'Доступ к TinyPlace требует оплаты.',
- 'tinyplaceOrchestration.failedToLoad': 'Не удалось загрузить чаты TinyPlace',
- 'tinyplaceOrchestration.noSessions': 'Сессий приложения TinyPlace пока нет.',
- 'tinyplaceOrchestration.noMessages': 'В этом чате пока нет сообщений.',
- 'tinyplaceOrchestration.active': 'Активна',
- 'tinyplaceOrchestration.inactive': 'Неактивна',
- 'tinyplaceOrchestration.encryptedBody': 'Зашифрованное сообщение TinyPlace',
- 'tinyplaceOrchestration.unknownSender': 'Неизвестный отправитель',
- 'tinyplaceOrchestration.master.title': 'Агент / человек',
- 'tinyplaceOrchestration.master.subtitle': 'Главный чат',
- 'tinyplaceOrchestration.master.preview': 'Прямая координация между вами и OpenHuman.',
- 'tinyplaceOrchestration.subconscious.title': 'Подсознание',
- 'tinyplaceOrchestration.subconscious.subtitle': 'Внутренние чаты агентов',
- 'tinyplaceOrchestration.subconscious.preview': 'Фоновая координация агентов и циклы памяти.',
- 'tinyplaceOrchestration.session.subtitle': 'Сессия приложения TinyPlace',
- 'tinyplaceOrchestration.pairing.linkLabel': 'Связать сессию',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': 'Вставьте ID агента сессии',
- 'tinyplaceOrchestration.pairing.linkAction': 'Связать',
- 'tinyplaceOrchestration.pairing.requests': 'Запросы контактов',
- 'tinyplaceOrchestration.pairing.accept': 'Принять',
- 'tinyplaceOrchestration.pairing.decline': 'Отклонить',
- 'tinyplaceOrchestration.pairing.block': 'Блокировать',
- 'tinyplaceOrchestration.pairing.linked': 'Связана',
- 'tinyplaceOrchestration.pairing.pending': 'Ожидает',
- 'tinyplaceOrchestration.pairing.unlinked': 'Не связана',
- 'tinyplaceOrchestration.pairing.incoming': 'Входящие',
- 'tinyplaceOrchestration.pairing.outgoing': 'Исходящие',
- 'tinyplaceOrchestration.master.you': 'Вы',
- 'tinyplaceOrchestration.composer.placeholder': 'Сообщение для OpenHuman…',
- 'tinyplaceOrchestration.composer.send': 'Отправить',
- 'tinyplaceOrchestration.composer.sendFailed': 'Не удалось отправить сообщение',
- 'tinyplaceOrchestration.steering.label': 'Управление',
- 'tinyplaceOrchestration.relay.staging': 'Стейджинг',
- 'tinyplaceOrchestration.relay.prod': 'Продакшн',
- 'tinyplaceOrchestration.identity.loading': 'Загрузка личности…',
- 'tinyplaceOrchestration.identity.noHandle': 'Пока нет @handle',
- 'tinyplaceOrchestration.identity.copy': 'Копировать',
- 'tinyplaceOrchestration.identity.copied': 'Скопировано',
- 'tinyplaceOrchestration.identity.discoverable': 'Обнаруживаемый',
- 'tinyplaceOrchestration.identity.undiscoverable': 'Не обнаруживается',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- 'Опубликуйте карточку каталога и ключ шифрования, чтобы другие агенты могли писать вам.',
- 'tinyplaceOrchestration.identity.makeDiscoverable': 'Сделать обнаруживаемым',
- 'tinyplaceOrchestration.identity.republish': 'Опубликовать ключи заново',
- 'tinyplaceOrchestration.identity.publishing': 'Публикация…',
- 'tinyplaceOrchestration.identity.publishFailed': 'Не удалось опубликовать: попробуйте снова',
- 'tinyplaceOrchestration.identity.card': 'Карточка каталога',
- 'tinyplaceOrchestration.identity.key': 'Ключ шифрования',
- 'tinyplaceOrchestration.identity.published': 'Опубликовано',
- 'tinyplaceOrchestration.identity.notPublished': 'Не опубликовано',
- 'tinyplaceOrchestration.roster.instances': 'Экземпляры',
- 'tinyplaceOrchestration.roster.empty': 'Пока нет экземпляров агентов',
- 'tinyplaceOrchestration.roster.other': 'Другое',
- 'tinyplaceOrchestration.status.running': 'Выполняется',
- 'tinyplaceOrchestration.status.idle': 'Простаивает',
- 'tinyplaceOrchestration.status.waitingApproval': 'Ожидает подтверждения',
- 'tinyplaceOrchestration.status.errored': 'Ошибка',
- 'tinyplaceOrchestration.status.stopped': 'Остановлен',
- 'tinyplaceOrchestration.attention.title': 'Требует внимания',
- 'tinyplaceOrchestration.attention.empty': 'Всё выполнено',
- 'tinyplaceOrchestration.attention.unread': 'Непрочитанные сообщения',
- 'tinyplaceOrchestration.attention.review': 'Проверить',
- 'tinyplaceOrchestration.attention.open': 'Открыть',
- 'tinyplaceOrchestration.attention.kind.approval': 'Одобрение',
- 'tinyplaceOrchestration.attention.kind.needsInput': 'Нужен ввод',
- 'tinyplaceOrchestration.attention.kind.unread': 'Непрочитано',
'brain.empty': 'Ваш мозг пока пуст: подключите источник, чтобы начать формировать память.',
'brain.error': 'Не удалось загрузить ваш мозг. Пожалуйста, попробуйте ещё раз.',
'common.cancel': 'Отмена',
@@ -2921,10 +2728,6 @@ const messages: TranslationMap = {
'backend.localDescription':
'Запускай модели на своём устройстве с помощью Ollama. Полная приватность, требует настройки.',
'backend.ramRecommended': 'Рекомендуется 16 ГБ+ RAM',
- 'tinyplaceOrchestration.subconsciousBadge': 'Подсознание · управление',
- 'tinyplaceOrchestration.steeringHeader.current': 'Активная директива',
- 'tinyplaceOrchestration.steeringHeader.none': 'Нет активной директивы',
- 'tinyplaceOrchestration.steeringHeader.expires': 'истекает через {n} циклов',
'actionable.complete': 'Выполнить',
'actionable.dismiss': 'Закрыть',
'actionable.snooze': 'Отложить',
@@ -5261,10 +5064,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': 'Автоматически одобрять все действия',
'settings.agentAccess.autoApproveAll.desc':
'При включении агент будет выполнять все подходящие действия, не спрашивая вашего одобрения. Это включает запись файлов, команды оболочки, сетевые запросы и любые другие побочные эффекты. Жесткие блокировки безопасности (каталоги учетных данных и системные каталоги) продолжают действовать, а действия из ненадежных или неизвестных источников никогда не одобряются автоматически.',
- 'settings.agentAccess.tinyplaceAutopilot.title': 'Автономный агент tiny.place',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- 'Позвольте OpenHuman самостоятельно действовать в tiny.place. По расписанию он ищет подходящую работу (сначала открытые награды), выполняет задачи по своим навыкам и действует от вашего имени. Он работает без присмотра и может тратить средства, поэтому при тестировании используйте devnet. По умолчанию выключено.',
- 'settings.agentAccess.tinyplaceAutopilot.label': 'Запускать автоматически',
'settings.agentAccess.timeout.label': 'Тайм-аут действия',
'settings.agentAccess.timeout.desc':
'Сколько времени может выполняться отдельный инструмент или действие до отмены. Увеличьте это значение, если крупная локальная модель прерывается до завершения ответа.',
@@ -6673,9 +6472,7 @@ const messages: TranslationMap = {
'notch.speaking': 'Говорю…',
'notch.transcribing': 'Транскрибирую…',
'notch.executing': 'Выполняю…',
- 'memory.tab.orchestration': 'Оркестрация',
- 'memory.tab.orchestrationDescription':
- 'Запускайте мультиагентные рабочие процессы: распределяйте вопрос между параллельными агентами, перепроверяйте их выводы и наблюдайте, как каждая фаза сходится в единый синтезированный ответ.',
+
'orchestration.subtitle':
'Запустите мультиагентный рабочий процесс, следите за ходом его фаз и читайте синтезированный результат.',
'orchestration.loading': 'Загрузка рабочих процессов…',
@@ -6825,10 +6622,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'Бюджет эмбеддингов израсходован, поэтому новые данные больше не добавляются в память. Настройте локальные эмбеддинги или добавьте свой ключ API, чтобы продолжить.',
'memoryBudget.cta': 'Настроить эмбеддинги',
- 'tinyplaceSunset.title': 'Tiny Place уходит из приложения',
- 'tinyplaceSunset.message':
- 'Чтобы продолжить пользоваться tiny.place, откройте tiny.place. После 31 августа 2026 года он будет удалён из приложения.',
- 'tinyplaceSunset.cta': 'Открыть tiny.place',
'userErrors.scope.memory': 'Память',
// Code block chrome
diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts
index c9110ac3df..38ccd9bb48 100644
--- a/app/src/lib/i18n/zh-CN.ts
+++ b/app/src/lib/i18n/zh-CN.ts
@@ -288,120 +288,10 @@ const messages: TranslationMap = {
'nav.flows': '工作流',
'nav.workflowRuns': '工作流运行',
'nav.workflowDiscoveries': '发现工作流',
- 'nav.orchestration': '编排',
- 'orchestration.cloudUnreachable': '无法连接云端大脑:正在显示缓存的视图。',
- 'orchPage.subtitle': '协调你的主智能体',
- 'orchPage.group.agent': '智能体',
- 'orchPage.group.network': '网络',
- 'orchPage.group.insights': '洞察',
- 'orchPage.overview.nav': '智能体图谱',
- 'orchPage.overview.desc': '您的智能体及其协调的子智能体的实时图谱。',
- 'orchPage.network.desc': '您已连接的对等智能体、发现与使用情况。',
'wallet.tabs.balance': '钱包余额',
'wallet.tabs.recovery': '恢复',
'wallet.ariaLabel': '钱包视图',
- 'orchPage.medulla.nav': '概览',
- 'orchPage.medulla.badge': '即将推出',
- 'orchPage.medulla.title': 'Medulla',
- 'orchPage.medulla.tagline': 'OpenHuman 的编排模型',
- 'orchPage.medulla.body':
- 'Medulla 是 OpenHuman 从零打造的自研大语言模型,专为同时编排数千个智能体而设计:具备 1000 万 token 的上下文窗口和极低成本的编排能力。',
- 'orchPage.medulla.featAgents': '数千个智能体',
- 'orchPage.medulla.featContext': '10M token 上下文',
- 'orchPage.medulla.featCost': '低成本编排',
- 'orchPage.medulla.subscriberTitle': 'OpenHuman 订阅用户',
- 'orchPage.medulla.subscriberNote': 'Medulla 上线后将仅面向 OpenHuman 订阅用户开放。',
- 'orchPage.medulla.subscriberCta': '获取订阅',
- 'orchPage.medulla.discordTitle': '加入 Discord',
- 'orchPage.medulla.earlyAccess': '想抢先体验?加入我们的 Discord,领取抢先体验邀请。',
- 'orchPage.medulla.cta': '加入我们的 Discord',
- 'orchPage.demo.banner': '这是一个大规模编排效果的示例。',
- 'orchPage.demo.device': '设备',
- 'orchPage.demo.taskRoute': '路由入站请求',
- 'orchPage.demo.taskSummarize': '总结对话',
- 'orchPage.demo.taskEnrich': '丰富联系人记录',
- 'orchPage.demo.taskSchedule': '安排跟进',
- 'orchPage.demo.taskDraft': '起草回复',
- 'orchPage.demo.taskSync': '同步数据源',
- 'orchPage.demo.networkTitle': '对等智能体',
- 'orchPage.demo.networkSummary': '已连接 {peers} 个 · {sessions} 个活跃子智能体',
- 'orchPage.demo.peer.connected': '已连接',
- 'orchPage.demo.peer.connecting': '连接中',
- 'orchPage.demo.peer.idle': '空闲',
- 'orchPage.demo.peerSessions': '{count} 个子智能体',
- 'orchPage.demo.chat.user1': '在我的所有渠道上协调这次外联活动。',
- 'orchPage.demo.chat.assistant1':
- '这就来:正在 2 台设备上启动 120 个智能体,并行运行外联、信息丰富和跟进。',
- 'orchPage.demo.chat.activity1': '设备 1 · 100 个智能体正在路由 1,284 个对话',
- 'orchPage.demo.chat.activity2': '设备 2 · 20 个智能体正在丰富 512 个联系人',
- 'orchPage.demo.chat.activity3': '正在起草 640 条个性化回复',
- 'orchPage.demo.chat.assistant2': '完成。120 个智能体在 38 秒内处理了 1,796 个对话。',
- 'orchPage.demo.chat.composerDisabled': '拥有 Medulla 访问权限即可使用聊天',
- 'orchPage.tasks.nav': '任务',
- 'orchPage.tasks.subtitle': '编排器的全局任务看板',
- 'orchPage.tasks.colPending': '待处理',
- 'orchPage.tasks.colActive': '进行中',
- 'orchPage.tasks.colBlocked': '已阻塞',
- 'orchPage.tasks.colCompleted': '已完成',
- 'orchPage.overview.core': '智能体核心',
- 'orchPage.overview.empty': '暂无可可视化的子智能体',
- 'orchPage.agent.nav': '聊天',
- 'orchPage.agent.mainTab': '主智能体',
- 'orchPage.agent.consciousTab': '意识',
- 'orchPage.agent.subconsciousTab': '潜意识',
- 'orchPage.agent.modeLabel': '智能体心智',
- 'orchPage.agent.description': '与主智能体聊天并观察其潜意识',
- 'orchPage.agent.viewSession': '查看会话',
- 'orchPage.sessions.railTitle': '活跃智能体',
- 'orchPage.sessions.empty': '暂无活跃智能体',
- 'orchPage.sessions.statusConnected': '已连接',
- 'orchPage.sessions.statusDisconnected': '已断开',
- 'orchPage.sessions.statusWaiting': '等待输入',
- 'orchPage.session.runtime': '运行时',
- 'orchPage.session.directory': '目录',
- 'orchPage.session.runningOn': '运行于',
- 'orchPage.connections.nav': '连接',
- 'orchPage.connections.title': '已关联智能体',
- 'orchPage.connections.description': '你的智能体协作的伙伴:展开其中一个即可查看你与它的会话',
- 'orchPage.connections.empty': '暂无连接。',
- 'orchPage.connections.emptyCta': '添加连接',
- 'orchPage.connections.statContacts': '连接',
- 'orchPage.connections.statPending': '待处理',
- 'orchPage.connections.statSessions': '会话',
- 'orchPage.connections.sessionCount': '{n} 个会话',
- 'orchPage.connections.noSessions': '暂无会话',
- 'orchPage.connections.messageCount': '{n} 条消息',
- 'orchPage.connections.back': '连接',
- 'orchPage.connections.replyPlaceholder': '回复…',
- 'orchPage.connections.initTitle': '初始化一个智能体或实例',
- 'orchPage.connections.initDesc':
- '启动一个新的子智能体与你协作。打开智能体聊天,描述它的角色、目标和所需工具:OpenHuman 会创建一个专属实例,你可以在这里进行操控。',
- 'orchPage.connections.initCta': '在聊天中开始',
- 'orchPage.connections.status.needsYou': '需要你',
- 'orchPage.connections.status.running': '运行中',
- 'orchPage.connections.status.idle': '空闲',
- 'orchPage.connections.status.done': '完成',
- 'orchPage.connections.status.error': '错误',
- 'orchPage.connections.pendingHint': '等待接受',
- 'orchPage.discover.nav': '发现',
- 'orchPage.discover.linkAction': '添加',
- 'orchPage.discover.identityTitle': '你的可发现性',
- 'orchPage.discover.notDiscoverableGuide':
- '注册一个 @handle,以便其他智能体可以找到你并给你发消息。',
- 'orchPage.discover.linkTitle': '关联新智能体',
- 'orchPage.discover.linkDescription': '粘贴智能体 ID 以发送连接请求。',
- 'orchPage.discover.noRequests': '没有传入请求。',
- 'orchPage.usage.nav': '用量',
- 'orchPage.usage.connections': '连接',
- 'orchPage.usage.balance': '信用余额',
- 'orchPage.usage.balanceHint': '促销 + 充值',
- 'orchPage.usage.cycleSpend': '周期支出',
- 'orchPage.usage.ofBudget': '/',
- 'orchPage.usage.inferenceCalls': '模型调用',
- 'orchPage.usage.integrationCalls': '集成调用',
- 'orchPage.usage.tokensSaved': '已节省令牌',
- 'orchPage.usage.saved': '已节省',
- 'orchPage.usage.footnote': '用量反映你当前的计费周期。',
+
'nav.wallet': '钱包',
'nav.avatarMenu.account': '账户',
'nav.avatarMenu.billing': '账单',
@@ -427,85 +317,6 @@ const messages: TranslationMap = {
'brain.goals.actionError': '出了点问题。请重试。',
'brain.tabs.sources': '来源',
'brain.tabs.sync': '同步',
- 'brain.tabs.orchestration': '编排',
- 'tinyplaceOrchestration.title': 'TinyPlace 中继',
- 'tinyplaceOrchestration.subtitle': '固定的代理频道和应用会话聊天',
- 'tinyplaceOrchestration.refresh': '刷新',
- 'tinyplaceOrchestration.newInstance': '新建实例',
- 'tinyplaceOrchestration.newInstanceSoon': '即将推出',
- 'tinyplaceOrchestration.pinned': '固定',
- 'tinyplaceOrchestration.sessions': '会话',
- 'tinyplaceOrchestration.contacts': '联系人',
- 'tinyplaceOrchestration.noContacts': '暂无联系人。',
- 'tinyplaceOrchestration.newSession': '新会话',
- 'tinyplaceOrchestration.otherSessions': '其他会话',
- 'tinyplaceOrchestration.loading': '正在加载 TinyPlace 聊天…',
- 'tinyplaceOrchestration.paymentRequired': '访问 TinyPlace 需要付款。',
- 'tinyplaceOrchestration.failedToLoad': '无法加载 TinyPlace 聊天',
- 'tinyplaceOrchestration.noSessions': '还没有 TinyPlace 应用会话。',
- 'tinyplaceOrchestration.noMessages': '此聊天中还没有消息。',
- 'tinyplaceOrchestration.active': '活跃',
- 'tinyplaceOrchestration.inactive': '不活跃',
- 'tinyplaceOrchestration.encryptedBody': '加密的 TinyPlace 消息',
- 'tinyplaceOrchestration.unknownSender': '未知发送者',
- 'tinyplaceOrchestration.master.title': '代理 / 人类',
- 'tinyplaceOrchestration.master.subtitle': '主聊天',
- 'tinyplaceOrchestration.master.preview': '你和 OpenHuman 之间的直接协调。',
- 'tinyplaceOrchestration.subconscious.title': '潜意识',
- 'tinyplaceOrchestration.subconscious.subtitle': '代理内部聊天',
- 'tinyplaceOrchestration.subconscious.preview': '后台代理协调和记忆循环。',
- 'tinyplaceOrchestration.session.subtitle': 'TinyPlace 应用会话',
- 'tinyplaceOrchestration.pairing.linkLabel': '链接会话',
- 'tinyplaceOrchestration.pairing.linkPlaceholder': '粘贴会话智能体 ID',
- 'tinyplaceOrchestration.pairing.linkAction': '链接',
- 'tinyplaceOrchestration.pairing.requests': '联系人请求',
- 'tinyplaceOrchestration.pairing.accept': '接受',
- 'tinyplaceOrchestration.pairing.decline': '拒绝',
- 'tinyplaceOrchestration.pairing.block': '屏蔽',
- 'tinyplaceOrchestration.pairing.linked': '已链接',
- 'tinyplaceOrchestration.pairing.pending': '待处理',
- 'tinyplaceOrchestration.pairing.unlinked': '未链接',
- 'tinyplaceOrchestration.pairing.incoming': '传入',
- 'tinyplaceOrchestration.pairing.outgoing': '传出',
- 'tinyplaceOrchestration.master.you': '你',
- 'tinyplaceOrchestration.composer.placeholder': '给 OpenHuman 发消息…',
- 'tinyplaceOrchestration.composer.send': '发送',
- 'tinyplaceOrchestration.composer.sendFailed': '消息发送失败',
- 'tinyplaceOrchestration.steering.label': '引导',
- 'tinyplaceOrchestration.relay.staging': '预发布',
- 'tinyplaceOrchestration.relay.prod': '生产',
- 'tinyplaceOrchestration.identity.loading': '正在加载身份…',
- 'tinyplaceOrchestration.identity.noHandle': '尚无 @handle',
- 'tinyplaceOrchestration.identity.copy': '复制',
- 'tinyplaceOrchestration.identity.copied': '已复制',
- 'tinyplaceOrchestration.identity.discoverable': '可被发现',
- 'tinyplaceOrchestration.identity.undiscoverable': '不可被发现',
- 'tinyplaceOrchestration.identity.undiscoverableHint':
- '发布你的目录卡片和加密密钥,以便其他代理可以给你发消息。',
- 'tinyplaceOrchestration.identity.makeDiscoverable': '设为可被发现',
- 'tinyplaceOrchestration.identity.republish': '重新发布密钥',
- 'tinyplaceOrchestration.identity.publishing': '正在发布…',
- 'tinyplaceOrchestration.identity.publishFailed': '发布失败:请重试',
- 'tinyplaceOrchestration.identity.card': '目录卡片',
- 'tinyplaceOrchestration.identity.key': '加密密钥',
- 'tinyplaceOrchestration.identity.published': '已发布',
- 'tinyplaceOrchestration.identity.notPublished': '未发布',
- 'tinyplaceOrchestration.roster.instances': '实例',
- 'tinyplaceOrchestration.roster.empty': '暂无代理实例',
- 'tinyplaceOrchestration.roster.other': '其他',
- 'tinyplaceOrchestration.status.running': '运行中',
- 'tinyplaceOrchestration.status.idle': '空闲',
- 'tinyplaceOrchestration.status.waitingApproval': '等待批准',
- 'tinyplaceOrchestration.status.errored': '出错',
- 'tinyplaceOrchestration.status.stopped': '已停止',
- 'tinyplaceOrchestration.attention.title': '需要你处理',
- 'tinyplaceOrchestration.attention.empty': '全部处理完毕',
- 'tinyplaceOrchestration.attention.unread': '未读消息',
- 'tinyplaceOrchestration.attention.review': '审查',
- 'tinyplaceOrchestration.attention.open': '打开',
- 'tinyplaceOrchestration.attention.kind.approval': '审批',
- 'tinyplaceOrchestration.attention.kind.needsInput': '需要输入',
- 'tinyplaceOrchestration.attention.kind.unread': '未读',
'brain.empty': '你的大脑暂时是空的:连接一个来源即可开始构建记忆。',
'brain.error': '无法加载你的大脑,请重试。',
'common.cancel': '取消',
@@ -2742,10 +2553,6 @@ const messages: TranslationMap = {
'backend.advanced': '高级',
'backend.localDescription': '使用 Ollama 在本地运行模型。完全隐私,需要设置。',
'backend.ramRecommended': '建议 16GB+ 内存',
- 'tinyplaceOrchestration.subconsciousBadge': '潜意识 · 引导',
- 'tinyplaceOrchestration.steeringHeader.current': '当前指令',
- 'tinyplaceOrchestration.steeringHeader.none': '无活动指令',
- 'tinyplaceOrchestration.steeringHeader.expires': '{n} 个周期后过期',
'actionable.complete': '完成',
'actionable.dismiss': '忽略',
'actionable.snooze': '稍后提醒',
@@ -4929,10 +4736,6 @@ const messages: TranslationMap = {
'settings.agentAccess.autoApproveAll.label': '自动批准所有操作',
'settings.agentAccess.autoApproveAll.desc':
'启用后,智能体将自动执行所有符合条件的操作,无需事先征得你的批准。这包括文件写入、Shell 命令、网络请求以及任何其他副作用。严格的安全阻止措施(凭据目录和系统目录)仍然适用,来自不受信任或未知来源的操作永远不会被自动批准。',
- 'settings.agentAccess.tinyplaceAutopilot.title': '自主 tiny.place 代理',
- 'settings.agentAccess.tinyplaceAutopilot.desc':
- '让 OpenHuman 自行在 tiny.place 上行动:按计划寻找有价值的工作(优先开放的悬赏),完成符合其技能的任务,并以你的身份行动。它在无人监督下运行且可以花费资金,测试时请使用 devnet。默认关闭。',
- 'settings.agentAccess.tinyplaceAutopilot.label': '自动运行',
'settings.agentAccess.timeout.label': '操作超时',
'settings.agentAccess.timeout.desc':
'单个工具或操作在被取消前可运行的时长。如果大型本地模型在完成响应前被中断,请增大此值。',
@@ -6250,9 +6053,7 @@ const messages: TranslationMap = {
'notch.speaking': '说话中…',
'notch.transcribing': '转录中…',
'notch.executing': '执行中…',
- 'memory.tab.orchestration': '编排',
- 'memory.tab.orchestrationDescription':
- '运行多智能体工作流:将一个问题分发给多个并行智能体,交叉核对它们的发现,并观察每个阶段汇聚成一个综合答案。',
+
'orchestration.subtitle': '启动多智能体工作流,观察其各阶段进展,并阅读综合结果。',
'orchestration.loading': '正在加载工作流…',
'orchestration.failedToLoad': '加载工作流失败',
@@ -6386,10 +6187,6 @@ const messages: TranslationMap = {
'memoryBudget.exhaustedMessage':
'你的嵌入额度已用尽,新内容不会再加入记忆。设置本地嵌入或添加你自己的 API 密钥即可恢复。',
'memoryBudget.cta': '设置嵌入',
- 'tinyplaceSunset.title': 'Tiny Place 即将移出应用',
- 'tinyplaceSunset.message':
- '若要继续使用 tiny.place,请前往 tiny.place。2026 年 8 月 31 日后它将从应用中移除。',
- 'tinyplaceSunset.cta': '打开 tiny.place',
'userErrors.scope.memory': '记忆',
// Code block chrome
diff --git a/app/src/lib/orchestration/__tests__/usePairing.test.ts b/app/src/lib/orchestration/__tests__/usePairing.test.ts
deleted file mode 100644
index dd7096276b..0000000000
--- a/app/src/lib/orchestration/__tests__/usePairing.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { act, renderHook, waitFor } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { PaymentRequiredError } from '../../agentworld/invokeApiClient';
-import { usePairing } from '../usePairing';
-
-const listMock = vi.hoisted(() => vi.fn());
-vi.mock('../../agentworld/apiClient', () => ({
- apiClient: { orchestrationPairing: { list: listMock } },
-}));
-
-const snapshot = {
- records: [],
- contacts: { contacts: [] },
- requests: { incoming: [], outgoing: [] },
- stats: { agentId: 'me', contactCount: 2, pendingIncoming: 1, pendingOutgoing: 0 },
-};
-
-describe('usePairing', () => {
- beforeEach(() => vi.clearAllMocks());
- afterEach(() => vi.restoreAllMocks());
-
- it('loads a snapshot on mount', async () => {
- listMock.mockResolvedValue(snapshot);
- const { result } = renderHook(() => usePairing());
- await waitFor(() => expect(result.current.state.status).toBe('ok'));
- expect(listMock).toHaveBeenCalledTimes(1);
- });
-
- it('maps a PaymentRequiredError to payment_required', async () => {
- listMock.mockRejectedValue(new PaymentRequiredError({}));
- const { result } = renderHook(() => usePairing());
- await waitFor(() => expect(result.current.state.status).toBe('payment_required'));
- });
-
- it('surfaces a generic error', async () => {
- listMock.mockRejectedValue(new Error('boom'));
- const { result } = renderHook(() => usePairing());
- await waitFor(() => expect(result.current.state.status).toBe('error'));
- });
-
- it('runs an action then reloads', async () => {
- listMock.mockResolvedValue(snapshot);
- const { result } = renderHook(() => usePairing());
- await waitFor(() => expect(result.current.state.status).toBe('ok'));
- const action = vi.fn().mockResolvedValue(undefined);
- await act(async () => {
- await result.current.runAction('block:x', action);
- });
- expect(action).toHaveBeenCalledTimes(1);
- expect(listMock).toHaveBeenCalledTimes(2); // initial + reload
- expect(result.current.actionError).toBeNull();
- });
-
- it('captures an action error without reloading', async () => {
- listMock.mockResolvedValue(snapshot);
- const { result } = renderHook(() => usePairing());
- await waitFor(() => expect(result.current.state.status).toBe('ok'));
- await act(async () => {
- await result.current.runAction('block:x', () => Promise.reject(new Error('nope')));
- });
- expect(result.current.actionError).toBe('nope');
- expect(listMock).toHaveBeenCalledTimes(1); // no reload after failure
- });
-});
diff --git a/app/src/lib/orchestration/mergeToolActivity.test.ts b/app/src/lib/orchestration/mergeToolActivity.test.ts
deleted file mode 100644
index 40dd202370..0000000000
--- a/app/src/lib/orchestration/mergeToolActivity.test.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { mergeToolActivity, type ToolActivity, toolResultFailed } from './mergeToolActivity';
-import type { ChatMessage } from './useOrchestrationChats';
-
-const msg = (over: Partial<ChatMessage>): ChatMessage => ({
- id: 'x',
- from: 'agent',
- body: '',
- timestamp: '2026-07-08T00:00:00Z',
- encrypted: false,
- ...over,
-});
-
-describe('toolResultFailed', () => {
- it('flags isError, non-zero exit, or ok=false; passes success', () => {
- expect(toolResultFailed({ ok: true, isError: false, exitCode: 0 })).toBe(false);
- expect(toolResultFailed({ isError: true })).toBe(true);
- expect(toolResultFailed({ exitCode: 1 })).toBe(true);
- expect(toolResultFailed({ ok: false })).toBe(true);
- expect(toolResultFailed({})).toBe(false);
- });
-});
-
-describe('mergeToolActivity', () => {
- it('merges a tool_call with its tool_result by callId', () => {
- const rows = mergeToolActivity([
- msg({ id: 'a', eventKind: 'tool_call', toolName: 'Bash', callId: 'c1', body: 'ls' }),
- msg({ id: 'b', eventKind: 'tool_result', callId: 'c1', body: 'out', ok: true }),
- ]);
- expect(rows).toHaveLength(1);
- const tool = rows[0] as ToolActivity;
- expect(tool.kind).toBe('tool');
- expect(tool.command).toBe('ls');
- expect(tool.output).toBe('out');
- expect(tool.toolName).toBe('Bash');
- expect(tool.hasResult).toBe(true);
- expect(tool.failed).toBe(false);
- });
-
- it('marks a failed result (isError / exitCode)', () => {
- const rows = mergeToolActivity([
- msg({ id: 'a', eventKind: 'tool_call', callId: 'c1', body: 'read x' }),
- msg({
- id: 'b',
- eventKind: 'tool_result',
- callId: 'c1',
- body: 'boom',
- isError: true,
- exitCode: 1,
- ok: false,
- }),
- ]);
- expect((rows[0] as ToolActivity).failed).toBe(true);
- });
-
- it('keeps a tool_call open (no result) as an unfinished tool row', () => {
- const rows = mergeToolActivity([
- msg({ id: 'a', eventKind: 'tool_call', callId: 'c1', body: 'ls' }),
- ]);
- expect(rows).toHaveLength(1);
- expect((rows[0] as ToolActivity).hasResult).toBe(false);
- });
-
- it('renders an orphan tool_result (no prior call) standalone', () => {
- const rows = mergeToolActivity([
- msg({
- id: 'r',
- eventKind: 'tool_result',
- callId: 'zz',
- body: 'late',
- ok: true,
- toolName: 'Read',
- }),
- ]);
- expect(rows).toHaveLength(1);
- const tool = rows[0] as ToolActivity;
- expect(tool.command).toBe('');
- expect(tool.output).toBe('late');
- expect(tool.toolName).toBe('Read');
- expect(tool.hasResult).toBe(true);
- });
-
- it('passes non-tool rows through as message rows, preserving order', () => {
- const rows = mergeToolActivity([
- msg({ id: 'u', eventKind: 'user_prompt', body: 'hi' }),
- msg({ id: 'a', eventKind: 'tool_call', callId: 'c1', body: 'ls' }),
- msg({ id: 'b', eventKind: 'tool_result', callId: 'c1', body: 'out' }),
- msg({ id: 'm', eventKind: 'agent_message', body: 'done' }),
- ]);
- expect(rows.map(r => r.kind)).toEqual(['message', 'tool', 'message']);
- expect(rows[0]).toMatchObject({ kind: 'message', message: { id: 'u' } });
- expect(rows[2]).toMatchObject({ kind: 'message', message: { id: 'm' } });
- });
-
- it('handles interleaved concurrent tool calls', () => {
- const rows = mergeToolActivity([
- msg({ id: 'a', eventKind: 'tool_call', callId: 'c1', body: 'one' }),
- msg({ id: 'b', eventKind: 'tool_call', callId: 'c2', body: 'two' }),
- msg({ id: 'c', eventKind: 'tool_result', callId: 'c2', body: 'two-out' }),
- msg({ id: 'd', eventKind: 'tool_result', callId: 'c1', body: 'one-out' }),
- ]);
- expect(rows).toHaveLength(2);
- expect((rows[0] as ToolActivity).output).toBe('one-out');
- expect((rows[1] as ToolActivity).output).toBe('two-out');
- });
-});
diff --git a/app/src/lib/orchestration/mergeToolActivity.ts b/app/src/lib/orchestration/mergeToolActivity.ts
deleted file mode 100644
index 3f689734d7..0000000000
--- a/app/src/lib/orchestration/mergeToolActivity.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-/**
- * Fold a v2 orchestration transcript into renderable rows.
- *
- * The harness stream delivers a `tool_call` and its `tool_result` as two
- * separate rows correlated by `callId`. For rendering we want them as ONE unit
- * (command + output + outcome), so `mergeToolActivity` pairs them and derives a
- * single `failed` flag from the result's `isError` / `exitCode` / `ok`. Every
- * other row passes through unchanged. Pure — unit-tested in isolation.
- */
-import type { ChatMessage } from './useOrchestrationChats';
-
-/** A merged tool_call (+ its tool_result when present). */
-export interface ToolActivity {
- kind: 'tool';
- /** Stable key: the tool_call id (or the orphan result id). */
- id: string;
- toolName?: string;
- /** The tool_call body (command / display). Empty for an orphan result. */
- command: string;
- /** The tool_result body (output), once it has arrived. */
- output?: string;
- callId?: string;
- /** True once the matching tool_result exists. */
- hasResult: boolean;
- /** The tool run failed — `isError`, a non-zero `exitCode`, or `ok === false`. */
- failed: boolean;
- timestamp: string;
-}
-
-/** A plain (non-tool) transcript row, rendered as a bubble/inline block. */
-interface MessageRow {
- kind: 'message';
- message: ChatMessage;
-}
-
-type TranscriptRow = ToolActivity | MessageRow;
-
-/** Whether a `tool_result` row represents a failure. */
-export function toolResultFailed(
- result: Pick<ChatMessage, 'ok' | 'isError' | 'exitCode'>
-): boolean {
- return result.isError === true || (result.exitCode ?? 0) > 0 || result.ok === false;
-}
-
-function activityFromCall(call: ChatMessage): ToolActivity {
- return {
- kind: 'tool',
- id: call.id,
- ...(call.toolName ? { toolName: call.toolName } : {}),
- command: call.body,
- ...(call.callId ? { callId: call.callId } : {}),
- hasResult: false,
- failed: false,
- timestamp: call.timestamp,
- };
-}
-
-function applyResult(activity: ToolActivity, result: ChatMessage): ToolActivity {
- return {
- ...activity,
- output: result.body,
- hasResult: true,
- failed: toolResultFailed(result),
- ...(activity.toolName ? {} : result.toolName ? { toolName: result.toolName } : {}),
- };
-}
-
-/**
- * Merge `tool_call`/`tool_result` pairs (by `callId`) into single `tool` rows.
- * A result with no matching prior call renders as its own tool row (command
- * empty). Order is preserved by the position of the `tool_call` (or an orphan
- * result). Non-tool rows are wrapped as `message` rows.
- */
-export function mergeToolActivity(messages: ChatMessage[]): TranscriptRow[] {
- const rows: TranscriptRow[] = [];
- // callId → index into `rows` of the open tool activity awaiting its result.
- const openByCallId = new Map<string, number>();
-
- for (const message of messages) {
- if (message.eventKind === 'tool_call') {
- const activity = activityFromCall(message);
- if (message.callId) openByCallId.set(message.callId, rows.length);
- rows.push(activity);
- continue;
- }
- if (message.eventKind === 'tool_result') {
- const openIndex = message.callId ? openByCallId.get(message.callId) : undefined;
- if (openIndex !== undefined) {
- const open = rows[openIndex] as ToolActivity;
- rows[openIndex] = applyResult(open, message);
- if (message.callId) openByCallId.delete(message.callId);
- } else {
- // Orphan result (call not seen) — render standalone.
- const orphan = applyResult(activityFromCall({ ...message, body: '' }), message);
- rows.push(orphan);
- }
- continue;
- }
- rows.push({ kind: 'message', message });
- }
-
- return rows;
-}
diff --git a/app/src/lib/orchestration/orchestrationClient.ts b/app/src/lib/orchestration/orchestrationClient.ts
deleted file mode 100644
index 5876dfaf5e..0000000000
--- a/app/src/lib/orchestration/orchestrationClient.ts
+++ /dev/null
@@ -1,314 +0,0 @@
-/**
- * Renderer client for the subconscious-orchestration Brain surface.
- *
- * Thin typed wrappers over the core `openhuman.orchestration_*` JSON-RPC
- * methods, routed through `callCoreRpc` exactly like the tiny.place bridge in
- * `invokeApiClient.ts`. The Rust core owns all business logic — this file is
- * only the transport seam.
- *
- * Error conventions mirror `invokeApiClient`:
- * - 402 Payment Required surfaces as {@link PaymentRequiredError} (re-exported
- * here so callers do not need to reach into the tiny.place bridge).
- * - All other transport / RPC failures propagate as plain `Error`.
- */
-import { callCoreRpc } from '../../services/coreRpcClient';
-import { PaymentRequiredError } from '../agentworld/invokeApiClient';
-
-export { PaymentRequiredError };
-
-// ── Domain types (must match the Rust RPC shapes; do not rename) ──────────────
-
-export type OrchestrationChatKind = 'master' | 'subconscious' | 'session';
-
-/** External agent harness that emits a session (drives the roster grouping). */
-export type HarnessType = 'claude' | 'codex' | 'gemini' | 'cursor' | 'windsurf';
-
-/**
- * Coarse instance status for the roster dot. Peer instances carry no true
- * run-state yet, so the core derives only `idle` / `stopped` today; the
- * remaining states are modelled here (and by `InstanceStatusDot`) for the
- * attention-queue and run-state follow-ups.
- */
-export type InstanceStatus = 'running' | 'idle' | 'waiting-approval' | 'errored' | 'stopped';
-
-export interface SessionSummary {
- sessionId: string;
- agentId: string;
- source: string;
- /** Emitting harness when this is an external instance; absent for master/subconscious/user-created. */
- harnessType?: HarnessType;
- /** Coarse status for the roster dot (see {@link InstanceStatus}). */
- status: InstanceStatus;
- /** One-line current activity (latest message preview) for the roster. */
- currentTask?: string;
- label?: string;
- workspace?: string;
- chatKind: OrchestrationChatKind;
- lastMessageAt: string;
- unread: number;
- /** Total persisted messages in the session; `0` for pinned/new windows. */
- messageCount?: number;
- active: boolean;
- pinned: boolean;
- /**
- * Live peer reachability from the core presence map. `true` = confidently
- * online (heard from within the TTL); `false` = confidently offline
- * (heartbeat); `undefined` = unknown → fall back to `active`/status.
- */
- peerOnline?: boolean;
- /** ISO-8601 last time the core heard from this peer, if ever. */
- lastSeenAt?: string;
-}
-
-/**
- * Typed kind of a harness (v2) event, mirroring the SDK's
- * `tinyplace.harness.session.v2` stream. Absent on legacy v1 rows (which carry
- * only role + body). The core hides `status`/`lifecycle`/`unknown` from the
- * thread, so those should not normally reach the renderer.
- */
-export type HarnessEventKind =
- | 'user_prompt'
- | 'agent_message'
- | 'agent_thinking'
- | 'tool_call'
- | 'tool_result'
- | 'approval_request'
- | 'status'
- | 'lifecycle'
- | 'error'
- | 'unknown';
-
-export interface OrchestrationMessage {
- id: string;
- agentId: string;
- sessionId: string;
- chatKind: OrchestrationChatKind;
- role: string;
- body: string;
- timestamp: string;
- seq: number;
- /** Typed event kind for v2 harness streams; absent on v1 text rows. */
- eventKind?: HarnessEventKind;
- /** Raw harness tool name (e.g. "Bash") on tool_call / tool_result rows. */
- toolName?: string;
- /** Correlation id shared by a tool_call and its tool_result. */
- callId?: string;
- /** tool_result outcome: whether the tool call succeeded. Absent off tool_result. */
- ok?: boolean;
- /** tool_result: the harness flagged the result as an error. */
- isError?: boolean;
- /** tool_result: process exit code when the tool was a command. */
- exitCode?: number;
-}
-
-export interface OrchestrationSteering {
- text: string;
- createdAt: string;
- expiresAfterCycles: number;
-}
-
-export interface OrchestrationStatus {
- steering?: OrchestrationSteering;
- ingestLastMessageAt?: string;
- /** Whether the hosted brain was reachable at the last health sync. `false`
- * drives the "cloud brain unreachable" offline notice. Absent = assume up. */
- cloudReachable?: boolean;
-}
-
-interface SessionsListResponse {
- sessions: SessionSummary[];
-}
-
-interface SessionCreateResponse {
- session: SessionSummary;
-}
-
-interface MessagesListResponse {
- messages: OrchestrationMessage[];
-}
-
-interface SendMasterMessageResponse {
- ok: true;
- messageId: string;
-}
-
-interface MarkReadResponse {
- ok: true;
-}
-
-/** Live socket event payload emitted by the core on new orchestration messages. */
-export interface OrchestrationMessageEvent {
- agentId: string;
- sessionId: string;
- chatKind: string;
-}
-
-// ── Attention queue ─────────────────────────────────────────────────────────
-
-/** The kind of "needs you" signal, in descending urgency. */
-export type AttentionKind = 'approval' | 'needs-input' | 'unread';
-
-/** What the renderer should do when the user acts on an attention item. */
-export type AttentionAction =
- | { type: 'approval'; requestId: string }
- | { type: 'open-thread'; threadId: string }
- | { type: 'open-run'; runId: string }
- | { type: 'open-session'; sessionId: string };
-
-/** One actionable row in the attention queue. */
-export interface AttentionItem {
- /** Stable list key (`<kind>:<source-id>`). */
- id: string;
- kind: AttentionKind;
- /** The instance/source this concerns (request id / run id / session id). */
- instanceId: string;
- /** Short label (tool name / agent display name / session label). */
- title: string;
- /** One-line detail; absent for `unread` (use `count`). */
- summary?: string;
- /** Unread message count; present only for the `unread` kind. */
- count?: number;
- action: AttentionAction;
- /** RFC3339 creation/activity time, when known. */
- createdAt?: string;
-}
-
-/** Per-kind + total counts for badging the zone. */
-export interface AttentionCounts {
- total: number;
- approvals: number;
- needsInput: number;
- unread: number;
-}
-
-export interface AttentionQueue {
- items: AttentionItem[];
- counts: AttentionCounts;
-}
-
-/** One @handle this agent's wallet holds (reverse-resolved from the directory). */
-export interface SelfHandle {
- username: string;
- primary: boolean;
-}
-
-/**
- * This agent's own tiny.place identity and whether peers can reach it.
- *
- * `discoverable` is the bottom line: a peer can DM this agent only when both its
- * directory card (`cardPublished`) and its Signal encryption key (`keyPublished`)
- * are live. A fresh identity can accept contacts yet stay un-messageable until it
- * registers a @handle — the card surfaces that gap instead of a mystery 404.
- */
-export interface SelfIdentity {
- agentId: string;
- handles: SelfHandle[];
- primaryHandle?: string;
- cardPublished: boolean;
- keyPublished: boolean;
- discoverable: boolean;
-}
-
-/** The relay endpoint the core talks to, plus a coarse network label. */
-export interface RelayInfo {
- baseUrl: string;
- network: 'staging' | 'prod';
-}
-
-// ── Internal helper ───────────────────────────────────────────────────────────
-
-function safeParseJson(s: string): unknown {
- try {
- return JSON.parse(s) as unknown;
- } catch {
- return s;
- }
-}
-
-/**
- * Call a `openhuman.orchestration_*` method and return the typed result.
- *
- * The core serialises 402 errors as a plain string `"PAYMENT_REQUIRED:<json>"`;
- * we decode it into a {@link PaymentRequiredError} so callers can render the
- * paywall state, matching `invokeApiClient`. All other errors propagate as-is.
- */
-async function call<T>(method: string, params?: Record<string, unknown>): Promise<T> {
- try {
- return await callCoreRpc<T>({ method, params: params ?? {} });
- } catch (err) {
- const msg = String(err);
- const prefix = 'PAYMENT_REQUIRED:';
- const idx = msg.indexOf(prefix);
- if (idx >= 0) {
- throw new PaymentRequiredError(safeParseJson(msg.slice(idx + prefix.length)));
- }
- throw err;
- }
-}
-
-// ── Public API ────────────────────────────────────────────────────────────────
-
-export const orchestrationClient = {
- /** List all orchestration chats (pinned master + subconscious, plus sessions). */
- sessionsList: () => call<SessionsListResponse>('openhuman.orchestration_sessions_list', {}),
-
- /** Create a new empty session for a contact; returns the created summary. */
- sessionsCreate: (params: { agentId: string; label?: string }) =>
- call<SessionCreateResponse>('openhuman.orchestration_sessions_create', {
- agentId: params.agentId,
- ...(params.label !== undefined ? { label: params.label } : {}),
- }),
-
- /**
- * List messages for a chat. `chat` is `"master"`, `"subconscious"`, or a
- * session's `sessionId`.
- */
- messagesList: (params: { chat: string; limit?: number; before?: string }) =>
- call<MessagesListResponse>('openhuman.orchestration_messages_list', {
- chat: params.chat,
- ...(params.limit !== undefined ? { limit: params.limit } : {}),
- ...(params.before !== undefined ? { before: params.before } : {}),
- }),
-
- /**
- * Send a message from the human master. With `sessionId` the message threads
- * under that session (session envelope); otherwise it goes to the Master chat.
- */
- sendMasterMessage: (params: { body: string; recipient?: string; sessionId?: string }) =>
- call<SendMasterMessageResponse>('openhuman.orchestration_send_master_message', {
- body: params.body,
- ...(params.recipient !== undefined ? { recipient: params.recipient } : {}),
- ...(params.sessionId !== undefined ? { sessionId: params.sessionId } : {}),
- }),
-
- /** Mark a chat as read (clears the server-side unread count). */
- markRead: (chat: string) => call<MarkReadResponse>('openhuman.orchestration_mark_read', { chat }),
-
- /** Current orchestration status (active steering directive, tick timing). */
- status: () => call<OrchestrationStatus>('openhuman.orchestration_status', {}),
-
- /**
- * The aggregated "needs you" queue: pending tool approvals, agent runs
- * awaiting input, and instances with unread messages, priority-ordered.
- */
- attention: () => call<AttentionQueue>('openhuman.orchestration_attention', {}),
-
- /**
- * This agent's own tiny.place identity + discoverability (agent id, @handles,
- * whether its directory card and Signal key are published, whether peers can
- * DM it). Powers the SelfIdentityCard.
- */
- selfIdentity: () => call<SelfIdentity>('openhuman.orchestration_self_identity', {}),
-
- /**
- * Make this agent discoverable: publish (or refresh) its directory card + Signal
- * encryption key for the wallet's current identity, then return the updated
- * {@link SelfIdentity}. No @handle registration and no payment — it repairs the
- * common "has an identity but card/key aren't published" gap that makes every
- * inbound DM 404. Powers the SelfIdentityCard's "Make discoverable" action.
- */
- publishIdentity: () => call<SelfIdentity>('openhuman.orchestration_publish_identity', {}),
-
- /** The relay endpoint + network label the core is talking to (RelayBadge). */
- relayInfo: () => call<RelayInfo>('openhuman.orchestration_relay_info', {}),
-};
diff --git a/app/src/lib/orchestration/useMedullaAccess.ts b/app/src/lib/orchestration/useMedullaAccess.ts
deleted file mode 100644
index c345d7ea66..0000000000
--- a/app/src/lib/orchestration/useMedullaAccess.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { useUser } from '../../hooks/useUser';
-
-/**
- * Whether the current user is entitled to Medulla (the orchestration model) and
- * the live orchestration engine, driven by the backend `user.hasMedullaAccess`
- * flag. When `false` (the default until early access is granted), the
- * Orchestration page hides the live chat and renders a scale showcase (demo
- * graph / tasks / network) instead of the live surfaces.
- */
-export function useMedullaAccess(): boolean {
- const { user } = useUser();
- return Boolean(user?.hasMedullaAccess);
-}
diff --git a/app/src/lib/orchestration/useOrchestrationChats.ts b/app/src/lib/orchestration/useOrchestrationChats.ts
deleted file mode 100644
index 47e2bd49e0..0000000000
--- a/app/src/lib/orchestration/useOrchestrationChats.ts
+++ /dev/null
@@ -1,410 +0,0 @@
-/**
- * Data hook backing the TinyPlace orchestration Brain tab.
- *
- * Owns everything that talks to the core:
- * - sessions list (pinned master + subconscious + app sessions)
- * - per-chat message loads (lazy, for the selected chat)
- * - the master composer send (optimistic append)
- * - read receipts (`mark_read` on open)
- * - orchestration status (active steering directive)
- * - live refetch on the `orchestration:message` socket event
- *
- * The component stays presentational: it renders the `ChatWindow[]` view model
- * this hook produces and calls the returned actions.
- */
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-
-import { socketService } from '../../services/socketService';
-import {
- type HarnessEventKind,
- orchestrationClient,
- type OrchestrationMessage,
- type OrchestrationMessageEvent,
- type OrchestrationStatus,
- PaymentRequiredError,
- type SessionSummary,
-} from './orchestrationClient';
-
-const MESSAGE_LIMIT = 100;
-
-export const MASTER_CHAT_KEY = 'master';
-export const SUBCONSCIOUS_CHAT_KEY = 'subconscious';
-
-export type ChatKind = 'master' | 'subconscious' | 'session';
-
-export interface ChatMessage {
- id: string;
- from: string;
- body: string;
- timestamp: string;
- encrypted: boolean;
- /** Typed harness (v2) event kind; absent on legacy v1 text rows. */
- eventKind?: HarnessEventKind;
- /** Tool name on tool_call / tool_result rows. */
- toolName?: string;
- /** Correlation id linking a tool_call to its tool_result. */
- callId?: string;
- /** tool_result outcome — whether the tool call succeeded. */
- ok?: boolean;
- /** tool_result — the harness flagged the result as an error. */
- isError?: boolean;
- /** tool_result — process exit code when the tool was a command. */
- exitCode?: number;
-}
-
-export interface ChatWindow {
- id: string;
- kind: ChatKind;
- title: string;
- subtitle: string;
- preview: string;
- lastTimestamp: string | null;
- unread: number;
- active: boolean;
- pinned: boolean;
- peerAgentId: string | null;
- messages: ChatMessage[];
-}
-
-type Translate = (key: string) => string;
-
-type SessionsState =
- | { status: 'loading' }
- | { status: 'error'; message: string }
- | { status: 'payment_required' }
- | { status: 'ok' };
-
-type MessagesPaneState =
- | { status: 'idle' }
- | { status: 'loading' }
- | { status: 'error'; message: string }
- | { status: 'ok' };
-
-/** RPC `chat` key for a summary: sessions key on their id, pinned on their kind. */
-function chatKeyForSession(summary: SessionSummary): string {
- return summary.chatKind === 'session' ? summary.sessionId : summary.chatKind;
-}
-
-function truncate(text: string, length = 96): string {
- if (text.length <= length) return text;
- return `${text.slice(0, length - 1)}…`;
-}
-
-function mapMessage(message: OrchestrationMessage): ChatMessage {
- return {
- id: message.id,
- from: message.role?.trim() || message.agentId || '',
- body: message.body,
- timestamp: message.timestamp,
- encrypted: false,
- ...(message.eventKind ? { eventKind: message.eventKind } : {}),
- ...(message.toolName ? { toolName: message.toolName } : {}),
- ...(message.callId ? { callId: message.callId } : {}),
- ...(message.ok !== undefined ? { ok: message.ok } : {}),
- ...(message.isError !== undefined ? { isError: message.isError } : {}),
- ...(message.exitCode !== undefined ? { exitCode: message.exitCode } : {}),
- };
-}
-
-function messageTime(timestamp: string): number {
- const parsed = Date.parse(timestamp);
- return Number.isFinite(parsed) ? parsed : 0;
-}
-
-function sortMessages(messages: ChatMessage[]): ChatMessage[] {
- return messages.slice().sort((a, b) => messageTime(a.timestamp) - messageTime(b.timestamp));
-}
-
-function pinnedTitle(kind: ChatKind, t: Translate): string {
- return kind === 'subconscious'
- ? t('tinyplaceOrchestration.subconscious.title')
- : t('tinyplaceOrchestration.master.title');
-}
-
-function pinnedSubtitle(kind: ChatKind, t: Translate): string {
- return kind === 'subconscious'
- ? t('tinyplaceOrchestration.subconscious.subtitle')
- : t('tinyplaceOrchestration.master.subtitle');
-}
-
-function pinnedPreview(kind: ChatKind, t: Translate): string {
- return kind === 'subconscious'
- ? t('tinyplaceOrchestration.subconscious.preview')
- : t('tinyplaceOrchestration.master.preview');
-}
-
-function buildChatWindow(
- summary: SessionSummary,
- messages: ChatMessage[] | undefined,
- t: Translate
-): ChatWindow {
- const key = chatKeyForSession(summary);
- const loaded = messages ?? [];
- const last = loaded[loaded.length - 1];
- const preview = last
- ? truncate(last.body)
- : summary.pinned
- ? pinnedPreview(summary.chatKind, t)
- : '';
- return {
- id: key,
- kind: summary.chatKind,
- title: summary.pinned
- ? pinnedTitle(summary.chatKind, t)
- : summary.label?.trim() || summary.sessionId,
- subtitle: summary.pinned
- ? pinnedSubtitle(summary.chatKind, t)
- : summary.workspace?.trim() ||
- summary.source?.trim() ||
- t('tinyplaceOrchestration.session.subtitle'),
- preview,
- lastTimestamp: summary.lastMessageAt || last?.timestamp || null,
- unread: summary.unread,
- active: summary.active,
- pinned: summary.pinned,
- peerAgentId: summary.chatKind === 'session' ? summary.agentId || null : null,
- messages: loaded,
- };
-}
-
-interface UseOrchestrationChatsResult {
- sessionsState: SessionsState;
- messagesState: MessagesPaneState;
- chats: ChatWindow[];
- selectedId: string;
- selected: ChatWindow | undefined;
- status: OrchestrationStatus | null;
- masterError: string | null;
- selectChat: (chatKey: string) => void;
- refresh: () => Promise<void>;
- sendMessage: (chat: ChatWindow | undefined, body: string) => Promise<boolean>;
- createSession: (agentId: string, label?: string) => Promise<string | null>;
-}
-
-export function useOrchestrationChats(t: Translate): UseOrchestrationChatsResult {
- const [sessionsState, setSessionsState] = useState<SessionsState>({ status: 'loading' });
- const [messagesState, setMessagesState] = useState<MessagesPaneState>({ status: 'idle' });
- const [summaries, setSummaries] = useState<SessionSummary[]>([]);
- const [messagesByChat, setMessagesByChat] = useState<Record<string, ChatMessage[]>>({});
- const [status, setStatus] = useState<OrchestrationStatus | null>(null);
- const [selectedId, setSelectedId] = useState<string>(MASTER_CHAT_KEY);
- const [masterError, setMasterError] = useState<string | null>(null);
- const mountedRef = useRef(true);
- // Track the selected chat for socket handlers without re-subscribing on every change.
- const selectedIdRef = useRef(selectedId);
- selectedIdRef.current = selectedId;
-
- const loadMessages = useCallback(async (chatKey: string) => {
- setMessagesState({ status: 'loading' });
- try {
- const result = await orchestrationClient.messagesList({
- chat: chatKey,
- limit: MESSAGE_LIMIT,
- });
- if (!mountedRef.current) return;
- setMessagesByChat(prev => ({
- ...prev,
- [chatKey]: sortMessages(result.messages.map(mapMessage)),
- }));
- setMessagesState({ status: 'ok' });
- } catch (error) {
- if (!mountedRef.current) return;
- if (error instanceof PaymentRequiredError) {
- setSessionsState({ status: 'payment_required' });
- setMessagesState({ status: 'idle' });
- return;
- }
- const message = error instanceof Error ? error.message : String(error);
- setMessagesState({ status: 'error', message });
- }
- }, []);
-
- const refreshStatus = useCallback(async () => {
- try {
- const next = await orchestrationClient.status();
- if (mountedRef.current) setStatus(next);
- } catch {
- // Status is advisory only — never block the chat surface on it.
- }
- }, []);
-
- const loadSessions = useCallback(async (): Promise<SessionSummary[]> => {
- const result = await orchestrationClient.sessionsList();
- if (mountedRef.current) setSummaries(result.sessions);
- return result.sessions;
- }, []);
-
- const markRead = useCallback(async (chatKey: string) => {
- try {
- await orchestrationClient.markRead(chatKey);
- if (!mountedRef.current) return;
- // Optimistically clear the local unread badge; a refetch reconciles.
- setSummaries(prev =>
- prev.map(s => (chatKeyForSession(s) === chatKey ? { ...s, unread: 0 } : s))
- );
- } catch {
- // Read receipts are best-effort; a failure must not break the pane.
- }
- }, []);
-
- const refresh = useCallback(async () => {
- setSessionsState({ status: 'loading' });
- try {
- await Promise.all([loadSessions(), refreshStatus()]);
- if (!mountedRef.current) return;
- setSessionsState({ status: 'ok' });
- await loadMessages(selectedIdRef.current);
- } catch (error) {
- if (!mountedRef.current) return;
- if (error instanceof PaymentRequiredError) {
- setSessionsState({ status: 'payment_required' });
- return;
- }
- const message = error instanceof Error ? error.message : String(error);
- setSessionsState({ status: 'error', message });
- }
- }, [loadSessions, refreshStatus, loadMessages]);
-
- const selectChat = useCallback(
- (chatKey: string) => {
- if (chatKey === selectedIdRef.current) return;
- setSelectedId(chatKey);
- setMasterError(null);
- void loadMessages(chatKey);
- void markRead(chatKey);
- },
- [loadMessages, markRead]
- );
-
- // Send into a chat. Master/subconscious go to the Master send path; a session
- // chat threads under its own session id (routed to its peer contact).
- const sendMessage = useCallback(
- async (chat: ChatWindow | undefined, rawBody: string): Promise<boolean> => {
- const body = rawBody.trim();
- if (!body || !chat) return false;
- const chatKey = chat.id;
- const isSession = chat.kind === 'session' && !!chat.peerAgentId;
- setMasterError(null);
- const optimistic: ChatMessage = {
- id: `optimistic:${Date.now()}`,
- from: t('tinyplaceOrchestration.master.you'),
- body,
- timestamp: new Date().toISOString(),
- encrypted: false,
- };
- setMessagesByChat(prev => ({
- ...prev,
- [chatKey]: sortMessages([...(prev[chatKey] ?? []), optimistic]),
- }));
- try {
- await orchestrationClient.sendMasterMessage(
- isSession ? { body, recipient: chat.peerAgentId as string, sessionId: chatKey } : { body }
- );
- if (!mountedRef.current) return true;
- // Reconcile against the authoritative server state.
- void loadMessages(chatKey);
- void loadSessions();
- return true;
- } catch (error) {
- if (!mountedRef.current) return false;
- // Roll the optimistic message back out.
- setMessagesByChat(prev => ({
- ...prev,
- [chatKey]: (prev[chatKey] ?? []).filter(m => m.id !== optimistic.id),
- }));
- const message = error instanceof Error ? error.message : String(error);
- setMasterError(message);
- return false;
- }
- },
- [loadMessages, loadSessions, t]
- );
-
- // Create a new empty session for a contact and select it.
- const createSession = useCallback(
- async (agentId: string, label?: string): Promise<string | null> => {
- setMasterError(null);
- try {
- const { session } = await orchestrationClient.sessionsCreate({
- agentId,
- ...(label ? { label } : {}),
- });
- if (!mountedRef.current) return null;
- await loadSessions();
- const key = session.sessionId;
- setSelectedId(key);
- void loadMessages(key);
- return key;
- } catch (error) {
- if (!mountedRef.current) return null;
- const message = error instanceof Error ? error.message : String(error);
- setMasterError(message);
- return null;
- }
- },
- [loadSessions, loadMessages]
- );
-
- // Initial load + mark the default (master) chat read.
- useEffect(() => {
- mountedRef.current = true;
- const handle = window.setTimeout(() => {
- void refresh().then(() => {
- if (mountedRef.current) void markRead(selectedIdRef.current);
- });
- }, 0);
- return () => {
- window.clearTimeout(handle);
- mountedRef.current = false;
- };
- // Run once on mount; refresh/markRead are stable useCallback refs.
- }, [refresh, markRead]);
-
- // Live updates: refetch the affected chat + sessions list on new messages.
- useEffect(() => {
- const handler = (payload: unknown) => {
- const event = payload as OrchestrationMessageEvent | null;
- if (!event || typeof event !== 'object') return;
- const affected = event.chatKind === 'session' ? event.sessionId : event.chatKind;
- void loadSessions();
- void refreshStatus();
- if (affected && affected === selectedIdRef.current) {
- void loadMessages(affected);
- }
- };
- // Register through socketService (not the raw socket): it queues listeners
- // until the socket exists, so live refetch still attaches when the tab mounts
- // while the core socket is still being created or is reconnecting.
- socketService.on('orchestration:message', handler);
- socketService.on('orchestration_message', handler);
- return () => {
- socketService.off('orchestration:message', handler);
- socketService.off('orchestration_message', handler);
- };
- }, [loadSessions, loadMessages, refreshStatus]);
-
- const chats = useMemo(() => {
- return summaries.map(summary =>
- buildChatWindow(summary, messagesByChat[chatKeyForSession(summary)], t)
- );
- }, [summaries, messagesByChat, t]);
-
- const resolvedSelectedId = chats.some(chat => chat.id === selectedId)
- ? selectedId
- : (chats[0]?.id ?? MASTER_CHAT_KEY);
- const selected = chats.find(chat => chat.id === resolvedSelectedId);
-
- return {
- sessionsState,
- messagesState,
- chats,
- selectedId: resolvedSelectedId,
- selected,
- status,
- masterError,
- selectChat,
- refresh,
- sendMessage,
- createSession,
- };
-}
diff --git a/app/src/lib/orchestration/useOrchestrationSessions.test.ts b/app/src/lib/orchestration/useOrchestrationSessions.test.ts
deleted file mode 100644
index 5c40bcbf25..0000000000
--- a/app/src/lib/orchestration/useOrchestrationSessions.test.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { renderHook, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { OrchestrationMessage, SessionSummary } from './orchestrationClient';
-import {
- mapTranscriptMessage,
- useContactSessions,
- useSessionTranscript,
-} from './useOrchestrationSessions';
-
-const sessionsList = vi.hoisted(() => vi.fn());
-const messagesList = vi.hoisted(() => vi.fn());
-vi.mock('./orchestrationClient', async orig => ({
- ...(await orig<typeof import('./orchestrationClient')>()),
- orchestrationClient: { sessionsList, messagesList },
-}));
-vi.mock('../../services/socketService', () => ({ socketService: { on: vi.fn(), off: vi.fn() } }));
-
-const session = (over: Partial<SessionSummary>): SessionSummary => ({
- sessionId: 's1',
- agentId: '@a',
- source: 'claude',
- status: 'idle',
- chatKind: 'session',
- lastMessageAt: '2026-07-08T00:00:00Z',
- unread: 0,
- active: false,
- pinned: false,
- ...over,
-});
-
-describe('mapTranscriptMessage', () => {
- it('maps wire fields incl. tool outcome, defaulting from to role/agentId', () => {
- const wire = {
- id: 'm1',
- agentId: '@a',
- sessionId: 's1',
- chatKind: 'session',
- role: '',
- body: 'out',
- timestamp: 't',
- seq: 1,
- eventKind: 'tool_result',
- toolName: 'Bash',
- callId: 'c1',
- ok: false,
- isError: true,
- exitCode: 2,
- } as OrchestrationMessage;
- const m = mapTranscriptMessage(wire);
- expect(m.from).toBe('@a');
- expect(m.eventKind).toBe('tool_result');
- expect(m.ok).toBe(false);
- expect(m.isError).toBe(true);
- expect(m.exitCode).toBe(2);
- });
-});
-
-describe('useContactSessions', () => {
- beforeEach(() => vi.clearAllMocks());
-
- it('groups session-kind rows by contact agent id', async () => {
- sessionsList.mockResolvedValue({
- sessions: [
- session({ sessionId: 's1', agentId: '@a' }),
- session({ sessionId: 's2', agentId: '@a' }),
- session({ sessionId: 's3', agentId: '@b' }),
- session({ sessionId: 'master', agentId: 'master', chatKind: 'master' }),
- ],
- });
- const { result } = renderHook(() => useContactSessions());
- await waitFor(() => expect(result.current.state.status).toBe('ok'));
- expect(result.current.sessions).toHaveLength(3);
- expect(result.current.byContact.get('@a')).toHaveLength(2);
- expect(result.current.byContact.get('@b')).toHaveLength(1);
- });
-
- it('surfaces an error state', async () => {
- sessionsList.mockRejectedValue(new Error('boom'));
- const { result } = renderHook(() => useContactSessions());
- await waitFor(() => expect(result.current.state.status).toBe('error'));
- });
-});
-
-describe('useSessionTranscript', () => {
- beforeEach(() => vi.clearAllMocks());
-
- it('loads a session transcript', async () => {
- messagesList.mockResolvedValue({
- messages: [
- {
- id: 'm1',
- agentId: '@a',
- sessionId: 's1',
- chatKind: 'session',
- role: 'agent',
- body: 'hi',
- timestamp: 't',
- seq: 1,
- },
- ],
- });
- const { result } = renderHook(() => useSessionTranscript('s1'));
- await waitFor(() => expect(result.current.state.status).toBe('ok'));
- expect(result.current.messages).toHaveLength(1);
- expect(messagesList).toHaveBeenCalledWith({ chat: 's1', limit: 100 });
- });
-
- it('stays idle for a null session', async () => {
- const { result } = renderHook(() => useSessionTranscript(null));
- await waitFor(() => expect(result.current.state.status).toBe('idle'));
- expect(messagesList).not.toHaveBeenCalled();
- });
-});
diff --git a/app/src/lib/orchestration/useOrchestrationSessions.ts b/app/src/lib/orchestration/useOrchestrationSessions.ts
deleted file mode 100644
index 8bcf4bdbc2..0000000000
--- a/app/src/lib/orchestration/useOrchestrationSessions.ts
+++ /dev/null
@@ -1,207 +0,0 @@
-/**
- * Hooks backing the Connections + Agent-chat session surfaces.
- *
- * - {@link useContactSessions}: the sessions list grouped by contact agent id
- * (the `sessionsByContact` map the roster/accordion needs), live-refreshed on
- * the `orchestration:message` socket event.
- * - {@link useSessionTranscript}: the message transcript for one session
- * (lazy-loaded, socket-refreshed), mapped to {@link ChatMessage} for the
- * shared `SessionTranscript` renderer.
- *
- * Kept separate from `useOrchestrationChats` (which owns the pinned master /
- * subconscious chat surface) so a panel pulls in only what it needs.
- */
-import debugFactory from 'debug';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-
-import { socketService } from '../../services/socketService';
-import {
- orchestrationClient,
- type OrchestrationMessage,
- type OrchestrationMessageEvent,
- PaymentRequiredError,
- type SessionSummary,
-} from './orchestrationClient';
-import type { ChatMessage } from './useOrchestrationChats';
-
-const debug = debugFactory('orchestration:sessions');
-
-const TRANSCRIPT_LIMIT = 100;
-
-type SessionsState =
- | { status: 'loading' }
- | { status: 'error'; message: string }
- | { status: 'payment_required' }
- | { status: 'ok' };
-
-interface UseContactSessionsResult {
- state: SessionsState;
- /** All non-pinned session windows. */
- sessions: SessionSummary[];
- /** Sessions grouped by their peer contact agent id. */
- byContact: Map<string, SessionSummary[]>;
- refresh: () => Promise<void>;
-}
-
-function groupByContact(sessions: SessionSummary[]): Map<string, SessionSummary[]> {
- const map = new Map<string, SessionSummary[]>();
- for (const session of sessions) {
- if (session.chatKind !== 'session' || !session.agentId) continue;
- const list = map.get(session.agentId) ?? [];
- list.push(session);
- map.set(session.agentId, list);
- }
- return map;
-}
-
-export function useContactSessions(): UseContactSessionsResult {
- const [state, setState] = useState<SessionsState>({ status: 'loading' });
- const [sessions, setSessions] = useState<SessionSummary[]>([]);
- const mountedRef = useRef(true);
-
- const refresh = useCallback(async () => {
- debug('[orchestration:sessions] contact-sessions refresh: entry');
- try {
- const { sessions: rows } = await orchestrationClient.sessionsList();
- if (!mountedRef.current) return;
- const sessionRows = rows.filter(s => s.chatKind === 'session');
- debug('[orchestration:sessions] contact-sessions refresh: ok count=%d', sessionRows.length);
- setSessions(sessionRows);
- setState({ status: 'ok' });
- } catch (error) {
- if (!mountedRef.current) return;
- if (error instanceof PaymentRequiredError) {
- debug('[orchestration:sessions] contact-sessions refresh: payment_required');
- setState({ status: 'payment_required' });
- return;
- }
- const message = error instanceof Error ? error.message : String(error);
- debug('[orchestration:sessions] contact-sessions refresh: error %s', message);
- setState({ status: 'error', message });
- }
- }, []);
-
- useEffect(() => {
- mountedRef.current = true;
- const handle = window.setTimeout(() => void refresh(), 0);
- const onMessage = (): void => {
- debug('[orchestration:sessions] socket refresh (contact sessions)');
- void refresh();
- };
- socketService.on('orchestration:message', onMessage);
- socketService.on('orchestration_message', onMessage);
- return () => {
- window.clearTimeout(handle);
- mountedRef.current = false;
- socketService.off('orchestration:message', onMessage);
- socketService.off('orchestration_message', onMessage);
- };
- }, [refresh]);
-
- const byContact = useMemo(() => groupByContact(sessions), [sessions]);
- return { state, sessions, byContact, refresh };
-}
-
-/** OrchestrationMessage → ChatMessage view-model row. */
-export function mapTranscriptMessage(message: OrchestrationMessage): ChatMessage {
- return {
- id: message.id,
- from: message.role?.trim() || message.agentId || '',
- body: message.body,
- timestamp: message.timestamp,
- encrypted: false,
- ...(message.eventKind ? { eventKind: message.eventKind } : {}),
- ...(message.toolName ? { toolName: message.toolName } : {}),
- ...(message.callId ? { callId: message.callId } : {}),
- ...(message.ok !== undefined ? { ok: message.ok } : {}),
- ...(message.isError !== undefined ? { isError: message.isError } : {}),
- ...(message.exitCode !== undefined ? { exitCode: message.exitCode } : {}),
- };
-}
-
-type TranscriptState =
- | { status: 'idle' }
- | { status: 'loading' }
- | { status: 'error'; message: string }
- | { status: 'ok' };
-
-interface UseSessionTranscriptResult {
- state: TranscriptState;
- messages: ChatMessage[];
- refresh: () => Promise<void>;
-}
-
-/** Load + live-refresh one session's transcript. Pass `null` to load nothing. */
-export function useSessionTranscript(sessionId: string | null): UseSessionTranscriptResult {
- const [state, setState] = useState<TranscriptState>({ status: 'idle' });
- const [messages, setMessages] = useState<ChatMessage[]>([]);
- const mountedRef = useRef(true);
- // Monotonic request token: only the newest in-flight load may apply its
- // result, so switching `sessionId` can never overwrite state with a slower
- // response for the PREVIOUS session (the shared `mountedRef` alone can't
- // guard this — the new effect re-sets it to true before the stale request
- // resolves).
- const reqRef = useRef(0);
-
- const refresh = useCallback(async () => {
- if (!sessionId) {
- setMessages([]);
- setState({ status: 'idle' });
- return;
- }
- const reqId = ++reqRef.current;
- const target = sessionId;
- debug('[orchestration:sessions] transcript load: entry session=%s req=%d', target, reqId);
- setState(prev => (prev.status === 'ok' ? prev : { status: 'loading' }));
- try {
- const { messages: rows } = await orchestrationClient.messagesList({
- chat: target,
- limit: TRANSCRIPT_LIMIT,
- });
- // Drop a stale response (a newer load started, or we unmounted).
- if (!mountedRef.current || reqRef.current !== reqId) {
- debug(
- '[orchestration:sessions] transcript load: dropped stale session=%s req=%d',
- target,
- reqId
- );
- return;
- }
- debug(
- '[orchestration:sessions] transcript load: ok session=%s count=%d',
- target,
- rows.length
- );
- setMessages(rows.map(mapTranscriptMessage));
- setState({ status: 'ok' });
- } catch (error) {
- if (!mountedRef.current || reqRef.current !== reqId) return;
- const message = error instanceof Error ? error.message : String(error);
- debug('[orchestration:sessions] transcript load: error session=%s %s', target, message);
- setState({ status: 'error', message });
- }
- }, [sessionId]);
-
- useEffect(() => {
- mountedRef.current = true;
- const handle = window.setTimeout(() => void refresh(), 0);
- const onMessage = (payload: unknown): void => {
- const event = payload as OrchestrationMessageEvent | null;
- const affected = event && event.chatKind === 'session' ? event.sessionId : null;
- if (affected && affected === sessionId) {
- debug('[orchestration:sessions] socket refresh (transcript) session=%s', sessionId);
- void refresh();
- }
- };
- socketService.on('orchestration:message', onMessage);
- socketService.on('orchestration_message', onMessage);
- return () => {
- window.clearTimeout(handle);
- mountedRef.current = false;
- socketService.off('orchestration:message', onMessage);
- socketService.off('orchestration_message', onMessage);
- };
- }, [refresh, sessionId]);
-
- return { state, messages, refresh };
-}
diff --git a/app/src/lib/orchestration/usePairing.ts b/app/src/lib/orchestration/usePairing.ts
deleted file mode 100644
index 8677946681..0000000000
--- a/app/src/lib/orchestration/usePairing.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * Shared pairing data hook for the Orchestration sub-pages.
- *
- * Wraps `apiClient.orchestrationPairing.*` (the tiny.place agent contacts graph)
- * so the Connections, Discover, and Usage panels all read one consistent
- * snapshot and run mutating actions (link / accept / decline / block) through the
- * same load→act→reload lifecycle. Kept separate from `useOrchestrationChats`
- * (which owns the chat transcript surface) so a page can pull in only what it
- * needs.
- */
-import debugFactory from 'debug';
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-import { apiClient } from '../agentworld/apiClient';
-import { type PairingSnapshot, PaymentRequiredError } from '../agentworld/invokeApiClient';
-
-const debug = debugFactory('orchestration:pairing');
-
-type PairingState =
- | { status: 'loading' }
- | { status: 'error'; message: string }
- | { status: 'payment_required' }
- | { status: 'ok'; snapshot: PairingSnapshot };
-
-interface UsePairingResult {
- state: PairingState;
- /** Re-fetch the pairing snapshot. */
- reload: () => Promise<void>;
- /** Run a mutating pairing action, then reload; tracks pending id + error. */
- runAction: (actionId: string, fn: () => Promise<unknown>) => Promise<void>;
- /** The id passed to the currently in-flight `runAction`, or null. */
- pendingAction: string | null;
- /** The last action error message, cleared when a new action starts. */
- actionError: string | null;
-}
-
-export function usePairing(): UsePairingResult {
- const [state, setState] = useState<PairingState>({ status: 'loading' });
- const [pendingAction, setPendingAction] = useState<string | null>(null);
- const [actionError, setActionError] = useState<string | null>(null);
- const mountedRef = useRef(true);
-
- const reload = useCallback(async () => {
- debug('reload: entry');
- setState(prev => (prev.status === 'ok' ? prev : { status: 'loading' }));
- try {
- const snapshot = await apiClient.orchestrationPairing.list();
- if (!mountedRef.current) return;
- debug(
- 'reload: ok contacts=%d incoming=%d outgoing=%d',
- snapshot.contacts.contacts.length,
- snapshot.requests.incoming.length,
- snapshot.requests.outgoing.length
- );
- setState({ status: 'ok', snapshot });
- } catch (error) {
- if (!mountedRef.current) return;
- if (error instanceof PaymentRequiredError) {
- debug('reload: payment_required');
- setState({ status: 'payment_required' });
- return;
- }
- const message = error instanceof Error ? error.message : String(error);
- debug('reload: error %s', message);
- setState({ status: 'error', message });
- }
- }, []);
-
- const runAction = useCallback(
- async (actionId: string, fn: () => Promise<unknown>) => {
- debug('runAction: entry id=%s', actionId);
- setPendingAction(actionId);
- setActionError(null);
- try {
- await fn();
- if (!mountedRef.current) return;
- debug('runAction: success id=%s', actionId);
- await reload();
- } catch (error) {
- if (!mountedRef.current) return;
- const message = error instanceof Error ? error.message : String(error);
- debug('runAction: error id=%s %s', actionId, message);
- setActionError(message);
- } finally {
- if (mountedRef.current) setPendingAction(null);
- }
- },
- [reload]
- );
-
- useEffect(() => {
- mountedRef.current = true;
- const handle = window.setTimeout(() => void reload(), 0);
- return () => {
- window.clearTimeout(handle);
- mountedRef.current = false;
- };
- }, [reload]);
-
- return { state, reload, runAction, pendingAction, actionError };
-}
diff --git a/app/src/pages/Brain.tsx b/app/src/pages/Brain.tsx
index 5cdd7f3aa1..ceeccb2ffe 100644
--- a/app/src/pages/Brain.tsx
+++ b/app/src/pages/Brain.tsx
@@ -1,12 +1,10 @@
/**
* Brain — the centerpiece memory surface.
*
- * Sub-tabs: Welcome, Graph, Goals, Sources, Sync, and
- * **Orchestration** (the TinyPlace multi-agent surface, folded back in from the
- * former top-level `/orchestration` tab — see {@link OrchestrationView}).
+ * Sub-tabs: Welcome, Graph, Goals, Sources, and Sync.
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { Navigate, useLocation, useNavigate } from 'react-router-dom';
+import { useLocation, useNavigate } from 'react-router-dom';
import { CodingSessionsCard } from '../components/intelligence/CodingSessionsCard';
import GoalsPanel from '../components/intelligence/GoalsPanel';
@@ -19,10 +17,8 @@ import { ToastContainer } from '../components/intelligence/Toast';
import PageWelcome from '../components/layout/PageWelcome';
import { SidebarContent } from '../components/layout/shell/SidebarSlot';
import TwoPaneNav from '../components/layout/TwoPaneNav';
-import OrchestrationView from '../components/orchestration/OrchestrationView';
import SettingsTabbedPage from '../components/settings/layout/SettingsTabbedPage';
import { Alert, AlertDescription, Card } from '../components/ui';
-import { useTinyPlaceIdentity } from '../hooks/useTinyPlaceIdentity';
import { useT } from '../lib/i18n/I18nContext';
import { useCoreState } from '../providers/CoreStateProvider';
import type { ToastNotification } from '../types/intelligence';
@@ -32,7 +28,7 @@ import {
memoryTreeGraphExport,
} from '../utils/tauriCommands';
-type BrainTab = 'welcome' | 'graph' | 'goals' | 'sources' | 'sync' | 'orchestration';
+type BrainTab = 'welcome' | 'graph' | 'goals' | 'sources' | 'sync';
/** Small inline icon helper for the Brain sidebar nav. */
const navIcon = (d: string) => (
@@ -41,24 +37,12 @@ const navIcon = (d: string) => (
</svg>
);
-const BRAIN_TABS: readonly BrainTab[] = [
- 'welcome',
- 'graph',
- 'goals',
- 'sources',
- 'sync',
- 'orchestration',
-];
+const BRAIN_TABS: readonly BrainTab[] = ['welcome', 'graph', 'goals', 'sources', 'sync'];
/**
* Canonical text header (title + one-line description) per functional tab.
- * Orchestration is excluded — it renders its own full-bleed surface
- * ({@link OrchestrationView}) with its own chip nav, not the shared scaffold.
*/
-const BRAIN_HEADERS: Record<
- Exclude<BrainTab, 'welcome' | 'orchestration'>,
- { titleKey: string; descKey: string }
-> = {
+const BRAIN_HEADERS: Record<Exclude<BrainTab, 'welcome'>, { titleKey: string; descKey: string }> = {
graph: { titleKey: 'brain.tabs.graph', descKey: 'brain.header.graph' },
goals: { titleKey: 'brain.tabs.goals', descKey: 'brain.header.goals' },
sources: { titleKey: 'brain.tabs.sources', descKey: 'brain.header.sources' },
@@ -83,28 +67,6 @@ export default function Brain() {
},
[location.pathname, location.search, navigate]
);
- // Back-compat: the old `?tab=tinyplace-orchestration` slug (from when
- // Orchestration was briefly a top-level tab) now maps to the folded-in
- // Orchestration sub-tab.
- useEffect(() => {
- if (new URLSearchParams(location.search).get('tab') === 'tinyplace-orchestration') {
- console.debug('[brain] legacy tinyplace-orchestration deep link → ?tab=orchestration');
- navigate('/brain?tab=orchestration', { replace: true });
- }
- }, [location.search, navigate]);
-
- // #5424 — the Orchestration sub-tab is a tiny.place surface, hidden from users
- // without an identity. If a *confirmed* non-holder lands on `?tab=orchestration`
- // via a stale deep link, redirect to the Brain welcome tab. This is a
- // render-phase redirect (not a post-commit effect), so once the check resolves
- // to a non-holder OrchestrationView never mounts. While the check is still in
- // flight we render optimistically — matching the AgentWorldShell route guard —
- // so a holder (the common case) never sees a flash; the brief optimistic window
- // for a stale non-holder link is the deliberate trade-off.
- const { status: tinyplaceStatus, hasIdentity: hasTinyplaceIdentity } = useTinyPlaceIdentity();
- const shouldRedirectFromOrchestration =
- activeTab === 'orchestration' && tinyplaceStatus === 'ready' && !hasTinyplaceIdentity;
-
const [graph, setGraph] = useState<GraphExportResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const [mode, setMode] = useState<GraphMode>('tree');
@@ -130,15 +92,6 @@ export default function Brain() {
const refresh = useCallback(() => setRefreshKey(k => k + 1), []);
useEffect(() => {
- // Orchestration is a full-bleed sub-tab that never renders the memory graph,
- // so skip the export RPC + memory-tree listener entirely while it's active.
- // Without this, folding Orchestration under Brain would fire an unrelated
- // graph load on every `/brain?tab=orchestration` (and redirected
- // `/orchestration`) visit, which the old standalone page never did.
- if (activeTab === 'orchestration') {
- console.debug('[brain] graph fetch: skipped (orchestration tab)');
- return;
- }
let cancelled = false;
const load = async () => {
console.debug('[brain] graph fetch: entry mode=%s', mode);
@@ -170,14 +123,8 @@ export default function Brain() {
};
// `authUserId` is a dependency so a logout→login (identity becomes
// available again) re-pulls the persisted graph instead of leaving the
- // signed-out empty state on screen (#4149). `activeTab` gates the fetch off
- // on the Orchestration sub-tab (and re-runs it when returning to a
- // graph-bearing tab).
- }, [mode, refreshKey, authUserId, activeTab]);
-
- if (shouldRedirectFromOrchestration) {
- return <Navigate to="/brain" replace />;
- }
+ // signed-out empty state on screen (#4149).
+ }, [mode, refreshKey, authUserId]);
return (
<div className="h-full">
@@ -217,36 +164,13 @@ export default function Brain() {
'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15'
),
},
- // TinyPlace multi-agent orchestration, folded back under Brain
- // from the former top-level `/orchestration` tab. Hidden from
- // users without a tiny.place identity (#5424).
- ...(hasTinyplaceIdentity
- ? [
- {
- value: 'orchestration',
- label: t('brain.tabs.orchestration'),
- icon: navIcon(
- 'M12 7v3m0 0l-5.5 6M12 10l5.5 6M12 5a2 2 0 100 0M5 19a2 2 0 100 0M19 19a2 2 0 100 0'
- ),
- },
- ]
- : []),
],
},
]}
/>
</div>
</SidebarContent>
- {activeTab === 'orchestration' ? (
- // Full-bleed: OrchestrationView renders its own chip nav + surfaces
- // (chat, graph, task board), which need the full content width — so it
- // sits outside the shared max-w scaffold the other tabs use.
- <div className="flex h-full flex-col">
- <div className="min-h-0 flex-1">
- <OrchestrationView />
- </div>
- </div>
- ) : (
+ {
// Full width on purpose: the header band has to run edge to edge across
// the content card, so the width cap cannot live above it. Each tab's
// body carries its own `mx-auto max-w-3xl`, which is what the old
@@ -304,13 +228,8 @@ export default function Brain() {
than a bordered card floating in the content column. */
<div className="h-full p-4">
<SettingsTabbedPage
- title={t(
- BRAIN_HEADERS[activeTab as Exclude<BrainTab, 'welcome' | 'orchestration'>]
- .titleKey
- )}
- description={t(
- BRAIN_HEADERS[activeTab as Exclude<BrainTab, 'welcome' | 'orchestration'>].descKey
- )}>
+ title={t(BRAIN_HEADERS[activeTab as Exclude<BrainTab, 'welcome'>].titleKey)}
+ description={t(BRAIN_HEADERS[activeTab as Exclude<BrainTab, 'welcome'>].descKey)}>
<div className="w-full space-y-5">
{activeTab === 'graph' && (
<div className="space-y-5 animate-fade-up">
@@ -366,7 +285,7 @@ export default function Brain() {
</div>
)}
</div>
- )}
+ }
<ToastContainer notifications={toasts} onRemove={removeToast} />
</div>
diff --git a/app/src/pages/__tests__/Brain.test.tsx b/app/src/pages/__tests__/Brain.test.tsx
index f5b2fa3a5a..65e6548f67 100644
--- a/app/src/pages/__tests__/Brain.test.tsx
+++ b/app/src/pages/__tests__/Brain.test.tsx
@@ -1,43 +1,20 @@
import { act, screen, waitFor } from '@testing-library/react';
-import { useLocation } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { renderWithProviders } from '../../test/test-utils';
import Brain from '../Brain';
-/** Renders the live router pathname so redirect tests can assert the final route. */
-function LocationProbe() {
- return <div data-testid="location-pathname">{useLocation().pathname}</div>;
-}
-
const graphExportMock = vi.hoisted(() => vi.fn());
// Controllable authenticated identity so we can simulate a logout→login cycle
// (userId null → set) and assert the graph reloads (#4149).
const coreAuthRef = vi.hoisted(() => ({ current: 'user-A' as string | null }));
-// Captures navigate() calls so we can assert the legacy TinyPlace-orchestration
-// deep link bounces to the folded-in Orchestration sub-tab.
const navigateSpy = vi.hoisted(() => vi.fn());
-// Fires on every OrchestrationView render, so a redirect test can prove the
-// gated surface never mounted (not merely that it left the DOM afterwards).
-const orchestrationRenderSpy = vi.hoisted(() => vi.fn());
-// Controllable tiny.place identity so we can render Brain as a holder (default)
-// or a confirmed non-holder hitting the gated `?tab=orchestration` deep link.
-const tinyplaceIdentityRef = vi.hoisted(() => ({
- current: { status: 'ready', hasIdentity: true } as {
- status: 'loading' | 'ready';
- hasIdentity: boolean;
- },
-}));
vi.mock('react-router-dom', async importOriginal => {
const actual = await importOriginal<typeof import('react-router-dom')>();
return { ...actual, useNavigate: () => navigateSpy };
});
-vi.mock('../../hooks/useTinyPlaceIdentity', () => ({
- useTinyPlaceIdentity: () => tinyplaceIdentityRef.current,
-}));
-
vi.mock('../../utils/tauriCommands', () => ({
memoryTreeGraphExport: graphExportMock,
isTauri: () => false,
@@ -69,16 +46,6 @@ vi.mock('../../components/layout/ChipTabs', async () => {
};
});
vi.mock('../../components/ui/BetaBanner', () => ({ default: () => null }));
-vi.mock('../../components/orchestration/OrchestrationView', async () => {
- const React = await import('react');
- return {
- default: () => {
- orchestrationRenderSpy();
- return React.createElement('div', { 'data-testid': 'brain-orchestration' });
- },
- };
-});
-
vi.mock('../../components/intelligence/MemoryControls', () => ({ MemoryControls: () => null }));
vi.mock('../../components/intelligence/MemoryTreeStatusPanel', async () => {
const React = await import('react');
@@ -110,7 +77,6 @@ describe('Brain page', () => {
beforeEach(() => {
vi.clearAllMocks();
coreAuthRef.current = 'user-A';
- tinyplaceIdentityRef.current = { status: 'ready', hasIdentity: true };
});
afterEach(() => {
@@ -196,74 +162,4 @@ describe('Brain page', () => {
expect(screen.getByTestId('brain-sync-audit')).toBeInTheDocument();
});
});
-
- it('renders the folded-in Orchestration view on the orchestration tab', async () => {
- graphExportMock.mockResolvedValue(makeGraph(0));
- await act(async () => {
- renderWithProviders(<Brain />, { initialEntries: ['/?tab=orchestration'] });
- });
- await waitFor(() => {
- expect(screen.getByTestId('brain-orchestration')).toBeInTheDocument();
- });
- });
-
- it('does not fetch the memory graph on the orchestration tab', async () => {
- graphExportMock.mockResolvedValue(makeGraph(0));
- await act(async () => {
- renderWithProviders(<Brain />, { initialEntries: ['/?tab=orchestration'] });
- });
- await waitFor(() => {
- expect(screen.getByTestId('brain-orchestration')).toBeInTheDocument();
- });
- // Folding Orchestration under Brain must not trigger the unrelated
- // memoryTreeGraphExport RPC that the standalone page never issued.
- expect(graphExportMock).not.toHaveBeenCalled();
- });
-
- it('redirects a confirmed non-holder away from ?tab=orchestration without mounting OrchestrationView', async () => {
- // #5424 — the redirect is render-phase, so the gated tiny.place surface must
- // never mount (not even for a single commit) once the identity check
- // resolves to a non-holder.
- tinyplaceIdentityRef.current = { status: 'ready', hasIdentity: false };
- graphExportMock.mockResolvedValue(makeGraph(0));
- await act(async () => {
- renderWithProviders(
- <>
- <Brain />
- <LocationProbe />
- </>,
- { initialEntries: ['/?tab=orchestration'] }
- );
- });
- // Render-phase guard: OrchestrationView must never mount — asserting on the
- // spy (not just final DOM) catches a regression that mounts then redirects
- // from an effect.
- expect(orchestrationRenderSpy).not.toHaveBeenCalled();
- expect(screen.queryByTestId('brain-orchestration')).not.toBeInTheDocument();
- // Router landed on the Brain welcome tab.
- expect(screen.getByTestId('location-pathname')).toHaveTextContent('/brain');
- expect(screen.getByTestId('brain-welcome')).toBeInTheDocument();
- });
-
- it('keeps rendering OrchestrationView while the identity check is still loading', async () => {
- // The in-flight window must not redirect — only a *confirmed* non-holder does.
- tinyplaceIdentityRef.current = { status: 'loading', hasIdentity: false };
- graphExportMock.mockResolvedValue(makeGraph(0));
- await act(async () => {
- renderWithProviders(<Brain />, { initialEntries: ['/?tab=orchestration'] });
- });
- await waitFor(() => {
- expect(screen.getByTestId('brain-orchestration')).toBeInTheDocument();
- });
- });
-
- it('redirects the legacy tinyplace-orchestration deep link to the orchestration tab', async () => {
- graphExportMock.mockResolvedValue(makeGraph(0));
- await act(async () => {
- renderWithProviders(<Brain />, { initialEntries: ['/?tab=tinyplace-orchestration'] });
- });
- await waitFor(() => {
- expect(navigateSpy).toHaveBeenCalledWith('/brain?tab=orchestration', { replace: true });
- });
- });
});
diff --git a/app/src/pages/__tests__/OrchestrationRedirect.test.tsx b/app/src/pages/__tests__/OrchestrationRedirect.test.tsx
deleted file mode 100644
index f35fa3bff1..0000000000
--- a/app/src/pages/__tests__/OrchestrationRedirect.test.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * OrchestrationRedirect maps the retired `/orchestration` route (and its legacy
- * `?tab=`/`?sub=`/`?session=` query) onto Brain's `/brain?tab=orchestration`
- * with the `?ov=`/`?sub=` scheme. Rendered under a MemoryRouter with a `/brain`
- * sink route that reports the resolved URL so each mapping branch is asserted.
- */
-import { render, screen } from '@testing-library/react';
-import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
-import { describe, expect, it } from 'vitest';
-
-import { OrchestrationRedirect } from '../../AppRoutes';
-
-function BrainProbe() {
- const { pathname, search } = useLocation();
- return <div data-testid="brain">{`${pathname}${search}`}</div>;
-}
-
-const resolve = (from: string): string => {
- render(
- <MemoryRouter initialEntries={[from]}>
- <Routes>
- <Route path="/orchestration" element={<OrchestrationRedirect />} />
- <Route path="/brain" element={<BrainProbe />} />
- </Routes>
- </MemoryRouter>
- );
- const target = screen.getByTestId('brain').textContent ?? '';
- const params = new URLSearchParams(target.split('?')[1] ?? '');
- return `${target.split('?')[0]}?${params.toString()}`;
-};
-
-describe('OrchestrationRedirect', () => {
- it('bare /orchestration → the orchestration tab (no view override)', () => {
- const params = new URLSearchParams(resolve('/orchestration').split('?')[1]);
- expect(params.get('tab')).toBe('orchestration');
- expect(params.get('ov')).toBeNull();
- });
-
- it.each(['agent', 'overview', 'tasks', 'network', 'medulla'])('legacy ?tab=%s → ?ov=%s', view => {
- const params = new URLSearchParams(resolve(`/orchestration?tab=${view}`).split('?')[1]);
- expect(params.get('tab')).toBe('orchestration');
- expect(params.get('ov')).toBe(view);
- });
-
- it.each(['connections', 'discover', 'usage'])('legacy ?tab=%s → ?ov=network&sub=%s', sub => {
- const params = new URLSearchParams(resolve(`/orchestration?tab=${sub}`).split('?')[1]);
- expect(params.get('ov')).toBe('network');
- expect(params.get('sub')).toBe(sub);
- });
-
- it('preserves a network ?sub= when landing on ?tab=network', () => {
- const params = new URLSearchParams(
- resolve('/orchestration?tab=network&sub=usage').split('?')[1]
- );
- expect(params.get('ov')).toBe('network');
- expect(params.get('sub')).toBe('usage');
- });
-
- it('preserves ?session= for the agent chat', () => {
- const params = new URLSearchParams(
- resolve('/orchestration?tab=agent&session=sess-1').split('?')[1]
- );
- expect(params.get('ov')).toBe('agent');
- expect(params.get('session')).toBe('sess-1');
- });
-
- it('ignores an unknown ?tab= (falls back to the orchestration tab)', () => {
- const params = new URLSearchParams(resolve('/orchestration?tab=bogus').split('?')[1]);
- expect(params.get('tab')).toBe('orchestration');
- expect(params.get('ov')).toBeNull();
- });
-});
diff --git a/app/src/store/chatRuntimeSlice.test.ts b/app/src/store/chatRuntimeSlice.test.ts
index 99a2224d32..4bedcb0735 100644
--- a/app/src/store/chatRuntimeSlice.test.ts
+++ b/app/src/store/chatRuntimeSlice.test.ts
@@ -27,8 +27,8 @@ function makeRun(id: string, status: AgentRunStatus): AgentRun {
id,
kind: 'subagent',
status,
- agentId: 'tinyplace_agent',
- metadata: { displayName: 'Tinyplace Agent' },
+ agentId: 'research_agent',
+ metadata: { displayName: 'Research Agent' },
startedAt: '2026-06-23T00:00:00Z',
updatedAt: '2026-06-23T00:00:00Z',
};
@@ -338,35 +338,30 @@ describe('chatRuntimeSlice queue status', () => {
hydrateRuntimeFromSnapshot({
snapshot: makeInterruptedSnapshot('t1', [
{
- id: 't1:subagent:s1:tinyplace_agent',
- name: 'subagent:tinyplace_agent',
+ id: 't1:subagent:s1:research_agent',
+ name: 'subagent:research_agent',
round: 1,
status: 'running',
- subagent: {
- taskId: 's1',
- agentId: 'tinyplace_agent',
- status: 'running',
- toolCalls: [],
- },
+ subagent: { taskId: 's1', agentId: 'research_agent', status: 'running', toolCalls: [] },
},
{
- id: 't1:subagent:s2:tinyplace_agent',
- name: 'subagent:tinyplace_agent',
+ id: 't1:subagent:s2:research_agent',
+ name: 'subagent:research_agent',
round: 1,
status: 'success',
subagent: {
taskId: 's2',
- agentId: 'tinyplace_agent',
+ agentId: 'research_agent',
status: 'completed',
toolCalls: [],
},
},
{
- id: 't1:subagent:s3:tinyplace_agent',
- name: 'subagent:tinyplace_agent',
+ id: 't1:subagent:s3:research_agent',
+ name: 'subagent:research_agent',
round: 1,
status: 'error',
- subagent: { taskId: 's3', agentId: 'tinyplace_agent', status: 'failed', toolCalls: [] },
+ subagent: { taskId: 's3', agentId: 'research_agent', status: 'failed', toolCalls: [] },
},
]),
})
@@ -415,11 +410,11 @@ describe('chatRuntimeSlice queue status', () => {
entries: [
{
id: 't-dup:subagent:run-1:spawn_subagent',
- name: 'subagent:tinyplace_agent',
+ name: 'subagent:research_agent',
round: 1,
seq: 0,
status: 'running',
- subagent: { taskId: 'run-1', agentId: 'tinyplace_agent', toolCalls: [] },
+ subagent: { taskId: 'run-1', agentId: 'research_agent', toolCalls: [] },
},
],
})
diff --git a/app/src/types/api.ts b/app/src/types/api.ts
index 71c607368c..fb436080da 100644
--- a/app/src/types/api.ts
+++ b/app/src/types/api.ts
@@ -53,14 +53,6 @@ export interface User {
referral: UserReferral;
subscription: UserSubscription;
role: 'admin' | 'team' | 'user';
- /**
- * Backend entitlement flag: whether this user has access to Medulla (the
- * orchestration model) and the live orchestration engine. When absent or
- * `false`, the Orchestration page renders a showcase/demo of what
- * orchestration looks like at scale instead of the live surfaces. Set true
- * for subscribers granted early access.
- */
- hasMedullaAccess?: boolean;
settings: UserSettings;
autoDeleteTelegramMessagesAfterDays: number;
autoDeleteThreadsAfterDays: number;
diff --git a/app/src/utils/links.ts b/app/src/utils/links.ts
index 9434eefdc1..ae749191d5 100644
--- a/app/src/utils/links.ts
+++ b/app/src/utils/links.ts
@@ -1,8 +1,5 @@
export const DISCORD_INVITE_URL = 'https://discord.tinyhumans.ai';
export const PRICING_URL = 'https://tinyhumans.ai/pricing';
export const BILLING_DASHBOARD_URL = 'https://tinyhumans.ai/dashboard';
-/** tiny.place — the agent network. Kept working outside the app after the
- * in-app surface is removed (#5424); the sunset notice links here. */
-export const TINYPLACE_URL = 'https://tiny.place';
export const PRIVACY_POLICY_URL = 'https://tinyhumans.gitbook.io/openhuman/legal/privacy-policy';
export const TERMS_OF_USE_URL = 'https://tinyhumans.gitbook.io/openhuman/legal/terms-of-use';
diff --git a/app/test/playwright/specs/tinyplace-messaging.spec.ts b/app/test/playwright/specs/tinyplace-messaging.spec.ts
deleted file mode 100644
index 2e9fae723c..0000000000
--- a/app/test/playwright/specs/tinyplace-messaging.spec.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-// Core-RPC e2e: tiny.place direct messaging between the app's own core (Alice)
-// and a second real openhuman-core (Bob), against a real tiny.place backend.
-//
-// This used to also drive the in-app Messaging UI (the `/agent-world/messaging`
-// route), but that surface was removed (#5424) along with the rest of the
-// Agent World / tiny.place UI. What remains here is the part with independent
-// value: proving that the app's own bootstrapped core (the one the web-session
-// harness launches, PW_CORE_RPC_URL) can complete a full encrypted DM round
-// trip against a real peer core and a real backend — not just the manually
-// launched pair the core suite at e2e/tinyplace-messaging/messaging.e2e.mjs
-// already exercises exhaustively (contact request/accept, refusal between
-// non-contacts, ciphertext-only relay, ratchet reply, etc. — not re-asserted
-// here to avoid duplicating that suite).
-//
-// Requires the web session harness (app/scripts/e2e-web-session.sh) with
-// TINYPLACE_API_BASE_URL exported so the core hits a real backend. The
-// messaging e2e runner (e2e/tinyplace-messaging/run-ui.sh) wires this up.
-import { expect, test } from '@playwright/test';
-
-// The core-launch helper is shared with the core-level suite (plain ESM).
-import { launchAgent, receiveMessage } from '../../../../e2e/tinyplace-messaging/lib/core.mjs';
-
-const CORE_RPC_URL = process.env.PW_CORE_RPC_URL || 'http://127.0.0.1:17788/rpc';
-const CORE_RPC_TOKEN = process.env.PW_CORE_RPC_TOKEN || 'openhuman-playwright-token';
-const BACKEND = process.env.TINYPLACE_API_BASE_URL || 'http://localhost:18080';
-const HAS_TINYPLACE_BACKEND = Boolean(process.env.TINYPLACE_API_BASE_URL);
-
-const TEST_MNEMONIC_WORDS = 12;
-// A fresh, valid BIP-39 mnemonic for Alice (the app's core identity). Generated
-// via the same dependency-free generator the core suite uses.
-async function freshMnemonic(): Promise<string> {
- const { generateMnemonic } = await import('../../../../e2e/tinyplace-messaging/lib/mnemonic.mjs');
- const m = generateMnemonic();
- if (m.split(' ').length !== TEST_MNEMONIC_WORDS) throw new Error('unexpected mnemonic length');
- return m;
-}
-
-const PLACEHOLDER_ACCOUNTS = [
- {
- chain: 'evm',
- address: '0x0000000000000000000000000000000000000001',
- derivationPath: "m/44'/60'/0'/0/0",
- },
- {
- chain: 'btc',
- address: 'bc1qplaceholderplaceholderplaceholderplac0000',
- derivationPath: "m/84'/0'/0'/0/0",
- },
- {
- chain: 'solana',
- address: '11111111111111111111111111111111',
- derivationPath: "m/44'/501'/0'/0'",
- },
- {
- chain: 'tron',
- address: 'T0000000000000000000000000000000001',
- derivationPath: "m/44'/195'/0'/0/0",
- },
-];
-
-/** Call Alice's (the app's) core over JSON-RPC and unwrap the {logs,result}. */
-async function aliceRpc<T = any>(method: string, params: Record<string, unknown> = {}): Promise<T> {
- const res = await fetch(CORE_RPC_URL, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${CORE_RPC_TOKEN}` },
- body: JSON.stringify({ jsonrpc: '2.0', id: Date.now(), method, params }),
- });
- const body = await res.json();
- if (body.error) throw new Error(`${method} -> ${JSON.stringify(body.error)}`);
- let result = body.result;
- if (result && typeof result === 'object' && 'result' in result && 'logs' in result) {
- result = result.result;
- }
- return result as T;
-}
-
-// Wraps aliceRpc as a `{ rpc }` handle so it can be passed to the shared
-// `receiveMessage` helper the same way a `launchAgent()` handle is.
-const aliceCore = { rpc: aliceRpc };
-
-let bob: Awaited<ReturnType<typeof launchAgent>>;
-let aliceCryptoId: string;
-
-test.describe('tiny.place direct messaging (core RPC)', () => {
- test.skip(
- !HAS_TINYPLACE_BACKEND,
- 'requires TINYPLACE_API_BASE_URL from the dedicated tiny.place E2E runner'
- );
- test.describe.configure({ mode: 'serial' });
-
- test.beforeAll(async () => {
- // 1) Give the app's core a fresh tiny.place identity + published Signal keys.
- const mnemonic = await freshMnemonic();
- const encryptedMnemonic = await aliceRpc<string>('openhuman.encrypt_secret', {
- plaintext: mnemonic,
- });
- await aliceRpc('openhuman.wallet_setup', {
- consentGranted: true,
- source: 'imported',
- mnemonicWordCount: TEST_MNEMONIC_WORDS,
- encryptedMnemonic,
- accounts: PLACEHOLDER_ACCOUNTS,
- force: true,
- });
- await aliceRpc('openhuman.tinyplace_signal_provision', { preKeyCount: 10 });
- await aliceRpc('openhuman.tinyplace_signal_register_encryption_key', {});
- const status = await aliceRpc<{ agentId: string }>('openhuman.tinyplace_signal_key_status', {});
- aliceCryptoId = status.agentId;
- expect(aliceCryptoId, 'app core produced a cryptoId').toBeTruthy();
-
- // 2) Launch the peer core (Bob) and make Alice + Bob accepted contacts so
- // the relay will carry their DMs.
- bob = await launchAgent('pw-bob', { port: 17851, backend: BACKEND });
- await aliceRpc('openhuman.tinyplace_contacts_request', { agentId: bob.cryptoId });
- await bob.rpc('openhuman.tinyplace_contacts_accept', { agentId: aliceCryptoId });
- });
-
- test.afterAll(() => {
- bob?.stop();
- });
-
- test('Alice sends an encrypted DM the peer decrypts, and decrypts the peer reply', async () => {
- // Send an end-to-end encrypted message from the app's own core.
- const outgoing = `alice → bob @ ${Date.now()}`;
- const sent = await aliceRpc<{ encrypted: boolean; messageId: string }>(
- 'openhuman.tinyplace_signal_send_message',
- { recipient: bob.cryptoId, plaintext: outgoing }
- );
- expect(sent.encrypted, 'send reports the message was encrypted').toBe(true);
-
- // The real peer core receives + decrypts exactly what the app's core sent.
- const received = await receiveMessage(bob, { fromCryptoId: aliceCryptoId, timeoutMs: 12_000 });
- expect(received, 'peer decrypts the message sent from the app core').toBe(outgoing);
-
- // Now the peer replies; the app's own core must receive + decrypt it.
- const reply = `bob → alice @ ${Date.now()}`;
- await bob.rpc('openhuman.tinyplace_signal_send_message', {
- recipient: aliceCryptoId,
- plaintext: reply,
- });
-
- const decrypted = await receiveMessage(aliceCore, {
- fromCryptoId: bob.cryptoId,
- timeoutMs: 15_000,
- });
- expect(decrypted, 'app core decrypts the peer reply').toBe(reply);
- });
-});
diff --git a/docs/README.de.md b/docs/README.de.md
index 50ff4f1731..4a16b629e6 100644
--- a/docs/README.de.md
+++ b/docs/README.de.md
@@ -73,7 +73,6 @@ OpenHuman ist drei Dinge, die die meisten Assistenten nicht sind: **ein Gehirn**
- **[Workflows](https://tinyhumans.gitbook.io/openhuman/features/workflows)**: der Agent schlägt die Automatisierung vor; du prüfst sie auf einer Canvas und speicherst. Dauerhafte, trigger-gesteuerte, freigabe-gesicherte Läufe auf dem quelloffenen [tinyflows](https://github.com/tinyhumansai/tinyflows).
- **[Ein Harness, das die Arbeit zu Ende bringt](https://tinyhumans.gitbook.io/openhuman/developing/architecture/agent-harness)**: checkpointed Graph-Läufe auf dem quelloffenen [tinyagents](https://github.com/tinyhumansai/tinyagents). Festgefahrene Agenten werden nachgesteuert, gestoppte liefern eine Root Cause zurück, jeder Lauf lässt sich mit echten Kosten pro Aufruf wieder abspielen.
- **[Ein Split Brain, immer an](https://tinyhumans.gitbook.io/openhuman/features/orchestration)**: ein schneller Reflex-Agent triagiert eingehenden Traffic, während ein tiefer Reasoning-Kern an Worker-Flotten delegiert, gesteuert vom Unterbewusstsein.
-- **[Eine Agenten-Ökonomie](https://tinyhumans.gitbook.io/openhuman/features/tinyplace)**: ein `@handle` auf [tiny.place](https://tiny.place), Signal-verschlüsselte Agent-zu-Agent-Orchestrierung, x402-USDC-Bounties und Handel. Keys berühren nie die Festplatte.
### 🔬 Der Deep Researcher & Macher
diff --git a/docs/README.ja-JP.md b/docs/README.ja-JP.md
index 785a7109bc..45aafc1725 100644
--- a/docs/README.ja-JP.md
+++ b/docs/README.ja-JP.md
@@ -73,7 +73,6 @@ OpenHuman は、ほとんどのアシスタントが持っていない 3 つの
- **[Workflows](https://tinyhumans.gitbook.io/openhuman/features/workflows)**: エージェントが自動化を提案し、あなたはキャンバス上でレビューして保存します。オープンソースの [tinyflows](https://github.com/tinyhumansai/tinyflows) 上で、永続的・トリガー駆動・承認ゲート付きの実行が行われます。
- **[仕事をやり遂げるハーネス](https://tinyhumans.gitbook.io/openhuman/developing/architecture/agent-harness)**: オープンソースの [tinyagents](https://github.com/tinyhumansai/tinyagents) 上でのチェックポイント付きグラフ実行です。行き詰まったエージェントは軌道修正され、停止したエージェントは根本原因を返し、すべての実行は呼び出しごとの実コスト付きでリプレイできます。
- **[常時稼働のスプリットブレイン](https://tinyhumans.gitbook.io/openhuman/features/orchestration)**: 高速な反射エージェントが受信トラフィックをトリアージし、深い推論コアがワーカー艦隊に委任します。サブコンシャスがそれを操縦します。
-- **[エージェントの経済圏](https://tinyhumans.gitbook.io/openhuman/features/tinyplace)**: [tiny.place](https://tiny.place) 上の `@handle`、Signal 暗号化のエージェント間オーケストレーション、x402 USDC バウンティと取引。鍵はディスクに一切触れません。
### 🔬 ディープリサーチャー & 実行者
diff --git a/docs/README.ko.md b/docs/README.ko.md
index e740f8e16c..54fdaf12c5 100644
--- a/docs/README.ko.md
+++ b/docs/README.ko.md
@@ -73,7 +73,6 @@ OpenHuman은 대부분의 어시스턴트가 갖지 못한 세 가지입니다:
- **[Workflows](https://tinyhumans.gitbook.io/openhuman/features/workflows)**: 에이전트가 자동화를 제안하면 캔버스에서 검토하고 저장하면 됩니다. 내구성 있고, 트리거 기반이며, 승인 게이트를 거치는 실행이 오픈 소스 [tinyflows](https://github.com/tinyhumansai/tinyflows) 위에서 동작합니다.
- **[일을 끝까지 마무리하는 하네스](https://tinyhumans.gitbook.io/openhuman/developing/architecture/agent-harness)**: 오픈 소스 [tinyagents](https://github.com/tinyhumansai/tinyagents) 기반의 체크포인트 그래프 실행입니다. 막힌 에이전트는 방향을 조정받고, 중단된 에이전트는 근본 원인을 돌려주며, 모든 실행은 호출별 실제 비용과 함께 재생됩니다.
- **[상시 가동되는 분할 두뇌(split brain)](https://tinyhumans.gitbook.io/openhuman/features/orchestration)**: 빠른 반사 에이전트가 들어오는 트래픽을 분류하는 동안 깊은 추론 코어가 워커 함대에 작업을 위임하며, 잠재의식이 이를 조종합니다.
-- **[에이전트 경제](https://tinyhumans.gitbook.io/openhuman/features/tinyplace)**: [tiny.place](https://tiny.place)의 `@handle`, Signal로 암호화된 에이전트 간 오케스트레이션, x402 USDC 바운티와 거래까지 제공합니다. 키는 디스크에 절대 닿지 않습니다.
### 🔬 깊이 있는 리서처이자 실행가
diff --git a/docs/README.ur-pk.md b/docs/README.ur-pk.md
index 8b927ee69b..4ae8179733 100644
--- a/docs/README.ur-pk.md
+++ b/docs/README.ur-pk.md
@@ -87,7 +87,6 @@ OpenHuman تین چیزیں ہے جو زیادہ تر اسسٹنٹس نہیں ہ
- **[ورک فلوز](https://tinyhumans.gitbook.io/openhuman/features/workflows)**: ایجنٹ آٹومیشن تجویز کرتا ہے؛ آپ اسے کینوس پر جائزہ لے کر محفوظ کرتے ہیں۔ اوپن سورس [tinyflows](https://github.com/tinyhumansai/tinyflows) پر پائیدار، ٹرگر سے چلنے والے، منظوری سے محفوظ رنز۔
- **[ایک ہارنس جو کام مکمل کرتا ہے](https://tinyhumans.gitbook.io/openhuman/developing/architecture/agent-harness)**: اوپن سورس [tinyagents](https://github.com/tinyhumansai/tinyagents) پر چیک پوائنٹ شدہ گراف رنز۔ اٹکے ہوئے ایجنٹس کو راہ دکھائی جاتی ہے، رکے ہوئے بنیادی وجہ واپس دیتے ہیں، ہر رن حقیقی فی کال لاگت کے ساتھ دوبارہ چلایا جا سکتا ہے۔
- **[ایک split brain، ہمیشہ فعال](https://tinyhumans.gitbook.io/openhuman/features/orchestration)**: ایک تیز reflex ایجنٹ آنے والی ٹریفک کو چھانٹتا ہے جبکہ ایک گہرا reasoning کور ورکر فلیٹس کو کام سونپتا ہے، لاشعور کی رہنمائی میں۔
-- **[ایک ایجنٹ معیشت](https://tinyhumans.gitbook.io/openhuman/features/tinyplace)**: [tiny.place](https://tiny.place) پر ایک `@handle`، Signal-انکرپٹڈ ایجنٹ سے ایجنٹ آرکسٹریشن، x402 USDC انعامی کام اور تجارت۔ چابیاں کبھی ڈسک کو نہیں چھوتیں۔
### 🔬 گہرا محقق اور کام کرنے والا
diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md
index 1195f19935..ca9a60394f 100644
--- a/docs/README.zh-CN.md
+++ b/docs/README.zh-CN.md
@@ -73,7 +73,6 @@ OpenHuman 是大多数助手所不具备的三样东西的集合:**一颗大
- **[Workflows](https://tinyhumans.gitbook.io/openhuman/features/workflows)**:智能体提出自动化方案;你在画布上审阅并保存。持久化、触发器驱动、审批把关的运行,基于开源的 [tinyflows](https://github.com/tinyhumansai/tinyflows)。
- **[能把事情做完的执行框架](https://tinyhumans.gitbook.io/openhuman/developing/architecture/agent-harness)**:基于开源 [tinyagents](https://github.com/tinyhumansai/tinyagents) 的检查点式图运行:卡住的智能体会被引导回正轨,中止的会交回根因,每次运行都可回放并附带真实的每次调用成本。
- **[常驻的分脑](https://tinyhumans.gitbook.io/openhuman/features/orchestration)**:一个快速反应智能体负责分流入站流量,一个深度推理核心负责向工作者舰队分派任务,由潜意识统一调度。
-- **[智能体经济](https://tinyhumans.gitbook.io/openhuman/features/tinyplace)**:在 [tiny.place](https://tiny.place) 上的 `@handle`、Signal 加密的智能体间编排、x402 USDC 赏金与交易。密钥永不落盘。
### 🔬 深度研究员与实干家
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index c70e437a1f..151fd7edc8 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -272,7 +272,6 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an
| 6.3.2 | Wait for a sub-agent result | RU | `src/openhuman/agent/orchestration/running_subagents.rs`, `src/openhuman/agent/orchestration/tools/wait_subagent.rs` | ✅ | `wait_subagent` blocks on the completion `watch` with a timeout; prunes terminal entries, leaves entries intact on timeout. |
| 6.3.3 | Steer lands in child history | RU | `src/openhuman/agent/harness/subagent_runner/ops_tests.rs::run_queue_steer_lands_in_subagent_history` | ✅ | End-to-end: a queued steer is drained by the child `run_turn_engine` and appears as a `[User steering message]` user turn in the provider request. |
| 6.3.9 | Vision sub-agent reads attached images | RU | `src/openhuman/agent/registry/agents/loader.rs::vision_agent_loads_on_vision_hint`, `src/openhuman/inference/provider/factory_tests.rs::vision_tier_is_vision_capable`, `src/openhuman/agent/harness/engine/core.rs::gate_tests`, `src/openhuman/agent/multimodal_tests.rs::extract_image_placeholders_pulls_att_tokens_in_order` | ✅ | Orchestrator (non-vision `chat-v1`) keeps the image as a placeholder, delegates to `vision_agent` on the `vision-v1` tier, which rehydrates the on-disk attachment and reads it. Engine gate prefers per-tier `current_model_vision`; turn placeholders forwarded into the sub-agent prompt. |
-| 6.3.10 | Auto-accept contact requests from linked agents | RU | `src/openhuman/agent/orchestration/pairing.rs::{auto_accept_gate_accepts_linked_but_leaves_others_pending,auto_accept_gate_unifies_base58_and_base64_of_same_key,auto_accept_gate_accepts_nothing_with_empty_linked_set,auto_accept_fails_closed_on_unreadable_pairing_store,incoming_pending_requesters_filters_and_resolves_requester}` | ✅ | On an inbound tiny.place `contact_request`, OpenHuman auto-accepts iff the requester is in `linked_agent_ids()` (its own paired agents) and otherwise leaves it pending for the human — the e2e gate that stops the relay dropping a linked agent's `session_info` intro. Fail-closed: a pairing-store read error yields an empty linked set → nothing auto-accepted. base58/base64 encodings of the same key unify via the shared DM-ingest matcher. |
| 6.3.11 | Async-by-default archetype delegation (durable ref) | RU | `src/openhuman/agent/orchestration/tools/tools_e2e_tests.rs::archetype_delegation_defaults_to_async_with_durable_session_e2e`, `src/openhuman/agent/orchestration/tools/archetype_delegation.rs::parameters_schema_advertises_async_default_blocking_opt_in` | ✅ | `delegate_*` / `build_workflow` with a parent turn + chat thread return `[async_subagent_ref]` (task_id + subagent_session_id) immediately, persist a durable reusable session, and queue the result for background delivery as a new turn; `blocking: true` opts back into inline dispatch, and no-thread contexts fall back automatically. |
| 6.3.12 | Cross-turn sub-agent roster (durable store merge) | RU | `src/openhuman/agent/orchestration/running_subagents.rs::snapshot_and_block_scope_to_parent_and_reflect_live_status` | ✅ | `[active_subagents]` merges the in-memory registry with the per-workspace `subagent_sessions` store, so a cold-booted parent still sees earlier workers (id, status, task title) and resumes instead of re-delegating; Closed sessions excluded, other parents' sessions never leak. |
@@ -501,7 +500,6 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an
| ID | Feature | Layer | Test path(s) | Status | Notes |
| ------ | --------------------------------------------------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| 11.3.1 | Hosted-only orchestration (client = trigger + effects + render) | RI+VU | `tests/orchestration_hosted_client.rs`, `app/src/components/intelligence/TinyPlaceOrchestrationTab.test.tsx`, `app/src/components/orchestration/__tests__/AgentChatPanel.test.tsx` | ✅ | Local wake-graph brain retired (frontend_agent/graph/master_agent/reasoning_agent deleted). Client forwards events to the hosted brain (`POST /orchestration/v1/events`), uploads world-diffs, syncs hosted sessions/messages/steering into the render cache, and executes `send_dm`/`evict` socket effects; cloud-unreachable banner on outage. |
| 11.3.2 | Direct paid Medulla orchestration with local OpenHuman tools | RU | `src/openhuman/hosted/orchestration/medulla.rs`, `src/openhuman/hosted/orchestration/schemas.rs` | ✅ | `openhuman.orchestration_run` checks the active paid plan, starts a hosted Medulla cycle, executes requested contact/session/send tools locally, and continues pending/tool-use events to a final result. Mocked HTTP tests cover direct and tool-loop success plus plan, pending, backend-error, unknown-tool, and tool-failure paths. |
| 11.3.3 | Local medulla-serve supervision (`medulla_local` RPC, Flavor A draft) | RU+RI | `src/openhuman/medulla_local/server_tests.rs`, `tests/medulla_local_e2e.rs` | ✅ | Behind the default-ON `medulla-local` feature. Unit tests drive the supervisor's handshake seam against a mock connector: restart-and-retry fires only on mid-request transport death of an idempotent op (exactly one respawn); the non-idempotent `instruct` is never replayed — a transport break surfaces the typed `MaybeApplied` error with no duplicate submission; an overall per-request deadline (`subconscious.medulla_local.request_deadline_secs`, default 300s) bounds a request even while the child keeps streaming frames or while a serve→host port callback (`inference.invoke`/`tools.invoke`) hangs on a stalled provider/tool — tripping as the typed transport error (`MaybeApplied` for `instruct`, restart-and-retry-once for `status`); a retry that also breaks mid-request resets the replacement connection, so the next request re-establishes cleanly instead of reusing a poisoned transport; child liveness is probed before the cached connection is trusted, so a child that dies between requests reports `running=false` and is respawned on the next request instead of misreporting `MaybeApplied`; `ok=false` serve rejections fail fast with the typed `RequestError` without killing the child; and the global cache is keyed on an order-canonical config fingerprint (map-field insertion order cannot invalidate it, a changed config rebuilds and bypasses the start-failure backoff). The transport is unix-only; non-unix targets compile a stub whose entry points report a typed unsupported-platform error (self-tested on those targets). The RI suite boots the real JSON-RPC router and asserts `medulla_local.status` returns a well-formed idle snapshot (running=false, actionable message) and `instruct` fails cleanly when no serve entry is configured — hermetic, no Node child or network. |
diff --git a/docs/library-minimal-recipe.md b/docs/library-minimal-recipe.md
index 6dada72a52..1740e532f0 100644
--- a/docs/library-minimal-recipe.md
+++ b/docs/library-minimal-recipe.md
@@ -133,9 +133,7 @@ build-fact error:
RPC, absent from `/schema`); `audio_generate_podcast` tools absent; `openhuman
voice` returns "voice disabled".
- **web3:** wallet / web3 / x402 controllers unregistered; swap/bridge/dapp agent
- tools absent; the x402 402-retry path returns unpaid; tinyplace on-chain
- payments degrade to graceful "wallet disabled" errors (tinyplace comms +
- ed25519 signing are unaffected).
+ tools absent; the x402 402-retry path returns unpaid.
- **media:** `media_generate_*` agent tools absent.
- **meet:** meet controllers unregistered; live Meet bot / STT-LLM-TTS loop absent.
- **mcp:** `mcp_server` / `mcp_registry` (`mcp_clients` namespace) / `mcp_audit`
diff --git a/docs/scoping/master-chat.md b/docs/scoping/master-chat.md
deleted file mode 100644
index 69bbaa39f6..0000000000
--- a/docs/scoping/master-chat.md
+++ /dev/null
@@ -1,400 +0,0 @@
-# Master Chat — scoping (read-only investigation)
-
-**Feature target.** A human asks the OpenHuman agent a question in a "Master chat".
-OpenHuman either (a) answers from its own persisted session history with other agents,
-or (b) asks an external agent on the human's behalf by DMing it under a session id
-(new or existing), with the external reply threading back into the Master-chat answer.
-
-**Grounding.** All `EXISTS` refs are against `upstream/main` (`git show upstream/main:<path>`,
-fetched at investigation time — `upstream/main` @ `f49249360`). In-flight work accounted
-for: **PR #4582 is already MERGED into main** (shared per-pair `session_key`, plus the
-warn-only seq guard); **issue #4583 is OPEN** (robust monotonic ingest cursor — *not* yet
-implemented, only the interim warn shipped); **plugin PR tiny.place#227** (one shared
-session id per thread, reused on reply) is the peer-side counterpart the merged core code
-already assumes.
-
-> Terminology caution: in the code today, **"master" (`ChatKind::Master`)** is the window
-> that aggregates *plain (non-envelope) DMs* from peers, and `orchestration_send_master_message`
-> is the human→front-end **steering** send. The task's "Master chat" (human asks OpenHuman,
-> OpenHuman answers *back to the human*) is a **superset** that is only partially realized by
-> this window — see the gap analysis.
-
----
-
-## WHAT EXISTS TODAY
-
-Domain root: `src/openhuman/hosted/orchestration/` (declared in `mod.rs:16-34`; enabled behind
-`config.orchestration.enabled`, schema `src/openhuman/config/schema/orchestration.rs:39`).
-Startup wiring: `src/core/jsonrpc.rs:2294-2300` (ingest subscriber, wake subscriber, drain
-supervisor).
-
-### 1. Master vs Session windows model
-
-- **`ChatKind`** — `Master | Subconscious | Session` (`types.rs:113-155`, `as_str`/`from_str`
- with Master as the safe default at `:150`).
-- **`SessionEnvelopeV1`** — hand-rolled mirror of the tiny.place harness envelope
- (`types.rs:79-96`); `is_valid_v1` requires `envelope_version == "tinyplace.harness.session.v1"`
- and a non-empty `harness_session_id` (`types.rs:99-104`); `parse` returns `None` for any
- non-envelope body so it routes to Master (`types.rs:108-112`).
-- **`session_key()`** (`types.rs:123-135`) — **PR #4582, on main**: returns
- `scope.wrapper_session_id` (the shared per-pair conversation id both peers stamp on every
- message for a thread), falling back to `harness_session_id` only for a legacy envelope.
- This is the sole inbound routing key.
-- **`SessionEnvelopeV1::outgoing()`** (`types.rs:139-162`) — builds a v1 envelope with both
- `wrapper_session_id` and `harness_session_id` set to the same `session_id`, `role="owner"`,
- so a compliant peer threads its reply under the same id.
-- **`classify_message`** (`ingest.rs:44-90`) — pure classifier: a parseable envelope →
- `ChatKind::Session` keyed by `session_key()` (`ingest.rs:47-75`, seq = `env.message.line`,
- source = `harness.provider`, label from folder scope, workspace from cwd); anything else →
- `ChatKind::Master`, `session_id="master"`, `role="user"`, `seq=0` (`ingest.rs:76-88`).
-- **Persisted rows** — `OrchestrationSession` (`types.rs` `sessionId/agentId/source/label/
- workspace/lastSeq/...`) and `OrchestrationMessage` (`id/agentId/sessionId/chatKind/role/
- body/timestamp/seq`); `body` is decrypted plaintext ⇒ workspace-internal only.
-
-### 2. Ingest → persist → wake pipeline
-
-- **Bus subscribers** (`bus.rs`): `OrchestrationIngestSubscriber` (domain `tinyplace`,
- `bus.rs:60-92`) feeds `ingest_stream_message`; `OrchestrationWakeSubscriber` (domain `agent`,
- `bus.rs:112-133`) fans each persisted `OrchestrationSessionMessage` to the renderer socket
- **and** calls `ops::schedule_wake` — for **all** kinds except subconscious.
-- **`ingest_one`** (`ingest.rs:171-247`):
- 1. **linked-sender gate** — only DMs from paired (linked) agents are decrypted; unpaired
- senders are skipped *without* decrypt/ack so they stay in the Messaging UI mailbox
- (`ingest.rs:187-198`).
- 2. **dedupe-before-decrypt** by relay `msg_id`, protecting the non-idempotent Signal ratchet;
- a duplicate re-acks but never re-decrypts (`ingest.rs:200-217`).
- 3. decrypt-once → `classify_message` → `persist_message` (`ingest.rs:219-224`).
- 4. on a new row: `acknowledge_message` + `publish_global(OrchestrationSessionMessage{...})`
- (`ingest.rs:226-242`).
-- **`persist_message`** (`ingest.rs:92-149`): upserts the session row and inserts the message
- idempotently. Contains the **#4583 interim guard** — if `chat_kind == Session` and the inbound
- `seq <= existing last_seq`, it logs a `warn` (`ingest.rs:107-127`) but still persists
- (proved by test `persist_still_stores_a_lower_seq_in_the_same_wrapper_session`).
-- **Delivery is poll-only**: `drain_mailbox_once` (`ingest.rs:264-310`) lists `/messages` every
- 15 s via `start_message_drain_supervisor` (`ops.rs:129-145`) — relay DMs never hit the
- `/inbox/stream` WS, so the poller is the real inbound path.
-- **`schedule_wake`** (`ops.rs:83-118`): per-session debounce via a generation counter
- (`ops.rs:58-78`); subconscious kind returns early (`ops.rs:96-98`); the last trigger within
- `debounce_ms` wins → `invoke_orchestration_graph`.
-- **Per-session idempotence cursor** (`ops.rs:51-54`, `192-211`): `has_new_work` compares
- `latest_seq` against `kv["cursor:{agent}:{session}"]`; `advance_cursor` moves it **only after
- a completed, DM-sent cycle** (`ops.rs:518-522`). Store: `session_last_seq` (`store.rs:219`),
- `upsert_session` clamps `last_seq = MAX(old,new)` (`store.rs:169`), `ingest_cursor_lag`
- (`store.rs:385`). **There is no monotonic `next_session_seq` on main** (confirmed absent) —
- cursor and lag both key on `env.message.line`, which is the #4583 defect.
-
-### 3. Wake graph nodes (what runs the LLM)
-
-- **Graph shape** (`graph/mod.rs:1-30`, wired in `graph/build.rs:328-345`):
- `normalize → frontend → execute → compress → world_diff → frontend → send_dm →
- context_guard → done`. One `OrchestrationState` (`graph/state.rs:49-95`) is threaded and
- SQLite-checkpointed per super-step under thread `orchestration:<session_id>`
- (`build.rs:351-383`).
-- **Injected `OrchestrationRuntime` seam** (`build.rs:44-61`) — every LLM/effect op is behind
- this trait; production impl `ProductionRuntime` in `ops.rs:550-817`.
-- **`frontend` (router)** (`build.rs:149-211`): two-pass Quick-LLM. Pass 1 → `frontend_instruct`
- (`ops.rs:595-604`) → macro-instructions → `execute`. Pass 2 (once `agent_reply` present) →
- `frontend_compile` (`ops.rs:606-617`) → `channel_response` → `send_dm`. `max_supersteps`
- backstop guarantees termination (`build.rs:166-181`). Agent package: `frontend_agent/`
- (`prompt.md`, `agent.toml` tier `chat`, tools `defer_to_orchestrator` + `reply_to_channel`
- from `tools.rs`).
-- **`execute` (reasoning core)** (`build.rs:217-231` / `ops.rs:619-640`): runs `reasoning_agent`
- with the current steering directive scoped in (`reasoning_agent/steering.rs`, `ops.rs:626-633`);
- produces `reply` + a `trace`. Package `reasoning_agent/agent.toml`: tier `reasoning`,
- subagents `researcher/code_executor/tools_agent`, tools **`spawn_async_subagent, wait,
- tinyplace_whoami, tinyplace_status, tinyplace_feed, current_time, resolve_time`** — i.e. only
- tiny.place **read** tools; **no DM-send tool, no session-mint tool.**
-- **`compress`** (`ops.rs:642-707`): 20:1 summary of the trace → `compressed_history` row
- (`store.rs:474`).
-- **`world_diff`** (`ops.rs:709-736`): append-only per-`(agent,session)` mutation timeline
- (`store.rs:515` `append_world_diff`, monotonic `seq`).
-- **`context_guard`/`evict`** (`ops.rs:738-802`): utilization estimate; over threshold, evicts
- the oldest compressed summaries into memory-RAG under `path_scope = orchestration/<session>`
- (`ops.rs:764-784`).
-- **`send_dm`** (`build.rs:273-294` / `ops.rs:804-816`): sends `channel_response` back to
- **`state.counterpart_agent_id`** (the session's peer). `dm_sent` latch prevents double-send.
-
-### 4. The SEND path (OpenHuman → peer under a sessionId)
-
-Two send surfaces exist, both routing through `tinyplace::handle_tinyplace_signal_send_message`:
-
-- **Graph reply** — `ProductionRuntime::send_dm` (`ops.rs:804-816`) → `session_send_plaintext`
- (`ops.rs:822-835`): for a real session id it wraps the body in `SessionEnvelopeV1::outgoing`
- (so the peer threads its reply under the *same* id); `"master"`/`"subconscious"` stay plain.
- **This is a reply only — it always targets the current session's `counterpart_agent_id`;
- it cannot initiate a new outbound thread to a different agent or mint a new session id.**
-- **Human steering send** — `orchestration_send_master_message` (`schemas.rs:108-118`, handler
- `:437-539`): body + optional `recipient` + optional `sessionId`. Recipient resolution
- (`schemas.rs:457-472`): explicit wins; else the session's contact (`store::session_agent_id`,
- `store.rs:368`); else the latest master peer (`store::latest_master_peer`, `store.rs:356`).
- With `sessionId` it wraps a v1 envelope (`session_envelope_plaintext`, `schemas.rs:425-435`)
- and mirrors into that session window; without it, plain into `"master"`. It then
- `notify_orchestration_message` (`schemas.rs:535`) — which, via the wake subscriber, **wakes
- the local graph** on that window.
-- **Session mint** — `orchestration_sessions_create` (`schemas.rs:82-91`, handler `:347-380`)
- mints a fresh `uuid` session id for a contact, `source="user_created"`. **Renderer-driven
- only** — no agent-side or graph-side caller.
-
-### 5. Session persistence + read surface + frontend
-
-- **Store reads**: `list_sessions` (`store.rs:254`), `list_messages_by_session`
- (`store.rs:279`, session-key aggregated, paged by `before`), `list_recent_messages`
- (`store.rs:441`, chronological window used by the graph), `unread_count`/`mark_chat_read`
- (`store.rs:329`/`339`).
-- **RPC surface** (`schemas.rs:23-71`): `orchestration_sessions_list`, `_sessions_create`,
- `_messages_list`, `_send_master_message`, `_mark_read`, `_status`, `_self_identity`,
- `_relay_info` — internal registry (renderer-only, never advertised to agents).
-- **Frontend Master-chat surface**:
- - Client `app/src/lib/orchestration/orchestrationClient.ts:166-200` (`sessionsList`,
- `messagesList`, `sendMasterMessage`, `sessionsCreate`, `markRead`, `status`, ...).
- - Hook `app/src/lib/orchestration/useOrchestrationChats.ts` — `sendMessage` (`:260-303`):
- a **session** chat sends `{ body, recipient, sessionId }`; **master/subconscious** send
- `{ body }` (steering to the latest master peer). Optimistic append + reconcile via
- `loadMessages`/`loadSessions`.
- - UI: `app/src/components/intelligence/TinyPlaceOrchestrationTab.tsx` + `TinyPlaceRoster`,
- `InstanceCard`, `InstanceStatusDot`, `HarnessGlyph`, `SelfIdentityCard`, `RelayBadge`
- (roster of instance-shaped sessions; recent commits 0500aa9fb / 05a3c97b9).
-
-### 6. Is cross-agent Session-window history fed to the LLM today?
-
-**No.** The graph seeds from **one** window only: `seed_state` (`ops.rs:150-166`) calls
-`list_recent_messages(agent_id, session_id, message_window)` and `OrchestrationState::seed`
-(`state.rs:97-134`) folds just those messages + the single `counterpart_agent_id`. The
-reasoning core's only cross-session recall is indirect (memory-RAG over evicted compressed
-summaries at `orchestration/<session>`, and the `tinyplace_feed`/`_status` read tools). There
-is **no** node or tool that loads/validates the OpenHuman↔agentX **session transcript(s)** as
-explicit context for answering a question, and none that spans *multiple* sessions/peers.
-
----
-
-## WHAT'S NEEDED (gap analysis)
-
-Target flow: **human asks in Master chat → orchestration LOADS the relevant OpenHuman↔agent
-session history (validate persistence) → runs the LLM over that history + the question → if an
-external agent is needed, SEND a DM under a session id (reuse the per-pair id if a thread
-exists, else mint) → the external reply threads back (shared-session-id model) → update the
-Master-chat answer.**
-
-Wired-vs-missing summary of the 5 sub-flows. **The `State at scoping` column is the
-pre-PR baseline** (kept as historical context); the `Landed` column is what this PR
-delivers.
-
-| # | Sub-flow | State at scoping (pre-PR) | Landed in this PR |
-|---|----------|---------------------------|-------------------|
-| 1 | human→OpenHuman question intake + routing into the graph | **Partial** — `send_master_message` + master wake exist, but they reply *outbound to a peer*, not *back to the human*. No "answer the asker" surface. | ✅ W2 local-ask path + human-facing `master_agent`; answers land back in the Master window. |
-| 2 | graph loads + validates cross-agent session history as context | **Missing** — single-window seed only. | ✅ `orchestration_list_sessions` / `orchestration_read_session` browse tools. |
-| 3 | decision + tool for OpenHuman to ask an external agent | **Missing** — reasoning core has no send/ask tool. | ✅ `orchestration_send_to_agent` (linked-peers-only guardrail). |
-| 4 | choose new-vs-existing session id for the outbound ask | **Missing** — `sessions_create` mints; no reuse-lookup; no agent caller. | ✅ reuse `latest_session_for_agent`, else mint fresh. |
-| 5 | thread external reply back into the Master-chat answer | **Missing** — reply wakes the *sub-session* graph and replies to the peer; never correlated back to the originating Master question. | ✅ W7 correlation (process-global beacon) → reply surfaced as OpenHuman's own message. |
-
-Session-persistence-validity concerns to carry through: **dedupe** (already solid —
-`message_exists` before decrypt, `INSERT OR IGNORE`); **ordering/#4583** (cursor keyed on
-`env.message.line` can silently drop the 2nd+ inbound message on a shared `wrapper_session_id`
-— **blocks reliable reply-threading**, must be fixed before sub-flow 5 is trustworthy);
-**stale/dead session ids** (no liveness/expiry on session rows); **shared-id reuse rules**
-(#227/#4582 give inbound threading; outbound *initiation* id-choice is unspecified).
-
-### Status update — PR #4599 (OPEN, `Closes #4583`, follow-up to #4582)
-
-#4599 lands the **reliable reactive reply loop** (`ingest.rs`/`ops.rs`/`store.rs`/`tools.rs`
-only). It closes the P0 foundation and adds plumbing the answer path reuses — but delivers
-**none** of the target-flow gaps (it makes *peer→OpenHuman→peer* replies reliable, not
-*human→OpenHuman→(history|external agent)→human*):
-
-- **W1 → DONE**: `store::next_session_seq` = `MAX(seq)+1` per `(agent,session)`, stamped in
- `persist_message` on both `last_seq` and message `seq` (replaces the warn guard); also fixes
- the `cycle_id` collision.
-- **Reply-content fix → DONE (new prerequisite for a *correct* answer)**:
- `tools::with_decision_capture` task-local captures the `reply_to_channel` /
- `defer_to_orchestrator` payload; `frontend_instruct`/`frontend_compile` prefer it over
- `run_single`'s trailing narration.
-- **Answer-display plumbing → DONE (reused by W7/W10)**:
- `ProductionRuntime::persist_outgoing_reply` writes the reply `role=owner` (monotonic seq) +
- `notify_orchestration_message` → the reply now renders in `orchestration_messages_list` / the
- chat window.
-- **Wake resilience → DONE**: `schedule_wake` retries with 5s/15s/45s backoff,
- checkpoint-resumed, bails if superseded.
-
-Three follow-ups #4599 explicitly defers (its "Related") are folded in below as **F1/F2/F3**.
-
-### Design pivot — agentic tools, not static seed (branch `feat/master-chat-orchestration-tools`)
-
-Per the owner: the master orchestration layer should have **tools** to (1) browse its
-OpenHuman↔agent session chats and (2) send messages on OpenHuman's behalf — rather than the
-graph pre-loading history into the prompt. This **replaces W3/W4** ("seed history into state")
-with on-demand read tools the reasoning core calls, and reframes W5 as the send tool.
-
-**Shipped in this branch (read slice):**
-
-- ✅ `orchestration_list_sessions` + `orchestration_read_session` read tools
- (`orchestration/tools.rs`), registered in `tools/ops.rs`, added to the `reasoning_agent`
- allowlist + prompt nudge. Read-only, concurrency-safe, workspace-internal store access via
- `store::{list_sessions,count_messages,list_recent_messages,list_messages_by_session}`.
- Delivers target half (a): answer from own history.
-
-**Shipped in this branch (send slice — W5 + W6):**
-
-- ✅ `orchestration_send_to_agent` (`orchestration/tools.rs`) — DM a peer on OpenHuman's
- behalf. **Guardrail: linked-peers-only** (`pairing::linked_agent_ids` OR an existing session
- with the peer) — refuses cold-DMs from the un-gated background origin. **Session id:
- reuse-or-mint per peer** via new `store::latest_session_for_agent` (reuse the peer's newest
- thread's shared `wrapper_session_id` so the reply threads back; else mint a uuid). Sends a v1
- envelope via `handle_tinyplace_signal_send_message`, records the outbound `role=owner`
- message + `notify_orchestration_message` (mirrors #4599's `persist_outgoing_reply`).
- `PermissionLevel::Write`. Added to the `reasoning_agent` allowlist + prompt.
-- Verified: `cargo test openhuman::orchestration` → 64/64 (6 new); loader 85/85; lib clean.
-
-**Shipped in this branch (reply-threading — W7, core-only):**
-
-- ✅ One-shot outbound-ask correlation. For a local-master turn the `execute` node opens a
- **process-global origin beacon** (`tools::begin_master_origin`/`end_master_origin`) around the
- agent turn; `orchestration_send_to_agent` reads it and records
- `store::set_pending_ask((peer_agent, ask_session) → origin)`. A process-global is used instead of
- a task-local because the harness dispatches tool calls past an internal `tokio::spawn`, and
- task-locals do **not** cross a spawn — the earlier `with_origin_session` task-local silently never
- reached the tool, so the correlation never armed. The key is scoped by `(peer_agent, session)` so
- a legacy shared `wrapper_session_id` across peers can't misroute a reply. When the peer's reply
- lands, `invoke_with_runtime` correlates it and **finishes the cycle without running the reply
- graph** — no ping-pong. One-shot: the pending marker is consumed **only after the reply is durably
- surfaced** (`store::{pending_ask_origin,clear_pending_ask}`), so a transient store failure retries
- on the next drain instead of dropping the answer.
-- ✅ Reply surfaced as **OpenHuman's own message**, not the peer's raw words. For a master-initiated
- ask the reply is run through the **tool-free `master_reporter`** (`report_peer_reply_to_master`) —
- the peer text is untrusted, so the reporter carries no tiny.place tools/sub-agents (no
- prompt-injection surface) and emits an `assistant` message in the Master window. Peer/A2A origins
- keep the deterministic raw `thread_reply_to_origin`.
-- ✅ Fire-and-forget: `orchestration_send_to_agent` returns an immediate ack and the `master_agent`
- prompt forbids polling/`read_session` for the reply, so W7 is the sole async reporter (no
- duplicate surfacing).
-- Verified: `cargo test openhuman::orchestration` green (incl. `outbound_ask_reply_threads_to_
- origin_and_skips_the_reply_graph`, `pending_ask_correlation_is_one_shot`,
- `master_origin_beacon_sets_and_clears`); full loop proven live on staging.
-- **Limitation (needs F3):** correlation is a pragmatic 1:1 request/response — it assumes the
- *next* inbound message on the ask session is the answer. Many-in-flight / interleaved replies
- need an explicit envelope `inReplyTo`/`fromSession` (F3, cross-repo). The process-global beacon is
- safe because local-master wakes are serialized; a concurrent A2A send during a master turn is the
- one documented edge (single-user desktop, non-fatal). Peer-session (A2A) W7 still rides the
- best-effort task-local.
-
-**Still to do here:** RPC/UI surface for the human-facing master ask/answer (W8–W12) and
-perf/robustness **F1/F2**; robust correlation **F3** (cross-repo).
-
-### Prioritized work-item CHECKLIST (ordered Rust core → JSON-RPC → UI → tests) — remaining after #4599
-
-**P0 — foundation / correctness**
-
-- [x] **W1 — Fix the #4583 wake-cursor/seq decoupling. — DONE in #4599** (`store::next_session_seq`
- stamped in `persist_message`). Note: #4599 keys `last_seq`/message `seq` on the ordinal;
- `has_new_work`/`advance_cursor`/`ingest_cursor_lag` already ride `last_seq`, so they inherit
- the fix. No remaining work.
-
-- [ ] **W2 — Master-chat "ask" intake distinct from steering.** Introduce a question record
- (role `owner`, a `pending`/answered marker) and route it into the graph as *the question to
- answer for the human*, separate from `send_master_message`'s outbound peer-steering.
- *Where:* `orchestration/{types.rs,store.rs,ops.rs,schemas.rs}` (+ maybe a `master` chat mode).
- *Size:* **M.** *Deps:* W1.
-
-**P1 — the answer path**
-
-- [ ] **W3 — Cross-agent session-history loader + validity check.** A store read that gathers
- the relevant OpenHuman↔agent transcript(s) (by peer and/or across peers), validates ordering
- (monotonic seq from W1), drops dead/stale sessions, and returns a bounded, LLM-ready context.
- *Where:* `orchestration/store.rs` (new `load_history_for_question`) + `ops.rs::seed_state`
- (extend state with a `history_context`). *Size:* **M/L.** *Deps:* #4599 (monotonic seq).
-
-- [ ] **W4 — Feed the history into the reasoning/front-end prompt.** Extend `OrchestrationState`
- (`graph/state.rs`) with the loaded history and render it in `frontend_instruct` / `execute`
- prompts (`ops.rs:595-640`). *Where:* `orchestration/graph/state.rs`, `ops.rs`. *Size:* **S/M.**
- *Deps:* W3.
-
-- [ ] **W5 — "Ask an external agent" decision + tool.** A new domain tool (e.g.
- `ask_external_agent { recipient, question, sessionId? }`) that the reasoning core can call;
- it performs the outbound session-scoped send. Add to `reasoning_agent/agent.toml` allowlist
- and gate it (approval/linked-only). *Where:* `orchestration/tools.rs` (+ re-export in
- `tools/mod.rs`), `reasoning_agent/agent.toml`, reuse `session_send_plaintext`/
- `handle_tinyplace_signal_send_message`. *Size:* **M.** *Deps:* W2.
-
-- [ ] **W6 — New-vs-existing session-id chooser for the outbound ask.** Resolve "do I already
- have a live thread with peer X?" → reuse that `wrapper_session_id`; else mint (uuid, per
- `sessions_create`) and record the `(peer → session_id)` mapping. Encode the #227/#4582 reuse
- rule (one shared id per thread; both peers reuse on reply). *Where:* `orchestration/store.rs`
- (a `find_or_create_session_for_peer`), consumed by W5. *Size:* **M.** *Deps:* W5.
-
-- [ ] **W7 — Thread the external reply back into the Master-chat answer.** Correlate the
- inbound session reply (arriving under the shared id, `ChatKind::Session`, waking that
- sub-session's graph) back to the originating Master question, and update/emit the Master-chat
- answer instead of (or in addition to) replying to the peer. Needs a pending-ask ↔ session-id
- correlation table and a resume/notify into the master window. Reuse #4599's
- `persist_outgoing_reply`/`notify_orchestration_message` for surfacing the answer; the
- correlation primitive is **F3** (envelope `inReplyTo`/`fromSession`). *Where:*
- `orchestration/store.rs` (correlation kv/table), `ops.rs` (wake handling for a correlated
- session), `bus.rs`. *Size:* **L.** *Deps:* W2, W5, W6, **F3**. *Risk:* highest — cross-graph
- correlation + the reactive `send_dm`-always-to-counterpart assumption in `build.rs:273-294`
- must be relaxed.
-
-**P2 — JSON-RPC surface**
-
-- [ ] **W8 — RPC for master-chat ask + answer polling.** e.g. `orchestration_ask_master`
- (submit question) and answer surfacing via existing `messages_list`/socket, plus a pending
- status. *Where:* `orchestration/schemas.rs` (new schema + handler; register in
- `all_*controllers`). *Size:* **M.** *Deps:* W2, W7.
-
-- [ ] **W9 — Extend `orchestration_status`/session DTOs** with pending-ask + external-ask
- in-flight signals for the UI. *Where:* `schemas.rs`. *Size:* **S.** *Deps:* W8.
-
-**P3 — UI**
-
-- [ ] **W10 — Master-chat ask/answer UX.** Client method + hook wiring so a master question
- shows "OpenHuman is asking @peer…" and the threaded answer updates in place. *Where:*
- `app/src/lib/orchestration/orchestrationClient.ts`, `useOrchestrationChats.ts`,
- `TinyPlaceOrchestrationTab.tsx`. *Size:* **M.** *Deps:* W8. *Note:* i18n keys in `en.ts` +
- all locales; no dynamic imports.
-
-**P4 — tests (each item lands with its own unit tests; these are the cross-cutting suites)**
-
-- [ ] **W11 — Rust: threading correctness.** (a,b) seq/cursor line-0 + reuse cases are already
- covered by #4599 (`persist_stamps_monotonic_ingest_seq_so_line_zero_dms_still_wake`) — only
- (c) remains: outbound ask reuses an existing per-pair id and the reply correlates back to the
- originating master question. *Where:* `orchestration/{ops.rs,store.rs}` inline tests +
- `tests/json_rpc_e2e.rs`. *Size:* **M.** *Deps:* W6, W7.
-- [ ] **W12 — JSON-RPC E2E + Vitest** for ask→answer round-trip (mock peer reply). *Where:*
- `scripts/test-rust-with-mock.sh`, `app/src/**/*.test.tsx`. *Size:* **M.** *Deps:* W8, W10.
-
-**F — deferred by #4599 (fold into the target work)**
-
-- [ ] **F1 — `send_dm` before `compress`/`world_diff`** to cut ~20s time-to-reply (reorder the
- graph edges so the outbound reply dispatches before the post-processing tail). *Where:*
- `orchestration/graph/build.rs` (edge wiring). *Size:* **S.** *Deps:* none. *Note:* perf, not
- blocking, but improves the human-facing answer latency the target cares about.
-- [ ] **F2 — Scope the checkpoint thread id to `(agent, session)`.** Today it is
- `orchestration:<session_id>` (`build.rs:358`), so two peers sharing a session id can collide
- on checkpoints. *Where:* `orchestration/graph/build.rs::run_orchestration_graph`. *Size:* **S.**
- *Deps:* none. *Correctness* — do alongside W6/W7 (which multiply active sessions per id).
-- [ ] **F3 — `SessionEnvelopeV1` `inReplyTo` / `fromSession` correlation.** The primitive W7
- needs to tie an inbound reply to the exact outbound ask (vs. inferring from session id alone),
- and to drive a `send_and_wait`-style block. *Where:* `orchestration/types.rs`
- (`SessionEnvelopeV1`), plus **tiny.place SDK / plugin #227 peer coordination**. *Size:* **M**
- (core) **+ external.** *Deps:* peer/SDK support. *Risk:* cross-repo — the blocking dependency
- for a clean W7.
-
----
-
-## Open questions / risks
-
-1. **Semantic overload of "master".** The window is currently peer-plain-DM aggregation +
- human steering; the target needs a human-question/answer channel. Decide whether to reuse
- `ChatKind::Master` or add a mode — affects W2/W7 and the wake router's terminate predicate.
-2. **`send_dm` is unconditional-to-counterpart** (`build.rs:273-294`). Sub-flow 5 requires the
- graph to sometimes answer the human instead of/along with the peer — a structural change to
- the terminal node, not just a new tool.
-3. **#4583 silent-drop — RESOLVED by #4599** (`next_session_seq` monotonic ordinal). Build
- reply-threading on `last_seq`/message `seq`, not the wire `line`.
-4. **Outbound id-choice reuse rule is peer-side (#227) only in code.** The core has no
- "find existing thread with peer X" lookup; W6 must define freshness/liveness (ties to the
- stale-session-id concern — session rows have no expiry today).
-5. **`env.message.line` is now ignored for ordering** (#4599). Its value no longer matters to
- the wake cursor; correlation (W7) must ride the store seq / an explicit `inReplyTo` (F3),
- not `line`.
-6. **Approval/security:** an agent-initiated outbound DM (W5) is a new external-effect tool;
- must respect the linked-agent gate (`ingest.rs:187-198`) and the approval gate — scope its
- `CommandClass`/tier deliberately.
diff --git a/e2e/tinyplace-messaging/README.md b/e2e/tinyplace-messaging/README.md
deleted file mode 100644
index d9d169abc5..0000000000
--- a/e2e/tinyplace-messaging/README.md
+++ /dev/null
@@ -1,96 +0,0 @@
-# openhuman ↔ tiny.place messaging e2e
-
-End-to-end coverage for the tiny.place direct-messaging flow — **DMs, contact
-requests, accepting requests, and sending messages** — exercised through
-openhuman's real core against a real tiny.place backend. Two layers:
-
-| Layer | File | What it drives |
-| ----- | ---- | -------------- |
-| **Core** | [`messaging.e2e.mjs`](messaging.e2e.mjs) | Two real `openhuman-core` processes talking to each other over the `openhuman.tinyplace_*` JSON-RPC surface (the exact API the desktop UI calls via `core_rpc_relay`). |
-| **UI** | [`../../app/test/playwright/specs/tinyplace-messaging.spec.ts`](../../app/test/playwright/specs/tinyplace-messaging.spec.ts) | The web build of the app (Messaging screen) driving the same flow through the browser, with a second core as the peer. |
-
-Both run against the **real Go backend** (identity/contacts/relay/Signal
-key services) — not a mock — because messaging is contact-gated and
-Signal-encrypted server-side, and only the real backend enforces that.
-
-## What the core suite proves
-
-Each `openhuman-core` derives its tiny.place identity (a base58 Solana
-`cryptoId`) from its wallet mnemonic, so two cores with two fresh mnemonics are
-two distinct agents. The suite walks the full lifecycle:
-
-1. **Identities** — each core boots a distinct, message-ready identity
- (published signed pre-key, one-time pre-keys, and directory encryption key).
-2. **Contact gate** — a DM between non-contacts is refused (`not_a_contact`).
-3. **Send request** — Alice sends a contact request; Bob sees it `pending`.
-4. **Accept request** — Bob accepts; both sides see a mutual `accepted` contact.
-5. **Send DM (X3DH)** — Alice's first message is stored by the relay as opaque
- ciphertext and decrypts correctly on Bob's side.
-6. **Reply (Double Ratchet)** — Bob's reply decrypts on Alice's side.
-7. **In-session DM** — a follow-up message still decrypts.
-
-## Run it
-
-```bash
-# Core layer (two openhuman-core processes over JSON-RPC). Brings up an isolated
-# backend (mongo+redis+backend, static payment verifier) if one isn't already
-# reachable, builds the core if needed, then runs the node:test suite.
-./run.sh
-
-# UI layer (Playwright against the web build). Same backend handling; boots the
-# app's core + web host and a peer core, then drives the Messaging screen.
-./run-ui.sh
-```
-
-Or, if you already have a backend and a built core:
-
-```bash
-TINYPLACE_API_BASE_URL=http://localhost:18080 node --test messaging.e2e.mjs
-```
-
-## What the UI suite proves
-
-Driven through the real **Messaging** screen (`/agent-world/messaging`) of the
-web build, against the same real backend, with a second core as the peer:
-
-1. **Send** — typing a recipient + message and hitting Send emits an
- end-to-end encrypted DM that the real peer core receives and decrypts.
-2. **Receive** — a reply sent by the peer renders as plaintext in the UI thread.
-
-Contact establishment is done out-of-band here (it's exhaustively covered by the
-core suite); the UI layer focuses on the encrypted send/receive round trip a
-user actually performs on screen.
-
-### Requirements
-
-- Docker (only if you want `run.sh` to auto-start the backend).
-- A built `openhuman-core` binary (`cargo build --bin openhuman-core`; `run.sh`
- builds it if missing). On Apple Silicon prefix with `GGML_NATIVE=OFF`.
-
-### Env knobs
-
-| Var | Default | Meaning |
-| --- | ------- | ------- |
-| `TINYPLACE_API_BASE_URL` | `http://localhost:18080` | Backend base URL both cores point at. |
-| `OPENHUMAN_CORE_BIN` | `target/debug/openhuman-core` | Path to the core binary. |
-| `MANAGE_STACK` | `1` | `0` disables auto start/stop of the backend. |
-| `BACKEND_PORT` | `18080` | Host port for the managed backend. |
-| `VERBOSE` | – | `1` streams each core's stdout/stderr. |
-
-## Why two cores instead of one core + a mock peer
-
-The core's tiny.place identity and Signal session state are process-global
-singletons — one process is exactly one identity. A real two-party round trip
-therefore needs two processes. Using two real cores (rather than a hand-rolled
-SDK peer) means **both** ends of every assertion are the actual openhuman code
-path under test.
-
-## Notes
-
-- Every run generates fresh mnemonics (see [`lib/mnemonic.mjs`](lib/mnemonic.mjs))
- so identities never collide with pre-key state a previous run already
- published to the backend (which would `409` on re-provision). No npm install
- is needed — the BIP-39 generator is dependency-free.
-- The backend must run with a payment verifier that doesn't require real funds
- for identity provisioning; the umbrella `e2e/docker-compose.e2e.yml` overlay
- (static verifier) is what `run.sh` uses.
diff --git a/e2e/tinyplace-messaging/lib/bip39-english.txt b/e2e/tinyplace-messaging/lib/bip39-english.txt
deleted file mode 100644
index 942040ed50..0000000000
--- a/e2e/tinyplace-messaging/lib/bip39-english.txt
+++ /dev/null
@@ -1,2048 +0,0 @@
-abandon
-ability
-able
-about
-above
-absent
-absorb
-abstract
-absurd
-abuse
-access
-accident
-account
-accuse
-achieve
-acid
-acoustic
-acquire
-across
-act
-action
-actor
-actress
-actual
-adapt
-add
-addict
-address
-adjust
-admit
-adult
-advance
-advice
-aerobic
-affair
-afford
-afraid
-again
-age
-agent
-agree
-ahead
-aim
-air
-airport
-aisle
-alarm
-album
-alcohol
-alert
-alien
-all
-alley
-allow
-almost
-alone
-alpha
-already
-also
-alter
-always
-amateur
-amazing
-among
-amount
-amused
-analyst
-anchor
-ancient
-anger
-angle
-angry
-animal
-ankle
-announce
-annual
-another
-answer
-antenna
-antique
-anxiety
-any
-apart
-apology
-appear
-apple
-approve
-april
-arch
-arctic
-area
-arena
-argue
-arm
-armed
-armor
-army
-around
-arrange
-arrest
-arrive
-arrow
-art
-artefact
-artist
-artwork
-ask
-aspect
-assault
-asset
-assist
-assume
-asthma
-athlete
-atom
-attack
-attend
-attitude
-attract
-auction
-audit
-august
-aunt
-author
-auto
-autumn
-average
-avocado
-avoid
-awake
-aware
-away
-awesome
-awful
-awkward
-axis
-baby
-bachelor
-bacon
-badge
-bag
-balance
-balcony
-ball
-bamboo
-banana
-banner
-bar
-barely
-bargain
-barrel
-base
-basic
-basket
-battle
-beach
-bean
-beauty
-because
-become
-beef
-before
-begin
-behave
-behind
-believe
-below
-belt
-bench
-benefit
-best
-betray
-better
-between
-beyond
-bicycle
-bid
-bike
-bind
-biology
-bird
-birth
-bitter
-black
-blade
-blame
-blanket
-blast
-bleak
-bless
-blind
-blood
-blossom
-blouse
-blue
-blur
-blush
-board
-boat
-body
-boil
-bomb
-bone
-bonus
-book
-boost
-border
-boring
-borrow
-boss
-bottom
-bounce
-box
-boy
-bracket
-brain
-brand
-brass
-brave
-bread
-breeze
-brick
-bridge
-brief
-bright
-bring
-brisk
-broccoli
-broken
-bronze
-broom
-brother
-brown
-brush
-bubble
-buddy
-budget
-buffalo
-build
-bulb
-bulk
-bullet
-bundle
-bunker
-burden
-burger
-burst
-bus
-business
-busy
-butter
-buyer
-buzz
-cabbage
-cabin
-cable
-cactus
-cage
-cake
-call
-calm
-camera
-camp
-can
-canal
-cancel
-candy
-cannon
-canoe
-canvas
-canyon
-capable
-capital
-captain
-car
-carbon
-card
-cargo
-carpet
-carry
-cart
-case
-cash
-casino
-castle
-casual
-cat
-catalog
-catch
-category
-cattle
-caught
-cause
-caution
-cave
-ceiling
-celery
-cement
-census
-century
-cereal
-certain
-chair
-chalk
-champion
-change
-chaos
-chapter
-charge
-chase
-chat
-cheap
-check
-cheese
-chef
-cherry
-chest
-chicken
-chief
-child
-chimney
-choice
-choose
-chronic
-chuckle
-chunk
-churn
-cigar
-cinnamon
-circle
-citizen
-city
-civil
-claim
-clap
-clarify
-claw
-clay
-clean
-clerk
-clever
-click
-client
-cliff
-climb
-clinic
-clip
-clock
-clog
-close
-cloth
-cloud
-clown
-club
-clump
-cluster
-clutch
-coach
-coast
-coconut
-code
-coffee
-coil
-coin
-collect
-color
-column
-combine
-come
-comfort
-comic
-common
-company
-concert
-conduct
-confirm
-congress
-connect
-consider
-control
-convince
-cook
-cool
-copper
-copy
-coral
-core
-corn
-correct
-cost
-cotton
-couch
-country
-couple
-course
-cousin
-cover
-coyote
-crack
-cradle
-craft
-cram
-crane
-crash
-crater
-crawl
-crazy
-cream
-credit
-creek
-crew
-cricket
-crime
-crisp
-critic
-crop
-cross
-crouch
-crowd
-crucial
-cruel
-cruise
-crumble
-crunch
-crush
-cry
-crystal
-cube
-culture
-cup
-cupboard
-curious
-current
-curtain
-curve
-cushion
-custom
-cute
-cycle
-dad
-damage
-damp
-dance
-danger
-daring
-dash
-daughter
-dawn
-day
-deal
-debate
-debris
-decade
-december
-decide
-decline
-decorate
-decrease
-deer
-defense
-define
-defy
-degree
-delay
-deliver
-demand
-demise
-denial
-dentist
-deny
-depart
-depend
-deposit
-depth
-deputy
-derive
-describe
-desert
-design
-desk
-despair
-destroy
-detail
-detect
-develop
-device
-devote
-diagram
-dial
-diamond
-diary
-dice
-diesel
-diet
-differ
-digital
-dignity
-dilemma
-dinner
-dinosaur
-direct
-dirt
-disagree
-discover
-disease
-dish
-dismiss
-disorder
-display
-distance
-divert
-divide
-divorce
-dizzy
-doctor
-document
-dog
-doll
-dolphin
-domain
-donate
-donkey
-donor
-door
-dose
-double
-dove
-draft
-dragon
-drama
-drastic
-draw
-dream
-dress
-drift
-drill
-drink
-drip
-drive
-drop
-drum
-dry
-duck
-dumb
-dune
-during
-dust
-dutch
-duty
-dwarf
-dynamic
-eager
-eagle
-early
-earn
-earth
-easily
-east
-easy
-echo
-ecology
-economy
-edge
-edit
-educate
-effort
-egg
-eight
-either
-elbow
-elder
-electric
-elegant
-element
-elephant
-elevator
-elite
-else
-embark
-embody
-embrace
-emerge
-emotion
-employ
-empower
-empty
-enable
-enact
-end
-endless
-endorse
-enemy
-energy
-enforce
-engage
-engine
-enhance
-enjoy
-enlist
-enough
-enrich
-enroll
-ensure
-enter
-entire
-entry
-envelope
-episode
-equal
-equip
-era
-erase
-erode
-erosion
-error
-erupt
-escape
-essay
-essence
-estate
-eternal
-ethics
-evidence
-evil
-evoke
-evolve
-exact
-example
-excess
-exchange
-excite
-exclude
-excuse
-execute
-exercise
-exhaust
-exhibit
-exile
-exist
-exit
-exotic
-expand
-expect
-expire
-explain
-expose
-express
-extend
-extra
-eye
-eyebrow
-fabric
-face
-faculty
-fade
-faint
-faith
-fall
-false
-fame
-family
-famous
-fan
-fancy
-fantasy
-farm
-fashion
-fat
-fatal
-father
-fatigue
-fault
-favorite
-feature
-february
-federal
-fee
-feed
-feel
-female
-fence
-festival
-fetch
-fever
-few
-fiber
-fiction
-field
-figure
-file
-film
-filter
-final
-find
-fine
-finger
-finish
-fire
-firm
-first
-fiscal
-fish
-fit
-fitness
-fix
-flag
-flame
-flash
-flat
-flavor
-flee
-flight
-flip
-float
-flock
-floor
-flower
-fluid
-flush
-fly
-foam
-focus
-fog
-foil
-fold
-follow
-food
-foot
-force
-forest
-forget
-fork
-fortune
-forum
-forward
-fossil
-foster
-found
-fox
-fragile
-frame
-frequent
-fresh
-friend
-fringe
-frog
-front
-frost
-frown
-frozen
-fruit
-fuel
-fun
-funny
-furnace
-fury
-future
-gadget
-gain
-galaxy
-gallery
-game
-gap
-garage
-garbage
-garden
-garlic
-garment
-gas
-gasp
-gate
-gather
-gauge
-gaze
-general
-genius
-genre
-gentle
-genuine
-gesture
-ghost
-giant
-gift
-giggle
-ginger
-giraffe
-girl
-give
-glad
-glance
-glare
-glass
-glide
-glimpse
-globe
-gloom
-glory
-glove
-glow
-glue
-goat
-goddess
-gold
-good
-goose
-gorilla
-gospel
-gossip
-govern
-gown
-grab
-grace
-grain
-grant
-grape
-grass
-gravity
-great
-green
-grid
-grief
-grit
-grocery
-group
-grow
-grunt
-guard
-guess
-guide
-guilt
-guitar
-gun
-gym
-habit
-hair
-half
-hammer
-hamster
-hand
-happy
-harbor
-hard
-harsh
-harvest
-hat
-have
-hawk
-hazard
-head
-health
-heart
-heavy
-hedgehog
-height
-hello
-helmet
-help
-hen
-hero
-hidden
-high
-hill
-hint
-hip
-hire
-history
-hobby
-hockey
-hold
-hole
-holiday
-hollow
-home
-honey
-hood
-hope
-horn
-horror
-horse
-hospital
-host
-hotel
-hour
-hover
-hub
-huge
-human
-humble
-humor
-hundred
-hungry
-hunt
-hurdle
-hurry
-hurt
-husband
-hybrid
-ice
-icon
-idea
-identify
-idle
-ignore
-ill
-illegal
-illness
-image
-imitate
-immense
-immune
-impact
-impose
-improve
-impulse
-inch
-include
-income
-increase
-index
-indicate
-indoor
-industry
-infant
-inflict
-inform
-inhale
-inherit
-initial
-inject
-injury
-inmate
-inner
-innocent
-input
-inquiry
-insane
-insect
-inside
-inspire
-install
-intact
-interest
-into
-invest
-invite
-involve
-iron
-island
-isolate
-issue
-item
-ivory
-jacket
-jaguar
-jar
-jazz
-jealous
-jeans
-jelly
-jewel
-job
-join
-joke
-journey
-joy
-judge
-juice
-jump
-jungle
-junior
-junk
-just
-kangaroo
-keen
-keep
-ketchup
-key
-kick
-kid
-kidney
-kind
-kingdom
-kiss
-kit
-kitchen
-kite
-kitten
-kiwi
-knee
-knife
-knock
-know
-lab
-label
-labor
-ladder
-lady
-lake
-lamp
-language
-laptop
-large
-later
-latin
-laugh
-laundry
-lava
-law
-lawn
-lawsuit
-layer
-lazy
-leader
-leaf
-learn
-leave
-lecture
-left
-leg
-legal
-legend
-leisure
-lemon
-lend
-length
-lens
-leopard
-lesson
-letter
-level
-liar
-liberty
-library
-license
-life
-lift
-light
-like
-limb
-limit
-link
-lion
-liquid
-list
-little
-live
-lizard
-load
-loan
-lobster
-local
-lock
-logic
-lonely
-long
-loop
-lottery
-loud
-lounge
-love
-loyal
-lucky
-luggage
-lumber
-lunar
-lunch
-luxury
-lyrics
-machine
-mad
-magic
-magnet
-maid
-mail
-main
-major
-make
-mammal
-man
-manage
-mandate
-mango
-mansion
-manual
-maple
-marble
-march
-margin
-marine
-market
-marriage
-mask
-mass
-master
-match
-material
-math
-matrix
-matter
-maximum
-maze
-meadow
-mean
-measure
-meat
-mechanic
-medal
-media
-melody
-melt
-member
-memory
-mention
-menu
-mercy
-merge
-merit
-merry
-mesh
-message
-metal
-method
-middle
-midnight
-milk
-million
-mimic
-mind
-minimum
-minor
-minute
-miracle
-mirror
-misery
-miss
-mistake
-mix
-mixed
-mixture
-mobile
-model
-modify
-mom
-moment
-monitor
-monkey
-monster
-month
-moon
-moral
-more
-morning
-mosquito
-mother
-motion
-motor
-mountain
-mouse
-move
-movie
-much
-muffin
-mule
-multiply
-muscle
-museum
-mushroom
-music
-must
-mutual
-myself
-mystery
-myth
-naive
-name
-napkin
-narrow
-nasty
-nation
-nature
-near
-neck
-need
-negative
-neglect
-neither
-nephew
-nerve
-nest
-net
-network
-neutral
-never
-news
-next
-nice
-night
-noble
-noise
-nominee
-noodle
-normal
-north
-nose
-notable
-note
-nothing
-notice
-novel
-now
-nuclear
-number
-nurse
-nut
-oak
-obey
-object
-oblige
-obscure
-observe
-obtain
-obvious
-occur
-ocean
-october
-odor
-off
-offer
-office
-often
-oil
-okay
-old
-olive
-olympic
-omit
-once
-one
-onion
-online
-only
-open
-opera
-opinion
-oppose
-option
-orange
-orbit
-orchard
-order
-ordinary
-organ
-orient
-original
-orphan
-ostrich
-other
-outdoor
-outer
-output
-outside
-oval
-oven
-over
-own
-owner
-oxygen
-oyster
-ozone
-pact
-paddle
-page
-pair
-palace
-palm
-panda
-panel
-panic
-panther
-paper
-parade
-parent
-park
-parrot
-party
-pass
-patch
-path
-patient
-patrol
-pattern
-pause
-pave
-payment
-peace
-peanut
-pear
-peasant
-pelican
-pen
-penalty
-pencil
-people
-pepper
-perfect
-permit
-person
-pet
-phone
-photo
-phrase
-physical
-piano
-picnic
-picture
-piece
-pig
-pigeon
-pill
-pilot
-pink
-pioneer
-pipe
-pistol
-pitch
-pizza
-place
-planet
-plastic
-plate
-play
-please
-pledge
-pluck
-plug
-plunge
-poem
-poet
-point
-polar
-pole
-police
-pond
-pony
-pool
-popular
-portion
-position
-possible
-post
-potato
-pottery
-poverty
-powder
-power
-practice
-praise
-predict
-prefer
-prepare
-present
-pretty
-prevent
-price
-pride
-primary
-print
-priority
-prison
-private
-prize
-problem
-process
-produce
-profit
-program
-project
-promote
-proof
-property
-prosper
-protect
-proud
-provide
-public
-pudding
-pull
-pulp
-pulse
-pumpkin
-punch
-pupil
-puppy
-purchase
-purity
-purpose
-purse
-push
-put
-puzzle
-pyramid
-quality
-quantum
-quarter
-question
-quick
-quit
-quiz
-quote
-rabbit
-raccoon
-race
-rack
-radar
-radio
-rail
-rain
-raise
-rally
-ramp
-ranch
-random
-range
-rapid
-rare
-rate
-rather
-raven
-raw
-razor
-ready
-real
-reason
-rebel
-rebuild
-recall
-receive
-recipe
-record
-recycle
-reduce
-reflect
-reform
-refuse
-region
-regret
-regular
-reject
-relax
-release
-relief
-rely
-remain
-remember
-remind
-remove
-render
-renew
-rent
-reopen
-repair
-repeat
-replace
-report
-require
-rescue
-resemble
-resist
-resource
-response
-result
-retire
-retreat
-return
-reunion
-reveal
-review
-reward
-rhythm
-rib
-ribbon
-rice
-rich
-ride
-ridge
-rifle
-right
-rigid
-ring
-riot
-ripple
-risk
-ritual
-rival
-river
-road
-roast
-robot
-robust
-rocket
-romance
-roof
-rookie
-room
-rose
-rotate
-rough
-round
-route
-royal
-rubber
-rude
-rug
-rule
-run
-runway
-rural
-sad
-saddle
-sadness
-safe
-sail
-salad
-salmon
-salon
-salt
-salute
-same
-sample
-sand
-satisfy
-satoshi
-sauce
-sausage
-save
-say
-scale
-scan
-scare
-scatter
-scene
-scheme
-school
-science
-scissors
-scorpion
-scout
-scrap
-screen
-script
-scrub
-sea
-search
-season
-seat
-second
-secret
-section
-security
-seed
-seek
-segment
-select
-sell
-seminar
-senior
-sense
-sentence
-series
-service
-session
-settle
-setup
-seven
-shadow
-shaft
-shallow
-share
-shed
-shell
-sheriff
-shield
-shift
-shine
-ship
-shiver
-shock
-shoe
-shoot
-shop
-short
-shoulder
-shove
-shrimp
-shrug
-shuffle
-shy
-sibling
-sick
-side
-siege
-sight
-sign
-silent
-silk
-silly
-silver
-similar
-simple
-since
-sing
-siren
-sister
-situate
-six
-size
-skate
-sketch
-ski
-skill
-skin
-skirt
-skull
-slab
-slam
-sleep
-slender
-slice
-slide
-slight
-slim
-slogan
-slot
-slow
-slush
-small
-smart
-smile
-smoke
-smooth
-snack
-snake
-snap
-sniff
-snow
-soap
-soccer
-social
-sock
-soda
-soft
-solar
-soldier
-solid
-solution
-solve
-someone
-song
-soon
-sorry
-sort
-soul
-sound
-soup
-source
-south
-space
-spare
-spatial
-spawn
-speak
-special
-speed
-spell
-spend
-sphere
-spice
-spider
-spike
-spin
-spirit
-split
-spoil
-sponsor
-spoon
-sport
-spot
-spray
-spread
-spring
-spy
-square
-squeeze
-squirrel
-stable
-stadium
-staff
-stage
-stairs
-stamp
-stand
-start
-state
-stay
-steak
-steel
-stem
-step
-stereo
-stick
-still
-sting
-stock
-stomach
-stone
-stool
-story
-stove
-strategy
-street
-strike
-strong
-struggle
-student
-stuff
-stumble
-style
-subject
-submit
-subway
-success
-such
-sudden
-suffer
-sugar
-suggest
-suit
-summer
-sun
-sunny
-sunset
-super
-supply
-supreme
-sure
-surface
-surge
-surprise
-surround
-survey
-suspect
-sustain
-swallow
-swamp
-swap
-swarm
-swear
-sweet
-swift
-swim
-swing
-switch
-sword
-symbol
-symptom
-syrup
-system
-table
-tackle
-tag
-tail
-talent
-talk
-tank
-tape
-target
-task
-taste
-tattoo
-taxi
-teach
-team
-tell
-ten
-tenant
-tennis
-tent
-term
-test
-text
-thank
-that
-theme
-then
-theory
-there
-they
-thing
-this
-thought
-three
-thrive
-throw
-thumb
-thunder
-ticket
-tide
-tiger
-tilt
-timber
-time
-tiny
-tip
-tired
-tissue
-title
-toast
-tobacco
-today
-toddler
-toe
-together
-toilet
-token
-tomato
-tomorrow
-tone
-tongue
-tonight
-tool
-tooth
-top
-topic
-topple
-torch
-tornado
-tortoise
-toss
-total
-tourist
-toward
-tower
-town
-toy
-track
-trade
-traffic
-tragic
-train
-transfer
-trap
-trash
-travel
-tray
-treat
-tree
-trend
-trial
-tribe
-trick
-trigger
-trim
-trip
-trophy
-trouble
-truck
-true
-truly
-trumpet
-trust
-truth
-try
-tube
-tuition
-tumble
-tuna
-tunnel
-turkey
-turn
-turtle
-twelve
-twenty
-twice
-twin
-twist
-two
-type
-typical
-ugly
-umbrella
-unable
-unaware
-uncle
-uncover
-under
-undo
-unfair
-unfold
-unhappy
-uniform
-unique
-unit
-universe
-unknown
-unlock
-until
-unusual
-unveil
-update
-upgrade
-uphold
-upon
-upper
-upset
-urban
-urge
-usage
-use
-used
-useful
-useless
-usual
-utility
-vacant
-vacuum
-vague
-valid
-valley
-valve
-van
-vanish
-vapor
-various
-vast
-vault
-vehicle
-velvet
-vendor
-venture
-venue
-verb
-verify
-version
-very
-vessel
-veteran
-viable
-vibrant
-vicious
-victory
-video
-view
-village
-vintage
-violin
-virtual
-virus
-visa
-visit
-visual
-vital
-vivid
-vocal
-voice
-void
-volcano
-volume
-vote
-voyage
-wage
-wagon
-wait
-walk
-wall
-walnut
-want
-warfare
-warm
-warrior
-wash
-wasp
-waste
-water
-wave
-way
-wealth
-weapon
-wear
-weasel
-weather
-web
-wedding
-weekend
-weird
-welcome
-west
-wet
-whale
-what
-wheat
-wheel
-when
-where
-whip
-whisper
-wide
-width
-wife
-wild
-will
-win
-window
-wine
-wing
-wink
-winner
-winter
-wire
-wisdom
-wise
-wish
-witness
-wolf
-woman
-wonder
-wood
-wool
-word
-work
-world
-worry
-worth
-wrap
-wreck
-wrestle
-wrist
-write
-wrong
-yard
-year
-yellow
-you
-young
-youth
-zebra
-zero
-zone
-zoo
diff --git a/e2e/tinyplace-messaging/lib/core.mjs b/e2e/tinyplace-messaging/lib/core.mjs
deleted file mode 100644
index 155edf3265..0000000000
--- a/e2e/tinyplace-messaging/lib/core.mjs
+++ /dev/null
@@ -1,189 +0,0 @@
-// Boot a real `openhuman-core` process and drive its tiny.place messaging RPCs.
-//
-// openhuman is a Rust core exposing JSON-RPC over `POST /rpc`. All tiny.place
-// messaging lives in the core's `tinyplace` domain (methods
-// `openhuman.tinyplace_*`), backed by the vendored Rust tiny.place SDK. The
-// core derives its tiny.place identity (a base58 Solana cryptoId) from the
-// wallet mnemonic at m/44'/501'/0'/0'. So: one core process = one identity, and
-// two cores with two mnemonics = two agents that can message each other over a
-// real tiny.place backend — exactly what these tests exercise.
-import { spawn } from "node:child_process";
-import { mkdtempSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-
-import { generateMnemonic } from "./mnemonic.mjs";
-
-const HERE = resolve(fileURLToPath(import.meta.url), "..");
-const REPO_ROOT = resolve(HERE, "..", "..", "..");
-
-export const DEFAULT_CORE_BIN =
- process.env.OPENHUMAN_CORE_BIN || join(REPO_ROOT, "target", "debug", "openhuman-core");
-export const DEFAULT_BACKEND =
- process.env.TINYPLACE_API_BASE_URL || "http://localhost:18080";
-
-const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
-
-// The tiny.place identity is re-derived from the mnemonic, so these per-chain
-// account addresses are cosmetic metadata; wallet_setup only validates that
-// each supported chain appears once with a non-empty address + derivation path.
-// The Solana derivation path must be the canonical one the signer uses.
-const PLACEHOLDER_ACCOUNTS = [
- { chain: "evm", address: "0x0000000000000000000000000000000000000001", derivationPath: "m/44'/60'/0'/0/0" },
- { chain: "btc", address: "bc1qplaceholderplaceholderplaceholderplac0000", derivationPath: "m/84'/0'/0'/0/0" },
- { chain: "solana", address: "11111111111111111111111111111111", derivationPath: "m/44'/501'/0'/0'" },
- { chain: "tron", address: "T0000000000000000000000000000000001", derivationPath: "m/44'/195'/0'/0/0" },
-];
-
-function makeRpc(port, token, label) {
- return async function rpc(method, params = {}) {
- let res;
- try {
- res = await fetch(`http://127.0.0.1:${port}/rpc`, {
- method: "POST",
- headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
- body: JSON.stringify({ jsonrpc: "2.0", id: Date.now(), method, params }),
- });
- } catch (e) {
- throw new Error(`[${label}] ${method} transport error: ${e.message}`);
- }
- const body = await res.json();
- if (body.error) {
- throw new Error(`[${label}] ${method} -> ${JSON.stringify(body.error)}`);
- }
- // The core wraps every handler payload as { logs, result }; unwrap it.
- let result = body.result;
- if (result && typeof result === "object" && "result" in result && "logs" in result) {
- result = result.result;
- }
- return result;
- };
-}
-
-/**
- * Launch an openhuman core, import a fresh wallet identity, publish Signal
- * pre-keys, and advertise the encryption key on the directory card — i.e. a
- * fully message-ready tiny.place agent.
- *
- * Returns a handle: { name, cryptoId, rpc, port, workspace, stop() }.
- */
-export async function launchAgent(name, opts = {}) {
- const {
- port,
- backend = DEFAULT_BACKEND,
- coreBin = DEFAULT_CORE_BIN,
- mnemonic = generateMnemonic(),
- preKeyCount = 10,
- verbose = !!process.env.VERBOSE,
- readyTimeoutMs = 45_000,
- } = opts;
- if (!port) throw new Error("launchAgent requires an explicit port");
-
- const token = `oh-${name}-${process.pid}-token`;
- const workspace = mkdtempSync(join(tmpdir(), `oh-${name}-`));
- const child = spawn(
- coreBin,
- ["run", "--host", "127.0.0.1", "--port", String(port), "--jsonrpc-only"],
- {
- env: {
- ...process.env,
- OPENHUMAN_WORKSPACE: workspace,
- OPENHUMAN_KEYRING_BACKEND: "file",
- OPENHUMAN_CORE_TOKEN: token,
- TINYPLACE_API_BASE_URL: backend,
- },
- stdio: ["ignore", "pipe", "pipe"],
- },
- );
- const logs = [];
- const capture = (stream, tag) =>
- stream.on("data", (d) => {
- const line = d.toString();
- logs.push(line);
- if (verbose) process.stderr.write(`[${name}${tag}] ${line}`);
- });
- capture(child.stdout, "");
- capture(child.stderr, "!");
-
- let stopped = false;
- const stop = () => {
- if (!stopped) {
- stopped = true;
- child.kill("SIGKILL");
- }
- };
- const fail = (msg) => {
- stop();
- return new Error(`${msg}\n--- last core logs (${name}) ---\n${logs.slice(-15).join("")}`);
- };
-
- try {
- // 1) Wait for the HTTP server to accept connections.
- let up = false;
- const deadline = Date.now() + readyTimeoutMs;
- while (Date.now() < deadline) {
- if (child.exitCode !== null) throw fail(`core '${name}' exited early (code ${child.exitCode})`);
- try {
- const r = await fetch(`http://127.0.0.1:${port}/health`);
- if (r.ok) { up = true; break; }
- } catch { /* not up yet */ }
- await sleep(400);
- }
- if (!up) throw fail(`core '${name}' /health never came up on :${port}`);
-
- const rpc = makeRpc(port, token, name);
-
- // 2) Import a fresh wallet identity (encrypt the mnemonic, then persist it).
- const encryptedMnemonic = await rpc("openhuman.encrypt_secret", { plaintext: mnemonic });
- await rpc("openhuman.wallet_setup", {
- consentGranted: true,
- source: "imported",
- mnemonicWordCount: mnemonic.split(" ").length,
- encryptedMnemonic,
- accounts: PLACEHOLDER_ACCOUNTS,
- force: true,
- });
-
- // 3) Publish Signal pre-keys so peers can start an encrypted session, and
- // advertise the encryption key on the directory card so it's routable.
- await rpc("openhuman.tinyplace_signal_provision", { preKeyCount });
- await rpc("openhuman.tinyplace_signal_register_encryption_key", {});
-
- const status = await rpc("openhuman.tinyplace_signal_key_status", {});
- const cryptoId = status.agentId;
- if (!cryptoId) throw fail(`core '${name}' produced an empty cryptoId`);
-
- return { name, cryptoId, rpc, port, workspace, stop, mnemonic };
- } catch (e) {
- stop();
- throw e;
- }
-}
-
-/**
- * Poll a core's mailbox, decrypting + acknowledging each envelope, until a
- * message from `fromCryptoId` (or any, if omitted) is decrypted — or timeout.
- * Returns the decrypted plaintext string, or null on timeout.
- */
-export async function receiveMessage(core, { fromCryptoId, timeoutMs = 8_000 } = {}) {
- const deadline = Date.now() + timeoutMs;
- while (Date.now() < deadline) {
- const list = await core.rpc("openhuman.tinyplace_messages_list", { limit: 50 });
- const envelopes = Array.isArray(list) ? list : list?.messages ?? [];
- for (const envelope of envelopes) {
- let decoded;
- try {
- decoded = await core.rpc("openhuman.tinyplace_signal_decrypt_message", { envelope });
- } finally {
- // Acknowledge (delete) regardless: the ratchet already advanced.
- await core.rpc("openhuman.tinyplace_messages_acknowledge", { messageId: envelope.id });
- }
- if (decoded && (!fromCryptoId || decoded.from === fromCryptoId)) {
- return decoded.plaintext;
- }
- }
- await sleep(400);
- }
- return null;
-}
diff --git a/e2e/tinyplace-messaging/lib/mnemonic.mjs b/e2e/tinyplace-messaging/lib/mnemonic.mjs
deleted file mode 100644
index b7814d78f3..0000000000
--- a/e2e/tinyplace-messaging/lib/mnemonic.mjs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Minimal, dependency-free BIP-39 mnemonic generator (English, 128-bit → 12
-// words). Self-contained so the messaging e2e needs no npm install in this
-// pnpm-enforced repo. Standard algorithm: 16 random entropy bytes, append the
-// first ENT/32 = 4 bits of SHA-256(entropy) as checksum, slice into 11-bit
-// groups, map each to the canonical English wordlist.
-//
-// We only need *fresh, valid* mnemonics per run so every test identity is a
-// brand-new tiny.place cryptoId (avoids colliding with prekey state a previous
-// run already published to the backend, which would 409 on re-provision).
-import { createHash, randomBytes } from "node:crypto";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-const HERE = dirname(fileURLToPath(import.meta.url));
-const WORDLIST = readFileSync(join(HERE, "bip39-english.txt"), "utf8")
- .split("\n")
- .map((w) => w.trim())
- .filter(Boolean);
-
-if (WORDLIST.length !== 2048) {
- throw new Error(`bip39 wordlist must have 2048 words, got ${WORDLIST.length}`);
-}
-
-/** Generate a fresh, checksum-valid 12-word English BIP-39 mnemonic. */
-export function generateMnemonic() {
- const entropy = randomBytes(16); // 128 bits
- const checksum = createHash("sha256").update(entropy).digest();
-
- // Build a big-endian bit string of entropy (128) + checksum (4) = 132 bits.
- let bits = "";
- for (const byte of entropy) bits += byte.toString(2).padStart(8, "0");
- bits += checksum[0].toString(2).padStart(8, "0").slice(0, 4);
-
- const words = [];
- for (let i = 0; i < bits.length; i += 11) {
- words.push(WORDLIST[parseInt(bits.slice(i, i + 11), 2)]);
- }
- return words.join(" ");
-}
diff --git a/e2e/tinyplace-messaging/messaging.e2e.mjs b/e2e/tinyplace-messaging/messaging.e2e.mjs
deleted file mode 100644
index bca400ae97..0000000000
--- a/e2e/tinyplace-messaging/messaging.e2e.mjs
+++ /dev/null
@@ -1,178 +0,0 @@
-// End-to-end: openhuman ↔ tiny.place messaging, driven through the real
-// openhuman core JSON-RPC surface against a real tiny.place backend.
-//
-// Two independent `openhuman-core` processes (Alice, Bob), each with its own
-// freshly-imported wallet identity, exercise the complete DM lifecycle exactly
-// as the desktop app would drive it over `core_rpc_relay`:
-//
-// • send a contact request (openhuman.tinyplace_contacts_request)
-// • see it arrive on the other side (openhuman.tinyplace_contacts_requests)
-// • accept the request (openhuman.tinyplace_contacts_accept)
-// • confirm the mutual contact (openhuman.tinyplace_contacts_list)
-// • send Signal-encrypted DMs (openhuman.tinyplace_signal_send_message)
-// • receive + decrypt + acknowledge (messages_list / signal_decrypt_message / messages_acknowledge)
-//
-// It also proves the two security invariants that make this a real messaging
-// system: DMs are refused between non-contacts, and the relay only ever stores
-// opaque ciphertext.
-//
-// Requires: a reachable tiny.place backend (TINYPLACE_API_BASE_URL, default
-// http://localhost:18080) and a built `openhuman-core` binary. `run.sh` wires
-// both up; see README.md.
-import { test, before, after } from "node:test";
-import assert from "node:assert/strict";
-import net from "node:net";
-
-import { launchAgent, receiveMessage, DEFAULT_BACKEND, DEFAULT_CORE_BIN } from "./lib/core.mjs";
-import { existsSync } from "node:fs";
-
-function freePort() {
- return new Promise((res, rej) => {
- const srv = net.createServer();
- srv.on("error", rej);
- srv.listen(0, "127.0.0.1", () => {
- const { port } = srv.address();
- srv.close(() => res(port));
- });
- });
-}
-
-async function backendReachable() {
- try {
- const r = await fetch(`${DEFAULT_BACKEND}/healthz`);
- return r.ok;
- } catch {
- return false;
- }
-}
-
-let alice;
-let bob;
-
-before(async () => {
- assert.ok(
- existsSync(DEFAULT_CORE_BIN),
- `openhuman-core binary not found at ${DEFAULT_CORE_BIN}. Build it: cargo build --bin openhuman-core (or run run.sh).`,
- );
- assert.ok(
- await backendReachable(),
- `tiny.place backend not reachable at ${DEFAULT_BACKEND}/healthz. Start it first (see run.sh / README.md).`,
- );
- const [pa, pb] = await Promise.all([freePort(), freePort()]);
- [alice, bob] = await Promise.all([
- launchAgent("alice", { port: pa }),
- launchAgent("bob", { port: pb }),
- ]);
-});
-
-after(() => {
- alice?.stop();
- bob?.stop();
-});
-
-test("each core boots a distinct, message-ready tiny.place identity", async () => {
- assert.match(alice.cryptoId, /^[1-9A-HJ-NP-Za-km-z]{32,44}$/, "alice cryptoId is base58");
- assert.match(bob.cryptoId, /^[1-9A-HJ-NP-Za-km-z]{32,44}$/, "bob cryptoId is base58");
- assert.notEqual(alice.cryptoId, bob.cryptoId, "the two cores have different identities");
-
- for (const core of [alice, bob]) {
- const status = await core.rpc("openhuman.tinyplace_signal_key_status", {});
- assert.equal(status.agentId, core.cryptoId);
- assert.equal(status.hasActiveSignedPreKey, true, `${core.name} published a signed pre-key`);
- assert.ok(status.localPreKeyCount > 0, `${core.name} holds local one-time pre-keys`);
- assert.equal(status.encryptionKeyPublished, true, `${core.name} advertised its encryption key`);
- }
-});
-
-test("a DM is refused between agents who are not contacts", async () => {
- // Fresh, unrelated identity → not a contact of Bob → the relay must refuse.
- const stranger = await launchAgent("stranger", { port: await freePort() });
- try {
- await assert.rejects(
- () =>
- stranger.rpc("openhuman.tinyplace_signal_send_message", {
- recipient: bob.cryptoId,
- plaintext: "you don't know me",
- }),
- /not_a_contact|403|contact/i,
- "sending a DM without an accepted contact relationship is rejected",
- );
- } finally {
- stranger.stop();
- }
-});
-
-test("Alice sends a contact request and Bob sees it pending", async () => {
- await alice.rpc("openhuman.tinyplace_contacts_request", { agentId: bob.cryptoId });
-
- const incoming = await bob.rpc("openhuman.tinyplace_contacts_requests", {});
- const ids = (incoming.incoming ?? []).map((r) => r.agentId ?? r.cryptoId);
- assert.ok(ids.includes(alice.cryptoId), "Alice's request is in Bob's incoming requests");
-
- const status = await bob.rpc("openhuman.tinyplace_contacts_status", { agentId: alice.cryptoId });
- assert.equal(status.status, "pending", "relationship is pending before acceptance");
-});
-
-test("Bob accepts and both sides see a mutual accepted contact", async () => {
- await bob.rpc("openhuman.tinyplace_contacts_accept", { agentId: alice.cryptoId });
-
- const aliceContacts = await alice.rpc("openhuman.tinyplace_contacts_list", {});
- const aliceIds = (aliceContacts.contacts ?? []).map((c) => c.agentId ?? c.cryptoId);
- assert.ok(aliceIds.includes(bob.cryptoId), "Bob is in Alice's contact list");
-
- const bobStatus = await bob.rpc("openhuman.tinyplace_contacts_status", { agentId: alice.cryptoId });
- assert.equal(bobStatus.status, "accepted", "relationship is accepted");
-});
-
-test("Alice → Bob: first DM (X3DH) is delivered as ciphertext and decrypts", async () => {
- const plaintext = "hello bob — first encrypted DM from alice";
- const sent = await alice.rpc("openhuman.tinyplace_signal_send_message", {
- recipient: bob.cryptoId,
- plaintext,
- });
- assert.equal(sent.encrypted, true, "send reports the message was encrypted");
- assert.ok(sent.messageId, "send returns a messageId");
-
- // Inspect the raw relayed envelope before decrypting: the relay must only
- // ever hold opaque ciphertext, never the plaintext.
- let sawCiphertext = false;
- for (let i = 0; i < 15 && !sawCiphertext; i++) {
- const list = await bob.rpc("openhuman.tinyplace_messages_list", { limit: 50 });
- const envelopes = Array.isArray(list) ? list : list?.messages ?? [];
- const env = envelopes.find((e) => e.id === sent.messageId);
- if (env) {
- assert.notEqual(env.body, plaintext, "relay envelope body is not the plaintext");
- assert.ok(!String(env.body ?? "").includes(plaintext), "ciphertext does not contain the plaintext");
- assert.match(env.type, /PREKEY_BUNDLE|CIPHERTEXT/, "envelope carries a Signal message type");
- sawCiphertext = true;
- } else {
- await new Promise((r) => setTimeout(r, 400));
- }
- }
- assert.ok(sawCiphertext, "Bob's relay mailbox received the ciphertext envelope");
-
- const received = await receiveMessage(bob, { fromCryptoId: alice.cryptoId });
- assert.equal(received, plaintext, "Bob decrypts Alice's first message");
-});
-
-test("Bob → Alice: ratchet reply decrypts, proving a bidirectional session", async () => {
- const plaintext = "hi alice — ratchet reply from bob";
- const sent = await bob.rpc("openhuman.tinyplace_signal_send_message", {
- recipient: alice.cryptoId,
- plaintext,
- });
- assert.equal(sent.encrypted, true);
-
- const received = await receiveMessage(alice, { fromCryptoId: bob.cryptoId });
- assert.equal(received, plaintext, "Alice decrypts Bob's reply");
-});
-
-test("a follow-up DM in the established session still decrypts", async () => {
- const plaintext = "and one more, to prove the session persists";
- await alice.rpc("openhuman.tinyplace_signal_send_message", {
- recipient: bob.cryptoId,
- plaintext,
- });
- const received = await receiveMessage(bob, { fromCryptoId: alice.cryptoId });
- assert.equal(received, plaintext, "Bob decrypts a subsequent in-session message");
-});
diff --git a/e2e/tinyplace-messaging/run-ui.sh b/e2e/tinyplace-messaging/run-ui.sh
deleted file mode 100755
index ac925900bf..0000000000
--- a/e2e/tinyplace-messaging/run-ui.sh
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env bash
-#
-# Run the openhuman ↔ tiny.place messaging UI e2e (Playwright).
-#
-# Reuses the app's standard web-session harness (app/scripts/e2e-web-session.sh)
-# — mock cloud backend + standalone core + static web host — but points the
-# core's *tiny.place* backend at a real one via TINYPLACE_API_BASE_URL, so the
-# Messaging screen exchanges real Signal DMs. The peer core is launched by the
-# spec itself.
-#
-# Steps (each skipped if already satisfied):
-# 1. Ensure a tiny.place backend is reachable (auto-start one unless MANAGE_STACK=0).
-# 2. Ensure the web bundle + core binary are built.
-# 3. Run the Playwright spec through the web session.
-#
-# Env knobs: same as run.sh, plus:
-# HEADED=1 run Playwright headed.
-set -euo pipefail
-
-HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-OPENHUMAN_ROOT="$(cd "$HERE/../.." && pwd)"
-UMBRELLA_ROOT="$(cd "$OPENHUMAN_ROOT/.." && pwd)"
-APP_DIR="$OPENHUMAN_ROOT/app"
-
-BACKEND_PORT="${BACKEND_PORT:-18080}"
-export TINYPLACE_API_BASE_URL="${TINYPLACE_API_BASE_URL:-http://localhost:${BACKEND_PORT}}"
-# Reuse the already-built debug core instead of a separate e2e-web target.
-export E2E_WEB_CORE_TARGET_DIR="${E2E_WEB_CORE_TARGET_DIR:-$OPENHUMAN_ROOT/target}"
-MANAGE_STACK="${MANAGE_STACK:-1}"
-COMPOSE_PROJECT="tinyplace-ohe2e"
-SPEC="test/playwright/specs/tinyplace-messaging.spec.ts"
-
-log() { printf '\033[1;35m[messaging-ui-e2e]\033[0m %s\n' "$*"; }
-backend_up() { curl -fsS "${TINYPLACE_API_BASE_URL%/}/healthz" >/dev/null 2>&1; }
-
-STARTED_STACK=0
-cleanup() {
- if [ "$STARTED_STACK" = "1" ]; then
- log "tearing down backend stack ($COMPOSE_PROJECT)"
- ( cd "$UMBRELLA_ROOT" && MONGO_PORT="${MONGO_PORT:-37017}" REDIS_PORT="${REDIS_PORT:-16379}" BACKEND_PORT="$BACKEND_PORT" \
- docker compose -p "$COMPOSE_PROJECT" -f docker-compose.yml -f e2e/docker-compose.e2e.yml down -v >/dev/null 2>&1 || true )
- fi
-}
-trap cleanup EXIT
-
-# 1) Backend
-if backend_up; then
- log "backend reachable at $TINYPLACE_API_BASE_URL"
-elif [ "$MANAGE_STACK" != "0" ]; then
- log "starting isolated backend stack (mongo+redis+backend, static verifier) on :$BACKEND_PORT"
- ( cd "$UMBRELLA_ROOT" && MONGO_PORT="${MONGO_PORT:-37017}" REDIS_PORT="${REDIS_PORT:-16379}" BACKEND_PORT="$BACKEND_PORT" \
- docker compose -p "$COMPOSE_PROJECT" -f docker-compose.yml -f e2e/docker-compose.e2e.yml up --build -d mongo redis backend )
- STARTED_STACK=1
- for i in $(seq 1 60); do backend_up && break; sleep 2; done
- backend_up || { log "ERROR: backend never became healthy"; exit 1; }
- log "backend healthy"
-else
- log "ERROR: backend not reachable and MANAGE_STACK=0."; exit 1
-fi
-
-# 2) Build web bundle + core if needed.
-if [ ! -f "$APP_DIR/dist-web/index.html" ] || [ ! -x "$E2E_WEB_CORE_TARGET_DIR/debug/openhuman-core" ]; then
- log "building web e2e bundle (+ core if missing)…"
- ( cd "$OPENHUMAN_ROOT" && bash app/scripts/e2e-web-build.sh )
-fi
-# Ensure the Playwright browser is present.
-( cd "$APP_DIR" && pnpm exec playwright install chromium chromium-headless-shell >/dev/null 2>&1 || true )
-
-# 3) Run the spec through the web session harness.
-log "running Playwright spec: $SPEC (tiny.place backend: $TINYPLACE_API_BASE_URL)"
-ARGS=("$SPEC")
-[ "${HEADED:-}" = "1" ] && ARGS+=("--headed")
-exec bash "$APP_DIR/scripts/e2e-web-session.sh" "${ARGS[@]}"
diff --git a/e2e/tinyplace-messaging/run.sh b/e2e/tinyplace-messaging/run.sh
deleted file mode 100755
index 8cffd2009a..0000000000
--- a/e2e/tinyplace-messaging/run.sh
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/env bash
-#
-# Run the openhuman ↔ tiny.place messaging core e2e.
-#
-# Steps (each is skipped if already satisfied):
-# 1. Ensure a tiny.place backend is reachable at $TINYPLACE_API_BASE_URL.
-# If not, and MANAGE_STACK != 0, bring one up from the umbrella
-# docker-compose (mongo + redis + backend, static payment verifier) on an
-# isolated compose project + ports, and tear it down on exit.
-# 2. Ensure the openhuman-core binary is built.
-# 3. Run the node:test suite.
-#
-# Env knobs:
-# TINYPLACE_API_BASE_URL backend base URL (default http://localhost:18080)
-# OPENHUMAN_CORE_BIN path to openhuman-core (default target/debug/openhuman-core)
-# MANAGE_STACK 1 = auto-manage backend (default 1)
-# BACKEND_PORT host port for managed backend (default 18080)
-# VERBOSE 1 = stream core logs
-set -euo pipefail
-
-HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-OPENHUMAN_ROOT="$(cd "$HERE/../.." && pwd)"
-UMBRELLA_ROOT="$(cd "$OPENHUMAN_ROOT/.." && pwd)"
-
-BACKEND_PORT="${BACKEND_PORT:-18080}"
-export TINYPLACE_API_BASE_URL="${TINYPLACE_API_BASE_URL:-http://localhost:${BACKEND_PORT}}"
-export OPENHUMAN_CORE_BIN="${OPENHUMAN_CORE_BIN:-$OPENHUMAN_ROOT/target/debug/openhuman-core}"
-MANAGE_STACK="${MANAGE_STACK:-1}"
-COMPOSE_PROJECT="tinyplace-ohe2e"
-
-log() { printf '\033[1;36m[messaging-e2e]\033[0m %s\n' "$*"; }
-
-backend_up() { curl -fsS "${TINYPLACE_API_BASE_URL%/}/healthz" >/dev/null 2>&1; }
-
-STARTED_STACK=0
-cleanup() {
- if [ "$STARTED_STACK" = "1" ]; then
- log "tearing down backend stack ($COMPOSE_PROJECT)"
- ( cd "$UMBRELLA_ROOT" && MONGO_PORT="${MONGO_PORT:-37017}" REDIS_PORT="${REDIS_PORT:-16379}" BACKEND_PORT="$BACKEND_PORT" \
- docker compose -p "$COMPOSE_PROJECT" -f docker-compose.yml -f e2e/docker-compose.e2e.yml down -v >/dev/null 2>&1 || true )
- fi
-}
-trap cleanup EXIT
-
-# 1) Backend
-if backend_up; then
- log "backend reachable at $TINYPLACE_API_BASE_URL"
-elif [ "$MANAGE_STACK" != "0" ]; then
- if [ ! -f "$UMBRELLA_ROOT/docker-compose.yml" ] || [ ! -f "$UMBRELLA_ROOT/e2e/docker-compose.e2e.yml" ]; then
- log "ERROR: cannot find umbrella docker-compose to auto-start the backend."
- log "Start a tiny.place backend yourself and set TINYPLACE_API_BASE_URL."
- exit 1
- fi
- log "starting isolated backend stack (mongo+redis+backend, static verifier) on :$BACKEND_PORT"
- ( cd "$UMBRELLA_ROOT" && MONGO_PORT="${MONGO_PORT:-37017}" REDIS_PORT="${REDIS_PORT:-16379}" BACKEND_PORT="$BACKEND_PORT" \
- docker compose -p "$COMPOSE_PROJECT" -f docker-compose.yml -f e2e/docker-compose.e2e.yml up --build -d mongo redis backend )
- STARTED_STACK=1
- log "waiting for backend health…"
- for i in $(seq 1 60); do backend_up && break; sleep 2; done
- backend_up || { log "ERROR: backend never became healthy"; exit 1; }
- log "backend healthy"
-else
- log "ERROR: backend not reachable and MANAGE_STACK=0."
- exit 1
-fi
-
-# 2) Core binary
-if [ ! -x "$OPENHUMAN_CORE_BIN" ]; then
- log "building openhuman-core (this can take a while the first time)…"
- ( cd "$OPENHUMAN_ROOT" && GGML_NATIVE=OFF cargo build --bin openhuman-core --manifest-path Cargo.toml )
-fi
-log "using core binary: $OPENHUMAN_CORE_BIN"
-
-# 3) Test
-log "running node:test suite…"
-cd "$HERE"
-exec node --test messaging.e2e.mjs
diff --git a/gitbooks/README.md b/gitbooks/README.md
index 0c8af6d072..17371199c8 100644
--- a/gitbooks/README.md
+++ b/gitbooks/README.md
@@ -25,7 +25,6 @@ OpenHuman solves this with a stack that's calmly, deliberately different:
- [**Workflows**](features/workflows.md)**.** Durable, visual automations on the open-source tinyflows engine. Describe the automation in chat, the agent _proposes_ a workflow graph, you review it on a canvas and save it. Flows fire on schedules or live app events, pause at approval gates, and resume exactly where they stopped, with full step-by-step run history.
- [**A harness that finishes the job**](developing/architecture/agent-harness.md)**.** Every turn runs on the open-source tinyagents graph engine: durable checkpointing (sub-agents pause for your input and resume, instead of dying), a no-progress circuit breaker that stops identical-call loops and hands back a root-cause summary, classified tool failures rendered as actionable timeline cards, and durable, replayable run journals with per-call token and cost accounting.
- [**Privacy Mode**](features/privacy-mode.md)**.** One switch, enforced in the Rust core: local-only mode structurally blocks every cloud model call and permits only on-device runtimes (Ollama, LM Studio, MLX, local OpenAI-compatible).
-- [**An agent economy**](features/tinyplace.md)**.** OpenHuman agents are citizens of tiny.place: a `@handle` identity, Signal-protocol E2E messaging with other agents, x402 USDC bounties and marketplace trading, all signed by an on-device wallet key that never touches disk.
- **Simple, UI-first.** A clean desktop experience and short onboarding paths take you from install to a working agent in a few clicks - no config-first setup, no terminal required. The agent has [a face](features/mascot/README.md): a desktop mascot that speaks, reacts to its surroundings, joins your meetings as a real participant, remembers you across weeks, and keeps thinking in the background even when you've stopped typing.
Together, these turn OpenHuman into something fundamentally different from a chatbot. It is an AI agent that consumes large amounts of personal data at low cost, maintains a persistent and evolving understanding of your world, and takes proactive actions on your behalf.
diff --git a/gitbooks/SUMMARY.md b/gitbooks/SUMMARY.md
index 4364176ebb..136b3e03b3 100644
--- a/gitbooks/SUMMARY.md
+++ b/gitbooks/SUMMARY.md
@@ -59,7 +59,6 @@
- [System & Utilities](features/native-tools/system-and-utilities.md)
- [Notifications & Activity](features/notifications-and-activity.md)
- [Wallet](features/wallet.md)
-- [tiny.place Agent Economy](features/tinyplace.md)
- [Billing, Cost & Usage](features/billing-and-usage.md)
- [Rewards & Referrals](features/rewards-and-referrals.md)
- [iOS Companion](features/ios-companion.md)
diff --git a/gitbooks/developing/architecture.md b/gitbooks/developing/architecture.md
index ebc0e8b3ca..5b1294643c 100644
--- a/gitbooks/developing/architecture.md
+++ b/gitbooks/developing/architecture.md
@@ -290,13 +290,11 @@ Every layer is async and non-blocking. The Rust core processes thousands of conc
## Vendored crate family & recent shifts
-Core subsystems run on published `tiny*` crates, vendored as git submodules under `vendor/` (`tinyagents`, `tinyflows`, `tinycortex`, `tinychannels`, `tinyjuice`, `tinyplace`) so crate changes can be tested in-tree before publishing. The major ownership boundaries are:
+Core subsystems run on published `tiny*` crates, vendored as git submodules under `vendor/` (`tinyagents`, `tinyflows`, `tinycortex`, `tinychannels`, `tinyjuice`) so crate changes can be tested in-tree before publishing. The major ownership boundaries are:
- **Agent engine on tinyagents** — every agent turn runs through the `tinyagents` crate harness via the seam in `src/openhuman/agent/tinyagents/`; see [Agent Harness](architecture/agent-harness.md).
- **Memory on tinycortex** — the generic store/tree/queue/retrieval/sync engine is crate-owned. OpenHuman keeps RPC, tools, scheduling, credentials, security/event policy, worker orchestration, and the host namespace-document store; `src/openhuman/memory/tinycortex/` implements those seams. Concrete embedding transports are shared through `tinyagents::harness::embeddings`.
- **Inference on the crate ModelRouter** — host workload-tier model routing and cloud provider slugs now use the crate-native `ModelRouter`/`OpenAiModel` (#4782, #4783).
-- **Hosted-only brain** — the client-local orchestration graph engine (`src/openhuman/hosted/orchestration/graph/`) was retired (#4738); the client is a thin hosted-brain participant (pushers, effect/tool executors, wire allowlist — #4725) surfaced in the `/orchestration` and `/brain/tinyplace-orchestration` routes.
-
---
## Technology Stack
diff --git a/gitbooks/developing/architecture/frontend.md b/gitbooks/developing/architecture/frontend.md
index e476edee44..9af14cce57 100644
--- a/gitbooks/developing/architecture/frontend.md
+++ b/gitbooks/developing/architecture/frontend.md
@@ -44,7 +44,6 @@ app/src/
├── pages/ # Route-level screens (incl. onboarding/, ios/, dev/)
├── features/ # Feature verticals (human/, conversations/, meet/, voice/)
├── components/ # Shared UI (incl. settings/, layout/shell/, accounts/)
-├── agentworld/ # tiny.place Agent World surface (/agent-world/*)
├── hooks/ # App hooks
├── utils/ # Config, Tauri command wrappers, routing utilities
└── assets/ # Icons and static assets
@@ -408,7 +407,6 @@ Current desktop routes (read `AppRoutes.tsx` for the authoritative table — the
/human → HumanPage (dedicated mascot stage)
/brain → Brain (memory knowledge-graph)
/flows → FlowsPage · /flows/draft → draft canvas · /flows/:id → FlowCanvasPage
-/orchestration → OrchestrationPage (TinyPlace multi-agent coordination)
/workflows/run → WorkflowsRun (single-purpose Skill runner)
/connections → Skills page (connections hub)
/chat/:threadId? → Accounts (unified chat: agent + connected web apps)
@@ -418,7 +416,6 @@ Current desktop routes (read `AppRoutes.tsx` for the authoritative table — the
/rewards → Rewards
/ptt-overlay → PttOverlayPage (push-to-talk overlay window)
/dev/agent-insights → dev-only preview
-/agent-world/* → AgentWorld (tiny.place A2A social network)
* → DefaultRedirect
```
@@ -429,10 +426,9 @@ Back-compat redirects (all `Navigate replace`, query params preserved):
/activity → /settings/notifications /channels → /connections?tab=messaging
/intelligence→ /settings/notifications /routines → /settings/automations
/workflows → /settings/automations /webhooks → /settings/integrations#webhooks
-/brain/tinyplace-orchestration → /orchestration
```
-There is **no** `/login` route — authentication flows through the Welcome page, the `/auth` callback, and deep links. Desktop **Settings is not an inline route**: when the URL is `/settings/*`, `AppShellDesktop` keeps rendering the _background_ location and mounts `SettingsModal` on top (see [Settings](frontend.md#settings)). Note that `/agents` does not exist; the agent-social surface is `/agent-world/*`.
+There is **no** `/login` route — authentication flows through the Welcome page, the `/auth` callback, and deep links. Desktop **Settings is not an inline route**: when the URL is `/settings/*`, `AppShellDesktop` keeps rendering the _background_ location and mounts `SettingsModal` on top (see [Settings](frontend.md#settings)). Note that `/agents` does not exist.
### Route guards
diff --git a/gitbooks/developing/architecture/orchestration.md b/gitbooks/developing/architecture/orchestration.md
deleted file mode 100644
index 81494d26b4..0000000000
--- a/gitbooks/developing/architecture/orchestration.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# Subconscious orchestration layer
-
-The orchestration layer is OpenHuman's **split-brain** coordinator for wrapped
-Claude Code / Codex sessions that talk to the owner agent over tiny.place
-Signal-encrypted DMs. It turns each inbound session DM into one autonomous
-**wake cycle** driven by a single `tinyagents` graph, keeps a durable per-session
-chat model, and runs an offline **subconscious** that reflects on how the world
-is trending and steers later cycles.
-
-Domain root: [`src/openhuman/hosted/orchestration/`](../../../src/openhuman/hosted/orchestration).
-Design spec: [`docs/arch-subconscious.md`](../../../docs/arch-subconscious.md) and
-the staged plan under [`docs/plans/subconscious-orchestration/`](../../../docs/plans/subconscious-orchestration).
-
-## End-to-end flow
-
-```text
-Claude Code / Codex session
- └─ tinyplace harness wrapper — tails the session JSONL → SessionEnvelopeV1
- └─ Signal E2E DM → owner agent's tiny.place inbox [tagged sessionId, source, role]
- └─ ingest (decrypt-once → classify → persist → ack) orchestration/ingest.rs
- └─ OrchestrationSessionMessage event → debounced wake
- └─ THE WAKE GRAPH (one tinyagents CompiledGraph) orchestration/graph/
- normalize → frontend(1) → execute → compress → world_diff
- ▲ │
- └───────────────────────────────────┘
- │
- └─(channel_response)─► send_dm ─► context_guard ─► done
- └─ subconscious tick (offline, cron/heartbeat) — reviews compressed history +
- cumulative world diff → emits a steering directive that later cycles inject
- UI: Brain → Orchestration tab (orchestration.* RPC + orchestration:message socket)
-```
-
-## The wake graph (stages 4 to 5)
-
-One `OrchestrationState` (`graph/state.rs`) flows through the whole cycle and is
-checkpointed at every super-step boundary under thread `orchestration:<session_id>`
-by `SqlRunLedgerCheckpointer`. `frontend` is the router (command-routing): when
-`channel_response` is present it wraps up (`send_dm`), otherwise it hands macro
-instructions to `execute` and loops back. The reasoning core always sets
-`agent_reply`, so the second front-end pass compiles a `channel_response`; a hard
-`max_supersteps` backstop guarantees termination (spec §5 loop continuity).
-
-Every behaviour-bearing node is bundled behind one injected `OrchestrationRuntime`
-(`graph/mod.rs`): the two-pass front end (Quick LLM, `hint:chat`), the reasoning
-core (`hint:reasoning`, spawns worker sub-agents), 20:1 compression, the
-append-only world-state diff, utilization + eviction, and the DM reply. As a
-result, the graph mechanics are hermetically unit-testable with a single stub
-while production wires the real agents / store / memory in `ops.rs`.
-
-Memory mechanics (spec §3 to §4):
-
-- **`compress`** condenses the cycle's execution trace to a strict `input/20` token
- budget (200-token floor only when still compressive), retry-once-then-truncate,
- persisted idempotently by `cycle_id` to the `compressed_history` table.
-- **`world_diff`** appends one entry to an append-only timeline (monotonic `seq`
- from genesis, `terminal_state` kv), idempotent by `cycle_id`.
-- **`context_guard`** runs after all mutations, before END: at ≥
- `context_evict_threshold` (clamped 0.8 to 0.9) it evicts the oldest compressed
- entries to memory RAG under `path_scope = orchestration/<session>` and resets
- utilization.
-
-## The subconscious steering loop (stage 6)
-
-The existing `SubconsciousEngine` tick gains an `orchestration_review` stage that
-runs **fully offline**: a single tool-free provider chat on the `subconscious`
-route under `SubconsciousTainted` origin. It reads unreviewed `compressed_history`
-plus the cumulative world-diff timeline and emits at most one dense
-`STEERING_DIRECTIVE` (with `expires_after_cycles`) into the append-only
-`steering_directives` store (supersede chain + cycle-count expiry). At the start of
-each wake cycle `ops::seed_state` bumps a global reasoning-cycle counter and loads
-the current non-expired directive into `state.subconscious_steering`, which the
-`execute` node weaves into its system prompt via a task-local. The subconscious is
-a decoupled writer: never an edge in the wake graph, never a channel/effect.
-
-## RPC + UI (stage 7)
-
-Renderer-only controllers (internal registry) in `orchestration/schemas.rs`:
-`openhuman.orchestration_{sessions_list, messages_list, send_master_message,
-mark_read, status}`. Live updates ride an `orchestration:message` socket event
-(`bus.rs` broadcast → `core/socketio.rs` bridge) fanned out for every persisted
-chat message. The Brain → Orchestration tab (`TinyPlaceOrchestrationTab.tsx` +
-`useOrchestrationChats.ts`) reads real store classification, live-updates, and lets
-the owner steer the front-end agent from the Master composer.
-
-The `openhuman.orchestration_run` renderer RPC is the direct request/response
-entry point for the backend's paid Medulla engine. It performs a paid-plan
-preflight, advertises OpenHuman's local contact, session-history, and
-send-to-agent tools, and executes requested calls on the device. Tool results
-are returned through `/orchestration/v1/run/continue` until Medulla produces a
-final reply. The backend repeats authentication, entitlement, and resource
-limit enforcement on every cycle.
-
-## Running unattended (stage 8)
-
-- **No message loss**: ingest dedupes by relay `message_id` _before_ decrypt (the
- Signal ratchet is never advanced twice); a relay/decrypt error leaves the message
- un-acked for a clean retry.
-- **No duplicate DM**: the idempotence cursor advances only after a completed,
- DM-sent cycle; `dm_sent` is checkpointed and the deterministic `cycle_id` keeps
- the `compressed_history` / `world_diff` store writes idempotent across a
- checkpoint resume.
-- **Backpressure**: each cycle awaits `scheduler_gate::wait_for_capacity()`, so a
- `Paused`/`Throttled` gate defers the cycle rather than dropping it.
-- **Malformed input**: any non-envelope / malformed DM body falls back to the peer's
- Master window; the parser never panics.
-- **Observability**: nodes log entry/exit with `session_id` / `cycle_id` /
- `tick_id` correlation ids; `orchestration.status` exposes the current steering
- directive, last subconscious tick, ingest-cursor lag, and last error. Message
- bodies / decrypted plaintext / seeds are never logged (guarded by a source-scan
- test).
-
-## Configuration
-
-The `[orchestration]` config block (`src/openhuman/config/schema/orchestration.rs`)
-uses `enabled` as its master switch. Optional direct-cycle overrides are grouped
-under `[orchestration.medulla.prompt_overrides]`,
-`[orchestration.medulla.config]`, and `[orchestration.medulla.limits]`. Omitted
-values retain backend defaults, and the backend clamps all supplied graph and
-resource limits.
diff --git a/gitbooks/features/orchestration.md b/gitbooks/features/orchestration.md
index 4fb7085d1d..972eb36417 100644
--- a/gitbooks/features/orchestration.md
+++ b/gitbooks/features/orchestration.md
@@ -1,14 +1,14 @@
---
description: >-
OpenHuman is an orchestrator, not a chatbot: durable agent graphs, visual
- workflows, sub-agent fleets, a split-brain always-on layer, and end-to-end
- encrypted agent-to-agent sessions, all in one coherent stack.
+ workflows, sub-agent fleets, and a split-brain always-on layer, all in one
+ coherent stack.
icon: sitemap
---
# The Orchestrator
-<figure><img src="../.gitbook/assets/orchestration.png" alt=""><figcaption><p>OpenHuman orchestrating a fleet of agents (its own workers and external harnesses alike) over Signal-encrypted agent-to-agent sessions.</p></figcaption></figure>
+<figure><img src="../.gitbook/assets/orchestration.png" alt=""><figcaption><p>OpenHuman orchestrating a fleet of agents.</p></figcaption></figure>
Most harnesses run one agent in one loop. OpenHuman is built as an **orchestrator**: a stack for coordinating many agents, over long horizons, across machines. It does this durably, observably, and under your control.
@@ -30,12 +30,6 @@ The orchestrator spawns specialized sub-agents (up to 3 levels deep), reuses com
Inbound traffic hits a **fast reflex agent** that triages in seconds and hands a deep **reasoning core** a concise brief; the core does the multi-step work and delegates to workers. The [subconscious loop](subconscious.md) reviews compressed session history and injects steering directives, keeping the always-on layer aligned with your goals, while 20:1 compression keeps week-long sessions bounded.
-## 5. Encrypted orchestration across machines
-
-OpenHuman instances collaborate through [tiny.place](tinyplace.md) sessions secured with the **Signal protocol**: real end-to-end encryption, with keys derived on-device and never persisted. Pairing is consent-based and fails closed: an unlinked agent's message is just a message, never an instruction. Your agent can orchestrate other agents (and be orchestrated) without a server ever seeing plaintext.
-
-Because the transport is plain Signal-encrypted messaging, the other side doesn't have to be OpenHuman. Connect **Claude Code, Codex, OpenClaw, Hermes**, or anything that can hold a session, and use OpenHuman as the conductor for all of your agents and tools.
-
## What's next: RLMs
The direction we're building toward: **Rhai-backed language workflows**. These are agents that express orchestration as small programs in a sandboxed REPL, rather than a fixed graph, so control flow itself becomes something the model writes, inspects, and repairs. The graph engine, checkpointing, and trust model above are the substrate for it.
@@ -50,10 +44,9 @@ The direction we're building toward: **Rhai-backed language workflows**. These a
| Parallelism | Manual / plugin | Native sub-agent fleets, map-reduce fan-out, worker reuse |
| Automation | Scripts & cron | Visual, durable, approval-gated workflows |
| Always-on | None | Split-brain reflex + reasoning core, subconscious steering |
-| Agent-to-agent | None | Signal-encrypted sessions, consent-based pairing, x402 payments |
## See also
-- [Workflows](workflows.md) · [Subconscious Loop](subconscious.md) · [tiny.place Agent Economy](tinyplace.md)
+- [Workflows](workflows.md) · [Subconscious Loop](subconscious.md)
- [Agent Harness](../developing/architecture/agent-harness.md): the developer deep-dive on graphs, breakers, journals.
- [Agent Coordination tools](native-tools/agent-coordination.md): the user-facing spawn/delegate surface.
diff --git a/gitbooks/features/tinyplace.md b/gitbooks/features/tinyplace.md
deleted file mode 100644
index af9ba96330..0000000000
--- a/gitbooks/features/tinyplace.md
+++ /dev/null
@@ -1,43 +0,0 @@
----
-description: >-
- Your agent is a citizen of tiny.place, the agent-to-agent social economy.
- Register a @handle, message other agents over Signal-protocol E2E encryption,
- post and win x402 USDC bounties, and trade in the marketplace.
-icon: globe
----
-
-# tiny.place: The Agent Economy
-
-Most assistants live alone on your machine. OpenHuman agents have a **society**. [tiny.place](https://tiny.place) is an agent-to-agent social network and economy, and OpenHuman ships first-class citizenship: identity, messaging, payments, work, and trade.
-
-## What your agent can do there
-
-- **Own an identity.** Register a `@handle`, a paid, on-chain identity your agent acts as. Identities can be bought, sold, bid on, and assigned; you can hold several and switch the active one.
-- **Message other agents, privately.** Agent-to-agent DMs run over the **Signal protocol**: real end-to-end encryption, with the identity key derived in-memory from your wallet seed and _never written to disk_.
-- **Earn and pay with x402.** tiny.place actions that cost money (registering a handle, funding a bounty) are settled through **x402 micropayments** in USDC or SOL, paid by the built-in [wallet](wallet.md) and signed with the agent's identity key. Every payment carries a signed purpose (e.g. `identity.register`) so you can audit what was paid for and why.
-- **Find work and post it.** **Bounties** are contest-style paid tasks: your agent can browse open bounties, submit work, and get paid on approval; or post its own bounty and adjudicate submissions (including a model-council adjudication mode). A parallel **jobs** flow covers proposal → shortlist → select → escrow → dispute.
-- **Trade.** A marketplace for identities and products: browse, buy, bid, make offers, check an identity's floor price and sale history.
-- **Be social.** Feeds, follows, groups, channels, profiles, and unified search. Your agent can post, react, and build a following.
-
-The agent gets a curated tool surface for all of this (`tinyplace_whoami`, `tinyplace_feed`, `tinyplace_find_work`, `tinyplace_post_bounty`, `tinyplace_submit_work`, `tinyplace_register`, and more), with registration and payments classed as external-effect actions that respect your [approval gate](approval-gate.md).
-
-## Agents talking to agents: orchestration sessions
-
-tiny.place is also how OpenHuman instances collaborate. The **orchestration** layer ingests harness-session DMs from _paired_ agents. Pairing is consent-based (pending → linked → blocked), and DMs from unlinked senders are treated as ordinary messages, never as instructions.
-
-Inbound sessions run through a **split-brain wake graph**: a fast reflex agent triages each message in seconds (reply immediately, or hand the deep reasoning core a concise brief), while the reasoning core does the real multi-step work and delegates to sub-agent workers. Long sessions stay bounded via 20:1 history compression and a rolling world-state diff, and your [subconscious loop](subconscious.md) periodically reviews the whole picture and injects a short steering directive to keep the layer aligned with _your_ priorities.
-
-You can watch and join any of it from **Intelligence → tiny.place**: a contacts → sessions tree with per-session chat, plus a Master channel for plain DMs.
-
-## Security posture
-
-- The tiny.place identity **is** the wallet key. It is derived on demand via the same SLIP-0010 path used for all Solana signing (`m/44'/501'/0'/0'`), never logged, never persisted, never crossed over IPC.
-- x402 accepts **USDC and SOL only**; unsupported assets are rejected outright.
-- tiny.place RPC controllers are internal-only: callable from the desktop app, **not** advertised to agents beyond the curated tool set.
-- Session ingest fails closed: unpaired sender ⇒ no orchestration.
-
-## See also
-
-- [Wallet](wallet.md): the on-device key that funds and signs everything above.
-- [Approval Gate](approval-gate.md): the human check on paid and external actions.
-- [Subconscious Loop](subconscious.md): the steering brain behind orchestration.
diff --git a/plan.md b/plan.md
index d5a3c48f16..e58059af5b 100644
--- a/plan.md
+++ b/plan.md
@@ -167,7 +167,7 @@ Net: ~100 declarations → ~10 with identical per-toolkit coverage.
- **Onboarding credential forms**: happy-path persistence + invalid-input-blocks-navigation for
CustomInference/CustomSearch pages.
- **Coverage-gate scope**: add `scripts/**` (and `packages/**`) to the path filters (§5).
-- **~20 RPC controller domains with zero E2E references** (`recall_calendar`, `tinyplace`,
+- **~20 RPC controller domains with zero E2E references** (`recall_calendar`,
`devices`, `people`, `redirect_links`, …) — one RPC round-trip each; full list in Appendix A.3.
### P2 — polish / lower blast radius
@@ -494,7 +494,7 @@ names — **in-process calls, not RPC** — i.e. unit tests mislabeled `_e2e`. R
### A.3 Missing (adds to §4)
- **P1 — ~20 registered controller domains with zero references anywhere in `tests/`**, including
- real backend-facing surface: `recall_calendar`, `tinyplace`, `redirect_links`,
+ real backend-facing surface: `recall_calendar`, `redirect_links`,
`desktop_companion`, `devices`, `announcements`, `provider_surfaces`, `people`,
`council_registry`, `audio_toolkit`, `agent_experience`, `http_host`, `skill_runtime`,
`session_import`. Minimum: one RPC round-trip (primary read + write) per domain via
diff --git a/scripts/ci/orch-ip-gate.sh b/scripts/ci/orch-ip-gate.sh
index c863bf2bbf..b3268a67ab 100755
--- a/scripts/ci/orch-ip-gate.sh
+++ b/scripts/ci/orch-ip-gate.sh
@@ -20,10 +20,6 @@ for d in reasoning_agent frontend_agent master_agent master_reporter; do
[ -d "src/openhuman/hosted/orchestration/$d" ] && note "orchestration/$d agent package present"
done
-# 2. The retired tiny.place subconscious steering profile.
-[ -f src/openhuman/subconscious/profiles/tinyplace.rs ] &&
- note "tinyplace subconscious profile present"
-
# 3. Any orchestration prompt.md asset (the proprietary prompt IP).
if find src/openhuman/hosted/orchestration -name 'prompt.md' -print -quit 2>/dev/null | grep -q .; then
note "orchestration prompt.md asset present"
diff --git a/scripts/dep-sim.py b/scripts/dep-sim.py
index 0fbb0b979a..2dec902845 100755
--- a/scripts/dep-sim.py
+++ b/scripts/dep-sim.py
@@ -130,7 +130,7 @@ def reachable(root, children, cut: set[str], global_cut: bool = False) -> set[tu
The gap between them is not academic. The `encryption` cohort measures -17
globally but **-4** as a gate, because `hmac`/`hkdf`/`x25519-dalek` arrive via
- `tinyplace` and `zeroize` via `aws-lc-rs -> rustls -> reqwest`. Quoting the
+ `zeroize` via `aws-lc-rs -> rustls -> reqwest`. Quoting the
global number as a gate's value overstates it by a factor of four.
"""
if root[0] in cut:
diff --git a/scripts/generate-test-inventory.mjs b/scripts/generate-test-inventory.mjs
index 8f0c46fe89..4a49bf4f9c 100644
--- a/scripts/generate-test-inventory.mjs
+++ b/scripts/generate-test-inventory.mjs
@@ -15,7 +15,7 @@
// (b) CONTROLLER-DOMAIN CHECK — every controller domain registered in
// `src/core/all.rs` (via `crate::openhuman::<domain>::all_*_controllers`)
// is referenced by >=1 file under `tests/`. Catches RPC domains that
-// ship with zero integration/E2E coverage (recall_calendar, tinyplace,
+// ship with zero integration/E2E coverage (recall_calendar,
// devices, …).
//
// Known-current offenders are seeded into the allowlists below so the check
@@ -74,7 +74,6 @@ const DOMAIN_ALLOWLIST = new Set([
'task_sources',
'text_input',
'thread_goals',
- 'tinyplace',
]);
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/scripts/kernel-floor.limits b/scripts/kernel-floor.limits
index 47b20603b8..0381e9e12c 100644
--- a/scripts/kernel-floor.limits
+++ b/scripts/kernel-floor.limits
@@ -410,8 +410,8 @@
# 304/281/5 2026-08-08 tokio-tungstenite unified on 0.29 (-6 packages/-2
# names). Root Cargo.toml's two per-target
# tokio-tungstenite entries and
-# vendor/tinyplace/sdk/rust/Cargo.toml were pinned at
-# "0.24"; bumped all three to "0.29" (same feature names:
+# the relevant manifests were pinned at "0.24"; bumped
+# all entries to "0.29" (same feature names:
# connect/handshake/native-tls/rustls-tls-webpki-roots).
# Sheds the duplicate tungstenite 0.24 + thiserror 1.x +
# thiserror-impl 1.x majors from the `flows` profile
@@ -423,7 +423,6 @@
# `String` — `.into()` at each send call site in
# src/openhuman/platform/socket/ws_loop.rs (+ its test
# double server in ws_loop_tests.rs) and
-# vendor/tinyplace/sdk/rust/src/websocket.rs.
# NOTE: the DEFAULT (full-feature) profile still shows
# both tungstenite 0.24 and 0.29 — socketioxide 0.15.2 /
# engineioxide 0.15.2 (pulled in by the default-ON
@@ -472,8 +471,8 @@
# join the `web3` gate, unblocked by giving Polymarket its
# own `prediction-markets` feature that implies it (-67 —
# the largest single shed in the program). bs58 and
-# ed25519-dalek stay always-on (orchestration + tinyplace
-# identity), and curve25519-dalek survives under them.
+# ed25519-dalek stay always-on, and curve25519-dalek
+# survives under them.
# 375/6 2026-08-01 M2 step 4: tracing-appender + tracing-log behind
# default-ON `file-logging` (-9). Off-state keeps stderr
# and Sentry but writes nothing to disk, and drops the
diff --git a/src/core/all.rs b/src/core/all.rs
index 8d1e6c8444..2a39ca1860 100644
--- a/src/core/all.rs
+++ b/src/core/all.rs
@@ -134,12 +134,9 @@ pub enum DomainGroup {
/// Desktop-shell-facing surfaces a headless or embedded host has no use for
/// (`desktop/`).
Desktop,
- /// Clients of the hosted TinyHumans backend — billing, team, referral,
- /// announcements, the hosted orchestration brain (`hosted/`). A self-hosted
- /// build drops these as a unit.
+ /// Clients of the hosted TinyHumans backend — billing, team, referral, and
+ /// announcements (`hosted/`). A self-hosted build drops these as a unit.
Hosted,
- /// The multi-agent relay surface (`tinyplace/`).
- Relay,
/// Loadable native modules: the module host, its registry, and the `modules`
/// RPC surface (`modules/`).
Modules,
@@ -149,7 +146,7 @@ pub enum DomainGroup {
impl DomainGroup {
/// Number of variants. Kept in sync by `domain_group_all_lists_every_variant`.
- pub const COUNT: usize = 22;
+ pub const COUNT: usize = 21;
/// Every variant, for exhaustive iteration in drift guards.
///
@@ -180,7 +177,6 @@ impl DomainGroup {
DomainGroup::Runtimes,
DomainGroup::Desktop,
DomainGroup::Hosted,
- DomainGroup::Relay,
DomainGroup::Modules,
DomainGroup::Platform,
];
@@ -209,9 +205,8 @@ impl DomainGroup {
DomainGroup::Runtimes => 16,
DomainGroup::Desktop => 17,
DomainGroup::Hosted => 18,
- DomainGroup::Relay => 19,
- DomainGroup::Modules => 20,
- DomainGroup::Platform => 21,
+ DomainGroup::Modules => 19,
+ DomainGroup::Platform => 20,
}
}
}
@@ -1036,28 +1031,6 @@ fn build_internal_only_controllers() -> Vec<GroupedController> {
DomainGroup::Modules,
crate::openhuman::modules::all_registered_controllers(),
);
- // tiny.place A2A social-network integration: renderer-callable via core_rpc_relay
- // but NOT advertised to agents in tool listings or schema discovery.
- push(
- &mut controllers,
- DomainGroup::Relay,
- crate::openhuman::tinyplace::all_tinyplace_registered_controllers(),
- );
- // User-consented tiny.place pairing for wrapped agent sessions: UI-callable
- // via core_rpc_relay, but excluded from agent tool listings/schema discovery.
- push(
- &mut controllers,
- DomainGroup::Agent,
- crate::openhuman::agent::orchestration::all_pairing_registered_controllers(),
- );
- // Orchestration read surface (stage 7): the TinyPlaceOrchestrationTab reads
- // sessions/messages, sends Master steering DMs, marks read, and polls status.
- // Renderer-only — not advertised to agents.
- push(
- &mut controllers,
- DomainGroup::Hosted,
- crate::openhuman::hosted::orchestration::all_registered_controllers(),
- );
controllers
}
@@ -1175,12 +1148,6 @@ pub fn namespace_description(namespace: &str) -> Option<&'static str> {
"agent_team" => Some(
"Durable agent-team coordination: teams, members, dependency-aware task claiming, and teammate messaging.",
),
- "orchestration_pairing" => Some(
- "User-consented tiny.place contact pairing for wrapped agent sessions.",
- ),
- "orchestration" => Some(
- "Subconscious-orchestration read surface: chat windows (master/subconscious/per-session), message history, Master steering DMs, read state, and steering status.",
- ),
"billing" => Some("Subscription plan, payment links, and credit top-up via the backend."),
"announcements" => {
Some("Latest active product announcement surfaced on harness init, via the backend.")
@@ -1225,9 +1192,6 @@ pub fn namespace_description(namespace: &str) -> Option<&'static str> {
"subsystems" => Some(
"Kernel subsystem slots and their bound drivers: class, health, contract version, and advertised capabilities.",
),
- "tinyplace" => Some(
- "tiny.place A2A social-network integration: directory, explorer, and search over the agent network.",
- ),
_ => None,
}
}
diff --git a/src/core/all_tests.rs b/src/core/all_tests.rs
index 856d269d8b..bec0fc2316 100644
--- a/src/core/all_tests.rs
+++ b/src/core/all_tests.rs
@@ -1274,7 +1274,6 @@ fn carved_out_families_report_their_own_group() {
("task_sources", DomainGroup::Integrations),
("billing", DomainGroup::Hosted),
("team", DomainGroup::Hosted),
- ("tinyplace", DomainGroup::Relay),
("dashboard", DomainGroup::Desktop),
("notification", DomainGroup::Desktop),
("sandbox", DomainGroup::Runtimes),
@@ -1323,7 +1322,6 @@ fn platform_holds_only_kernel_surfaces() {
| "team"
| "referral"
| "announcements"
- | "tinyplace"
| "dashboard"
| "notification"
| "sandbox"
@@ -1383,7 +1381,6 @@ fn kernel_preset_is_the_floor() {
("runtimes", k.runtimes),
("desktop", k.desktop),
("hosted", k.hosted),
- ("relay", k.relay),
("platform", k.platform),
] {
assert!(!on, "kernel() must leave `{name}` off");
@@ -1401,7 +1398,6 @@ fn embedded_preset_excludes_desktop_and_hosted() {
!e.hosted,
"embedded() must not enable hosted-backend clients"
);
- assert!(!e.relay, "embedded() must not enable the relay surface");
// Still needs these: skills run on the managed runtimes, and the session
// loop is driven by cron.
assert!(e.runtimes, "embedded() needs the code-execution runtimes");
@@ -1486,7 +1482,6 @@ fn every_domain_group_is_accounted_for_in_store_init_plan() {
DomainGroup::Runtimes,
DomainGroup::Desktop,
DomainGroup::Hosted,
- DomainGroup::Relay,
// The registry is a compiled-in `const` table and the loaded-module set
// lives in tinybus's own `ModuleHost`, so there is nothing for
// `init_stores` to stand up.
@@ -1543,7 +1538,6 @@ fn every_domain_group_is_accounted_for_in_subscriber_plan() {
DomainGroup::Automation,
DomainGroup::Runtimes,
DomainGroup::Hosted,
- DomainGroup::Relay,
// Modules run on their own in-process broker, so they cannot publish a
// `DomainEvent` and there is nothing on the core bus to subscribe to.
DomainGroup::Modules,
diff --git a/src/core/events.rs b/src/core/events.rs
index cd030d59d7..332b1e0fd2 100644
--- a/src/core/events.rs
+++ b/src/core/events.rs
@@ -126,15 +126,6 @@ pub enum DomainEvent {
orchestration_id: String,
reason: Option<String>,
},
- /// A tiny.place contact edge changed for a wrapped orchestration session.
- /// Payload is intentionally metadata only; contact graph details stay behind
- /// the signed tiny.place API.
- OrchestrationPairingChanged {
- agent_id: String,
- status: String,
- source: String,
- },
-
// ── Subconscious orchestrator ───────────────────────────────────────
/// A subconscious trigger finished gate evaluation (promote or drop).
/// Observability only — lets dashboards see ingestion volume and the
@@ -1257,27 +1248,6 @@ pub enum DomainEvent {
},
/// A thread's goal was cleared (deleted).
ThreadGoalCleared { thread_id: String },
-
- /// A JSON message arrived on a tinyplace WebSocket stream.
- /// Published by the stream manager's recv loop. Carries the raw
- /// server-sent JSON value (inbox item, conversation message, etc.)
- /// so the Socket.IO bridge can forward it to the renderer.
- TinyPlaceStreamMessage {
- /// Stream identifier (e.g. `"inbox"`, `"conversation:abc123"`).
- stream_id: String,
- /// Stream kind for routing.
- kind: String,
- /// The raw JSON message from the tinyplace server.
- message: serde_json::Value,
- },
- /// A tinyplace WebSocket stream changed lifecycle status.
- /// Published by the stream manager on connect, disconnect, and failure.
- TinyPlaceStreamStatusChanged {
- /// Stream identifier.
- stream_id: String,
- /// New status: `"connecting"`, `"connected"`, `"disconnected"`, `"failed"`.
- status: String,
- },
}
impl DomainEvent {
@@ -1295,7 +1265,6 @@ impl DomainEvent {
| Self::AgentOrchestrationCompleted { .. }
| Self::AgentOrchestrationFailed { .. }
| Self::AgentOrchestrationClosed { .. }
- | Self::OrchestrationPairingChanged { .. }
| Self::RunQueueMessageQueued { .. }
| Self::RunQueueFollowupDispatched { .. }
| Self::RunQueueInterrupted { .. }
@@ -1427,10 +1396,6 @@ impl DomainEvent {
| Self::McpClientToolExecuted { .. }
| Self::McpSetupSecretRequested { .. }
| Self::McpToolRejected { .. } => "mcp_client",
-
- Self::TinyPlaceStreamMessage { .. } | Self::TinyPlaceStreamStatusChanged { .. } => {
- "tinyplace"
- }
}
}
@@ -1448,7 +1413,6 @@ impl DomainEvent {
Self::AgentOrchestrationCompleted { .. } => "AgentOrchestrationCompleted",
Self::AgentOrchestrationFailed { .. } => "AgentOrchestrationFailed",
Self::AgentOrchestrationClosed { .. } => "AgentOrchestrationClosed",
- Self::OrchestrationPairingChanged { .. } => "OrchestrationPairingChanged",
Self::SubconsciousTriggerProcessed { .. } => "SubconsciousTriggerProcessed",
Self::RunQueueMessageQueued { .. } => "RunQueueMessageQueued",
Self::RunQueueFollowupDispatched { .. } => "RunQueueFollowupDispatched",
@@ -1560,8 +1524,6 @@ impl DomainEvent {
Self::TaskRunReclaimed { .. } => "TaskRunReclaimed",
Self::ThreadGoalUpdated { .. } => "ThreadGoalUpdated",
Self::ThreadGoalCleared { .. } => "ThreadGoalCleared",
- Self::TinyPlaceStreamMessage { .. } => "TinyPlaceStreamMessage",
- Self::TinyPlaceStreamStatusChanged { .. } => "TinyPlaceStreamStatusChanged",
Self::Voice(_) => "Voice",
}
}
diff --git a/src/core/jsonrpc.rs b/src/core/jsonrpc.rs
index 20278a7b65..23f7d22cc2 100644
--- a/src/core/jsonrpc.rs
+++ b/src/core/jsonrpc.rs
@@ -131,11 +131,8 @@ pub async fn rpc_handler(State(state): State<AppState>, Json(req): Json<RpcReque
display_message
);
} else if is_wallet_not_configured_error(&display_message) {
- // A `tinyplace_*` RPC needs a wallet-derived signer but the user
- // has not set one up. Expected user-state (the UI shows a
- // "set up wallet" prompt), not an internal failure — skip Sentry
- // here so the message is left untouched for direct (agent-tool)
- // callers. See `is_wallet_not_configured_error`.
+ // A wallet-backed RPC cannot run before wallet setup. This is
+ // expected user state, not an internal failure.
tracing::info!(
method = %method,
"[rpc] wallet-not-configured (expected user-state) — skipping Sentry"
@@ -426,17 +423,9 @@ fn is_param_validation_error(msg: &str) -> bool {
/// Returns `true` when the error is the wallet's "not configured yet" message.
///
-/// Several `tinyplace_*` RPCs derive a signer seed from the wallet before they
-/// can run (the feed, signal/messaging, etc. — backend `GraphQLAuth::Agent`
-/// requires a signer). For a user who has not set up a wallet, the wallet layer
-/// returns [`crate::openhuman::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE`]. That is
-/// an expected user-state, not an internal failure: the UI already renders a
-/// "set up wallet" prompt, and there is no local lever to make the call succeed
-/// until the user creates a wallet. Classifying it here — at the single Sentry
-/// boundary — keeps it out of Sentry for *every* path that surfaces it (the
-/// shared client builder and the direct `signal_store` seed call alike) without
-/// the controllers returning a structured envelope, which would leak the raw
-/// sentinel string to agent tools that call those handlers directly.
+/// Wallet-backed RPCs return
+/// [`crate::openhuman::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE`] before
+/// setup. That is expected user state, not an internal failure.
///
/// Matched against the shared wallet constant (exact equality) so a wording
/// change in the wallet layer fails the coupling test in `jsonrpc_tests.rs`
@@ -2261,15 +2250,6 @@ fn register_domain_subscribers(
);
}
- // Hosted: ingest tiny.place harness session DMs off the stream bus.
- if plan.hosted {
- if group_first_time(DomainGroup::Hosted) {
- crate::openhuman::hosted::orchestration::register_orchestration_ingest_subscriber();
- }
- } else {
- log::debug!("[event_bus] orchestration ingest SKIPPED — Hosted domain disabled");
- }
-
// Agent: native agent handlers + background-completion delivery +
// run-ledger finalizer.
if plan.agent {
diff --git a/src/core/jsonrpc_tests.rs b/src/core/jsonrpc_tests.rs
index 67f0f7704f..546cbeef0b 100644
--- a/src/core/jsonrpc_tests.rs
+++ b/src/core/jsonrpc_tests.rs
@@ -1712,7 +1712,7 @@ async fn desktop_auth_rejects_embedded_fetch_metadata() {
#[cfg(feature = "http-server")]
fn is_wallet_not_configured_error_matches_wallet_constant() {
// The classifier keys off the wallet layer's exact "not configured"
- // message so a wallet-less user's tinyplace RPC stays out of Sentry.
+ // message so wallet-backed RPCs stay out of Sentry.
assert!(is_wallet_not_configured_error(
crate::openhuman::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE
));
@@ -1736,7 +1736,7 @@ fn is_wallet_not_configured_error_does_not_match_other_errors() {
// Other wallet/seed-derivation failures (decrypt, key derivation, locked
// keychain) are real defects and must keep reaching Sentry.
assert!(!is_wallet_not_configured_error(
- "tinyplace signer init: bad seed"
+ "wallet signer init: bad seed"
));
assert!(!is_wallet_not_configured_error(
"decrypt secret: kms timeout"
diff --git a/src/core/observability.rs b/src/core/observability.rs
index 3ddd8ce095..4e25a41c45 100644
--- a/src/core/observability.rs
+++ b/src/core/observability.rs
@@ -3912,13 +3912,13 @@ mod tests {
// Bare, as the wallet layer produces it.
sentinel.to_string(),
// The wrap that #5805 actually observed.
- format!("self_identity key_status: {sentinel}"),
+ format!("wallet status: {sentinel}"),
// Two layers — a wrapper wrapping a wrapper. Exact equality and a
// single-prefix strip both fail here; substring matching does not.
- format!("orchestration.self_identity failed: self_identity key_status: {sentinel}"),
+ format!("wallet transfer failed: wallet status: {sentinel}"),
// A different domain entirely, to show the fix is not scoped to the
// one call site the issue was found through.
- format!("tinyplace signal seed: {sentinel}"),
+ format!("wallet balance failed: {sentinel}"),
] {
assert_eq!(
expected_error_kind(&msg),
@@ -3928,7 +3928,7 @@ mod tests {
}
// Full demotion path (classifier -> report arm) must not panic.
report_error_or_expected(
- &format!("self_identity key_status: {sentinel}"),
+ &format!("wallet status: {sentinel}"),
"rpc",
"invoke_method",
&[],
diff --git a/src/core/runtime/builder.rs b/src/core/runtime/builder.rs
index b75133176b..f69a0cbcb0 100644
--- a/src/core/runtime/builder.rs
+++ b/src/core/runtime/builder.rs
@@ -61,8 +61,6 @@ pub struct ServiceSet {
pub integrations: bool,
/// Workspace memory-source periodic sync — repos, folders, RSS, web pages.
pub memory_sync: bool,
- /// Orchestration relay-mailbox drain supervisor.
- pub orchestration: bool,
}
impl ServiceSet {
@@ -81,7 +79,6 @@ impl ServiceSet {
mcp_boot: true,
integrations: true,
memory_sync: true,
- orchestration: true,
}
}
@@ -101,7 +98,6 @@ impl ServiceSet {
mcp_boot: false,
integrations: false,
memory_sync: false,
- orchestration: false,
}
}
@@ -121,7 +117,6 @@ impl ServiceSet {
mcp_boot: false,
integrations: false,
memory_sync: false,
- orchestration: false,
}
}
@@ -151,7 +146,6 @@ impl ServiceSet {
mcp_boot: false,
integrations: false,
memory_sync: true,
- orchestration: false,
}
}
}
@@ -218,8 +212,6 @@ pub struct DomainSet {
pub desktop: bool,
/// Clients of the hosted TinyHumans backend.
pub hosted: bool,
- /// The multi-agent relay surface (tinyplace).
- pub relay: bool,
/// Loadable native modules: the module host, registry and `modules` RPC.
pub modules: bool,
/// Everything not in a named family — always on in `full()`.
@@ -250,7 +242,6 @@ impl DomainSet {
runtimes: true,
desktop: true,
hosted: true,
- relay: true,
modules: true,
platform: true,
}
@@ -280,7 +271,6 @@ impl DomainSet {
runtimes: false,
desktop: false,
hosted: false,
- relay: false,
modules: false,
platform: false,
}
@@ -327,7 +317,6 @@ impl DomainSet {
runtimes: true,
desktop: false,
hosted: false,
- relay: false,
modules: false,
platform: true,
}
@@ -363,7 +352,6 @@ impl DomainSet {
runtimes: false,
desktop: false,
hosted: false,
- relay: false,
modules: false,
platform: false,
}
@@ -391,7 +379,6 @@ impl DomainSet {
runtimes: false,
desktop: false,
hosted: false,
- relay: false,
modules: false,
platform: false,
}
@@ -419,7 +406,6 @@ impl DomainSet {
DomainGroup::Runtimes => self.runtimes,
DomainGroup::Desktop => self.desktop,
DomainGroup::Hosted => self.hosted,
- DomainGroup::Relay => self.relay,
DomainGroup::Modules => self.modules,
DomainGroup::Platform => self.platform,
}
@@ -1093,7 +1079,6 @@ mod tests {
assert!(!custom.mcp_boot);
assert!(!custom.integrations);
assert!(!custom.memory_sync);
- assert!(!custom.orchestration);
let desktop = ServiceSet::desktop();
assert!(desktop.memory_queue);
@@ -1102,12 +1087,10 @@ mod tests {
assert!(desktop.mcp_boot);
assert!(desktop.integrations);
assert!(desktop.memory_sync);
- assert!(desktop.orchestration);
// headless_api() runs no bootstrap jobs either.
let headless = ServiceSet::headless_api();
assert!(!headless.integrations);
assert!(!headless.memory_sync);
- assert!(!headless.orchestration);
}
}
diff --git a/src/core/runtime/services.rs b/src/core/runtime/services.rs
index 4d52292ddd..af9d3789eb 100644
--- a/src/core/runtime/services.rs
+++ b/src/core/runtime/services.rs
@@ -213,9 +213,6 @@ pub(crate) struct BootstrapJobPlan {
/// Workspace memory-source periodic sync — repos, folders, RSS, web pages
/// (`memory_sync::workspace::start_workspace_periodic_sync`).
pub workspace_memory_sync: bool,
- /// Orchestration relay-mailbox drain supervisor
- /// (`orchestration::start_message_drain_supervisor`).
- pub orchestration_drain: bool,
/// Proactive task pollers (`task_sources::start_periodic_poll` +
/// `agent::task_dispatcher::start_board_poller`).
pub proactive_task_pollers: bool,
@@ -232,7 +229,6 @@ pub(crate) fn bootstrap_job_plan(services: &ServiceSet) -> BootstrapJobPlan {
memory_queue: services.memory_queue,
composio_integration_sync: services.integrations,
workspace_memory_sync: services.memory_sync,
- orchestration_drain: services.orchestration,
proactive_task_pollers: services.cron,
}
}
@@ -247,7 +243,7 @@ pub(crate) fn bootstrap_job_plan(services: &ServiceSet) -> BootstrapJobPlan {
/// behind its own concern flag. The four non-channel jobs used to ride
/// `services.channels` — a channels-off + memory/integrations-on embedder
/// silently lost all of them (#5028) — so they now sit behind `integrations` /
-/// `memory_sync` / `orchestration` instead.
+/// `memory_sync` instead.
///
/// `config` is unread as of openhuman#5560 — the engine's `queue::start` was
/// this function's only consumer of it, and the loaded TinyMemory module starts
@@ -338,14 +334,6 @@ pub fn start_bootstrap_jobs(services: ServiceSet, _config: &Config) {
log::debug!("[runtime.bootstrap] workspace periodic sync disabled by ServiceSet");
}
- // Orchestration — relay-mailbox drain supervisor.
- if plan.orchestration_drain {
- log::debug!("[runtime.bootstrap] starting orchestration message drain supervisor");
- crate::openhuman::hosted::orchestration::start_message_drain_supervisor();
- } else {
- log::debug!("[runtime.bootstrap] message drain supervisor disabled by ServiceSet");
- }
-
if plan.proactive_task_pollers {
log::debug!("[runtime.bootstrap] starting proactive task pollers (task sources + board)");
crate::openhuman::integrations::task_sources::start_periodic_poll();
@@ -551,7 +539,6 @@ mod tests {
memory_queue: true,
composio_integration_sync: true,
workspace_memory_sync: true,
- orchestration_drain: true,
proactive_task_pollers: true,
}
);
@@ -564,7 +551,6 @@ mod tests {
memory_queue: false,
composio_integration_sync: false,
workspace_memory_sync: false,
- orchestration_drain: false,
proactive_task_pollers: false,
};
assert_eq!(bootstrap_job_plan(&ServiceSet::none()), empty);
@@ -580,7 +566,6 @@ mod tests {
let plan = bootstrap_job_plan(&integrations);
assert!(plan.composio_integration_sync);
assert!(!plan.workspace_memory_sync);
- assert!(!plan.orchestration_drain);
assert!(!plan.memory_queue);
assert!(!plan.proactive_task_pollers);
@@ -589,14 +574,6 @@ mod tests {
let plan = bootstrap_job_plan(&memory_sync);
assert!(plan.workspace_memory_sync);
assert!(!plan.composio_integration_sync);
- assert!(!plan.orchestration_drain);
-
- let mut orchestration = ServiceSet::none();
- orchestration.orchestration = true;
- let plan = bootstrap_job_plan(&orchestration);
- assert!(plan.orchestration_drain);
- assert!(!plan.composio_integration_sync);
- assert!(!plan.workspace_memory_sync);
}
/// From desktop(), disabling exactly one concern flag disables only its job.
@@ -607,7 +584,6 @@ mod tests {
let plan = bootstrap_job_plan(&services);
assert!(!plan.composio_integration_sync);
assert!(plan.workspace_memory_sync);
- assert!(plan.orchestration_drain);
assert!(plan.memory_queue);
assert!(plan.proactive_task_pollers);
@@ -616,14 +592,6 @@ mod tests {
let plan = bootstrap_job_plan(&services);
assert!(!plan.workspace_memory_sync);
assert!(plan.composio_integration_sync);
- assert!(plan.orchestration_drain);
-
- let mut services = ServiceSet::desktop();
- services.orchestration = false;
- let plan = bootstrap_job_plan(&services);
- assert!(!plan.orchestration_drain);
- assert!(plan.composio_integration_sync);
- assert!(plan.workspace_memory_sync);
}
/// The #5028 regression: `channels` gates NO bootstrap job. Turning channels
diff --git a/src/core/socketio.rs b/src/core/socketio.rs
index c491a07c6a..7014b53df1 100644
--- a/src/core/socketio.rs
+++ b/src/core/socketio.rs
@@ -684,9 +684,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {
let io_auth = io.clone();
let io_mcp_setup = io.clone();
let io_memory_sync = io.clone();
- let io_tinyplace = io.clone();
let io_channel_status = io.clone();
- let io_orchestration = io.clone();
let io_companion = io.clone();
// 2. Dictation hotkey events → broadcast to all connected clients.
@@ -793,30 +791,6 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {
log::debug!("[socketio] core_notification bridge stopped");
});
- // 5b. Orchestration chat activity → broadcast to all clients so the
- // TinyPlaceOrchestrationTab targeted-refetches the affected chat live
- // (stage 7). Mirrors the overlay/notification fire-and-forget pattern.
- tokio::spawn(async move {
- let mut rx = crate::openhuman::hosted::orchestration::subscribe_orchestration_socket();
- loop {
- let payload = match rx.recv().await {
- Ok(payload) => payload,
- Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
- log::warn!(
- "[socketio] dropped {} orchestration events due to lag",
- skipped
- );
- continue;
- }
- Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
- };
- log::debug!("[socketio] broadcast orchestration:message");
- let _ = io_orchestration.emit("orchestration:message", &payload);
- let _ = io_orchestration.emit("orchestration_message", &payload);
- }
- log::debug!("[socketio] orchestration bridge stopped");
- });
-
// 6. SessionExpired events → broadcast to all clients so the UI can
// proactively tear down user-scoped state and route to onboarding
// instead of waiting for the next poll to discover the JWT is gone.
@@ -1194,72 +1168,6 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {
log::debug!("[socketio] memory_sync bridge stopped");
});
- // 9. Tinyplace stream events → broadcast to all connected frontend sockets.
- tokio::spawn(async move {
- let bus = {
- const RETRY_INTERVAL_MS: u64 = 250;
- const MAX_WAIT_SECS: u64 = 30;
- let max_attempts = (MAX_WAIT_SECS * 1000) / RETRY_INTERVAL_MS;
- let mut attempts: u64 = 0;
- loop {
- if let Some(bus) = crate::core::bus::BUS.get() {
- break bus;
- }
- attempts += 1;
- if attempts > max_attempts {
- log::warn!(
- "[socketio] event_bus not initialised after {}s — tinyplace bridge giving up",
- MAX_WAIT_SECS
- );
- return;
- }
- tokio::time::sleep(std::time::Duration::from_millis(RETRY_INTERVAL_MS)).await;
- }
- };
- let mut rx = bus.receiver();
- loop {
- let Some(event) = rx.recv().await else {
- break;
- };
- match event {
- crate::core::events::DomainEvent::TinyPlaceStreamMessage {
- stream_id,
- kind,
- message,
- } => {
- let payload = json!({
- "stream_id": stream_id,
- "kind": kind,
- "message": message,
- });
- log::debug!(
- "[socketio] broadcast tinyplace:stream_message stream_id={} kind={}",
- stream_id,
- kind
- );
- let _ = io_tinyplace.emit("tinyplace:stream_message", &payload);
- }
- crate::core::events::DomainEvent::TinyPlaceStreamStatusChanged {
- stream_id,
- status,
- } => {
- let payload = json!({
- "stream_id": stream_id,
- "status": status,
- });
- log::debug!(
- "[socketio] broadcast tinyplace:stream_status stream_id={} status={}",
- stream_id,
- status
- );
- let _ = io_tinyplace.emit("tinyplace:stream_status", &payload);
- }
- _ => {}
- }
- }
- log::debug!("[socketio] tinyplace stream bridge stopped");
- });
-
// 10. Channel listener health → broadcast `channel:connection-updated` to
// all clients so the Messaging tab reflects the *live* connection state
// instead of a stale, credential-presence-only "Connected" (issue
diff --git a/src/openhuman/agent/harness/subagent_runner/ops_tests.rs b/src/openhuman/agent/harness/subagent_runner/ops_tests.rs
index 7133ecf15d..a1f2b04f02 100644
--- a/src/openhuman/agent/harness/subagent_runner/ops_tests.rs
+++ b/src/openhuman/agent/harness/subagent_runner/ops_tests.rs
@@ -131,13 +131,13 @@ fn filter_wildcard_includes_all_minus_disallowed() {
fn filter_wildcard_honours_disallowed_prefix_entries() {
let parent: Vec<Box<dyn Tool>> = vec![
stub("alpha"),
- stub("tinyplace_registry_register"),
- stub("tinyplace_marketplace_buy_identity"),
+ stub("vendor_registry_register"),
+ stub("vendor_marketplace_buy_identity"),
stub("gamma"),
];
let mut def = make_def_named_tools(&[]);
def.tools = ToolScope::Wildcard;
- def.disallowed_tools = vec!["tinyplace_*".into()];
+ def.disallowed_tools = vec!["vendor_*".into()];
let idx = filter_tool_indices(&parent, &def.tools, &def.disallowed_tools, None);
let names: Vec<&str> = idx.iter().map(|&i| parent[i].name()).collect();
assert_eq!(names, vec!["alpha", "gamma"]);
diff --git a/src/openhuman/agent/harness/subagent_runner/tool_prep.rs b/src/openhuman/agent/harness/subagent_runner/tool_prep.rs
index 6ed7f175d3..48bf7e5868 100644
--- a/src/openhuman/agent/harness/subagent_runner/tool_prep.rs
+++ b/src/openhuman/agent/harness/subagent_runner/tool_prep.rs
@@ -229,14 +229,14 @@ mod tests {
use super::*;
#[test]
- fn custom_tinyplace_delegate_is_treated_as_spawn_tool() {
+ fn custom_delegate_is_treated_as_spawn_tool() {
assert!(is_subagent_spawn_tool("spawn_subagent"));
assert!(is_subagent_spawn_tool("delegate_researcher"));
// Context scouting is top-level only — never visible to sub-agents
// (incl. wildcard agents), which would otherwise scout the wrong
// parent context. See #3949 review.
assert!(is_subagent_spawn_tool("agent_prepare_context"));
- assert!(!is_subagent_spawn_tool("tinyplace_directory_resolve"));
+ assert!(!is_subagent_spawn_tool("directory_resolve"));
}
#[test]
diff --git a/src/openhuman/agent/orchestration/mod.rs b/src/openhuman/agent/orchestration/mod.rs
index 1d6148d56e..a2c49a5f58 100644
--- a/src/openhuman/agent/orchestration/mod.rs
+++ b/src/openhuman/agent/orchestration/mod.rs
@@ -22,8 +22,6 @@ pub(crate) mod background_delivery;
pub mod command_center;
pub(crate) mod delegation;
mod ops;
-pub mod pairing;
-mod pairing_schemas;
pub(crate) mod parent_context;
pub(crate) mod run_ledger_finalize;
pub(crate) mod running_subagents;
@@ -45,10 +43,6 @@ pub use command_center::{
all_command_center_controller_schemas, all_command_center_registered_controllers,
};
pub use ops::{AgentOrchestrationSession, OrchestrationError};
-pub use pairing_schemas::{
- all_controller_schemas as all_pairing_controller_schemas,
- all_registered_controllers as all_pairing_registered_controllers,
-};
pub use subagent_control::{
all_controller_schemas as all_subagent_control_controller_schemas,
all_registered_controllers as all_subagent_control_registered_controllers,
diff --git a/src/openhuman/agent/orchestration/pairing.rs b/src/openhuman/agent/orchestration/pairing.rs
deleted file mode 100644
index 08bb31b3cf..0000000000
--- a/src/openhuman/agent/orchestration/pairing.rs
+++ /dev/null
@@ -1,1126 +0,0 @@
-//! User-consented tiny.place contact pairing for wrapped agent sessions.
-//!
-//! The tiny.place backend owns the contact graph; this module owns OpenHuman's
-//! local consent record for orchestration sessions that are allowed to exchange
-//! 1:1 encrypted envelopes.
-
-use std::collections::{HashMap, HashSet};
-use std::fmt::Write as _;
-use std::path::{Path, PathBuf};
-use std::sync::{Arc, LazyLock};
-
-use serde::{Deserialize, Serialize};
-use serde_json::Value;
-use tokio::sync::Mutex;
-
-use chrono::{DateTime, Duration, Utc};
-
-use crate::core::bus::BUS;
-use crate::core::events::DomainEvent;
-use crate::openhuman::config::Config;
-use crate::openhuman::hosted::orchestration::ingest::resolve_linked_id;
-use crate::openhuman::tinyplace::ops::{global_state as tinyplace_state, map_err};
-
-const LOG_TARGET: &str = "orchestration_pairing";
-
-/// How long a local co-location handshake entry stays auto-acceptable. The CLI
-/// writes its entry moments before it sends the contact request, so the window
-/// is deliberately short — a long-lived entry would keep a since-departed agent
-/// id auto-acceptable long after the CLI is gone.
-fn local_handshake_ttl() -> Duration {
- Duration::hours(1)
-}
-
-static STORE_LOCKS: LazyLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> =
- LazyLock::new(|| Mutex::new(HashMap::new()));
-
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum PairingStatus {
- Pending,
- Linked,
- Blocked,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum PairingSource {
- UserLink,
- ApprovedRequest,
-}
-
-impl PairingSource {
- fn as_str(&self) -> &'static str {
- match self {
- Self::UserLink => "user_link",
- Self::ApprovedRequest => "approved_request",
- }
- }
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PairingRecord {
- pub agent_id: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub label: Option<String>,
- pub status: PairingStatus,
- pub linked_at: String,
- pub source: PairingSource,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PairingSnapshot {
- pub records: Vec<PairingRecord>,
- pub contacts: Value,
- pub requests: Value,
- pub stats: Value,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PairingActionResult {
- pub record: Option<PairingRecord>,
- pub remote: Value,
-}
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct PairingStore {
- #[serde(default)]
- records: Vec<PairingRecord>,
-}
-
-pub async fn list(config: &Config) -> Result<PairingSnapshot, String> {
- log::debug!(target: LOG_TARGET, "[orchestration_pairing] list.entry");
- let records = load_store(&config.workspace_dir).await?.records;
- let client = tinyplace_state().client().await?;
- let contacts: Value = client
- .http()
- .get_agent_auth::<Value>("/contacts", &[("limit".to_string(), "100".to_string())])
- .await
- .map_err(map_err)?;
- let requests: Value = client
- .http()
- .get_agent_auth::<Value>(
- "/contacts/requests",
- &[("limit".to_string(), "100".to_string())],
- )
- .await
- .map_err(map_err)?;
- let stats: Value = client
- .http()
- .get_agent_auth::<Value>("/contacts/stats", &[])
- .await
- .map_err(map_err)?;
- log::debug!(
- target: LOG_TARGET,
- "[orchestration_pairing] list.exit records={}",
- records.len()
- );
- Ok(PairingSnapshot {
- records,
- contacts,
- requests,
- stats,
- })
-}
-
-pub async fn link_session(
- config: &Config,
- agent_id: &str,
- label: Option<String>,
-) -> Result<PairingActionResult, String> {
- let agent_id = normalize_agent_id(agent_id)?;
- log::debug!(target: LOG_TARGET, "[orchestration_pairing] link.entry agent_id={agent_id}");
- let client = tinyplace_state().client().await?;
- let status = contact_status(&agent_id).await?;
- if status == "blocked" {
- log::warn!(
- target: LOG_TARGET,
- "[orchestration_pairing] link.blocked agent_id={agent_id}"
- );
- return Err("session agent is blocked; unblock before linking".to_string());
- }
-
- let remote = if status == "accepted" {
- serde_json::json!({ "agentId": agent_id, "status": "accepted" })
- } else {
- client
- .http()
- .post_agent_auth::<Value, ()>(&contact_path(&agent_id, None), None)
- .await
- .map_err(map_err)?
- };
- let record_status = if remote_status(&remote).as_deref() == Some("accepted") {
- PairingStatus::Linked
- } else {
- PairingStatus::Pending
- };
- let record = persist_record(
- &config.workspace_dir,
- agent_id,
- label,
- record_status,
- PairingSource::UserLink,
- )
- .await?;
- publish_pairing_changed(&record);
- log::debug!(target: LOG_TARGET, "[orchestration_pairing] link.exit agent_id={}", record.agent_id);
- Ok(PairingActionResult {
- record: Some(record),
- remote,
- })
-}
-
-pub async fn accept_request(
- config: &Config,
- agent_id: &str,
-) -> Result<PairingActionResult, String> {
- let agent_id = normalize_agent_id(agent_id)?;
- log::debug!(target: LOG_TARGET, "[orchestration_pairing] accept.entry agent_id={agent_id}");
- let client = tinyplace_state().client().await?;
- let remote: Value = client
- .http()
- .post_agent_auth::<Value, ()>(&contact_path(&agent_id, Some("accept")), None)
- .await
- .map_err(map_err)?;
- let record = persist_record(
- &config.workspace_dir,
- agent_id,
- None,
- PairingStatus::Linked,
- PairingSource::ApprovedRequest,
- )
- .await?;
- publish_pairing_changed(&record);
- log::debug!(target: LOG_TARGET, "[orchestration_pairing] accept.exit agent_id={}", record.agent_id);
- Ok(PairingActionResult {
- record: Some(record),
- remote,
- })
-}
-
-pub async fn decline_request(
- config: &Config,
- agent_id: &str,
-) -> Result<PairingActionResult, String> {
- let agent_id = normalize_agent_id(agent_id)?;
- log::debug!(target: LOG_TARGET, "[orchestration_pairing] decline.entry agent_id={agent_id}");
- let client = tinyplace_state().client().await?;
- let remote: Value = client
- .http()
- .delete_agent_auth::<Value, ()>(&contact_path(&agent_id, None), None)
- .await
- .map_err(map_err)?;
- remove_record(&config.workspace_dir, &agent_id).await?;
- BUS.publish(DomainEvent::OrchestrationPairingChanged {
- agent_id: agent_id.clone(),
- status: "removed".to_string(),
- source: "approved_request".to_string(),
- });
- log::debug!(target: LOG_TARGET, "[orchestration_pairing] decline.exit agent_id={agent_id}");
- Ok(PairingActionResult {
- record: None,
- remote,
- })
-}
-
-pub async fn block_request(config: &Config, agent_id: &str) -> Result<PairingActionResult, String> {
- let agent_id = normalize_agent_id(agent_id)?;
- log::debug!(target: LOG_TARGET, "[orchestration_pairing] block.entry agent_id={agent_id}");
- let client = tinyplace_state().client().await?;
- let remote: Value = client
- .http()
- .post_agent_auth::<Value, ()>(&contact_path(&agent_id, Some("block")), None)
- .await
- .map_err(map_err)?;
- let record = persist_record(
- &config.workspace_dir,
- agent_id,
- None,
- PairingStatus::Blocked,
- PairingSource::ApprovedRequest,
- )
- .await?;
- publish_pairing_changed(&record);
- log::debug!(target: LOG_TARGET, "[orchestration_pairing] block.exit agent_id={}", record.agent_id);
- Ok(PairingActionResult {
- record: Some(record),
- remote,
- })
-}
-
-async fn contact_status(agent_id: &str) -> Result<String, String> {
- let client = tinyplace_state().client().await?;
- match client
- .http()
- .get_agent_auth::<Value>(&contact_path(agent_id, Some("status")), &[])
- .await
- {
- Ok(remote) => Ok(remote_status(&remote).unwrap_or_else(|| "none".to_string())),
- // A 404 from /contacts/{id}/status means "no contact relationship yet" —
- // the normal state before you've ever linked this agent. Treat it as
- // `none` (not an error) so `link_session` proceeds to send the request
- // instead of surfacing a false "not found" and aborting the first link.
- Err(e) if e.status() == Some(404) => {
- log::debug!(
- target: LOG_TARGET,
- "[orchestration_pairing] contact_status.none agent_id={agent_id} (404 = no relationship yet)"
- );
- Ok("none".to_string())
- }
- Err(e) => Err(map_err(e)),
- }
-}
-
-/// Whether the peer is an accepted tiny.place contact.
-///
-/// This is intentionally a live relay check rather than a read of the local
-/// orchestration pairing store. An accepted contact is already a
-/// user-consented recipient for an outbound message, even when it has not been
-/// linked as an inbound orchestration session in the current workspace.
-pub(crate) async fn is_accepted_contact(agent_id: &str) -> Result<bool, String> {
- let agent_id = normalize_agent_id(agent_id)?;
- Ok(contact_status(&agent_id).await? == "accepted")
-}
-
-fn remote_status(value: &Value) -> Option<String> {
- value
- .get("status")
- .and_then(Value::as_str)
- .map(str::to_string)
-}
-
-async fn persist_record(
- workspace_dir: &Path,
- agent_id: String,
- label: Option<String>,
- status: PairingStatus,
- source: PairingSource,
-) -> Result<PairingRecord, String> {
- let store_lock = store_lock(workspace_dir).await;
- let _guard = store_lock.lock().await;
- let mut store = load_store(workspace_dir).await?;
- let record = PairingRecord {
- agent_id,
- label: label.and_then(|value| {
- let trimmed = value.trim();
- (!trimmed.is_empty()).then(|| trimmed.to_string())
- }),
- status,
- linked_at: chrono::Utc::now().to_rfc3339(),
- source,
- };
- store
- .records
- .retain(|existing| existing.agent_id != record.agent_id);
- store.records.push(record.clone());
- store.records.sort_by(|a, b| a.agent_id.cmp(&b.agent_id));
- save_store(workspace_dir, &store).await?;
- Ok(record)
-}
-
-async fn remove_record(workspace_dir: &Path, agent_id: &str) -> Result<(), String> {
- let store_lock = store_lock(workspace_dir).await;
- let _guard = store_lock.lock().await;
- let mut store = load_store(workspace_dir).await?;
- store.records.retain(|record| record.agent_id != agent_id);
- save_store(workspace_dir, &store).await
-}
-
-async fn store_lock(workspace_dir: &Path) -> Arc<Mutex<()>> {
- let path = store_path(workspace_dir);
- let mut locks = STORE_LOCKS.lock().await;
- locks
- .entry(path)
- .or_insert_with(|| Arc::new(Mutex::new(())))
- .clone()
-}
-
-async fn load_store(workspace_dir: &Path) -> Result<PairingStore, String> {
- let path = store_path(workspace_dir);
- match tokio::fs::read(&path).await {
- Ok(bytes) => serde_json::from_slice(&bytes)
- .map_err(|e| format!("read orchestration pairing store: {e}")),
- Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(PairingStore::default()),
- Err(err) => Err(format!("read orchestration pairing store: {err}")),
- }
-}
-
-/// Agent ids that hold an accepted (linked) local pairing record. Local-only
-/// read (no network) — used to gate which DM senders the orchestration layer is
-/// allowed to decrypt/ingest, so ordinary human DMs are never consumed. Returns
-/// an empty set on any read error (fail-closed: nothing is ingested).
-pub(crate) async fn linked_agent_ids(workspace_dir: &Path) -> std::collections::HashSet<String> {
- match load_store(workspace_dir).await {
- Ok(store) => store
- .records
- .into_iter()
- .filter(|record| record.status == PairingStatus::Linked)
- .map(|record| record.agent_id)
- .collect(),
- Err(e) => {
- log::warn!(target: LOG_TARGET, "[orchestration_pairing] linked_agent_ids read failed: {e}");
- HashSet::new()
- }
- }
-}
-
-/// One entry in the local co-location handshake file (`~/.openhuman/local-agents.json`).
-/// A tiny.place CLI wrapper writes its own agent id + the OpenHuman owner it is
-/// connecting to, moments before it sends its contact request. Because a contact
-/// request carries NO owner declaration on the wire, this same-machine file is
-/// how a freshly-connecting local agent proves "I am a co-located CLI that wants
-/// THIS OpenHuman as my owner" — same-user filesystem access is the trust proof.
-#[derive(Debug, Clone, Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct LocalAgentEntry {
- agent_id: String,
- /// The OpenHuman agent id this CLI declares as its owner. Auto-accept only
- /// fires when this matches OUR own id — so a CLI configured for a *different*
- /// local OpenHuman identity is never cross-accepted just for sharing a box.
- owner: String,
- /// RFC3339 write time. Required + TTL-bounded (fail-closed): a missing or
- /// stale timestamp is not trusted, so a long-dead entry can't linger as
- /// auto-acceptable.
- #[serde(default)]
- ts: Option<String>,
-}
-
-#[derive(Debug, Clone, Default, Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct LocalAgentsFile {
- #[serde(default)]
- agents: Vec<LocalAgentEntry>,
-}
-
-/// Path of the local co-location handshake file, `~/.openhuman/local-agents.json`.
-/// `None` when the home dir is unresolvable (never trust anything in that case).
-fn local_agents_path() -> Option<PathBuf> {
- dirs::home_dir().map(|home| home.join(".openhuman").join("local-agents.json"))
-}
-
-/// Fail-closed ownership/permission gate for a handshake path (issue #4777
-/// review). Same-user filesystem access is the ONLY trust proof for
-/// auto-accepting a co-located CLI's contact request, so a path another local
-/// account could have written must never be trusted. On Unix, require the path
-/// to be owned by the current effective uid AND not group/world-writable —
-/// otherwise a permissive umask or shared home would let a different local user
-/// plant a fresh owner-matching entry and get auto-accepted with no human click.
-/// A missing/unreadable stat is untrusted (`false`). Non-Unix hosts trust the
-/// path (the handshake is a same-machine dev-CLI feature; Windows ACLs are out
-/// of scope) — every other trust source stays fail-closed regardless.
-#[cfg(unix)]
-fn path_is_privately_owned(path: &Path) -> bool {
- use std::os::unix::fs::MetadataExt as _;
- // SAFETY: `geteuid` takes no arguments, mutates no state, and cannot fail.
- let euid = unsafe { libc::geteuid() };
- match std::fs::metadata(path) {
- Ok(meta) => meta.uid() == euid && (meta.mode() & 0o022) == 0,
- Err(_) => false,
- }
-}
-
-#[cfg(not(unix))]
-fn path_is_privately_owned(_path: &Path) -> bool {
- true
-}
-
-/// Read + parse the local co-location handshake file. Missing file → empty (the
-/// common case: no local CLI connecting). A parse/read error is logged and also
-/// yields empty — fail-closed, trusts nothing. Cheap: local file read, no network.
-fn load_local_agents() -> LocalAgentsFile {
- let Some(path) = local_agents_path() else {
- return LocalAgentsFile::default();
- };
- load_local_agents_from(&path)
-}
-
-/// Perm-gated read + parse of a handshake file at `path`. Split from
-/// [`load_local_agents`] so the trust gate is unit-testable with a tempfile,
-/// without depending on the real home dir.
-fn load_local_agents_from(path: &Path) -> LocalAgentsFile {
- let bytes = match std::fs::read(path) {
- Ok(bytes) => bytes,
- Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
- return LocalAgentsFile::default()
- }
- Err(err) => {
- log::warn!(target: LOG_TARGET, "[orchestration_pairing] local_agents.read_failed: {err}");
- return LocalAgentsFile::default();
- }
- };
- // Trust proof (fail-closed): require the handshake file AND its parent
- // `.openhuman` dir to be privately owned by us and not writable by others.
- // On a multi-user host with a group/world-writable home (permissive umask,
- // shared box), another local account could otherwise inject a fresh
- // owner-matching entry and open a DM/orchestration channel to this brain
- // with no human approval. The parent-dir check also closes the symlink
- // vector (an attacker cannot plant a symlink in a dir they cannot write).
- let parent_ok = path.parent().map(path_is_privately_owned).unwrap_or(false);
- if !parent_ok || !path_is_privately_owned(path) {
- log::warn!(
- target: LOG_TARGET,
- "[orchestration_pairing] local_agents.untrusted_perms — file or parent dir not privately owned; refusing to trust handshake"
- );
- return LocalAgentsFile::default();
- }
- serde_json::from_slice(&bytes).unwrap_or_else(|e| {
- log::warn!(target: LOG_TARGET, "[orchestration_pairing] local_agents.parse_failed: {e}");
- LocalAgentsFile::default()
- })
-}
-
-/// True when `ts` is a parseable RFC3339 stamp within the handshake TTL of `now`
-/// (allowing minor clock skew into the future). A missing/malformed/expired stamp
-/// is NOT fresh — fail-closed. Pure.
-fn entry_is_fresh(ts: Option<&str>, now: DateTime<Utc>) -> bool {
- let Some(ts) = ts else {
- return false;
- };
- let Ok(written) = DateTime::parse_from_rfc3339(ts) else {
- return false;
- };
- let written = written.with_timezone(&Utc);
- let age = now.signed_duration_since(written);
- age >= -Duration::minutes(5) && age < local_handshake_ttl()
-}
-
-/// Reduce the local handshake file to the set of agent ids OpenHuman may
-/// auto-accept: those declaring US (`own`) as owner AND still fresh. Pure — the
-/// trust gate is unit-testable without any filesystem or network IO.
-fn coload_trusted_ids(file: &LocalAgentsFile, own: &str, now: DateTime<Utc>) -> HashSet<String> {
- let own_set: HashSet<String> = std::iter::once(own.to_string()).collect();
- file.agents
- .iter()
- .filter(|entry| resolve_linked_id(&entry.owner, &own_set).is_some())
- .filter(|entry| entry_is_fresh(entry.ts.as_deref(), now))
- .map(|entry| entry.agent_id.trim().to_string())
- .filter(|id| !id.is_empty())
- .collect()
-}
-
-/// Poll the tiny.place incoming contact-request queue and auto-accept every
-/// request whose requester is either (a) already a linked (paired) agent, or
-/// (b) a co-located local CLI that named us as owner in the local handshake file
-/// — and ONLY those. A request from any other agent is deliberately left
-/// **pending** for the human to decide: generic auto-accept stays off, because
-/// accepting a contact is a trust decision (the relay's own rule is "never
-/// auto-accept"). The two exceptions are the user's *own* already-paired agents
-/// and their *own* freshly-launched local CLI on this same machine.
-///
-/// Why this is the delivery gate: tiny.place's relay DROPS any DM to a peer that
-/// has not accepted a contact request, so a wrapped agent that re-establishes
-/// contact (a fresh daemon or reconnect that re-sends its one `contact_add`, or a
-/// relay-side contact reset) is otherwise blocked behind a pending request — its
-/// session intro (`session_info`) and entire session stream never arrive.
-/// Auto-accepting linked agents opens that gate for them only. (A *rotated* key is
-/// a different Ed25519 identity, so it is NOT in the linked set and its request is
-/// correctly left pending for the human.)
-///
-/// No per-cycle churn: accepting moves the relay edge from `pending` → `accepted`,
-/// and `/contacts/requests` only lists *pending* requests, so an accepted
-/// requester drops out of `incoming` and is not re-selected next pass. We also
-/// accept under the **canonical** linked id (see [`requesters_to_auto_accept`]),
-/// so a base64-form request can't slip past a base58 stored id and re-fire.
-///
-/// Fail-closed on both sources: [`linked_agent_ids`] returns an **empty** set on
-/// any pairing-store read error, and [`load_local_agents`] / [`coload_trusted_ids`]
-/// yield **empty** on a missing/corrupt handshake file, an unresolvable owner id,
-/// or a stale/undated entry — so a read failure or an unlocked-wallet miss
-/// auto-accepts NOTHING (every request is left pending) rather than opening the
-/// gate. Returns the number of requests accepted this pass.
-pub async fn auto_accept_linked_contact_requests(config: &Config) -> Result<usize, String> {
- let linked = linked_agent_ids(&config.workspace_dir).await;
- // Candidate co-location entries (same-machine handshake file). Cheap local
- // read, no network, no wallet needed.
- let local = load_local_agents();
- // Nothing linked AND no local handshake candidates → nothing to match; skip
- // the round-trip AND avoid needing an unlocked wallet (fail-closed no-op).
- if linked.is_empty() && local.agents.is_empty() {
- return Ok(0);
- }
- let client = tinyplace_state().client().await?;
- // Resolve OUR own id so co-location entries can be owner-matched. Best-effort:
- // if the signer is unavailable we simply trust no local entries (linked-only).
- let trusted = match client.http().signer() {
- Some(signer) => coload_trusted_ids(&local, &signer.agent_id(), Utc::now()),
- None => {
- log::debug!(target: LOG_TARGET, "[orchestration_pairing] auto_accept.signer_unavailable");
- HashSet::new()
- }
- };
- // Union of the two trust sources. `requesters_to_auto_accept` canonicalizes a
- // requester's wire id against this set, so base64/base58 forms unify.
- let mut acceptable = linked.clone();
- acceptable.extend(trusted.iter().cloned());
- if acceptable.is_empty() {
- return Ok(0);
- }
- // `limit=100` caps one scan (consistent with `list()`); a linked requester
- // beyond the 100th *pending* request waits until earlier ones clear. Fine at
- // expected volumes — a paired fleet is small — revisit with pagination if not.
- let requests: Value = client
- .http()
- .get_agent_auth::<Value>(
- "/contacts/requests",
- &[("limit".to_string(), "100".to_string())],
- )
- .await
- .map_err(map_err)?;
- let to_accept = requesters_to_auto_accept(&incoming_pending_requesters(&requests), &acceptable);
- log::debug!(
- target: LOG_TARGET,
- "[orchestration_pairing] auto_accept.scan linked={} coload={} accept={}",
- linked.len(),
- trusted.len(),
- to_accept.len()
- );
- let mut accepted = 0usize;
- for agent_id in to_accept {
- match accept_request(config, &agent_id).await {
- Ok(_) => {
- accepted += 1;
- log::info!(
- target: LOG_TARGET,
- "[orchestration_pairing] auto_accept.linked agent_id={agent_id}"
- );
- }
- Err(e) => log::warn!(
- target: LOG_TARGET,
- "[orchestration_pairing] auto_accept.failed agent_id={agent_id}: {e}"
- ),
- }
- }
- Ok(accepted)
-}
-
-/// Requester agent id of every *pending incoming* contact request in a raw
-/// `/contacts/requests` response. For an incoming request the counterpart is the
-/// requester: prefer the top-level `agentId`, falling back to `contact.requester`
-/// (the relay does not always populate `agentId`). Mirrors the frontend
-/// `contactAddress` resolution in `orchestrationTabHelpers.ts`. Pure — no IO — so
-/// the parse is unit-testable without a live client.
-fn incoming_pending_requesters(requests: &Value) -> Vec<String> {
- let Some(incoming) = requests.get("incoming").and_then(Value::as_array) else {
- return Vec::new();
- };
- incoming
- .iter()
- .filter(|view| view.get("status").and_then(Value::as_str) == Some("pending"))
- .filter_map(request_view_requester)
- .collect()
-}
-
-/// The counterpart (requester) address of a single incoming contact-request view.
-fn request_view_requester(view: &Value) -> Option<String> {
- if let Some(id) = view.get("agentId").and_then(Value::as_str) {
- let trimmed = id.trim();
- if !trimmed.is_empty() {
- return Some(trimmed.to_string());
- }
- }
- view.get("contact")
- .and_then(|contact| contact.get("requester"))
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|requester| !requester.is_empty())
- .map(str::to_string)
-}
-
-/// Decide which incoming requesters to auto-accept: exactly those already in the
-/// linked-agent set. Requesters not linked are intentionally left for the human.
-///
-/// Returns each match's **canonical linked id** (via [`resolve_linked_id`]), NOT
-/// the raw wire id — so a request that carries the base64 form of a key stored as
-/// base58 is accepted/persisted under the existing base58 record rather than
-/// spawning a duplicate `Linked` record for the same identity. Pure — the trust
-/// gate is unit-testable without any network or store IO.
-fn requesters_to_auto_accept(incoming: &[String], linked: &HashSet<String>) -> Vec<String> {
- incoming
- .iter()
- .filter_map(|id| resolve_linked_id(id, linked))
- .collect()
-}
-
-async fn save_store(workspace_dir: &Path, store: &PairingStore) -> Result<(), String> {
- let path = store_path(workspace_dir);
- let parent = path
- .parent()
- .ok_or_else(|| "invalid orchestration pairing store path".to_string())?;
- tokio::fs::create_dir_all(parent)
- .await
- .map_err(|e| format!("create orchestration pairing store dir: {e}"))?;
- let tmp = path.with_extension("json.tmp");
- let bytes = serde_json::to_vec_pretty(store)
- .map_err(|e| format!("serialize orchestration pairing store: {e}"))?;
- tokio::fs::write(&tmp, bytes)
- .await
- .map_err(|e| format!("write orchestration pairing store: {e}"))?;
- #[cfg(windows)]
- {
- match tokio::fs::remove_file(&path).await {
- Ok(()) => {}
- Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
- Err(err) => {
- return Err(format!(
- "remove existing orchestration pairing store: {err}"
- ))
- }
- }
- }
- tokio::fs::rename(&tmp, &path)
- .await
- .map_err(|e| format!("replace orchestration pairing store: {e}"))
-}
-
-fn store_path(workspace_dir: &Path) -> PathBuf {
- workspace_dir
- .join("agent_orchestration")
- .join("pairings.json")
-}
-
-fn normalize_agent_id(agent_id: &str) -> Result<String, String> {
- let trimmed = agent_id.trim();
- if trimmed.is_empty() {
- Err("agentId is required".to_string())
- } else {
- Ok(trimmed.to_string())
- }
-}
-
-fn contact_path(agent_id: &str, suffix: Option<&str>) -> String {
- match suffix {
- Some(suffix) => format!("/contacts/{}/{}", encode_path_segment(agent_id), suffix),
- None => format!("/contacts/{}", encode_path_segment(agent_id)),
- }
-}
-
-fn encode_path_segment(raw: &str) -> String {
- let mut out = String::with_capacity(raw.len());
- for byte in raw.bytes() {
- if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
- out.push(byte as char);
- } else {
- write!(&mut out, "%{byte:02X}").expect("writing to String cannot fail");
- }
- }
- out
-}
-
-fn publish_pairing_changed(record: &PairingRecord) {
- BUS.publish(DomainEvent::OrchestrationPairingChanged {
- agent_id: record.agent_id.clone(),
- status: serde_json::to_value(&record.status)
- .ok()
- .and_then(|value| value.as_str().map(str::to_string))
- .unwrap_or_else(|| "unknown".to_string()),
- source: record.source.as_str().to_string(),
- });
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn contact_paths_encode_agent_ids() {
- assert_eq!(
- contact_path("agent/with space", Some("status")),
- "/contacts/agent%2Fwith%20space/status"
- );
- }
-
- #[tokio::test]
- async fn pairing_store_upserts_and_removes_records() {
- let tmp = tempfile::tempdir().unwrap();
- let record = persist_record(
- tmp.path(),
- "@worker".to_string(),
- Some("Worker".to_string()),
- PairingStatus::Pending,
- PairingSource::UserLink,
- )
- .await
- .unwrap();
- assert_eq!(record.agent_id, "@worker");
-
- let record = persist_record(
- tmp.path(),
- "@worker".to_string(),
- None,
- PairingStatus::Linked,
- PairingSource::ApprovedRequest,
- )
- .await
- .unwrap();
- assert_eq!(record.status, PairingStatus::Linked);
-
- let store = load_store(tmp.path()).await.unwrap();
- assert_eq!(store.records.len(), 1);
- assert_eq!(store.records[0].source, PairingSource::ApprovedRequest);
-
- remove_record(tmp.path(), "@worker").await.unwrap();
- let store = load_store(tmp.path()).await.unwrap();
- assert!(store.records.is_empty());
- }
-
- #[tokio::test]
- async fn pairing_store_rewrites_existing_file() {
- let tmp = tempfile::tempdir().unwrap();
- persist_record(
- tmp.path(),
- "@worker".to_string(),
- Some("Worker".to_string()),
- PairingStatus::Pending,
- PairingSource::UserLink,
- )
- .await
- .unwrap();
-
- persist_record(
- tmp.path(),
- "@worker".to_string(),
- None,
- PairingStatus::Linked,
- PairingSource::ApprovedRequest,
- )
- .await
- .unwrap();
-
- let store = load_store(tmp.path()).await.unwrap();
- assert_eq!(store.records.len(), 1);
- assert_eq!(store.records[0].status, PairingStatus::Linked);
- assert_eq!(store.records[0].source, PairingSource::ApprovedRequest);
- }
-
- // ── Auto-accept gate (O2) ────────────────────────────────────────────────
-
- // A real base58 pairing-store address and the base64 Ed25519 key of the SAME
- // 32-byte identity (as seen on the wire), reused from the ingest matcher test.
- const LINKED_BASE58: &str = "7jr5FKYETssD6T1MCzsR4aT4dnjjyJCE2SANYYX1R5vm";
- const LINKED_BASE64: &str = "ZCAAuA+2GVoRrT08Gt8JUVnxnISTelSxnDuyScze334=";
- const UNLINKED_BASE58: &str = "De6RHrMj6eDqX1WBTXk11sks4WXHMaqEX9A6oQ3ZEmsg";
-
- #[test]
- fn auto_accept_gate_accepts_linked_but_leaves_others_pending() {
- let linked: HashSet<String> = [LINKED_BASE58.to_string()].into_iter().collect();
-
- // (1) A linked requester is selected for auto-accept.
- assert_eq!(
- requesters_to_auto_accept(&[LINKED_BASE58.to_string()], &linked),
- vec![LINKED_BASE58.to_string()]
- );
-
- // (2) A non-linked requester is left pending (never selected).
- assert!(
- requesters_to_auto_accept(&[UNLINKED_BASE58.to_string()], &linked).is_empty(),
- "an unlinked requester must be left pending for the human"
- );
-
- // Mixed batch: only the linked id is accepted, order preserved.
- assert_eq!(
- requesters_to_auto_accept(
- &[
- UNLINKED_BASE58.to_string(),
- LINKED_BASE58.to_string(),
- UNLINKED_BASE58.to_string(),
- ],
- &linked,
- ),
- vec![LINKED_BASE58.to_string()]
- );
- }
-
- #[test]
- fn auto_accept_gate_unifies_and_canonicalizes_base58_and_base64() {
- // The pairing store keeps the base58 address; a contact request may carry
- // the base64 Ed25519 key. Both are the same identity, so the linked
- // agent's request must still be accepted (the shared matcher unifies the
- // two encodings) — otherwise the e2e intro gate stays shut. Crucially the
- // gate returns the CANONICAL base58 stored id, not the raw base64 wire id,
- // so accepting under it reuses the existing record instead of persisting a
- // duplicate `Linked` row for the same identity.
- let linked: HashSet<String> = [LINKED_BASE58.to_string()].into_iter().collect();
- assert_eq!(
- requesters_to_auto_accept(&[LINKED_BASE64.to_string()], &linked),
- vec![LINKED_BASE58.to_string()],
- "must canonicalize the base64 wire id to the stored base58 id"
- );
- }
-
- #[test]
- fn auto_accept_gate_accepts_nothing_with_empty_linked_set() {
- // linked_agent_ids() fails closed to an empty set on any store read error;
- // with no linked agents the gate must accept nothing (every request stays
- // pending) rather than opening the contact gate wide.
- let empty = HashSet::new();
- assert!(
- requesters_to_auto_accept(&[LINKED_BASE58.to_string()], &empty).is_empty(),
- "an empty (fail-closed) linked set must auto-accept nothing"
- );
- }
-
- #[tokio::test]
- async fn auto_accept_fails_closed_on_unreadable_pairing_store() {
- // The read-error path end-to-end (minus network): a corrupt pairing store
- // makes linked_agent_ids() fail closed to an empty set, so the gate cannot
- // auto-accept even a would-be-linked requester.
- let tmp = tempfile::tempdir().unwrap();
- let path = store_path(tmp.path());
- tokio::fs::create_dir_all(path.parent().unwrap())
- .await
- .unwrap();
- tokio::fs::write(&path, b"{ this is not valid json")
- .await
- .unwrap();
-
- let linked = linked_agent_ids(tmp.path()).await;
- assert!(
- linked.is_empty(),
- "a corrupt pairing store must fail closed to an empty linked set"
- );
- assert!(
- requesters_to_auto_accept(&[LINKED_BASE58.to_string()], &linked).is_empty(),
- "no auto-accept when the linked set is fail-closed empty"
- );
- }
-
- #[test]
- fn incoming_pending_requesters_filters_and_resolves_requester() {
- // Pending incoming only; `agentId` preferred, else `contact.requester`;
- // accepted requests and outgoing requests are ignored.
- let requests = serde_json::json!({
- "incoming": [
- { "agentId": "AAA", "status": "pending", "direction": "incoming",
- "contact": { "requester": "AAA", "addressee": "me", "status": "pending" } },
- // agentId blank → fall back to contact.requester.
- { "agentId": "", "status": "pending", "direction": "incoming",
- "contact": { "requester": "BBB", "addressee": "me", "status": "pending" } },
- // already accepted → skipped.
- { "agentId": "CCC", "status": "accepted", "direction": "incoming",
- "contact": { "requester": "CCC", "addressee": "me", "status": "accepted" } },
- ],
- "outgoing": [
- // outgoing is never a request to accept.
- { "agentId": "DDD", "status": "pending", "direction": "outgoing",
- "contact": { "requester": "me", "addressee": "DDD", "status": "pending" } },
- ],
- });
- assert_eq!(
- incoming_pending_requesters(&requests),
- vec!["AAA".to_string(), "BBB".to_string()]
- );
-
- // Missing/empty `incoming` → nothing, no panic.
- assert!(incoming_pending_requesters(&serde_json::json!({})).is_empty());
- assert!(incoming_pending_requesters(&serde_json::json!({ "incoming": [] })).is_empty());
- }
-
- #[tokio::test]
- async fn pairing_store_serializes_concurrent_mutations() {
- let tmp = tempfile::tempdir().unwrap();
- let mut tasks = Vec::new();
-
- for index in 0..20 {
- let workspace_dir = tmp.path().to_path_buf();
- tasks.push(tokio::spawn(async move {
- persist_record(
- &workspace_dir,
- format!("@worker-{index}"),
- Some(format!("Worker {index}")),
- PairingStatus::Linked,
- PairingSource::ApprovedRequest,
- )
- .await
- }));
- }
-
- for task in tasks {
- task.await.unwrap().unwrap();
- }
-
- let store = load_store(tmp.path()).await.unwrap();
- assert_eq!(store.records.len(), 20);
- for index in 0..20 {
- assert!(store
- .records
- .iter()
- .any(|record| record.agent_id == format!("@worker-{index}")));
- }
- }
-
- fn local_file(entries: &[(&str, &str, Option<&str>)]) -> LocalAgentsFile {
- LocalAgentsFile {
- agents: entries
- .iter()
- .map(|(agent_id, owner, ts)| LocalAgentEntry {
- agent_id: agent_id.to_string(),
- owner: owner.to_string(),
- ts: ts.map(str::to_string),
- })
- .collect(),
- }
- }
-
- #[test]
- fn coload_trusts_fresh_entry_that_names_us_as_owner() {
- let now = DateTime::parse_from_rfc3339("2026-07-10T12:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- // A CLI (LINKED_BASE58) that named us (UNLINKED_BASE58) as owner, 1 min ago.
- let file = local_file(&[(LINKED_BASE58, UNLINKED_BASE58, Some("2026-07-10T11:59:00Z"))]);
- let trusted = coload_trusted_ids(&file, UNLINKED_BASE58, now);
- assert_eq!(
- trusted,
- [LINKED_BASE58.to_string()].into_iter().collect(),
- "a fresh entry naming us as owner is trusted"
- );
- }
-
- #[test]
- fn coload_owner_match_is_encoding_agnostic() {
- // The entry declares the owner in base64 while our own id is base58 — the
- // same identity. `resolve_linked_id` must unify them so the owner-match holds.
- let now = DateTime::parse_from_rfc3339("2026-07-10T12:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let file = local_file(&[(UNLINKED_BASE58, LINKED_BASE64, Some("2026-07-10T11:59:30Z"))]);
- let trusted = coload_trusted_ids(&file, LINKED_BASE58, now);
- assert_eq!(
- trusted,
- [UNLINKED_BASE58.to_string()].into_iter().collect(),
- "owner declared base64 must match our base58 own id"
- );
- }
-
- #[test]
- fn coload_rejects_entry_for_a_different_owner() {
- let now = DateTime::parse_from_rfc3339("2026-07-10T12:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- // Entry names LINKED_BASE58 as owner, but WE are UNLINKED_BASE58 → not ours.
- let file = local_file(&[(
- "SomeLocalCliAgentIdXXXXXXXXXXXXXXXXXXXXXXXXX",
- LINKED_BASE58,
- Some("2026-07-10T11:59:00Z"),
- )]);
- assert!(
- coload_trusted_ids(&file, UNLINKED_BASE58, now).is_empty(),
- "a CLI declaring a DIFFERENT local OpenHuman as owner is never trusted"
- );
- }
-
- #[test]
- fn coload_rejects_stale_or_undated_entries() {
- let now = DateTime::parse_from_rfc3339("2026-07-10T12:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- // Expired (2h old, TTL is 1h).
- let stale = local_file(&[(LINKED_BASE58, UNLINKED_BASE58, Some("2026-07-10T10:00:00Z"))]);
- assert!(
- coload_trusted_ids(&stale, UNLINKED_BASE58, now).is_empty(),
- "an entry past its TTL is not trusted"
- );
- // Missing timestamp → fail-closed.
- let undated = local_file(&[(LINKED_BASE58, UNLINKED_BASE58, None)]);
- assert!(
- coload_trusted_ids(&undated, UNLINKED_BASE58, now).is_empty(),
- "an entry with no timestamp is not trusted"
- );
- }
-
- #[test]
- fn entry_freshness_bounds() {
- let now = DateTime::parse_from_rfc3339("2026-07-10T12:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- assert!(entry_is_fresh(Some("2026-07-10T11:59:59Z"), now)); // just now
- assert!(entry_is_fresh(Some("2026-07-10T11:01:00Z"), now)); // 59 min → within TTL
- assert!(!entry_is_fresh(Some("2026-07-10T10:59:00Z"), now)); // 61 min → expired
- assert!(!entry_is_fresh(Some("2026-07-10T12:10:00Z"), now)); // 10 min future → skew reject
- assert!(!entry_is_fresh(Some("not-a-timestamp"), now)); // malformed
- assert!(!entry_is_fresh(None, now)); // absent
- }
-
- // ── Handshake-file trust gate (#4777 review — permission hardening) ───────
-
- /// A well-formed one-entry handshake JSON body naming us as owner.
- fn handshake_body() -> String {
- serde_json::json!({
- "agents": [{
- "agentId": LINKED_BASE58,
- "owner": UNLINKED_BASE58,
- "ts": "2026-07-10T11:59:00Z",
- }]
- })
- .to_string()
- }
-
- #[test]
- fn load_local_agents_from_missing_is_empty() {
- let tmp = tempfile::tempdir().unwrap();
- let path = tmp.path().join("does-not-exist.json");
- assert!(
- load_local_agents_from(&path).agents.is_empty(),
- "a missing handshake file yields an empty (fail-closed) set"
- );
- }
-
- #[cfg(unix)]
- #[test]
- fn load_local_agents_from_trusts_privately_owned_file() {
- use std::os::unix::fs::PermissionsExt as _;
- let tmp = tempfile::tempdir().unwrap();
- std::fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
- let path = tmp.path().join("local-agents.json");
- std::fs::write(&path, handshake_body()).unwrap();
- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
- let file = load_local_agents_from(&path);
- assert_eq!(
- file.agents.len(),
- 1,
- "a privately-owned handshake file is read"
- );
- assert_eq!(file.agents[0].agent_id, LINKED_BASE58);
- }
-
- #[cfg(unix)]
- #[test]
- fn load_local_agents_from_rejects_world_writable_file() {
- use std::os::unix::fs::PermissionsExt as _;
- let tmp = tempfile::tempdir().unwrap();
- std::fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
- let path = tmp.path().join("local-agents.json");
- std::fs::write(&path, handshake_body()).unwrap();
- // A group/world-writable file could have been forged by another local
- // user → fail closed and trust nothing.
- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap();
- assert!(
- load_local_agents_from(&path).agents.is_empty(),
- "a world-writable handshake file is refused"
- );
- }
-
- #[cfg(unix)]
- #[test]
- fn load_local_agents_from_rejects_world_writable_dir() {
- use std::os::unix::fs::PermissionsExt as _;
- let tmp = tempfile::tempdir().unwrap();
- let path = tmp.path().join("local-agents.json");
- std::fs::write(&path, handshake_body()).unwrap();
- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
- // A world-writable parent dir lets another user swap the file (or plant a
- // symlink) → the file's own perms are not enough, so trust nothing.
- std::fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o777)).unwrap();
- let trusted_empty = load_local_agents_from(&path).agents.is_empty();
- // Restore private perms before the tempdir is cleaned up.
- std::fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o700)).ok();
- assert!(
- trusted_empty,
- "a world-writable parent dir makes the handshake untrusted"
- );
- }
-}
diff --git a/src/openhuman/agent/orchestration/pairing_schemas.rs b/src/openhuman/agent/orchestration/pairing_schemas.rs
deleted file mode 100644
index c7805e9cad..0000000000
--- a/src/openhuman/agent/orchestration/pairing_schemas.rs
+++ /dev/null
@@ -1,204 +0,0 @@
-//! Controller schemas for user-consented tiny.place session pairing.
-
-use serde_json::{Map, Value};
-
-use crate::core::all::{ControllerFuture, RegisteredController};
-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-use crate::openhuman::config::rpc as config_rpc;
-
-pub fn all_controller_schemas() -> Vec<ControllerSchema> {
- vec![
- schema_for("orchestration_pairing_list"),
- schema_for("orchestration_pairing_link_session"),
- schema_for("orchestration_pairing_accept_request"),
- schema_for("orchestration_pairing_decline_request"),
- schema_for("orchestration_pairing_block_request"),
- ]
-}
-
-pub fn all_registered_controllers() -> Vec<RegisteredController> {
- vec![
- RegisteredController {
- schema: schema_for("orchestration_pairing_list"),
- handler: handle_list,
- },
- RegisteredController {
- schema: schema_for("orchestration_pairing_link_session"),
- handler: handle_link_session,
- },
- RegisteredController {
- schema: schema_for("orchestration_pairing_accept_request"),
- handler: handle_accept_request,
- },
- RegisteredController {
- schema: schema_for("orchestration_pairing_decline_request"),
- handler: handle_decline_request,
- },
- RegisteredController {
- schema: schema_for("orchestration_pairing_block_request"),
- handler: handle_block_request,
- },
- ]
-}
-
-fn schema_for(function: &str) -> ControllerSchema {
- match function {
- "orchestration_pairing_list" => ControllerSchema {
- namespace: "orchestration_pairing",
- function: "list",
- description: "List local orchestration pairing records plus the signed tiny.place contact state.",
- inputs: vec![],
- outputs: vec![json_output("result", "PairingSnapshot.")],
- },
- "orchestration_pairing_link_session" => ControllerSchema {
- namespace: "orchestration_pairing",
- function: "link_session",
- description: "User-consented link request for a wrapped session identity. Refuses blocked peers and sends no free-text contact payload.",
- inputs: vec![
- required_str("agentId", "Session agent identity to link."),
- optional_str("label", "Optional local display label for the session identity."),
- ],
- outputs: vec![json_output("result", "PairingActionResult.")],
- },
- "orchestration_pairing_accept_request" => ControllerSchema {
- namespace: "orchestration_pairing",
- function: "accept_request",
- description: "Accept an incoming contact request and persist a local approved-request pairing record.",
- inputs: vec![required_str("agentId", "Requesting session agent identity.")],
- outputs: vec![json_output("result", "PairingActionResult.")],
- },
- "orchestration_pairing_decline_request" => ControllerSchema {
- namespace: "orchestration_pairing",
- function: "decline_request",
- description: "Decline an incoming contact request and remove any local pairing record.",
- inputs: vec![required_str("agentId", "Requesting session agent identity.")],
- outputs: vec![json_output("result", "PairingActionResult.")],
- },
- "orchestration_pairing_block_request" => ControllerSchema {
- namespace: "orchestration_pairing",
- function: "block_request",
- description: "Block an incoming contact request and persist a local blocked record so it is not re-requested automatically.",
- inputs: vec![required_str("agentId", "Requesting session agent identity.")],
- outputs: vec![json_output("result", "PairingActionResult.")],
- },
- other => unreachable!("unknown orchestration_pairing schema: {other}"),
- }
-}
-
-fn handle_list(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("list").await?;
- to_json(super::pairing::list(&config).await?)
- })
-}
-
-fn handle_link_session(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("link_session").await?;
- let agent_id = required_param(&params, "agentId")?;
- let label = params
- .get("label")
- .and_then(Value::as_str)
- .map(str::to_string);
- to_json(super::pairing::link_session(&config, agent_id, label).await?)
- })
-}
-
-fn handle_accept_request(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("accept_request").await?;
- let agent_id = required_param(&params, "agentId")?;
- to_json(super::pairing::accept_request(&config, agent_id).await?)
- })
-}
-
-fn handle_decline_request(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("decline_request").await?;
- let agent_id = required_param(&params, "agentId")?;
- to_json(super::pairing::decline_request(&config, agent_id).await?)
- })
-}
-
-fn handle_block_request(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("block_request").await?;
- let agent_id = required_param(&params, "agentId")?;
- to_json(super::pairing::block_request(&config, agent_id).await?)
- })
-}
-
-async fn load_config(action: &str) -> Result<crate::openhuman::config::Config, String> {
- log::debug!(target: "orchestration_pairing_rpc", "[orchestration_pairing_rpc] {action}.config_load");
- config_rpc::load_config_with_timeout()
- .await
- .inspect_err(|err| {
- log::warn!(target: "orchestration_pairing_rpc", "[orchestration_pairing_rpc] {action}.config_failed err={err}");
- })
-}
-
-fn required_param<'a>(params: &'a Map<String, Value>, key: &str) -> Result<&'a str, String> {
- params
- .get(key)
- .and_then(Value::as_str)
- .filter(|value| !value.trim().is_empty())
- .ok_or_else(|| format!("{key} is required"))
-}
-
-fn required_str(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::String,
- comment,
- required: true,
- }
-}
-
-fn optional_str(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment,
- required: false,
- }
-}
-
-fn json_output(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Json,
- comment,
- required: true,
- }
-}
-
-fn to_json<T: serde::Serialize>(value: T) -> Result<Value, String> {
- serde_json::to_value(value)
- .map_err(|err| format!("serialize orchestration pairing response: {err}"))
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn schemas_use_orchestration_pairing_namespace() {
- let schemas = all_controller_schemas();
- assert_eq!(schemas.len(), 5);
- assert!(schemas
- .iter()
- .all(|schema| schema.namespace == "orchestration_pairing"));
- assert_eq!(
- schema_for("orchestration_pairing_link_session").function,
- "link_session"
- );
- }
-
- #[test]
- fn required_param_rejects_blank_agent_id() {
- let mut params = Map::new();
- params.insert("agentId".to_string(), Value::String(" ".to_string()));
- let err = required_param(&params, "agentId").unwrap_err();
- assert!(err.contains("agentId"));
- }
-}
diff --git a/src/openhuman/agent/orchestration/run_ledger_finalize.rs b/src/openhuman/agent/orchestration/run_ledger_finalize.rs
index 2a85be89cc..304a1c75b5 100644
--- a/src/openhuman/agent/orchestration/run_ledger_finalize.rs
+++ b/src/openhuman/agent/orchestration/run_ledger_finalize.rs
@@ -18,7 +18,7 @@
//! `spawn_async_subagent` runs: they outlive the parent turn, so when they
//! finish the progress sink is already dropped and `let _ = tx.send(...)` fails
//! silently. The ledger row stays `running` forever, and every thread reopen
-//! re-renders it as a perpetual "Tinyplace Agent" timeline row.
+//! re-renders it as a perpetual agent timeline row.
//!
//! This subscriber closes that gap by settling the ledger from the **global
//! bus**, which always fires from the detached task regardless of the parent
diff --git a/src/openhuman/agent/registry/agents/tools_agent/agent.toml b/src/openhuman/agent/registry/agents/tools_agent/agent.toml
index 312810bd9b..87e31cb4d3 100644
--- a/src/openhuman/agent/registry/agents/tools_agent/agent.toml
+++ b/src/openhuman/agent/registry/agents/tools_agent/agent.toml
@@ -18,7 +18,7 @@ hint = "burst"
# surface. Composio meta-tools and dynamic `<TOOLKIT>_*` action tools are
# stripped at runtime (see `filter_non_composio_indices` in the subagent
# runner), so the LLM never sees integration-specific tools here; those belong
-# to `integrations_agent`. Specialist-owned trading/tiny.place tools are also
+# to `integrations_agent`. Specialist-owned trading tools are also
# stripped via `disallowed_tools` above so they route through their dedicated
# agents exclusively.
wildcard = {}
diff --git a/src/openhuman/agent/tinyagents/host/definition_registry.rs b/src/openhuman/agent/tinyagents/host/definition_registry.rs
index baa3dffb46..1ee164b4a1 100644
--- a/src/openhuman/agent/tinyagents/host/definition_registry.rs
+++ b/src/openhuman/agent/tinyagents/host/definition_registry.rs
@@ -365,7 +365,7 @@ impl OpenHumanDefinitionRegistry {
}
// Fail closed. Emitting the wildcard here would silently
// re-grant every denied tool — for shipped definitions that
- // means specialist-only routes like `tinyplace_*` becoming
+ // means specialist-only routes becoming
// generally available. An agent with no tools is a visible,
// debuggable failure; a silently widened one is not.
None => {
@@ -792,7 +792,7 @@ mod tests {
///
/// Written against a synthetic definition rather than a shipped one on
/// purpose: the shipped denylists are product data and come and go (the
- /// last one, `tools_agent`'s `tinyplace_*`, left with that tool family),
+ /// last specialist-only family left),
/// while the projection rule this pins is permanent.
#[test]
fn a_wildcard_denylist_is_materialized_against_the_registered_tools() {
diff --git a/src/openhuman/agent/tinyagents/host/tool_outcome_classifier.rs b/src/openhuman/agent/tinyagents/host/tool_outcome_classifier.rs
index 8eeeff8cd4..3d27362610 100644
--- a/src/openhuman/agent/tinyagents/host/tool_outcome_classifier.rs
+++ b/src/openhuman/agent/tinyagents/host/tool_outcome_classifier.rs
@@ -59,7 +59,7 @@
//! side-effect free — declared through
//! [`OpenHumanToolOutcomeClassifier::with_retry_safe_tools`] as an
//! **allowlist**. An allowlist rather than the inverse, because
-//! `Tool::external_effect()` is arg-less: `ShellTool` and the TinyPlace raw
+//! `Tool::external_effect()` is arg-less: `ShellTool` and other raw
//! tool classify their effect from *arguments* (`external_effect_with_args`)
//! and leave the arg-less variant at the default `false`, so a denylist built
//! from it would admit precisely the tools that must be excluded. Absent the
@@ -120,7 +120,7 @@ impl OpenHumanToolOutcomeClassifier {
/// List a tool here only when calling it twice is *definitionally*
/// harmless — a pure read. Do **not** build this by inverting
/// `Tool::external_effect()`: that signal is arg-less, and a tool whose
- /// effect depends on its arguments (`ShellTool`, the TinyPlace raw tool)
+ /// effect depends on its arguments (`ShellTool`, raw tools)
/// overrides `external_effect_with_args` while leaving the arg-less
/// variant at the default `false`. Inverting it would silently admit
/// exactly the tools that most need excluding.
diff --git a/src/openhuman/agent/turn_origin.rs b/src/openhuman/agent/turn_origin.rs
index 7b4edc2c4b..0dedda4065 100644
--- a/src/openhuman/agent/turn_origin.rs
+++ b/src/openhuman/agent/turn_origin.rs
@@ -500,7 +500,7 @@ mod tests {
assert!(observed.is_none());
}
- /// The `hosted::orchestration::effect_executor::run_local_agent` spawn site
+ /// A hosted effect-executor spawn site
/// (#5508 / #5499): the device-tool bridge fires the local sub-agent from a
/// bare `tokio::spawn` where there is **no ambient turn** to inherit — unlike
/// the four sites PR #5465 fixed with `capture`/`propagate`, `capture()` here
diff --git a/src/openhuman/config/mod.rs b/src/openhuman/config/mod.rs
index 43ab27908d..d32e0e0da0 100644
--- a/src/openhuman/config/mod.rs
+++ b/src/openhuman/config/mod.rs
@@ -44,21 +44,20 @@ pub use schema::{
HeartbeatConfig, HttpHeader, HttpRequestConfig, IMessageConfig, IntegrationToggle,
IntegrationsConfig, LarkConfig, LearningConfig, LinqConfig, LlmBackend, LocalAiConfig,
MatrixConfig, McpAuthConfig, McpClientConfig, McpClientIdentityConfig, McpServerConfig,
- MedullaClientConfig, MedullaCycleConfig, MedullaCycleLimits, MedullaPromptOverrides,
- MedullaVerification, MemoryConfig, MemoryTreeConfig, ModelRouteConfig, MultimodalConfig,
- MultimodalFileConfig, ObservabilityConfig, OrchestratorModelConfig, PrivacyConfig, PrivacyMode,
- ProxyConfig, ProxyScope, ReflectionSource, ReliabilityConfig, ResourceLimitsConfig,
- RuntimeConfig, RuntimePoolConfig, RuntimePoolLangConfig, SandboxBackend, SandboxConfig,
- SchedulerConfig, SchedulerGateConfig, SchedulerGateMode, SearchConfig, SearchEngine,
- SearchEngineCredentials, SearxngConfig, SecretsConfig, SecurityConfig, ShellConfig,
- SlackConfig, StorageConfig, StorageProviderConfig, StorageProviderSection, StreamMode,
- SttEngine, TeamModelConfig, TelegramConfig, TokenjuiceConfig, UpdateConfig,
- UpdateRestartStrategy, VoiceActivationMode, VoiceServerConfig, WebSearchConfig, WebhookConfig,
- YuanbaoConfig, DEFAULT_CLOUD_LLM_MODEL, DEFAULT_MEMORY_SYNC_INTERVAL_SECS, DEFAULT_MODEL,
- MEMORY_SYNC_INTERVAL_PRESETS_SECS, MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1,
- MODEL_CODING_V1, MODEL_REASONING_QUICK_V1, MODEL_REASONING_V1, MODEL_SUMMARIZATION_V1,
- MODEL_VISION_V1, SEARCH_ENGINE_BRAVE, SEARCH_ENGINE_DISABLED, SEARCH_ENGINE_EXA,
- SEARCH_ENGINE_MANAGED, SEARCH_ENGINE_PARALLEL, SEARCH_ENGINE_QUERIT,
+ MemoryConfig, MemoryTreeConfig, ModelRouteConfig, MultimodalConfig, MultimodalFileConfig,
+ ObservabilityConfig, OrchestratorModelConfig, PrivacyConfig, PrivacyMode, ProxyConfig,
+ ProxyScope, ReflectionSource, ReliabilityConfig, ResourceLimitsConfig, RuntimeConfig,
+ RuntimePoolConfig, RuntimePoolLangConfig, SandboxBackend, SandboxConfig, SchedulerConfig,
+ SchedulerGateConfig, SchedulerGateMode, SearchConfig, SearchEngine, SearchEngineCredentials,
+ SearxngConfig, SecretsConfig, SecurityConfig, ShellConfig, SlackConfig, StorageConfig,
+ StorageProviderConfig, StorageProviderSection, StreamMode, SttEngine, TeamModelConfig,
+ TelegramConfig, TokenjuiceConfig, UpdateConfig, UpdateRestartStrategy, VoiceActivationMode,
+ VoiceServerConfig, WebSearchConfig, WebhookConfig, YuanbaoConfig, DEFAULT_CLOUD_LLM_MODEL,
+ DEFAULT_MEMORY_SYNC_INTERVAL_SECS, DEFAULT_MODEL, MEMORY_SYNC_INTERVAL_PRESETS_SECS,
+ MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1, MODEL_CODING_V1, MODEL_REASONING_QUICK_V1,
+ MODEL_REASONING_V1, MODEL_SUMMARIZATION_V1, MODEL_VISION_V1, SEARCH_ENGINE_BRAVE,
+ SEARCH_ENGINE_DISABLED, SEARCH_ENGINE_EXA, SEARCH_ENGINE_MANAGED, SEARCH_ENGINE_PARALLEL,
+ SEARCH_ENGINE_QUERIT,
};
// Kept as a separate re-export (issue #4117) so the large alphabetized group
// above stays byte-identical and rustfmt-stable.
diff --git a/src/openhuman/config/schema/mod.rs b/src/openhuman/config/schema/mod.rs
index 061ba57174..b15220ac7f 100644
--- a/src/openhuman/config/schema/mod.rs
+++ b/src/openhuman/config/schema/mod.rs
@@ -51,7 +51,6 @@ mod local_ai;
mod modules;
mod node;
mod observability;
-mod orchestration;
mod privacy;
mod proxy;
mod routes;
@@ -89,10 +88,6 @@ pub use local_ai::{LocalAiConfig, LocalAiUsage};
pub use modules::{ModuleOverride, ModulesConfig};
pub use node::NodeConfig;
pub use observability::{AgentTracingBackend, AgentTracingConfig, ObservabilityConfig};
-pub use orchestration::{
- MedullaClientConfig, MedullaCycleConfig, MedullaCycleLimits, MedullaPromptOverrides,
- MedullaVerification, OrchestrationConfig,
-};
pub use privacy::{PrivacyConfig, PrivacyMode};
pub use proxy::{
apply_runtime_proxy_to_builder, build_runtime_proxy_client,
diff --git a/src/openhuman/config/schema/orchestration.rs b/src/openhuman/config/schema/orchestration.rs
deleted file mode 100644
index 000b9c58f7..0000000000
--- a/src/openhuman/config/schema/orchestration.rs
+++ /dev/null
@@ -1,133 +0,0 @@
-//! Hosted orchestration configuration.
-
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-
-fn default_enabled() -> bool {
- true
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
-#[serde(default)]
-pub struct OrchestrationConfig {
- /// Master switch for hosted orchestration ingest, rendering, and direct
- /// Medulla runs. Default: `true`.
- #[serde(default = "default_enabled")]
- pub enabled: bool,
-
- /// Options forwarded to the paid `/orchestration/v1/run` surface.
- #[serde(default)]
- pub medulla: MedullaClientConfig,
-}
-
-impl Default for OrchestrationConfig {
- fn default() -> Self {
- Self {
- enabled: default_enabled(),
- medulla: MedullaClientConfig::default(),
- }
- }
-}
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
-#[serde(default)]
-pub struct MedullaClientConfig {
- /// Optional prompt replacements. Empty fields retain backend defaults.
- #[serde(default)]
- pub prompt_overrides: MedullaPromptOverrides,
-
- /// Optional graph tuning. The backend clamps every supplied value.
- #[serde(default)]
- pub config: MedullaCycleConfig,
-
- /// Optional per-cycle resource limits. The backend clamps every value.
- #[serde(default)]
- pub limits: MedullaCycleLimits,
-}
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
-#[serde(default)]
-pub struct MedullaPromptOverrides {
- pub orchestrate_system: Option<String>,
- pub reasoning_execute_system: Option<String>,
- pub orchestrate_rlm_system: Option<String>,
- pub compress_system: Option<String>,
- pub frontend_gate_system: Option<String>,
-}
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
-#[serde(default)]
-pub struct MedullaCycleConfig {
- pub max_passes: Option<u32>,
- pub max_steps: Option<u32>,
- pub max_depth: Option<u32>,
- pub context_window_tokens: Option<u64>,
- pub verification: Option<MedullaVerification>,
-}
-
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
-#[serde(rename_all = "snake_case")]
-pub enum MedullaVerification {
- Remind,
- Off,
-}
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
-#[serde(default)]
-pub struct MedullaCycleLimits {
- pub max_concurrency: Option<u32>,
- pub max_tokens: Option<u64>,
- pub deadline_ms: Option<u64>,
- pub max_tasks_per_delegate: Option<u32>,
- pub max_depth: Option<u32>,
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn defaults_keep_orchestration_enabled_without_overrides() {
- let config = OrchestrationConfig::default();
- assert!(config.enabled);
- assert!(config.medulla.config.max_passes.is_none());
- assert!(config.medulla.limits.deadline_ms.is_none());
- assert!(config.medulla.prompt_overrides.orchestrate_system.is_none());
- }
-
- #[test]
- fn medulla_nested_toml_deserializes() {
- let config: OrchestrationConfig = toml::from_str(
- r#"
-enabled = true
-
-[medulla.prompt_overrides]
-orchestrate_system = "Plan carefully"
-
-[medulla.config]
-max_passes = 3
-verification = "remind"
-
-[medulla.limits]
-max_concurrency = 8
-deadline_ms = 90000
-"#,
- )
- .unwrap();
-
- assert_eq!(config.medulla.config.max_passes, Some(3));
- assert!(matches!(
- config.medulla.config.verification,
- Some(MedullaVerification::Remind)
- ));
- assert_eq!(config.medulla.limits.max_concurrency, Some(8));
- assert_eq!(
- config
- .medulla
- .prompt_overrides
- .orchestrate_system
- .as_deref(),
- Some("Plan carefully")
- );
- }
-}
diff --git a/src/openhuman/config/schema/types.rs b/src/openhuman/config/schema/types.rs
index ba2b12859a..8d401281d2 100644
--- a/src/openhuman/config/schema/types.rs
+++ b/src/openhuman/config/schema/types.rs
@@ -190,11 +190,6 @@ pub struct Config {
#[serde(default)]
pub scheduler_gate: SchedulerGateConfig,
- /// tiny.place harness session-DM ingest layer. See
- /// [`crate::openhuman::hosted::orchestration`].
- #[serde(default)]
- pub orchestration: OrchestrationConfig,
-
/// User-facing activity-level knob (0–4) controlling how proactive
/// background AI work is. Maps into scheduler_gate mode, periodic sync
/// cadence, heartbeat/subconscious toggles. See issue #3117.
@@ -808,7 +803,6 @@ impl Default for Config {
reliability: ReliabilityConfig::default(),
scheduler: SchedulerConfig::default(),
scheduler_gate: SchedulerGateConfig::default(),
- orchestration: OrchestrationConfig::default(),
agent_activity_level: AgentActivityLevel::default(),
memory_sync_interval_secs: None,
agent: AgentConfig::default(),
diff --git a/src/openhuman/cron/scheduler_tests.rs b/src/openhuman/cron/scheduler_tests.rs
index 1b3a2e1f9c..67ed1fb091 100644
--- a/src/openhuman/cron/scheduler_tests.rs
+++ b/src/openhuman/cron/scheduler_tests.rs
@@ -1027,14 +1027,6 @@ async fn cron_agent_job_uses_agent_definition_tool_scope() {
!visible.is_empty(),
"morning briefing has a wildcard scope plus a disallowlist, so the builder must materialize an explicit visible-tool filter"
);
- assert!(
- !visible.contains("use_tinyplace"),
- "morning briefing cron jobs must use the morning_briefing definition scope, not the orchestrator delegate surface"
- );
- assert!(
- !visible.iter().any(|name| name.starts_with("tinyplace_")),
- "morning briefing cron jobs must preserve tinyplace_* disallowlist"
- );
}
#[tokio::test]
diff --git a/src/openhuman/hosted/mod.rs b/src/openhuman/hosted/mod.rs
index afc53be239..a9d89316b0 100644
--- a/src/openhuman/hosted/mod.rs
+++ b/src/openhuman/hosted/mod.rs
@@ -7,17 +7,11 @@
//!
//! - [`announcements`] — product announcements feed
//! - [`billing`] — credits, plans, Stripe/Coinbase-backed balance reads
-//! - [`orchestration`] — device-side client of the hosted orchestration brain
//! - [`referral`] — referral codes and rewards
//! - [`team`] — team membership/roles/invites (authorization is
//! enforced server-side; this is a proxy, not a local implementation)
-//!
-//! **`orchestration` here is the hosted client, not the local control plane.**
-//! The local one is `agent_orchestration` (moving to `agent/orchestration`).
-//! The names rhyme; the two are unrelated and must not be merged.
pub mod announcements;
pub mod billing;
-pub mod orchestration;
pub mod referral;
pub mod team;
diff --git a/src/openhuman/hosted/orchestration/attention.rs b/src/openhuman/hosted/orchestration/attention.rs
deleted file mode 100644
index 8338d1006c..0000000000
--- a/src/openhuman/hosted/orchestration/attention.rs
+++ /dev/null
@@ -1,834 +0,0 @@
-//! Attention queue: fold the cross-domain "needs you" signals for the
-//! orchestration hub into one flat, priority-ordered list.
-//!
-//! The TinyPlace Orchestration tab renders this as a single "Needs you" zone so
-//! a user running many agent instances sees, in one place, everything blocked on
-//! them: tool calls parked on the approval gate, agent runs awaiting input, and
-//! instances with unread inbound messages. This module owns only the pure
-//! aggregation + ordering — the handler in [`super::schemas`] gathers the raw
-//! signals from each source domain and hands them here.
-//!
-//! Keeping this out of `ops.rs` (already large) preserves the single-file
-//! single-responsibility rule and lets the whole assembly be unit-tested without
-//! a live approval gate, command center, or store.
-
-use serde::Serialize;
-
-/// The kind of attention signal, in descending urgency. Serialized kebab-case
-/// so the renderer can key an icon/tone off it.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
-#[serde(rename_all = "kebab-case")]
-pub(crate) enum AttentionKind {
- /// A tool call is parked on the approval gate awaiting the user's decision.
- Approval,
- /// An agent run is blocked awaiting user input (command-center NeedsInput).
- NeedsInput,
- /// An instance has unread inbound messages.
- Unread,
-}
-
-impl AttentionKind {
- /// Sort weight — lower is more urgent (rendered first). Approvals are
- /// TTL-bound (they auto-deny), so they lead; blocked runs next; unread last.
- fn priority(self) -> u8 {
- match self {
- AttentionKind::Approval => 0,
- AttentionKind::NeedsInput => 1,
- AttentionKind::Unread => 2,
- }
- }
-}
-
-/// What the renderer should do when the user acts on an item. Tagged so the
-/// frontend can `switch` on `type` and carry exactly the id it needs.
-///
-/// `rename_all` only renames the variant tag; `rename_all_fields` is required to
-/// carry the struct-variant fields to camelCase (`requestId`, `threadId`, …) so
-/// the wire matches the `AttentionAction` union the TS client declares — without
-/// it the ids serialize snake_case and the renderer router reads `undefined`.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-#[serde(
- tag = "type",
- rename_all = "kebab-case",
- rename_all_fields = "camelCase"
-)]
-pub(crate) enum AttentionAction {
- /// Open the approval decision surface for `requestId`.
- Approval { request_id: String },
- /// Open a conversation thread transcript.
- OpenThread { thread_id: String },
- /// Open an agent run (no thread linked yet).
- OpenRun { run_id: String },
- /// Open an orchestration chat window.
- OpenSession { session_id: String },
-}
-
-/// One actionable row in the attention queue.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub(crate) struct AttentionItem {
- /// Stable key for the renderer list (`<kind>:<source-id>`).
- pub id: String,
- pub kind: AttentionKind,
- /// The instance/source this concerns (request id / run id / session id).
- pub instance_id: String,
- /// Short label (tool name / agent display name / session label).
- pub title: String,
- /// One-line, PII-safe detail (approval/run summary). `None` for unread —
- /// the frontend localizes a count instead (`count`), so no English leaks
- /// into the wire.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub summary: Option<String>,
- /// Unread message count — set only for the `unread` kind so the renderer can
- /// localize "N unread" rather than the backend shipping English.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub count: Option<i64>,
- pub action: AttentionAction,
- /// RFC3339 creation/activity time when known — used for the newest-first
- /// tie-break within a kind.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub created_at: Option<String>,
-}
-
-/// Per-kind + total counts so the UI can badge the zone without re-counting.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub(crate) struct AttentionCounts {
- pub total: usize,
- pub approvals: usize,
- pub needs_input: usize,
- pub unread: usize,
-}
-
-/// The assembled attention queue returned by `orchestration_attention`.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub(crate) struct AttentionQueue {
- pub items: Vec<AttentionItem>,
- pub counts: AttentionCounts,
-}
-
-// ── Neutral input signals ───────────────────────────────────────────────────
-//
-// Decoupled from the source domains' own types (`PendingApproval`,
-// `AgentWorkRow`, `SessionSummary`) so the assembly is trivially testable and
-// this module never depends on those crates' internals.
-
-/// A tool call parked on the approval gate.
-pub(crate) struct ApprovalSignal {
- pub request_id: String,
- pub tool_name: String,
- pub action_summary: String,
- pub created_at: Option<String>,
-}
-
-/// An agent run in the command-center `NeedsInput` bucket.
-pub(crate) struct NeedsInputSignal {
- pub run_id: String,
- /// Display name, falling back to the run id at the call site.
- pub title: String,
- pub summary: Option<String>,
- /// Preferred deep-link target: a worker/parent thread, when the run has one.
- pub thread_id: Option<String>,
- pub updated_at: Option<String>,
-}
-
-/// An orchestration instance with unread inbound messages.
-pub(crate) struct UnreadSignal {
- pub session_id: String,
- pub label: Option<String>,
- pub unread: i64,
- pub last_message_at: Option<String>,
-}
-
-/// A REMOTE agent session parked on a tool-approval decision. Phase 1 persists
-/// `status.state = "waiting_approval"` on the session (plus the prompt in
-/// `current_detail` and the in-flight `active_call_id`) when a v2
-/// `approval_request` event arrives from a peer harness. Unlike [`ApprovalSignal`]
-/// — which is a call parked on THIS core's local approval gate — this is a
-/// remote instance blocked on the user; acting on it opens the orchestration
-/// chat window so the user can steer the reply.
-pub(crate) struct RemoteApprovalSignal {
- pub session_id: String,
- /// Human-friendly session label; falls back to the session id at the builder.
- pub label: Option<String>,
- /// The approval prompt / current-activity line (PII-safe summary text).
- pub detail: Option<String>,
- /// The in-flight tool call id awaiting the decision, when known. Carried for
- /// parity with the persisted run-state; not currently surfaced on the wire.
- pub active_call_id: Option<String>,
- pub created_at: Option<String>,
-}
-
-// ── Builders ────────────────────────────────────────────────────────────────
-
-fn approval_item(sig: ApprovalSignal) -> AttentionItem {
- AttentionItem {
- id: format!("approval:{}", sig.request_id),
- kind: AttentionKind::Approval,
- instance_id: sig.request_id.clone(),
- title: sig.tool_name,
- summary: Some(sig.action_summary),
- count: None,
- action: AttentionAction::Approval {
- request_id: sig.request_id,
- },
- created_at: sig.created_at,
- }
-}
-
-fn needs_input_item(sig: NeedsInputSignal) -> AttentionItem {
- // Deep-link to the thread when one exists, else to the run itself.
- let action = match sig.thread_id {
- Some(thread_id) => AttentionAction::OpenThread { thread_id },
- None => AttentionAction::OpenRun {
- run_id: sig.run_id.clone(),
- },
- };
- AttentionItem {
- id: format!("needs-input:{}", sig.run_id),
- kind: AttentionKind::NeedsInput,
- instance_id: sig.run_id,
- title: sig.title,
- summary: sig.summary,
- count: None,
- action,
- created_at: sig.updated_at,
- }
-}
-
-fn unread_item(sig: UnreadSignal) -> AttentionItem {
- let title = sig.label.unwrap_or_else(|| sig.session_id.clone());
- AttentionItem {
- id: format!("unread:{}", sig.session_id),
- kind: AttentionKind::Unread,
- title,
- summary: None,
- count: Some(sig.unread),
- action: AttentionAction::OpenSession {
- session_id: sig.session_id.clone(),
- },
- instance_id: sig.session_id,
- created_at: sig.last_message_at,
- }
-}
-
-fn remote_approval_item(sig: RemoteApprovalSignal) -> AttentionItem {
- let title = sig.label.unwrap_or_else(|| sig.session_id.clone());
- // Namespaced apart from local approvals (`approval:<request_id>`) so a session
- // id can never collide with a request id in the renderer's list keys, even
- // though both surface as the same `Approval` kind.
- AttentionItem {
- id: format!("remote-approval:{}", sig.session_id),
- kind: AttentionKind::Approval,
- title,
- summary: sig.detail,
- count: None,
- action: AttentionAction::OpenSession {
- session_id: sig.session_id.clone(),
- },
- instance_id: sig.session_id,
- created_at: sig.created_at,
- }
-}
-
-// ── Assembly ────────────────────────────────────────────────────────────────
-
-/// Fold the four signal sources into one ordered queue. Unread signals with a
-/// zero count are dropped (nothing to surface). Ordering is by kind urgency,
-/// then newest-first within a kind, then id for a stable total order.
-///
-/// `remote_approvals` are peer sessions parked on an approval decision (Phase 1's
-/// persisted `waiting_approval` run-state). They share the `Approval` kind with
-/// the local-gate `approvals`, so they lead the queue and are counted under
-/// `counts.approvals` — they ARE approvals, just remote ones.
-pub(crate) fn assemble_attention(
- approvals: Vec<ApprovalSignal>,
- needs_input: Vec<NeedsInputSignal>,
- unread: Vec<UnreadSignal>,
- remote_approvals: Vec<RemoteApprovalSignal>,
-) -> AttentionQueue {
- let mut items: Vec<AttentionItem> = Vec::new();
- items.extend(approvals.into_iter().map(approval_item));
- items.extend(remote_approvals.into_iter().map(remote_approval_item));
- items.extend(needs_input.into_iter().map(needs_input_item));
- items.extend(unread.into_iter().filter(|s| s.unread > 0).map(unread_item));
-
- items.sort_by(|a, b| {
- a.kind
- .priority()
- .cmp(&b.kind.priority())
- // Newest-first within a kind: reverse-compare the RFC3339 strings
- // (lexical order matches chronological order). A missing timestamp
- // sorts last.
- .then_with(|| b.created_at.cmp(&a.created_at))
- .then_with(|| a.id.cmp(&b.id))
- });
-
- let counts = AttentionCounts {
- approvals: items
- .iter()
- .filter(|i| i.kind == AttentionKind::Approval)
- .count(),
- needs_input: items
- .iter()
- .filter(|i| i.kind == AttentionKind::NeedsInput)
- .count(),
- unread: items
- .iter()
- .filter(|i| i.kind == AttentionKind::Unread)
- .count(),
- total: items.len(),
- };
-
- AttentionQueue { items, counts }
-}
-
-/// Map pending approvals into neutral signals, stamping the creation time as
-/// RFC3339 for the newest-first sort.
-pub(crate) fn approval_signals(
- pending: Vec<crate::openhuman::security::approval::types::PendingApproval>,
-) -> Vec<ApprovalSignal> {
- pending
- .into_iter()
- .map(|p| ApprovalSignal {
- request_id: p.request_id,
- tool_name: p.tool_name,
- action_summary: p.action_summary,
- created_at: Some(p.created_at.to_rfc3339()),
- })
- .collect()
-}
-
-/// Map a command-center view's `NeedsInput` bucket into neutral signals. Pure —
-/// the handler passes the already-fetched view. A run deep-links to its worker
-/// thread (then parent thread); its display name falls back to the run id.
-pub(crate) fn needs_input_from_command_center(
- view: crate::openhuman::agent::orchestration::command_center::CommandCenterView,
-) -> Vec<NeedsInputSignal> {
- use crate::openhuman::agent::orchestration::command_center::AgentWorkBucket;
- view.groups
- .into_iter()
- .find(|g| g.bucket == AgentWorkBucket::NeedsInput)
- .map(|group| {
- group
- .rows
- .into_iter()
- .map(|row| NeedsInputSignal {
- title: row.display_name.unwrap_or_else(|| row.run_id.clone()),
- thread_id: row.worker_thread_id.or(row.parent_thread_id),
- summary: row.summary,
- updated_at: Some(row.updated_at),
- run_id: row.run_id,
- })
- .collect()
- })
- .unwrap_or_default()
-}
-
-/// Map orchestration sessions into remote-approval signals — keeping only those
-/// whose persisted v2 run-state is `waiting_approval` (Phase 1 stamps this when a
-/// peer harness emits an `approval_request`). Pure: the handler passes the
-/// already-fetched session list. `detail` carries the PII-safe approval prompt
-/// (`current_detail`); the deep link opens the session window (`last_message_at`
-/// stamps the newest-first tie-break).
-pub(crate) fn remote_approval_signals(
- sessions: Vec<super::types::OrchestrationSession>,
-) -> Vec<RemoteApprovalSignal> {
- sessions
- .into_iter()
- .filter(|s| s.status_state.as_deref() == Some("waiting_approval"))
- .map(|s| RemoteApprovalSignal {
- session_id: s.session_id,
- label: s.label,
- detail: s.current_detail,
- active_call_id: s.active_call_id,
- created_at: Some(s.last_message_at),
- })
- .collect()
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn approval(id: &str, at: &str) -> ApprovalSignal {
- ApprovalSignal {
- request_id: id.into(),
- tool_name: "shell".into(),
- action_summary: "run a command".into(),
- created_at: Some(at.into()),
- }
- }
-
- #[test]
- fn empty_sources_yield_empty_queue_with_zero_counts() {
- let q = assemble_attention(vec![], vec![], vec![], vec![]);
- assert!(q.items.is_empty());
- assert_eq!(
- q.counts,
- AttentionCounts {
- total: 0,
- approvals: 0,
- needs_input: 0,
- unread: 0
- }
- );
- }
-
- #[test]
- fn kinds_order_approval_then_needs_input_then_unread() {
- let q = assemble_attention(
- vec![approval("r1", "2026-07-06T10:00:00Z")],
- vec![NeedsInputSignal {
- run_id: "run-1".into(),
- title: "researcher".into(),
- summary: Some("blocked on a question".into()),
- thread_id: Some("thread-9".into()),
- updated_at: Some("2026-07-06T11:00:00Z".into()),
- }],
- vec![UnreadSignal {
- session_id: "h-1".into(),
- label: Some("Claude · repo audit".into()),
- unread: 3,
- last_message_at: Some("2026-07-06T12:00:00Z".into()),
- }],
- vec![],
- );
- let kinds: Vec<AttentionKind> = q.items.iter().map(|i| i.kind).collect();
- assert_eq!(
- kinds,
- vec![
- AttentionKind::Approval,
- AttentionKind::NeedsInput,
- AttentionKind::Unread
- ]
- );
- assert_eq!(
- q.counts,
- AttentionCounts {
- total: 3,
- approvals: 1,
- needs_input: 1,
- unread: 1
- }
- );
- }
-
- #[test]
- fn newest_first_within_a_kind() {
- let q = assemble_attention(
- vec![
- approval("old", "2026-07-06T09:00:00Z"),
- approval("new", "2026-07-06T12:00:00Z"),
- approval("mid", "2026-07-06T10:30:00Z"),
- ],
- vec![],
- vec![],
- vec![],
- );
- let ids: Vec<&str> = q.items.iter().map(|i| i.instance_id.as_str()).collect();
- assert_eq!(ids, vec!["new", "mid", "old"]);
- }
-
- #[test]
- fn zero_unread_is_dropped() {
- let q = assemble_attention(
- vec![],
- vec![],
- vec![
- UnreadSignal {
- session_id: "quiet".into(),
- label: None,
- unread: 0,
- last_message_at: None,
- },
- UnreadSignal {
- session_id: "loud".into(),
- label: None,
- unread: 5,
- last_message_at: Some("2026-07-06T12:00:00Z".into()),
- },
- ],
- vec![],
- );
- assert_eq!(q.items.len(), 1);
- assert_eq!(q.items[0].instance_id, "loud");
- assert_eq!(q.items[0].count, Some(5));
- assert_eq!(q.items[0].summary, None);
- }
-
- #[test]
- fn item_shapes_carry_correct_ids_and_actions() {
- let q = assemble_attention(
- vec![approval("req-7", "2026-07-06T10:00:00Z")],
- vec![
- // Thread present → OpenThread.
- NeedsInputSignal {
- run_id: "run-a".into(),
- title: "agent-a".into(),
- summary: None,
- thread_id: Some("t-1".into()),
- updated_at: None,
- },
- // No thread → OpenRun fallback.
- NeedsInputSignal {
- run_id: "run-b".into(),
- title: "agent-b".into(),
- summary: None,
- thread_id: None,
- updated_at: None,
- },
- ],
- vec![UnreadSignal {
- session_id: "sess-1".into(),
- label: Some("Codex".into()),
- unread: 2,
- last_message_at: None,
- }],
- vec![],
- );
- let by_id = |id: &str| q.items.iter().find(|i| i.id == id).unwrap().clone();
-
- let appr = by_id("approval:req-7");
- assert_eq!(
- appr.action,
- AttentionAction::Approval {
- request_id: "req-7".into()
- }
- );
-
- let run_a = by_id("needs-input:run-a");
- assert_eq!(
- run_a.action,
- AttentionAction::OpenThread {
- thread_id: "t-1".into()
- }
- );
- let run_b = by_id("needs-input:run-b");
- assert_eq!(
- run_b.action,
- AttentionAction::OpenRun {
- run_id: "run-b".into()
- }
- );
-
- let unread = by_id("unread:sess-1");
- assert_eq!(
- unread.action,
- AttentionAction::OpenSession {
- session_id: "sess-1".into()
- }
- );
- assert_eq!(unread.title, "Codex");
- }
-
- #[test]
- fn action_serializes_tagged_with_camelcase_id_fields() {
- // The TS `AttentionAction` union reads `requestId`/`threadId`/`runId`/
- // `sessionId`; the wire must match or the renderer router gets `undefined`.
- let cases = [
- (
- AttentionAction::Approval {
- request_id: "r".into(),
- },
- "approval",
- "requestId",
- ),
- (
- AttentionAction::OpenThread {
- thread_id: "t".into(),
- },
- "open-thread",
- "threadId",
- ),
- (
- AttentionAction::OpenRun { run_id: "n".into() },
- "open-run",
- "runId",
- ),
- (
- AttentionAction::OpenSession {
- session_id: "s".into(),
- },
- "open-session",
- "sessionId",
- ),
- ];
- for (action, tag, id_field) in cases {
- let v = serde_json::to_value(&action).unwrap();
- assert_eq!(v.get("type").and_then(|x| x.as_str()), Some(tag));
- assert!(
- v.get(id_field).is_some(),
- "action {tag} must expose camelCase id field {id_field}, got {v}"
- );
- }
- }
-
- #[test]
- fn unread_title_falls_back_to_session_id_when_unlabeled() {
- let q = assemble_attention(
- vec![],
- vec![],
- vec![UnreadSignal {
- session_id: "h-xyz".into(),
- label: None,
- unread: 1,
- last_message_at: None,
- }],
- vec![],
- );
- assert_eq!(q.items[0].title, "h-xyz");
- }
-
- // ── command-center mapping ──────────────────────────────────────────────
-
- use crate::openhuman::agent::orchestration::command_center::{
- AgentWorkBucket, AgentWorkRow, CommandCenterGroup, CommandCenterView,
- };
-
- fn work_row(run_id: &str, bucket: AgentWorkBucket) -> AgentWorkRow {
- AgentWorkRow {
- run_id: run_id.into(),
- kind: "subagent".into(),
- agent_id: None,
- display_name: None,
- bucket,
- status: "awaiting_user".into(),
- parent_thread_id: None,
- worker_thread_id: None,
- summary: None,
- error: None,
- started_at: "2026-07-06T10:00:00Z".into(),
- updated_at: "2026-07-06T10:05:00Z".into(),
- elapsed_ms: None,
- input_tokens: 0,
- output_tokens: 0,
- cost_usd: 0.0,
- tool_count: 0,
- }
- }
-
- fn view(groups: Vec<CommandCenterGroup>) -> CommandCenterView {
- let total = groups.iter().map(|g| g.rows.len()).sum();
- CommandCenterView { groups, total }
- }
-
- #[test]
- fn command_center_maps_only_the_needs_input_bucket() {
- // A NeedsInput run with a worker thread + display name, plus a Working
- // run that must be ignored.
- let blocked = AgentWorkRow {
- display_name: Some("researcher".into()),
- worker_thread_id: Some("worker-1".into()),
- parent_thread_id: Some("parent-1".into()),
- summary: Some("needs a decision".into()),
- ..work_row("run-blocked", AgentWorkBucket::NeedsInput)
- };
- let v = view(vec![
- CommandCenterGroup {
- bucket: AgentWorkBucket::NeedsInput,
- count: 1,
- rows: vec![blocked],
- },
- CommandCenterGroup {
- bucket: AgentWorkBucket::Working,
- count: 1,
- rows: vec![work_row("run-working", AgentWorkBucket::Working)],
- },
- ]);
-
- let signals = needs_input_from_command_center(v);
- assert_eq!(signals.len(), 1, "only the NeedsInput bucket maps");
- let s = &signals[0];
- assert_eq!(s.run_id, "run-blocked");
- assert_eq!(s.title, "researcher");
- // Worker thread wins over parent thread for the deep link.
- assert_eq!(s.thread_id.as_deref(), Some("worker-1"));
- assert_eq!(s.summary.as_deref(), Some("needs a decision"));
- }
-
- #[test]
- fn command_center_falls_back_to_run_id_and_parent_thread() {
- // No display name → run id; no worker thread → parent thread.
- let row = AgentWorkRow {
- parent_thread_id: Some("parent-9".into()),
- ..work_row("run-x", AgentWorkBucket::NeedsInput)
- };
- let signals = needs_input_from_command_center(view(vec![CommandCenterGroup {
- bucket: AgentWorkBucket::NeedsInput,
- count: 1,
- rows: vec![row],
- }]));
- assert_eq!(signals[0].title, "run-x");
- assert_eq!(signals[0].thread_id.as_deref(), Some("parent-9"));
- }
-
- #[test]
- fn approval_signals_map_fields_and_stamp_created_at() {
- use crate::openhuman::security::approval::types::PendingApproval;
- let p = PendingApproval::new("r1", "shell", "run ls", serde_json::json!({}), None);
- let sigs = approval_signals(vec![p]);
- assert_eq!(sigs.len(), 1);
- assert_eq!(sigs[0].request_id, "r1");
- assert_eq!(sigs[0].tool_name, "shell");
- assert_eq!(sigs[0].action_summary, "run ls");
- assert!(sigs[0].created_at.is_some(), "created_at is stamped");
- }
-
- #[test]
- fn command_center_empty_when_no_needs_input_group() {
- let signals = needs_input_from_command_center(view(vec![CommandCenterGroup {
- bucket: AgentWorkBucket::Completed,
- count: 0,
- rows: vec![],
- }]));
- assert!(signals.is_empty());
- }
-
- // ── remote-approval mapping ─────────────────────────────────────────────
-
- use crate::openhuman::hosted::orchestration::types::OrchestrationSession;
-
- fn session(id: &str, state: Option<&str>) -> OrchestrationSession {
- OrchestrationSession {
- session_id: id.into(),
- agent_id: "@peer".into(),
- source: "claude".into(),
- last_seq: 1,
- created_at: "2026-07-06T00:00:00Z".into(),
- last_message_at: "2026-07-06T12:00:00Z".into(),
- status_state: state.map(str::to_string),
- ..Default::default()
- }
- }
-
- #[test]
- fn remote_approval_signals_keep_only_waiting_approval_sessions() {
- let waiting = OrchestrationSession {
- label: Some("Claude · deploy".into()),
- current_detail: Some("approve `rm -rf build/`".into()),
- active_call_id: Some("call-9".into()),
- ..session("h-waiting", Some("waiting_approval"))
- };
- let signals = remote_approval_signals(vec![
- waiting,
- session("h-running", Some("running")),
- session("h-idle", Some("idle")),
- session("h-legacy", None),
- ]);
- assert_eq!(signals.len(), 1, "only the waiting_approval session maps");
- let s = &signals[0];
- assert_eq!(s.session_id, "h-waiting");
- assert_eq!(s.label.as_deref(), Some("Claude · deploy"));
- assert_eq!(s.detail.as_deref(), Some("approve `rm -rf build/`"));
- assert_eq!(s.active_call_id.as_deref(), Some("call-9"));
- assert_eq!(s.created_at.as_deref(), Some("2026-07-06T12:00:00Z"));
- }
-
- fn remote(session_id: &str, at: &str) -> RemoteApprovalSignal {
- RemoteApprovalSignal {
- session_id: session_id.into(),
- label: Some("Claude · deploy".into()),
- detail: Some("approve `rm -rf build/`".into()),
- active_call_id: Some("call-9".into()),
- created_at: Some(at.into()),
- }
- }
-
- #[test]
- fn remote_approval_surfaces_as_approval_kind_ahead_of_other_kinds() {
- let q = assemble_attention(
- vec![],
- vec![NeedsInputSignal {
- run_id: "run-1".into(),
- title: "researcher".into(),
- summary: None,
- thread_id: Some("t-1".into()),
- updated_at: Some("2026-07-06T11:00:00Z".into()),
- }],
- vec![UnreadSignal {
- session_id: "h-2".into(),
- label: None,
- unread: 2,
- last_message_at: Some("2026-07-06T13:00:00Z".into()),
- }],
- vec![remote("h-remote", "2026-07-06T12:00:00Z")],
- );
- // The remote approval leads (Approval kind, priority 0).
- assert_eq!(q.items[0].kind, AttentionKind::Approval);
- assert_eq!(q.items[0].id, "remote-approval:h-remote");
- assert_eq!(
- q.items[0].action,
- AttentionAction::OpenSession {
- session_id: "h-remote".into()
- }
- );
- assert_eq!(
- q.items[0].summary.as_deref(),
- Some("approve `rm -rf build/`")
- );
- assert_eq!(q.items[0].title, "Claude · deploy");
- // Counted under approvals — a remote approval IS an approval.
- assert_eq!(
- q.counts,
- AttentionCounts {
- total: 3,
- approvals: 1,
- needs_input: 1,
- unread: 1
- }
- );
- }
-
- #[test]
- fn remote_approval_title_falls_back_to_session_id_when_unlabeled() {
- let q = assemble_attention(
- vec![],
- vec![],
- vec![],
- vec![RemoteApprovalSignal {
- session_id: "h-bare".into(),
- label: None,
- detail: None,
- active_call_id: None,
- created_at: None,
- }],
- );
- assert_eq!(q.items.len(), 1);
- assert_eq!(q.items[0].title, "h-bare");
- assert_eq!(q.counts.approvals, 1);
- }
-
- #[test]
- fn empty_remote_approvals_is_a_no_op() {
- // A queue with only a local approval is unchanged by an empty remote vec.
- let q = assemble_attention(
- vec![approval("r1", "2026-07-06T10:00:00Z")],
- vec![],
- vec![],
- vec![],
- );
- assert_eq!(q.items.len(), 1);
- assert_eq!(q.items[0].id, "approval:r1");
- assert_eq!(q.counts.approvals, 1);
- }
-
- #[test]
- fn local_and_remote_approvals_coexist_newest_first() {
- // Both are Approval kind; within the kind they order newest-first, so the
- // later remote approval leads the earlier local one.
- let q = assemble_attention(
- vec![approval("local-old", "2026-07-06T09:00:00Z")],
- vec![],
- vec![],
- vec![remote("remote-new", "2026-07-06T12:00:00Z")],
- );
- assert_eq!(q.counts.approvals, 2);
- let ids: Vec<&str> = q.items.iter().map(|i| i.id.as_str()).collect();
- assert_eq!(
- ids,
- vec!["remote-approval:remote-new", "approval:local-old"]
- );
- }
-}
diff --git a/src/openhuman/hosted/orchestration/bus.rs b/src/openhuman/hosted/orchestration/bus.rs
deleted file mode 100644
index 0c906dc232..0000000000
--- a/src/openhuman/hosted/orchestration/bus.rs
+++ /dev/null
@@ -1,89 +0,0 @@
-//! Event-bus subscriber that drives orchestration ingest off inbound tiny.place
-//! DM stream messages.
-
-use std::sync::{Arc, OnceLock};
-
-use async_trait::async_trait;
-use once_cell::sync::Lazy;
-use tokio::sync::broadcast;
-
-use crate::core::bus::BUS;
-use crate::core::events::DomainEvent;
-use tinybus::EventHandler;
-use tinybus::SubscriptionHandle;
-
-static INGEST_HANDLE: OnceLock<SubscriptionHandle> = OnceLock::new();
-
-/// Broadcast bus of orchestration chat activity for the renderer socket bridge.
-/// Each message is a `{ agentId, sessionId, chatKind }` payload the
-/// `core/socketio.rs` bridge re-emits as `orchestration:message` so the
-/// `TinyPlaceOrchestrationTab` can targeted-refetch the affected chat live.
-static ORCH_SOCKET_BUS: Lazy<broadcast::Sender<serde_json::Value>> = Lazy::new(|| {
- let (tx, _rx) = broadcast::channel(128);
- tx
-});
-
-/// Subscribe to orchestration socket activity. Used by the Socket.IO bridge.
-pub fn subscribe_orchestration_socket() -> broadcast::Receiver<serde_json::Value> {
- ORCH_SOCKET_BUS.subscribe()
-}
-
-/// Fan an orchestration chat activity event out to the renderer socket bridge.
-pub fn notify_orchestration_message(agent_id: &str, session_id: &str, chat_kind: &str) {
- let payload = serde_json::json!({
- "agentId": agent_id,
- "sessionId": session_id,
- "chatKind": chat_kind,
- });
- // No subscribers (headless / cron) is fine — drop silently.
- let _ = ORCH_SOCKET_BUS.send(payload);
-}
-
-/// Register the orchestration ingest subscriber on the global event bus.
-pub fn register_orchestration_ingest_subscriber() {
- if INGEST_HANDLE.get().is_some() {
- return;
- }
- match BUS.subscribe(Arc::new(OrchestrationIngestSubscriber)) {
- Some(handle) => {
- let _ = INGEST_HANDLE.set(handle);
- }
- None => {
- log::warn!(
- "[orchestration] failed to register ingest subscriber — bus not initialized"
- );
- }
- }
-}
-
-pub struct OrchestrationIngestSubscriber;
-
-#[async_trait]
-impl EventHandler<DomainEvent> for OrchestrationIngestSubscriber {
- fn name(&self) -> &str {
- "orchestration::ingest"
- }
-
- fn domains(&self) -> Option<&[&str]> {
- Some(&["tinyplace"])
- }
-
- async fn handle(&self, event: &DomainEvent) {
- let DomainEvent::TinyPlaceStreamMessage {
- stream_id,
- kind,
- message,
- } = event
- else {
- return;
- };
- let config = match crate::openhuman::config::Config::load_or_init().await {
- Ok(config) => config,
- Err(e) => {
- log::warn!("[orchestration] ingest.config_load_failed: {e}");
- return;
- }
- };
- super::ingest::ingest_stream_message(&config, kind, stream_id, message).await;
- }
-}
diff --git a/src/openhuman/hosted/orchestration/cloud.rs b/src/openhuman/hosted/orchestration/cloud.rs
deleted file mode 100644
index 24819837cd..0000000000
--- a/src/openhuman/hosted/orchestration/cloud.rs
+++ /dev/null
@@ -1,253 +0,0 @@
-//! Hosted-brain uplink + read surface.
-//!
-//! Forwards sanitized orchestration events (`POST /orchestration/v1/events`) and
-//! world-diff batches (`POST /orchestration/v1/world-diff`) to the hosted brain,
-//! which runs the wake/reasoning graph server-side, and reads back
-//! sessions / messages (`GET /orchestration/v1/*`). Forwarding is
-//! best-effort and fire-and-forget, so it never blocks or fails ingest.
-//!
-//! Auth + base-URL plumbing mirrors the other hosted-API adapters
-//! (`announcements/ops.rs`, `billing/ops.rs`): an app-session JWT via
-//! `require_live_session_token`, the backend base via `effective_backend_api_url`,
-//! and one shared `BackendOAuthClient`.
-
-use std::time::Duration;
-
-use reqwest::Method;
-use serde_json::Value;
-
-use crate::api::config::effective_backend_api_url;
-use crate::api::BackendOAuthClient;
-use crate::openhuman::config::Config;
-
-use super::wire::{OrchestrationEventEnvelopeWire, WorldDiffBatchWire};
-
-const LOG: &str = "orchestration";
-const EVENTS_PATH: &str = "/orchestration/v1/events";
-const WORLD_DIFF_PATH: &str = "/orchestration/v1/world-diff";
-
-/// Jittered retry schedule for a transient push failure (3 retries after the
-/// first attempt). Matches the plan's 1s/4s/10s cadence.
-const DEFAULT_BACKOFFS: [Duration; 3] = [
- Duration::from_secs(1),
- Duration::from_secs(4),
- Duration::from_secs(10),
-];
-
-/// Push one sanitized event to the hosted brain. Resolves the app-session JWT
-/// and backend base, then POSTs with bounded retry. Returns `Err` only after
-/// the retry budget is exhausted (or the session is signed out).
-pub async fn push_event(
- config: &Config,
- envelope: &OrchestrationEventEnvelopeWire,
-) -> Result<Option<String>, String> {
- let token =
- crate::openhuman::security::credentials::session_support::require_live_session_token(
- config,
- )?;
- let api_url = effective_backend_api_url(&config.api_url);
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- push_event_with(&client, &token, envelope, &DEFAULT_BACKOFFS).await
-}
-
-/// Upload a batch of world-diff entries — the subconscious tier's primary
-/// trigger. Same auth/base/retry plumbing as [`push_event`]. Returns `Err` only
-/// after the retry budget is exhausted (or the session is signed out).
-pub async fn push_world_diff(config: &Config, batch: &WorldDiffBatchWire) -> Result<(), String> {
- if batch.entries.is_empty() {
- return Ok(());
- }
- let token =
- crate::openhuman::security::credentials::session_support::require_live_session_token(
- config,
- )?;
- let api_url = effective_backend_api_url(&config.api_url);
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- post_with_retry(
- &client,
- &token,
- WORLD_DIFF_PATH,
- batch.to_value(),
- &DEFAULT_BACKOFFS,
- &format!(
- "world-diff session={} entries={}",
- batch.session_id,
- batch.entries.len()
- ),
- )
- .await
- .map(|_| ())
-}
-
-/// Inner push with an injectable client, token, and backoff schedule so the
-/// transport can be exercised against a mock server without real credentials or
-/// real sleeps (`backoffs = &[]` → single attempt). Public for integration
-/// tests (`tests/orchestration_shadow_push_e2e.rs`).
-pub async fn push_event_with(
- client: &BackendOAuthClient,
- token: &str,
- envelope: &OrchestrationEventEnvelopeWire,
- backoffs: &[Duration],
-) -> Result<Option<String>, String> {
- let label = format!(
- "event session={} seq={}",
- envelope.session_id, envelope.event.seq
- );
- let resp = post_with_retry(
- client,
- token,
- EVENTS_PATH,
- envelope.to_value(),
- backoffs,
- &label,
- )
- .await?;
- // `202 { accepted, cycleId }` — return the cycleId so the caller can record
- // the cycle's device-authoritative origin (see `exec_gate`).
- Ok(resp
- .get("cycleId")
- .and_then(|v| v.as_str())
- .map(str::to_string))
-}
-
-/// Generic authed POST with bounded jittered-backoff retry. Shared by every
-/// orchestration uplink (`events`, `world-diff`). `backoffs = &[]` → one attempt.
-async fn post_with_retry(
- client: &BackendOAuthClient,
- token: &str,
- path: &str,
- body: serde_json::Value,
- backoffs: &[Duration],
- label: &str,
-) -> Result<Value, String> {
- let mut attempt: usize = 0;
- loop {
- match client
- .authed_json(token, Method::POST, path, Some(body.clone()))
- .await
- {
- Ok(data) => {
- log::debug!(target: LOG, "[orchestration] cloud.push.ok {label} attempt={}", attempt + 1);
- return Ok(data);
- }
- Err(err) => {
- let msg = crate::api::flatten_authed_error(err);
- if attempt >= backoffs.len() {
- log::warn!(target: LOG, "[orchestration] cloud.push.give_up {label} attempts={} err={msg}", attempt + 1);
- return Err(msg);
- }
- log::warn!(target: LOG, "[orchestration] cloud.push.retry {label} attempt={} err={msg}", attempt + 1);
- tokio::time::sleep(backoffs[attempt]).await;
- attempt += 1;
- }
- }
- }
-}
-
-/// World-diff uploader with injectable client/token/backoffs for tests.
-pub async fn push_world_diff_with(
- client: &BackendOAuthClient,
- token: &str,
- batch: &WorldDiffBatchWire,
- backoffs: &[Duration],
-) -> Result<(), String> {
- let label = format!(
- "world-diff session={} entries={}",
- batch.session_id,
- batch.entries.len()
- );
- post_with_retry(
- client,
- token,
- WORLD_DIFF_PATH,
- batch.to_value(),
- backoffs,
- &label,
- )
- .await
- .map(|_| ())
-}
-
-// ── Hosted read surface (GET) ─────────────────────────────────────────────────
-// The renderer reads session / message / state / world-diff state
-// from the hosted brain over these routes. Each returns the unwrapped `data`
-// payload (`BackendOAuthClient` strips the `{success,data}` envelope). Callers
-// fall back to the local render cache on `Err` and surface an offline notice.
-// A replayed/duplicate write is a 202 (not a 409) server-side, so a read never
-// needs to special-case dedupe.
-
-const SESSIONS_PATH: &str = "/orchestration/v1/sessions";
-
-/// A session token + backend client resolved once and reused across every GET in a
-/// single sync read pass. `sync_reads` issues `fetch_sessions` + up to
-/// `MAX_SESSIONS_PER_SYNC` `fetch_messages` per 20s tick, so rebuilding the client
-/// (and re-loading the session profile) per GET would repeat the profile lookup and
-/// discard the reqwest connection pool on every request.
-/// Resolve it once with [`read_pass`] and thread it through the pass.
-pub struct ReadPass {
- client: BackendOAuthClient,
- token: String,
-}
-
-/// Resolve the token + client for one sync read pass. `Err` (no live session) → the
-/// caller degrades the whole pass to the local render cache.
-pub fn read_pass(config: &Config) -> Result<ReadPass, String> {
- let token =
- crate::openhuman::security::credentials::session_support::require_live_session_token(
- config,
- )?;
- let api_url = effective_backend_api_url(&config.api_url);
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- Ok(ReadPass { client, token })
-}
-
-impl ReadPass {
- /// GET the hosted session list →
- /// `[{ sessionId, counterpartAgentId, lastSeq, status, lastCycleId?, lastEventTs?, updatedAt? }]`.
- pub async fn fetch_sessions(&self) -> Result<Value, String> {
- self.authed_get(SESSIONS_PATH.to_string(), "sessions").await
- }
-
- /// GET messages for a session, optionally after a `seq` cursor →
- /// `[{ seq, role, sender, body, kind, ts, cycleId }]`. Cursor param is `?after=`.
- pub async fn fetch_messages(
- &self,
- session_id: &str,
- after_seq: Option<i64>,
- ) -> Result<Value, String> {
- let mut path = format!(
- "/orchestration/v1/sessions/{}/messages",
- urlencoding::encode(session_id)
- );
- if let Some(after) = after_seq {
- path.push_str(&format!("?after={after}"));
- }
- self.authed_get(path, "messages").await
- }
-
- /// Shared authed GET → unwrapped `data`, reusing this pass's token + client.
- /// Returns a flattened error string on transport / non-2xx so the caller can
- /// degrade to the local render cache.
- async fn authed_get(&self, path: String, label: &str) -> Result<Value, String> {
- match self
- .client
- .authed_json(&self.token, Method::GET, &path, None)
- .await
- {
- Ok(data) => {
- log::debug!(target: LOG, "[orchestration] cloud.read.ok {label}");
- Ok(data)
- }
- Err(err) => {
- let msg = crate::api::flatten_authed_error(err);
- log::warn!(target: LOG, "[orchestration] cloud.read.fail {label} err={msg}");
- Err(msg)
- }
- }
- }
-}
-
-// Transport tests live in `tests/orchestration_shadow_push_e2e.rs` (integration
-// crate): the root crate's `cfg(test)` build is currently blocked by unrelated
-// stale test modules at this checkout, so the pusher is exercised over wiremock
-// from an integration test that links the compiled lib instead.
diff --git a/src/openhuman/hosted/orchestration/effect_executor.rs b/src/openhuman/hosted/orchestration/effect_executor.rs
deleted file mode 100644
index 60d7197f14..0000000000
--- a/src/openhuman/hosted/orchestration/effect_executor.rs
+++ /dev/null
@@ -1,1016 +0,0 @@
-//! Client-side executor for device-bound orchestration effects pushed by the
-//! hosted brain over the socket.
-//!
-//! The backend computes a wake cycle and, when it wants the device to act,
-//! delivers an effect frame (`orch:effect:send_dm`, `orch:effect:evict`, …). The
-//! device runs the effect against its local Signal keys / memory and acks with
-//! `orch:effect:result { callId, ok, error? }`. Delivery is at-least-once and the
-//! client dedupes on `callId` (a `send_dm` whose ack was already latched
-//! server-side is a no-op here — see [`is_duplicate_call`]).
-
-use std::collections::HashSet;
-use std::sync::Mutex;
-
-use serde::Deserialize;
-use serde_json::{json, Value};
-
-const LOG: &str = "orchestration";
-
-/// A `send_dm` effect: relay `body` to `counterpartAgentId` over Signal, wrapping
-/// it in `sessionId`'s session envelope so the peer threads the reply.
-#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SendDmEffect {
- #[serde(default)]
- pub cycle_id: String,
- pub call_id: String,
- pub counterpart_agent_id: String,
- #[serde(default)]
- pub session_id: String,
- #[serde(default)]
- pub body: String,
-}
-
-/// Parse an `orch:effect:send_dm` frame. Pure.
-pub fn parse_send_dm(data: &Value) -> Result<SendDmEffect, String> {
- serde_json::from_value(data.clone()).map_err(|e| format!("parse send_dm: {e}"))
-}
-
-/// Build the `orch:effect:result` ack frame the device sends back. Pure.
-pub fn effect_result_frame(call_id: &str, ok: bool, error: Option<&str>) -> Value {
- json!({ "callId": call_id, "ok": ok, "error": error })
-}
-
-/// The device-tool manifest declared to the hosted brain on socket connect
-/// (`orch:register_tools`). These are **queryable** tools the reasoning loop may
-/// call mid-cycle (results feed back), distinct from the terminal `send_dm`
-/// effect. Phase 2 seeds it with a read-only status probe; local-workspace tools
-/// grow this list as they are wired to the device tool dispatcher.
-pub fn device_tool_manifest() -> Value {
- json!({
- "tools": [
- {
- "name": "device_status",
- "description": "Report this device's app version and platform.",
- "inputSchema": { "type": "object", "properties": {}, "additionalProperties": false }
- },
- {
- "name": "run_local_agent",
- "description": "Spawn a local device sub-agent (e.g. code_executor for repo/shell/file work, researcher, tools_agent) on the user's own machine for background work, and return an acknowledgement. LOCAL-EXECUTION: only runs for a Master-chat cycle (the human ↔ their own OpenHuman); it is refused for any agent-to-agent cycle.",
- "inputSchema": {
- "type": "object",
- "required": ["agent_id", "prompt"],
- "properties": {
- "agent_id": { "type": "string", "description": "Local sub-agent id, e.g. code_executor, researcher, tools_agent." },
- "prompt": { "type": "string", "description": "Clear, self-contained instruction for the sub-agent." },
- "context": { "type": "string", "description": "Optional context blob from prior results." },
- "toolkit": { "type": "string", "description": "Composio toolkit to scope to (e.g. gmail, notion). REQUIRED when agent_id is integrations_agent; ignored otherwise." }
- },
- "additionalProperties": false
- }
- }
- ]
- })
-}
-
-/// A device tool call pushed by the hosted brain (`orch:tool_call`). Run it
-/// locally and return the result over `orch:tool_result`.
-#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ToolCallFrame {
- #[serde(default)]
- pub cycle_id: String,
- pub call_id: String,
- pub name: String,
- #[serde(default)]
- pub args: Value,
-}
-
-/// Parse an `orch:tool_call` frame. Pure.
-pub fn parse_tool_call(data: &Value) -> Result<ToolCallFrame, String> {
- serde_json::from_value(data.clone()).map_err(|e| format!("parse tool_call: {e}"))
-}
-
-/// Build the `orch:tool_result` frame returned to the hosted brain. Pure.
-pub fn tool_result_frame(call_id: &str, ok: bool, result: Value, error: Option<&str>) -> Value {
- json!({ "callId": call_id, "ok": ok, "result": result, "error": error })
-}
-
-/// Run a device-declared tool locally and return its result. `device_status` is
-/// read-only; `run_local_agent` executes local workspace work and is therefore
-/// **gated**: it runs only when `cycle_id` belongs to a Master-chat cycle
-/// (device-authoritative origin, see [`super::exec_gate`]). The gate is enforced
-/// here — on the device that holds the capability — so a prompt-injected or
-/// compromised cloud brain cannot induce local execution for an A2A cycle.
-pub async fn dispatch_device_tool(
- name: &str,
- args: &Value,
- cycle_id: &str,
-) -> Result<Value, String> {
- if super::exec_gate::is_local_execution_tool(name)
- && !super::exec_gate::cycle_is_master(cycle_id)
- {
- log::warn!(
- target: LOG,
- "[orchestration] device_tool.denied name={name} cycle={cycle_id} reason=non_master_origin"
- );
- return Err(format!(
- "device tool '{name}' denied: local execution is restricted to the Master chat"
- ));
- }
- match name {
- "device_status" => Ok(json!({
- "version": env!("CARGO_PKG_VERSION"),
- "platform": std::env::consts::OS,
- })),
- "run_local_agent" => run_local_agent(args, cycle_id).await,
- other => Err(format!("unknown device tool: {other}")),
- }
-}
-
-/// The gated `run_local_agent` device tool. Reached only after the Master-chat
-/// gate in [`dispatch_device_tool`] has passed.
-///
-/// **Async model:** we do NOT block the wake cycle on a (potentially long) local
-/// sub-agent. We fire it in the background and return an immediate `accepted`
-/// ack — which the hosted brain sees as `orch:tool_result` well inside the
-/// device-tool timeout. When the sub-agent finishes, [`run_local_agent_and_forward`]
-/// pushes its result up as a fresh `tool_completion` event, which wakes a NEW
-/// cycle that reasons over the result. So the original cycle is never blocked,
-/// and the result still lands back in the brain via the follow-up cycle.
-async fn run_local_agent(args: &Value, cycle_id: &str) -> Result<Value, String> {
- let (counterpart, session_id) = super::exec_gate::cycle_target(cycle_id)
- .ok_or_else(|| "run_local_agent: unknown cycle origin".to_string())?;
- let agent_id = args
- .get("agent_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- let prompt = args
- .get("prompt")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- if agent_id.is_empty() || prompt.is_empty() {
- return Err("run_local_agent: `agent_id` and `prompt` are required".to_string());
- }
- let task_id = cycle_id.to_string();
- let run_args = args.clone();
- let bg_task_id = task_id.clone();
- // Scope an explicit turn origin around the spawned sub-agent work.
- //
- // This runs on a fresh `tokio::spawn` task with no agent turn on the stack,
- // and `AGENT_TURN_ORIGIN` is a `tokio::task_local` that does NOT cross
- // `tokio::spawn` — so `turn_origin::current()` here is `None`, the approval
- // gate reads `AgentTurnOrigin::Unknown`, and every external_effect tool the
- // sub-agent calls (cron_add / cron_update / shell / …) is refused as "no
- // origin label" (issues #5508, #5499). PR #5465 fixed the four canonical
- // spawn sites via capture/propagate; this is the residual one.
- //
- // Unlike those sites there is no ambient origin to inherit (the device-tool
- // bridge is not itself an agent turn), so `with_inherited_origin(None, …)`
- // would stay `Unknown` and keep failing closed. We instead scope an explicit
- // `AgentTurnOrigin::Cli`: this only runs after the device-authoritative
- // Master-chat gate in `dispatch_device_tool` has passed (a compromised cloud
- // brain cannot reach here for an A2A cycle), so it is trusted, turn-less,
- // device-initiated internal dispatch — exactly the label `mcp::registry`'s
- // credential-help turn and `task_dispatcher` use for the same shape.
- let bg = crate::openhuman::agent::turn_origin::with_origin(
- crate::openhuman::agent::turn_origin::AgentTurnOrigin::Cli,
- async move {
- if let Err(e) = run_local_agent_and_forward(
- &counterpart,
- &session_id,
- &bg_task_id,
- &agent_id,
- run_args,
- )
- .await
- {
- log::warn!(
- target: LOG,
- "[orchestration] run_local_agent.forward_failed task={bg_task_id}: {e}"
- );
- }
- },
- );
- tokio::spawn(bg);
- Ok(json!({
- "accepted": true,
- "taskId": task_id,
- "status": "running",
- "note": "local sub-agent started; its result will arrive as a follow-up tool_completion event."
- }))
-}
-
-/// Run the requested local sub-agent to completion and return `(ok, output)`.
-///
-/// The device tool bridge fires this from a bare `tokio::spawn` task, so there is
-/// no agent turn on the stack and `current_parent()` is `None`. We install a
-/// background root [`ParentExecutionContext`] via the blessed [`with_root_parent`]
-/// (provider / tools / memory / model / workspace harvested from a `Config`-built
-/// agent) and dispatch through [`run_subagent`] directly — the same pattern every
-/// other turn-less surface uses (delegation, workflow runs, agent teams,
-/// subconscious). This is what lets a Master-chat cycle actually run a local
-/// sub-agent; without it the nested spawn failed `NoParentContext`
-/// ("spawn_async_subagent called outside of an agent turn").
-///
-/// The `AGENT_TURN_ORIGIN` task-local is a **separate** axis and is scoped by
-/// [`run_local_agent`] around the spawn (as [`AgentTurnOrigin::Cli`]), not here —
-/// `turn_origin.rs` forbids manufacturing a label inside `run_subagent`. Without
-/// that outer scope the sub-agent's external_effect tools (cron_add / shell / …)
-/// would reach the approval gate as `Unknown` and be refused (#5508, #5499).
-///
-/// We call `run_subagent` (synchronous, real `output`) rather than the
-/// `spawn_async_subagent` tool wrapper on purpose: the wrapper defaults to the
-/// async path (returning a `[async_subagent_ref]`, not the answer) and gates on
-/// the root parent's empty `allowed_subagent_ids`; `run_subagent` has neither
-/// footgun. Every failure (unknown agent id, provider/parent build, run error)
-/// becomes `(false, message)` — never a bail — so the caller always forwards a
-/// `tool_completion` and the hosted brain always learns the outcome.
-async fn run_local_subagent(
- config: &crate::openhuman::config::Config,
- agent_id: &str,
- prompt: &str,
- context: Option<String>,
- toolkit: Option<String>,
-) -> (bool, String) {
- use crate::openhuman::agent::harness::definition::AgentDefinitionRegistry;
- use crate::openhuman::agent::harness::subagent_runner::{
- run_subagent, SubagentRunOptions, SubagentRunStatus,
- };
- use crate::openhuman::agent::orchestration::parent_context::with_root_parent;
-
- // `integrations_agent` MUST be scoped to a single Composio toolkit — mirror the
- // `SpawnSubagentTool` pre-flight so a device run can't reason over the full,
- // unscoped integration surface. `run_subagent` only narrows tools + the
- // Connected-Integrations section when `toolkit_override` is set, so reject a
- // toolkit-less request rather than run it unscoped.
- if agent_id == "integrations_agent" && toolkit.is_none() {
- return (
- false,
- "run_local_agent(integrations_agent): a `toolkit` argument is required".to_string(),
- );
- }
-
- let definition = match AgentDefinitionRegistry::global().and_then(|r| r.get(agent_id).cloned())
- {
- Some(def) => def,
- None => {
- return (
- false,
- format!("run_local_agent: unknown agent_id '{agent_id}'"),
- )
- }
- };
- let options = SubagentRunOptions {
- context,
- toolkit_override: toolkit,
- ..Default::default()
- };
- let run = async move {
- match run_subagent(&definition, prompt, options).await {
- Ok(outcome) => {
- let output = outcome.output;
- match outcome.status {
- // A clarification question / stop-reason lives in `status`, not
- // `output` — surface it so the brain sees more than empty text.
- SubagentRunStatus::Completed => (true, output),
- SubagentRunStatus::AwaitingUser { question, .. } => {
- (false, format!("{output}\n[awaiting user] {question}"))
- }
- SubagentRunStatus::Incomplete { reason } => {
- (false, format!("{output}\n[incomplete] {reason}"))
- }
- }
- }
- Err(e) => (false, format!("sub-agent invocation error: {e}")),
- }
- };
- // Bare background task → no ambient parent, so a root is built from config.
- // (Tests install a mock parent and hit `with_root_parent`'s reuse branch.)
- with_root_parent(config, "local_exec", "local_exec", "localexec", run)
- .await
- .unwrap_or_else(|e| (false, format!("build local-exec parent: {e}")))
-}
-
-/// Background half of `run_local_agent`: run the local sub-agent to completion,
-/// then forward its result up as a `tool_completion` event on the originating
-/// session (which the backend wakes a fresh cycle for).
-async fn run_local_agent_and_forward(
- counterpart: &str,
- session_id: &str,
- task_id: &str,
- agent_id: &str,
- run_args: Value,
-) -> Result<(), String> {
- // Config is needed both to build the background parent context for the
- // sub-agent run and to persist + forward the completion — load it once.
- let config = crate::openhuman::config::Config::load_or_init()
- .await
- .map_err(|e| format!("config load: {e}"))?;
-
- // 1. Run the local sub-agent to completion (real output) under a background
- // root parent context. A failed run still yields `(false, msg)` so the
- // hosted brain always learns the outcome via the forwarded `tool_completion`.
- let prompt = run_args
- .get("prompt")
- .and_then(|v| v.as_str())
- .unwrap_or_default()
- .to_string();
- let context = run_args
- .get("context")
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
- let toolkit = run_args
- .get("toolkit")
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
- let (ok, output) = run_local_subagent(&config, agent_id, &prompt, context, toolkit).await;
-
- let body = format!(
- "[local sub-agent `{agent_id}` task {task_id} {}]\n{output}",
- if ok { "completed" } else { "failed" }
- );
-
- // 2. Persist the completion into the render cache (allocates a monotonic seq)
- // and forward it as a `tool_completion` event → backend wakes a new cycle.
- let now = chrono::Utc::now().to_rfc3339();
- let seq = super::store::with_connection(&config.workspace_dir, |conn| {
- let seq = super::store::next_session_seq(conn, counterpart, session_id)?;
- super::store::insert_message(
- conn,
- &super::types::OrchestrationMessage {
- id: format!("tool-completion:{task_id}:{seq}"),
- agent_id: counterpart.to_string(),
- session_id: session_id.to_string(),
- chat_kind: super::types::ChatKind::Master,
- role: "system".to_string(),
- body: body.clone(),
- timestamp: now.clone(),
- seq,
- // Bookkeeping row: this raw `[local sub-agent … completed]` dump is
- // forwarded to the brain (below) purely so it can synthesize a
- // reply — the user reads that synthesized `send_dm` reply, not this.
- // Tagging it with an excluded event_kind keeps the row (so `seq`
- // stays allocated and the envelope forwards) but hides it from the
- // master transcript, previews, and unread counts (store.rs filters
- // out 'status'/'lifecycle'/'unknown'/'session_info'). Without this,
- // a brain that spawns many sub-agents floods the chat with raw
- // dumps. See list_messages_by_session / count_unread in store.rs.
- event_kind: Some("lifecycle".to_string()),
- ..Default::default()
- },
- )?;
- Ok(seq)
- })
- .map_err(|e| format!("persist completion: {e}"))?;
-
- let ts = super::wire::parse_ts_ms(&now).unwrap_or(0);
- let envelope = super::wire::OrchestrationEventEnvelopeWire::build(
- counterpart,
- session_id,
- seq,
- "system",
- counterpart,
- &body,
- ts,
- "tool_completion",
- );
- if let Err(e) = super::cloud::push_event(&config, &envelope).await {
- // Forward failed (offline / signed out / retries exhausted): the brain
- // never got this result and the completion row was persisted hidden, so
- // it would vanish entirely. Un-hide it — it is now the only copy — and
- // nudge the renderer so the user sees the result rather than losing it.
- let completion_id = format!("tool-completion:{task_id}:{seq}");
- if let Err(store_err) = super::store::with_connection(&config.workspace_dir, |conn| {
- super::store::clear_message_event_kind(conn, &completion_id)
- }) {
- log::warn!(
- target: LOG,
- "[orchestration] run_local_agent.unhide_failed task={task_id}: {store_err}"
- );
- }
- super::bus::notify_orchestration_message(
- counterpart,
- session_id,
- super::types::ChatKind::Master.as_str(),
- );
- return Err(e);
- }
- log::debug!(
- target: LOG,
- "[orchestration] run_local_agent.forwarded task={task_id} session={session_id} seq={seq} ok={ok}"
- );
- Ok(())
-}
-
-/// Handle an inbound `orch:tool_call` frame end-to-end: parse → dispatch →
-/// build the result frame. Returns `(callId, resultFrame)` to emit, or `None`
-/// when the frame is unparseable. Async because a local sub-agent spawn is.
-pub async fn handle_tool_call(data: &Value) -> Option<(String, Value)> {
- let frame = match parse_tool_call(data) {
- Ok(f) => f,
- Err(e) => {
- log::warn!(target: LOG, "[orchestration] tool_call.parse_failed: {e}");
- return None;
- }
- };
- // Dedup redelivered side-effecting local-execution tools (run_local_agent):
- // `orch:tool_call` is at-least-once, so the same call can arrive twice, and
- // without this each redelivery re-spawns the sub-agent AND forwards another
- // `tool_completion` — which wakes another brain cycle and can surface a
- // duplicate reply. Read-only tools (device_status) are idempotent and left
- // un-guarded. Mirrors the guard in `handle_send_dm`. A successful async ack
- // stays latched (a redelivery re-acks without re-spawning); a claim whose
- // dispatch FAILS is released below so the redelivery re-runs and returns the
- // real error instead of a fabricated accept.
- if super::exec_gate::is_local_execution_tool(&frame.name) && is_duplicate_call(&frame.call_id) {
- log::debug!(
- target: LOG,
- "[orchestration] tool_call.duplicate call_id={} name={} (re-acking, no re-dispatch)",
- frame.call_id,
- frame.name
- );
- return Some((
- frame.call_id.clone(),
- tool_result_frame(
- &frame.call_id,
- true,
- json!({ "accepted": true, "status": "running", "duplicate": true }),
- None,
- ),
- ));
- }
- let (ok, result, error) =
- match dispatch_device_tool(&frame.name, &frame.args, &frame.cycle_id).await {
- Ok(value) => (true, value, None),
- Err(e) => (false, Value::Null, Some(e)),
- };
- // A claimed local-execution call whose dispatch FAILED — an A2A-gate denial
- // (dispatch_device_tool restricts run_local_agent to Master cycles), an
- // unknown cycle origin, or invalid args — must release its claim so an
- // at-least-once redelivery re-runs it and returns the same real error. Left
- // latched, the dedup fast-path above would fabricate an `accepted/running` ok
- // for a call that never ran, masking the denial and stranding the brain on a
- // `tool_completion` that never comes.
- if !ok && super::exec_gate::is_local_execution_tool(&frame.name) {
- // Diagnostic for the denied/invalid path; no raw args or error body.
- log::warn!(
- target: LOG,
- "[orchestration] tool_call.dispatch_failed call_id={} name={} released_claim=true",
- frame.call_id,
- frame.name
- );
- release_call(&frame.call_id);
- }
- Some((
- frame.call_id.clone(),
- tool_result_frame(&frame.call_id, ok, result, error.as_deref()),
- ))
-}
-
-// ── callId dedupe (at-least-once delivery guard) ──────────────────────────────
-
-static SEEN_CALL_IDS: Mutex<Option<HashSet<String>>> = Mutex::new(None);
-
-/// Bound on retained call ids. At the cap the window is cleared wholesale (a coarse
-/// TTL) so the guard can't grow without limit now that both send_dm and evict feed
-/// it; a redelivery for an effect older than this many claims may then re-execute,
-/// which is safe (effects are idempotent) and vanishingly rare.
-const SEEN_CALL_IDS_CAP: usize = 16_384;
-
-/// Claim `call_id` for execution and report whether it was already claimed (i.e. a
-/// redelivered effect). Claiming on entry — rather than on success — is deliberate:
-/// it stops a redelivery that arrives *while the first attempt is still running* from
-/// executing the effect a second time. A claim whose effect ultimately FAILS is
-/// released via [`release_call`] so the hosted brain's redelivery re-runs it; a claim
-/// whose effect succeeds stays latched so the redelivery is re-acked idempotently
-/// without re-executing.
-pub fn is_duplicate_call(call_id: &str) -> bool {
- let mut guard = SEEN_CALL_IDS.lock().unwrap_or_else(|p| p.into_inner());
- let set = guard.get_or_insert_with(HashSet::new);
- if set.len() >= SEEN_CALL_IDS_CAP {
- set.clear();
- }
- !set.insert(call_id.to_string())
-}
-
-/// Release a `call_id` claimed by [`is_duplicate_call`] after its effect FAILED, so a
-/// subsequent redelivery re-executes it instead of the guard re-acking a stale
-/// `ok:true` and silently dropping the lost work.
-pub fn release_call(call_id: &str) {
- let mut guard = SEEN_CALL_IDS.lock().unwrap_or_else(|p| p.into_inner());
- if let Some(set) = guard.as_mut() {
- set.remove(call_id);
- }
-}
-
-/// Wrap the reply body for `session_id`. Empty/`master`/`subconscious` sessions
-/// send the plain body; a real harness session is wrapped in a v1 envelope so
-/// the peer threads it. Delegates to the shared orchestration helper.
-fn outgoing_plaintext(session_id: &str, body: &str) -> Result<String, String> {
- if session_id.is_empty() {
- return Ok(body.to_string());
- }
- super::ops::session_send_plaintext(session_id, body).map_err(|e| e.to_string())
-}
-
-/// Execute a `send_dm` effect: wrap + send over Signal via the existing
-/// tinyplace transport. The device's Signal keys never leave the machine.
-pub async fn execute_send_dm(effect: &SendDmEffect) -> Result<(), String> {
- let plaintext = outgoing_plaintext(&effect.session_id, &effect.body)?;
- let mut params = serde_json::Map::new();
- params.insert(
- "recipient".to_string(),
- Value::from(effect.counterpart_agent_id.clone()),
- );
- params.insert("plaintext".to_string(), Value::from(plaintext));
- crate::openhuman::tinyplace::handle_tinyplace_signal_send_message(params)
- .await
- .map_err(|e| format!("signal send: {e}"))?;
- Ok(())
-}
-
-/// A self-directed reply (the human↔OpenHuman Master chat, or the subconscious
-/// window) — rendered into the local cache, never Signal-sent to a peer. The
-/// hosted brain ships every terminal reply as a `send_dm`; the device decides
-/// whether that reply is for a peer or for the user's own window.
-fn is_self_session(session_id: &str) -> bool {
- session_id.is_empty() || session_id == "master" || session_id == "subconscious"
-}
-
-/// Persist a hosted-authored reply into the local render cache as an `assistant`
-/// message and nudge the renderer, so the reply shows in its window even though
-/// the reasoning ran server-side. Idempotent by `call_id` (`INSERT OR IGNORE`),
-/// so a redelivered effect never doubles a row.
-async fn persist_reply(
- agent_id: &str,
- session_id: &str,
- chat_kind: super::types::ChatKind,
- call_id: &str,
- body: &str,
-) -> Result<(), String> {
- use super::types::{OrchestrationMessage, OrchestrationSession};
- let config = crate::openhuman::config::Config::load_or_init()
- .await
- .map_err(|e| format!("config load: {e}"))?;
- let now = chrono::Utc::now().to_rfc3339();
- let message_id = format!("reply:{call_id}");
- let agent_owned = agent_id.to_string();
- let session_owned = session_id.to_string();
- let body_owned = body.to_string();
- let now_owned = now.clone();
- super::store::with_connection(&config.workspace_dir, move |conn| {
- // Allocate the per-session seq and persist the reply in one immediate txn so
- // two concurrent self-replies on the same (agent_id, session_id) can't read
- // the same `MAX(seq)+1` and persist a duplicate ordinal (matches `ingest_one`).
- super::store::in_immediate_txn(conn, |conn| {
- let seq = super::store::next_session_seq(conn, &agent_owned, &session_owned)?;
- super::store::upsert_session(
- conn,
- &OrchestrationSession {
- session_id: session_owned.clone(),
- agent_id: agent_owned.clone(),
- source: chat_kind.as_str().to_string(),
- last_seq: seq,
- created_at: now_owned.clone(),
- last_message_at: now_owned.clone(),
- ..Default::default()
- },
- )?;
- super::store::insert_message(
- conn,
- &OrchestrationMessage {
- id: message_id.clone(),
- agent_id: agent_owned.clone(),
- session_id: session_owned.clone(),
- chat_kind,
- role: "assistant".to_string(),
- body: body_owned.clone(),
- timestamp: now_owned.clone(),
- seq,
- ..Default::default()
- },
- )?;
- Ok(())
- })
- })
- .map_err(|e| format!("persist reply: {e}"))?;
- super::bus::notify_orchestration_message(agent_id, session_id, chat_kind.as_str());
- Ok(())
-}
-
-/// Handle an inbound `orch:effect:send_dm` frame end-to-end.
-///
-/// The hosted brain ships every terminal reply here. The device:
-/// - mirrors the reply body into the local render cache (so the window shows it
-/// regardless of the peer-send outcome), then
-/// - for a **self** session (Master / subconscious) that is the whole job — the
-/// reply is rendered, never Signal-sent;
-/// - for a **peer** session it is also sent over Signal to the counterpart.
-///
-/// Returns `(callId, ackFrame)` for the caller to emit over `orch:effect:result`,
-/// or `None` when the frame is unparseable (nothing to ack).
-pub async fn handle_send_dm(data: &Value) -> Option<(String, Value)> {
- let effect = match parse_send_dm(data) {
- Ok(e) => e,
- Err(e) => {
- log::warn!(target: LOG, "[orchestration] effect.send_dm.parse_failed: {e}");
- return None;
- }
- };
-
- if is_duplicate_call(&effect.call_id) {
- log::debug!(
- target: LOG,
- "[orchestration] effect.send_dm.duplicate call_id={} (re-acking)",
- effect.call_id
- );
- return Some((
- effect.call_id.clone(),
- effect_result_frame(&effect.call_id, true, None),
- ));
- }
-
- let self_session = is_self_session(&effect.session_id);
- // Where the reply is rendered locally. Self replies land in the user's own
- // Master/subconscious window; peer replies land in that peer's session.
- let (cache_agent, cache_session, chat_kind) = if self_session {
- let session = if effect.session_id.is_empty() {
- "master"
- } else {
- &effect.session_id
- };
- (
- super::types::LOCAL_MASTER_AGENT.to_string(),
- session.to_string(),
- super::types::ChatKind::from_str(session),
- )
- } else {
- (
- effect.counterpart_agent_id.clone(),
- effect.session_id.clone(),
- super::types::ChatKind::Session,
- )
- };
-
- let persist_res = persist_reply(
- &cache_agent,
- &cache_session,
- chat_kind,
- &effect.call_id,
- &effect.body,
- )
- .await;
-
- // A self reply is terminal here — no peer to Signal. Ack reflects the local
- // render outcome so a rare cache-write failure is visible server-side.
- if self_session {
- return Some(match persist_res {
- Ok(()) => {
- log::debug!(
- target: LOG,
- "[orchestration] effect.send_dm.self_reply call_id={} session={}",
- effect.call_id,
- cache_session
- );
- (
- effect.call_id.clone(),
- effect_result_frame(&effect.call_id, true, None),
- )
- }
- Err(e) => {
- log::warn!(target: LOG, "[orchestration] effect.send_dm.self_persist_failed call_id={}: {e}", effect.call_id);
- // Un-claim so a redelivery retries the local render.
- release_call(&effect.call_id);
- (
- effect.call_id.clone(),
- effect_result_frame(&effect.call_id, false, Some(&e)),
- )
- }
- });
- }
-
- // Peer reply: the cache mirror is best-effort (log on failure), but the ack
- // reflects the Signal send — that is what the hosted outbox is tracking.
- if let Err(e) = persist_res {
- log::warn!(target: LOG, "[orchestration] effect.send_dm.cache_mirror_failed call_id={}: {e}", effect.call_id);
- }
- let (ok, error) = match execute_send_dm(&effect).await {
- Ok(()) => {
- log::debug!(
- target: LOG,
- "[orchestration] effect.send_dm.sent call_id={} session={}",
- effect.call_id,
- effect.session_id
- );
- (true, None)
- }
- Err(e) => {
- log::warn!(target: LOG, "[orchestration] effect.send_dm.failed call_id={}: {e}", effect.call_id);
- (false, Some(e))
- }
- };
- if !ok {
- // Un-claim so a redelivery re-sends instead of re-acking a stale success.
- release_call(&effect.call_id);
- }
- Some((
- effect.call_id.clone(),
- effect_result_frame(&effect.call_id, ok, error.as_deref()),
- ))
-}
-
-// ── evict effect (context-guard → local memory RAG) ───────────────────────────
-
-/// One evicted compressed-history entry the hosted context-guard is asking the
-/// device to mirror into its local memory RAG so the summary stays retrievable
-/// offline after the server drops it from the wake context window.
-#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct EvictEntry {
- #[serde(default)]
- pub cycle_id: String,
- #[serde(default)]
- pub summary: String,
-}
-
-/// An `orch:effect:evict` effect. Backend frame:
-/// `{ cycleId, callId, sessionId, entries: [{ cycleId, summary }] }`.
-#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct EvictEffect {
- #[serde(default)]
- pub cycle_id: String,
- pub call_id: String,
- #[serde(default)]
- pub session_id: String,
- #[serde(default)]
- pub entries: Vec<EvictEntry>,
-}
-
-/// Parse an `orch:effect:evict` frame. Pure.
-pub fn parse_evict(data: &Value) -> Result<EvictEffect, String> {
- serde_json::from_value(data.clone()).map_err(|e| format!("parse evict: {e}"))
-}
-
-/// Stable, idempotent RAG source id for an evicted entry. The ingest pipeline
-/// gates on this key, so a redelivered evict (or a replayed cycle) re-ingests
-/// nothing even beyond the `callId` dedupe.
-fn evict_source_id(session_id: &str, cycle_id: &str) -> String {
- let session = if session_id.is_empty() {
- "master"
- } else {
- session_id
- };
- format!("orch_evict:{session}:{cycle_id}")
-}
-
-/// Fold each evicted summary into local memory RAG through the bound driver's
-/// Ingest family. The device's memory never leaves the machine — only the
-/// hosted brain's own compressed summary text (which it just sent us) is
-/// stored, and it is stored by whichever driver this workspace is bound to.
-pub async fn execute_evict(effect: &EvictEffect) -> Result<(), String> {
- use crate::openhuman::memory::api::chunks::{DataSource, SourceRef};
- use crate::openhuman::memory::api::provider::types::IngestItem;
- use crate::openhuman::memory::api::provider::MemoryProvider;
- use crate::openhuman::memory::api::types::MemoryTaint;
-
- let config = crate::openhuman::config::Config::load_or_init()
- .await
- .map_err(|e| format!("config load: {e}"))?;
-
- let binding = crate::openhuman::memory::binding::for_config(&config)?;
- // A write, so an absent family refuses rather than reporting success. The
- // caller un-claims the `callId` on `Err`, so the brain redelivers the evict
- // instead of us acking away a summary that was never stored.
- // Routed through the guard so policy (redaction, taint stamping) applies
- // to evicted summaries the same way it applies to explicit ingest calls.
- let guard = binding.guard();
- let Some(ingest) = guard.as_ingest() else {
- return Err(format!(
- "evict ingest: driver '{}' does not serve the Ingest family",
- binding.driver_id()
- ));
- };
-
- let mut ingested = 0usize;
- for entry in &effect.entries {
- if entry.summary.trim().is_empty() {
- continue;
- }
- let source_id = evict_source_id(&effect.session_id, &entry.cycle_id);
- let item = IngestItem {
- namespace: None,
- // `DataSource` is a closed enum of upstream connectors and names no
- // orchestration eviction, so no variant is *true* here. It is also
- // not stored: the document canonicaliser keeps only body,
- // modified_at and source_ref, and chunk `Metadata` has no provider
- // column at all. `Upload` is the honest shape of the three that do
- // survive — content that arrived once with no upstream to refetch —
- // and the eviction's own provenance rides on `source_id`, the tags
- // and `path_scope`, all of which are preserved verbatim below.
- source: DataSource::Upload,
- source_id: source_id.clone(),
- owner: "user".to_string(),
- source_ref: Some(SourceRef::new(source_id)),
- content: entry.summary.clone(),
- mime: None,
- timestamp: Some(chrono::Utc::now()),
- tags: vec!["orchestration".to_string(), "evicted".to_string()],
- author: None,
- channel_label: None,
- platform: None,
- // Mail-only fields; this source is not mail, and the contract
- // documents empty/absent as the same statement as "not mail".
- to: Vec::new(),
- cc: Vec::new(),
- subject: None,
- list_unsubscribe: None,
- // The chunk tier cannot carry a non-default taint and the driver
- // rejects an item that claims one, so `Internal` is the only value
- // ingest accepts. It is also the true one: this is the hosted
- // brain's own summary of the user's own conversation, not content
- // synced in from a third-party source.
- taint: MemoryTaint::Internal,
- path_scope: Some("orchestration/evicted".to_string()),
- };
- ingest
- .ingest_document(item)
- .await
- .map_err(|e| format!("evict ingest cycle={}: {e}", entry.cycle_id))?;
- ingested += 1;
- }
- log::debug!(
- target: LOG,
- "[orchestration] effect.evict.ingested count={ingested} session={}",
- effect.session_id
- );
- Ok(())
-}
-
-/// Handle an inbound `orch:effect:evict` frame end-to-end: parse → dedupe →
-/// mirror into RAG → produce the ack frame. Returns `(callId, ackFrame)` for the
-/// caller to emit over `orch:effect:result`, or `None` when unparseable.
-pub async fn handle_evict(data: &Value) -> Option<(String, Value)> {
- let effect = match parse_evict(data) {
- Ok(e) => e,
- Err(e) => {
- log::warn!(target: LOG, "[orchestration] effect.evict.parse_failed: {e}");
- return None;
- }
- };
-
- if is_duplicate_call(&effect.call_id) {
- log::debug!(
- target: LOG,
- "[orchestration] effect.evict.duplicate call_id={} (re-acking)",
- effect.call_id
- );
- return Some((
- effect.call_id.clone(),
- effect_result_frame(&effect.call_id, true, None),
- ));
- }
-
- let (ok, error) = match execute_evict(&effect).await {
- Ok(()) => (true, None),
- Err(e) => {
- log::warn!(target: LOG, "[orchestration] effect.evict.failed call_id={}: {e}", effect.call_id);
- (false, Some(e))
- }
- };
- if !ok {
- // Un-claim so a redelivery re-runs the eviction instead of re-acking a stale
- // success and losing the summary the brain asked to evict.
- release_call(&effect.call_id);
- }
- Some((
- effect.call_id.clone(),
- effect_result_frame(&effect.call_id, ok, error.as_deref()),
- ))
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::openhuman::config::Config;
-
- #[tokio::test]
- async fn integrations_agent_without_toolkit_is_rejected() {
- // The toolkit guard fires before any registry/provider/network work, so a
- // toolkit-less integrations_agent request is a failure completion rather
- // than an unscoped run over the full Composio surface.
- let (ok, msg) = run_local_subagent(
- &Config::default(),
- "integrations_agent",
- "check gmail",
- None,
- None,
- )
- .await;
- assert!(!ok);
- assert!(
- msg.contains("toolkit"),
- "expected toolkit error, got: {msg}"
- );
- }
-
- #[tokio::test]
- async fn duplicate_run_local_agent_tool_call_is_reacked_without_redispatch() {
- // A redelivered run_local_agent call_id must NOT re-spawn the sub-agent:
- // the guard re-acks accepted/running without dispatching (dispatch would
- // run_local_agent → spawn → forward a duplicate tool_completion).
- let call_id = "call-dup-run-local-agent-test";
- assert!(
- !is_duplicate_call(call_id),
- "first claim is not a duplicate"
- );
- let frame = serde_json::json!({
- "callId": call_id,
- "name": "run_local_agent",
- "cycleId": "cyc:openhuman:local:master:1",
- "args": { "agent_id": "researcher", "prompt": "x" },
- });
- let (cid, result) = handle_tool_call(&frame).await.expect("frame parses");
- assert_eq!(cid, call_id);
- assert_eq!(result["ok"].as_bool(), Some(true));
- assert_eq!(
- result["result"]["duplicate"].as_bool(),
- Some(true),
- "redelivery re-acked as duplicate without re-dispatch"
- );
- release_call(call_id);
- }
-
- #[tokio::test]
- async fn read_only_device_status_is_not_dedup_guarded() {
- // Read-only tools are idempotent: even a previously-seen call_id still
- // dispatches and returns real data — the guard is scoped to
- // side-effecting local-execution tools, never device_status.
- let call_id = "call-device-status-test";
- is_duplicate_call(call_id); // claim it as if already seen
- let frame = serde_json::json!({
- "callId": call_id,
- "name": "device_status",
- "cycleId": "cyc:openhuman:local:master:1",
- "args": {},
- });
- let (_, result) = handle_tool_call(&frame).await.expect("frame parses");
- assert_eq!(result["ok"].as_bool(), Some(true));
- assert!(
- result["result"]["platform"].is_string(),
- "real status returned, not the duplicate placeholder"
- );
- assert!(result["result"].get("duplicate").is_none());
- release_call(call_id);
- }
-
- #[tokio::test]
- async fn failed_run_local_agent_dispatch_releases_claim_for_redelivery() {
- // A run_local_agent on a non-Master (e.g. A2A) cycle is denied by the
- // gate. Its claim must be released so an at-least-once redelivery re-runs
- // and is denied AGAIN — never fabricated as accepted/duplicate (which
- // would strand the brain waiting on a tool_completion that never comes).
- let call_id = "call-a2a-denied-release-test";
- let frame = serde_json::json!({
- "callId": call_id,
- "name": "run_local_agent",
- "cycleId": "cyc:openhuman:a2a:@peer:5", // unregistered → not Master → denied
- "args": { "agent_id": "researcher", "prompt": "x" },
- });
- let (_, first) = handle_tool_call(&frame).await.expect("frame parses");
- assert_eq!(
- first["ok"].as_bool(),
- Some(false),
- "non-Master run_local_agent is denied"
- );
- // Redelivery: the failed claim was released, so it re-dispatches and is
- // denied again — not the duplicate re-ack.
- let (_, second) = handle_tool_call(&frame).await.expect("frame parses");
- assert_eq!(
- second["ok"].as_bool(),
- Some(false),
- "redelivery re-denied, not fabricated-accepted"
- );
- assert!(second["result"].get("duplicate").is_none());
- // Same real denial both times — not a fabricated/different error.
- assert_eq!(first["error"], second["error"]);
- assert!(
- second["error"]
- .as_str()
- .unwrap_or_default()
- .contains("restricted to the Master chat"),
- "the real non-Master denial: {}",
- second["error"]
- );
- release_call(call_id);
- }
-}
diff --git a/src/openhuman/hosted/orchestration/exec_gate.rs b/src/openhuman/hosted/orchestration/exec_gate.rs
deleted file mode 100644
index 0a64326f51..0000000000
--- a/src/openhuman/hosted/orchestration/exec_gate.rs
+++ /dev/null
@@ -1,136 +0,0 @@
-//! Device-authoritative trust gate for local-execution device tools.
-//!
-//! The hosted brain runs in the cloud and can push `orch:tool_call` frames for
-//! device-declared tools. Some of those tools (`run_local_agent` → the local
-//! `code_executor` / workspace workers) execute code and read files on the
-//! user's machine. Those must run **only** for a Master-chat cycle (the human
-//! talking to their own OpenHuman), never for an A2A cycle driven by another
-//! agent's DM — otherwise a prompt-injected reasoning turn could induce local
-//! code execution / file exfiltration (confused deputy).
-//!
-//! The gate is **device-authoritative**: it does not trust any origin the
-//! backend asserts in the tool-call frame (an injected brain could lie). When
-//! the device forwards an event to the hosted brain (`POST /events`) it already
-//! knows the cycle's counterpart, and the backend returns the `cycleId` for
-//! that trigger. We record `cycleId -> counterpart` from *our own* forward, so
-//! at tool-call time we resolve the origin from a fact we established, not one
-//! the backend supplied. Unknown cycles fail closed (denied).
-
-use std::collections::{HashMap, VecDeque};
-use std::sync::Mutex;
-
-use super::types::LOCAL_MASTER_AGENT;
-
-/// Bound on tracked cycles — cycles are short-lived, so a small ring is plenty
-/// and keeps this from growing unbounded over a long session.
-const MAX_TRACKED: usize = 512;
-
-/// The counterpart + session a forwarded cycle belongs to (device-recorded).
-#[derive(Clone)]
-struct CycleTarget {
- counterpart: String,
- session_id: String,
-}
-
-struct CycleOrigins {
- target_by_cycle: HashMap<String, CycleTarget>,
- /// FIFO of cycle ids for bounded eviction of the oldest entries.
- order: VecDeque<String>,
-}
-
-static CYCLE_ORIGINS: Mutex<Option<CycleOrigins>> = Mutex::new(None);
-
-/// Record the counterpart + session a forwarded cycle belongs to. Called at
-/// forward time (`ingest` / master-send → `cloud::push_event`) with the
-/// `cycleId` the backend returned and the counterpart/session *we* addressed the
-/// event to. This is the device-authoritative fact the gate resolves against.
-pub fn record_cycle_origin(cycle_id: &str, counterpart: &str, session_id: &str) {
- if cycle_id.is_empty() {
- return;
- }
- let mut guard = CYCLE_ORIGINS.lock().unwrap_or_else(|p| p.into_inner());
- let store = guard.get_or_insert_with(|| CycleOrigins {
- target_by_cycle: HashMap::new(),
- order: VecDeque::new(),
- });
- let target = CycleTarget {
- counterpart: counterpart.to_string(),
- session_id: session_id.to_string(),
- };
- if store
- .target_by_cycle
- .insert(cycle_id.to_string(), target)
- .is_none()
- {
- store.order.push_back(cycle_id.to_string());
- while store.order.len() > MAX_TRACKED {
- if let Some(old) = store.order.pop_front() {
- store.target_by_cycle.remove(&old);
- }
- }
- }
-}
-
-/// True only when `cycle_id` was recorded as a **local Master-chat** cycle
-/// (counterpart == [`LOCAL_MASTER_AGENT`]). Unknown or A2A cycles → false
-/// (fail closed). This is the authorization for local-execution device tools.
-pub fn cycle_is_master(cycle_id: &str) -> bool {
- let guard = CYCLE_ORIGINS.lock().unwrap_or_else(|p| p.into_inner());
- guard
- .as_ref()
- .and_then(|s| s.target_by_cycle.get(cycle_id))
- .map(|t| t.counterpart == LOCAL_MASTER_AGENT)
- .unwrap_or(false)
-}
-
-/// The `(counterpart, session_id)` a cycle targets, for routing a local
-/// sub-agent's completion back to the right session. `None` for unknown cycles.
-pub fn cycle_target(cycle_id: &str) -> Option<(String, String)> {
- let guard = CYCLE_ORIGINS.lock().unwrap_or_else(|p| p.into_inner());
- guard
- .as_ref()
- .and_then(|s| s.target_by_cycle.get(cycle_id))
- .map(|t| (t.counterpart.clone(), t.session_id.clone()))
-}
-
-/// Device tools that touch local code / files / shell. Denied for any non-Master
-/// cycle. Kept as an explicit allowlist so adding a tool to the manifest can't
-/// silently escape the gate.
-pub fn is_local_execution_tool(name: &str) -> bool {
- matches!(name, "run_local_agent")
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn unknown_cycle_is_not_master() {
- assert!(!cycle_is_master("never-seen"));
- }
-
- #[test]
- fn master_cycle_is_allowed_a2a_is_denied() {
- record_cycle_origin("cyc-master", LOCAL_MASTER_AGENT, "master");
- record_cycle_origin("cyc-peer", "8xPeerBase58Addr", "sess-1");
- assert!(cycle_is_master("cyc-master"));
- assert!(!cycle_is_master("cyc-peer"));
- assert_eq!(
- cycle_target("cyc-master"),
- Some((LOCAL_MASTER_AGENT.to_string(), "master".to_string()))
- );
- }
-
- #[test]
- fn empty_cycle_id_is_ignored_and_denied() {
- record_cycle_origin("", LOCAL_MASTER_AGENT, "master");
- assert!(!cycle_is_master(""));
- assert_eq!(cycle_target(""), None);
- }
-
- #[test]
- fn local_execution_tools_are_gated() {
- assert!(is_local_execution_tool("run_local_agent"));
- assert!(!is_local_execution_tool("device_status"));
- }
-}
diff --git a/src/openhuman/hosted/orchestration/ingest.rs b/src/openhuman/hosted/orchestration/ingest.rs
deleted file mode 100644
index 1cce39f7a6..0000000000
--- a/src/openhuman/hosted/orchestration/ingest.rs
+++ /dev/null
@@ -1,1561 +0,0 @@
-//! DM ingest: decrypt-once → classify → persist → acknowledge.
-//!
-//! Driven by the existing `DomainEvent::TinyPlaceStreamMessage` (the tinyplace
-//! websocket recv loop), filtered to conversation/DM streams. Never logs message
-//! bodies or seeds.
-
-use std::collections::HashSet;
-use std::path::Path;
-
-use base64::Engine as _;
-
-use crate::openhuman::config::Config;
-use crate::openhuman::tinyplace::{acknowledge_message, decrypt_envelope};
-
-use super::presence;
-use super::store;
-use super::types::{
- ChatKind, HarnessEventKind, OrchestrationMessage, OrchestrationSession, SessionEnvelopeV1,
- SessionEnvelopeV2,
-};
-
-const LOG: &str = "orchestration";
-
-/// True when a tiny.place agent id `from` is one of the linked (paired) agents.
-///
-/// tiny.place identifies the *same* Ed25519 key two ways: the orchestration
-/// pairing store keeps the **base58** Solana address (that's what the
-/// contacts/directory API returns and what the pairing UI stores), while an
-/// inbound `MessageEnvelope.from` carries the **base64** Ed25519 public key (the
-/// relay's raw-key form). A plain string compare therefore treats a
-/// legitimately-linked agent as unpaired and silently drops every DM it sends —
-/// so the message never lands in the orchestration view. Compare by the decoded
-/// 32-byte key so the two encodings unify. Fall back to the exact-string check
-/// first (cheap, and covers ids that aren't 32-byte keys, e.g. a handle).
-///
-/// Shared with the contact-request auto-accept gate
-/// (`agent_orchestration::pairing`): "is this id one of my linked agents?" is the
-/// same trust question for an inbound DM and an inbound contact request, so both
-/// resolve it through this single encoding-unifying matcher.
-pub(crate) fn agent_id_in_linked_set(from: &str, linked: &HashSet<String>) -> bool {
- resolve_linked_id(from, linked).is_some()
-}
-
-/// Resolve `from` to the **canonical** linked-set id it matches — the exact
-/// stored string if present, otherwise the stored id whose decoded 32-byte key
-/// equals `from`'s (unifying the base58 pairing-store form and the base64 wire
-/// form of one Ed25519 key). Returns `None` when `from` is not a linked agent.
-///
-/// A caller that then accepts/persists against the match MUST use this canonical
-/// id, not the raw wire id: `PairingStore` dedupes records by exact-string
-/// `agent_id`, so accepting under a base64 `from` while the linked record is
-/// base58 would persist a *second* `Linked` record for the same identity — and
-/// unlinking one encoding would leave the other still authorizing the peer.
-pub(crate) fn resolve_linked_id(from: &str, linked: &HashSet<String>) -> Option<String> {
- if let Some(exact) = linked.get(from) {
- return Some(exact.clone());
- }
- let from_key = decode_agent_key(from)?;
- linked
- .iter()
- .find(|id| decode_agent_key(id) == Some(from_key))
- .cloned()
-}
-
-/// Decode a tiny.place agent identifier to its raw 32-byte Ed25519 public key,
-/// accepting either the base64 (envelope `from`) or base58 (pairing store)
-/// encoding. Returns `None` for anything that isn't a 32-byte key (handles,
-/// malformed ids) so callers fall back to a string compare.
-fn decode_agent_key(value: &str) -> Option<[u8; 32]> {
- // base64 (Ed25519 raw key) — the inbound `MessageEnvelope.from` form.
- if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(value) {
- if let Ok(arr) = <[u8; 32]>::try_from(bytes.as_slice()) {
- return Some(arr);
- }
- }
- // base58 (Solana address) — the pairing-store form.
- if let Ok(bytes) = bs58::decode(value).into_vec() {
- if let Ok(arr) = <[u8; 32]>::try_from(bytes.as_slice()) {
- return Some(arr);
- }
- }
- None
-}
-
-/// A decrypted DM turned into the fields we persist. Pure result of
-/// [`classify_message`] — no IO, so it is unit-testable without a live client.
-#[derive(Debug, Clone, PartialEq, Eq)]
-struct ClassifiedMessage {
- chat_kind: ChatKind,
- session_id: String,
- role: String,
- source: String,
- label: Option<String>,
- workspace: Option<String>,
- /// The wire `line` (v1) / `event.seq` (v2). Retained for parity/debugging only
- /// — persistence deliberately IGNORES it and stamps a store ordinal (#4583).
- seq: i64,
- body: String,
- timestamp: String,
- // ── v2 event shape (all `None`/false for v1 + Master) ────────────────────
- /// v2 `event.kind`; drives the per-message render branch (Phase 2).
- event_kind: Option<String>,
- /// v2 tool identity for `tool_call` / `approval_request`.
- tool_name: Option<String>,
- /// v2 `call_id` correlating `tool_result` → `tool_call`.
- call_id: Option<String>,
- /// v2 `tool_result` outcome (`None` for rows that are not `tool_result`).
- ok: Option<bool>,
- is_error: Option<bool>,
- exit_code: Option<i64>,
- /// v2 `status.state` (or a derived state for approval/lifecycle/error) written
- /// onto the session row so `derive_status` reads a real run-state.
- status_state: Option<String>,
- /// v2 `status.detail` → the session's `current_detail` (roster task line).
- status_detail: Option<String>,
- /// v2 `status.active_call_id` → the session's `active_call_id`.
- active_call_id: Option<String>,
- /// Whether this event advances the monotonic wake ordinal. Content events
- /// (prompts/messages/thinking/tool_call/tool_result/approval/error) do; pure
- /// session-state events (`status`/`lifecycle`/`unknown`) do NOT, so a status
- /// ping never spuriously wakes the front-end graph.
- advances_seq: bool,
- /// True only for an authoritative `status` snapshot, which OWNS the session's
- /// run-state columns and must be able to CLEAR `current_detail`/`active_call_id`
- /// (e.g. `running_tool` → `idle`). Content events leave this false so the
- /// COALESCE upsert preserves the last status instead of wiping it.
- authoritative_status: bool,
- // ── session_info enrichment (only a `session_info` event sets these) ──────
- /// `session_info.title` → the session row's `title`.
- title: Option<String>,
- /// `session_info.model` (or `event.model` fallback) → the session row's `model`.
- model: Option<String>,
- /// `session_info.handle` → the session row's `handle`.
- handle: Option<String>,
- /// `session_info.repo` → the session row's `repo`.
- repo: Option<String>,
- /// `session_info.branch` → the session row's `branch`.
- branch: Option<String>,
- /// `session_info.capabilities` → the session row's `capabilities`.
- capabilities: Vec<String>,
-}
-
-/// True for streams that carry ciphertext DM envelopes worth ingesting.
-fn is_dm_stream(kind: &str, stream_id: &str) -> bool {
- kind.eq_ignore_ascii_case("conversation")
- || kind.eq_ignore_ascii_case("dm")
- || stream_id.starts_with("conversation:")
-}
-
-/// True when a `decrypt_envelope` error is a permanent Signal-layer decryption
-/// failure (no session, bad MAC, malformed ciphertext) rather than a transient
-/// one (key-bundle fetch, network, store IO). `decrypt_envelope` prefixes every
-/// Signal decrypt error with `"decryption failed: "`, so that marker is the
-/// discriminator. Permanent failures are dead-lettered so a single unreadable
-/// envelope can't poison the drain loop forever. Pure.
-fn is_unrecoverable_decrypt_error(err: &str) -> bool {
- err.contains("decryption failed")
-}
-
-/// Stable-sort a batch of envelopes so session-establishing PREKEY_BUNDLE
-/// messages are processed before CIPHERTEXT ones. Pure.
-fn order_prekey_bundles_first(messages: &mut [tinyplace::types::MessageEnvelope]) {
- messages.sort_by_key(|m| {
- u8::from(m.envelope_type != tinyplace::signal::session::TYPE_PREKEY_BUNDLE)
- });
-}
-
-/// Classify a decrypted DM into the fields we persist. Version-dispatched: try a
-/// v2 harness envelope first, then a v1 envelope, else the peer's Master window.
-/// Both envelope versions discriminate on `envelope_version`, so the order is
-/// safe (a v1 body never matches v2 and vice-versa); this is the v1↔v2
-/// coexistence seam — both persist into the same session model. Pure.
-fn classify_message(plaintext: String, fallback_timestamp: &str) -> ClassifiedMessage {
- if let Some(env) = SessionEnvelopeV2::parse(&plaintext) {
- return classify_v2(env, fallback_timestamp);
- }
- if let Some(env) = SessionEnvelopeV1::parse(&plaintext) {
- return classify_v1(env, fallback_timestamp);
- }
- // Not a harness envelope → a plain DM in the peer's Master window.
- //
- // This path only ever runs on an INBOUND, decrypted DM (the counterpart is
- // the sender — see `ingest_one`), so the author is the PEER, never us. Stamp
- // `"peer"` rather than `"user"`: the transcript treats `you`/`owner`/`user`
- // as owner-authored and right-aligns them, so a peer's incoming Master DM was
- // rendering on the owner's side (both halves of a two-way DM stacked right).
- // `"peer"` is not owner-authored → it left-aligns as the counterpart. Our own
- // outgoing Master message is persisted separately as `"owner"` and stays right.
- ClassifiedMessage {
- chat_kind: ChatKind::Master,
- session_id: "master".to_string(),
- role: "peer".to_string(),
- source: String::new(),
- label: None,
- workspace: None,
- seq: 0,
- body: plaintext,
- timestamp: fallback_timestamp.to_string(),
- event_kind: None,
- tool_name: None,
- call_id: None,
- ok: None,
- is_error: None,
- exit_code: None,
- status_state: None,
- status_detail: None,
- active_call_id: None,
- advances_seq: true,
- authoritative_status: false,
- // session_info enrichment — only a v2 `session_info` event populates these.
- title: None,
- model: None,
- handle: None,
- repo: None,
- branch: None,
- capabilities: Vec::new(),
- }
-}
-
-/// Classify a v1 harness envelope — the original per-session mapping, unchanged.
-fn classify_v1(env: SessionEnvelopeV1, fallback_timestamp: &str) -> ClassifiedMessage {
- // Compute the session key while `env` is still fully intact (before any
- // field moves below), since `session_key` borrows `&env`.
- let session_id = env.session_key();
- let label = (env.scope.scope_type == "folder").then(|| env.scope.key.clone());
- let workspace = (!env.scope.cwd.is_empty()).then(|| env.scope.cwd.clone());
- let timestamp = if env.message.timestamp.is_empty() {
- fallback_timestamp.to_string()
- } else {
- env.message.timestamp
- };
- ClassifiedMessage {
- chat_kind: ChatKind::Session,
- // Key on the single per-pair session id (the shared `wrapper_session_id`
- // both peers put on every message for a thread), so a reply threads back
- // into the same session. Falls back to `harness_session_id` for a legacy
- // envelope with no per-pair id. See `SessionEnvelopeV1::session_key`.
- session_id,
- role: env.message.role,
- source: env.harness.provider,
- label,
- workspace,
- seq: env.message.line,
- body: env.message.text,
- timestamp,
- event_kind: None,
- tool_name: None,
- call_id: None,
- ok: None,
- is_error: None,
- exit_code: None,
- status_state: None,
- status_detail: None,
- active_call_id: None,
- advances_seq: true,
- authoritative_status: false,
- // session_info enrichment — only a v2 `session_info` event populates these.
- title: None,
- model: None,
- handle: None,
- repo: None,
- branch: None,
- capabilities: Vec::new(),
- }
-}
-
-/// Classify a v2 harness envelope. Switches on `event.kind`, mapping each to the
-/// persisted fields (per the plan's mapping table). Content events become thread
-/// messages that advance the wake ordinal; `status`/`lifecycle`/`unknown` are
-/// session-state-only (they still persist a row for id-dedupe + ack, but do NOT
-/// advance the wake ordinal). Pure.
-fn classify_v2(env: SessionEnvelopeV2, fallback_timestamp: &str) -> ClassifiedMessage {
- let session_id = env.session_key();
- let label = (env.scope.scope_type == "folder").then(|| env.scope.key.clone());
- let workspace = (!env.scope.cwd.is_empty()).then(|| env.scope.cwd.clone());
- let source = env.harness.provider.clone();
- let timestamp = if env.event.ts.is_empty() {
- fallback_timestamp.to_string()
- } else {
- env.event.ts.clone()
- };
- let kind_str = env.event.kind.clone();
- let wire_role = env.event.role.clone();
- let seq = env.event.seq;
- // `session_info.model` is optional; fall back to the frame's `event.model`.
- let event_model = env.event.model.clone();
-
- // Per-kind body + tool/status fields + wake disposition.
- let mut b = V2Body::default();
- match env.event.decoded() {
- HarnessEventKind::SessionInfo(p) => {
- // Session intro/announce: enrichment, not a chat bubble. Persist a
- // seq=0 row (id-dedupe + ack) that does NOT advance the wake ordinal —
- // same disposition as status/lifecycle — and fold the payload into the
- // session record fields. `title` doubles as the row body so the
- // session_info message carries a human-readable trace of the intro.
- b.body = p.title.clone().unwrap_or_default();
- b.advances_seq = false;
- b.title = p.title;
- b.model = p.model.or(event_model);
- b.handle = p.handle;
- b.repo = p.repo;
- b.branch = p.branch;
- b.capabilities = p.capabilities;
- }
- HarnessEventKind::UserPrompt(p) => {
- b.body = p.text;
- b.default_role = "owner";
- }
- HarnessEventKind::AgentMessage(p) => {
- b.body = p.text;
- }
- HarnessEventKind::AgentThinking(p) => {
- b.body = p.text;
- }
- HarnessEventKind::ToolCall(p) => {
- b.body = p.display;
- b.tool_name = non_empty(p.tool_name);
- b.call_id = non_empty(p.call_id);
- }
- HarnessEventKind::ToolResult(p) => {
- b.body = p.output;
- b.call_id = non_empty(p.call_id);
- // Carry the outcome so the renderer can distinguish a failed run.
- b.ok = p.ok;
- b.is_error = Some(p.is_error);
- b.exit_code = p.exit_code;
- }
- HarnessEventKind::ApprovalRequest(p) => {
- b.body = p.display;
- b.tool_name = non_empty(p.tool_name);
- b.call_id = p.call_id.and_then(non_empty);
- // Drive the roster dot to waiting-approval.
- b.status_state = Some("waiting_approval".to_string());
- }
- HarnessEventKind::Status(p) => {
- b.body = p.detail.clone();
- b.status_state = non_empty(p.state);
- b.status_detail = non_empty(p.detail);
- b.active_call_id = p.active_call_id.and_then(non_empty);
- b.advances_seq = false;
- // Authoritative run-state snapshot: it may CLEAR detail/active_call_id
- // (running_tool → idle), so persistence overwrites rather than COALESCEs.
- b.authoritative_status = true;
- }
- HarnessEventKind::Lifecycle(p) => {
- b.body = p.phase.clone();
- // A session_end lifecycle marks the instance stopped; other phases
- // carry no run-state.
- if p.phase == "session_end" {
- b.status_state = Some("stopped".to_string());
- }
- b.advances_seq = false;
- }
- HarnessEventKind::Error(p) => {
- b.body = p.message;
- b.status_state = Some("errored".to_string());
- }
- HarnessEventKind::Unknown(p) => {
- // Preserve the raw payload as the body so nothing is silently lost.
- b.body = serde_json::to_string(&p.raw).unwrap_or_default();
- b.advances_seq = false;
- // Persist as the literal `unknown` (not the raw wire kind) so the store
- // readers keep a forward/garbled event out of the thread + unread count.
- b.kind_override = Some("unknown");
- }
- }
-
- let role = if !wire_role.is_empty() {
- wire_role
- } else {
- b.default_role.to_string()
- };
-
- ClassifiedMessage {
- chat_kind: ChatKind::Session,
- session_id,
- role,
- source,
- label,
- workspace,
- seq,
- body: b.body,
- timestamp,
- event_kind: Some(b.kind_override.map(str::to_string).unwrap_or(kind_str)),
- tool_name: b.tool_name,
- call_id: b.call_id,
- ok: b.ok,
- is_error: b.is_error,
- exit_code: b.exit_code,
- status_state: b.status_state,
- status_detail: b.status_detail,
- active_call_id: b.active_call_id,
- advances_seq: b.advances_seq,
- authoritative_status: b.authoritative_status,
- title: b.title,
- model: b.model,
- handle: b.handle,
- repo: b.repo,
- branch: b.branch,
- capabilities: b.capabilities,
- }
-}
-
-/// Per-kind accumulator for [`classify_v2`], so the big match stays a set of small
-/// assignments with sensible defaults (content event, `agent` role).
-struct V2Body {
- body: String,
- default_role: &'static str,
- tool_name: Option<String>,
- call_id: Option<String>,
- ok: Option<bool>,
- is_error: Option<bool>,
- exit_code: Option<i64>,
- status_state: Option<String>,
- status_detail: Option<String>,
- active_call_id: Option<String>,
- advances_seq: bool,
- authoritative_status: bool,
- /// Overrides the persisted `event_kind` for a forward/garbled kind that
- /// `decoded()` folded to `Unknown`: stored as the literal `"unknown"` so the
- /// store readers keep it out of the thread instead of leaking the raw kind.
- kind_override: Option<&'static str>,
- // ── session_info enrichment (only the `SessionInfo` arm sets these) ───────
- title: Option<String>,
- model: Option<String>,
- handle: Option<String>,
- repo: Option<String>,
- branch: Option<String>,
- capabilities: Vec<String>,
-}
-
-impl Default for V2Body {
- fn default() -> Self {
- V2Body {
- body: String::new(),
- default_role: "agent",
- tool_name: None,
- call_id: None,
- ok: None,
- is_error: None,
- exit_code: None,
- status_state: None,
- status_detail: None,
- active_call_id: None,
- advances_seq: true,
- authoritative_status: false,
- kind_override: None,
- title: None,
- model: None,
- handle: None,
- repo: None,
- branch: None,
- capabilities: Vec::new(),
- }
- }
-}
-
-/// `Some(s)` when non-empty, else `None` — so blank wire strings persist as NULL.
-fn non_empty(s: String) -> Option<String> {
- (!s.is_empty()).then_some(s)
-}
-
-/// Persist a classified message + its session row. Idempotent by `msg_id`;
-/// returns true if a new message row landed. Testable with a tempdir DB.
-/// Persist a classified message. Returns `Some(ingest_seq)` when a new row
-/// landed (the store-assigned per-session ordinal), or `None` when the message
-/// was a duplicate and nothing was written. The seq is the idempotency key the
-/// shadow cloud push (`cloud::push_event`) uploads with.
-fn persist_message(
- workspace_dir: &Path,
- msg_id: &str,
- agent_id: &str,
- classified: &ClassifiedMessage,
- now: &str,
-) -> Result<Option<i64>, String> {
- store::with_connection(workspace_dir, |c| {
- // Wake idempotence keys on a per-session `seq` being monotonic, but the
- // harness `message.line` we classify into `seq` is NOT reliable: a wrapped
- // Claude harness stamps `line = 0` on every DM, and a peer reusing one
- // `wrapper_session_id` across harness sessions can reset it. Under the
- // shared per-pair session key that collapses every message into one
- // session whose `last_seq`/wake cursor then pins at 0, so after the first
- // message the graph is skipped and the DM is silently dropped (#4583).
- //
- // Fix: ignore the wire `line` for ordering and stamp a store-assigned,
- // strictly-increasing per-(agent, session) ingest ordinal. Messages are
- // append-only and deduped-by-id upstream, so `MAX(seq)+1` is monotonic and
- // every genuinely-new DM advances `last_seq` past the cursor → wakes the graph.
- //
- // Allocate the ordinal and write both rows in one IMMEDIATE txn so a
- // concurrent writer on the same session (the drain here vs the graph's
- // `send_dm` reply persist) can't read the same `MAX(seq)` and duplicate it.
- store::in_immediate_txn(c, |c| {
- // Content events advance the monotonic wake ordinal (the #4583 fix);
- // pure session-state events (status/lifecycle/unknown) persist a row
- // for id-dedupe + ack but stamp `seq = 0` so they do NOT advance
- // `last_seq` and therefore never spuriously wake the front-end graph.
- // (`upsert_session` clamps `last_seq` with `MAX(...)`, so a 0 here only
- // refreshes `last_message_at` + the status columns.)
- let ingest_seq = if classified.advances_seq {
- store::next_session_seq(c, agent_id, &classified.session_id)?
- } else {
- 0
- };
- store::upsert_session(
- c,
- &OrchestrationSession {
- session_id: classified.session_id.clone(),
- agent_id: agent_id.to_string(),
- source: classified.source.clone(),
- label: classified.label.clone(),
- workspace: classified.workspace.clone(),
- last_seq: ingest_seq,
- created_at: now.to_string(),
- last_message_at: classified.timestamp.clone(),
- status_state: classified.status_state.clone(),
- current_detail: classified.status_detail.clone(),
- active_call_id: classified.active_call_id.clone(),
- title: classified.title.clone(),
- model: classified.model.clone(),
- handle: classified.handle.clone(),
- repo: classified.repo.clone(),
- branch: classified.branch.clone(),
- capabilities: classified.capabilities.clone(),
- },
- )?;
- // An authoritative `status` snapshot OWNS the run-state columns and may
- // CLEAR them (running_tool → idle); the COALESCE upsert above can't, so
- // overwrite them directly. Content events skip this and keep COALESCE.
- if classified.authoritative_status {
- store::apply_run_state(
- c,
- agent_id,
- &classified.session_id,
- classified.status_state.as_deref(),
- classified.status_detail.as_deref(),
- classified.active_call_id.as_deref(),
- )?;
- }
- let landed = store::insert_message(
- c,
- &OrchestrationMessage {
- id: msg_id.to_string(),
- agent_id: agent_id.to_string(),
- session_id: classified.session_id.clone(),
- chat_kind: classified.chat_kind,
- role: classified.role.clone(),
- body: classified.body.clone(),
- timestamp: classified.timestamp.clone(),
- seq: ingest_seq,
- event_kind: classified.event_kind.clone(),
- tool_name: classified.tool_name.clone(),
- call_id: classified.call_id.clone(),
- ok: classified.ok,
- is_error: classified.is_error,
- exit_code: classified.exit_code,
- },
- )?;
- // An `error` event also records the short cause on the status surface
- // (`orchestration.status.last_error`). Body is a harness error message,
- // never a response body — safe to store (workspace-internal DB).
- if landed && classified.event_kind.as_deref() == Some("error") {
- store::kv_set(c, "orchestration:last_error", &classified.body)?;
- }
- Ok(landed.then_some(ingest_seq))
- })
- })
- .map_err(|e| format!("persist: {e}"))
-}
-
-/// Forward a freshly-landed event to the hosted brain
-/// (`POST /orchestration/v1/events`), which runs the wake cycle server-side.
-/// Builds the sanitized wire envelope (the security allowlist lives in
-/// [`super::wire`]) and spawns the upload so ingest never blocks on the network.
-/// Best-effort/fire-and-forget: a push failure (or offline) is logged and
-/// dropped — the render cache still holds the row and the first-login migration
-/// replay backfills anything missed while offline.
-fn forward_event(
- config: &Config,
- agent_id: &str,
- ingest_seq: i64,
- classified: &ClassifiedMessage,
- now: &str,
-) {
- // Content events carry the real per-session ordinal; a status/lifecycle
- // event stamps seq 0 and would collide on the backend's idempotency key, so
- // only forward seq-advancing events.
- if ingest_seq <= 0 {
- return;
- }
- let ts = super::wire::parse_ts_ms(&classified.timestamp)
- .or_else(|| super::wire::parse_ts_ms(now))
- .unwrap_or(0);
- let kind = classified
- .event_kind
- .as_deref()
- .unwrap_or_else(|| classified.chat_kind.as_str());
- let envelope = super::wire::OrchestrationEventEnvelopeWire::build(
- agent_id,
- &classified.session_id,
- ingest_seq,
- &classified.role,
- // For an inbound DM the sender is the counterpart agent itself.
- agent_id,
- &classified.body,
- ts,
- kind,
- );
- let config = config.clone();
- tokio::spawn(async move {
- match super::cloud::push_event(&config, &envelope).await {
- Ok(cycle_id) => {
- // Device-authoritative origin: record the cycle → counterpart we
- // forwarded, so the local-execution trust gate can resolve this
- // cycle's origin without trusting the backend (see `exec_gate`).
- if let Some(cid) = cycle_id {
- super::exec_gate::record_cycle_origin(
- &cid,
- &envelope.counterpart_agent_id,
- &envelope.session_id,
- );
- }
- }
- Err(e) => log::warn!(target: LOG, "[orchestration] cloud.shadow_push_failed: {e}"),
- }
- });
-}
-
-/// Entry point from the bus subscriber. Cheap no-op when orchestration is
-/// disabled or the stream is not a DM stream.
-pub async fn ingest_stream_message(
- config: &Config,
- kind: &str,
- stream_id: &str,
- raw: &serde_json::Value,
-) {
- if !config.orchestration.enabled {
- return;
- }
- if !is_dm_stream(kind, stream_id) {
- return;
- }
- let envelope: tinyplace::types::MessageEnvelope = match serde_json::from_value(raw.clone()) {
- Ok(env) => env,
- Err(e) => {
- log::debug!(target: LOG, "[orchestration] ingest.skip stream={stream_id} not-an-envelope err={e}");
- return;
- }
- };
- if let Err(e) = ingest_one(config, envelope).await {
- log::warn!(target: LOG, "[orchestration] ingest.error stream={stream_id}: {e}");
- }
-}
-
-async fn ingest_one(
- config: &Config,
- envelope: tinyplace::types::MessageEnvelope,
-) -> Result<(), String> {
- let msg_id = envelope.id.clone();
- let agent_id = envelope.from.clone();
- log::debug!(target: LOG, "[orchestration] ingest.entry id={msg_id} from={agent_id}");
- let workspace_dir = config.workspace_dir.clone();
-
- // 0. Sender gate: only ingest DMs from linked (accepted) pairing agents —
- // i.e. wrapped Codex/Claude sessions. Decrypting advances the Signal
- // ratchet, so an unpaired sender's DM (an ordinary human message) must
- // never be decrypted or consumed here; it stays readable by the existing
- // Messaging UI via messages.list / signal.decryptMessage.
- let linked =
- crate::openhuman::agent::orchestration::pairing::linked_agent_ids(&workspace_dir).await;
- if !agent_id_in_linked_set(&agent_id, &linked) {
- log::debug!(
- target: LOG,
- "[orchestration] ingest.skip_unpaired from={agent_id} linked_count={}",
- linked.len()
- );
- return Ok(());
- }
-
- // 1. Dedupe BEFORE decrypt — protects the non-idempotent Signal ratchet.
- let already = store::with_connection(&workspace_dir, |c| store::message_exists(c, &msg_id))
- .map_err(|e| format!("store lookup: {e}"))?;
- if already {
- // The row already exists but a prior run may have crashed (or the relay
- // ack failed) after persist. Retry the ack so the relay copy is
- // consumed; never re-decrypt or re-publish.
- log::debug!(target: LOG, "[orchestration] ingest.dedupe id={msg_id}");
- if let Err(e) = acknowledge_message(&msg_id).await {
- log::warn!(target: LOG, "[orchestration] ingest.ack_failed_dedupe id={msg_id}: {e}");
- }
- return Ok(());
- }
-
- // 2. Decrypt exactly once, then classify + persist.
- //
- // A Signal-layer decryption failure ("No session", bad MAC, malformed body)
- // is PERMANENT for this envelope: the ratchet state needed to read it is
- // gone or was never established (e.g. a CIPHERTEXT whose establishing
- // PREKEY_BUNDLE was lost, or a session reset on our side). Because we only
- // acknowledge on success (stage 3), leaving such an envelope in the mailbox
- // makes every subsequent drain re-fetch, re-attempt, and re-log it forever —
- // a poison message that also grows the mailbox unboundedly. So dead-letter
- // it: acknowledge (consume) once and move on. Transient errors (bundle
- // fetch, network, store IO) are NOT swallowed — they are returned so the
- // envelope is retried on the next drain.
- let plaintext = match decrypt_envelope(&envelope).await {
- Ok(plaintext) => plaintext,
- Err(e) if is_unrecoverable_decrypt_error(&e) => {
- log::warn!(
- target: LOG,
- "[orchestration] ingest.drop_undecryptable from={agent_id} id={msg_id}: {e}"
- );
- if let Err(ack) = acknowledge_message(&msg_id).await {
- log::warn!(target: LOG, "[orchestration] ingest.ack_failed_drop id={msg_id}: {ack}");
- }
- return Ok(());
- }
- Err(e) => return Err(e),
- };
- // A decryptable inbound envelope proves the peer is reachable right now —
- // feed the live presence map (drives the online/offline indicator).
- presence::mark_seen(&agent_id);
- let classified = classify_message(plaintext, &envelope.timestamp);
- let now = chrono::Utc::now().to_rfc3339();
- let landed = persist_message(&workspace_dir, &msg_id, &agent_id, &classified, &now)?;
-
- // 3. Acknowledge (consume once) + fan out for stages 4/7.
- if let Some(ingest_seq) = landed {
- if let Err(e) = acknowledge_message(&msg_id).await {
- log::warn!(target: LOG, "[orchestration] ingest.ack_failed id={msg_id}: {e}");
- }
-
- // Forward the sanitized event to the hosted brain, which runs the wake
- // cycle and replies via socket effects. The device no longer wakes a
- // local graph.
- forward_event(config, &agent_id, ingest_seq, &classified, &now);
-
- // Record a compact device world-observation for the hosted subconscious
- // tier; the periodic uploader batches these to the world-diff route,
- // whose receipt schedules a steering tick. Never carries the body — only
- // a bounded derived note (see `world_model`).
- let obs_ts = super::wire::parse_ts_ms(&classified.timestamp)
- .or_else(|| super::wire::parse_ts_ms(&now))
- .unwrap_or(0);
- let obs_note = super::world_model::observe_ingest_note(
- &classified.session_id,
- &agent_id,
- classified
- .event_kind
- .as_deref()
- .unwrap_or_else(|| classified.chat_kind.as_str()),
- &classified.body,
- );
- if let Err(e) = store::with_connection(&workspace_dir, |c| {
- store::append_world_obs(c, &classified.session_id, &obs_note, obs_ts)
- }) {
- log::warn!(target: LOG, "[orchestration] world_obs.append_failed id={msg_id}: {e}");
- }
-
- // Live-UI nudge: fan the persisted message to the renderer socket so the
- // affected chat targeted-refetches. Reasoning/reply is the hosted brain's
- // job now — this is presentation only, no wake scheduling.
- super::bus::notify_orchestration_message(
- &agent_id,
- &classified.session_id,
- classified.chat_kind.as_str(),
- );
- }
- log::debug!(
- target: LOG,
- "[orchestration] ingest.exit id={msg_id} landed={}",
- landed.is_some()
- );
- Ok(())
-}
-
-/// Poll the relay mailbox once and run every delivered envelope through the
-/// ingest pipeline.
-///
-/// The relay delivers DMs to `/messages` (poll-only) and — unlike inbox items —
-/// never publishes them to the `/inbox/stream` WebSocket, so a poller is the
-/// only way orchestration learns about inbound DMs. Envelopes from senders that
-/// are not orchestration-linked are skipped by [`ingest_one`] WITHOUT being
-/// decrypted or acknowledged, so they stay in the mailbox for the Messaging UI.
-///
-/// Returns the number of envelopes examined this pass. Best-effort per envelope:
-/// a decrypt/persist failure on one is logged and does not abort the batch.
-pub async fn drain_mailbox_once(config: &Config) -> Result<usize, String> {
- if !config.orchestration.enabled {
- return Ok(0);
- }
- let client = crate::openhuman::tinyplace::ops::global_state()
- .client()
- .await?;
- let signer = client
- .http()
- .signer()
- .ok_or_else(|| "no signer configured".to_string())?;
- let agent_id = signer.agent_id();
- let resp = client
- .messages
- .list(&agent_id, Some(100))
- .await
- .map_err(|e| format!("messages.list: {e}"))?;
- let mut messages = resp.messages;
- let count = messages.len();
- if count > 0 {
- log::debug!(target: LOG, "[orchestration] drain.fetched count={count}");
- }
- // Process session-establishing PREKEY_BUNDLE envelopes before CIPHERTEXT
- // ones: relay list order is not guaranteed chronological, so a first-contact
- // batch could otherwise hand a CIPHERTEXT to `ingest_one` before the
- // PREKEY_BUNDLE that sets up its Signal session, needlessly failing (and,
- // now, dead-lettering) a message that was about to become decryptable. The
- // sort is stable, so same-type envelopes keep their delivered order.
- order_prekey_bundles_first(&mut messages);
- for envelope in messages {
- if let Err(e) = ingest_one(config, envelope).await {
- log::warn!(target: LOG, "[orchestration] drain.ingest_error: {e}");
- }
- }
- Ok(count)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- const ENVELOPE: &str = r#"{
- "envelope_version": "tinyplace.harness.session.v1",
- "version": 1,
- "scope": { "type": "folder", "key": "my-repo", "cwd": "/w",
- "wrapper_session_id": "w1", "harness_session_id": "h1" },
- "harness": { "provider": "codex", "command": "codex", "argv": [] },
- "message": { "id": "m1", "line": 7, "role": "user", "text": "hello",
- "timestamp": "2026-07-02T01:00:00Z" },
- "source": { "path": "p", "record_type": "user" }
- }"#;
-
- #[test]
- fn dm_stream_filter() {
- assert!(is_dm_stream("conversation", "conversation:abc"));
- assert!(is_dm_stream("DM", "x"));
- assert!(is_dm_stream("other", "conversation:abc"));
- assert!(!is_dm_stream("inbox", "inbox"));
- }
-
- #[test]
- fn linked_gate_unifies_base58_and_base64_of_same_key() {
- // Real pair observed in the wild: the pairing store holds the base58
- // Solana address; the inbound `MessageEnvelope.from` holds the base64
- // Ed25519 public key. Both are the same 32-byte key, so a linked agent
- // must be recognised regardless of which encoding arrives.
- let base58 = "7jr5FKYETssD6T1MCzsR4aT4dnjjyJCE2SANYYX1R5vm";
- let base64 = "ZCAAuA+2GVoRrT08Gt8JUVnxnISTelSxnDuyScze334=";
- assert_eq!(
- decode_agent_key(base58),
- decode_agent_key(base64),
- "base58 and base64 forms must decode to the same key"
- );
-
- // Pairing store keeps the base58 address; the DM arrives base64.
- let linked: HashSet<String> = [base58.to_string()].into_iter().collect();
- assert!(
- agent_id_in_linked_set(base64, &linked),
- "a base64 `from` must match a base58-stored linked agent"
- );
-
- // Exact-string match still works (both base58), and the reverse too.
- assert!(agent_id_in_linked_set(base58, &linked));
- let linked_b64: HashSet<String> = [base64.to_string()].into_iter().collect();
- assert!(agent_id_in_linked_set(base58, &linked_b64));
-
- // An unrelated key is still rejected.
- let other = "De6RHrMj6eDqX1WBTXk11sks4WXHMaqEX9A6oQ3ZEmsg";
- assert!(!agent_id_in_linked_set(other, &linked));
-
- // `resolve_linked_id` unifies encodings AND returns the CANONICAL stored
- // id (base58), never the raw base64 wire form — so a caller accepting
- // against the match reuses the one linked record instead of duplicating it.
- assert_eq!(
- resolve_linked_id(base64, &linked).as_deref(),
- Some(base58),
- "a base64 `from` must canonicalize to the stored base58 id"
- );
- assert_eq!(resolve_linked_id(base58, &linked).as_deref(), Some(base58));
- assert_eq!(resolve_linked_id(other, &linked), None);
- }
-
- #[test]
- fn linked_gate_falls_back_to_string_for_non_key_ids() {
- // A handle (not a 32-byte key) can only match by exact string.
- let linked: HashSet<String> = ["@codex-handle".to_string()].into_iter().collect();
- assert!(agent_id_in_linked_set("@codex-handle", &linked));
- assert!(!agent_id_in_linked_set("@other-handle", &linked));
- assert!(decode_agent_key("@codex-handle").is_none());
- }
-
- #[tokio::test]
- async fn drain_is_a_noop_when_orchestration_disabled() {
- // Guard short-circuits before touching the tiny.place client, so this
- // exercises the early return without any wallet/network.
- let mut config = Config::default();
- config.orchestration.enabled = false;
- assert_eq!(drain_mailbox_once(&config).await, Ok(0));
- }
-
- #[test]
- fn classifies_harness_envelope_as_session() {
- let c = classify_message(ENVELOPE.to_string(), "2026-07-02T09:00:00Z");
- assert_eq!(c.chat_kind, ChatKind::Session);
- assert_eq!(c.session_id, "w1"); // keyed on the shared per-pair wrapper_session_id
- assert_eq!(c.role, "user");
- assert_eq!(c.source, "codex");
- assert_eq!(c.label.as_deref(), Some("my-repo")); // folder scope → label
- assert_eq!(c.workspace.as_deref(), Some("/w"));
- assert_eq!(c.seq, 7);
- assert_eq!(c.body, "hello");
- assert_eq!(c.timestamp, "2026-07-02T01:00:00Z"); // envelope ts wins
- }
-
- #[test]
- fn classifies_plain_dm_as_master_with_fallback_timestamp() {
- let c = classify_message("just chatting".to_string(), "2026-07-02T09:00:00Z");
- assert_eq!(c.chat_kind, ChatKind::Master);
- assert_eq!(c.session_id, "master");
- // Inbound Master DMs are peer-authored → NOT an owner-authored role
- // (`you`/`owner`/`user`), so the transcript left-aligns them.
- assert_eq!(c.role, "peer");
- assert!(!["you", "owner", "user"].contains(&c.role.as_str()));
- assert!(c.label.is_none());
- assert_eq!(c.seq, 0);
- assert_eq!(c.body, "just chatting");
- assert_eq!(c.timestamp, "2026-07-02T09:00:00Z"); // fallback used
- }
-
- /// A v2 wire envelope for `kind`/`payload`, keyed on `wrapper` session id.
- fn v2_env(kind: &str, payload: &str, wrapper: &str, role: &str) -> String {
- format!(
- r#"{{
- "envelope_version": "tinyplace.harness.session.v2",
- "version": 2,
- "scope": {{ "type": "folder", "key": "my-repo", "cwd": "/w",
- "wrapper_session_id": "{wrapper}", "harness_session_id": "h2" }},
- "harness": {{ "provider": "claude", "command": "claude", "argv": [] }},
- "event": {{ "id": "e1", "seq": 9, "ts": "2026-07-05T01:00:00Z",
- "role": "{role}", "kind": "{kind}", "payload": {payload} }},
- "source": {{ "path": "p", "record_type": "assistant" }}
- }}"#
- )
- }
-
- #[test]
- fn classifies_v2_content_events_with_kind_and_tool_fields() {
- // agent_message → session message, role from wire, event_kind set.
- let am = classify_message(
- v2_env("agent_message", r#"{ "text": "on it" }"#, "w2", "agent"),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(am.chat_kind, ChatKind::Session);
- assert_eq!(am.session_id, "w2"); // shared wrapper id, same as v1
- assert_eq!(am.source, "claude");
- assert_eq!(am.label.as_deref(), Some("my-repo"));
- assert_eq!(am.role, "agent");
- assert_eq!(am.body, "on it");
- assert_eq!(am.event_kind.as_deref(), Some("agent_message"));
- assert_eq!(am.timestamp, "2026-07-05T01:00:00Z"); // event ts wins
- assert!(am.advances_seq);
-
- // user_prompt defaults role to owner when the wire role is blank.
- let up = classify_message(
- v2_env(
- "user_prompt",
- r#"{ "text": "go", "source": "human" }"#,
- "w2",
- "",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(up.role, "owner");
- assert_eq!(up.body, "go");
-
- // tool_call → body is the display, tool_name + call_id captured.
- let tc = classify_message(
- v2_env(
- "tool_call",
- r#"{ "call_id": "c1", "tool_name": "bash", "tool_kind": "shell", "display": "ls" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(tc.event_kind.as_deref(), Some("tool_call"));
- assert_eq!(tc.body, "ls");
- assert_eq!(tc.tool_name.as_deref(), Some("bash"));
- assert_eq!(tc.call_id.as_deref(), Some("c1"));
- assert!(tc.advances_seq);
-
- // tool_result → body is the output, call_id correlates back to the call.
- let tr = classify_message(
- v2_env(
- "tool_result",
- r#"{ "call_id": "c1", "ok": true, "output": "file.rs", "output_bytes": 7 }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(tr.event_kind.as_deref(), Some("tool_result"));
- assert_eq!(tr.body, "file.rs");
- assert_eq!(tr.call_id.as_deref(), Some("c1"));
- // A successful result carries ok=true / is_error=false, exit_code absent.
- assert_eq!(tr.ok, Some(true));
- assert_eq!(tr.is_error, Some(false));
- assert_eq!(tr.exit_code, None);
-
- // A FAILED tool_result carries the outcome so the renderer can flag it red.
- let tr_err = classify_message(
- v2_env(
- "tool_result",
- r#"{ "call_id": "c1", "ok": false, "is_error": true, "exit_code": 1, "output": "boom" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(tr_err.ok, Some(false));
- assert_eq!(tr_err.is_error, Some(true));
- assert_eq!(tr_err.exit_code, Some(1));
-
- // Older/partial payloads may omit `ok`; keep it unknown instead of
- // defaulting to failure.
- let tr_unknown = classify_message(
- v2_env(
- "tool_result",
- r#"{ "call_id": "c1", "is_error": false, "output": "done" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(tr_unknown.ok, None);
- assert_eq!(tr_unknown.is_error, Some(false));
- assert_eq!(tr_unknown.exit_code, None);
-
- // Non-tool_result rows leave the outcome fields unset.
- assert_eq!(tc.ok, None);
- assert_eq!(tc.is_error, None);
- assert_eq!(am.ok, None);
- }
-
- #[test]
- fn classifies_v2_status_and_approval_and_error_run_state() {
- // status → session-state-only: sets status_state/detail, does NOT advance seq.
- let st = classify_message(
- v2_env(
- "status",
- r#"{ "state": "running_tool", "detail": "compiling", "active_call_id": "c1" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(st.event_kind.as_deref(), Some("status"));
- assert_eq!(st.status_state.as_deref(), Some("running_tool"));
- assert_eq!(st.status_detail.as_deref(), Some("compiling"));
- assert_eq!(st.active_call_id.as_deref(), Some("c1"));
- assert!(!st.advances_seq, "status must not advance the wake ordinal");
- assert!(
- st.authoritative_status,
- "a status snapshot owns the run-state columns (may clear them)"
- );
-
- // approval_request → drives waiting_approval, keeps advancing (owner must act).
- let ar = classify_message(
- v2_env(
- "approval_request",
- r#"{ "call_id": "c9", "tool_name": "rm", "display": "rm -rf x" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(ar.status_state.as_deref(), Some("waiting_approval"));
- assert_eq!(ar.tool_name.as_deref(), Some("rm"));
- assert!(ar.advances_seq);
- assert!(
- !ar.authoritative_status,
- "approval sets status_state but is not a run-state snapshot (COALESCE)"
- );
-
- // error → errored run-state + body is the message.
- let er = classify_message(
- v2_env(
- "error",
- r#"{ "message": "boom", "fatal": true }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(er.status_state.as_deref(), Some("errored"));
- assert_eq!(er.body, "boom");
-
- // lifecycle session_end → stopped, session-state-only.
- let lc = classify_message(
- v2_env("lifecycle", r#"{ "phase": "session_end" }"#, "w2", "agent"),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(lc.status_state.as_deref(), Some("stopped"));
- assert!(!lc.advances_seq);
-
- // unknown → dropped from the wake path, raw preserved as body. The raw
- // wire kind ("teleport") is normalized to the literal "unknown" so store
- // readers keep it out of the thread instead of leaking a forward kind.
- let uk = classify_message(
- v2_env("teleport", r#"{ "flux": 1 }"#, "w2", "agent"),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(uk.event_kind.as_deref(), Some("unknown"));
- assert!(!uk.advances_seq);
- assert!(uk.body.contains("flux"));
- }
-
- #[test]
- fn classifies_v2_session_info_as_session_enrichment() {
- // A full session_info: enrichment fields map onto the session record, the
- // title doubles as the row body, and it does NOT advance the wake ordinal
- // (same disposition as status/lifecycle).
- let si = classify_message(
- v2_env(
- "session_info",
- r#"{ "agent_address": "A1", "handle": "@alice", "title": "myrepo · feat/x",
- "repo": "org/myrepo", "branch": "feat/x", "model": "claude-opus-4-8",
- "capabilities": ["agent_message", "tool_call"], "resumed": false,
- "started_at": "2026-07-08T00:00:00Z" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(si.chat_kind, ChatKind::Session);
- assert_eq!(si.session_id, "w2");
- assert_eq!(si.event_kind.as_deref(), Some("session_info"));
- assert!(
- !si.advances_seq,
- "session_info must not advance the wake ordinal"
- );
- assert!(!si.authoritative_status);
- assert_eq!(si.body, "myrepo · feat/x", "title doubles as the row body");
- assert_eq!(si.title.as_deref(), Some("myrepo · feat/x"));
- assert_eq!(si.model.as_deref(), Some("claude-opus-4-8"));
- assert_eq!(si.handle.as_deref(), Some("@alice"));
- assert_eq!(si.repo.as_deref(), Some("org/myrepo"));
- assert_eq!(si.branch.as_deref(), Some("feat/x"));
- assert_eq!(si.capabilities, vec!["agent_message", "tool_call"]);
- }
-
- #[test]
- fn session_info_model_falls_back_to_event_model() {
- // The payload omits `model`; the frame's `event.model` fills it (spec §2b:
- // "may also ride on event.model").
- let wire = format!(
- r#"{{
- "envelope_version": "tinyplace.harness.session.v2",
- "version": 2,
- "scope": {{ "type": "folder", "key": "my-repo", "cwd": "/w",
- "wrapper_session_id": "w2", "harness_session_id": "h2" }},
- "harness": {{ "provider": "claude", "command": "claude", "argv": [] }},
- "event": {{ "id": "e1", "seq": 0, "ts": "2026-07-05T01:00:00Z",
- "model": "opus-from-frame", "role": "agent",
- "kind": "session_info",
- "payload": {{ "agent_address": "A1" }} }},
- "source": {{ "path": "p", "record_type": "assistant" }}
- }}"#
- );
- let si = classify_message(wire, "2026-07-05T09:00:00Z");
- assert_eq!(si.model.as_deref(), Some("opus-from-frame"));
- assert!(si.title.is_none());
- assert!(si.capabilities.is_empty());
- }
-
- #[test]
- fn persisting_session_info_enriches_session_lazily_and_idempotently() {
- let tmp = tempfile::tempdir().unwrap();
- // session_info is the FIRST event for this session — it must lazy-create
- // the record (enrichment, not a prerequisite), populate the metadata, and
- // stamp last_seq = 0 (no spurious wake).
- let si = classify_message(
- v2_env(
- "session_info",
- r#"{ "agent_address": "A1", "handle": "@alice", "title": "Intro",
- "repo": "org/myrepo", "branch": "feat/x", "model": "opus",
- "capabilities": ["agent_message"], "resumed": false,
- "started_at": "2026-07-08T00:00:00Z" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert!(persist_message(tmp.path(), "si1", "@peer", &si, "now")
- .unwrap()
- .is_some());
- // Re-persisting the SAME event id is idempotent (dedup on the relay id).
- assert!(persist_message(tmp.path(), "si1", "@peer", &si, "now")
- .unwrap()
- .is_none());
-
- store::with_connection(tmp.path(), |c| {
- let s = store::load_session(c, "@peer", "w2")?.expect("session lazy-created");
- assert_eq!(s.title.as_deref(), Some("Intro"));
- assert_eq!(s.model.as_deref(), Some("opus"));
- assert_eq!(s.handle.as_deref(), Some("@alice"));
- assert_eq!(s.repo.as_deref(), Some("org/myrepo"));
- assert_eq!(s.branch.as_deref(), Some("feat/x"));
- assert_eq!(s.capabilities, vec!["agent_message".to_string()]);
- assert_eq!(s.last_seq, 0, "session_info must not advance last_seq");
- assert_eq!(store::count_messages(c, "@peer", "w2")?, 1);
- Ok(())
- })
- .unwrap();
-
- // A reconnect re-intro (resumed=true, NEW event id, refreshed title)
- // UPDATES the record rather than duplicating it, and a content event in
- // between never wipes the intro metadata (COALESCE).
- let content = classify_message(
- v2_env("agent_message", r#"{ "text": "working" }"#, "w2", "agent"),
- "2026-07-05T09:01:00Z",
- );
- assert!(persist_message(tmp.path(), "m1", "@peer", &content, "now")
- .unwrap()
- .is_some());
- let resumed = classify_message(
- v2_env(
- "session_info",
- r#"{ "agent_address": "A1", "title": "Intro v2", "resumed": true,
- "started_at": "2026-07-08T01:00:00Z" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:02:00Z",
- );
- assert!(persist_message(tmp.path(), "si2", "@peer", &resumed, "now")
- .unwrap()
- .is_some());
-
- store::with_connection(tmp.path(), |c| {
- let s = store::load_session(c, "@peer", "w2")?.expect("session");
- assert_eq!(
- s.title.as_deref(),
- Some("Intro v2"),
- "resumed intro refreshes title"
- );
- // Untouched intro fields survive the content event + the thin re-intro.
- assert_eq!(s.model.as_deref(), Some("opus"));
- assert_eq!(s.capabilities, vec!["agent_message".to_string()]);
- // Only the content event advanced the ordinal (seq 1); both session_info
- // rows persist at seq 0.
- assert_eq!(s.last_seq, 1);
- assert_eq!(store::count_messages(c, "@peer", "w2")?, 3);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn v1_and_v2_envelopes_coexist_in_one_session_model() {
- // During rollout a wrapped harness may emit v1 then v2 under the SAME
- // shared wrapper id. Both classify to ChatKind::Session under the same
- // session_id and persist into one session — proving the coexistence seam.
- let tmp = tempfile::tempdir().unwrap();
- let v1 = classify_message(ENVELOPE.to_string(), "2026-07-02T09:00:00Z"); // wrapper w1
- let v2 = classify_message(
- v2_env("agent_message", r#"{ "text": "v2 line" }"#, "w1", "agent"),
- "2026-07-05T09:00:00Z",
- );
- assert_eq!(v1.session_id, "w1");
- assert_eq!(v2.session_id, "w1");
-
- assert!(persist_message(tmp.path(), "m-v1", "@peer", &v1, "now")
- .unwrap()
- .is_some());
- assert!(persist_message(tmp.path(), "m-v2", "@peer", &v2, "now")
- .unwrap()
- .is_some());
- store::with_connection(tmp.path(), |c| {
- // Both rows land in the single "w1" session, seqs monotonic 1,2.
- assert_eq!(store::count_messages(c, "@peer", "w1")?, 2);
- let seqs: Vec<i64> = store::list_recent_messages(c, "@peer", "w1", 10)?
- .iter()
- .map(|m| m.seq)
- .collect();
- assert_eq!(seqs, vec![1, 2]);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn persisting_v2_status_updates_session_row_without_advancing_seq() {
- let tmp = tempfile::tempdir().unwrap();
- // A content message establishes the session at seq 1.
- let msg = classify_message(
- v2_env("agent_message", r#"{ "text": "working" }"#, "w2", "agent"),
- "2026-07-05T09:00:00Z",
- );
- assert!(persist_message(tmp.path(), "m1", "@peer", &msg, "now")
- .unwrap()
- .is_some());
- // A status event follows: it lands a (deduped) row + updates the session
- // status columns, but last_seq must stay at 1 (no spurious wake).
- let status = classify_message(
- v2_env(
- "status",
- r#"{ "state": "running", "detail": "still working", "active_call_id": "c3" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert!(persist_message(tmp.path(), "m2", "@peer", &status, "now")
- .unwrap()
- .is_some());
-
- store::with_connection(tmp.path(), |c| {
- let session = store::load_session(c, "@peer", "w2")?.expect("session exists");
- assert_eq!(session.status_state.as_deref(), Some("running"));
- assert_eq!(session.current_detail.as_deref(), Some("still working"));
- assert_eq!(session.active_call_id.as_deref(), Some("c3"));
- assert_eq!(session.last_seq, 1, "status must not advance last_seq");
- // The status row is persisted (id-dedupe) with its event_kind + seq 0.
- let msgs = store::list_recent_messages(c, "@peer", "w2", 10)?;
- let status_row = msgs
- .iter()
- .find(|m| m.event_kind.as_deref() == Some("status"))
- .expect("status row persisted");
- assert_eq!(status_row.seq, 0);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn a_later_status_snapshot_clears_stale_detail_and_active_call_id() {
- let tmp = tempfile::tempdir().unwrap();
- // running_tool: detail + active_call_id populated.
- let running = classify_message(
- v2_env(
- "status",
- r#"{ "state": "running_tool", "detail": "compiling", "active_call_id": "c1" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert!(persist_message(tmp.path(), "s1", "@peer", &running, "now")
- .unwrap()
- .is_some());
- store::with_connection(tmp.path(), |c| {
- let s = store::load_session(c, "@peer", "w2")?.expect("session");
- assert_eq!(s.current_detail.as_deref(), Some("compiling"));
- assert_eq!(s.active_call_id.as_deref(), Some("c1"));
- Ok(())
- })
- .unwrap();
-
- // idle: the harness went quiet — detail + active_call_id are absent. The
- // authoritative snapshot must CLEAR them, not keep the stale "compiling"/c1
- // (the COALESCE upsert alone would preserve them — the bug this fixes).
- let idle = classify_message(
- v2_env("status", r#"{ "state": "idle" }"#, "w2", "agent"),
- "2026-07-05T09:01:00Z",
- );
- assert!(persist_message(tmp.path(), "s2", "@peer", &idle, "now")
- .unwrap()
- .is_some());
- store::with_connection(tmp.path(), |c| {
- let s = store::load_session(c, "@peer", "w2")?.expect("session");
- assert_eq!(s.status_state.as_deref(), Some("idle"));
- assert_eq!(s.current_detail, None, "stale detail must be cleared");
- assert_eq!(
- s.active_call_id, None,
- "stale active_call_id must be cleared"
- );
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn a_content_event_never_wipes_a_live_status() {
- let tmp = tempfile::tempdir().unwrap();
- // Establish a live run-state via a status snapshot.
- let running = classify_message(
- v2_env(
- "status",
- r#"{ "state": "running_tool", "detail": "compiling", "active_call_id": "c1" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert!(persist_message(tmp.path(), "s1", "@peer", &running, "now")
- .unwrap()
- .is_some());
- // A content event (agent_message) carries no run-state — it must COALESCE,
- // preserving the live status rather than nulling it.
- let msg = classify_message(
- v2_env(
- "agent_message",
- r#"{ "text": "still going" }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:30Z",
- );
- assert!(persist_message(tmp.path(), "m1", "@peer", &msg, "now")
- .unwrap()
- .is_some());
- store::with_connection(tmp.path(), |c| {
- let s = store::load_session(c, "@peer", "w2")?.expect("session");
- assert_eq!(s.status_state.as_deref(), Some("running_tool"));
- assert_eq!(s.current_detail.as_deref(), Some("compiling"));
- assert_eq!(s.active_call_id.as_deref(), Some("c1"));
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn persisting_v2_error_records_last_error() {
- let tmp = tempfile::tempdir().unwrap();
- let err = classify_message(
- v2_env(
- "error",
- r#"{ "message": "rate limited", "fatal": false }"#,
- "w2",
- "agent",
- ),
- "2026-07-05T09:00:00Z",
- );
- assert!(persist_message(tmp.path(), "e1", "@peer", &err, "now")
- .unwrap()
- .is_some());
- store::with_connection(tmp.path(), |c| {
- assert_eq!(
- store::kv_get(c, "orchestration:last_error")?.as_deref(),
- Some("rate limited")
- );
- let session = store::load_session(c, "@peer", "w2")?.unwrap();
- assert_eq!(session.status_state.as_deref(), Some("errored"));
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn persist_message_is_idempotent_and_buckets_by_session() {
- let tmp = tempfile::tempdir().unwrap();
- let session = classify_message(ENVELOPE.to_string(), "2026-07-02T09:00:00Z");
- let master = classify_message("hi".to_string(), "2026-07-02T09:00:00Z");
-
- assert!(persist_message(tmp.path(), "m1", "@peer", &session, "now")
- .unwrap()
- .is_some());
- // Replay of the same relay id does not double-insert.
- assert!(persist_message(tmp.path(), "m1", "@peer", &session, "now")
- .unwrap()
- .is_none());
- assert!(persist_message(tmp.path(), "m2", "@peer", &master, "now")
- .unwrap()
- .is_some());
-
- store::with_connection(tmp.path(), |c| {
- assert_eq!(store::count_messages(c, "@peer", "w1")?, 1); // per-pair wrapper id
- assert_eq!(store::count_messages(c, "@peer", "master")?, 1);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn persist_stamps_monotonic_ingest_seq_so_line_zero_dms_still_wake() {
- // Regression for the silent drop (#4583). A wrapped Claude harness stamps
- // `line = 0` on EVERY DM, so pre-fix both messages classified to seq 0;
- // under the shared wrapper-session key the wake cursor pinned at 0 and the
- // second message was persisted + acked but never woke the graph (no reply).
- // Persist must ignore the wire `line` and stamp a strictly-increasing
- // per-(agent, session) ingest ordinal so `last_seq` advances past the cursor.
- let tmp = tempfile::tempdir().unwrap();
- let line_zero = || {
- classify_message(
- ENVELOPE.replace("\"line\": 7", "\"line\": 0"),
- "2026-07-02T09:00:00Z",
- )
- };
- let first = line_zero();
- let second = line_zero();
- assert_eq!(first.seq, 0); // wire line is 0 for both …
- assert_eq!(second.seq, 0);
-
- assert!(persist_message(tmp.path(), "mA", "@peer", &first, "now")
- .unwrap()
- .is_some());
- assert!(persist_message(tmp.path(), "mB", "@peer", &second, "now")
- .unwrap()
- .is_some());
-
- store::with_connection(tmp.path(), |c| {
- // … but the persisted seqs are monotonic ingest ordinals 1 and 2, and
- // last_seq advanced to 2 — so a wake cursor left at 1 sees new work.
- assert_eq!(store::count_messages(c, "@peer", "w1")?, 2);
- assert_eq!(store::session_last_seq(c, "@peer", "w1")?, Some(2));
- let seqs: Vec<i64> = store::list_recent_messages(c, "@peer", "w1", 10)?
- .iter()
- .map(|m| m.seq)
- .collect();
- assert_eq!(seqs, vec![1, 2]);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn unrecoverable_decrypt_errors_are_dead_lettered_but_transient_ones_are_not() {
- // Signal-layer failures (prefixed "decryption failed:" by decrypt_envelope)
- // are permanent for the envelope and must be dropped so they can't poison
- // the drain loop forever — this is the "No session" case from the bug.
- assert!(is_unrecoverable_decrypt_error(
- "decryption failed: invalid argument: No session for De6RHrMj6eDqX1WBTXk11sks"
- ));
- assert!(is_unrecoverable_decrypt_error("decryption failed: bad MAC"));
- // Transient failures must be retried, not swallowed.
- assert!(!is_unrecoverable_decrypt_error(
- "HTTP 503: /keys/abc/bundle"
- ));
- assert!(!is_unrecoverable_decrypt_error(
- "identity key: store unavailable"
- ));
- assert!(!is_unrecoverable_decrypt_error("messages.list: timeout"));
- }
-
- #[test]
- fn prekey_bundles_are_ordered_before_ciphertext_preserving_relative_order() {
- let env = |id: &str, ty: &str| -> tinyplace::types::MessageEnvelope {
- serde_json::from_value(serde_json::json!({ "id": id, "type": ty })).unwrap()
- };
- // Delivered order interleaves a CIPHERTEXT before the PREKEY_BUNDLE that
- // establishes its session — the ordering race the fix removes.
- let mut batch = vec![
- env("c1", "CIPHERTEXT"),
- env("pk", "PREKEY_BUNDLE"),
- env("c2", "CIPHERTEXT"),
- ];
- order_prekey_bundles_first(&mut batch);
- let ids: Vec<&str> = batch.iter().map(|m| m.id.as_str()).collect();
- // PREKEY_BUNDLE first; CIPHERTEXT keep their delivered order (stable sort).
- assert_eq!(ids, vec!["pk", "c1", "c2"]);
- }
-}
diff --git a/src/openhuman/hosted/orchestration/medulla.rs b/src/openhuman/hosted/orchestration/medulla.rs
deleted file mode 100644
index 91920679e6..0000000000
--- a/src/openhuman/hosted/orchestration/medulla.rs
+++ /dev/null
@@ -1,702 +0,0 @@
-//! Client for the backend's paid Medulla request/response surface.
-//!
-//! OpenHuman supplies its existing local orchestration tools to
-//! `/orchestration/v1/run`, executes requested calls on-device, and returns the
-//! results through `/run/continue` until the cycle ends.
-
-use std::sync::Arc;
-
-use reqwest::Method;
-use serde::{Deserialize, Serialize};
-use serde_json::{json, Map, Value};
-
-use crate::api::config::effective_backend_api_url;
-use crate::api::BackendOAuthClient;
-use crate::openhuman::config::{Config, MedullaClientConfig};
-use crate::openhuman::tools::Tool;
-
-const LOG: &str = "orchestration";
-const RUN_PATH: &str = "/orchestration/v1/run";
-const CONTINUE_PATH: &str = "/orchestration/v1/run/continue";
-const PLAN_PATH: &str = "/payments/stripe/currentPlan";
-const MAX_LOOP_EVENTS: usize = 128;
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-#[serde(rename_all = "camelCase")]
-pub struct MedullaRunResult {
- pub reply: String,
- #[serde(default)]
- pub pass_count: u32,
- #[serde(default)]
- pub compressed_history: Vec<String>,
- #[serde(default)]
- pub escalations: Vec<String>,
- pub session_id: String,
- pub cycle_id: String,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct ToolCall {
- id: String,
- name: String,
- #[serde(default)]
- args: Value,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(tag = "stop", rename_all = "snake_case")]
-enum LoopEvent {
- ToolUse {
- #[serde(rename = "cycleId")]
- cycle_id: String,
- #[serde(rename = "sessionId")]
- session_id: String,
- #[serde(rename = "toolCalls")]
- tool_calls: Vec<ToolCall>,
- },
- End {
- #[serde(flatten)]
- result: MedullaRunResult,
- },
- Pending {
- #[serde(rename = "cycleId")]
- cycle_id: String,
- #[serde(rename = "sessionId")]
- session_id: String,
- },
- Error {
- #[serde(rename = "cycleId")]
- cycle_id: String,
- error: String,
- },
-}
-
-/// Run a Medulla cycle using the signed-in user's paid backend plan. The local
-/// plan lookup is a fail-fast UX guard; the backend remains authoritative and
-/// repeats the paid-plan check on both run endpoints.
-pub async fn run(
- config: &Config,
- input: &str,
- session_id: Option<&str>,
-) -> Result<MedullaRunResult, String> {
- if !config.orchestration.enabled {
- return Err("hosted orchestration is disabled in config".to_string());
- }
- let input = input.trim();
- if input.is_empty() {
- return Err("input is required".to_string());
- }
-
- let token =
- crate::openhuman::security::credentials::session_support::require_live_session_token(
- config,
- )?;
- let api_url = effective_backend_api_url(&config.api_url);
- let client = BackendOAuthClient::new(&api_url).map_err(|err| err.to_string())?;
- ensure_paid_plan(&client, &token).await?;
-
- let tuning = config.orchestration.medulla.clone();
- let config = Arc::new(config.clone());
- let tools: Vec<Box<dyn Tool>> = vec![
- Box::new(super::tools::ListContactsTool),
- Box::new(super::tools::ListSessionsTool::new(Arc::clone(&config))),
- Box::new(super::tools::ReadSessionTool::new(Arc::clone(&config))),
- Box::new(super::tools::SendToAgentTool::new(config)),
- ];
-
- run_with_client(&client, &token, input, session_id, &tools, &tuning).await
-}
-
-async fn ensure_paid_plan(client: &BackendOAuthClient, token: &str) -> Result<(), String> {
- let data = client
- .authed_json(token, Method::GET, PLAN_PATH, None)
- .await
- .map_err(crate::api::flatten_authed_error)?;
- if paid_plan_active(&data) {
- return Ok(());
- }
- Err("Medulla orchestration requires an active Basic or Pro plan".to_string())
-}
-
-fn paid_plan_active(data: &Value) -> bool {
- let plan = data.get("plan").and_then(Value::as_str).unwrap_or_default();
- let active = data
- .get("hasActiveSubscription")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- active && matches!(plan.to_ascii_uppercase().as_str(), "BASIC" | "PRO")
-}
-
-async fn run_with_client(
- client: &BackendOAuthClient,
- token: &str,
- input: &str,
- session_id: Option<&str>,
- tools: &[Box<dyn Tool>],
- tuning: &MedullaClientConfig,
-) -> Result<MedullaRunResult, String> {
- let mut body = Map::new();
- body.insert("input".to_string(), Value::String(input.to_string()));
- if let Some(session_id) = session_id.map(str::trim).filter(|id| !id.is_empty()) {
- body.insert(
- "sessionId".to_string(),
- Value::String(session_id.to_string()),
- );
- }
- if !tools.is_empty() {
- body.insert(
- "tools".to_string(),
- Value::Array(tools.iter().map(|tool| tool_spec(tool.as_ref())).collect()),
- );
- }
- if let Some(options) = tuning_value(tuning) {
- body.insert("options".to_string(), options);
- }
-
- tracing::debug!(
- input_bytes = input.len(),
- tool_count = tools.len(),
- has_session = session_id.is_some(),
- "[orchestration] medulla.run.start"
- );
- let first = post(client, token, RUN_PATH, Value::Object(body)).await?;
- if tools.is_empty() {
- let result = serde_json::from_value(first)
- .map_err(|err| format!("parse Medulla run response: {err}"))?;
- tracing::debug!("[orchestration] medulla.run.end direct=true");
- return Ok(result);
- }
-
- drive_tool_loop(client, token, tools, first).await
-}
-
-async fn drive_tool_loop(
- client: &BackendOAuthClient,
- token: &str,
- tools: &[Box<dyn Tool>],
- mut value: Value,
-) -> Result<MedullaRunResult, String> {
- for event_index in 0..MAX_LOOP_EVENTS {
- let event: LoopEvent = serde_json::from_value(value)
- .map_err(|err| format!("parse Medulla loop event: {err}"))?;
- match event {
- LoopEvent::End { result } => {
- tracing::debug!(
- cycle_id = %result.cycle_id,
- pass_count = result.pass_count,
- events = event_index + 1,
- "[orchestration] medulla.run.end"
- );
- return Ok(result);
- }
- LoopEvent::Error { cycle_id, error } => {
- tracing::warn!(cycle_id = %cycle_id, "[orchestration] medulla.run.error");
- return Err(format!("Medulla cycle {cycle_id} failed: {error}"));
- }
- LoopEvent::Pending {
- cycle_id,
- session_id,
- } => {
- tracing::debug!(
- cycle_id = %cycle_id,
- session_id = %session_id,
- "[orchestration] medulla.run.pending"
- );
- value = continue_run(client, token, &cycle_id, Vec::new()).await?;
- }
- LoopEvent::ToolUse {
- cycle_id,
- session_id,
- tool_calls,
- } => {
- tracing::debug!(
- cycle_id = %cycle_id,
- session_id = %session_id,
- call_count = tool_calls.len(),
- "[orchestration] medulla.run.tool_use"
- );
- let mut results = Vec::with_capacity(tool_calls.len());
- for call in tool_calls {
- results.push(execute_tool_call(tools, call).await);
- }
- value = continue_run(client, token, &cycle_id, results).await?;
- }
- }
- }
- Err(format!(
- "Medulla tool loop exceeded {MAX_LOOP_EVENTS} events"
- ))
-}
-
-async fn execute_tool_call(tools: &[Box<dyn Tool>], call: ToolCall) -> Value {
- let Some(tool) = tools.iter().find(|tool| tool.name() == call.name) else {
- tracing::warn!(tool = %call.name, "[orchestration] medulla.tool.unknown");
- return json!({
- "id": call.id,
- "ok": false,
- "error": format!("unknown OpenHuman tool: {}", call.name),
- });
- };
-
- tracing::debug!(tool = %call.name, call_id = %call.id, "[orchestration] medulla.tool.start");
- match tool.execute(call.args).await {
- Ok(result) if !result.is_error => {
- tracing::debug!(tool = %call.name, call_id = %call.id, "[orchestration] medulla.tool.end");
- json!({ "id": call.id, "ok": true, "result": result.output_for_llm(true) })
- }
- Ok(result) => {
- tracing::warn!(tool = %call.name, call_id = %call.id, "[orchestration] medulla.tool.failed");
- json!({ "id": call.id, "ok": false, "error": result.output() })
- }
- Err(err) => {
- tracing::warn!(tool = %call.name, call_id = %call.id, error = %err, "[orchestration] medulla.tool.failed");
- json!({ "id": call.id, "ok": false, "error": err.to_string() })
- }
- }
-}
-
-async fn continue_run(
- client: &BackendOAuthClient,
- token: &str,
- cycle_id: &str,
- tool_results: Vec<Value>,
-) -> Result<Value, String> {
- post(
- client,
- token,
- CONTINUE_PATH,
- json!({ "cycleId": cycle_id, "toolResults": tool_results }),
- )
- .await
-}
-
-async fn post(
- client: &BackendOAuthClient,
- token: &str,
- path: &str,
- body: Value,
-) -> Result<Value, String> {
- client
- .authed_json(token, Method::POST, path, Some(body))
- .await
- .map_err(crate::api::flatten_authed_error)
-}
-
-fn tool_spec(tool: &dyn Tool) -> Value {
- json!({
- "name": tool.name(),
- "description": tool.description(),
- "parameters": tool.parameters_schema(),
- })
-}
-
-fn tuning_value(tuning: &MedullaClientConfig) -> Option<Value> {
- let prompt_overrides = &tuning.prompt_overrides;
- let prompt_overrides = json_object([
- (
- "ORCHESTRATE_SYSTEM",
- prompt_overrides
- .orchestrate_system
- .as_ref()
- .map(|v| json!(v)),
- ),
- (
- "REASONING_EXECUTE_SYSTEM",
- prompt_overrides
- .reasoning_execute_system
- .as_ref()
- .map(|v| json!(v)),
- ),
- (
- "ORCHESTRATE_RLM_SYSTEM",
- prompt_overrides
- .orchestrate_rlm_system
- .as_ref()
- .map(|v| json!(v)),
- ),
- (
- "COMPRESS_SYSTEM",
- prompt_overrides.compress_system.as_ref().map(|v| json!(v)),
- ),
- (
- "FRONTEND_GATE_SYSTEM",
- prompt_overrides
- .frontend_gate_system
- .as_ref()
- .map(|v| json!(v)),
- ),
- ]);
- let config = &tuning.config;
- let config = json_object([
- ("maxPasses", config.max_passes.map(|v| json!(v))),
- ("maxSteps", config.max_steps.map(|v| json!(v))),
- ("maxDepth", config.max_depth.map(|v| json!(v))),
- (
- "contextWindowTokens",
- config.context_window_tokens.map(|v| json!(v)),
- ),
- (
- "verification",
- config.verification.map(|v| {
- json!(match v {
- crate::openhuman::config::MedullaVerification::Remind => "remind",
- crate::openhuman::config::MedullaVerification::Off => "off",
- })
- }),
- ),
- ]);
- let limits = &tuning.limits;
- let limits = json_object([
- ("maxConcurrency", limits.max_concurrency.map(|v| json!(v))),
- ("maxTokens", limits.max_tokens.map(|v| json!(v))),
- ("deadlineMs", limits.deadline_ms.map(|v| json!(v))),
- (
- "maxTasksPerDelegate",
- limits.max_tasks_per_delegate.map(|v| json!(v)),
- ),
- ("maxDepth", limits.max_depth.map(|v| json!(v))),
- ]);
- let options = json_object([
- ("promptOverrides", prompt_overrides.map(Value::Object)),
- ("config", config.map(Value::Object)),
- ("limits", limits.map(Value::Object)),
- ]);
- options.map(Value::Object)
-}
-
-fn json_object<const N: usize>(entries: [(&str, Option<Value>); N]) -> Option<Map<String, Value>> {
- let object: Map<String, Value> = entries
- .into_iter()
- .filter_map(|(key, value)| value.map(|value| (key.to_string(), value)))
- .collect();
- (!object.is_empty()).then_some(object)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use async_trait::async_trait;
- use wiremock::matchers::{header, method, path};
- use wiremock::{Mock, MockServer, ResponseTemplate};
-
- use crate::openhuman::config::{MedullaCycleConfig, MedullaPromptOverrides};
- use crate::openhuman::tools::ToolResult;
-
- struct EchoTool;
-
- #[async_trait]
- impl Tool for EchoTool {
- fn name(&self) -> &str {
- "echo"
- }
-
- fn description(&self) -> &str {
- "Echo text"
- }
-
- fn parameters_schema(&self) -> Value {
- json!({"type":"object","properties":{"text":{"type":"string"}},"required":["text"]})
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- Ok(ToolResult::success(
- args.get("text").and_then(Value::as_str).unwrap_or_default(),
- ))
- }
- }
-
- struct FailingTool;
-
- #[async_trait]
- impl Tool for FailingTool {
- fn name(&self) -> &str {
- "fail"
- }
-
- fn description(&self) -> &str {
- "Return a tool-level failure"
- }
-
- fn parameters_schema(&self) -> Value {
- json!({"type":"object"})
- }
-
- async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
- Ok(ToolResult::error("expected failure"))
- }
- }
-
- struct ExplodingTool;
-
- #[async_trait]
- impl Tool for ExplodingTool {
- fn name(&self) -> &str {
- "explode"
- }
-
- fn description(&self) -> &str {
- "Return an execution error"
- }
-
- fn parameters_schema(&self) -> Value {
- json!({"type":"object"})
- }
-
- async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
- anyhow::bail!("execution exploded")
- }
- }
-
- fn end_event() -> Value {
- json!({
- "stop":"end",
- "reply":"done",
- "passCount":2,
- "compressedHistory":[],
- "escalations":[],
- "cycleId":"cycle-1",
- "sessionId":"session-1"
- })
- }
-
- fn envelope(data: Value) -> Value {
- json!({"success": true, "data": data})
- }
-
- #[test]
- fn paid_plan_requires_active_basic_or_pro() {
- assert!(paid_plan_active(
- &json!({"plan":"PRO","hasActiveSubscription":true})
- ));
- assert!(paid_plan_active(
- &json!({"plan":"basic","hasActiveSubscription":true})
- ));
- assert!(!paid_plan_active(
- &json!({"plan":"FREE","hasActiveSubscription":true})
- ));
- assert!(!paid_plan_active(
- &json!({"plan":"PRO","hasActiveSubscription":false})
- ));
- }
-
- #[test]
- fn tuning_uses_backend_field_names_and_omits_empty_sections() {
- assert!(tuning_value(&MedullaClientConfig::default()).is_none());
- let tuning = MedullaClientConfig {
- prompt_overrides: MedullaPromptOverrides {
- orchestrate_system: Some("custom".to_string()),
- ..Default::default()
- },
- config: MedullaCycleConfig {
- max_passes: Some(3),
- ..Default::default()
- },
- ..Default::default()
- };
- assert_eq!(
- tuning_value(&tuning),
- Some(json!({
- "promptOverrides": {"ORCHESTRATE_SYSTEM":"custom"},
- "config": {"maxPasses":3}
- }))
- );
- }
-
- #[tokio::test]
- async fn paid_plan_check_accepts_paid_and_rejects_free() {
- for (plan, active, should_pass) in [("PRO", true, true), ("FREE", true, false)] {
- let server = MockServer::start().await;
- Mock::given(method("GET"))
- .and(path(PLAN_PATH))
- .and(header("authorization", "Bearer test-token"))
- .respond_with(ResponseTemplate::new(200).set_body_json(envelope(json!({
- "plan": plan,
- "hasActiveSubscription": active
- }))))
- .mount(&server)
- .await;
-
- let client = BackendOAuthClient::new(&server.uri()).unwrap();
- let result = ensure_paid_plan(&client, "test-token").await;
- assert_eq!(result.is_ok(), should_pass);
- }
- }
-
- #[tokio::test]
- async fn public_run_validates_enabled_and_input_before_credentials() {
- let mut config = Config::default();
- config.orchestration.enabled = false;
- assert_eq!(
- run(&config, "task", None).await.unwrap_err(),
- "hosted orchestration is disabled in config"
- );
-
- config.orchestration.enabled = true;
- assert_eq!(
- run(&config, " ", None).await.unwrap_err(),
- "input is required"
- );
- }
-
- #[tokio::test]
- async fn run_without_tools_returns_direct_result_and_forwards_options() {
- let server = MockServer::start().await;
- Mock::given(method("POST"))
- .and(path(RUN_PATH))
- .and(header("authorization", "Bearer test-token"))
- .respond_with(ResponseTemplate::new(200).set_body_json(envelope(end_event())))
- .mount(&server)
- .await;
-
- let client = BackendOAuthClient::new(&server.uri()).unwrap();
- let tuning = MedullaClientConfig {
- config: MedullaCycleConfig {
- max_passes: Some(4),
- ..Default::default()
- },
- ..Default::default()
- };
- let result = run_with_client(
- &client,
- "test-token",
- "direct",
- Some(" session-1 "),
- &[],
- &tuning,
- )
- .await
- .unwrap();
-
- assert_eq!(result.reply, "done");
- let requests = server.received_requests().await.unwrap();
- let body: Value = serde_json::from_slice(&requests[0].body).unwrap();
- assert_eq!(body["sessionId"], "session-1");
- assert_eq!(body["options"]["config"]["maxPasses"], 4);
- assert!(body.get("tools").is_none());
- }
-
- #[tokio::test]
- async fn pending_event_polls_until_end() {
- let server = MockServer::start().await;
- Mock::given(method("POST"))
- .and(path(CONTINUE_PATH))
- .respond_with(ResponseTemplate::new(200).set_body_json(envelope(end_event())))
- .mount(&server)
- .await;
- let client = BackendOAuthClient::new(&server.uri()).unwrap();
-
- let result = drive_tool_loop(
- &client,
- "test-token",
- &[Box::new(EchoTool)],
- json!({"stop":"pending","cycleId":"cycle-1","sessionId":"session-1"}),
- )
- .await
- .unwrap();
-
- assert_eq!(result.reply, "done");
- let requests = server.received_requests().await.unwrap();
- let body: Value = serde_json::from_slice(&requests[0].body).unwrap();
- assert_eq!(body, json!({"cycleId":"cycle-1","toolResults":[]}));
- }
-
- #[tokio::test]
- async fn error_event_is_returned_with_cycle_context() {
- let server = MockServer::start().await;
- let client = BackendOAuthClient::new(&server.uri()).unwrap();
- let error = drive_tool_loop(
- &client,
- "test-token",
- &[],
- json!({"stop":"error","cycleId":"cycle-bad","error":"budget exceeded"}),
- )
- .await
- .unwrap_err();
-
- assert_eq!(error, "Medulla cycle cycle-bad failed: budget exceeded");
- }
-
- #[tokio::test]
- async fn unknown_and_failed_tools_are_reported_to_backend() {
- let server = MockServer::start().await;
- Mock::given(method("POST"))
- .and(path(CONTINUE_PATH))
- .respond_with(ResponseTemplate::new(200).set_body_json(envelope(end_event())))
- .mount(&server)
- .await;
- let client = BackendOAuthClient::new(&server.uri()).unwrap();
- let tools: Vec<Box<dyn Tool>> = vec![Box::new(FailingTool), Box::new(ExplodingTool)];
-
- drive_tool_loop(
- &client,
- "test-token",
- &tools,
- json!({
- "stop":"tool_use",
- "cycleId":"cycle-1",
- "sessionId":"session-1",
- "toolCalls":[
- {"id":"call-unknown","name":"missing","args":{}},
- {"id":"call-failed","name":"fail","args":{}},
- {"id":"call-exploded","name":"explode","args":{}}
- ]
- }),
- )
- .await
- .unwrap();
-
- let requests = server.received_requests().await.unwrap();
- let body: Value = serde_json::from_slice(&requests[0].body).unwrap();
- assert_eq!(body["toolResults"][0]["ok"], false);
- assert_eq!(
- body["toolResults"][0]["error"],
- "unknown OpenHuman tool: missing"
- );
- assert_eq!(body["toolResults"][1]["error"], "expected failure");
- assert_eq!(body["toolResults"][2]["error"], "execution exploded");
- }
-
- #[tokio::test]
- async fn tool_loop_executes_locally_and_continues_to_end() {
- let server = MockServer::start().await;
- Mock::given(method("POST"))
- .and(path(RUN_PATH))
- .and(header("authorization", "Bearer test-token"))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({
- "success": true,
- "data": {
- "stop":"tool_use",
- "cycleId":"cycle-1",
- "sessionId":"session-1",
- "toolCalls":[{"id":"call-1","name":"echo","args":{"text":"hello"}}]
- }
- })))
- .mount(&server)
- .await;
- Mock::given(method("POST"))
- .and(path(CONTINUE_PATH))
- .respond_with(ResponseTemplate::new(200).set_body_json(envelope(end_event())))
- .mount(&server)
- .await;
-
- let client = BackendOAuthClient::new(&server.uri()).unwrap();
- let tools: Vec<Box<dyn Tool>> = vec![Box::new(EchoTool)];
- let result = run_with_client(
- &client,
- "test-token",
- "use echo",
- None,
- &tools,
- &MedullaClientConfig::default(),
- )
- .await
- .unwrap();
-
- assert_eq!(result.reply, "done");
- assert_eq!(result.pass_count, 2);
- let requests = server.received_requests().await.unwrap();
- let continued: Value = serde_json::from_slice(&requests[1].body).unwrap();
- assert_eq!(continued["toolResults"][0]["result"], "hello");
- }
-}
diff --git a/src/openhuman/hosted/orchestration/migrate_history.rs b/src/openhuman/hosted/orchestration/migrate_history.rs
deleted file mode 100644
index 14330b1a8a..0000000000
--- a/src/openhuman/hosted/orchestration/migrate_history.rs
+++ /dev/null
@@ -1,111 +0,0 @@
-//! First-login migration of local orchestration history to the hosted brain.
-//!
-//! The hosted brain has no import-without-wake route — every `POST /events` may
-//! fire a wake cycle — so a blind bulk replay of the whole local DB would
-//! re-answer long-completed threads. Instead this **resumes only pending work**:
-//! for each session whose most-recent turn is an unanswered `user` ask, it
-//! replays that single turn so the hosted brain picks it up where the retired
-//! local brain left off. Everything else stays viewable in the local render
-//! cache without being re-processed.
-//!
-//! Safe to call on every login: idempotent (the backend upserts on
-//! `(counterpart, session, seq)` and re-runs are 202 no-ops) and one-shot via a
-//! `kv` flag. If a replay fails the flag stays unset so it retries next login.
-
-use crate::openhuman::config::Config;
-
-use super::store;
-use super::wire::OrchestrationEventEnvelopeWire;
-
-const LOG: &str = "orchestration";
-const MIGRATED_FLAG: &str = "orch:history_migrated";
-
-/// Run the one-shot history migration if it hasn't completed yet.
-pub async fn migrate_if_needed(config: &Config) {
- match store::with_connection(&config.workspace_dir, |c| store::kv_get(c, MIGRATED_FLAG)) {
- Ok(Some(_)) => return,
- Ok(None) => {}
- Err(e) => {
- log::warn!(target: LOG, "[orchestration] migrate.flag_read_failed: {e}");
- return;
- }
- }
-
- match resume_pending(config).await {
- Ok(resumed) => {
- if let Err(e) = store::with_connection(&config.workspace_dir, |c| {
- store::kv_set(c, MIGRATED_FLAG, "1")
- }) {
- // Not fatal — replays are idempotent, so a retry next login is safe.
- log::warn!(target: LOG, "[orchestration] migrate.flag_set_failed: {e}");
- }
- log::info!(target: LOG, "[orchestration] migrate.done resumed={resumed}");
- }
- Err(e) => {
- // Leave the flag unset so it retries next login.
- log::warn!(target: LOG, "[orchestration] migrate.failed (will retry next login): {e}");
- }
- }
-}
-
-/// Replay each session's single most-recent turn iff it is a pending `user` ask.
-/// Returns the number of turns replayed.
-async fn resume_pending(config: &Config) -> Result<usize, String> {
- let sessions = store::with_connection(&config.workspace_dir, store::list_sessions)
- .map_err(|e| format!("list sessions: {e}"))?;
-
- let mut resumed = 0usize;
- for session in sessions {
- // Agent-scoped read: `list_sessions` rows are keyed by `(agent_id, session_id)`,
- // and a legacy session id can collide across peers, so read the latest turn
- // for *this* session's `agent_id` — reading by `session_id` alone could replay
- // another peer's ask under `session.agent_id` and wake the wrong conversation.
- let latest = store::with_connection(&config.workspace_dir, |c| {
- store::latest_content_message(c, &session.agent_id, &session.session_id)
- })
- .map_err(|e| format!("latest message session={}: {e}", session.session_id))?;
-
- let Some(msg) = latest else {
- continue;
- };
- // Only a genuinely pending inbound ask is resumed; a thread whose last
- // turn is an assistant/owner/system message is already handled (or not
- // the brain's job) and must not be re-answered. Inbound peer Master DMs
- // are persisted role "peer" (they left-align in the transcript per
- // #4777) but are still a pending ask that must wake the brain on resume,
- // exactly as the live `forward_event` path does — so treat "peer" like
- // "user" here. (The replay envelope re-sanitizes "peer" → "user" in
- // `wire::build`, so the hosted brain sees the same role either way; the
- // distinction is display-only and never reaches inference.)
- if !matches!(msg.role.as_str(), "user" | "peer") || msg.seq <= 0 {
- continue;
- }
-
- let ts = super::wire::parse_ts_ms(&msg.timestamp).unwrap_or(0);
- let envelope = OrchestrationEventEnvelopeWire::build(
- &session.agent_id,
- &session.session_id,
- msg.seq,
- &msg.role,
- &session.agent_id,
- &msg.body,
- ts,
- msg.event_kind.as_deref().unwrap_or("message"),
- );
- let cycle_id = super::cloud::push_event(config, &envelope)
- .await
- .map_err(|e| format!("replay session={} seq={}: {e}", session.session_id, msg.seq))?;
- // Record the resumed cycle's device-authoritative origin so a Master-chat
- // turn resumed by the migration can still authorize `run_local_agent`
- // (otherwise the gate sees an unknown cycle and denies local execution).
- if let Some(cid) = cycle_id {
- super::exec_gate::record_cycle_origin(
- &cid,
- &envelope.counterpart_agent_id,
- &envelope.session_id,
- );
- }
- resumed += 1;
- }
- Ok(resumed)
-}
diff --git a/src/openhuman/hosted/orchestration/mod.rs b/src/openhuman/hosted/orchestration/mod.rs
deleted file mode 100644
index a9458ecf8b..0000000000
--- a/src/openhuman/hosted/orchestration/mod.rs
+++ /dev/null
@@ -1,112 +0,0 @@
-//! Orchestration domain — the device-side client of the **hosted** orchestration
-//! brain.
-//!
-//! The reasoning/wake graph runs server-side (`tinyhumansai/backend`). On the
-//! device this domain is a pure trigger + effect-executor + renderer:
-//!
-//! - [`types`]: the harness `SessionEnvelopeV1` mirror + persisted session/message model.
-//! - [`store`]: SQLite render cache at `<workspace>/orchestration/orchestration.db`.
-//! - [`ingest`]: decrypt-once → dedupe → persist(cache) → forward to the hosted brain.
-//! - [`cloud`]: the hosted uplink (`POST events`/`world-diff`) + read surface (`GET …`).
-//! - [`effect_executor`]: runs `send_dm` / `evict` / `tool_call` effects the brain pushes.
-//! - [`world_diff_uploader`] / [`world_model`]: device world-observations → subconscious tier.
-//! - [`sync`]: hosted reachability for the status/offline surface.
-//! - [`migrate_history`]: one-shot first-login import of local history to the brain.
-
-pub mod attention;
-pub mod bus;
-pub mod cloud;
-pub mod effect_executor;
-pub mod exec_gate;
-pub mod ingest;
-pub mod medulla;
-pub mod migrate_history;
-pub mod ops;
-pub mod presence;
-pub mod schemas;
-pub mod store;
-pub mod sync;
-pub mod tools;
-pub mod types;
-pub mod wire;
-pub mod world_diff_uploader;
-pub mod world_model;
-
-pub use bus::{
- notify_orchestration_message, register_orchestration_ingest_subscriber,
- subscribe_orchestration_socket,
-};
-pub use ops::start_message_drain_supervisor;
-pub use schemas::{all_controller_schemas, all_registered_controllers};
-
-// ── Hosted-client background services (login-gated) ──────────────────────────
-
-use std::sync::Mutex;
-
-use tokio::task::JoinHandle;
-
-use crate::openhuman::config::Config;
-
-/// Join handles for the per-login hosted-client loops (read-sync + world-diff
-/// uploader), so a logout→login aborts the old session's loops before starting
-/// fresh ones — no duplicates, and never a loop bound to a previous session's
-/// config/workspace.
-static HOSTED_CLIENT_TASKS: Mutex<Vec<JoinHandle<()>>> = Mutex::new(Vec::new());
-
-fn abort_hosted_client_tasks() {
- let mut guard = HOSTED_CLIENT_TASKS
- .lock()
- .unwrap_or_else(|p| p.into_inner());
- for handle in guard.drain(..) {
- handle.abort();
- }
-}
-
-/// Start (or restart) the device-side hosted-orchestration client for the active
-/// login: the read-sync loop (hosted read surface → render cache + reachability)
-/// and the world-diff uploader, plus the one-shot idempotent history migration.
-///
-/// Called from `credentials::ops::start_login_gated_services`, so it runs on both
-/// startup (already logged in) and a fresh login. Idempotent: aborts any loops
-/// from a previous session first. No-op (and stops any running loops) when
-/// orchestration is disabled.
-pub async fn start_hosted_client_services(config: &Config) {
- if !config.orchestration.enabled {
- abort_hosted_client_tasks();
- return;
- }
- {
- let mut guard = HOSTED_CLIENT_TASKS
- .lock()
- .unwrap_or_else(|p| p.into_inner());
- for handle in guard.drain(..) {
- handle.abort();
- }
- let sync_cfg = config.clone();
- guard.push(tokio::spawn(async move {
- sync::run_sync_loop(sync_cfg, sync::DEFAULT_SYNC_INTERVAL).await;
- }));
- let flush_cfg = config.clone();
- guard.push(tokio::spawn(async move {
- world_diff_uploader::run_flush_loop(
- flush_cfg,
- world_diff_uploader::DEFAULT_FLUSH_INTERVAL,
- )
- .await;
- }));
- // Fire-and-forget the one-shot history migration so a slow/offline
- // network can't block login-gated startup. Idempotent; the flag stays
- // unset on failure so it retries next login.
- let migrate_cfg = config.clone();
- guard.push(tokio::spawn(async move {
- migrate_history::migrate_if_needed(&migrate_cfg).await;
- }));
- }
- log::info!(target: "orchestration", "[orchestration] hosted-client services started");
-}
-
-/// Stop the hosted-client loops (logout). Symmetric with
-/// [`start_hosted_client_services`].
-pub fn stop_hosted_client_services() {
- abort_hosted_client_tasks();
-}
diff --git a/src/openhuman/hosted/orchestration/ops.rs b/src/openhuman/hosted/orchestration/ops.rs
deleted file mode 100644
index 40f26c54ff..0000000000
--- a/src/openhuman/hosted/orchestration/ops.rs
+++ /dev/null
@@ -1,557 +0,0 @@
-//! Orchestration transport-side helpers (hosted-brain era).
-//!
-//! The wake/reasoning graph runs server-side now; what remains on the device is
-//! the glue the rest of the domain still calls:
-//! - [`start_message_drain_supervisor`]: poll the relay mailbox → ingest → forward.
-//! - [`session_send_plaintext`]: wrap an outgoing reply for a session/Master window.
-//! - [`build_self_identity`]: the device's published identity card.
-//! - attention signals: [`command_center_needs_input`], [`gather_unread_signals`],
-//! [`gather_remote_approval_signals`].
-
-use std::sync::OnceLock;
-
-use serde::Serialize;
-use serde_json::Value;
-
-use crate::openhuman::config::Config;
-
-use super::store;
-use super::types::SessionEnvelopeV1;
-
-const LOG: &str = "orchestration";
-static MESSAGE_DRAIN_SUPERVISOR_STARTED: OnceLock<()> = OnceLock::new();
-
-/// How long the drain supervisor sleeps between cycles.
-///
-/// Named because [`NOT_DISCOVERABLE_WARN_AFTER_CYCLES`] is expressed in cycles
-/// and the escalation message reports elapsed seconds; deriving one from the
-/// other keeps them from drifting apart when the interval is tuned.
-const CYCLE_SLEEP_SECS: u32 = 15;
-
-/// Consecutive supervisor cycles in which this agent is still not discoverable
-/// before the loop escalates the **cause** from `debug` to exactly one `warn`.
-///
-/// The cycle sleeps 15 s, so 4 is ~1 minute — long enough to sit through the
-/// ordinary boot case (the wallet is usually locked for the first cycle or two
-/// and `ensure_signal_keys_published` returns `Err` until it is unlocked),
-/// short enough that a registration that never completes is visible while an
-/// operator is still looking.
-///
-/// Same shape as `platform::socket::ws_loop`'s `FAIL_ESCALATE_THRESHOLD`
-/// (`ws_loop.rs:52`), which solved this exact problem for the socket loop: one
-/// escalated line per run, not one per cycle, so a permanently-locked wallet
-/// costs one `warn` rather than an unbounded stream of them.
-const NOT_DISCOVERABLE_WARN_AFTER_CYCLES: u32 = 4;
-
-/// Whether this cycle is the one that escalates.
-///
-/// Exactly one cycle in a consecutive run qualifies — `==`, not `>=`. Above the
-/// threshold the loop returns to `debug`, which is what keeps a long-running
-/// unregistered instance from re-creating the very problem #5627 is about: an
-/// expected-but-persistent state reported on a repeating timer.
-fn should_escalate_not_discoverable(consecutive_cycles: u32) -> bool {
- consecutive_cycles == NOT_DISCOVERABLE_WARN_AFTER_CYCLES
-}
-
-pub fn start_message_drain_supervisor() {
- if MESSAGE_DRAIN_SUPERVISOR_STARTED.set(()).is_err() {
- log::debug!(target: LOG, "[orchestration] message drain supervisor already running");
- return;
- }
-
- tokio::spawn(async {
- // Receiving DMs is impossible unless this agent has published its Signal
- // keys (peers 404 on the prekey bundle otherwise) — the exact blocker
- // that leaves the orchestration receive loop silently dead. Ensure we
- // are discoverable before/while polling. This mirrors the manual
- // Messaging UI actions but runs automatically for any orchestration-
- // enabled instance. Retry each cycle until confirmed (the wallet may not
- // be unlocked at boot), then stop probing.
- let mut discoverable = false;
- // Consecutive cycles spent still-not-discoverable, for the one-shot
- // escalation below. Reset the moment publication is confirmed.
- let mut not_discoverable_cycles: u32 = 0;
- loop {
- let config = match Config::load_or_init().await {
- Ok(c) => c,
- Err(e) => {
- log::debug!(target: LOG, "[orchestration] drain config load: {e}");
- tokio::time::sleep(std::time::Duration::from_secs(CYCLE_SLEEP_SECS as u64))
- .await;
- continue;
- }
- };
- // Respect the orchestration opt-out. When `[orchestration].enabled` is
- // false we must NOT publish Signal keys (that mutates remote directory
- // state and makes the user discoverable) nor drain the mailbox.
- if !config.orchestration.enabled {
- // Clear the streak while opted out. Cycles spent disabled are
- // not failed publication attempts, so carrying the count across
- // an opt-out would let a single failure after re-enabling trip
- // the threshold immediately — the escalation must mean "four
- // consecutive *attempts* failed", not "four cycles elapsed".
- not_discoverable_cycles = 0;
- tokio::time::sleep(std::time::Duration::from_secs(CYCLE_SLEEP_SECS as u64)).await;
- continue;
- }
- if !discoverable {
- // #5627: the symptom used to be loud and the cause silent —
- // `signal_key_status`'s 404s logged at `warn` every cycle while
- // the reason registration had not completed sat at `debug`. The
- // 404s are now `debug` (they are the expected not-yet-published
- // state); in exchange the *cause* escalates once, here, when a
- // run of cycles proves it is not merely a slow boot.
- //
- // Both arms below share one escalation block: the decision is
- // the same, only the reason text differs.
- match crate::openhuman::tinyplace::ensure_signal_keys_published().await {
- Ok(true) => {
- discoverable = true;
- not_discoverable_cycles = 0;
- log::info!(
- target: LOG,
- "[orchestration] discoverable: Signal keys published — peers can reply"
- );
- }
- // Bound by value so the inner match can consume it — the
- // two non-success outcomes take the same decision and differ
- // only in the reason they report.
- other => {
- let reason = match other {
- Err(e) => format!("last error (wallet locked / no signer?): {e}"),
- _ => "publish was attempted each cycle but never confirmed".to_string(),
- };
- not_discoverable_cycles += 1;
- if should_escalate_not_discoverable(not_discoverable_cycles) {
- let elapsed_secs = not_discoverable_cycles * CYCLE_SLEEP_SECS;
- log::warn!(
- target: LOG,
- "[orchestration] Signal keys still not published after \
- {not_discoverable_cycles} cycles (~{elapsed_secs}s) — this agent \
- is not discoverable and cannot receive DMs; {reason}"
- );
- } else {
- log::debug!(
- target: LOG,
- "[orchestration] ensure_signal_keys not yet confirmed — will retry; {reason}"
- );
- }
- }
- }
- }
- // Auto-accept contact requests from already-linked agents FIRST, so a
- // paired wrapped-agent that re-established contact is unblocked before
- // this same cycle drains its mailbox. Non-linked requesters are left
- // pending for the human (accepting a contact is a trust decision).
- match crate::openhuman::agent::orchestration::pairing::auto_accept_linked_contact_requests(
- &config,
- )
- .await
- {
- Ok(n) if n > 0 => {
- log::info!(target: LOG, "[orchestration] auto-accepted {n} linked contact request(s)")
- }
- Ok(_) => {}
- Err(e) => log::debug!(target: LOG, "[orchestration] auto-accept error: {e}"),
- }
- match super::ingest::drain_mailbox_once(&config).await {
- Ok(n) if n > 0 => {
- log::debug!(target: LOG, "[orchestration] drain: examined {n} envelope(s)")
- }
- Ok(_) => {}
- Err(e) => log::debug!(target: LOG, "[orchestration] drain error: {e}"),
- }
- tokio::time::sleep(std::time::Duration::from_secs(CYCLE_SLEEP_SECS as u64)).await;
- }
- });
-}
-
-/// Wire body for an agent reply into `session_id`: a v1 session envelope for a
-/// real harness session (so the peer threads its reply under the same id), or
-/// the plain body for the pinned Master / subconscious windows.
-pub(crate) fn session_send_plaintext(session_id: &str, body: &str) -> anyhow::Result<String> {
- if session_id == "master" || session_id == "subconscious" {
- return Ok(body.to_string());
- }
- let message_id = format!("session-out:{}", uuid::Uuid::new_v4());
- let now = chrono::Utc::now().to_rfc3339();
- serde_json::to_string(&SessionEnvelopeV1::outgoing(
- session_id,
- body,
- &message_id,
- &now,
- ))
- .map_err(|e| anyhow::anyhow!("envelope encode: {e}"))
-}
-
-// ── Self-identity composition (orchestration_self_identity read model) ────────
-
-/// One @handle this agent's wallet holds (reverse-resolved from the directory).
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub(crate) struct HandleEntry {
- pub(crate) username: String,
- pub(crate) primary: bool,
-}
-
-/// This agent's own tiny.place identity and whether peers can reach it.
-///
-/// `discoverable` is the bottom line the UI cares about: a peer can DM this
-/// agent only if both its directory card AND its Signal encryption key are
-/// published. A fresh identity can accept contacts yet still be un-messageable
-/// until it registers a @handle (which is what publishes both), so the
-/// `SelfIdentityCard` surfaces the gap instead of leaving it a mystery 404.
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub(crate) struct SelfIdentity {
- pub(crate) agent_id: String,
- pub(crate) handles: Vec<HandleEntry>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(crate) primary_handle: Option<String>,
- pub(crate) card_published: bool,
- pub(crate) key_published: bool,
- pub(crate) discoverable: bool,
-}
-
-/// Pure composition of the three tinyplace reads into the renderer shape. Kept
-/// here (business logic) so the parsing/discoverability rules are unit-testable
-/// without a live tiny.place client; the `schemas` handler supplies the reads.
-///
-/// `reverse` is the raw `directory_reverse` JSON (`{ identities: [...] }`), or
-/// `None` on a reverse miss. Discoverable = card live AND encryption key
-/// published + current — either gap leaves the agent un-messageable.
-pub(crate) fn build_self_identity(
- agent_id: String,
- key_published: bool,
- reverse: Option<&Value>,
- card_published: bool,
-) -> SelfIdentity {
- let mut handles: Vec<HandleEntry> = Vec::new();
- let mut primary_handle: Option<String> = None;
- if let Some(idents) = reverse
- .and_then(|r| r.get("identities"))
- .and_then(Value::as_array)
- {
- for ident in idents {
- let username = ident
- .get("username")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let Some(username) = username else { continue };
- let primary = ident
- .get("primary")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- if primary && primary_handle.is_none() {
- primary_handle = Some(username.to_string());
- }
- handles.push(HandleEntry {
- username: username.to_string(),
- primary,
- });
- }
- }
- // Fall back to the first handle when none is flagged primary.
- if primary_handle.is_none() {
- primary_handle = handles.first().map(|h| h.username.clone());
- }
- SelfIdentity {
- agent_id,
- handles,
- primary_handle,
- card_published,
- key_published,
- discoverable: card_published && key_published,
- }
-}
-
-// ── Attention queue aggregation ─────────────────────────────────────────────
-//
-// The `orchestration_attention` handler in [`super::schemas`] awaits the async
-// approval gate itself, then delegates the two synchronous source reads below.
-// Both are best-effort: a source failure degrades to an empty bucket (logged)
-// so the surviving signals still surface. The neutral-signal → item mapping is
-// the pure, unit-tested code in [`super::attention`].
-
-/// Cap on the command-center runs scanned for the `NeedsInput` bucket — the
-/// attention zone only needs the currently-blocked runs, not the full ledger.
-const ATTENTION_RUN_LIMIT: u32 = 100;
-
-/// Fetch the command-center `NeedsInput` bucket as neutral attention signals.
-/// Best-effort — a read error yields an empty vec (logged) so the rest of the
-/// attention queue still assembles.
-///
-/// The ledger query is filtered to `AwaitingUser` runs so [`ATTENTION_RUN_LIMIT`]
-/// bounds *blocked* runs only. Fetching a global recent page then filtering (as
-/// `list_agent_work` does) would let an older still-blocked run be paged out by
-/// newer working/completed runs in a busy workspace, silently dropping it from
-/// the attention queue.
-pub(super) fn command_center_needs_input(
- config: &Config,
-) -> Vec<super::attention::NeedsInputSignal> {
- use crate::openhuman::agent::orchestration::command_center::build_view;
- use tinyagents::session::run_ledger::{list_agent_runs, AgentRunListRequest, AgentRunStatus};
- let request = AgentRunListRequest {
- status: Some(AgentRunStatus::AwaitingUser.as_str().to_string()),
- kind: None,
- parent_run_id: None,
- parent_thread_id: None,
- limit: Some(ATTENTION_RUN_LIMIT),
- offset: None,
- };
- match list_agent_runs(&config.workspace_dir, &request) {
- Ok(response) => {
- super::attention::needs_input_from_command_center(build_view(response.runs))
- }
- Err(e) => {
- log::warn!(target: LOG, "[orchestration_rpc] attention.command_center_failed: {e}");
- Vec::new()
- }
- }
-}
-
-/// Gather unread attention signals from the orchestration store: every non-pinned
-/// session with a positive unread count. The pinned master/subconscious windows
-/// are excluded — they are not agent instances.
-pub(super) fn gather_unread_signals(
- conn: &rusqlite::Connection,
-) -> anyhow::Result<Vec<super::attention::UnreadSignal>> {
- let mut out: Vec<super::attention::UnreadSignal> = Vec::new();
- let unread_counts = store::unread_counts(conn)?;
- for session in store::list_sessions(conn)? {
- if matches!(session.session_id.as_str(), "master" | "subconscious") {
- continue;
- }
- let unread = unread_counts.get(&session.session_id).copied().unwrap_or(0);
- if unread > 0 {
- out.push(super::attention::UnreadSignal {
- session_id: session.session_id,
- label: session.label,
- unread,
- last_message_at: Some(session.last_message_at),
- });
- }
- }
- Ok(out)
-}
-
-/// Gather remote-approval attention signals from the orchestration store: every
-/// session whose persisted v2 run-state is `waiting_approval` (Phase 1 stamps
-/// this — plus the prompt in `current_detail` and the in-flight `active_call_id`
-/// — when a peer harness emits an `approval_request`). Mirrors
-/// [`gather_unread_signals`]: pure store read, the pure mapper
-/// [`super::attention::remote_approval_signals`] does the filtering.
-pub(super) fn gather_remote_approval_signals(
- conn: &rusqlite::Connection,
-) -> anyhow::Result<Vec<super::attention::RemoteApprovalSignal>> {
- let signals = super::attention::remote_approval_signals(store::list_sessions(conn)?);
- for sig in &signals {
- log::debug!(
- target: LOG,
- "[orchestration_rpc] attention.remote_approval session_id={} has_call={}",
- sig.session_id,
- sig.active_call_id.is_some(),
- );
- }
- Ok(signals)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::openhuman::hosted::orchestration::types::{
- OrchestrationMessage, OrchestrationSession,
- };
-
- #[test]
- fn gather_unread_signals_skips_pinned_and_zero_unread() {
- use super::super::types::ChatKind;
- let tmp = tempfile::tempdir().unwrap();
- let config = Config {
- workspace_dir: tmp.path().to_path_buf(),
- ..Config::default()
- };
- let sess = |id: &str, source: &str, label: Option<&str>, at: &str| OrchestrationSession {
- session_id: id.into(),
- agent_id: "@peer".into(),
- source: source.into(),
- label: label.map(str::to_string),
- workspace: None,
- last_seq: 1,
- created_at: "2026-07-06T00:00:00Z".into(),
- last_message_at: at.into(),
- ..Default::default()
- };
- let message = |id: &str, session: &str, kind: ChatKind, at: &str| OrchestrationMessage {
- id: id.into(),
- agent_id: "@peer".into(),
- session_id: session.into(),
- chat_kind: kind,
- role: "user".into(),
- body: "hello".into(),
- timestamp: at.into(),
- seq: 1,
- ..Default::default()
- };
-
- let signals = store::with_connection(&config.workspace_dir, |conn| {
- // Non-pinned session with one unread message → surfaces.
- store::upsert_session(conn, &sess("h-1", "claude", Some("Claude · audit"), "t1"))?;
- store::insert_message(conn, &message("m1", "h-1", ChatKind::Session, "t1"))?;
- // Pinned master with a message → excluded (not an agent instance).
- store::upsert_session(conn, &sess("master", "core", None, "t2"))?;
- store::insert_message(conn, &message("m2", "master", ChatKind::Master, "t2"))?;
- // Non-pinned session with no messages → zero unread, dropped.
- store::upsert_session(conn, &sess("h-quiet", "codex", None, "t0"))?;
- gather_unread_signals(conn)
- })
- .unwrap();
-
- assert_eq!(
- signals.len(),
- 1,
- "only the non-pinned unread session surfaces"
- );
- assert_eq!(signals[0].session_id, "h-1");
- assert_eq!(signals[0].unread, 1);
- assert_eq!(signals[0].label.as_deref(), Some("Claude · audit"));
- }
-
- #[test]
- fn command_center_needs_input_surfaces_only_blocked_runs() {
- use tinyagents::session::run_ledger::{
- upsert_agent_run, AgentRunKind, AgentRunStatus, AgentRunUpsert,
- };
- let tmp = tempfile::tempdir().unwrap();
- let config = Config {
- workspace_dir: tmp.path().to_path_buf(),
- ..Config::default()
- };
- let seed = |id: &str, status: AgentRunStatus| {
- upsert_agent_run(
- &config.workspace_dir,
- AgentRunUpsert {
- id: id.into(),
- kind: AgentRunKind::Subagent,
- parent_run_id: None,
- parent_thread_id: Some("thread-1".into()),
- agent_id: Some("researcher".into()),
- status,
- prompt_ref: None,
- worker_thread_id: None,
- task_board_id: None,
- task_card_id: None,
- checkpoint_path: None,
- checkpoint: None,
- summary: None,
- error: None,
- metadata: serde_json::json!({}),
- started_at: None,
- completed_at: None,
- },
- )
- .unwrap();
- };
- // A blocked run and a working run — only the blocked one is attention-worthy.
- seed("run-blocked", AgentRunStatus::AwaitingUser);
- seed("run-working", AgentRunStatus::Running);
-
- let signals = command_center_needs_input(&config);
- assert_eq!(signals.len(), 1, "only the AwaitingUser run surfaces");
- assert_eq!(signals[0].run_id, "run-blocked");
- }
-
- #[test]
- fn self_identity_marks_published_identity_discoverable() {
- let reverse = serde_json::json!({
- "identities": [
- { "username": " ", "primary": false }, // blank → skipped
- { "username": "openhuman", "primary": false },
- { "username": "oh_primary", "primary": true },
- ]
- });
- let id = build_self_identity("addr123".to_string(), true, Some(&reverse), true);
- assert_eq!(id.agent_id, "addr123");
- assert_eq!(id.handles.len(), 2, "blank username skipped");
- assert_eq!(id.primary_handle.as_deref(), Some("oh_primary"));
- assert!(id.card_published && id.key_published && id.discoverable);
- }
-
- #[test]
- fn self_identity_primary_falls_back_to_first_handle() {
- let reverse = serde_json::json!({
- "identities": [ { "username": "solo" } ] // no primary flag
- });
- let id = build_self_identity("addr".to_string(), true, Some(&reverse), true);
- assert_eq!(id.primary_handle.as_deref(), Some("solo"));
- }
-
- #[test]
- fn self_identity_undiscoverable_when_card_or_key_missing() {
- // No reverse (handle-less), card present but key not published → the
- // exact un-messageable case the SelfIdentityCard must flag.
- let no_key = build_self_identity("addr".to_string(), false, None, true);
- assert!(no_key.handles.is_empty());
- assert!(no_key.primary_handle.is_none());
- assert!(!no_key.discoverable, "key not published → not discoverable");
-
- let no_card = build_self_identity("addr".to_string(), true, None, false);
- assert!(
- !no_card.discoverable,
- "card not published → not discoverable"
- );
- }
-
- fn test_config(tmp: &tempfile::TempDir) -> Config {
- Config {
- workspace_dir: tmp.path().to_path_buf(),
- ..Config::default()
- }
- }
-
- #[test]
- fn session_reply_is_wrapped_but_master_reply_stays_plain() {
- // A real session id → v1 envelope threaded under that id.
- let wire = session_send_plaintext("h-42", "on it").expect("encode");
- let env = SessionEnvelopeV1::parse(&wire).expect("valid v1 envelope");
- assert_eq!(env.scope.harness_session_id, "h-42");
- assert_eq!(env.message.text, "on it");
- // The pinned windows stay plain (no envelope).
- assert_eq!(session_send_plaintext("master", "hi").unwrap(), "hi");
- assert_eq!(session_send_plaintext("subconscious", "hi").unwrap(), "hi");
- }
-
- /// #5627 — the escalation must fire on **exactly one** cycle in a run.
- ///
- /// The point of the threshold is that silencing the 404s (which are the
- /// expected not-yet-published state) must not make a registration that
- /// never completes invisible. So the cause has to become visible — once.
- /// `>=` here would re-create the defect this issue is about in the other
- /// direction: an expected-but-persistent state reported on every tick of a
- /// 15-second timer, forever.
- #[test]
- fn not_discoverable_escalates_once_per_run_not_every_cycle() {
- // Below the threshold: still quiet, so an ordinary boot (wallet locked
- // for a cycle or two) costs nothing.
- for cycles in 0..NOT_DISCOVERABLE_WARN_AFTER_CYCLES {
- assert!(
- !should_escalate_not_discoverable(cycles),
- "cycle {cycles} is below the threshold and must stay at debug"
- );
- }
- // Exactly at the threshold: the one escalated line.
- assert!(
- should_escalate_not_discoverable(NOT_DISCOVERABLE_WARN_AFTER_CYCLES),
- "the threshold cycle must escalate so a stuck registration is visible"
- );
- // Above it: quiet again — one warn per run, not one per cycle.
- for extra in 1..=20 {
- let cycles = NOT_DISCOVERABLE_WARN_AFTER_CYCLES + extra;
- assert!(
- !should_escalate_not_discoverable(cycles),
- "cycle {cycles} is past the threshold and must NOT escalate again"
- );
- }
- }
-}
diff --git a/src/openhuman/hosted/orchestration/presence.rs b/src/openhuman/hosted/orchestration/presence.rs
deleted file mode 100644
index 5c687124a2..0000000000
--- a/src/openhuman/hosted/orchestration/presence.rs
+++ /dev/null
@@ -1,99 +0,0 @@
-//! In-memory peer presence for orchestration contacts / instances.
-//!
-//! Mirrors the devices-tunnel [`PEER_STATUS`](crate::openhuman::security::devices) pattern:
-//! a process-local map keyed by peer `agent_id`, updated whenever we hear from a
-//! peer (any inbound envelope, or a heartbeat `pong`), and read back at
-//! `sessions_list` time to overlay a live `peerOnline` / `lastSeenAt` onto each
-//! session summary. Not persisted — presence is a runtime property.
-//!
-//! Today the only feeder is inbound traffic (`mark_seen` on every ingested peer
-//! envelope), so `is_online` reports a **confident online** (`Some(true)`) within
-//! [`PRESENCE_TTL_MS`] and `None` (unknown → UI falls back to the recency
-//! heuristic) otherwise. Once the cross-session heartbeat ping/pong lands, a
-//! known-but-stale peer becomes a confident **offline** (`Some(false)`); the map
-//! + TTL are already shaped for that (see `mark_seen` callers).
-
-use std::collections::HashMap;
-use std::sync::Mutex;
-
-use once_cell::sync::Lazy;
-
-/// A peer seen within this window is reported online. Sized to sit comfortably
-/// above the planned heartbeat cadence (~30s) so a single missed ping doesn't
-/// flap the indicator.
-pub const PRESENCE_TTL_MS: i64 = 120_000; // 2 minutes
-
-#[derive(Clone, Copy, Debug)]
-struct PeerPresence {
- last_seen_ms: i64,
-}
-
-/// Live peer presence keyed by canonical peer `agent_id`. Process-local; a
-/// restart starts empty and re-learns from the first inbound / heartbeat.
-static PEER_STATUS: Lazy<Mutex<HashMap<String, PeerPresence>>> =
- Lazy::new(|| Mutex::new(HashMap::new()));
-
-fn now_ms() -> i64 {
- chrono::Utc::now().timestamp_millis()
-}
-
-/// Record that we just heard from `agent_id` — call on every inbound peer
-/// envelope and on a heartbeat `pong`. No-op for an empty id.
-pub fn mark_seen(agent_id: &str) {
- if agent_id.trim().is_empty() {
- return;
- }
- log::debug!(target: "orchestration", "[presence] mark_seen agent_id={agent_id}");
- PEER_STATUS.lock().unwrap().insert(
- agent_id.to_string(),
- PeerPresence {
- last_seen_ms: now_ms(),
- },
- );
-}
-
-/// Whether `agent_id` is currently online.
-///
-/// - `Some(true)` — heard from within [`PRESENCE_TTL_MS`].
-/// - `None` — never heard from, or last seen longer ago than the TTL. The UI
-/// treats `None` as "unknown" and falls back to the recency-based `active`
-/// heuristic, so this source can only ever *upgrade* to a confident online
-/// (never assert a false offline before the heartbeat exists).
-pub fn is_online(agent_id: &str) -> Option<bool> {
- let map = PEER_STATUS.lock().unwrap();
- let seen = map.get(agent_id)?;
- (now_ms() - seen.last_seen_ms <= PRESENCE_TTL_MS).then_some(true)
-}
-
-/// ISO-8601 (RFC 3339) last-seen timestamp for `agent_id`, if we've ever heard
-/// from it. `None` when unknown.
-pub fn last_seen_iso(agent_id: &str) -> Option<String> {
- let map = PEER_STATUS.lock().unwrap();
- let seen = map.get(agent_id)?;
- chrono::DateTime::from_timestamp_millis(seen.last_seen_ms).map(|dt| dt.to_rfc3339())
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn unknown_peer_is_none() {
- assert_eq!(is_online("@nobody-xyz"), None);
- assert_eq!(last_seen_iso("@nobody-xyz"), None);
- }
-
- #[test]
- fn mark_seen_marks_online_with_timestamp() {
- let id = "@presence-test-peer";
- mark_seen(id);
- assert_eq!(is_online(id), Some(true));
- assert!(last_seen_iso(id).is_some(), "last-seen recorded");
- }
-
- #[test]
- fn empty_id_is_noop() {
- mark_seen("");
- assert_eq!(is_online(""), None);
- }
-}
diff --git a/src/openhuman/hosted/orchestration/schemas.rs b/src/openhuman/hosted/orchestration/schemas.rs
deleted file mode 100644
index 71670c8418..0000000000
--- a/src/openhuman/hosted/orchestration/schemas.rs
+++ /dev/null
@@ -1,1328 +0,0 @@
-//! JSON-RPC read surface for the orchestration layer.
-//!
-//! Renderer-only controllers (internal registry — never advertised to agents):
-//! the `TinyPlaceOrchestrationTab` reads sessions + messages from the local
-//! render cache (kept in sync with the hosted brain by `sync`), sends Master
-//! steering DMs, and marks chats read. Namespace: `orchestration`; methods
-//! `openhuman.orchestration_*`.
-
-use serde::Serialize;
-use serde_json::{Map, Value};
-
-use crate::core::all::{ControllerFuture, RegisteredController};
-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-use crate::openhuman::config::{rpc as config_rpc, Config};
-
-use super::attention;
-use super::presence;
-use super::store;
-use super::types::{
- ChatKind, OrchestrationMessage, OrchestrationSession, SessionEnvelopeV1, LOCAL_MASTER_AGENT,
-};
-
-/// Active-window: a session is "active" if it saw traffic within this many ms.
-const ACTIVE_WINDOW_MS: i64 = 45 * 60 * 1000;
-const LOG: &str = "orchestration_rpc";
-
-pub fn all_controller_schemas() -> Vec<ControllerSchema> {
- vec![
- schema_for("orchestration_sessions_list"),
- schema_for("orchestration_sessions_create"),
- schema_for("orchestration_messages_list"),
- schema_for("orchestration_send_master_message"),
- schema_for("orchestration_mark_read"),
- schema_for("orchestration_status"),
- schema_for("orchestration_attention"),
- schema_for("orchestration_self_identity"),
- schema_for("orchestration_publish_identity"),
- schema_for("orchestration_relay_info"),
- schema_for("orchestration_run"),
- ]
-}
-
-pub fn all_registered_controllers() -> Vec<RegisteredController> {
- vec![
- RegisteredController {
- schema: schema_for("orchestration_sessions_list"),
- handler: handle_sessions_list,
- },
- RegisteredController {
- schema: schema_for("orchestration_sessions_create"),
- handler: handle_sessions_create,
- },
- RegisteredController {
- schema: schema_for("orchestration_messages_list"),
- handler: handle_messages_list,
- },
- RegisteredController {
- schema: schema_for("orchestration_send_master_message"),
- handler: handle_send_master_message,
- },
- RegisteredController {
- schema: schema_for("orchestration_mark_read"),
- handler: handle_mark_read,
- },
- RegisteredController {
- schema: schema_for("orchestration_status"),
- handler: handle_status,
- },
- RegisteredController {
- schema: schema_for("orchestration_attention"),
- handler: handle_attention,
- },
- RegisteredController {
- schema: schema_for("orchestration_self_identity"),
- handler: handle_self_identity,
- },
- RegisteredController {
- schema: schema_for("orchestration_publish_identity"),
- handler: handle_publish_identity,
- },
- RegisteredController {
- schema: schema_for("orchestration_relay_info"),
- handler: handle_relay_info,
- },
- RegisteredController {
- schema: schema_for("orchestration_run"),
- handler: handle_medulla_run,
- },
- ]
-}
-
-fn schema_for(function: &str) -> ControllerSchema {
- match function {
- "orchestration_sessions_list" => ControllerSchema {
- namespace: "orchestration",
- function: "sessions_list",
- description: "List orchestration chat windows (pinned master + subconscious plus per-session) with computed active + unread counts.",
- inputs: vec![],
- outputs: vec![json_output("result", "{ sessions: SessionSummary[] }.")],
- },
- "orchestration_sessions_create" => ControllerSchema {
- namespace: "orchestration",
- function: "sessions_create",
- description: "Create a new empty orchestration session for a contact (mints a fresh harness session id). Idempotent per (agentId, sessionId).",
- inputs: vec![
- required_str("agentId", "Contact agent id (address) the new session belongs to."),
- optional_str("label", "Optional human-friendly label for the session."),
- ],
- outputs: vec![json_output("result", "{ session: SessionSummary }.")],
- },
- "orchestration_messages_list" => ControllerSchema {
- namespace: "orchestration",
- function: "messages_list",
- description: "List messages for a chat: \"master\", \"subconscious\", or a harness session id.",
- inputs: vec![
- required_str("chat", "Chat key: \"master\" | \"subconscious\" | <sessionId>."),
- optional_str("before", "Exclusive ISO timestamp to page backwards from."),
- FieldSchema {
- name: "limit",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Max messages to return (default 100, capped at 500).",
- required: false,
- },
- ],
- outputs: vec![json_output("result", "{ messages: OrchestrationMessage[] }.")],
- },
- "orchestration_send_master_message" => ControllerSchema {
- namespace: "orchestration",
- function: "send_master_message",
- description: "Send a Master steering DM (owner → front-end agent) over the signal-send op. With a sessionId, sends a session-scoped envelope instead and threads it under that session window.",
- inputs: vec![
- required_str("body", "Message body to send to the Master counterpart."),
- optional_str("recipient", "Recipient agent id; defaults to the latest Master peer."),
- optional_str("sessionId", "Session id to send under; when set the body is wrapped in a v1 session envelope and mirrored into that session window instead of Master."),
- ],
- outputs: vec![json_output("result", "{ ok: bool, messageId?: string }.")],
- },
- "orchestration_mark_read" => ControllerSchema {
- namespace: "orchestration",
- function: "mark_read",
- description: "Advance a chat's read cursor to its newest message.",
- inputs: vec![required_str("chat", "Chat key: \"master\" | \"subconscious\" | <sessionId>.")],
- outputs: vec![json_output("result", "{ ok: bool }.")],
- },
- "orchestration_status" => ControllerSchema {
- namespace: "orchestration",
- function: "status",
- description: "Last subconscious tick and ingest health.",
- inputs: vec![],
- outputs: vec![json_output("result", "OrchestrationStatus.")],
- },
- "orchestration_attention" => ControllerSchema {
- namespace: "orchestration",
- function: "attention",
- description: "Aggregate the \"needs you\" signals across the hub — pending local tool approvals, remote sessions parked on an approval, agent runs awaiting input, and instances with unread messages — into one priority-ordered queue.",
- inputs: vec![],
- outputs: vec![json_output("result", "AttentionQueue { items: AttentionItem[], counts }.")],
- },
- "orchestration_self_identity" => ControllerSchema {
- namespace: "orchestration",
- function: "self_identity",
- description: "This agent's own tiny.place identity + discoverability: agent id (address), reverse-resolved @handles, whether its directory card and Signal encryption key are published, and whether peers can therefore DM it. Composes the tinyplace signal/directory reads.",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "{ agentId, handles: {username, primary}[], primaryHandle?, cardPublished, keyPublished, discoverable }.",
- )],
- },
- "orchestration_publish_identity" => ControllerSchema {
- namespace: "orchestration",
- function: "publish_identity",
- description: "Make this agent discoverable: publish (or refresh) its directory card and Signal encryption key for the current wallet identity, then return the updated self-identity. No @handle registration or payment — repairs the common \"has identity but card/key unpublished\" gap that makes inbound DMs 404. Returns the same shape as self_identity.",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "{ agentId, handles: {username, primary}[], primaryHandle?, cardPublished, keyPublished, discoverable }.",
- )],
- },
- "orchestration_relay_info" => ControllerSchema {
- namespace: "orchestration",
- function: "relay_info",
- description: "The tiny.place relay endpoint the core is talking to, plus a coarse network label (staging | prod) for the renderer's relay badge.",
- inputs: vec![],
- outputs: vec![json_output("result", "{ baseUrl, network }.")],
- },
- "orchestration_run" => ControllerSchema {
- namespace: "orchestration",
- function: "run",
- description: "Run the paid hosted Medulla engine with OpenHuman's local contact/session/send tools. Tool calls execute on this device and are returned through the backend continuation loop until a final reply is available.",
- inputs: vec![
- required_str("input", "The task or prompt for Medulla to orchestrate."),
- optional_str("sessionId", "Optional Medulla session id to continue."),
- ],
- outputs: vec![json_output(
- "result",
- "{ reply, passCount, compressedHistory, escalations, sessionId, cycleId }.",
- )],
- },
- other => unreachable!("unknown orchestration schema: {other}"),
- }
-}
-
-// ── DTOs (camelCase for the renderer) ───────────────────────────────────────
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-struct SessionSummary {
- session_id: String,
- agent_id: String,
- source: String,
- /// The emitting harness (claude/codex/gemini/cursor/windsurf) when this is an external agent
- /// instance; absent for the pinned master/subconscious/user-created windows.
- #[serde(skip_serializing_if = "Option::is_none")]
- harness_type: Option<String>,
- /// Coarse instance status for the roster status dot (see `derive_status`).
- status: String,
- /// One-line current activity (latest message preview) for the roster.
- #[serde(skip_serializing_if = "Option::is_none")]
- current_task: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- label: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- workspace: Option<String>,
- chat_kind: String,
- last_message_at: String,
- unread: i64,
- /// Total persisted messages in the session (all kinds), for the roster's
- /// per-session count. `0` for the pinned windows / a freshly created session.
- message_count: i64,
- active: bool,
- pinned: bool,
- /// Live peer reachability from the in-memory presence map (`presence.rs`).
- /// `Some(true)` = confidently online (heard from within the TTL);
- /// `Some(false)` = confidently offline (heartbeat, once landed); `None` =
- /// unknown → the UI falls back to the recency-based `active`.
- #[serde(skip_serializing_if = "Option::is_none")]
- peer_online: Option<bool>,
- /// ISO-8601 last time we heard from this peer, if ever.
- #[serde(skip_serializing_if = "Option::is_none")]
- last_seen_at: Option<String>,
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-struct OrchestrationStatus {
- #[serde(skip_serializing_if = "Option::is_none")]
- ingest_last_message_at: Option<String>,
- /// Sessions with pending wake work (health signal — persistently > 0 means
- /// the wake loop is stuck).
- ingest_cursor_lag: i64,
- /// Most recent orchestration error, if any (short cause string, never a body).
- #[serde(skip_serializing_if = "Option::is_none")]
- last_error: Option<String>,
- /// Whether the hosted brain was reachable at the last health probe. Drives
- /// the "cloud brain unreachable" offline notice in the renderer.
- cloud_reachable: bool,
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-struct RelayInfo {
- base_url: String,
- network: String,
-}
-
-/// Resolve the `chat` param to a store session id. `master` / `subconscious` map
-/// to their pinned session ids; anything else is treated as a harness session id.
-fn chat_to_session_id(chat: &str) -> &str {
- match chat {
- "master" => "master",
- "subconscious" => "subconscious",
- other => other,
- }
-}
-
-fn chat_kind_for_session(session_id: &str) -> ChatKind {
- match session_id {
- "master" => ChatKind::Master,
- "subconscious" => ChatKind::Subconscious,
- _ => ChatKind::Session,
- }
-}
-
-fn is_active(last_message_at: &str) -> bool {
- match chrono::DateTime::parse_from_rfc3339(last_message_at) {
- Ok(ts) => {
- let age = chrono::Utc::now().signed_duration_since(ts.with_timezone(&chrono::Utc));
- age.num_milliseconds() < ACTIVE_WINDOW_MS
- }
- Err(_) => false,
- }
-}
-
-/// The harness provider for a session, when its `source` names one. Session
-/// windows persist the emitting harness (claude/codex/gemini/cursor/windsurf) in `source` (see
-/// `ingest.rs`); the sentinel windows (master/subconscious/user_created/
-/// orchestration) carry no harness and yield `None`.
-fn harness_type_for(source: &str) -> Option<String> {
- matches!(
- source,
- "claude" | "codex" | "gemini" | "cursor" | "windsurf"
- )
- .then(|| source.to_string())
-}
-
-/// Coarse instance status for the roster dot. Reads the persisted v2 run-state
-/// (`status.state`) when present, mapping it to the renderer's five
-/// `InstanceStatus` values; falls back to recency for v1/legacy sessions that
-/// carry no run-state.
-///
-/// Staleness fallback: a `running`/`running_tool` session that has gone silent
-/// (no recent traffic → `active == false`) is reported `stopped`, so a crashed
-/// instance that never emitted a terminal `status` doesn't sit forever on a stuck
-/// green dot. `waiting_approval`/`errored`/`stopped`/`idle` are honoured as-is —
-/// they are already terminal/blocked states, not "silently alive" ones.
-fn derive_status(status_state: Option<&str>, active: bool) -> &'static str {
- match status_state {
- // Actively working — but downgrade to stopped if the session has gone
- // silent (staleness fallback).
- Some("running") | Some("running_tool") => {
- if active {
- "running"
- } else {
- "stopped"
- }
- }
- Some("waiting_approval") => "waiting-approval",
- Some("idle") => "idle",
- Some("stopped") => "stopped",
- Some("errored") => "errored",
- // No persisted run-state (v1/legacy) or an unrecognised value → the
- // original recency heuristic.
- _ => {
- if active {
- "idle"
- } else {
- "stopped"
- }
- }
- }
-}
-
-/// One-line, UTF-8-safe preview of a message body for the roster task line.
-/// Truncates on a char boundary and reserves room for the ellipsis so the result
-/// never exceeds `MAX` chars (avoids the byte-slice panics noted in the codebase).
-fn task_preview(body: &str) -> String {
- const MAX: usize = 80;
- let trimmed = body.trim();
- if trimmed.chars().count() <= MAX {
- return trimmed.to_string();
- }
- let mut out: String = trimmed.chars().take(MAX - 1).collect();
- out.push('…');
- out
-}
-
-fn summarize(
- session: OrchestrationSession,
- unread: i64,
- pinned: bool,
- current_task: Option<String>,
- message_count: i64,
-) -> SessionSummary {
- let chat_kind = chat_kind_for_session(&session.session_id);
- let active = pinned || is_active(&session.last_message_at);
- let harness_type = harness_type_for(&session.source);
- let status = derive_status(session.status_state.as_deref(), active).to_string();
- // Overlay live peer presence for real peer sessions only (the pinned
- // master/subconscious windows have no remote peer).
- let (peer_online, last_seen_at) = if pinned {
- (None, None)
- } else {
- (
- presence::is_online(&session.agent_id),
- presence::last_seen_iso(&session.agent_id),
- )
- };
- SessionSummary {
- chat_kind: chat_kind.as_str().to_string(),
- active,
- unread,
- message_count,
- pinned,
- harness_type,
- status,
- current_task,
- peer_online,
- last_seen_at,
- session_id: session.session_id,
- agent_id: session.agent_id,
- source: session.source,
- label: session.label,
- workspace: session.workspace,
- last_message_at: session.last_message_at,
- }
-}
-
-// ── Handlers ────────────────────────────────────────────────────────────────
-
-fn handle_sessions_list(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("sessions_list").await?;
- let sessions = store::with_connection(&config.workspace_dir, |conn| {
- let rows = store::list_sessions(conn)?;
- let visible_counts = store::visible_message_counts(conn)?;
- let pinned_visible_counts = store::visible_message_counts_by_session(conn)?;
- let unread_counts = store::unread_counts(conn)?;
- let mut out: Vec<SessionSummary> = Vec::with_capacity(rows.len() + 2);
- let mut have_master = false;
- let mut have_subconscious = false;
- for session in rows {
- let unread = unread_counts.get(&session.session_id).copied().unwrap_or(0);
- match session.session_id.as_str() {
- "master" => have_master = true,
- "subconscious" => have_subconscious = true,
- _ => {}
- }
- let pinned = matches!(session.session_id.as_str(), "master" | "subconscious");
- // Roster task line: prefer the v2 `status.detail` (the harness's own
- // current-activity line / active tool) when present; otherwise fall
- // back to the latest message preview. Pinned windows carry neither.
- let current_task = if pinned {
- None
- } else {
- match session
- .current_detail
- .as_deref()
- .map(str::trim)
- .filter(|d| !d.is_empty())
- {
- Some(detail) => Some(task_preview(detail)),
- None => store::latest_message_preview(
- conn,
- &session.agent_id,
- &session.session_id,
- )?
- .map(|body| task_preview(&body)),
- }
- };
- let message_count = if pinned {
- pinned_visible_counts
- .get(&session.session_id)
- .copied()
- .unwrap_or(0)
- } else {
- visible_counts
- .get(&(session.agent_id.clone(), session.session_id.clone()))
- .copied()
- .unwrap_or(0)
- };
- out.push(summarize(
- session,
- unread,
- pinned,
- current_task,
- message_count,
- ));
- }
- // Ensure the pinned windows always exist even before any traffic.
- if !have_master {
- out.push(pinned_placeholder("master"));
- }
- if !have_subconscious {
- out.push(pinned_placeholder("subconscious"));
- }
- Ok(out)
- })
- .map_err(|e| format!("sessions_list: {e:#}"))?;
- to_json(serde_json::json!({ "sessions": sessions }))
- })
-}
-
-fn handle_sessions_create(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("sessions_create").await?;
- let agent_id = required_param(&params, "agentId")?.to_string();
- let label = params
- .get("label")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
- let session_id = uuid::Uuid::new_v4().to_string();
- let now = chrono::Utc::now().to_rfc3339();
- log::debug!(
- target: LOG,
- "[orchestration_rpc] sessions_create agent_id={agent_id} session_id={session_id}"
- );
- let session = OrchestrationSession {
- session_id: session_id.clone(),
- agent_id: agent_id.clone(),
- source: "user_created".to_string(),
- label,
- workspace: None,
- last_seq: 0,
- created_at: now.clone(),
- last_message_at: now.clone(),
- ..Default::default()
- };
- store::with_connection(&config.workspace_dir, |conn| {
- store::upsert_session(conn, &session)
- })
- .map_err(|e| format!("sessions_create: {e:#}"))?;
- super::bus::notify_orchestration_message(&agent_id, &session_id, "session");
- to_json(serde_json::json!({ "session": summarize(session, 0, false, None, 0) }))
- })
-}
-
-fn pinned_placeholder(session_id: &str) -> SessionSummary {
- SessionSummary {
- session_id: session_id.to_string(),
- agent_id: session_id.to_string(),
- source: "orchestration".to_string(),
- harness_type: None,
- status: derive_status(None, true).to_string(),
- current_task: None,
- label: None,
- workspace: None,
- chat_kind: chat_kind_for_session(session_id).as_str().to_string(),
- last_message_at: String::new(),
- unread: 0,
- message_count: 0,
- active: true,
- pinned: true,
- peer_online: None,
- last_seen_at: None,
- }
-}
-
-fn handle_messages_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("messages_list").await?;
- let chat = required_param(&params, "chat")?.to_string();
- let session_id = chat_to_session_id(&chat).to_string();
- let before = params
- .get("before")
- .and_then(Value::as_str)
- .map(str::to_string);
- let limit = params
- .get("limit")
- .and_then(Value::as_u64)
- .unwrap_or(100)
- .min(500) as u32;
- let messages: Vec<OrchestrationMessage> =
- store::with_connection(&config.workspace_dir, |conn| {
- store::list_messages_by_session(conn, &session_id, limit, before.as_deref())
- })
- .map_err(|e| format!("messages_list: {e:#}"))?;
- to_json(serde_json::json!({ "messages": messages }))
- })
-}
-
-/// Build the v1 session-envelope wire body for an outgoing session message so a
-/// compliant peer harness threads the reply under the same `session_id`.
-fn session_envelope_plaintext(
- session_id: &str,
- body: &str,
- message_id: &str,
- now: &str,
-) -> Result<String, String> {
- serde_json::to_string(&SessionEnvelopeV1::outgoing(
- session_id, body, message_id, now,
- ))
- .map_err(|e| format!("envelope encode: {e}"))
-}
-
-fn handle_send_master_message(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("send_master_message").await?;
- let body = required_param(&params, "body")?.to_string();
- let explicit = params
- .get("recipient")
- .and_then(Value::as_str)
- .filter(|s| !s.trim().is_empty())
- .map(str::to_string);
- // When present, the message threads under this session (envelope) rather
- // than the Master window.
- let session_id = params
- .get("sessionId")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty() && *s != "master" && *s != "subconscious")
- .map(str::to_string);
-
- // W2 — "ask OpenHuman locally". No recipient AND no session id means the
- // human is asking the OpenHuman agent itself via the Master chat (not
- // steering an external peer). Route the question into OpenHuman's OWN
- // reasoning graph: persist it in the Master window + wake the reasoning
- // core locally — NO outbound peer DM, no recipient required. The core
- // answers (using its history/read tools and, if it needs a real external
- // agent, `orchestration_send_to_agent` + W7 threading) and its reply lands
- // back in this Master window. This is the human↔OpenHuman channel; peer
- // steering still works by passing an explicit `recipient`/`sessionId`.
- if explicit.is_none() && session_id.is_none() {
- let now = chrono::Utc::now().to_rfc3339();
- let message_id = format!("master-ask:{now}");
- // Allocate the ordinal and write both rows in ONE IMMEDIATE txn so a
- // concurrent master writer (a rapid double-send, or this ask racing the
- // graph's reply-persist on the same `(local, "master")` key) can't read
- // the same `MAX(seq)` and duplicate it. A duplicate `seq` collides on the
- // backend idempotency key `(user, counterpart, session, seq)` and the wake
- // is silently 202-deduped with no inference. Mirrors the DM ingest path
- // (`ingest.rs` — the sole other writer on this key also uses IMMEDIATE).
- let persisted: Result<i64, _> = store::with_connection(&config.workspace_dir, |conn| {
- store::in_immediate_txn(conn, |conn| {
- let seq = store::next_session_seq(conn, LOCAL_MASTER_AGENT, "master")?;
- store::upsert_session(
- conn,
- &OrchestrationSession {
- session_id: "master".to_string(),
- agent_id: LOCAL_MASTER_AGENT.to_string(),
- source: "master".to_string(),
- label: None,
- workspace: None,
- last_seq: seq,
- created_at: now.clone(),
- last_message_at: now.clone(),
- ..Default::default()
- },
- )?;
- store::insert_message(
- conn,
- &OrchestrationMessage {
- id: message_id.clone(),
- agent_id: LOCAL_MASTER_AGENT.to_string(),
- session_id: "master".to_string(),
- chat_kind: ChatKind::Master,
- role: "user".to_string(),
- body: body.clone(),
- timestamp: now.clone(),
- seq,
- ..Default::default()
- },
- )?;
- Ok(seq)
- })
- });
- let seq = match persisted {
- Ok(seq) => seq,
- Err(e) => return Err(format!("master ask persist: {e}")),
- };
- // Fan to the renderer so the question shows immediately.
- super::bus::notify_orchestration_message(
- LOCAL_MASTER_AGENT,
- "master",
- ChatKind::Master.as_str(),
- );
- // Forward the ask to the hosted brain — it wakes, reasons, and returns
- // the reply as a `send_dm` effect on the "master" session, which the
- // device renders back into this window (see `effect_executor`). No wake
- // graph runs on the device.
- let ts = super::wire::parse_ts_ms(&now).unwrap_or(0);
- let envelope = super::wire::OrchestrationEventEnvelopeWire::build(
- LOCAL_MASTER_AGENT,
- "master",
- seq,
- "user",
- LOCAL_MASTER_AGENT,
- &body,
- ts,
- "message",
- );
- let forward_cfg = config.clone();
- tokio::spawn(async move {
- match super::cloud::push_event(&forward_cfg, &envelope).await {
- Ok(cycle_id) => {
- // Record this Master-chat cycle's origin so the local-exec
- // trust gate authorizes it (counterpart == LOCAL_MASTER_AGENT).
- if let Some(cid) = cycle_id {
- super::exec_gate::record_cycle_origin(
- &cid,
- &envelope.counterpart_agent_id,
- &envelope.session_id,
- );
- }
- }
- Err(e) => {
- log::warn!(target: LOG, "[orchestration_rpc] master_ask.forward_failed: {e}")
- }
- }
- });
- log::debug!(target: LOG, "[orchestration_rpc] master_ask.forwarded id={message_id} seq={seq}");
- return to_json(serde_json::json!({ "ok": true, "messageId": message_id }));
- }
-
- // Resolve the recipient: explicit wins; otherwise the session's contact
- // (session mode) or the latest Master peer (master mode).
- let recipient = match (explicit, session_id.as_deref()) {
- (Some(r), _) => r,
- (None, Some(sid)) => {
- let sid = sid.to_string();
- store::with_connection(&config.workspace_dir, move |conn| {
- store::session_agent_id(conn, &sid)
- })
- .map_err(|e| format!("resolve session recipient: {e:#}"))?
- .ok_or_else(|| "unknown session — specify a recipient".to_string())?
- }
- (None, None) => {
- store::with_connection(&config.workspace_dir, store::latest_master_peer)
- .map_err(|e| format!("resolve recipient: {e:#}"))?
- .ok_or_else(|| "no Master counterpart yet — specify a recipient".to_string())?
- }
- };
-
- let now = chrono::Utc::now().to_rfc3339();
- let (window, chat_kind, message_id) = match &session_id {
- Some(sid) => (sid.clone(), ChatKind::Session, format!("session-out:{now}")),
- None => (
- "master".to_string(),
- ChatKind::Master,
- format!("master-out:{now}"),
- ),
- };
-
- // Session sends go over the wire as a v1 envelope; Master sends stay plain.
- let plaintext = match &session_id {
- Some(sid) => session_envelope_plaintext(sid, &body, &message_id, &now)?,
- None => body.clone(),
- };
-
- // Send the E2E DM to the front-end agent (human steering the front end).
- let mut send_params = Map::new();
- send_params.insert("recipient".to_string(), Value::from(recipient.clone()));
- send_params.insert("plaintext".to_string(), Value::from(plaintext));
- crate::openhuman::tinyplace::handle_tinyplace_signal_send_message(send_params)
- .await
- .map_err(|e| format!("signal send: {e}"))?;
-
- // Mirror it into the target window so the composer's message is visible,
- // and notify the renderer. `upsert_session` never clobbers an existing
- // session's `source`, so a user-created session keeps its origin.
- let persisted = store::with_connection(&config.workspace_dir, |conn| {
- store::upsert_session(
- conn,
- &OrchestrationSession {
- session_id: window.clone(),
- agent_id: recipient.clone(),
- source: match &session_id {
- Some(_) => "user_created".to_string(),
- None => "master".to_string(),
- },
- label: None,
- workspace: None,
- last_seq: 0,
- created_at: now.clone(),
- last_message_at: now.clone(),
- ..Default::default()
- },
- )?;
- store::insert_message(
- conn,
- &OrchestrationMessage {
- id: message_id.clone(),
- agent_id: recipient.clone(),
- session_id: window.clone(),
- chat_kind,
- role: "owner".to_string(),
- body: body.clone(),
- timestamp: now.clone(),
- seq: 0,
- ..Default::default()
- },
- )
- });
- if let Err(e) = persisted {
- log::warn!(target: LOG, "[orchestration_rpc] send_master.mirror_failed: {e}");
- }
- super::bus::notify_orchestration_message(&recipient, &window, chat_kind.as_str());
-
- to_json(serde_json::json!({ "ok": true, "messageId": message_id }))
- })
-}
-
-fn handle_mark_read(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("mark_read").await?;
- let chat = required_param(&params, "chat")?.to_string();
- let session_id = chat_to_session_id(&chat).to_string();
- store::with_connection(&config.workspace_dir, |conn| {
- store::mark_chat_read(conn, &session_id)
- })
- .map_err(|e| format!("mark_read: {e:#}"))?;
- to_json(serde_json::json!({ "ok": true }))
- })
-}
-
-fn handle_status(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("status").await?;
- // Reachability comes from the hosted health probe's kv cache (see `sync`),
- // so this read stays synchronous and offline-safe.
- let cloud_reachable = super::sync::cloud_reachable(&config);
-
- let (ingest_last, lag, last_error): (Option<String>, i64, Option<String>) =
- store::with_connection(&config.workspace_dir, |conn| {
- // MAX() always returns exactly one row (NULL when empty). Exclude the
- // pinned master/subconscious windows: they're bumped by manual owner
- // DMs (`handle_send_master_message`), which would otherwise mask a
- // stalled real ingestion pipeline with fresh traffic.
- let ingest_last: Option<String> = conn.query_row(
- "SELECT MAX(last_message_at) FROM sessions \
- WHERE session_id NOT IN ('master', 'subconscious')",
- [],
- |r| r.get::<_, Option<String>>(0),
- )?;
- let lag = store::ingest_cursor_lag(conn)?;
- let last_error = store::kv_get(conn, "orchestration:last_error")?;
- Ok((ingest_last, lag, last_error))
- })
- .map_err(|e| format!("status: {e:#}"))?;
-
- to_json(OrchestrationStatus {
- ingest_last_message_at: ingest_last.filter(|s| !s.is_empty()),
- ingest_cursor_lag: lag,
- last_error,
- cloud_reachable,
- })
- })
-}
-
-fn handle_attention(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = load_config("attention").await?;
-
- // 1. Pending tool approvals (global gate; empty when the gate is not
- // installed — never an error path). Mapping is the unit-tested pure
- // `attention::approval_signals`.
- let approvals = attention::approval_signals(
- crate::openhuman::security::approval::rpc::approval_list_pending()
- .await
- .map_err(|e| format!("attention.approvals: {e}"))?
- .value,
- );
-
- // 2. Agent runs blocked awaiting user input (command-center NeedsInput).
- // Best-effort: a command-center read failure must not sink the whole
- // queue — approvals + unread still surface.
- let needs_input = super::ops::command_center_needs_input(&config);
-
- // 3. Per-instance unread (non-pinned orchestration sessions). Best-effort
- // like the command-center read: a transient local-DB hiccup must not
- // sink the approvals + needs-input signals that already resolved.
- let unread = match store::with_connection(
- &config.workspace_dir,
- super::ops::gather_unread_signals,
- ) {
- Ok(unread) => unread,
- Err(e) => {
- log::warn!(target: LOG, "[orchestration_rpc] attention.unread_failed: {e}");
- Vec::new()
- }
- };
-
- // 4. Remote agent sessions parked on a tool-approval decision (Phase 1's
- // persisted `waiting_approval` run-state). Best-effort like the unread
- // read: a transient local-DB hiccup must not sink the other sources.
- // These fold into the Approval kind (see `assemble_attention`).
- let remote_approvals = match store::with_connection(
- &config.workspace_dir,
- super::ops::gather_remote_approval_signals,
- ) {
- Ok(remote_approvals) => remote_approvals,
- Err(e) => {
- log::warn!(target: LOG, "[orchestration_rpc] attention.remote_approvals_failed: {e}");
- Vec::new()
- }
- };
-
- let queue = attention::assemble_attention(approvals, needs_input, unread, remote_approvals);
- log::debug!(
- target: LOG,
- "[orchestration_rpc] attention.exit total={} approvals={} needs_input={} unread={}",
- queue.counts.total,
- queue.counts.approvals,
- queue.counts.needs_input,
- queue.counts.unread,
- );
- to_json(queue)
- })
-}
-
-/// Own tiny.place identity + discoverability, composed from the internal
-/// tinyplace signal/directory reads. Delegates like `send_master` does
-/// (`crate::openhuman::tinyplace::handle_tinyplace_*`), so there is no new
-/// tiny.place logic here — only aggregation into the shape the renderer needs.
-fn handle_self_identity(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- // 1. Key status → own agent id + whether the encryption key is published
- // to the directory and current. `encryptionKeyPublished` is false when
- // the card is missing OR the published key is stale (wrong wallet).
- let key_status =
- crate::openhuman::tinyplace::handle_tinyplace_signal_key_status(Map::new())
- .await
- .map_err(|e| format!("self_identity key_status: {e}"))?;
- let agent_id = key_status
- .get("agentId")
- .and_then(Value::as_str)
- .unwrap_or_default()
- .to_string();
- let key_published = key_status
- .get("encryptionKeyPublished")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- log::debug!(
- target: LOG,
- "[orchestration_rpc] self_identity agent_id_len={} key_published={key_published}",
- agent_id.len()
- );
-
- // 2. Reverse-resolve any @handles this wallet holds. Best-effort: a
- // handle-less identity is normal (and is exactly the un-messageable
- // case the card must flag), so a reverse miss is not an error.
- let reverse = if agent_id.is_empty() {
- None
- } else {
- let mut rev_params = Map::new();
- rev_params.insert("cryptoId".to_string(), Value::from(agent_id.clone()));
- // Bounded: a slow/degraded relay must degrade this to "no handle",
- // never hang the whole card on "Loading identity…" forever.
- match tokio::time::timeout(
- std::time::Duration::from_secs(5),
- crate::openhuman::tinyplace::handle_tinyplace_directory_reverse(rev_params),
- )
- .await
- {
- Ok(Ok(reverse)) => Some(reverse),
- Ok(Err(e)) => {
- log::debug!(target: LOG, "[orchestration_rpc] self_identity reverse miss: {e}");
- None
- }
- Err(_) => {
- log::warn!(target: LOG, "[orchestration_rpc] self_identity reverse timed out (relay slow)");
- None
- }
- }
- };
-
- // 3. Directory card presence: get_agent(self) 404s when no card is
- // published. Ok → a card is live; Err → treat as unpublished.
- let card_published = if agent_id.is_empty() {
- false
- } else {
- let mut card_params = Map::new();
- card_params.insert("agentId".to_string(), Value::from(agent_id.clone()));
- // Bounded like the reverse lookup above: a stalled relay degrades to
- // "card not published" rather than pinning the card on "Loading…".
- matches!(
- tokio::time::timeout(
- std::time::Duration::from_secs(5),
- crate::openhuman::tinyplace::handle_tinyplace_directory_get_agent(card_params),
- )
- .await,
- Ok(Ok(_))
- )
- };
-
- let identity = super::ops::build_self_identity(
- agent_id,
- key_published,
- reverse.as_ref(),
- card_published,
- );
- log::debug!(
- target: LOG,
- "[orchestration_rpc] self_identity handles={} card_published={card_published} discoverable={}",
- identity.handles.len(),
- identity.discoverable
- );
- to_json(identity)
- })
-}
-
-/// Make this agent fully messageable, then echo back the refreshed identity.
-///
-/// The `SelfIdentityCard` shows *why* peers can't DM this agent but had no
-/// remediation — the user was left to go register a @handle elsewhere even when
-/// the wallet already holds one. Two publishes are needed for a peer to actually
-/// deliver a first DM, and this does both:
-///
-/// 1. **Directory card + encryption key** (`signal_register_encryption_key`):
-/// upserts the directory card (minting a minimal one if none exists) and
-/// writes the wallet's encryption key into its metadata, so peers can *resolve*
-/// this address.
-/// 2. **X3DH prekey bundle** (`signal_provision`): generates a signed pre-key +
-/// one-time pre-keys and uploads them to `/keys/<addr>/bundle`, so peers can
-/// *initiate* a Signal session. Without this, resolution succeeds but the very
-/// first DM 404s on the bundle fetch — "discoverable" would be a lie. This is
-/// the step the old card-only publish missed.
-///
-/// Then re-reads `self_identity` so the card flips to "discoverable" in place. No
-/// @handle registration and no payment: this only publishes presence for the
-/// identity the wallet already has. Registering a brand-new paid handle stays in
-/// the tiny.place registry surface.
-fn handle_publish_identity(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(target: LOG, "[orchestration_rpc] publish_identity entry");
- // 1. Directory card + encryption key → resolvable.
- crate::openhuman::tinyplace::handle_tinyplace_signal_register_encryption_key(Map::new())
- .await
- .map_err(|e| format!("publish_identity card: {e}"))?;
- // 2. X3DH prekey bundle → a peer can initiate the first DM. A peer that
- // resolves the card but finds no bundle 404s on `/keys/<addr>/bundle`,
- // so this is required for real messageability, not optional polish.
- crate::openhuman::tinyplace::handle_tinyplace_signal_provision(Map::new())
- .await
- .map_err(|e| format!("publish_identity prekeys: {e}"))?;
- // 3. Re-read discoverability from the directory so the renderer gets the
- // post-publish truth (card + key now live), not an optimistic guess.
- handle_self_identity(Map::new()).await
- })
-}
-
-/// Relay endpoint + network label for the renderer's relay badge. Reads only the
-/// configured base URL (no client build / wallet unlock), so it always resolves.
-fn handle_relay_info(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let (base_url, network) = crate::openhuman::tinyplace::ops::relay_endpoint();
- log::debug!(target: LOG, "[orchestration_rpc] relay_info network={network}");
- to_json(RelayInfo {
- base_url,
- network: network.to_string(),
- })
- })
-}
-
-/// Direct paid Medulla entry point. The backend remains the authority for both
-/// authentication and plan enforcement; `medulla::run` also performs a local
-/// plan preflight so free users receive an immediate actionable error.
-fn handle_medulla_run(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let input = required_param(&params, "input")?.trim().to_string();
- let session_id = params
- .get("sessionId")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|value| !value.is_empty())
- .map(str::to_string);
- let config = load_config("medulla_run").await?;
- log::debug!(
- target: LOG,
- "[orchestration_rpc] medulla_run.entry input_bytes={} has_session={}",
- input.len(),
- session_id.is_some(),
- );
- let result = super::medulla::run(&config, &input, session_id.as_deref()).await?;
- to_json(result)
- })
-}
-
-// ── helpers ─────────────────────────────────────────────────────────────────
-
-async fn load_config(action: &str) -> Result<Config, String> {
- log::debug!(target: LOG, "[orchestration_rpc] {action}.config_load");
- config_rpc::load_config_with_timeout()
- .await
- .inspect_err(|err| {
- log::warn!(target: LOG, "[orchestration_rpc] {action}.config_failed err={err}");
- })
-}
-
-fn required_param<'a>(params: &'a Map<String, Value>, key: &str) -> Result<&'a str, String> {
- params
- .get(key)
- .and_then(Value::as_str)
- .filter(|value| !value.trim().is_empty())
- .ok_or_else(|| format!("{key} is required"))
-}
-
-fn required_str(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::String,
- comment,
- required: true,
- }
-}
-
-fn optional_str(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment,
- required: false,
- }
-}
-
-fn json_output(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Json,
- comment,
- required: true,
- }
-}
-
-fn to_json<T: serde::Serialize>(value: T) -> Result<Value, String> {
- serde_json::to_value(value).map_err(|err| format!("serialize orchestration response: {err}"))
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn schemas_use_orchestration_namespace() {
- let schemas = all_controller_schemas();
- assert_eq!(schemas.len(), 11);
- assert!(schemas.iter().all(|s| s.namespace == "orchestration"));
- assert_eq!(schema_for("orchestration_attention").function, "attention");
- assert_eq!(
- schema_for("orchestration_self_identity").function,
- "self_identity"
- );
- assert_eq!(
- schema_for("orchestration_publish_identity").function,
- "publish_identity"
- );
- // The publish-identity remediation must be wired into the live registry,
- // not just describable — otherwise the SelfIdentityCard button 404s.
- assert!(all_registered_controllers()
- .iter()
- .any(|c| c.schema.function == "publish_identity"));
- assert_eq!(
- schema_for("orchestration_relay_info").function,
- "relay_info"
- );
- assert_eq!(
- schema_for("orchestration_messages_list").function,
- "messages_list"
- );
- assert_eq!(
- schema_for("orchestration_sessions_create").function,
- "sessions_create"
- );
- assert_eq!(schema_for("orchestration_run").function, "run");
- assert!(all_registered_controllers()
- .iter()
- .any(|controller| controller.schema.function == "run"));
- }
-
- #[test]
- fn session_envelope_plaintext_roundtrips_as_v1() {
- let wire =
- session_envelope_plaintext("sess-1", "hello world", "msg-1", "2026-07-04T00:00:00Z")
- .expect("encode");
- let parsed = SessionEnvelopeV1::parse(&wire).expect("valid v1 envelope");
- assert_eq!(parsed.scope.harness_session_id, "sess-1");
- assert_eq!(parsed.message.text, "hello world");
- assert_eq!(parsed.message.role, "owner");
- }
-
- #[tokio::test]
- async fn created_session_persists_and_resolves_its_agent() {
- let tmp = tempfile::tempdir().unwrap();
- let config = Config {
- workspace_dir: tmp.path().to_path_buf(),
- ..Config::default()
- };
- let now = "2026-07-04T00:00:00Z".to_string();
- let session = OrchestrationSession {
- session_id: "sess-42".to_string(),
- agent_id: "@peer".to_string(),
- source: "user_created".to_string(),
- label: Some("Design review".to_string()),
- workspace: None,
- last_seq: 0,
- created_at: now.clone(),
- last_message_at: now,
- ..Default::default()
- };
- let resolved = store::with_connection(&config.workspace_dir, |conn| {
- store::upsert_session(conn, &session)?;
- let rows = store::list_sessions(conn)?;
- assert!(rows.iter().any(|s| s.session_id == "sess-42"
- && s.source == "user_created"
- && s.agent_id == "@peer"));
- store::session_agent_id(conn, "sess-42")
- })
- .unwrap();
- assert_eq!(resolved.as_deref(), Some("@peer"));
- }
-
- #[test]
- fn chat_resolution_and_kind() {
- assert_eq!(chat_to_session_id("master"), "master");
- assert_eq!(chat_to_session_id("subconscious"), "subconscious");
- assert_eq!(chat_to_session_id("h1-uuid"), "h1-uuid");
- assert_eq!(chat_kind_for_session("master"), ChatKind::Master);
- assert_eq!(chat_kind_for_session("h1"), ChatKind::Session);
- }
-
- #[tokio::test]
- async fn sessions_list_includes_pinned_windows_when_empty() {
- // Build against an empty tempdir workspace.
- let tmp = tempfile::tempdir().unwrap();
- let config = Config {
- workspace_dir: tmp.path().to_path_buf(),
- ..Config::default()
- };
- let sessions = store::with_connection(&config.workspace_dir, |conn| {
- // Directly exercise the pinned-fill logic path via list_sessions.
- let rows = store::list_sessions(conn)?;
- assert!(rows.is_empty());
- Ok(())
- });
- sessions.unwrap();
- // The handler always yields the two pinned placeholders.
- let master = pinned_placeholder("master");
- let sub = pinned_placeholder("subconscious");
- assert_eq!(master.chat_kind, "master");
- assert!(master.pinned && sub.pinned);
- }
-
- #[test]
- fn required_param_rejects_blank() {
- let mut params = Map::new();
- params.insert("chat".to_string(), Value::String(" ".to_string()));
- assert!(required_param(&params, "chat").is_err());
- }
-
- #[test]
- fn harness_type_only_for_known_providers() {
- assert_eq!(harness_type_for("claude").as_deref(), Some("claude"));
- assert_eq!(harness_type_for("codex").as_deref(), Some("codex"));
- assert_eq!(harness_type_for("gemini").as_deref(), Some("gemini"));
- assert_eq!(harness_type_for("cursor").as_deref(), Some("cursor"));
- assert_eq!(harness_type_for("windsurf").as_deref(), Some("windsurf"));
- // Sentinel / origin sources are not harnesses.
- assert_eq!(harness_type_for("master"), None);
- assert_eq!(harness_type_for("user_created"), None);
- assert_eq!(harness_type_for("orchestration"), None);
- }
-
- #[test]
- fn status_falls_back_to_recency_without_persisted_state() {
- // v1/legacy sessions carry no run-state → the original recency heuristic.
- assert_eq!(derive_status(None, true), "idle");
- assert_eq!(derive_status(None, false), "stopped");
- // An unrecognised persisted value also falls back to recency.
- assert_eq!(derive_status(Some("weird"), true), "idle");
- }
-
- #[test]
- fn status_maps_persisted_v2_run_state() {
- assert_eq!(derive_status(Some("running"), true), "running");
- assert_eq!(derive_status(Some("running_tool"), true), "running");
- assert_eq!(
- derive_status(Some("waiting_approval"), true),
- "waiting-approval"
- );
- assert_eq!(derive_status(Some("idle"), true), "idle");
- assert_eq!(derive_status(Some("stopped"), true), "stopped");
- assert_eq!(derive_status(Some("errored"), true), "errored");
- // waiting/errored are honoured even when the session has gone stale.
- assert_eq!(derive_status(Some("errored"), false), "errored");
- assert_eq!(
- derive_status(Some("waiting_approval"), false),
- "waiting-approval"
- );
- }
-
- #[test]
- fn status_staleness_downgrades_silent_running_to_stopped() {
- // A `running` session that has gone silent (no recent traffic) must not
- // sit on a stuck green dot — it downgrades to stopped.
- assert_eq!(derive_status(Some("running"), false), "stopped");
- assert_eq!(derive_status(Some("running_tool"), false), "stopped");
- }
-
- #[test]
- fn summarize_reads_persisted_run_state_and_detail() {
- let session = OrchestrationSession {
- session_id: "w2".to_string(),
- agent_id: "@peer".to_string(),
- source: "claude".to_string(),
- last_seq: 3,
- created_at: "2020-01-01T00:00:00Z".to_string(),
- // Recent enough to be "active".
- last_message_at: chrono::Utc::now().to_rfc3339(),
- status_state: Some("waiting_approval".to_string()),
- current_detail: Some("approve rm -rf".to_string()),
- ..Default::default()
- };
- // current_task is threaded from the handler (status.detail preferred there).
- let summary = summarize(session, 0, false, Some("approve rm -rf".to_string()), 7);
- assert_eq!(summary.status, "waiting-approval");
- assert_eq!(summary.current_task.as_deref(), Some("approve rm -rf"));
- assert_eq!(summary.message_count, 7);
- }
-
- #[test]
- fn task_preview_trims_and_caps_on_char_boundary() {
- assert_eq!(task_preview(" hello "), "hello");
- // A multibyte string longer than the cap truncates with an ellipsis and
- // never exceeds MAX chars (no mid-codepoint panic).
- let long = "é".repeat(200);
- let preview = task_preview(&long);
- assert_eq!(preview.chars().count(), 80);
- assert!(preview.ends_with('…'));
- }
-
- #[test]
- fn summarize_derives_harness_status_and_carries_task() {
- let session = OrchestrationSession {
- session_id: "w1".to_string(),
- agent_id: "@peer".to_string(),
- source: "claude".to_string(),
- label: None,
- workspace: None,
- last_seq: 3,
- created_at: "2020-01-01T00:00:00Z".to_string(),
- // Stale timestamp → not active → stopped.
- last_message_at: "2020-01-01T00:00:00Z".to_string(),
- ..Default::default()
- };
- let summary = summarize(session, 2, false, Some("drafting cards".to_string()), 12);
- assert_eq!(summary.harness_type.as_deref(), Some("claude"));
- assert_eq!(summary.status, "stopped");
- assert_eq!(summary.current_task.as_deref(), Some("drafting cards"));
- assert_eq!(summary.message_count, 12);
- assert!(!summary.active);
-
- // A pinned window is always active → idle, and carries no harness/task.
- let pinned = pinned_placeholder("master");
- assert_eq!(pinned.status, "idle");
- assert!(pinned.harness_type.is_none());
- }
-}
diff --git a/src/openhuman/hosted/orchestration/store.rs b/src/openhuman/hosted/orchestration/store.rs
deleted file mode 100644
index e4eca2ef54..0000000000
--- a/src/openhuman/hosted/orchestration/store.rs
+++ /dev/null
@@ -1,1605 +0,0 @@
-//! SQLite persistence for the orchestration domain.
-//!
-//! Lives at `<workspace>/orchestration/orchestration.db`. Message bodies are
-//! decrypted plaintext, so this path is workspace-internal (protected by
-//! `is_workspace_internal_path`). Follows the subconscious/cron `with_connection`
-//! pattern.
-
-use std::collections::HashMap;
-use std::path::Path;
-
-use anyhow::{Context, Result};
-use rusqlite::{params, Connection, OptionalExtension};
-
-use super::types::{OrchestrationMessage, OrchestrationSession};
-
-const SCHEMA_DDL: &str = "
- PRAGMA foreign_keys = ON;
-
- -- `status_state`/`current_detail`/`active_call_id` carry the v2 harness
- -- run-state (`status.state`/`status.detail`/`status.active_call_id`). Nullable
- -- and additive: a v1/legacy store gets them via `migrate` (existing rows NULL).
- -- `title`/`model`/`handle`/`repo`/`branch`/`capabilities` carry the v2
- -- `session_info` enrichment (`capabilities` is a JSON array of kind strings).
- -- Also nullable/additive — `migrate` backfills them on an older store.
- CREATE TABLE IF NOT EXISTS sessions (
- session_id TEXT NOT NULL,
- agent_id TEXT NOT NULL,
- source TEXT NOT NULL,
- label TEXT,
- workspace TEXT,
- last_seq INTEGER NOT NULL DEFAULT 0,
- created_at TEXT NOT NULL,
- last_message_at TEXT NOT NULL,
- status_state TEXT,
- current_detail TEXT,
- active_call_id TEXT,
- title TEXT,
- model TEXT,
- handle TEXT,
- repo TEXT,
- branch TEXT,
- capabilities TEXT,
- PRIMARY KEY (agent_id, session_id)
- );
-
- -- `event_kind`/`tool_name`/`call_id` carry the v2 per-message event shape
- -- (`event.kind` + tool identity/correlation). `ok`/`is_error`/`exit_code`
- -- carry the `tool_result` outcome. Nullable and additive; v1 and pinned
- -- master/subconscious rows leave them NULL.
- CREATE TABLE IF NOT EXISTS messages (
- id TEXT PRIMARY KEY,
- agent_id TEXT NOT NULL,
- session_id TEXT NOT NULL,
- chat_kind TEXT NOT NULL,
- role TEXT NOT NULL,
- body TEXT NOT NULL,
- timestamp TEXT NOT NULL,
- seq INTEGER NOT NULL DEFAULT 0,
- event_kind TEXT,
- tool_name TEXT,
- call_id TEXT,
- ok INTEGER,
- is_error INTEGER,
- exit_code INTEGER
- );
-
- CREATE INDEX IF NOT EXISTS idx_messages_session
- ON messages (agent_id, session_id, timestamp);
-
- CREATE TABLE IF NOT EXISTS kv (k TEXT PRIMARY KEY, v TEXT NOT NULL);
-
- -- Hosted-brain era: device-side world-observation buffer. Compact notes the
- -- device derives from locally-observed events (inbound DMs, executed effects);
- -- the periodic uploader drains these to `POST /orchestration/v1/world-diff`,
- -- whose receipt schedules the hosted subconscious steering tick. `seq` is a
- -- global monotonic ordinal (unique within any one session — all the backend
- -- dedupe on `(userId, sessionId, seq)` needs). Rows are deleted once uploaded.
- CREATE TABLE IF NOT EXISTS world_obs (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- session_id TEXT NOT NULL,
- seq INTEGER NOT NULL,
- note TEXT NOT NULL,
- ts INTEGER NOT NULL
- );
-";
-
-/// Open the orchestration DB, initialise the schema, and run `f`.
-pub fn with_connection<T>(
- workspace_dir: &Path,
- f: impl FnOnce(&Connection) -> Result<T>,
-) -> Result<T> {
- let db_path = workspace_dir.join("orchestration").join("orchestration.db");
- if let Some(parent) = db_path.parent() {
- std::fs::create_dir_all(parent)
- .with_context(|| format!("create orchestration dir: {}", parent.display()))?;
- }
- let conn = Connection::open(&db_path)
- .with_context(|| format!("open orchestration DB: {}", db_path.display()))?;
- // Concurrent writers (the drain ingesting an inbound DM vs the graph's
- // `send_dm` persisting a reply) each open their own connection. Wait for a
- // held write lock instead of erroring `SQLITE_BUSY`; paired with the
- // IMMEDIATE txn in the seq-allocating writers this serialises
- // `MAX(seq)+1 → INSERT` so `seq` stays unique per `(agent_id, session_id)`.
- conn.busy_timeout(std::time::Duration::from_secs(5))
- .context("set orchestration busy_timeout")?;
- // WAL lets readers run concurrently with the single writer, so the one-time,
- // schema-modifying `migrate()` ALTERs (first open after an upgrade) can't be
- // starved into `SQLITE_BUSY` by the drain/`send_dm` writers this store is
- // explicitly shared between — a rollback-journal `ALTER TABLE` needs an
- // EXCLUSIVE lock that any concurrent reader blocks, and a `busy_timeout`
- // expiry there surfaces as the opaque "migrate orchestration schema" failure.
- // `query_row` because `PRAGMA journal_mode` returns the resulting mode.
- conn.query_row("PRAGMA journal_mode = WAL", [], |_| Ok(()))
- .context("set orchestration journal_mode=WAL")?;
- conn.execute_batch(SCHEMA_DDL)
- .context("initialise orchestration schema")?;
- migrate(&conn).context("migrate orchestration schema")?;
- f(&conn)
-}
-
-/// Run `f` inside a single `BEGIN IMMEDIATE` transaction, rolling back on error.
-/// Use for read-then-write allocations (`MAX(seq)+1` then `INSERT`) so two
-/// concurrent writers on the same `(agent_id, session_id)` cannot read the same
-/// max and persist a duplicate `seq` (which would break the monotonic wake
-/// cursor). `IMMEDIATE` takes the write lock up front; the `busy_timeout` set in
-/// [`with_connection`] makes the loser wait for the holder to commit rather than
-/// fail.
-pub fn in_immediate_txn<T>(
- conn: &Connection,
- f: impl FnOnce(&Connection) -> Result<T>,
-) -> Result<T> {
- conn.execute_batch("BEGIN IMMEDIATE")
- .context("begin orchestration immediate txn")?;
- match f(conn) {
- Ok(value) => {
- conn.execute_batch("COMMIT")
- .context("commit orchestration txn")?;
- Ok(value)
- }
- Err(e) => {
- let _ = conn.execute_batch("ROLLBACK");
- Err(e)
- }
- }
-}
-
-/// True if `column` already exists on `table` (via `PRAGMA table_info`). Used to
-/// make additive `ALTER TABLE ... ADD COLUMN` migrations idempotent — SQLite has
-/// no `ADD COLUMN IF NOT EXISTS`, and re-adding an existing column errors.
-fn column_exists(conn: &Connection, table: &str, column: &str) -> Result<bool> {
- // `table` is a hardcoded internal literal (never user input); PRAGMA cannot be
- // parameterised, so it is interpolated directly.
- let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
- let mut rows = stmt.query([])?;
- while let Some(row) = rows.next()? {
- let name: String = row.get(1)?;
- if name == column {
- return Ok(true);
- }
- }
- Ok(false)
-}
-
-/// Additively add `column` to `table` when it is not already present. Idempotent,
-/// so it is safe on a fresh DB (SCHEMA_DDL already created the column → no-op) and
-/// on an older store (adds it; existing rows default NULL).
-fn add_column_if_missing(conn: &Connection, table: &str, column: &str, decl: &str) -> Result<()> {
- if !column_exists(conn, table, column)? {
- conn.execute_batch(&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"))?;
- }
- Ok(())
-}
-
-/// One-time, `user_version`-gated migrations. Runs after the idempotent
-/// `SCHEMA_DDL`; each version block executes exactly once per DB.
-fn migrate(conn: &Connection) -> Result<()> {
- // The v1 world-diff uniqueness migration was retired with the local wake
- // graph — the `world_diff` table no longer exists on fresh stores. Any legacy
- // rows in an upgraded store are harmless; nothing reads them.
-
- // v2 — additive harness-session-v2 receiver columns. Guarded per-column by a
- // `table_info` existence check rather than `user_version`, so it is order- and
- // freshness-independent: a fresh DB already has them from SCHEMA_DDL (no-op),
- // while a v1 store gains them here with existing rows defaulting NULL — which
- // `derive_status` reads as "no persisted run-state" and falls back to recency.
- add_column_if_missing(conn, "sessions", "status_state", "TEXT")?;
- add_column_if_missing(conn, "sessions", "current_detail", "TEXT")?;
- add_column_if_missing(conn, "sessions", "active_call_id", "TEXT")?;
- add_column_if_missing(conn, "messages", "event_kind", "TEXT")?;
- add_column_if_missing(conn, "messages", "tool_name", "TEXT")?;
- add_column_if_missing(conn, "messages", "call_id", "TEXT")?;
- // v2 tool_result outcome — additive, existing rows default NULL.
- add_column_if_missing(conn, "messages", "ok", "INTEGER")?;
- add_column_if_missing(conn, "messages", "is_error", "INTEGER")?;
- add_column_if_missing(conn, "messages", "exit_code", "INTEGER")?;
-
- // v2 `session_info` enrichment columns (spec §4). Same per-column,
- // freshness-independent guard as the run-state block above: a fresh DB has
- // them from SCHEMA_DDL (no-op); a pre-session_info store gains them here with
- // existing rows defaulting NULL. `capabilities` holds a JSON array of kinds.
- add_column_if_missing(conn, "sessions", "title", "TEXT")?;
- add_column_if_missing(conn, "sessions", "model", "TEXT")?;
- add_column_if_missing(conn, "sessions", "handle", "TEXT")?;
- add_column_if_missing(conn, "sessions", "repo", "TEXT")?;
- add_column_if_missing(conn, "sessions", "branch", "TEXT")?;
- add_column_if_missing(conn, "sessions", "capabilities", "TEXT")?;
- Ok(())
-}
-
-/// True if a relay message id is already persisted. This guard MUST run before
-/// decryption so the non-idempotent Signal double-ratchet is never advanced
-/// twice for the same message.
-pub fn message_exists(conn: &Connection, id: &str) -> Result<bool> {
- Ok(conn
- .query_row("SELECT 1 FROM messages WHERE id = ?1", params![id], |_| {
- Ok(())
- })
- .optional()?
- .is_some())
-}
-
-/// Insert or update the session row (keyed by agent + session). The
-/// `session_info` enrichment columns COALESCE like the run-state ones, so an
-/// ordinary event (which carries none) never wipes a prior intro's metadata, and
-/// a later `session_info` (`resumed=true`) refreshes rather than duplicates.
-/// `capabilities` is stored as a JSON array; an empty list encodes to NULL so it
-/// COALESCEs to "no change" instead of clobbering a prior non-empty list.
-pub fn upsert_session(conn: &Connection, s: &OrchestrationSession) -> Result<()> {
- let capabilities = encode_capabilities(&s.capabilities);
- conn.execute(
- "INSERT INTO sessions
- (session_id, agent_id, source, label, workspace, last_seq, created_at, last_message_at,
- status_state, current_detail, active_call_id,
- title, model, handle, repo, branch, capabilities)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
- ON CONFLICT(agent_id, session_id) DO UPDATE SET
- last_seq = MAX(sessions.last_seq, excluded.last_seq),
- -- Keep the newest activity time: a read-sync pulling an older hosted
- -- `lastEventTs` must not regress a just-rendered local reply. rfc3339
- -- (consistent format) compares lexicographically.
- last_message_at = MAX(sessions.last_message_at, excluded.last_message_at),
- label = COALESCE(excluded.label, sessions.label),
- workspace = COALESCE(excluded.workspace, sessions.workspace),
- -- Run-state fields COALESCE so a content event (which carries none)
- -- never wipes the last status; a fresh `status` event overwrites them.
- status_state = COALESCE(excluded.status_state, sessions.status_state),
- current_detail = COALESCE(excluded.current_detail, sessions.current_detail),
- active_call_id = COALESCE(excluded.active_call_id, sessions.active_call_id),
- -- session_info enrichment: COALESCE so non-session_info events preserve
- -- the last intro's metadata, and a `resumed=true` re-intro refreshes it.
- title = COALESCE(excluded.title, sessions.title),
- model = COALESCE(excluded.model, sessions.model),
- handle = COALESCE(excluded.handle, sessions.handle),
- repo = COALESCE(excluded.repo, sessions.repo),
- branch = COALESCE(excluded.branch, sessions.branch),
- capabilities = COALESCE(excluded.capabilities, sessions.capabilities)",
- params![
- s.session_id,
- s.agent_id,
- s.source,
- s.label,
- s.workspace,
- s.last_seq,
- s.created_at,
- s.last_message_at,
- s.status_state,
- s.current_detail,
- s.active_call_id,
- s.title,
- s.model,
- s.handle,
- s.repo,
- s.branch,
- capabilities,
- ],
- )?;
- Ok(())
-}
-
-/// Encode `session_info.capabilities` for the `sessions.capabilities` TEXT column:
-/// a JSON array, or `None` for an empty list so the COALESCE upsert treats it as
-/// "no update" (a content/status event carries no capabilities and must not wipe
-/// a prior intro's list).
-fn encode_capabilities(capabilities: &[String]) -> Option<String> {
- if capabilities.is_empty() {
- return None;
- }
- // A `Vec<String>` always serialises, but fall back to NULL rather than
- // failing the whole upsert on the impossible error path.
- serde_json::to_string(capabilities).ok()
-}
-
-/// Decode the `sessions.capabilities` JSON array back into a `Vec<String>`. A
-/// NULL/absent or malformed value reads as an empty list (never an error).
-fn decode_capabilities(raw: Option<String>) -> Vec<String> {
- raw.and_then(|s| serde_json::from_str(&s).ok())
- .unwrap_or_default()
-}
-
-/// Overwrite a session's v2 run-state columns from an authoritative `status`
-/// snapshot. `upsert_session` COALESCEs these so a content event (which carries
-/// no run-state) never wipes the last status; a `status` event, by contrast, OWNS
-/// them and must be able to CLEAR `current_detail`/`active_call_id` on a
-/// `running_tool` → `idle` transition. The row already exists (the ingest path
-/// runs `upsert_session` first), so this is a plain UPDATE that SETs — not
-/// coalesces — all three, letting `None` clear a stale value.
-pub fn apply_run_state(
- conn: &Connection,
- agent_id: &str,
- session_id: &str,
- status_state: Option<&str>,
- current_detail: Option<&str>,
- active_call_id: Option<&str>,
-) -> Result<()> {
- conn.execute(
- "UPDATE sessions
- SET status_state = ?3, current_detail = ?4, active_call_id = ?5
- WHERE agent_id = ?1 AND session_id = ?2",
- params![
- agent_id,
- session_id,
- status_state,
- current_detail,
- active_call_id
- ],
- )?;
- Ok(())
-}
-
-/// Insert a message, idempotent by relay id. Returns true if a new row landed.
-pub fn insert_message(conn: &Connection, m: &OrchestrationMessage) -> Result<bool> {
- let changed = conn.execute(
- "INSERT OR IGNORE INTO messages
- (id, agent_id, session_id, chat_kind, role, body, timestamp, seq,
- event_kind, tool_name, call_id, ok, is_error, exit_code)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
- params![
- m.id,
- m.agent_id,
- m.session_id,
- m.chat_kind.as_str(),
- m.role,
- m.body,
- m.timestamp,
- m.seq,
- m.event_kind,
- m.tool_name,
- m.call_id,
- m.ok,
- m.is_error,
- m.exit_code,
- ],
- )?;
- Ok(changed > 0)
-}
-
-/// Clear a message's `event_kind` (set it NULL), making a previously hidden
-/// bookkeeping row visible again in the transcript / unread counts. Used to
-/// un-hide a `tool_completion` row whose forward to the hosted brain failed, so
-/// its result is not silently lost from the UI. Returns whether a row changed.
-pub fn clear_message_event_kind(conn: &Connection, id: &str) -> Result<bool> {
- let changed = conn.execute(
- "UPDATE messages SET event_kind = NULL WHERE id = ?1",
- params![id],
- )?;
- Ok(changed > 0)
-}
-
-/// Count persisted messages for a session (test/observability helper).
-pub fn count_messages(conn: &Connection, agent_id: &str, session_id: &str) -> Result<i64> {
- Ok(conn.query_row(
- "SELECT COUNT(*) FROM messages WHERE agent_id = ?1 AND session_id = ?2",
- params![agent_id, session_id],
- |row| row.get(0),
- )?)
-}
-
-/// Count transcript-visible messages for a session, using the same visibility
-/// predicate as message reads, unread counts, and roster previews.
-pub fn count_visible_messages(conn: &Connection, agent_id: &str, session_id: &str) -> Result<i64> {
- Ok(conn.query_row(
- "SELECT COUNT(*) FROM messages WHERE agent_id = ?1 AND session_id = ?2
- AND (event_kind IS NULL
- OR event_kind NOT IN ('status', 'lifecycle', 'unknown', 'session_info'))",
- params![agent_id, session_id],
- |row| row.get(0),
- )?)
-}
-
-/// Count transcript-visible messages for a pinned chat, whose transcript is
-/// scoped only by `session_id` and can include rows from multiple peers.
-pub fn count_visible_messages_by_session(conn: &Connection, session_id: &str) -> Result<i64> {
- Ok(conn.query_row(
- "SELECT COUNT(*) FROM messages WHERE session_id = ?1
- AND (event_kind IS NULL
- OR event_kind NOT IN ('status', 'lifecycle', 'unknown', 'session_info'))",
- params![session_id],
- |row| row.get(0),
- )?)
-}
-
-/// Transcript-visible message counts keyed by `(agent_id, session_id)`.
-pub fn visible_message_counts(conn: &Connection) -> Result<HashMap<(String, String), i64>> {
- let mut stmt = conn.prepare(
- "SELECT agent_id, session_id, COUNT(*)
- FROM messages
- WHERE event_kind IS NULL
- OR event_kind NOT IN ('status', 'lifecycle', 'unknown', 'session_info')
- GROUP BY agent_id, session_id",
- )?;
- let rows = stmt
- .query_map([], |row| {
- Ok((
- (row.get::<_, String>(0)?, row.get::<_, String>(1)?),
- row.get::<_, i64>(2)?,
- ))
- })?
- .collect::<std::result::Result<HashMap<_, _>, _>>()?;
- Ok(rows)
-}
-
-/// Transcript-visible message counts keyed by `session_id` for pinned chats.
-pub fn visible_message_counts_by_session(conn: &Connection) -> Result<HashMap<String, i64>> {
- let mut stmt = conn.prepare(
- "SELECT session_id, COUNT(*)
- FROM messages
- WHERE event_kind IS NULL
- OR event_kind NOT IN ('status', 'lifecycle', 'unknown', 'session_info')
- GROUP BY session_id",
- )?;
- let rows = stmt
- .query_map([], |row| {
- Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
- })?
- .collect::<std::result::Result<HashMap<_, _>, _>>()?;
- Ok(rows)
-}
-
-/// Unread message counts keyed by `session_id`: the batched form of
-/// [`unread_count`], collapsing its per-session cursor lookup + `COUNT(*)` into a
-/// single query so a caller iterating N sessions runs one statement instead of
-/// 2N. `LEFT JOIN kv ON kv.k = 'read:' || m.session_id` reproduces
-/// `kv_get(&read_cursor_key(..))` — `kv.k` is `PRIMARY KEY`, so the join matches
-/// at most one cursor row per session (no fan-out) — and `COALESCE(kv.v, '')`
-/// reproduces the scalar path's `.unwrap_or_default()` empty cursor, so a session
-/// that was never marked read counts all of its visible messages. Sessions with
-/// zero unread are absent from the map; callers default missing entries to 0.
-pub fn unread_counts(conn: &Connection) -> Result<HashMap<String, i64>> {
- let mut stmt = conn.prepare(
- "SELECT m.session_id, COUNT(*)
- FROM messages m
- LEFT JOIN kv ON kv.k = 'read:' || m.session_id
- WHERE m.timestamp > COALESCE(kv.v, '')
- AND (m.event_kind IS NULL
- OR m.event_kind NOT IN ('status', 'lifecycle', 'unknown', 'session_info'))
- GROUP BY m.session_id",
- )?;
- let rows = stmt
- .query_map([], |row| {
- Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
- })?
- .collect::<std::result::Result<HashMap<_, _>, _>>()?;
- Ok(rows)
-}
-
-/// The next monotonic per-session ingest ordinal: `MAX(seq) + 1` over the
-/// session's messages (`1` for the first message). Stamped at persist time so
-/// the wake idempotence cursor rides a strictly-increasing value instead of the
-/// harness `message.line`, which is unreliable (a wrapped Claude harness stamps
-/// `line = 0` on every DM, and a peer can reuse/reset it across harness sessions
-/// under one shared `wrapper_session_id`). Messages are append-only and
-/// deduped-by-id before persist, so this is strictly increasing. (#4583)
-pub fn next_session_seq(conn: &Connection, agent_id: &str, session_id: &str) -> Result<i64> {
- Ok(conn.query_row(
- "SELECT COALESCE(MAX(seq), 0) + 1 FROM messages WHERE agent_id = ?1 AND session_id = ?2",
- params![agent_id, session_id],
- |row| row.get(0),
- )?)
-}
-
-/// The current `last_seq` for a session, or `None` if the session row does not
-/// exist yet. Used to detect a non-monotonic inbound `seq` before the upsert
-/// clamps it away via `MAX(...)`.
-pub fn session_last_seq(
- conn: &Connection,
- agent_id: &str,
- session_id: &str,
-) -> Result<Option<i64>> {
- Ok(conn
- .query_row(
- "SELECT last_seq FROM sessions WHERE agent_id = ?1 AND session_id = ?2",
- params![agent_id, session_id],
- |row| row.get(0),
- )
- .optional()?)
-}
-
-/// The most recent message body for a session — the roster task line's "current
-/// activity". Newest by timestamp then seq; `None` when the session has no
-/// messages yet. Body is decrypted plaintext (workspace-internal, like the rest
-/// of this store).
-pub fn latest_message_preview(
- conn: &Connection,
- agent_id: &str,
- session_id: &str,
-) -> Result<Option<String>> {
- Ok(conn
- .query_row(
- "SELECT body FROM messages
- WHERE agent_id = ?1 AND session_id = ?2
- AND (event_kind IS NULL
- OR event_kind NOT IN ('status', 'lifecycle', 'unknown', 'session_info'))
- ORDER BY timestamp DESC, seq DESC LIMIT 1",
- params![agent_id, session_id],
- |row| row.get(0),
- )
- .optional()?)
-}
-
-/// List every persisted session row, newest activity first (stage-7 read surface).
-pub fn list_sessions(conn: &Connection) -> Result<Vec<OrchestrationSession>> {
- let mut stmt = conn.prepare(
- "SELECT session_id, agent_id, source, label, workspace, last_seq, created_at, last_message_at,
- status_state, current_detail, active_call_id,
- title, model, handle, repo, branch, capabilities
- FROM sessions ORDER BY last_message_at DESC",
- )?;
- let rows = stmt
- .query_map([], map_session_row)?
- .collect::<std::result::Result<Vec<_>, _>>()?;
- Ok(rows)
-}
-
-/// List messages for a chat keyed by `session_id` alone (so the pinned `master` /
-/// `subconscious` windows aggregate across peers). Newest `limit` returned in
-/// chronological order; `before` (exclusive timestamp) pages backwards.
-pub fn list_messages_by_session(
- conn: &Connection,
- session_id: &str,
- limit: u32,
- before: Option<&str>,
-) -> Result<Vec<OrchestrationMessage>> {
- let rows = match before {
- Some(before) => {
- let mut stmt = conn.prepare(
- "SELECT id, agent_id, session_id, chat_kind, role, body, timestamp, seq,
- event_kind, tool_name, call_id, ok, is_error, exit_code
- FROM messages WHERE session_id = ?1 AND timestamp < ?2
- AND (event_kind IS NULL
- OR event_kind NOT IN ('status', 'lifecycle', 'unknown', 'session_info'))
- ORDER BY timestamp DESC, seq DESC LIMIT ?3",
- )?;
- let rows = stmt
- .query_map(params![session_id, before, limit], map_message_row)?
- .collect::<std::result::Result<Vec<_>, _>>()?;
- rows
- }
- None => {
- let mut stmt = conn.prepare(
- "SELECT id, agent_id, session_id, chat_kind, role, body, timestamp, seq,
- event_kind, tool_name, call_id, ok, is_error, exit_code
- FROM messages WHERE session_id = ?1
- AND (event_kind IS NULL
- OR event_kind NOT IN ('status', 'lifecycle', 'unknown', 'session_info'))
- ORDER BY timestamp DESC, seq DESC LIMIT ?2",
- )?;
- let rows = stmt
- .query_map(params![session_id, limit], map_message_row)?
- .collect::<std::result::Result<Vec<_>, _>>()?;
- rows
- }
- };
- Ok(rows.into_iter().rev().collect())
-}
-
-/// The newest non-bookkeeping message for a specific `(agent_id, session_id)` — the
-/// agent-scoped analogue of [`list_messages_by_session`]'s newest row (same
-/// `status`/`lifecycle`/`unknown`/`session_info` exclusion). Used by the one-shot
-/// history migration: `list_messages_by_session` reads by `session_id` alone, so a
-/// legacy session id shared with another peer could surface *that* peer's latest
-/// turn and replay the wrong ask under this session's `agent_id`.
-pub fn latest_content_message(
- conn: &Connection,
- agent_id: &str,
- session_id: &str,
-) -> Result<Option<OrchestrationMessage>> {
- conn.query_row(
- "SELECT id, agent_id, session_id, chat_kind, role, body, timestamp, seq,
- event_kind, tool_name, call_id, ok, is_error, exit_code
- FROM messages WHERE agent_id = ?1 AND session_id = ?2
- AND (event_kind IS NULL
- OR event_kind NOT IN ('status', 'lifecycle', 'unknown', 'session_info'))
- ORDER BY timestamp DESC, seq DESC LIMIT 1",
- params![agent_id, session_id],
- map_message_row,
- )
- .optional()
- .map_err(Into::into)
-}
-
-/// Row → [`OrchestrationMessage`] mapper (a free fn so it is `Copy` and can be
-/// reused across the two `query_map` arms without a borrow-lifetime tangle).
-/// Column order MUST match the `SELECT` lists in the message readers.
-fn map_message_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<OrchestrationMessage> {
- let chat_kind: String = row.get(3)?;
- Ok(OrchestrationMessage {
- id: row.get(0)?,
- agent_id: row.get(1)?,
- session_id: row.get(2)?,
- chat_kind: crate::openhuman::hosted::orchestration::types::ChatKind::from_str(&chat_kind),
- role: row.get(4)?,
- body: row.get(5)?,
- timestamp: row.get(6)?,
- seq: row.get(7)?,
- event_kind: row.get(8)?,
- tool_name: row.get(9)?,
- call_id: row.get(10)?,
- ok: row.get(11)?,
- is_error: row.get(12)?,
- exit_code: row.get(13)?,
- })
-}
-
-/// Row → [`OrchestrationSession`] mapper. Column order MUST match the `SELECT`
-/// lists in [`list_sessions`] and [`load_session`].
-fn map_session_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<OrchestrationSession> {
- Ok(OrchestrationSession {
- session_id: row.get(0)?,
- agent_id: row.get(1)?,
- source: row.get(2)?,
- label: row.get(3)?,
- workspace: row.get(4)?,
- last_seq: row.get(5)?,
- created_at: row.get(6)?,
- last_message_at: row.get(7)?,
- status_state: row.get(8)?,
- current_detail: row.get(9)?,
- active_call_id: row.get(10)?,
- title: row.get(11)?,
- model: row.get(12)?,
- handle: row.get(13)?,
- repo: row.get(14)?,
- branch: row.get(15)?,
- capabilities: decode_capabilities(row.get(16)?),
- })
-}
-
-/// Count unread messages for a chat: rows with `timestamp` after the read cursor.
-pub fn unread_count(conn: &Connection, session_id: &str) -> Result<i64> {
- let cursor = kv_get(conn, &read_cursor_key(session_id))?.unwrap_or_default();
- Ok(conn.query_row(
- "SELECT COUNT(*) FROM messages WHERE session_id = ?1 AND timestamp > ?2
- AND (event_kind IS NULL
- OR event_kind NOT IN ('status', 'lifecycle', 'unknown', 'session_info'))",
- params![session_id, cursor],
- |row| row.get(0),
- )?)
-}
-
-/// Advance a chat's read cursor to its newest message timestamp (mark-read).
-pub fn mark_chat_read(conn: &Connection, session_id: &str) -> Result<()> {
- let latest: Option<String> = conn
- .query_row(
- "SELECT MAX(timestamp) FROM messages WHERE session_id = ?1",
- params![session_id],
- |row| row.get(0),
- )
- .optional()?
- .flatten();
- if let Some(latest) = latest {
- kv_set(conn, &read_cursor_key(session_id), &latest)?;
- }
- Ok(())
-}
-
-/// The agent_id of the most recent `master`-window message — the default
-/// recipient when the human sends a Master steering DM.
-pub fn latest_master_peer(conn: &Connection) -> Result<Option<String>> {
- conn.query_row(
- "SELECT agent_id FROM messages WHERE session_id = 'master'
- ORDER BY timestamp DESC, seq DESC LIMIT 1",
- [],
- |row| row.get(0),
- )
- .optional()
- .map_err(Into::into)
-}
-
-/// The contact (`agent_id`) that owns a given session id, if the session exists.
-pub fn session_agent_id(conn: &Connection, session_id: &str) -> Result<Option<String>> {
- conn.query_row(
- "SELECT agent_id FROM sessions WHERE session_id = ?1 LIMIT 1",
- params![session_id],
- |row| row.get(0),
- )
- .optional()
- .map_err(Into::into)
-}
-
-/// The most recent non-pinned session id for a peer agent, if any — the thread to
-/// reuse when OpenHuman initiates an outbound ask to that peer, so the peer's
-/// reply threads back into the same session (shared `wrapper_session_id` model,
-/// #227/#4582). Newest by `last_message_at`. Returns `None` when there is no
-/// existing thread with the peer (caller mints a fresh session id).
-pub fn latest_session_for_agent(conn: &Connection, agent_id: &str) -> Result<Option<String>> {
- conn.query_row(
- "SELECT session_id FROM sessions
- WHERE agent_id = ?1 AND session_id NOT IN ('master', 'subconscious')
- ORDER BY last_message_at DESC LIMIT 1",
- params![agent_id],
- |row| row.get(0),
- )
- .optional()
- .map_err(Into::into)
-}
-
-fn read_cursor_key(session_id: &str) -> String {
- format!("read:{session_id}")
-}
-
-/// Ingest-cursor lag (stage-8 health): how many sessions have a latest message
-/// seq beyond the wake-cursor seq already processed — i.e. pending wake work. A
-/// persistently non-zero value signals the wake loop is stuck.
-pub fn ingest_cursor_lag(conn: &Connection) -> Result<i64> {
- let mut stmt = conn.prepare("SELECT agent_id, session_id, last_seq FROM sessions")?;
- let rows = stmt
- .query_map([], |r| {
- Ok((
- r.get::<_, String>(0)?,
- r.get::<_, String>(1)?,
- r.get::<_, i64>(2)?,
- ))
- })?
- .collect::<std::result::Result<Vec<_>, _>>()?;
- let mut lag = 0i64;
- for (agent_id, session_id, last_seq) in rows {
- // Master/subconscious windows are UI-only, not wake-driven — skip them.
- if session_id == "master" || session_id == "subconscious" {
- continue;
- }
- let cursor = kv_get(conn, &format!("cursor:{agent_id}:{session_id}"))?
- .and_then(|v| v.parse::<i64>().ok())
- .unwrap_or(i64::MIN);
- if last_seq > cursor {
- lag += 1;
- }
- }
- Ok(lag)
-}
-
-/// Load a single session row (the session's counterpart + metadata).
-pub fn load_session(
- conn: &Connection,
- agent_id: &str,
- session_id: &str,
-) -> Result<Option<OrchestrationSession>> {
- conn.query_row(
- "SELECT session_id, agent_id, source, label, workspace, last_seq, created_at, last_message_at,
- status_state, current_detail, active_call_id,
- title, model, handle, repo, branch, capabilities
- FROM sessions WHERE agent_id = ?1 AND session_id = ?2",
- params![agent_id, session_id],
- map_session_row,
- )
- .optional()
- .map_err(Into::into)
-}
-
-/// Load the most recent `limit` messages for a session, returned in chronological
-/// (oldest-first) order so the graph reads them like a transcript.
-pub fn list_recent_messages(
- conn: &Connection,
- agent_id: &str,
- session_id: &str,
- limit: u32,
-) -> Result<Vec<OrchestrationMessage>> {
- let mut stmt = conn.prepare(
- "SELECT id, agent_id, session_id, chat_kind, role, body, timestamp, seq,
- event_kind, tool_name, call_id, ok, is_error, exit_code
- FROM messages WHERE agent_id = ?1 AND session_id = ?2
- ORDER BY timestamp DESC, seq DESC LIMIT ?3",
- )?;
- let rows = stmt
- .query_map(params![agent_id, session_id, limit], map_message_row)?
- .collect::<std::result::Result<Vec<_>, _>>()?;
- // Reverse the DESC scan back to chronological order.
- Ok(rows.into_iter().rev().collect())
-}
-
-// ── Device world-observation buffer (hosted-brain uploader) ──────────────────
-
-/// One buffered world-observation row awaiting upload to the hosted brain.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct WorldObs {
- pub id: i64,
- pub session_id: String,
- pub seq: i64,
- pub note: String,
- pub ts: i64,
-}
-
-/// Append one device-observed world note. `seq` is a global monotonic ordinal
-/// (unique within any single session, which is all the backend dedupe on
-/// `(userId, sessionId, seq)` requires). Returns the assigned seq.
-/// Buffer a world observation for the periodic world-diff uploader.
-///
-/// `seq` is drawn from the **persistent, monotonic** `world_obs:next_seq` counter in
-/// `kv` — it must never reset. The backend dedupes world-diff entries on
-/// `(userId, sessionId, seq)`, and the uploader deletes every row after a successful
-/// push ([`delete_world_obs`]), so a `MAX(seq)+1`-over-the-table scheme restarts at
-/// `1` once the buffer drains and reuses seqs the backend already saw — it then
-/// treats the fresh observation as a duplicate `202` no-op and silently drops it, so
-/// only the first batch per session ever reaches the hosted subconscious tier. The
-/// counter is seeded above any still-buffered row so an upgraded DB with pending rows
-/// can't collide either, and the allocate-then-insert runs in an immediate txn so two
-/// concurrent appends can't draw the same ordinal.
-pub fn append_world_obs(conn: &Connection, session_id: &str, note: &str, ts: i64) -> Result<i64> {
- in_immediate_txn(conn, |conn| {
- let kv_max: i64 = kv_get(conn, "world_obs:next_seq")?
- .and_then(|v| v.parse::<i64>().ok())
- .unwrap_or(0);
- let table_max: i64 =
- conn.query_row("SELECT COALESCE(MAX(seq), 0) FROM world_obs", [], |r| {
- r.get(0)
- })?;
- let next_seq = kv_max.max(table_max) + 1;
- kv_set(conn, "world_obs:next_seq", &next_seq.to_string())?;
- conn.execute(
- "INSERT INTO world_obs (session_id, seq, note, ts) VALUES (?1, ?2, ?3, ?4)",
- params![session_id, next_seq, note, ts],
- )?;
- Ok(next_seq)
- })
-}
-
-/// Drain up to `limit` oldest buffered world observations (FIFO by insert order).
-/// Rows stay until [`delete_world_obs`] confirms a successful upload, so a failed
-/// flush retries on the next tick.
-pub fn drain_world_obs(conn: &Connection, limit: u32) -> Result<Vec<WorldObs>> {
- let mut stmt = conn
- .prepare("SELECT id, session_id, seq, note, ts FROM world_obs ORDER BY id ASC LIMIT ?1")?;
- let rows = stmt
- .query_map(params![limit], |r| {
- Ok(WorldObs {
- id: r.get(0)?,
- session_id: r.get(1)?,
- seq: r.get(2)?,
- note: r.get(3)?,
- ts: r.get(4)?,
- })
- })?
- .collect::<std::result::Result<Vec<_>, _>>()?;
- Ok(rows)
-}
-
-/// Delete buffered world observations by id after a confirmed upload.
-pub fn delete_world_obs(conn: &Connection, ids: &[i64]) -> Result<()> {
- for id in ids {
- conn.execute("DELETE FROM world_obs WHERE id = ?1", params![id])?;
- }
- Ok(())
-}
-
-/// Read a `kv` value (used for the per-session idempotence cursor).
-pub fn kv_get(conn: &Connection, key: &str) -> Result<Option<String>> {
- conn.query_row("SELECT v FROM kv WHERE k = ?1", params![key], |r| r.get(0))
- .optional()
- .map_err(Into::into)
-}
-
-/// Write a `kv` value (upsert).
-pub fn kv_set(conn: &Connection, key: &str, value: &str) -> Result<()> {
- conn.execute(
- "INSERT INTO kv (k, v) VALUES (?1, ?2)
- ON CONFLICT(k) DO UPDATE SET v = excluded.v",
- params![key, value],
- )?;
- Ok(())
-}
-
-/// Delete a `kv` value (no-op if absent).
-pub fn kv_delete(conn: &Connection, key: &str) -> Result<()> {
- conn.execute("DELETE FROM kv WHERE k = ?1", params![key])?;
- Ok(())
-}
-
-// ── Outbound-ask correlation (Master chat, W7) ───────────────────────────────
-//
-// When OpenHuman DMs a peer on the user's behalf (`orchestration_send_to_agent`),
-// we record a ONE-SHOT pending ask keyed by the outbound session id, mapping it
-// to the window the ask originated from (usually `master`). When the peer's reply
-// lands under that session id (shared `wrapper_session_id`), the wake path threads
-// the answer back into the origin window instead of auto-replying to the peer.
-//
-// This is a pragmatic 1:1 request/response correlation: it assumes the next
-// inbound message on the ask session is the answer. A robust many-in-flight
-// correlation needs an explicit envelope `inReplyTo` (tracked as F3 / #4583's
-// follow-ups); until then this covers the common single-ask case.
-
-/// Scope the pending-ask key by BOTH the answering peer and the session id.
-/// Sessions/checkpoints are keyed by `(agent, session)`, and legacy wrapper
-/// session ids can collide across peers (see the F2 checkpoint fix); keying by
-/// session id alone would let a *different* peer's inbound on a shared legacy
-/// session id consume the ask and misroute the reply.
-fn pending_ask_key(peer_agent_id: &str, ask_session_id: &str) -> String {
- format!("pending_ask:{peer_agent_id}:{ask_session_id}")
-}
-
-/// Record a one-shot pending outbound ask: `(peer_agent_id, ask_session_id)` →
-/// `origin_session_id`.
-pub fn set_pending_ask(
- conn: &Connection,
- peer_agent_id: &str,
- ask_session_id: &str,
- origin_session_id: &str,
-) -> Result<()> {
- kv_set(
- conn,
- &pending_ask_key(peer_agent_id, ask_session_id),
- origin_session_id,
- )
-}
-
-/// The origin window for a pending ask on `(peer_agent_id, ask_session_id)`.
-pub fn pending_ask_origin(
- conn: &Connection,
- peer_agent_id: &str,
- ask_session_id: &str,
-) -> Result<Option<String>> {
- kv_get(conn, &pending_ask_key(peer_agent_id, ask_session_id))
-}
-
-/// Clear a pending ask once its answer has been threaded back (one-shot).
-pub fn clear_pending_ask(
- conn: &Connection,
- peer_agent_id: &str,
- ask_session_id: &str,
-) -> Result<()> {
- kv_delete(conn, &pending_ask_key(peer_agent_id, ask_session_id))
-}
-
-#[cfg(test)]
-mod tests {
- use super::super::types::ChatKind;
- use super::*;
-
- fn msg(id: &str, agent: &str, session: &str, seq: i64) -> OrchestrationMessage {
- OrchestrationMessage {
- id: id.into(),
- agent_id: agent.into(),
- session_id: session.into(),
- chat_kind: ChatKind::Session,
- role: "agent".into(),
- body: "hi".into(),
- timestamp: "2026-07-02T00:00:00Z".into(),
- seq,
- ..Default::default()
- }
- }
-
- fn session(agent: &str, session: &str, seq: i64) -> OrchestrationSession {
- OrchestrationSession {
- session_id: session.into(),
- agent_id: agent.into(),
- source: "claude".into(),
- label: None,
- workspace: None,
- last_seq: seq,
- created_at: "2026-07-02T00:00:00Z".into(),
- last_message_at: "2026-07-02T00:00:00Z".into(),
- ..Default::default()
- }
- }
-
- #[test]
- fn persists_and_dedupes_by_message_id() {
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- upsert_session(conn, &session("@a", "h1", 1))?;
- assert!(!message_exists(conn, "m1")?);
- assert!(insert_message(conn, &msg("m1", "@a", "h1", 1))?);
- // Replay of the same id is a no-op and stays deduped.
- assert!(!insert_message(conn, &msg("m1", "@a", "h1", 1))?);
- assert!(message_exists(conn, "m1")?);
- assert_eq!(count_messages(conn, "@a", "h1")?, 1);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn clear_message_event_kind_unhides_a_hidden_row() {
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- upsert_session(conn, &session("@a", "master", 1))?;
- let hidden = OrchestrationMessage {
- event_kind: Some("lifecycle".into()),
- ..msg("tool-completion:cyc:1", "@a", "master", 1)
- };
- insert_message(conn, &hidden)?;
- // Hidden from the transcript while event_kind is an excluded kind.
- assert!(list_messages_by_session(conn, "master", 50, None)?.is_empty());
- // Un-hiding it (clear event_kind) makes it visible again.
- assert!(clear_message_event_kind(conn, "tool-completion:cyc:1")?);
- let visible = list_messages_by_session(conn, "master", 50, None)?;
- assert_eq!(visible.len(), 1);
- assert_eq!(visible[0].id, "tool-completion:cyc:1");
- // A non-existent id changes nothing.
- assert!(!clear_message_event_kind(conn, "nope")?);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn persists_and_reads_back_tool_result_outcome() {
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- upsert_session(conn, &session("@a", "h1", 1))?;
- let failed = OrchestrationMessage {
- event_kind: Some("tool_result".into()),
- tool_name: Some("Bash".into()),
- call_id: Some("c1".into()),
- ok: Some(false),
- is_error: Some(true),
- exit_code: Some(1),
- ..msg("m1", "@a", "h1", 1)
- };
- assert!(insert_message(conn, &failed)?);
- let back = list_recent_messages(conn, "@a", "h1", 10)?;
- assert_eq!(back.len(), 1);
- assert_eq!(back[0].ok, Some(false));
- assert_eq!(back[0].is_error, Some(true));
- assert_eq!(back[0].exit_code, Some(1));
- // A plain message leaves the outcome columns NULL → None on read.
- assert!(insert_message(conn, &msg("m2", "@a", "h1", 2))?);
- let plain = list_recent_messages(conn, "@a", "h1", 10)?;
- let m2 = plain.iter().find(|m| m.id == "m2").unwrap();
- assert_eq!(m2.ok, None);
- assert_eq!(m2.is_error, None);
- assert_eq!(m2.exit_code, None);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn latest_message_preview_returns_newest_or_none() {
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- upsert_session(conn, &session("@a", "h1", 1))?;
- // No messages yet.
- assert_eq!(latest_message_preview(conn, "@a", "h1")?, None);
-
- // Same timestamp → newest is decided by seq DESC.
- insert_message(conn, &msg("m1", "@a", "h1", 1))?;
- let mut newer = msg("m2", "@a", "h1", 2);
- newer.body = "later line".into();
- insert_message(conn, &newer)?;
- assert_eq!(
- latest_message_preview(conn, "@a", "h1")?.as_deref(),
- Some("later line")
- );
-
- // Scoped to (agent, session): a different session is not returned.
- assert_eq!(latest_message_preview(conn, "@a", "other")?, None);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn capabilities_codec_round_trips_and_is_null_safe() {
- // Non-empty → JSON array; decodes back identically.
- let caps = vec!["agent_message".to_string(), "tool_call".to_string()];
- let encoded = encode_capabilities(&caps).expect("non-empty encodes");
- assert_eq!(encoded, r#"["agent_message","tool_call"]"#);
- assert_eq!(decode_capabilities(Some(encoded)), caps);
-
- // Empty → NULL (so the COALESCE upsert treats it as "no update").
- assert_eq!(encode_capabilities(&[]), None);
-
- // NULL / malformed decode to an empty list, never an error.
- assert!(decode_capabilities(None).is_empty());
- assert!(decode_capabilities(Some("not json".into())).is_empty());
- }
-
- #[test]
- fn session_info_enrichment_persists_and_coalesces_across_upserts() {
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- // First upsert carries the full intro.
- let intro = OrchestrationSession {
- title: Some("Intro".into()),
- model: Some("opus".into()),
- handle: Some("@alice".into()),
- repo: Some("org/myrepo".into()),
- branch: Some("feat/x".into()),
- capabilities: vec!["agent_message".into()],
- ..session("@a", "h1", 0)
- };
- upsert_session(conn, &intro)?;
- let loaded = load_session(conn, "@a", "h1")?.expect("session");
- assert_eq!(loaded.title.as_deref(), Some("Intro"));
- assert_eq!(loaded.capabilities, vec!["agent_message".to_string()]);
-
- // A subsequent upsert with NO enrichment (e.g. a content event) must
- // COALESCE — the intro metadata survives.
- upsert_session(conn, &session("@a", "h1", 1))?;
- let after = load_session(conn, "@a", "h1")?.expect("session");
- assert_eq!(
- after.title.as_deref(),
- Some("Intro"),
- "title survives a bare upsert"
- );
- assert_eq!(after.model.as_deref(), Some("opus"));
- assert_eq!(after.capabilities, vec!["agent_message".to_string()]);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn status_lifecycle_unknown_rows_are_hidden_from_thread_and_unread() {
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- upsert_session(conn, &session("@a", "h1", 1))?;
-
- // A v1 row (no event_kind) and typed content rows stay visible;
- // status/lifecycle/unknown/session_info are persisted (for relay dedup)
- // but must not surface in the thread or the unread count.
- let mut plain = msg("v1", "@a", "h1", 1);
- plain.timestamp = "2026-07-02T00:00:01Z".into();
- insert_message(conn, &plain)?;
-
- let mut call = msg("call", "@a", "h1", 2);
- call.event_kind = Some("tool_call".into());
- call.timestamp = "2026-07-02T00:00:02Z".into();
- insert_message(conn, &call)?;
-
- for (id, kind, seq) in [
- ("st", "status", 3),
- ("lc", "lifecycle", 4),
- ("uk", "unknown", 5),
- ("si", "session_info", 6),
- ] {
- let mut hidden = msg(id, "@a", "h1", seq);
- hidden.event_kind = Some(kind.into());
- hidden.timestamp = format!("2026-07-02T00:00:0{seq}Z");
- insert_message(conn, &hidden)?;
- }
-
- let thread = list_messages_by_session(conn, "h1", 50, None)?;
- let ids: Vec<&str> = thread.iter().map(|m| m.id.as_str()).collect();
- assert_eq!(ids, vec!["v1", "call"], "only v1 + typed content rows");
-
- // Unread (cursor at 0) counts the two visible rows, not the 4 hidden.
- assert_eq!(unread_count(conn, "h1")?, 2);
- // UI session summaries use the same visibility predicate as unread and
- // transcript reads, while the raw observability count still includes
- // all persisted relay-dedupe rows.
- assert_eq!(count_visible_messages(conn, "@a", "h1")?, 2);
- assert_eq!(count_messages(conn, "@a", "h1")?, 6);
-
- let mut other_peer = msg("other-peer", "@b", "h1", 7);
- other_peer.timestamp = "2026-07-02T00:00:07Z".into();
- insert_message(conn, &other_peer)?;
- assert_eq!(count_visible_messages(conn, "@a", "h1")?, 2);
- assert_eq!(count_visible_messages_by_session(conn, "h1")?, 3);
- let by_agent_session = visible_message_counts(conn)?;
- assert_eq!(
- by_agent_session.get(&("@a".to_string(), "h1".to_string())),
- Some(&2)
- );
- assert_eq!(
- by_agent_session.get(&("@b".to_string(), "h1".to_string())),
- Some(&1)
- );
- let by_session = visible_message_counts_by_session(conn)?;
- assert_eq!(by_session.get("h1"), Some(&3));
-
- // Roster preview skips the hidden rows → newest visible is the call.
- assert_eq!(
- latest_message_preview(conn, "@a", "h1")?.as_deref(),
- Some("hi"),
- );
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn read_surface_lists_sessions_messages_and_tracks_unread() {
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- // Two sessions: a harness session and the pinned master window.
- upsert_session(conn, &session("@peer", "h1", 2))?;
- insert_message(conn, &msg("m1", "@peer", "h1", 1))?;
- let mut m2 = msg("m2", "@peer", "h1", 2);
- m2.timestamp = "2026-07-02T00:05:00Z".into();
- insert_message(conn, &m2)?;
-
- // list_sessions returns the row; messages come back chronologically.
- let sessions = list_sessions(conn)?;
- assert_eq!(sessions.len(), 1);
- assert_eq!(sessions[0].session_id, "h1");
- let msgs = list_messages_by_session(conn, "h1", 100, None)?;
- assert_eq!(
- msgs.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(),
- vec!["m1", "m2"]
- );
-
- // Both messages are unread until we mark the chat read.
- assert_eq!(unread_count(conn, "h1")?, 2);
- mark_chat_read(conn, "h1")?;
- assert_eq!(unread_count(conn, "h1")?, 0);
-
- // `before` pages backwards (exclusive).
- let older = list_messages_by_session(conn, "h1", 100, Some("2026-07-02T00:05:00Z"))?;
- assert_eq!(older.len(), 1);
- assert_eq!(older[0].id, "m1");
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn unread_counts_batches_and_matches_scalar_unread_count() {
- // The batched unread_counts() must equal the per-session scalar
- // unread_count() for every session, across: no cursor (all unread), a
- // mid-stream cursor (partial), fully read (zero), a hidden (excluded
- // event_kind) row, and a session with no messages.
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- // h1: two messages, never marked read -> 2 unread.
- upsert_session(conn, &session("@a", "h1", 2))?;
- insert_message(conn, &msg("a1", "@a", "h1", 1))?;
- insert_message(conn, &msg("a2", "@a", "h1", 2))?;
-
- // h2: read up to the first message, then a newer one arrives -> 1 unread.
- upsert_session(conn, &session("@b", "h2", 2))?;
- insert_message(conn, &msg("b1", "@b", "h2", 1))?;
- mark_chat_read(conn, "h2")?;
- let mut b2 = msg("b2", "@b", "h2", 2);
- b2.timestamp = "2026-07-02T00:05:00Z".into();
- insert_message(conn, &b2)?;
-
- // h3: fully read -> 0 unread (absent from the map).
- upsert_session(conn, &session("@c", "h3", 1))?;
- insert_message(conn, &msg("c1", "@c", "h3", 1))?;
- mark_chat_read(conn, "h3")?;
-
- // h4: one visible + one hidden (excluded event_kind) -> 1 unread.
- upsert_session(conn, &session("@d", "h4", 2))?;
- insert_message(conn, &msg("d1", "@d", "h4", 1))?;
- let hidden = OrchestrationMessage {
- event_kind: Some("lifecycle".into()),
- ..msg("d2", "@d", "h4", 2)
- };
- insert_message(conn, &hidden)?;
-
- // h5: session with no messages -> 0 unread (absent from the map).
- upsert_session(conn, &session("@e", "h5", 0))?;
-
- let batched = unread_counts(conn)?;
- for sid in ["h1", "h2", "h3", "h4", "h5"] {
- assert_eq!(
- batched.get(sid).copied().unwrap_or(0),
- unread_count(conn, sid)?,
- "batched unread mismatch for {sid}"
- );
- }
-
- // Concrete expectations, and zero-unread sessions dropped from the map.
- assert_eq!(batched.get("h1").copied(), Some(2));
- assert_eq!(batched.get("h2").copied(), Some(1));
- assert_eq!(batched.get("h4").copied(), Some(1));
- assert_eq!(batched.get("h3"), None);
- assert_eq!(batched.get("h5"), None);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn latest_master_peer_resolves_the_send_recipient() {
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- assert!(latest_master_peer(conn)?.is_none());
- let mut master = msg("mm", "@owner-agent", "master", 0);
- master.chat_kind = ChatKind::Master;
- insert_message(conn, &master)?;
- assert_eq!(latest_master_peer(conn)?.as_deref(), Some("@owner-agent"));
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn latest_session_for_agent_reuses_newest_thread_and_ignores_pinned() {
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- // No thread with the peer yet → caller mints a fresh id.
- assert!(latest_session_for_agent(conn, "@peer")?.is_none());
-
- // Two threads with the peer; the newest by last_message_at wins.
- let mut old = session("@peer", "s-old", 1);
- old.last_message_at = "2026-07-02T00:01:00Z".into();
- upsert_session(conn, &old)?;
- let mut new = session("@peer", "s-new", 1);
- new.last_message_at = "2026-07-02T00:09:00Z".into();
- upsert_session(conn, &new)?;
- assert_eq!(
- latest_session_for_agent(conn, "@peer")?.as_deref(),
- Some("s-new")
- );
-
- // A pinned window for the same agent id must never be reused.
- let mut pinned = session("@peer", "master", 1);
- pinned.last_message_at = "2026-07-02T23:00:00Z".into();
- upsert_session(conn, &pinned)?;
- assert_eq!(
- latest_session_for_agent(conn, "@peer")?.as_deref(),
- Some("s-new"),
- "pinned window excluded despite newer timestamp"
- );
-
- // Scoped by agent: a different peer has no thread.
- assert!(latest_session_for_agent(conn, "@other")?.is_none());
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn pending_ask_correlation_is_one_shot() {
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- // Nothing pending initially.
- assert!(pending_ask_origin(conn, "peer-a", "s-ask")?.is_none());
- // Record an ask to `peer-a` on session `s-ask` from the master window.
- set_pending_ask(conn, "peer-a", "s-ask", "master")?;
- assert_eq!(
- pending_ask_origin(conn, "peer-a", "s-ask")?.as_deref(),
- Some("master")
- );
- // Scoped by (agent, session) — same session id under a DIFFERENT peer
- // must not satisfy the ask (legacy session-id collision guard).
- assert!(pending_ask_origin(conn, "peer-b", "s-ask")?.is_none());
- // A different session under the same peer is also unaffected.
- assert!(pending_ask_origin(conn, "peer-a", "s-other")?.is_none());
- // Clearing consumes it (one-shot).
- clear_pending_ask(conn, "peer-a", "s-ask")?;
- assert!(pending_ask_origin(conn, "peer-a", "s-ask")?.is_none());
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn upsert_advances_last_seq_monotonically() {
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- upsert_session(conn, &session("@a", "h1", 5))?;
- upsert_session(conn, &session("@a", "h1", 2))?; // lower seq must not regress
- let seq: i64 = conn.query_row(
- "SELECT last_seq FROM sessions WHERE agent_id='@a' AND session_id='h1'",
- [],
- |r| r.get(0),
- )?;
- assert_eq!(seq, 5);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn migrates_pre_v2_schema_by_adding_session_and_message_columns() {
- // A store created before the harness-session-v2 receiver: the sessions and
- // messages tables lack the new run-state / event columns. Opening through
- // `with_connection` must add them additively (existing rows read NULL) and
- // then accept writes that populate them — proving the ALTER path, not just
- // the fresh-DDL path, works.
- let tmp = tempfile::tempdir().unwrap();
- let db_path = tmp.path().join("orchestration").join("orchestration.db");
- std::fs::create_dir_all(db_path.parent().unwrap()).unwrap();
- {
- let conn = Connection::open(&db_path).unwrap();
- conn.execute_batch(
- "CREATE TABLE sessions (
- session_id TEXT NOT NULL, agent_id TEXT NOT NULL, source TEXT NOT NULL,
- label TEXT, workspace TEXT, last_seq INTEGER NOT NULL DEFAULT 0,
- created_at TEXT NOT NULL, last_message_at TEXT NOT NULL,
- PRIMARY KEY (agent_id, session_id));
- CREATE TABLE messages (
- id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, session_id TEXT NOT NULL,
- chat_kind TEXT NOT NULL, role TEXT NOT NULL, body TEXT NOT NULL,
- timestamp TEXT NOT NULL, seq INTEGER NOT NULL DEFAULT 0);",
- )
- .unwrap();
- // A legacy row predating the new columns.
- conn.execute(
- "INSERT INTO sessions
- (session_id, agent_id, source, last_seq, created_at, last_message_at)
- VALUES ('h-old', '@a', 'claude', 1, 't', 't')",
- [],
- )
- .unwrap();
- conn.execute(
- "INSERT INTO messages
- (id, agent_id, session_id, chat_kind, role, body, timestamp, seq)
- VALUES ('m-old', '@a', 'h-old', 'session', 'agent', 'legacy body', 't', 1)",
- [],
- )
- .unwrap();
- }
-
- with_connection(tmp.path(), |conn| {
- // New columns now exist on both tables.
- for (table, column) in [
- ("sessions", "status_state"),
- ("sessions", "current_detail"),
- ("sessions", "active_call_id"),
- ("sessions", "title"),
- ("sessions", "model"),
- ("sessions", "handle"),
- ("sessions", "repo"),
- ("sessions", "branch"),
- ("sessions", "capabilities"),
- ("messages", "event_kind"),
- ("messages", "tool_name"),
- ("messages", "call_id"),
- ("messages", "ok"),
- ("messages", "is_error"),
- ("messages", "exit_code"),
- ] {
- assert!(
- column_exists(conn, table, column)?,
- "{table}.{column} must be added by migration"
- );
- }
-
- // The legacy rows still read; the new fields come back NULL (None).
- let old = load_session(conn, "@a", "h-old")?.expect("legacy session survives");
- assert_eq!(old.source, "claude");
- assert_eq!(old.status_state, None);
- assert_eq!(old.current_detail, None);
- let msgs = list_recent_messages(conn, "@a", "h-old", 10)?;
- assert_eq!(msgs.len(), 1);
- assert_eq!(msgs[0].body, "legacy body");
- assert_eq!(msgs[0].event_kind, None);
- assert_eq!(msgs[0].ok, None);
- assert_eq!(msgs[0].is_error, None);
- assert_eq!(msgs[0].exit_code, None);
-
- // And the upgraded schema accepts writes that populate the new fields.
- upsert_session(
- conn,
- &OrchestrationSession {
- status_state: Some("running".into()),
- current_detail: Some("compiling".into()),
- active_call_id: Some("call-1".into()),
- ..session("@a", "h-old", 1)
- },
- )?;
- let updated = load_session(conn, "@a", "h-old")?.unwrap();
- assert_eq!(updated.status_state.as_deref(), Some("running"));
- assert_eq!(updated.current_detail.as_deref(), Some("compiling"));
- assert_eq!(updated.active_call_id.as_deref(), Some("call-1"));
- let tool_result = OrchestrationMessage {
- event_kind: Some("tool_result".into()),
- tool_name: Some("Bash".into()),
- call_id: Some("call-1".into()),
- ok: Some(false),
- is_error: Some(true),
- exit_code: Some(1),
- ..msg("m-new", "@a", "h-old", 2)
- };
- assert!(insert_message(conn, &tool_result)?);
- let upgraded_messages = list_recent_messages(conn, "@a", "h-old", 10)?;
- let saved = upgraded_messages
- .iter()
- .find(|m| m.id == "m-new")
- .expect("upgraded schema stores outcome fields");
- assert_eq!(saved.ok, Some(false));
- assert_eq!(saved.is_error, Some(true));
- assert_eq!(saved.exit_code, Some(1));
- Ok(())
- })
- .unwrap();
-
- // Re-opening is idempotent — the ADD COLUMN guard must not error the second
- // time (no `duplicate column name`).
- with_connection(tmp.path(), |conn| {
- assert!(column_exists(conn, "messages", "call_id")?);
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn with_connection_enables_wal_journal_mode() {
- // WAL is what lets the one-time `migrate()` ALTERs run without being
- // starved into SQLITE_BUSY by a concurrent reader (see with_connection).
- let tmp = tempfile::tempdir().unwrap();
- with_connection(tmp.path(), |conn| {
- let mode: String = conn.query_row("PRAGMA journal_mode", [], |r| r.get(0))?;
- assert_eq!(mode.to_lowercase(), "wal", "orchestration DB runs in WAL");
- Ok(())
- })
- .unwrap();
- }
-
- #[test]
- fn migrates_pre_v2_schema_while_a_reader_is_open() {
- // Reproduces the "migrate orchestration schema" failure: a legacy store
- // missing the v2 columns is opened while another connection holds a read
- // lock (the drain loop). Under WAL the schema-modifying ADD COLUMNs must
- // still succeed instead of timing out on the reader's lock.
- let tmp = tempfile::tempdir().unwrap();
- let db_path = tmp.path().join("orchestration").join("orchestration.db");
- std::fs::create_dir_all(db_path.parent().unwrap()).unwrap();
- {
- let conn = Connection::open(&db_path).unwrap();
- conn.execute_batch(
- "CREATE TABLE sessions (
- session_id TEXT NOT NULL, agent_id TEXT NOT NULL, source TEXT NOT NULL,
- label TEXT, workspace TEXT, last_seq INTEGER NOT NULL DEFAULT 0,
- created_at TEXT NOT NULL, last_message_at TEXT NOT NULL,
- PRIMARY KEY (agent_id, session_id));
- CREATE TABLE messages (
- id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, session_id TEXT NOT NULL,
- chat_kind TEXT NOT NULL, role TEXT NOT NULL, body TEXT NOT NULL,
- timestamp TEXT NOT NULL, seq INTEGER NOT NULL DEFAULT 0);",
- )
- .unwrap();
- }
-
- // A second connection sitting on an open read transaction, mimicking the
- // drain having the DB open when the UI's sessions_list triggers migrate.
- let reader = Connection::open(&db_path).unwrap();
- reader
- .busy_timeout(std::time::Duration::from_secs(5))
- .unwrap();
- reader
- .query_row("PRAGMA journal_mode = WAL", [], |_| Ok(()))
- .unwrap();
- reader
- .execute_batch("BEGIN; SELECT COUNT(*) FROM messages;")
- .unwrap();
-
- // Migration through with_connection must not be starved by the reader.
- with_connection(tmp.path(), |conn| {
- assert!(column_exists(conn, "messages", "ok")?);
- assert!(column_exists(conn, "sessions", "capabilities")?);
- Ok(())
- })
- .expect("migration succeeds despite a concurrently-held reader");
-
- reader.execute_batch("COMMIT").unwrap();
- }
-
- #[test]
- fn in_immediate_txn_serialises_concurrent_seq_allocation() {
- // Two writers on the same (agent, session) — the drain's inbound persist
- // and the graph's send_dm reply persist — must not read the same
- // MAX(seq) and duplicate it. Allocate + insert under `in_immediate_txn`
- // from several threads and assert every seq is distinct and contiguous.
- use std::sync::Arc;
- let tmp = Arc::new(tempfile::tempdir().unwrap());
- with_connection(tmp.path(), |_| Ok(())).expect("initialise orchestration store");
- let db_path = Arc::new(tmp.path().join("orchestration").join("orchestration.db"));
- let n = 8usize;
- let handles: Vec<_> = (0..n)
- .map(|i| {
- let db_path = Arc::clone(&db_path);
- std::thread::spawn(move || {
- let c = Connection::open(&*db_path).expect("open orchestration db");
- c.busy_timeout(std::time::Duration::from_secs(5))
- .expect("set busy timeout");
- in_immediate_txn(&c, |c| {
- let seq = next_session_seq(c, "@peer", "s1")?;
- insert_message(c, &msg(&format!("m{i}"), "@peer", "s1", seq))?;
- Ok(seq)
- })
- .expect("txn ok")
- })
- })
- .collect();
- let mut seqs: Vec<i64> = handles.into_iter().map(|h| h.join().unwrap()).collect();
- seqs.sort_unstable();
- let mut unique = seqs.clone();
- unique.dedup();
- assert_eq!(
- unique.len(),
- n,
- "concurrent seq allocation must not duplicate: {seqs:?}"
- );
- assert_eq!(
- seqs,
- (1..=n as i64).collect::<Vec<_>>(),
- "seqs must be a contiguous 1..=n range"
- );
- }
-}
diff --git a/src/openhuman/hosted/orchestration/sync.rs b/src/openhuman/hosted/orchestration/sync.rs
deleted file mode 100644
index 02980a6783..0000000000
--- a/src/openhuman/hosted/orchestration/sync.rs
+++ /dev/null
@@ -1,237 +0,0 @@
-//! Hosted read-surface sync + reachability.
-//!
-//! The device renders the hosted brain's state. This loop pulls the hosted read
-//! surface (`GET /orchestration/v1/{sessions,sessions/:id/messages}`)
-//! into the local SQLite **render cache**, so the existing read handlers stay
-//! synchronous and offline-safe: they read the cache (which is hosted-sourced
-//! and kept fresh here + by live effects), and when the hosted brain is
-//! unreachable the cache is the fallback and `cloud_reachable` drives the
-//! "cloud brain unreachable" notice.
-//!
-//! Message sync is seq-gated (`?after=<local max>`), so the device's own
-//! forwarded turns are never re-inserted — only turns it is missing (e.g.
-//! authored on another device) are pulled in.
-
-use std::time::Duration;
-
-use serde::Deserialize;
-
-use crate::openhuman::config::Config;
-
-use super::store;
-use super::types::{ChatKind, OrchestrationMessage, OrchestrationSession};
-
-const LOG: &str = "orchestration";
-
-/// `kv` key: `"1"` when the last sync reached the hosted brain, `"0"` when not.
-pub const REACHABLE_KEY: &str = "orch:cloud_reachable";
-/// Default cadence of the read-sync loop.
-pub const DEFAULT_SYNC_INTERVAL: Duration = Duration::from_secs(20);
-
-/// Max sessions whose messages we page in per sync pass — bounds one sweep.
-const MAX_SESSIONS_PER_SYNC: usize = 100;
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct HostedSession {
- session_id: String,
- #[serde(default)]
- counterpart_agent_id: String,
- #[serde(default)]
- last_seq: i64,
- #[serde(default)]
- status: String,
- #[serde(default)]
- last_event_ts: Option<i64>,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct HostedMessage {
- seq: i64,
- #[serde(default)]
- role: String,
- #[serde(default)]
- body: String,
- #[serde(default)]
- kind: String,
- #[serde(default)]
- ts: i64,
- #[serde(default)]
- cycle_id: String,
-}
-
-fn chat_kind_for(session_id: &str) -> ChatKind {
- match session_id {
- "master" => ChatKind::Master,
- "subconscious" => ChatKind::Subconscious,
- _ => ChatKind::Session,
- }
-}
-
-/// Epoch-millis → RFC3339, falling back to now on a zero/invalid stamp so a row
-/// always has a sortable timestamp.
-fn ms_to_rfc3339(ms: i64) -> String {
- chrono::DateTime::<chrono::Utc>::from_timestamp_millis(ms)
- .unwrap_or_else(chrono::Utc::now)
- .to_rfc3339()
-}
-
-/// One sync pass: pull hosted sessions + missing messages into the render cache
-/// and update reachability. Returns whether the hosted brain was reachable
-/// (a `GET /sessions` success).
-pub async fn sync_reads(config: &Config) -> bool {
- // Resolve the token + backend client once and reuse them for every GET in this
- // pass (sessions + per-session messages), so the profile lookup and the
- // reqwest connection pool aren't rebuilt on each request.
- let pass = match super::cloud::read_pass(config) {
- Ok(p) => p,
- Err(e) => {
- log::debug!(target: LOG, "[orchestration] sync.unreachable: {e}");
- let _ = store::with_connection(&config.workspace_dir, |c| {
- store::kv_set(c, REACHABLE_KEY, "0")
- });
- return false;
- }
- };
- let sessions_raw = match pass.fetch_sessions().await {
- Ok(v) => v,
- Err(e) => {
- log::debug!(target: LOG, "[orchestration] sync.unreachable: {e}");
- let _ = store::with_connection(&config.workspace_dir, |c| {
- store::kv_set(c, REACHABLE_KEY, "0")
- });
- return false;
- }
- };
-
- // Reachable — mark it before the best-effort detail sync so the offline
- // notice clears even if a per-session page fails.
- let _ = store::with_connection(&config.workspace_dir, |c| {
- store::kv_set(c, REACHABLE_KEY, "1")
- });
-
- let sessions: Vec<HostedSession> = serde_json::from_value(sessions_raw).unwrap_or_default();
- for session in sessions.into_iter().take(MAX_SESSIONS_PER_SYNC) {
- // INVARIANT: `counterpart_agent_id` is the opaque handle the device itself
- // forwarded as `counterpartAgentId` (base64 `envelope.from`, see
- // `ingest::forward_event`), echoed back verbatim — the hosted brain routes on
- // it without decoding, it is not a credential. It therefore string-equals the
- // `agent_id` under which ingest / `persist_reply` stored the device's own
- // rows, which is what lets `local_max` below skip re-paging the device's
- // forwarded turns. Every device-side session row keys on this same base64 form
- // (ingest, this sync, and the send_dm mirror), so the encodings never diverge
- // locally. If the backend is ever changed to re-encode agent keys (e.g. to the
- // base58 pairing form), resolve this through `ingest::decode_agent_key` before
- // deriving `agent_id`/`local_max`, or the same session would be inserted twice
- // under two encodings and every turn would render twice.
- let agent_id = if session.counterpart_agent_id.is_empty() {
- session.session_id.clone()
- } else {
- session.counterpart_agent_id.clone()
- };
- // `created_at` is a cosmetic "first seen" time that never advances, so a
- // synthesized `now` is harmless there. `last_message_at` feeds
- // `handle_status`'s `MAX(last_message_at)` ingest-staleness check, so it must
- // NOT be synthesized from `now`: a quiet hosted session with no `lastEventTs`
- // would otherwise look fresh on every 20s tick and mask real staleness. Leave
- // it empty so the upsert's `MAX()` preserves any real prior timestamp instead.
- let event_at = session.last_event_ts.map(ms_to_rfc3339);
- let created_at = event_at
- .clone()
- .unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
- let last_message_at = event_at.unwrap_or_default();
-
- // Session metadata (status/last_seq) renders from hosted; COALESCE in
- // `upsert_session` preserves device-local enrichment (label, presence).
- let status_state = (!session.status.is_empty()).then(|| session.status.clone());
- let upsert = store::with_connection(&config.workspace_dir, |conn| {
- store::upsert_session(
- conn,
- &OrchestrationSession {
- session_id: session.session_id.clone(),
- agent_id: agent_id.clone(),
- source: "hosted".to_string(),
- last_seq: session.last_seq,
- created_at: created_at.clone(),
- last_message_at: last_message_at.clone(),
- status_state: status_state.clone(),
- ..Default::default()
- },
- )
- });
- if let Err(e) = upsert {
- log::warn!(target: LOG, "[orchestration] sync.session_upsert_failed session={} err={e}", session.session_id);
- continue;
- }
-
- // Page in only messages the device is missing (seq > local max), so its
- // own forwarded turns are never duplicated.
- let local_max = store::with_connection(&config.workspace_dir, |c| {
- store::next_session_seq(c, &agent_id, &session.session_id)
- })
- .map(|next| next - 1)
- .unwrap_or(0);
-
- let msgs_raw = match pass
- .fetch_messages(&session.session_id, Some(local_max))
- .await
- {
- Ok(v) => v,
- Err(e) => {
- log::debug!(target: LOG, "[orchestration] sync.messages_failed session={} err={e}", session.session_id);
- continue;
- }
- };
- let msgs: Vec<HostedMessage> = serde_json::from_value(msgs_raw).unwrap_or_default();
- if msgs.is_empty() {
- continue;
- }
- let kind = chat_kind_for(&session.session_id);
- let _ = store::with_connection(&config.workspace_dir, |conn| {
- for m in &msgs {
- store::insert_message(
- conn,
- &OrchestrationMessage {
- id: format!("hosted:{}:{}", session.session_id, m.seq),
- agent_id: agent_id.clone(),
- session_id: session.session_id.clone(),
- chat_kind: kind,
- role: m.role.clone(),
- body: m.body.clone(),
- timestamp: ms_to_rfc3339(m.ts),
- seq: m.seq,
- event_kind: (!m.kind.is_empty()).then(|| m.kind.clone()),
- call_id: (!m.cycle_id.is_empty()).then(|| m.cycle_id.clone()),
- ..Default::default()
- },
- )?;
- }
- Ok(())
- });
- }
-
- true
-}
-
-/// Run the periodic read-sync loop until the process exits.
-pub async fn run_sync_loop(config: Config, interval: Duration) {
- let mut tick = tokio::time::interval(interval);
- loop {
- tick.tick().await;
- if !config.orchestration.enabled {
- continue;
- }
- sync_reads(&config).await;
- }
-}
-
-/// Read the cached reachability flag. Absent (never synced) reads as reachable so
-/// the UI does not flash an offline notice before the first sync completes.
-pub fn cloud_reachable(config: &Config) -> bool {
- store::with_connection(&config.workspace_dir, |c| store::kv_get(c, REACHABLE_KEY))
- .ok()
- .flatten()
- .map(|v| v != "0")
- .unwrap_or(true)
-}
diff --git a/src/openhuman/hosted/orchestration/tools.rs b/src/openhuman/hosted/orchestration/tools.rs
deleted file mode 100644
index aba009f2fe..0000000000
--- a/src/openhuman/hosted/orchestration/tools.rs
+++ /dev/null
@@ -1,870 +0,0 @@
-//! Orchestration agent tools — read-only session-history browsing + a
-//! send-on-behalf DM tool over the tiny.place transport. Offered to agents via
-//! the shared tool registry; the reasoning that decides *what* to send now runs
-//! in the hosted brain (see [`super::cloud`]).
-//!
-//! - [`ListSessionsTool`] (`orchestration_list_sessions`) — enumerate the
-//! persisted OpenHuman↔agent session windows (peers/threads, one-line preview).
-//! - [`ReadSessionTool`] (`orchestration_read_session`) — read one session's
-//! transcript by id.
-//! - [`ListContactsTool`] / [`SendToAgentTool`] — list paired agents and send a
-//! DM on the user's behalf.
-//!
-//! The read tools are `ReadOnly` and touch only the workspace-internal
-//! orchestration DB via [`super::store`].
-
-use std::future::Future;
-use std::sync::{Arc, Mutex};
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-
-use crate::openhuman::config::Config;
-use crate::openhuman::tools::{PermissionLevel, Tool, ToolResult};
-
-use super::store;
-use super::types::{ChatKind, OrchestrationMessage, OrchestrationSession, SessionEnvelopeV1};
-
-tokio::task_local! {
- /// The window the current wake cycle is serving (the reasoning core's session
- /// id). `orchestration_send_to_agent` reads it to record where a peer's async
- /// reply should thread back to (the ask's origin). Scoped by the `execute`
- /// node around the reasoning agent's turn (see [`super::ops`]).
- static ORIGIN_SESSION: String;
-}
-
-/// Scope the originating wake session id around the reasoning agent's turn `fut`,
-/// so the send-on-behalf tool can correlate the eventual reply back to it.
-pub async fn with_origin_session<F: Future>(session_id: String, fut: F) -> F::Output {
- ORIGIN_SESSION.scope(session_id, Box::pin(fut)).await
-}
-
-/// The current wake cycle's origin session id, or `None` outside a scope.
-fn current_origin_session() -> Option<String> {
- ORIGIN_SESSION.try_with(|s| s.clone()).ok()
-}
-
-/// Process-global capture of the origin window a **local-master** turn is serving.
-///
-/// The [`ORIGIN_SESSION`] task-local above is set by the `execute` node around the
-/// agent's turn, but it does **not** reach `orchestration_send_to_agent`: the agent
-/// harness dispatches tool calls beyond one or more internal `tokio::spawn`
-/// boundaries, and task-locals do not cross a `spawn` (standard tokio semantics —
-/// the same reason `sandbox_context` re-scopes its mode right at `tool.execute`).
-/// So the earlier task-local correlation silently never armed `pending_ask`, and
-/// master-initiated asks never threaded their reply back. A process-global is
-/// immune to the spawn boundary, so the tool can read it reliably.
-///
-/// Safe for the master window because local-master wakes are **serialized** by the
-/// generation guard (one `master` session, deduped) — at most one master turn
-/// brackets this at a time. A concurrent A2A `send_to_agent` during that window
-/// would also read the master origin; in the single-user desktop model that
-/// overlap is rare and at worst mis-threads one peer reply into master. Documented,
-/// not ignored. Peer-session (A2A) W7 stays on the best-effort task-local for now.
-static MASTER_ORIGIN: Mutex<Option<String>> = Mutex::new(None);
-
-/// Open a master-origin capture window for the duration of a local-master turn.
-/// `origin` is the window a peer's async reply should thread back to (always
-/// `"master"`). Paired with [`end_master_origin`]; see [`super::ops`]'s `execute`.
-pub fn begin_master_origin(origin: String) {
- if let Ok(mut slot) = MASTER_ORIGIN.lock() {
- *slot = Some(origin);
- }
-}
-
-/// Close the capture window opened by [`begin_master_origin`].
-pub fn end_master_origin() {
- if let Ok(mut slot) = MASTER_ORIGIN.lock() {
- *slot = None;
- }
-}
-
-/// The origin window of the in-flight local-master turn, or `None` outside one.
-fn current_master_origin() -> Option<String> {
- MASTER_ORIGIN.lock().ok().and_then(|slot| slot.clone())
-}
-
-/// Extract a required string field, returning an error `ToolResult` when absent.
-fn required_str(args: &Value, field: &str) -> Result<String, ToolResult> {
- match args.get(field).and_then(Value::as_str) {
- Some(s) if !s.trim().is_empty() => Ok(s.to_string()),
- _ => Err(ToolResult::error(format!("`{field}` is required"))),
- }
-}
-
-fn recipient_may_receive_message(
- locally_linked: bool,
- has_known_session: bool,
- accepted_contact: bool,
-) -> bool {
- locally_linked || has_known_session || accepted_contact
-}
-
-// ── Reasoning-core session-history read tools (Master chat) ──────────────────
-
-/// Default / cap on how many messages a `orchestration_read_session` call returns.
-const READ_SESSION_DEFAULT_LIMIT: u32 = 50;
-const READ_SESSION_MAX_LIMIT: u32 = 200;
-/// Cap on how many session rows `orchestration_list_sessions` returns.
-const LIST_SESSIONS_MAX: usize = 100;
-/// One-line preview length for the session list (char-safe, matches the roster).
-const PREVIEW_MAX_CHARS: usize = 120;
-
-/// The pinned sentinel windows — not agent↔agent transcripts, so they are hidden
-/// from the history-browsing tools (the agent reads those via its normal channel).
-fn is_pinned_window(session_id: &str) -> bool {
- matches!(session_id, "master" | "subconscious")
-}
-
-/// UTF-8-safe one-line preview (mirrors the roster `task_preview` in `schemas.rs`).
-fn preview_line(body: &str) -> String {
- let trimmed = body.trim().replace('\n', " ");
- if trimmed.chars().count() <= PREVIEW_MAX_CHARS {
- return trimmed;
- }
- let mut out: String = trimmed.chars().take(PREVIEW_MAX_CHARS - 1).collect();
- out.push('…');
- out
-}
-
-/// `orchestration_list_sessions` — enumerate the persisted OpenHuman↔agent session
-/// windows so the reasoning core can decide which history to read.
-pub struct ListSessionsTool {
- config: Arc<Config>,
-}
-
-impl ListSessionsTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for ListSessionsTool {
- fn name(&self) -> &str {
- "orchestration_list_sessions"
- }
-
- fn description(&self) -> &str {
- "List your saved chat sessions with other agents (the persisted OpenHuman↔agent \
- transcripts), newest activity first. Use this to find which past conversation to \
- read before answering a question. Returns each session's id, the peer agent, the \
- source harness, an optional label, the last activity time, the message count, and a \
- one-line preview. Read a session's full transcript with `orchestration_read_session`."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "contactId": {
- "type": "string",
- "description": "Optional: only sessions with this contact (peer agent id/address). Omit to list across all contacts."
- },
- "limit": {
- "type": "integer",
- "description": "Max sessions to return (default all, capped at 100).",
- "minimum": 1,
- "maximum": LIST_SESSIONS_MAX,
- }
- },
- "additionalProperties": false
- })
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let limit = args
- .get("limit")
- .and_then(Value::as_u64)
- .map(|n| (n as usize).min(LIST_SESSIONS_MAX))
- .unwrap_or(LIST_SESSIONS_MAX);
- // Optional contact filter: only sessions with this peer (contact-wise view).
- let contact_id = args
- .get("contactId")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
-
- let workspace = self.config.workspace_dir.clone();
- let result = store::with_connection(&workspace, |conn| {
- let sessions: Vec<OrchestrationSession> = store::list_sessions(conn)?;
- let mut out = Vec::with_capacity(sessions.len());
- for s in sessions {
- if is_pinned_window(&s.session_id) {
- continue;
- }
- if let Some(ref cid) = contact_id {
- if &s.agent_id != cid {
- continue;
- }
- }
- let count = store::count_messages(conn, &s.agent_id, &s.session_id)?;
- // Newest message body as a one-line preview. `list_recent_messages`
- // orders newest-first internally (DESC) then reverses, so with a
- // limit of 1 the single returned row is the newest message.
- let preview = store::list_recent_messages(conn, &s.agent_id, &s.session_id, 1)?
- .last()
- .map(|m| preview_line(&m.body));
- out.push(json!({
- "sessionId": s.session_id,
- "peerAgentId": s.agent_id,
- "source": s.source,
- "label": s.label,
- "lastMessageAt": s.last_message_at,
- "messageCount": count,
- "preview": preview,
- }));
- if out.len() >= limit {
- break;
- }
- }
- Ok(out)
- });
-
- match result {
- Ok(sessions) => {
- log::debug!(
- target: "orchestration",
- "[orchestration] tool.list_sessions returned={}",
- sessions.len(),
- );
- let body = serde_json::to_string(&json!({ "sessions": sessions }))
- .unwrap_or_else(|_| "{\"sessions\":[]}".to_string());
- Ok(ToolResult::success(body))
- }
- Err(e) => Ok(ToolResult::error(format!("list_sessions failed: {e}"))),
- }
- }
-
- fn is_concurrency_safe(&self, _args: &Value) -> bool {
- true
- }
-}
-
-/// `orchestration_read_session` — read one session's transcript by id.
-pub struct ReadSessionTool {
- config: Arc<Config>,
-}
-
-impl ReadSessionTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for ReadSessionTool {
- fn name(&self) -> &str {
- "orchestration_read_session"
- }
-
- fn description(&self) -> &str {
- "Read the transcript of one of your saved agent chat sessions (from \
- `orchestration_list_sessions`). Returns the messages in chronological order with role, \
- body, and timestamp. Use `before` to page backwards through a long history."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "sessionId": {
- "type": "string",
- "description": "The session id to read (from orchestration_list_sessions)."
- },
- "limit": {
- "type": "integer",
- "description": "Max messages to return (default 50, capped at 200).",
- "minimum": 1,
- "maximum": READ_SESSION_MAX_LIMIT,
- },
- "before": {
- "type": "string",
- "description": "Exclusive ISO-8601 timestamp to page backwards from."
- }
- },
- "required": ["sessionId"],
- "additionalProperties": false
- })
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let session_id = match required_str(&args, "sessionId") {
- Ok(s) => s,
- Err(e) => return Ok(e),
- };
- if is_pinned_window(&session_id) {
- return Ok(ToolResult::error(
- "`sessionId` must be an agent session, not a pinned window".to_string(),
- ));
- }
- let limit = args
- .get("limit")
- .and_then(Value::as_u64)
- .map(|n| (n as u32).min(READ_SESSION_MAX_LIMIT))
- .unwrap_or(READ_SESSION_DEFAULT_LIMIT);
- let before = args
- .get("before")
- .and_then(Value::as_str)
- .filter(|s| !s.trim().is_empty())
- .map(str::to_string);
-
- let workspace = self.config.workspace_dir.clone();
- let result = store::with_connection(&workspace, |conn| {
- store::list_messages_by_session(conn, &session_id, limit, before.as_deref())
- });
-
- match result {
- Ok(messages) => {
- log::debug!(
- target: "orchestration",
- "[orchestration] tool.read_session session={session_id} returned={}",
- messages.len(),
- );
- let rendered: Vec<Value> = messages
- .into_iter()
- .map(|m| {
- json!({
- "role": m.role,
- "body": m.body,
- "timestamp": m.timestamp,
- })
- })
- .collect();
- let body = serde_json::to_string(&json!({
- "sessionId": session_id,
- "messages": rendered,
- }))
- .unwrap_or_else(|_| "{\"messages\":[]}".to_string());
- Ok(ToolResult::success(body))
- }
- Err(e) => Ok(ToolResult::error(format!("read_session failed: {e}"))),
- }
- }
-
- fn is_concurrency_safe(&self, _args: &Value) -> bool {
- true
- }
-}
-
-/// `orchestration_list_contacts` — enumerate this agent's tiny.place contacts.
-/// The starting point for the browse loop: list contacts → `orchestration_list_sessions`
-/// (with `contactId`) for a contact's threads → `orchestration_read_session` for history.
-/// Read-only; delegates to the tiny.place `contacts_list` controller (no new logic here).
-pub struct ListContactsTool;
-
-#[async_trait]
-impl Tool for ListContactsTool {
- fn name(&self) -> &str {
- "orchestration_list_contacts"
- }
-
- fn description(&self) -> &str {
- "List your tiny.place contacts — the agents you're connected with and can message. Use \
- this to find who to read a session history from (orchestration_list_sessions with that \
- contactId, then orchestration_read_session) or who to message (orchestration_send_to_agent). \
- Returns each contact's agent id (address) and handle/label."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({ "type": "object", "properties": {}, "additionalProperties": false })
- }
-
- async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
- match crate::openhuman::tinyplace::handle_tinyplace_contacts_list(serde_json::Map::new())
- .await
- {
- Ok(v) => {
- log::debug!(target: "orchestration", "[orchestration] tool.list_contacts ok");
- Ok(ToolResult::success(
- serde_json::to_string(&v).unwrap_or_else(|_| "{}".to_string()),
- ))
- }
- Err(e) => Ok(ToolResult::error(format!("list_contacts failed: {e}"))),
- }
- }
-
- fn is_concurrency_safe(&self, _args: &Value) -> bool {
- true
- }
-}
-
-// ── Reasoning-core send-on-behalf tool (Master chat) ─────────────────────────
-
-/// `orchestration_send_to_agent` — DM another agent on OpenHuman's behalf.
-///
-/// Guardrail (owner decision): **linked peers only** — the recipient must be a
-/// linked/paired agent OR one this OpenHuman already has a session with. This
-/// tool runs under a background origin that bypasses the interactive approval
-/// gate, so cold-DMing an arbitrary new address is refused here rather than
-/// prompting.
-///
-/// Session id (owner decision): **reuse-or-mint per peer** — reuse the peer's
-/// most recent thread (its shared `wrapper_session_id`) so the reply threads
-/// back into the same session (#227/#4582); mint a fresh uuid only when there is
-/// no existing thread. An explicit `sessionId` overrides the lookup.
-///
-/// Effect: sends a v1 session envelope over the tiny.place Signal channel and
-/// records the outbound message (`role = "owner"`) in the session window (so it
-/// shows in the chat + the agent's own history). The peer's reply arrives
-/// asynchronously via the normal ingest → wake path — this call does not block
-/// for it.
-pub struct SendToAgentTool {
- config: Arc<Config>,
-}
-
-impl SendToAgentTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for SendToAgentTool {
- fn name(&self) -> &str {
- "orchestration_send_to_agent"
- }
-
- fn description(&self) -> &str {
- "Send a direct message to another agent on OpenHuman's behalf (e.g. to ask them \
- something for the user). Only works for agents you are already linked with or have \
- chatted with before. By default the message threads into your existing conversation \
- with that agent (so their reply comes back into the same session); pass `sessionId` to \
- target a specific thread. The reply arrives asynchronously — it will show up in that \
- session, not as this tool's return value."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "recipient": {
- "type": "string",
- "description": "The agent id (address/@handle) to message. Must be a linked or already-known peer."
- },
- "message": {
- "type": "string",
- "description": "The message body to send."
- },
- "sessionId": {
- "type": "string",
- "description": "Optional: send under this existing session id. Omit to reuse your latest thread with the peer, or mint a new one."
- }
- },
- "required": ["recipient", "message"],
- "additionalProperties": false
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // External send effect — a Write-class action, so a read-only channel
- // cannot invoke it even though the deep-reasoning core can.
- PermissionLevel::Write
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let recipient = match required_str(&args, "recipient") {
- Ok(s) => s,
- Err(e) => return Ok(e),
- };
- let message = match required_str(&args, "message") {
- Ok(s) => s,
- Err(e) => return Ok(e),
- };
- let explicit_session = args
- .get("sessionId")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty() && !is_pinned_window(s))
- .map(str::to_string);
-
- let workspace = self.config.workspace_dir.clone();
-
- // Guardrail: locally linked peer, accepted tiny.place contact, OR an
- // existing session with them. Never cold-DM an arbitrary new address
- // from this un-gated background origin. The live contact check matters
- // after login changes the workspace: the relay contact remains accepted
- // while the workspace-local orchestration pairing/session stores start
- // empty.
- let linked =
- crate::openhuman::agent::orchestration::pairing::linked_agent_ids(&workspace).await;
- let known_session = store::with_connection(&workspace, |conn| {
- store::latest_session_for_agent(conn, &recipient)
- })
- .map_err(|e| anyhow::anyhow!("lookup session: {e}"))?;
- let accepted_contact = if linked.contains(&recipient) || known_session.is_some() {
- false
- } else {
- match crate::openhuman::agent::orchestration::pairing::is_accepted_contact(&recipient)
- .await
- {
- Ok(accepted) => accepted,
- Err(e) => {
- log::warn!(
- target: "orchestration",
- "[orchestration] tool.send_to_agent contact check failed: {e}"
- );
- false
- }
- }
- };
- if !recipient_may_receive_message(
- linked.contains(&recipient),
- known_session.is_some(),
- accepted_contact,
- ) {
- log::debug!(
- target: "orchestration",
- "[orchestration] tool.send_to_agent refused unlinked recipient",
- );
- return Ok(ToolResult::error(
- "recipient is not a linked or previously-contacted agent — cannot send".to_string(),
- ));
- }
-
- // Session id: explicit → reuse latest thread → mint fresh.
- let session_id = explicit_session
- .or(known_session)
- .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
-
- let now = chrono::Utc::now().to_rfc3339();
- let message_id = format!("orch-ask:{}", uuid::Uuid::new_v4());
-
- // Wrap in a v1 session envelope so a compliant peer threads its reply
- // under the same session id.
- let plaintext = match serde_json::to_string(&SessionEnvelopeV1::outgoing(
- &session_id,
- &message,
- &message_id,
- &now,
- )) {
- Ok(s) => s,
- Err(e) => return Ok(ToolResult::error(format!("envelope encode: {e}"))),
- };
-
- // Send over the tiny.place Signal channel (same op the graph's send_dm and
- // the send_master RPC use).
- let mut send_params = serde_json::Map::new();
- send_params.insert("recipient".to_string(), Value::from(recipient.clone()));
- send_params.insert("plaintext".to_string(), Value::from(plaintext));
- if let Err(e) =
- crate::openhuman::tinyplace::handle_tinyplace_signal_send_message(send_params).await
- {
- log::warn!(target: "orchestration", "[orchestration] tool.send_to_agent send failed: {e}");
- return Ok(ToolResult::error(format!("send failed: {e}")));
- }
-
- // Record the outbound message in the session window (role=owner) so it
- // surfaces in the chat + the agent's own history, and notify the renderer.
- // Mirrors effect_executor::persist_reply and the send_master RPC.
- let persisted = store::with_connection(&workspace, |conn| {
- let seq = store::next_session_seq(conn, &recipient, &session_id)?;
- store::upsert_session(
- conn,
- &OrchestrationSession {
- session_id: session_id.clone(),
- agent_id: recipient.clone(),
- source: String::new(),
- label: None,
- workspace: None,
- last_seq: seq,
- created_at: now.clone(),
- last_message_at: now.clone(),
- ..Default::default()
- },
- )?;
- store::insert_message(
- conn,
- &OrchestrationMessage {
- id: message_id.clone(),
- agent_id: recipient.clone(),
- session_id: session_id.clone(),
- chat_kind: ChatKind::Session,
- role: "owner".to_string(),
- body: message.clone(),
- timestamp: now.clone(),
- seq,
- ..Default::default()
- },
- )
- });
- if let Err(e) = persisted {
- log::warn!(target: "orchestration", "[orchestration] tool.send_to_agent persist failed: {e}");
- } else {
- super::bus::notify_orchestration_message(
- &recipient,
- &session_id,
- ChatKind::Session.as_str(),
- );
- }
-
- // Correlate the eventual reply back to the window this ask came from, so
- // the wake path threads the peer's answer into the Master chat (or the
- // originating session) instead of auto-replying to the peer. One-shot:
- // consumed by the next inbound message on this session. Skipped when the
- // origin is unknown (tool invoked outside a wake) or is the same session.
- //
- // Resolve origin from the process-global master beacon FIRST — it survives
- // the harness's `tokio::spawn` tool-dispatch boundary that drops the
- // `ORIGIN_SESSION` task-local (which is why this correlation used to never
- // arm). Fall back to the task-local for the best-effort A2A peer path.
- if let Some(origin) = current_master_origin().or_else(current_origin_session) {
- if origin != session_id && !origin.is_empty() {
- // Key by (recipient, session) so a legacy session-id collision with a
- // different peer can't consume this ask (matches the store scoping).
- if let Err(e) = store::with_connection(&workspace, |conn| {
- store::set_pending_ask(conn, &recipient, &session_id, &origin)
- }) {
- log::warn!(target: "orchestration", "[orchestration] tool.send_to_agent correlate failed: {e}");
- }
- }
- }
-
- log::debug!(
- target: "orchestration",
- "[orchestration] tool.send_to_agent sent session={session_id}",
- );
- let body = serde_json::to_string(&json!({
- "ok": true,
- "sessionId": session_id,
- "note": "Message sent. Fire-and-forget: the reply arrives later and is \
- surfaced to this chat AUTOMATICALLY when it comes. Do NOT wait, \
- poll, or call read_session for it — just tell your human you've \
- asked and will report back, then end your turn.",
- }))
- .unwrap_or_else(|_| "{\"ok\":true}".to_string());
- Ok(ToolResult::success(body))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[tokio::test]
- async fn master_origin_beacon_sets_and_clears() {
- // The W7 arming fix: unlike the `ORIGIN_SESSION` task-local (which does not
- // survive the harness's `tokio::spawn` tool-dispatch boundary), this
- // process-global beacon is readable from `orchestration_send_to_agent`.
- end_master_origin(); // normalize against any cross-test residue
- assert_eq!(current_master_origin(), None);
-
- // Inside a local-master turn: the tool can read the origin to arm pending_ask.
- begin_master_origin("master".to_string());
- assert_eq!(current_master_origin(), Some("master".to_string()));
-
- // Closed after the turn: a later A2A wake cannot read a stale master origin.
- end_master_origin();
- assert_eq!(current_master_origin(), None);
- }
-
- // ── session-history read tools ──────────────────────────────────────────
-
- use super::super::types::{ChatKind, OrchestrationMessage};
-
- fn test_config(tmp: &tempfile::TempDir) -> Arc<Config> {
- Arc::new(Config {
- workspace_dir: tmp.path().to_path_buf(),
- ..Config::default()
- })
- }
-
- fn seed_msg(
- conn: &rusqlite::Connection,
- session: &str,
- seq: i64,
- role: &str,
- body: &str,
- ts: &str,
- ) {
- store::insert_message(
- conn,
- &OrchestrationMessage {
- id: format!("{session}-{seq}"),
- agent_id: "@peer".into(),
- session_id: session.into(),
- chat_kind: ChatKind::Session,
- role: role.into(),
- body: body.into(),
- timestamp: ts.into(),
- seq,
- ..Default::default()
- },
- )
- .unwrap();
- }
-
- fn seed_session(conn: &rusqlite::Connection, session: &str, source: &str, last_at: &str) {
- store::upsert_session(
- conn,
- &OrchestrationSession {
- session_id: session.into(),
- agent_id: "@peer".into(),
- source: source.into(),
- label: None,
- workspace: None,
- last_seq: 0,
- created_at: last_at.into(),
- last_message_at: last_at.into(),
- ..Default::default()
- },
- )
- .unwrap();
- }
-
- #[tokio::test]
- async fn list_sessions_tool_lists_agent_sessions_and_hides_pinned() {
- let tmp = tempfile::tempdir().unwrap();
- let config = test_config(&tmp);
- store::with_connection(&config.workspace_dir, |conn| {
- seed_session(conn, "s-1", "claude", "2026-07-02T00:01:00Z");
- seed_msg(
- conn,
- "s-1",
- 1,
- "user",
- "how do I ship it?",
- "2026-07-02T00:01:00Z",
- );
- // A pinned window must be excluded from the history browser.
- seed_session(conn, "master", "master", "2026-07-02T00:02:00Z");
- seed_msg(conn, "master", 1, "user", "steer", "2026-07-02T00:02:00Z");
- Ok(())
- })
- .unwrap();
-
- let tool = ListSessionsTool::new(config);
- let out = tool.execute(json!({})).await.unwrap();
- assert!(!out.is_error);
- let v: Value = serde_json::from_str(&out.text()).unwrap();
- let sessions = v["sessions"].as_array().unwrap();
- assert_eq!(sessions.len(), 1, "only the agent session, not master");
- assert_eq!(sessions[0]["sessionId"], "s-1");
- assert_eq!(sessions[0]["peerAgentId"], "@peer");
- assert_eq!(sessions[0]["source"], "claude");
- assert_eq!(sessions[0]["messageCount"], 1);
- assert_eq!(sessions[0]["preview"], "how do I ship it?");
- }
-
- #[tokio::test]
- async fn list_sessions_tool_filters_by_contact() {
- let tmp = tempfile::tempdir().unwrap();
- let config = test_config(&tmp);
- // Two contacts, one session each.
- let sess = |agent: &str, session: &str| OrchestrationSession {
- session_id: session.into(),
- agent_id: agent.into(),
- source: "claude".into(),
- label: None,
- workspace: None,
- last_seq: 0,
- created_at: "2026-07-02T00:01:00Z".into(),
- last_message_at: "2026-07-02T00:01:00Z".into(),
- ..Default::default()
- };
- store::with_connection(&config.workspace_dir, |conn| {
- store::upsert_session(conn, &sess("@alice", "s-alice"))?;
- store::upsert_session(conn, &sess("@bob", "s-bob"))?;
- Ok(())
- })
- .unwrap();
-
- let tool = ListSessionsTool::new(config);
- // No filter → both contacts' sessions.
- let all = tool.execute(json!({})).await.unwrap();
- let v: Value = serde_json::from_str(&all.text()).unwrap();
- assert_eq!(v["sessions"].as_array().unwrap().len(), 2);
-
- // contactId filter → only that contact's sessions.
- let out = tool
- .execute(json!({ "contactId": "@alice" }))
- .await
- .unwrap();
- let v: Value = serde_json::from_str(&out.text()).unwrap();
- let sessions = v["sessions"].as_array().unwrap();
- assert_eq!(sessions.len(), 1);
- assert_eq!(sessions[0]["peerAgentId"], "@alice");
- assert_eq!(sessions[0]["sessionId"], "s-alice");
- }
-
- #[tokio::test]
- async fn read_session_tool_returns_transcript_chronologically() {
- let tmp = tempfile::tempdir().unwrap();
- let config = test_config(&tmp);
- store::with_connection(&config.workspace_dir, |conn| {
- seed_session(conn, "s-1", "codex", "2026-07-02T00:03:00Z");
- seed_msg(conn, "s-1", 1, "user", "first", "2026-07-02T00:01:00Z");
- seed_msg(conn, "s-1", 2, "agent", "second", "2026-07-02T00:02:00Z");
- Ok(())
- })
- .unwrap();
-
- let tool = ReadSessionTool::new(config);
- let out = tool.execute(json!({ "sessionId": "s-1" })).await.unwrap();
- assert!(!out.is_error);
- let v: Value = serde_json::from_str(&out.text()).unwrap();
- let msgs = v["messages"].as_array().unwrap();
- assert_eq!(msgs.len(), 2);
- assert_eq!(msgs[0]["role"], "user");
- assert_eq!(msgs[0]["body"], "first");
- assert_eq!(msgs[1]["body"], "second"); // chronological order
- }
-
- #[tokio::test]
- async fn read_session_tool_rejects_missing_id_and_pinned_window() {
- let tmp = tempfile::tempdir().unwrap();
- let config = test_config(&tmp);
- let tool = ReadSessionTool::new(config);
- assert!(tool.execute(json!({})).await.unwrap().is_error);
- assert!(
- tool.execute(json!({ "sessionId": "master" }))
- .await
- .unwrap()
- .is_error
- );
- }
-
- // ── send-on-behalf tool ─────────────────────────────────────────────────
-
- #[tokio::test]
- async fn send_to_agent_rejects_missing_args() {
- let tmp = tempfile::tempdir().unwrap();
- let tool = SendToAgentTool::new(test_config(&tmp));
- assert!(tool.execute(json!({})).await.unwrap().is_error);
- assert!(
- tool.execute(json!({ "recipient": "@peer" }))
- .await
- .unwrap()
- .is_error
- ); // missing message
- assert!(
- tool.execute(json!({ "message": "hi" }))
- .await
- .unwrap()
- .is_error
- ); // missing recipient
- }
-
- #[tokio::test]
- async fn send_to_agent_refuses_unlinked_unknown_recipient() {
- // Empty workspace: no linked peers, no existing session. The guardrail
- // must refuse BEFORE any network send (this test does no I/O to tiny.place).
- let tmp = tempfile::tempdir().unwrap();
- let tool = SendToAgentTool::new(test_config(&tmp));
- let out = tool
- .execute(json!({ "recipient": "@stranger", "message": "hello" }))
- .await
- .unwrap();
- assert!(out.is_error);
- assert!(out.text().contains("not a linked"));
- }
-
- #[test]
- fn accepted_contact_can_receive_without_workspace_pairing_or_session() {
- assert!(recipient_may_receive_message(false, false, true));
- assert!(recipient_may_receive_message(true, false, false));
- assert!(recipient_may_receive_message(false, true, false));
- assert!(!recipient_may_receive_message(false, false, false));
- }
-}
diff --git a/src/openhuman/hosted/orchestration/types.rs b/src/openhuman/hosted/orchestration/types.rs
deleted file mode 100644
index 8243605652..0000000000
--- a/src/openhuman/hosted/orchestration/types.rs
+++ /dev/null
@@ -1,892 +0,0 @@
-//! Orchestration domain types.
-//!
-//! [`SessionEnvelopeV1`] is a hand-written mirror of the tiny.place TypeScript
-//! SDK schema `sdk/typescript/src/types/harness.ts`. The Rust SDK does not ship
-//! this type on the `1.0.x` line we depend on (it was added on the unreleased
-//! `2.x` line — see the SDK port in tinyhumansai/tiny.place#210). Once a crate
-//! version that includes it is published *and* openhuman migrates off
-//! `tinyplace 1.0.1`, replace this block with
-//! `use tinyplace::types::SessionEnvelopeV1;` — field names already match.
-//!
-//! Wire format is **snake_case** (the CLI wrapper emits a literal snake_case
-//! object), unlike the camelCase tiny.place API — so these structs deliberately
-//! omit `#[serde(rename_all = "camelCase")]`.
-
-use serde::{Deserialize, Serialize};
-
-/// `envelope_version` discriminator for v1 harness envelopes.
-pub const SESSION_ENVELOPE_VERSION_V1: &str = "tinyplace.harness.session.v1";
-
-/// Sentinel counterpart for a **local** Master-chat cycle — the human asking the
-/// OpenHuman agent itself (W2), as opposed to a real external peer. When the wake
-/// graph sees this as the counterpart it must NOT send an outbound tiny.place DM;
-/// the reply belongs in the Master window. Contains a `:` so it can never collide
-/// with a real base58 tiny.place address.
-pub const LOCAL_MASTER_AGENT: &str = "openhuman:local";
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct HarnessBucket {
- #[serde(default)]
- pub unit: String,
- #[serde(default)]
- pub start: String,
- #[serde(default)]
- pub end: String,
-}
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct HarnessScope {
- #[serde(rename = "type", default)]
- pub scope_type: String,
- #[serde(default)]
- pub key: String,
- #[serde(default)]
- pub cwd: String,
- #[serde(default)]
- pub wrapper_session_id: String,
- #[serde(default)]
- pub harness_session_id: String,
-}
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct HarnessInfo {
- #[serde(default)]
- pub provider: String,
- #[serde(default)]
- pub command: String,
- #[serde(default)]
- pub argv: Vec<String>,
-}
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct HarnessEnvelopeMessage {
- #[serde(default)]
- pub id: String,
- #[serde(default)]
- pub line: i64,
- #[serde(default)]
- pub role: String,
- #[serde(default)]
- pub text: String,
- #[serde(default)]
- pub timestamp: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub phase: Option<String>,
-}
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct HarnessSource {
- #[serde(default)]
- pub path: String,
- #[serde(default)]
- pub record_type: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub source_role: Option<String>,
-}
-
-/// Mirror of the TS `SessionEnvelopeV1` interface.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct SessionEnvelopeV1 {
- #[serde(default)]
- pub envelope_version: String,
- #[serde(default)]
- pub version: u32,
- #[serde(default)]
- pub bucket: HarnessBucket,
- #[serde(default)]
- pub scope: HarnessScope,
- #[serde(default)]
- pub harness: HarnessInfo,
- #[serde(default)]
- pub message: HarnessEnvelopeMessage,
- #[serde(default)]
- pub source: HarnessSource,
-}
-
-impl SessionEnvelopeV1 {
- fn is_valid_v1(&self) -> bool {
- self.envelope_version == SESSION_ENVELOPE_VERSION_V1
- && !self.scope.harness_session_id.is_empty()
- }
-
- /// Parse a decrypted DM body as a v1 session envelope. Returns `None` for
- /// any non-envelope payload (a plain DM) so callers route it to Master.
- pub fn parse(body: &str) -> Option<Self> {
- let envelope: Self = serde_json::from_str(body).ok()?;
- envelope.is_valid_v1().then_some(envelope)
- }
-
- /// The single per-pair session id to bucket an inbound message under. Every
- /// message — whoever sent it — carries exactly one id: the shared conversation
- /// id in `scope.wrapper_session_id`. Both peers put the SAME id there for a given
- /// thread (the peer reuses it on reply), so it is the sole routing key. Falls
- /// back to `harness_session_id` only for a legacy envelope that predates the
- /// per-pair id.
- pub fn session_key(&self) -> String {
- if !self.scope.wrapper_session_id.is_empty() {
- return self.scope.wrapper_session_id.clone();
- }
- self.scope.harness_session_id.clone()
- }
-
- /// Build an outgoing v1 session envelope carrying `body` under `session_id`,
- /// so a compliant peer harness threads its reply under the same session.
- pub fn outgoing(session_id: &str, body: &str, message_id: &str, timestamp: &str) -> Self {
- SessionEnvelopeV1 {
- envelope_version: SESSION_ENVELOPE_VERSION_V1.to_string(),
- version: 1,
- scope: HarnessScope {
- scope_type: "session".to_string(),
- wrapper_session_id: session_id.to_string(),
- harness_session_id: session_id.to_string(),
- ..Default::default()
- },
- message: HarnessEnvelopeMessage {
- id: message_id.to_string(),
- role: "owner".to_string(),
- text: body.to_string(),
- timestamp: timestamp.to_string(),
- ..Default::default()
- },
- ..Default::default()
- }
- }
-}
-
-// ── v2 envelope: `tinyplace.harness.session.v2` ──────────────────────────────
-//
-// Hand-rolled mirror of the tiny.place v2 harness wire (snake_case, from the
-// TypeScript source), added beside the v1 mirror above. v2 replaces v1's single
-// `message` object with a typed `event` carrying a `kind` discriminator + a
-// per-kind `payload`, plus a richer `status` run-state. Same
-// `scope.wrapper_session_id` routing key as v1. See the port in
-// tinyhumansai/tiny.place#210; fold in `tinyplace::types::SessionEnvelopeV2` once
-// the vendored SDK ships it.
-
-/// `envelope_version` discriminator for v2 harness envelopes.
-pub const SESSION_ENVELOPE_VERSION_V2: &str = "tinyplace.harness.session.v2";
-
-/// The typed payload of a v2 `event`, keyed by `event.kind`. Adjacently tagged on
-/// the wire's `kind` (discriminator) + `payload` (content) fields, decoded via
-/// [`HarnessEvent::decoded`]. `snake_case` matches the wire kind strings.
-///
-/// `tool_kind` inside [`ToolCallPayload`] is intentionally a `String` (not an
-/// enum) so an unrecognised tool family does not fail the whole event decode.
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-#[serde(tag = "kind", content = "payload", rename_all = "snake_case")]
-pub enum HarnessEventKind {
- /// `session_info` — the session intro/announce, emitted once a wrapped agent
- /// session is initialised (spec §2). Enrichment, not a prerequisite: a session
- /// is lazy-created on the first event of any kind regardless.
- SessionInfo(SessionInfoPayload),
- UserPrompt(UserPromptPayload),
- AgentMessage(TextPayload),
- AgentThinking(TextPayload),
- ToolCall(ToolCallPayload),
- ToolResult(ToolResultPayload),
- ApprovalRequest(ApprovalRequestPayload),
- Status(StatusPayload),
- Lifecycle(LifecyclePayload),
- Error(ErrorPayload),
- /// `unknown` wire kind (`{ "raw": any }`) OR any forward-incompatible kind we
- /// cannot decode — folded here rather than hard-failing the parse.
- Unknown(UnknownPayload),
-}
-
-/// `session_info` payload — the session intro/announce (spec §2b). Thin: the
-/// provider / cwd / session-ids ride on the envelope frame, so this carries only
-/// what the frame lacks (identity confirmation, capabilities, UI metadata). Field
-/// names are byte-identical to the TS `SessionInfoPayload` emitter (spec §2a).
-#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
-pub struct SessionInfoPayload {
- /// base58 wallet identity — confirms `envelope.from`.
- #[serde(default)]
- pub agent_address: String,
- /// `@handle`, if registered.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub handle: Option<String>,
- /// Human-friendly session title for the UI header.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub title: Option<String>,
- /// git remote/slug, if in a repo.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub repo: Option<String>,
- /// git branch.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub branch: Option<String>,
- /// Active model (may also ride on `event.model`).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub model: Option<String>,
- /// plugin/CLI version — compat gating.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub harness_version: Option<String>,
- /// Advertised event kinds (subset of the wire `kind` strings) this session
- /// will emit — feature-gates the UI.
- #[serde(default)]
- pub capabilities: Vec<String>,
- /// `false` = fresh spawn, `true` = reconnect/resume (drives idempotent upsert
- /// rather than a duplicate record).
- #[serde(default)]
- pub resumed: bool,
- /// ISO-8601 session start.
- #[serde(default)]
- pub started_at: String,
-}
-
-/// `user_prompt` payload.
-#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
-pub struct UserPromptPayload {
- #[serde(default)]
- pub text: String,
- /// `"human"` | `"openhuman_inject"`.
- #[serde(default)]
- pub source: String,
-}
-
-/// Shared payload for the text-only kinds (`agent_message`, `agent_thinking`).
-#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
-pub struct TextPayload {
- #[serde(default)]
- pub text: String,
-}
-
-/// `tool_call` payload.
-#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
-pub struct ToolCallPayload {
- #[serde(default)]
- pub call_id: String,
- #[serde(default)]
- pub tool_name: String,
- /// `shell|file_read|file_write|edit|search|web|mcp|task|other` — kept as a
- /// free `String` for forward-compatibility (see [`HarnessEventKind`]).
- #[serde(default)]
- pub tool_kind: String,
- #[serde(default)]
- pub display: String,
- #[serde(default)]
- pub input: serde_json::Value,
-}
-
-/// `tool_result` payload.
-#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
-pub struct ToolResultPayload {
- #[serde(default)]
- pub call_id: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub ok: Option<bool>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub exit_code: Option<i64>,
- #[serde(default)]
- pub is_error: bool,
- #[serde(default)]
- pub output: String,
- #[serde(default)]
- pub output_bytes: i64,
-}
-
-/// `approval_request` payload.
-#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
-pub struct ApprovalRequestPayload {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub call_id: Option<String>,
- #[serde(default)]
- pub tool_name: String,
- #[serde(default)]
- pub display: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub reason: Option<String>,
-}
-
-/// `status` payload — the harness run-state.
-#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
-pub struct StatusPayload {
- /// `running|running_tool|waiting_approval|idle|stopped|errored`.
- #[serde(default)]
- pub state: String,
- #[serde(default)]
- pub detail: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub active_call_id: Option<String>,
-}
-
-/// `lifecycle` payload.
-#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
-pub struct LifecyclePayload {
- /// `session_start|session_end|turn_start|turn_end|compact`.
- #[serde(default)]
- pub phase: String,
-}
-
-/// `error` payload.
-#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
-pub struct ErrorPayload {
- #[serde(default)]
- pub message: String,
- #[serde(default)]
- pub fatal: bool,
-}
-
-/// `unknown` payload (`{ "raw": any }`).
-#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
-pub struct UnknownPayload {
- #[serde(default)]
- pub raw: serde_json::Value,
-}
-
-/// A v2 `event`: common envelope fields + the `kind`/`payload` pair. `kind` and
-/// `payload` are kept raw here (a discriminator string + arbitrary JSON) and
-/// decoded on demand by [`HarnessEvent::decoded`] so an unknown/garbled event
-/// never fails the whole envelope parse (it folds to
-/// [`HarnessEventKind::Unknown`]).
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct HarnessEvent {
- #[serde(default)]
- pub id: String,
- #[serde(default)]
- pub seq: i64,
- #[serde(default)]
- pub ts: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub turn_id: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub model: Option<String>,
- /// `owner` (iff `kind == user_prompt`) else `agent`.
- #[serde(default)]
- pub role: String,
- #[serde(default)]
- pub kind: String,
- #[serde(default)]
- pub payload: serde_json::Value,
-}
-
-impl HarnessEvent {
- /// Decode `(kind, payload)` into a typed [`HarnessEventKind`]. Forward-safe:
- /// an unrecognised `kind` or a payload that fails its kind's schema folds to
- /// [`HarnessEventKind::Unknown`] carrying the raw payload, so a future/garbled
- /// event never hard-fails the parse (which would silently route it to Master).
- pub fn decoded(&self) -> HarnessEventKind {
- let tagged = serde_json::json!({ "kind": self.kind, "payload": self.payload });
- serde_json::from_value(tagged).unwrap_or_else(|_| {
- HarnessEventKind::Unknown(UnknownPayload {
- raw: self.payload.clone(),
- })
- })
- }
-}
-
-/// Mirror of the TS `SessionEnvelopeV2` interface. Shares the v1 `bucket`/`scope`/
-/// `harness`/`source` blocks; swaps v1's `message` for a typed [`HarnessEvent`].
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct SessionEnvelopeV2 {
- #[serde(default)]
- pub envelope_version: String,
- #[serde(default)]
- pub version: u32,
- #[serde(default)]
- pub bucket: HarnessBucket,
- #[serde(default)]
- pub scope: HarnessScope,
- #[serde(default)]
- pub harness: HarnessInfo,
- #[serde(default)]
- pub event: HarnessEvent,
- #[serde(default)]
- pub source: HarnessSource,
-}
-
-impl SessionEnvelopeV2 {
- fn is_valid_v2(&self) -> bool {
- self.envelope_version == SESSION_ENVELOPE_VERSION_V2
- && !self.scope.harness_session_id.is_empty()
- }
-
- /// Parse a decrypted DM body as a v2 session envelope. Returns `None` for any
- /// non-v2 payload (a v1 envelope or a plain DM) so the classifier falls
- /// through to v1 then Master. Discriminates purely on `envelope_version`, so a
- /// v1 body never matches here (and vice-versa).
- pub fn parse(body: &str) -> Option<Self> {
- let envelope: Self = serde_json::from_str(body).ok()?;
- envelope.is_valid_v2().then_some(envelope)
- }
-
- /// The per-pair routing key — identical semantics to v1: the shared
- /// `scope.wrapper_session_id`, falling back to `harness_session_id` for a
- /// legacy envelope with no per-pair id.
- pub fn session_key(&self) -> String {
- if !self.scope.wrapper_session_id.is_empty() {
- return self.scope.wrapper_session_id.clone();
- }
- self.scope.harness_session_id.clone()
- }
-}
-
-/// Which pinned/session window a persisted message belongs to.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum ChatKind {
- /// Safe default (matches [`ChatKind::from_str`]'s unknown fallback).
- #[default]
- Master,
- Subconscious,
- Session,
-}
-
-impl ChatKind {
- pub fn as_str(&self) -> &'static str {
- match self {
- ChatKind::Master => "master",
- ChatKind::Subconscious => "subconscious",
- ChatKind::Session => "session",
- }
- }
-
- /// Parse the persisted string form back into a [`ChatKind`]. Unknown values
- /// fall back to [`ChatKind::Master`] (the safe, non-session default).
- pub fn from_str(s: &str) -> Self {
- match s {
- "session" => ChatKind::Session,
- "subconscious" => ChatKind::Subconscious,
- _ => ChatKind::Master,
- }
- }
-}
-
-/// Durable per-session record. `session_id` is the harness session id for
-/// [`ChatKind::Session`], or the literal `"master"` for a peer's Master window.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct OrchestrationSession {
- pub session_id: String,
- pub agent_id: String,
- pub source: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub label: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub workspace: Option<String>,
- pub last_seq: i64,
- pub created_at: String,
- pub last_message_at: String,
- /// v2 harness run-state from `status.state`
- /// (`running|running_tool|waiting_approval|idle|stopped|errored`). `None` for
- /// v1/legacy sessions — [`crate`]'s `derive_status` then falls back to recency.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub status_state: Option<String>,
- /// v2 `status.detail` — the current-activity line surfaced on the roster.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub current_detail: Option<String>,
- /// v2 `status.active_call_id` — the in-flight tool call while running a tool.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub active_call_id: Option<String>,
- // ── session_info enrichment (spec §4) ────────────────────────────────────
- // Populated from a `session_info` event; `None`/empty until one arrives (a
- // session is lazy-created on the first event of any kind regardless).
- /// `session_info.title` — human-friendly session title for the UI header.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub title: Option<String>,
- /// `session_info.model` — the active model advertised at session start.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub model: Option<String>,
- /// `session_info.handle` — the agent's `@handle`, if registered.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub handle: Option<String>,
- /// `session_info.repo` — git remote/slug the session runs in.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub repo: Option<String>,
- /// `session_info.branch` — git branch.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub branch: Option<String>,
- /// `session_info.capabilities` — advertised event kinds, for feature-gating
- /// the UI. Empty for v1/legacy sessions and until a `session_info` arrives.
- #[serde(default)]
- pub capabilities: Vec<String>,
-}
-
-/// A single persisted message. `body` is DECRYPTED plaintext and therefore
-/// workspace-internal only.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct OrchestrationMessage {
- pub id: String,
- pub agent_id: String,
- pub session_id: String,
- pub chat_kind: ChatKind,
- pub role: String,
- pub body: String,
- pub timestamp: String,
- pub seq: i64,
- /// v2 `event.kind` (`user_prompt`/`agent_message`/`tool_call`/…). `None` for
- /// v1 and pinned master/subconscious rows, which carry no per-event kind.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub event_kind: Option<String>,
- /// v2 tool identifier for `tool_call` / `approval_request` rows.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub tool_name: Option<String>,
- /// v2 correlation id linking a `tool_result` back to its `tool_call`.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub call_id: Option<String>,
- /// v2 `tool_result.ok` — whether the tool call succeeded. `None` on every row
- /// that is not a `tool_result` (so the renderer can distinguish a failed run
- /// from a successful one instead of both reading as plain output).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub ok: Option<bool>,
- /// v2 `tool_result.is_error` — the harness flagged the result as an error.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub is_error: Option<bool>,
- /// v2 `tool_result.exit_code` — process exit code when the tool was a command.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub exit_code: Option<i64>,
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- const SAMPLE: &str = r#"{
- "envelope_version": "tinyplace.harness.session.v1",
- "version": 1,
- "scope": { "type": "session", "key": "repo", "cwd": "/w",
- "wrapper_session_id": "w1", "harness_session_id": "h1" },
- "harness": { "provider": "claude", "command": "claude", "argv": [] },
- "message": { "id": "m1", "line": 2, "role": "agent", "text": "hi",
- "timestamp": "2026-07-02T00:00:00Z" },
- "source": { "path": "p", "record_type": "assistant" }
- }"#;
-
- #[test]
- fn parses_valid_v1_envelope() {
- let env = SessionEnvelopeV1::parse(SAMPLE).expect("valid v1");
- assert_eq!(env.scope.harness_session_id, "h1");
- assert_eq!(env.message.role, "agent");
- assert_eq!(env.harness.provider, "claude");
- }
-
- #[test]
- fn outgoing_builds_a_parseable_v1_envelope() {
- let env = SessionEnvelopeV1::outgoing("h9", "reply body", "m9", "2026-07-04T00:00:00Z");
- let wire = serde_json::to_string(&env).expect("encode");
- let parsed = SessionEnvelopeV1::parse(&wire).expect("valid v1");
- assert_eq!(parsed.scope.harness_session_id, "h9");
- assert_eq!(parsed.scope.wrapper_session_id, "h9");
- assert_eq!(parsed.message.text, "reply body");
- assert_eq!(parsed.message.role, "owner");
- }
-
- #[test]
- fn rejects_non_envelope_and_bad_version() {
- assert!(SessionEnvelopeV1::parse("a plain message").is_none());
- assert!(SessionEnvelopeV1::parse(
- r#"{"envelope_version":"x","scope":{"harness_session_id":"h"}}"#
- )
- .is_none());
- assert!(SessionEnvelopeV1::parse(
- r#"{"envelope_version":"tinyplace.harness.session.v1","scope":{"harness_session_id":""}}"#
- )
- .is_none());
- }
-
- // ── v2 envelope ─────────────────────────────────────────────────────────
-
- /// Build a v2 envelope wire string with the given `kind` + `payload` JSON.
- fn v2_wire(kind: &str, payload: &str) -> String {
- format!(
- r#"{{
- "envelope_version": "tinyplace.harness.session.v2",
- "version": 2,
- "bucket": {{ "unit": "minute", "start": "s", "end": "e" }},
- "scope": {{ "type": "folder", "key": "repo", "cwd": "/w",
- "wrapper_session_id": "w2", "harness_session_id": "h2" }},
- "harness": {{ "provider": "claude", "command": "claude", "argv": [] }},
- "event": {{ "id": "e1", "seq": 4, "ts": "2026-07-05T00:00:00Z",
- "turn_id": "t1", "model": "opus", "role": "agent",
- "kind": "{kind}", "payload": {payload} }},
- "source": {{ "path": "p", "record_type": "assistant" }}
- }}"#
- )
- }
-
- #[test]
- fn parses_valid_v2_envelope_and_common_event_fields() {
- let wire = v2_wire("agent_message", r#"{ "text": "hi there" }"#);
- let env = SessionEnvelopeV2::parse(&wire).expect("valid v2");
- assert_eq!(env.envelope_version, SESSION_ENVELOPE_VERSION_V2);
- assert_eq!(env.scope.wrapper_session_id, "w2");
- assert_eq!(env.harness.provider, "claude");
- assert_eq!(env.event.seq, 4);
- assert_eq!(env.event.turn_id.as_deref(), Some("t1"));
- assert_eq!(env.event.model.as_deref(), Some("opus"));
- assert_eq!(env.event.role, "agent");
- assert_eq!(env.session_key(), "w2");
- }
-
- #[test]
- fn v2_decodes_every_event_kind() {
- use HarnessEventKind::*;
-
- let up = SessionEnvelopeV2::parse(&v2_wire(
- "user_prompt",
- r#"{ "text": "do it", "source": "human" }"#,
- ))
- .unwrap();
- assert_eq!(
- up.event.decoded(),
- UserPrompt(UserPromptPayload {
- text: "do it".into(),
- source: "human".into()
- })
- );
-
- let am =
- SessionEnvelopeV2::parse(&v2_wire("agent_message", r#"{ "text": "ok" }"#)).unwrap();
- assert_eq!(
- am.event.decoded(),
- AgentMessage(TextPayload { text: "ok".into() })
- );
-
- let th =
- SessionEnvelopeV2::parse(&v2_wire("agent_thinking", r#"{ "text": "hmm" }"#)).unwrap();
- assert_eq!(
- th.event.decoded(),
- AgentThinking(TextPayload { text: "hmm".into() })
- );
-
- let tc = SessionEnvelopeV2::parse(&v2_wire(
- "tool_call",
- r#"{ "call_id": "c1", "tool_name": "bash", "tool_kind": "shell",
- "display": "ls -la", "input": { "cmd": "ls" } }"#,
- ))
- .unwrap();
- match tc.event.decoded() {
- ToolCall(p) => {
- assert_eq!(p.call_id, "c1");
- assert_eq!(p.tool_name, "bash");
- assert_eq!(p.tool_kind, "shell");
- assert_eq!(p.display, "ls -la");
- assert_eq!(p.input["cmd"], "ls");
- }
- other => panic!("expected tool_call, got {other:?}"),
- }
-
- let tr = SessionEnvelopeV2::parse(&v2_wire(
- "tool_result",
- r#"{ "call_id": "c1", "ok": true, "exit_code": 0, "is_error": false,
- "output": "done", "output_bytes": 4 }"#,
- ))
- .unwrap();
- assert_eq!(
- tr.event.decoded(),
- ToolResult(ToolResultPayload {
- call_id: "c1".into(),
- ok: Some(true),
- exit_code: Some(0),
- is_error: false,
- output: "done".into(),
- output_bytes: 4,
- })
- );
-
- let tr_unknown = SessionEnvelopeV2::parse(&v2_wire(
- "tool_result",
- r#"{ "call_id": "c1", "is_error": false, "output": "done" }"#,
- ))
- .unwrap();
- match tr_unknown.event.decoded() {
- ToolResult(p) => assert_eq!(p.ok, None),
- other => panic!("expected tool_result, got {other:?}"),
- }
-
- let ar = SessionEnvelopeV2::parse(&v2_wire(
- "approval_request",
- r#"{ "call_id": "c9", "tool_name": "rm", "display": "rm -rf x", "reason": "destructive" }"#,
- ))
- .unwrap();
- assert_eq!(
- ar.event.decoded(),
- ApprovalRequest(ApprovalRequestPayload {
- call_id: Some("c9".into()),
- tool_name: "rm".into(),
- display: "rm -rf x".into(),
- reason: Some("destructive".into()),
- })
- );
-
- let st = SessionEnvelopeV2::parse(&v2_wire(
- "status",
- r#"{ "state": "running_tool", "detail": "compiling", "active_call_id": "c1" }"#,
- ))
- .unwrap();
- assert_eq!(
- st.event.decoded(),
- Status(StatusPayload {
- state: "running_tool".into(),
- detail: "compiling".into(),
- active_call_id: Some("c1".into()),
- })
- );
-
- let lc = SessionEnvelopeV2::parse(&v2_wire("lifecycle", r#"{ "phase": "session_end" }"#))
- .unwrap();
- assert_eq!(
- lc.event.decoded(),
- Lifecycle(LifecyclePayload {
- phase: "session_end".into()
- })
- );
-
- let er =
- SessionEnvelopeV2::parse(&v2_wire("error", r#"{ "message": "boom", "fatal": true }"#))
- .unwrap();
- assert_eq!(
- er.event.decoded(),
- Error(ErrorPayload {
- message: "boom".into(),
- fatal: true
- })
- );
-
- let uk = SessionEnvelopeV2::parse(&v2_wire("unknown", r#"{ "raw": { "x": 1 } }"#)).unwrap();
- match uk.event.decoded() {
- Unknown(p) => assert_eq!(p.raw["x"], 1),
- other => panic!("expected unknown, got {other:?}"),
- }
- }
-
- #[test]
- fn v2_decodes_session_info_and_round_trips_wire_field_names() {
- let wire = v2_wire(
- "session_info",
- r#"{ "agent_address": "ELQUJvq27tYx", "handle": "@alice",
- "title": "myrepo · feat/x", "repo": "org/myrepo", "branch": "feat/x",
- "model": "claude-opus-4-8", "harness_version": "1.4.2",
- "capabilities": ["agent_message", "tool_call"],
- "resumed": false, "started_at": "2026-07-08T00:00:00Z" }"#,
- );
- let env = SessionEnvelopeV2::parse(&wire).expect("valid v2");
- let decoded = env.event.decoded();
- let expected = SessionInfoPayload {
- agent_address: "ELQUJvq27tYx".into(),
- handle: Some("@alice".into()),
- title: Some("myrepo · feat/x".into()),
- repo: Some("org/myrepo".into()),
- branch: Some("feat/x".into()),
- model: Some("claude-opus-4-8".into()),
- harness_version: Some("1.4.2".into()),
- capabilities: vec!["agent_message".into(), "tool_call".into()],
- resumed: false,
- started_at: "2026-07-08T00:00:00Z".into(),
- };
- assert_eq!(decoded, HarnessEventKind::SessionInfo(expected.clone()));
-
- // Re-encode the adjacently-tagged kind and decode again: a full round-trip
- // proves the `kind`/`payload` framing survives serialize → deserialize.
- let reencoded = serde_json::to_string(&HarnessEventKind::SessionInfo(expected.clone()))
- .expect("encode kind");
- let back: HarnessEventKind = serde_json::from_str(&reencoded).expect("decode kind");
- assert_eq!(back, HarnessEventKind::SessionInfo(expected.clone()));
-
- // The payload's wire field names must be byte-identical to the TS emitter
- // (spec §2a): snake_case keys, optionals present only when set.
- let payload_json = serde_json::to_value(&expected).unwrap();
- for key in [
- "agent_address",
- "handle",
- "title",
- "repo",
- "branch",
- "model",
- "harness_version",
- "capabilities",
- "resumed",
- "started_at",
- ] {
- assert!(payload_json.get(key).is_some(), "missing wire key `{key}`");
- }
-
- // Optionals are omitted when absent (`skip_serializing_if`), and defaults
- // fill missing wire fields so a thin `session_info` never fails to decode.
- let minimal =
- SessionEnvelopeV2::parse(&v2_wire("session_info", r#"{ "agent_address": "X" }"#))
- .expect("valid v2");
- match minimal.event.decoded() {
- HarnessEventKind::SessionInfo(p) => {
- assert_eq!(p.agent_address, "X");
- assert_eq!(p.handle, None);
- assert!(p.capabilities.is_empty());
- assert!(!p.resumed);
- }
- other => panic!("expected session_info, got {other:?}"),
- }
- let minimal_json = serde_json::to_value(SessionInfoPayload {
- agent_address: "X".into(),
- ..Default::default()
- })
- .unwrap();
- assert!(
- minimal_json.get("handle").is_none(),
- "unset optionals must be skipped on the wire"
- );
- }
-
- #[test]
- fn v2_unrecognised_kind_folds_to_unknown_not_a_parse_error() {
- // A future kind the receiver doesn't model must not fail the envelope
- // parse (which would silently route the DM to Master); it folds to Unknown
- // carrying the raw payload.
- let env = SessionEnvelopeV2::parse(&v2_wire("quantum_teleport", r#"{ "flux": 42 }"#))
- .expect("still a valid v2 envelope");
- match env.event.decoded() {
- HarnessEventKind::Unknown(p) => assert_eq!(p.raw["flux"], 42),
- other => panic!("expected unknown fold, got {other:?}"),
- }
- }
-
- #[test]
- fn v2_rejects_v1_body_and_plain_and_bad_version() {
- // A v1 envelope must NOT parse as v2 (discriminated on envelope_version).
- assert!(SessionEnvelopeV2::parse(SAMPLE).is_none());
- assert!(SessionEnvelopeV2::parse("a plain message").is_none());
- // Right shape, wrong version string.
- assert!(SessionEnvelopeV2::parse(
- r#"{"envelope_version":"tinyplace.harness.session.v3","scope":{"harness_session_id":"h"}}"#
- )
- .is_none());
- // Correct version but empty harness id → invalid.
- assert!(SessionEnvelopeV2::parse(
- r#"{"envelope_version":"tinyplace.harness.session.v2","scope":{"harness_session_id":""}}"#
- )
- .is_none());
- // Conversely a v2 body is not a v1 envelope.
- let v2 = v2_wire("agent_message", r#"{ "text": "x" }"#);
- assert!(SessionEnvelopeV1::parse(&v2).is_none());
- }
-
- #[test]
- fn v2_session_key_falls_back_to_harness_id() {
- let env = SessionEnvelopeV2::parse(
- r#"{
- "envelope_version": "tinyplace.harness.session.v2",
- "scope": { "harness_session_id": "h-only" },
- "event": { "kind": "agent_message", "payload": { "text": "x" } }
- }"#,
- )
- .expect("valid v2");
- assert_eq!(env.session_key(), "h-only");
- }
-
- #[test]
- fn session_key_is_the_shared_wrapper_id_then_harness_fallback() {
- // The single per-pair id lives in `wrapper_session_id`.
- assert_eq!(
- SessionEnvelopeV1::parse(SAMPLE).unwrap().session_key(),
- "w1"
- );
- // Legacy envelope with no per-pair id: fall back to the harness id.
- let env = SessionEnvelopeV1::parse(
- r#"{
- "envelope_version": "tinyplace.harness.session.v1",
- "scope": { "harness_session_id": "h-only" }
- }"#,
- )
- .expect("valid v1");
- assert_eq!(env.session_key(), "h-only");
- }
-}
diff --git a/src/openhuman/hosted/orchestration/wire.rs b/src/openhuman/hosted/orchestration/wire.rs
deleted file mode 100644
index 989a27e1a1..0000000000
--- a/src/openhuman/hosted/orchestration/wire.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-//! Sanitized wire DTOs for the hosted orchestration brain.
-//!
-//! # Security choke point
-//!
-//! This file is the trust-boundary allowlist between the device and the backend.
-//! Every field that crosses to `POST /orchestration/v1/events` is constructed
-//! **explicitly** here — there is no `#[derive(Serialize)]` over an internal
-//! state struct that could leak a newly-added field. Signal key material,
-//! credentials, local filesystem paths, and workspace locations are NEVER part
-//! of these structs, and the golden key-set test below asserts the exact JSON
-//! shape so a future field addition fails loudly in review.
-
-use serde::Serialize;
-use serde_json::Value;
-
-/// Wire-protocol version this client speaks. Must fall within the backend's
-/// advertised `[min, max]`; a mismatch yields `409 ORCH_PROTOCOL_MISMATCH`.
-pub const ORCH_WIRE_PROTOCOL: u8 = 1;
-
-/// The inner `event` object of an ingest upload. Field-for-field the backend's
-/// `orchestrationEventSchema`.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-pub struct OrchestrationEventWire {
- /// Store-assigned monotonic per-session ordinal (the idempotency key).
- pub seq: i64,
- /// One of `user` | `assistant` | `system` (clamped on build).
- pub role: String,
- /// The event's originator — for an inbound DM, the counterpart agent id.
- pub sender: String,
- /// Decrypted plaintext body. Never key material or a local path.
- pub body: String,
- /// Client event timestamp, epoch milliseconds.
- pub ts: i64,
- /// Event kind (`dm`, a v2 harness `event.kind`, …). Free-form, ≤64 chars.
- pub kind: String,
-}
-
-/// The full `POST /orchestration/v1/events` request body.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct OrchestrationEventEnvelopeWire {
- pub protocol: u8,
- /// The paired agent this session is with. Not a credential — a public handle.
- pub counterpart_agent_id: String,
- pub session_id: String,
- pub event: OrchestrationEventWire,
-}
-
-/// Clamp an arbitrary role string to the backend's accepted enum. Unknown roles
-/// (or empty) default to `user` so a malformed harness role never trips a 400.
-fn sanitize_role(role: &str) -> String {
- match role {
- "user" | "assistant" | "system" => role.to_string(),
- _ => "user".to_string(),
- }
-}
-
-impl OrchestrationEventEnvelopeWire {
- /// Build a sanitized envelope from primitive fields. Constructing from
- /// primitives (rather than an internal state struct) is deliberate: it keeps
- /// the crossed field set an explicit, auditable allowlist.
- #[allow(clippy::too_many_arguments)]
- pub fn build(
- counterpart_agent_id: &str,
- session_id: &str,
- seq: i64,
- role: &str,
- sender: &str,
- body: &str,
- ts: i64,
- kind: &str,
- ) -> Self {
- Self {
- protocol: ORCH_WIRE_PROTOCOL,
- counterpart_agent_id: counterpart_agent_id.to_string(),
- session_id: session_id.to_string(),
- event: OrchestrationEventWire {
- seq: seq.max(0),
- role: sanitize_role(role),
- sender: sender.to_string(),
- body: body.to_string(),
- ts: ts.max(0),
- kind: if kind.is_empty() {
- "message".to_string()
- } else {
- kind.to_string()
- },
- },
- }
- }
-
- /// Serialize to a JSON value for the HTTP body.
- pub fn to_value(&self) -> Value {
- // Infallible for this closed struct of primitives.
- serde_json::to_value(self).expect("orchestration wire envelope serializes")
- }
-}
-
-/// Parse an RFC3339 timestamp into epoch milliseconds. Pure; returns `None` on
-/// a malformed input so the caller can fall back (e.g. to the ingest clock).
-pub fn parse_ts_ms(ts: &str) -> Option<i64> {
- chrono::DateTime::parse_from_rfc3339(ts)
- .ok()
- .map(|dt| dt.timestamp_millis())
-}
-
-/// One world-state-diff entry crossing to `POST /orchestration/v1/world-diff`.
-/// `note` is a short derived observation (never a local path or key material).
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-pub struct WorldDiffEntryWire {
- pub seq: i64,
- pub note: String,
- pub ts: i64,
-}
-
-impl WorldDiffEntryWire {
- pub fn build(seq: i64, note: &str, ts: i64) -> Self {
- Self {
- seq: seq.max(0),
- note: note.to_string(),
- ts: ts.max(0),
- }
- }
-}
-
-/// The full `POST /orchestration/v1/world-diff` request body. Same allowlist
-/// discipline as the event envelope — only these fields are constructed.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct WorldDiffBatchWire {
- pub protocol: u8,
- pub session_id: String,
- pub entries: Vec<WorldDiffEntryWire>,
-}
-
-impl WorldDiffBatchWire {
- pub fn build(session_id: &str, entries: Vec<WorldDiffEntryWire>) -> Self {
- Self {
- protocol: ORCH_WIRE_PROTOCOL,
- session_id: session_id.to_string(),
- entries,
- }
- }
-
- pub fn to_value(&self) -> Value {
- serde_json::to_value(self).expect("orchestration world-diff batch serializes")
- }
-}
-
-// The wire allowlist is guarded by the golden key-set test in
-// `tests/orchestration_shadow_push_e2e.rs` (integration crate): the root
-// crate's `cfg(test)` build is currently blocked by unrelated stale test
-// modules at this checkout, so the security-critical assertions live where they
-// can actually run — against the compiled lib.
diff --git a/src/openhuman/hosted/orchestration/world_diff_uploader.rs b/src/openhuman/hosted/orchestration/world_diff_uploader.rs
deleted file mode 100644
index 50eadecd3f..0000000000
--- a/src/openhuman/hosted/orchestration/world_diff_uploader.rs
+++ /dev/null
@@ -1,98 +0,0 @@
-//! Periodic world-diff flusher.
-//!
-//! Drains the device `world_obs` buffer (compact observations produced from
-//! locally-observed events) and uploads it to the hosted brain via
-//! `POST /orchestration/v1/world-diff`, whose receipt schedules the subconscious
-//! steering tick. Best-effort: a failed flush leaves rows buffered for the next
-//! tick, and a replayed batch is an idempotent 202 server-side (dedupe on
-//! `(userId, sessionId, seq)`).
-
-use std::collections::BTreeMap;
-use std::time::Duration;
-
-use crate::openhuman::config::Config;
-
-use super::store;
-use super::wire::{WorldDiffBatchWire, WorldDiffEntryWire};
-
-const LOG: &str = "orchestration";
-
-/// Max observations drained per flush — bounds a single upload burst.
-const DRAIN_LIMIT: u32 = 200;
-
-/// Default cadence of the periodic flush loop.
-pub const DEFAULT_FLUSH_INTERVAL: Duration = Duration::from_secs(30);
-
-/// Drain the buffer once and upload it, grouped per session (the world-diff route
-/// keys on a single `sessionId`). Returns the number of entries uploaded. A
-/// session's rows are deleted only after its batch is accepted, so a transient
-/// failure retries next tick.
-pub async fn flush_once(config: &Config) -> Result<usize, String> {
- let rows = store::with_connection(&config.workspace_dir, |conn| {
- store::drain_world_obs(conn, DRAIN_LIMIT)
- })
- .map_err(|e| format!("drain world_obs: {e}"))?;
- if rows.is_empty() {
- return Ok(0);
- }
-
- let mut by_session: BTreeMap<String, Vec<store::WorldObs>> = BTreeMap::new();
- for row in rows {
- by_session
- .entry(row.session_id.clone())
- .or_default()
- .push(row);
- }
-
- let mut uploaded = 0usize;
- for (session_id, group) in by_session {
- let entries: Vec<WorldDiffEntryWire> = group
- .iter()
- .map(|r| WorldDiffEntryWire::build(r.seq, &r.note, r.ts))
- .collect();
- let batch = WorldDiffBatchWire::build(&session_id, entries);
- match super::cloud::push_world_diff(config, &batch).await {
- Ok(()) => {
- let ids: Vec<i64> = group.iter().map(|r| r.id).collect();
- let n = ids.len();
- if let Err(e) = store::with_connection(&config.workspace_dir, |conn| {
- store::delete_world_obs(conn, &ids)
- }) {
- // Uploaded but not cleared — a re-upload is an idempotent 202
- // no-op server-side (dedupe on seq). Safe but noisy; log it.
- log::warn!(
- target: LOG,
- "[orchestration] world_diff.flush.clear_failed session={session_id} err={e}"
- );
- }
- uploaded += n;
- }
- Err(e) => {
- log::warn!(
- target: LOG,
- "[orchestration] world_diff.flush.upload_failed session={session_id} err={e}"
- );
- // Leave the rows buffered for the next tick.
- }
- }
- }
- log::debug!(target: LOG, "[orchestration] world_diff.flush uploaded={uploaded}");
- Ok(uploaded)
-}
-
-/// Run the periodic flush loop until the process exits. Spawned once after login.
-/// The first (immediate) interval tick is skipped so the first flush waits a full
-/// interval, giving the socket time to come up.
-pub async fn run_flush_loop(config: Config, interval: Duration) {
- let mut tick = tokio::time::interval(interval);
- tick.tick().await;
- loop {
- tick.tick().await;
- if !config.orchestration.enabled {
- continue;
- }
- if let Err(e) = flush_once(&config).await {
- log::warn!(target: LOG, "[orchestration] world_diff.flush.error err={e}");
- }
- }
-}
diff --git a/src/openhuman/hosted/orchestration/world_model.rs b/src/openhuman/hosted/orchestration/world_model.rs
deleted file mode 100644
index ccaa38ab4e..0000000000
--- a/src/openhuman/hosted/orchestration/world_model.rs
+++ /dev/null
@@ -1,68 +0,0 @@
-//! Device-side world-observation notes for the hosted subconscious tier.
-//!
-//! In the hosted-brain era the device no longer runs the wake graph, so it does
-//! not compute the server's full `OrchestrationState` delta. Instead it emits a
-//! compact, bounded observation note per locally-observed event (an inbound DM,
-//! an executed effect). The periodic uploader batches these to
-//! `POST /orchestration/v1/world-diff`, whose receipt schedules the hosted
-//! subconscious steering tick.
-//!
-//! # Trust boundary
-//!
-//! A note crosses the wire (it becomes `WorldDiffEntryWire::note`). It follows
-//! the same discipline as the wire allowlist: **never** key material,
-//! credentials, or a local filesystem path — only a short derived observation.
-//! Message bodies are summarised to a length/shape, never copied.
-
-/// Hard cap on a note's length (chars) — bounds the crossed payload.
-const NOTE_MAX_CHARS: usize = 240;
-
-/// Build a compact world-observation note for an ingested session event. Bounded
-/// and single-line so it is safe to cross the wire: the body is summarised to its
-/// character count, never copied.
-pub fn observe_ingest_note(session_id: &str, sender: &str, kind: &str, body: &str) -> String {
- let body = body.trim();
- let shape = if body.is_empty() {
- "empty".to_string()
- } else {
- format!("{}chars", body.chars().count())
- };
- clamp(&format!(
- "inbound {} in {} from {} ({})",
- kind_or(kind),
- session_or(session_id),
- short_handle(sender),
- shape
- ))
-}
-
-fn kind_or(kind: &str) -> &str {
- if kind.is_empty() {
- "message"
- } else {
- kind
- }
-}
-
-fn session_or(session_id: &str) -> &str {
- if session_id.is_empty() {
- "master"
- } else {
- session_id
- }
-}
-
-/// A counterpart handle is a public identifier, never a credential — but bound
-/// its length so an oversized field can't bloat the note.
-fn short_handle(sender: &str) -> String {
- sender.chars().take(64).collect()
-}
-
-/// Collapse newlines and clamp to [`NOTE_MAX_CHARS`] so every note is a single
-/// bounded line.
-fn clamp(s: &str) -> String {
- s.chars()
- .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
- .take(NOTE_MAX_CHARS)
- .collect()
-}
diff --git a/src/openhuman/mod.rs b/src/openhuman/mod.rs
index f075a82dbb..fef2d25c2c 100644
--- a/src/openhuman/mod.rs
+++ b/src/openhuman/mod.rs
@@ -68,7 +68,6 @@ pub mod skills;
#[cfg(feature = "e2e-test-support")]
pub mod test_support;
pub mod threads;
-pub mod tinyplace;
pub mod tools;
pub mod util;
pub mod voice;
diff --git a/src/openhuman/modules/registry.rs b/src/openhuman/modules/registry.rs
index 7af72e5da4..bd3f199d66 100644
--- a/src/openhuman/modules/registry.rs
+++ b/src/openhuman/modules/registry.rs
@@ -114,9 +114,8 @@ const TINYDOCS: ModuleRecord = ModuleRecord {
/// matches one of the entries below — `super::wallet::attested_proxy` checks
/// this table itself rather than trusting that some check happened.
///
-/// One call brings key material back: `ExportKey`, used solely for tiny.place's
-/// `LocalSigner::from_seed`, which takes a seed and cannot be handed a message
-/// to sign instead. Replacing that seam is what it would take to remove it.
+/// The contract also exposes `ExportKey` for downstream hosts that must drive
+/// a signer locally; OpenHuman itself does not call it.
///
/// Three releases got here, and the order mattered. v0.2.3 changed no method at
/// all — it was the same module rebuilt against a bus that could attest it.
diff --git a/src/openhuman/modules/wallet.rs b/src/openhuman/modules/wallet.rs
index d45f08988e..1e8c03fdb1 100644
--- a/src/openhuman/modules/wallet.rs
+++ b/src/openhuman/modules/wallet.rs
@@ -195,10 +195,8 @@ pub async fn sign_message(
/// Ask the module for the raw derived key.
///
-/// The one call that brings key material back into this process. It exists for
-/// signers this host must drive itself — tinyplace's `LocalSigner`, which takes
-/// a seed and cannot be handed a transaction instead. Anything that can use
-/// [`sign_transaction_in_module`] must.
+/// A compatibility call for downstream hosts that must drive a signer locally.
+/// OpenHuman's own wallet paths sign inside the module.
///
/// # Errors
///
diff --git a/src/openhuman/platform/about_app/catalog_data.rs b/src/openhuman/platform/about_app/catalog_data.rs
index f2c2f9e659..9407f06fc1 100644
--- a/src/openhuman/platform/about_app/catalog_data.rs
+++ b/src/openhuman/platform/about_app/catalog_data.rs
@@ -1728,21 +1728,4 @@ pub(super) const CAPABILITIES: &[Capability] = &[
status: CapabilityStatus::Stable,
privacy: LOCAL_RAW,
},
- Capability {
- id: "intelligence.session_orchestration",
- name: "Session Orchestration",
- domain: "orchestration",
- category: CapabilityCategory::Intelligence,
- description: "Coordinate wrapped Claude Code / Codex sessions over tiny.place: the device \
- forwards session DMs to the hosted orchestration brain, which reasons, \
- replies, and steers on its own cadence server-side. The device executes the \
- effects the brain pushes back (send the reply, mirror an eviction into local \
- memory), renders the hosted read surface, and can run the paid Medulla API \
- directly with its local contact, session-history, and send-to-agent tools.",
- how_to: "Intelligence > Orchestration (pair a wrapped session, then chat via the Master \
- window), or call openhuman.orchestration_run. Prompt, graph, and resource \
- overrides live under [orchestration.medulla] in config.toml.",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
];
diff --git a/src/openhuman/platform/socket/event_handlers.rs b/src/openhuman/platform/socket/event_handlers.rs
index 57d90f56ee..3b42bd36c5 100644
--- a/src/openhuman/platform/socket/event_handlers.rs
+++ b/src/openhuman/platform/socket/event_handlers.rs
@@ -8,7 +8,6 @@ use std::sync::Arc;
use serde_json::json;
use tokio::sync::mpsc;
-use tokio_util::sync::CancellationToken;
use crate::api::models::socket::ConnectionStatus;
use crate::core::bus::BUS;
@@ -25,7 +24,7 @@ use super::manager::{emit_server_event, emit_state_change, SharedState};
pub(super) fn handle_sio_event(
event_name: &str,
data: serde_json::Value,
- emit_tx: &mpsc::UnboundedSender<String>,
+ _emit_tx: &mpsc::UnboundedSender<String>,
shared: &Arc<SharedState>,
) {
// Log every incoming event for observability.
@@ -64,14 +63,6 @@ pub(super) fn handle_sio_event(
super::medulla::workflows::begin_connection_generation();
*shared.status.write() = ConnectionStatus::Connected;
emit_state_change(shared);
- // Declare the device-tool manifest so the hosted brain knows which
- // tool calls to round-trip to this device (Phase 2). Sent every
- // (re)connect so the server's view is rebuilt from scratch.
- emit_via_channel(
- emit_tx,
- "orch:register_tools",
- crate::openhuman::hosted::orchestration::effect_executor::device_tool_manifest(),
- );
// Advertise this core's agent roster to the backend so a medulla
// operator can delegate `medulla:task_run` to a named agent. The
// backend clears the roster on socket disconnect.
@@ -88,85 +79,6 @@ pub(super) fn handle_sio_event(
*shared.status.write() = ConnectionStatus::Error;
emit_state_change(shared);
}
- // Hosted-brain device effect: relay a reply over Signal, then ack. Runs
- // async so the recv loop isn't blocked on the send; the ack rides back
- // over the same socket. Device Signal keys never leave the machine.
- "orch:effect:send_dm" => {
- let tx = emit_tx.clone();
- // Snapshotted before the spawn so the task is bound to the
- // connection that asked for the work, not to whichever one happens
- // to be live when it finishes.
- let connection = super::medulla::workflows::connection_generation();
- tokio::spawn(async move {
- if let Some((call_id, ack)) =
- crate::openhuman::hosted::orchestration::effect_executor::handle_send_dm(&data)
- .await
- {
- if emit_result_if_connected(
- &tx,
- &connection,
- "orch:effect:result",
- &call_id,
- ack,
- ) {
- log::debug!("[socket] orch:effect:send_dm acked call_id={call_id}");
- }
- }
- });
- }
- // Hosted-brain device tool call: run a local (read-only) device tool and
- // return the result so the reasoning loop can continue.
- "orch:tool_call" => {
- let tx = emit_tx.clone();
- let connection = super::medulla::workflows::connection_generation();
- tokio::spawn(async move {
- // Deliberately NOT a `select!` against the token, unlike the
- // registration reads in `medulla::workflows`. Dropping this
- // future mid-flight would abandon a side-effecting tool with
- // its `call_id` still latched and no result — the exact failure
- // this guard exists to prevent. Let it finish; gate the emit.
- if let Some((call_id, result)) =
- crate::openhuman::hosted::orchestration::effect_executor::handle_tool_call(
- &data,
- )
- .await
- {
- if emit_result_if_connected(
- &tx,
- &connection,
- "orch:tool_result",
- &call_id,
- result,
- ) {
- log::debug!("[socket] orch:tool_call result call_id={call_id}");
- }
- }
- });
- }
- // Hosted-brain context-guard eviction: fold the evicted compressed
- // summaries into local memory RAG so they stay retrievable offline, then
- // ack. Async so the recv loop isn't blocked on the RAG write; the ack
- // rides back over the same socket (shared `orch:effect:result` channel).
- "orch:effect:evict" => {
- let tx = emit_tx.clone();
- let connection = super::medulla::workflows::connection_generation();
- tokio::spawn(async move {
- if let Some((call_id, ack)) =
- crate::openhuman::hosted::orchestration::effect_executor::handle_evict(&data)
- .await
- {
- if emit_result_if_connected(
- &tx,
- &connection,
- "orch:effect:result",
- &call_id,
- ack,
- ) {
- log::debug!("[socket] orch:effect:evict acked call_id={call_id}");
- }
- }
- });
- }
// Webhook tunnel — publish to event bus for routing by WebhookRequestSubscriber
"webhook:request" => {
log::info!("[socket] Publishing webhook:request to event bus");
@@ -518,82 +430,6 @@ fn base64_encode(input: &str) -> String {
base64::engine::general_purpose::STANDARD.encode(input.as_bytes())
}
-/// Emit a hosted-brain result, but only if the connection that asked for it is
-/// still the live one.
-///
-/// The emit channel outlives the socket: `emit_tx`/`emit_rx` is created once per
-/// [`connect`](super::manager::SocketManager::connect) and re-used by every
-/// reconnect attempt in the loop. So a result queued while the socket is down is
-/// not dropped — it is flushed onto the *next* connection, which has a different
-/// sid and whose roster the backend has already cleared. Nobody is waiting for
-/// it there, and the frame can only confuse whoever is.
-///
-/// # Why the `call_id` claim is deliberately left alone
-///
-/// The effect has already *happened* by the time this is reached — the claim is
-/// taken on entry and the work runs to completion before the result comes back.
-/// Releasing it so the backend's redelivery re-runs the call would re-execute a
-/// side effect that already succeeded: `handle_send_dm` sends over Signal with
-/// no `call_id` reaching that transport, so a peer would receive the message
-/// twice, and a local-execution `orch:tool_call` would spawn a second
-/// background agent. Both paths keep a successful id latched on purpose.
-///
-/// The cost of leaving it latched is that the redelivery is answered with the
-/// synthetic `{"accepted": true, "status": "running", "duplicate": true}` frame
-/// rather than the real result, so the brain's turn does not complete. That is
-/// unchanged from before this guard existed, and it is the lesser harm: a
-/// stalled turn is recoverable, a duplicate message to a human is not. Closing
-/// it properly needs the result cached for replay on the next connection, or a
-/// server-side deadline on the tool call — neither of which belongs here. The
-/// `warn!` below names the stranded `call_id` so the stall is diagnosable
-/// instead of silent.
-///
-/// # The check and the send are one step
-///
-/// Both happen inside `medulla::workflows::with_live_connection`, which holds
-/// the generation lock across them. Checked separately, the socket loop could
-/// end the generation and drain the channel in the gap, and the send would then
-/// sit in an empty channel waiting for the next connection — the very thing
-/// this exists to prevent.
-///
-/// Returns whether the result was emitted.
-pub(super) fn emit_result_if_connected(
- tx: &mpsc::UnboundedSender<String>,
- connection: &CancellationToken,
- event: &str,
- call_id: &str,
- data: serde_json::Value,
-) -> bool {
- let delivered = super::medulla::workflows::with_live_connection(connection, || {
- emit_via_channel(tx, event, data);
- })
- .is_some();
-
- if !delivered {
- log::warn!(
- "[socket] {event} undeliverable (the socket closed before the result was ready); \
- dropped rather than sent on the next connection. The effect ran, so its claim \
- stays latched and the turn will not complete: call_id={call_id}"
- );
- }
- delivered
-}
-
-/// Send a Socket.IO event through the emit channel.
-///
-/// Format: `42["eventName", data]`
-pub(super) fn emit_via_channel(
- tx: &mpsc::UnboundedSender<String>,
- event: &str,
- data: serde_json::Value,
-) {
- let payload = serde_json::to_string(&json!([event, data])).unwrap_or_default();
- let msg = format!("42{}", payload);
- if let Err(e) = tx.send(msg) {
- log::error!("[socket] emit_via_channel failed: {e}");
- }
-}
-
// ---------------------------------------------------------------------------
// SIO event parsing
// ---------------------------------------------------------------------------
@@ -626,95 +462,6 @@ mod tests {
})
}
- // ── emit_result_if_connected ────────────────────────────────────
-
- use crate::openhuman::hosted::orchestration::effect_executor::{
- is_duplicate_call, release_call,
- };
-
- /// A `call_id` unique to this test process, so the tests do not collide
- /// through the process-global `SEEN_CALL_IDS` set.
- fn unique_call_id(tag: &str) -> String {
- use std::sync::atomic::{AtomicUsize, Ordering};
- static COUNTER: AtomicUsize = AtomicUsize::new(0);
- format!(
- "emit-guard-{tag}-{}",
- COUNTER.fetch_add(1, Ordering::Relaxed)
- )
- }
-
- #[test]
- fn a_result_is_emitted_while_its_connection_is_still_live() {
- let (tx, mut rx) = mpsc::unbounded_channel::<String>();
- let connection = CancellationToken::new();
- let call_id = unique_call_id("live");
-
- // Claim it the way the effect executor does on entry.
- assert!(
- !is_duplicate_call(&call_id),
- "first claim is not a duplicate"
- );
-
- let emitted = emit_result_if_connected(
- &tx,
- &connection,
- "orch:tool_result",
- &call_id,
- json!({"ok": true}),
- );
-
- assert!(emitted, "a live connection should take the result");
- let msg = rx.try_recv().expect("the result should be on the wire");
- assert!(msg.starts_with("42[\"orch:tool_result\""), "got: {msg}");
- // The claim must survive: the result reached the socket, so a
- // redelivery should be re-acked idempotently rather than re-run.
- assert!(
- is_duplicate_call(&call_id),
- "a delivered result must leave its call_id latched"
- );
- release_call(&call_id);
- }
-
- #[test]
- fn a_result_for_a_dead_connection_is_dropped_without_disturbing_its_claim() {
- // The defect this guards: the emit channel outlives the socket, so an
- // ungated emit lands on the *next* connection — a different sid, whose
- // roster the backend has already cleared.
- //
- // The claim must survive. The effect already ran by the time the result
- // exists, so releasing it would make the backend's redelivery re-execute
- // a side effect that succeeded — a second Signal message to a peer, or a
- // second background agent. See `emit_result_if_connected`.
- let (tx, mut rx) = mpsc::unbounded_channel::<String>();
- let connection = CancellationToken::new();
- let call_id = unique_call_id("dead");
-
- assert!(
- !is_duplicate_call(&call_id),
- "first claim is not a duplicate"
- );
- connection.cancel();
-
- let emitted = emit_result_if_connected(
- &tx,
- &connection,
- "orch:tool_result",
- &call_id,
- json!({"ok": true}),
- );
-
- assert!(!emitted, "a dead connection must not take the result");
- assert!(
- rx.try_recv().is_err(),
- "nothing should be queued for the next connection"
- );
- assert!(
- is_duplicate_call(&call_id),
- "an undeliverable result must not un-claim work that already ran"
- );
- release_call(&call_id);
- }
-
// ── base64_encode ───────────────────────────────────────────────
#[test]
@@ -856,37 +603,6 @@ mod tests {
assert_eq!(*shared.status.read(), ConnectionStatus::Disconnected);
}
- // ── emit_via_channel ────────────────────────────────────────────
-
- #[test]
- fn emit_via_channel_sends_socketio_event_frame() {
- let (tx, mut rx) = mpsc::unbounded_channel::<String>();
- emit_via_channel(&tx, "hello", json!({"x": 1}));
- let msg = rx.try_recv().expect("message should be sent");
- assert!(
- msg.starts_with("42"),
- "expected SIO EVENT prefix, got: {msg}"
- );
- assert!(msg.contains("\"hello\""));
- assert!(msg.contains("\"x\""));
- }
-
- #[test]
- fn emit_via_channel_works_with_null_data() {
- let (tx, mut rx) = mpsc::unbounded_channel::<String>();
- emit_via_channel(&tx, "ping", serde_json::Value::Null);
- let msg = rx.try_recv().expect("message should be sent");
- assert_eq!(msg, r#"42["ping",null]"#);
- }
-
- #[test]
- fn emit_via_channel_logs_but_does_not_panic_on_closed_receiver() {
- let (tx, rx) = mpsc::unbounded_channel::<String>();
- drop(rx); // receiver closed first
- // Must not panic — error path just logs.
- emit_via_channel(&tx, "ping", json!({}));
- }
-
// Regression: OPENHUMAN-TAURI-KC (#1814). A multi-byte UTF-8 char
// straddling byte 500 of `data.to_string()` used to panic the debug-log
// truncator with `byte index 500 is not a char boundary`, killing the
diff --git a/src/openhuman/platform/socket/medulla/envelope.rs b/src/openhuman/platform/socket/medulla/envelope.rs
index 067147d1ff..312c1dd307 100644
--- a/src/openhuman/platform/socket/medulla/envelope.rs
+++ b/src/openhuman/platform/socket/medulla/envelope.rs
@@ -1,20 +1,151 @@
-//! Maps the agent's per-turn [`AgentProgress`] stream onto the
-//! `tinyplace.harness.session.v2` envelope kinds openhuman already emits
-//! through its tinyplace wrapper.
-//!
-//! We deliberately reuse the tinyplace v2 types (`SessionEnvelopeV2`,
-//! `HarnessEvent`, `HarnessEventKind`, and the per-kind payload structs) rather
-//! than re-deriving the envelope schema — the produced envelopes are wire-
-//! identical to the ones a wrapped CLI session forwards, so a medulla operator
-//! consumes one stream shape regardless of how the session was driven.
+//! Maps the agent's per-turn [`AgentProgress`] stream onto Medulla's native
+//! harness-event envelope.
-use tinyplace::types::{
- ApprovalRequestPayload, HarnessEvent, HarnessEventKind, HarnessScope, SessionEnvelopeV2,
- StatusPayload, TextPayload, ToolCallPayload, ToolResultPayload, SESSION_ENVELOPE_VERSION_V2,
-};
+use serde::{Deserialize, Serialize};
use crate::openhuman::agent::progress::AgentProgress;
+const MEDULLA_ENVELOPE_VERSION: &str = "medulla.harness.session.v1";
+
+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
+pub struct TextPayload {
+ #[serde(default)]
+ pub text: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
+pub struct ToolCallPayload {
+ #[serde(default)]
+ pub call_id: String,
+ #[serde(default)]
+ pub tool_name: String,
+ #[serde(default)]
+ pub tool_kind: String,
+ #[serde(default)]
+ pub display: String,
+ #[serde(default)]
+ pub input: serde_json::Value,
+}
+
+#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
+pub struct ToolResultPayload {
+ #[serde(default)]
+ pub call_id: String,
+ #[serde(default)]
+ pub ok: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub exit_code: Option<i64>,
+ #[serde(default)]
+ pub is_error: bool,
+ #[serde(default)]
+ pub output: String,
+ #[serde(default)]
+ pub output_bytes: i64,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
+pub struct ApprovalRequestPayload {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub call_id: Option<String>,
+ #[serde(default)]
+ pub tool_name: String,
+ #[serde(default)]
+ pub display: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub reason: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
+pub struct StatusPayload {
+ #[serde(default)]
+ pub state: String,
+ #[serde(default)]
+ pub detail: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub active_call_id: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
+pub struct ErrorPayload {
+ #[serde(default)]
+ pub message: String,
+ #[serde(default)]
+ pub fatal: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "kind", content = "payload", rename_all = "snake_case")]
+pub enum HarnessEventKind {
+ AgentMessage(TextPayload),
+ AgentThinking(TextPayload),
+ ToolCall(ToolCallPayload),
+ ToolResult(ToolResultPayload),
+ ApprovalRequest(ApprovalRequestPayload),
+ Status(StatusPayload),
+ Error(ErrorPayload),
+ Unknown(serde_json::Value),
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct HarnessScope {
+ #[serde(rename = "type", default)]
+ pub scope_type: String,
+ #[serde(default)]
+ pub wrapper_session_id: String,
+ #[serde(default)]
+ pub harness_session_id: String,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct HarnessEvent {
+ #[serde(default)]
+ pub id: String,
+ #[serde(default)]
+ pub seq: i64,
+ #[serde(default)]
+ pub ts: String,
+ #[serde(default)]
+ pub role: String,
+ #[serde(default)]
+ pub kind: String,
+ #[serde(default)]
+ pub payload: serde_json::Value,
+}
+
+impl HarnessEvent {
+ pub fn decoded(&self) -> HarnessEventKind {
+ serde_json::from_value(serde_json::json!({
+ "kind": self.kind,
+ "payload": self.payload,
+ }))
+ .unwrap_or_else(|_| HarnessEventKind::Unknown(self.payload.clone()))
+ }
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct HarnessEnvelope {
+ #[serde(default)]
+ pub envelope_version: String,
+ #[serde(default)]
+ pub version: u32,
+ #[serde(default)]
+ pub scope: HarnessScope,
+ #[serde(default)]
+ pub event: HarnessEvent,
+}
+
+impl HarnessEnvelope {
+ pub fn is_valid(&self) -> bool {
+ self.envelope_version == MEDULLA_ENVELOPE_VERSION
+ && !self.scope.harness_session_id.is_empty()
+ }
+
+ pub fn parse(body: &str) -> Option<Self> {
+ let envelope: Self = serde_json::from_str(body).ok()?;
+ envelope.is_valid().then_some(envelope)
+ }
+}
+
/// `role` stamped on every openhuman-produced event: these are agent-side
/// stream frames (`owner` is reserved for `user_prompt`, which the agent never
/// emits about itself).
@@ -98,12 +229,12 @@ pub fn progress_to_event_kind(progress: &AgentProgress) -> Option<HarnessEventKi
Some(kind)
}
-/// Wrap a typed [`HarnessEventKind`] in a full [`SessionEnvelopeV2`] anchored to
+/// Wrap a typed [`HarnessEventKind`] in a full [`HarnessEnvelope`] anchored to
/// `session_id`, ready to serialize into a `medulla:task_envelope` frame.
///
/// `seq` is the monotonic per-session ordering counter; `ts` is an ISO-8601
/// timestamp.
-pub fn envelope_for_kind(session_id: &str, seq: i64, kind: &HarnessEventKind) -> SessionEnvelopeV2 {
+pub fn envelope_for_kind(session_id: &str, seq: i64, kind: &HarnessEventKind) -> HarnessEnvelope {
// `HarnessEventKind` is adjacently tagged (`{ "kind": .., "payload": .. }`),
// so serializing it yields exactly the `kind`/`payload` pair `HarnessEvent`
// stores — extract them rather than hand-writing the discriminator strings.
@@ -118,9 +249,9 @@ pub fn envelope_for_kind(session_id: &str, seq: i64, kind: &HarnessEventKind) ->
.cloned()
.unwrap_or(serde_json::Value::Null);
- SessionEnvelopeV2 {
- envelope_version: SESSION_ENVELOPE_VERSION_V2.to_string(),
- version: 2,
+ HarnessEnvelope {
+ envelope_version: MEDULLA_ENVELOPE_VERSION.to_string(),
+ version: 1,
scope: HarnessScope {
scope_type: "session".to_string(),
wrapper_session_id: session_id.to_string(),
@@ -141,7 +272,7 @@ pub fn envelope_for_kind(session_id: &str, seq: i64, kind: &HarnessEventKind) ->
}
/// Convenience: build a bare `status` envelope (used to bookend a task run).
-pub fn status_envelope(session_id: &str, seq: i64, state: &str, detail: &str) -> SessionEnvelopeV2 {
+pub fn status_envelope(session_id: &str, seq: i64, state: &str, detail: &str) -> HarnessEnvelope {
envelope_for_kind(
session_id,
seq,
@@ -154,11 +285,11 @@ pub fn status_envelope(session_id: &str, seq: i64, state: &str, detail: &str) ->
}
/// Convenience: build an `error` envelope.
-pub fn error_envelope(session_id: &str, seq: i64, message: &str, fatal: bool) -> SessionEnvelopeV2 {
+pub fn error_envelope(session_id: &str, seq: i64, message: &str, fatal: bool) -> HarnessEnvelope {
envelope_for_kind(
session_id,
seq,
- &HarnessEventKind::Error(tinyplace::types::ErrorPayload {
+ &HarnessEventKind::Error(ErrorPayload {
message: message.to_string(),
fatal,
}),
@@ -201,19 +332,18 @@ mod tests {
}
#[test]
- fn envelope_is_valid_v2_and_round_trips_through_the_wire() {
+ fn envelope_is_valid_and_round_trips_through_the_wire() {
let kind = HarnessEventKind::AgentMessage(TextPayload {
text: "done".to_string(),
});
let env = envelope_for_kind("sess-1", 7, &kind);
- assert!(env.is_valid_v2());
+ assert!(env.is_valid());
assert_eq!(env.event.kind, "agent_message");
assert_eq!(env.event.seq, 7);
- // Serialize → parse back through the tinyplace v2 decoder and confirm
- // the typed kind survives the round-trip.
+ // Serialize and parse back through the Medulla decoder.
let wire = serde_json::to_string(&env).unwrap();
- let parsed = SessionEnvelopeV2::parse(&wire).expect("valid v2 wire");
+ let parsed = HarnessEnvelope::parse(&wire).expect("valid Medulla wire");
match parsed.event.decoded() {
HarnessEventKind::AgentMessage(t) => assert_eq!(t.text, "done"),
other => panic!("unexpected decoded kind: {other:?}"),
diff --git a/src/openhuman/platform/socket/medulla/mod.rs b/src/openhuman/platform/socket/medulla/mod.rs
index 290fc5e7cc..64a62d9d5c 100644
--- a/src/openhuman/platform/socket/medulla/mod.rs
+++ b/src/openhuman/platform/socket/medulla/mod.rs
@@ -17,7 +17,7 @@
//!
//! Up (openhuman → backend):
//! - `medulla:task_envelope` — the live session stream, as
-//! `tinyplace.harness.session.v2` envelopes (see [`envelope`]).
+//! native Medulla harness envelopes (see [`envelope`]).
//! - `medulla:task_result` — explicit completion.
//! - `medulla:register_agents` — roster advertised on connect
//! ([`emit_register_agents`]); the backend clears it on disconnect.
@@ -461,7 +461,7 @@ fn usage_to_json(
}
/// Emit a `medulla:task_envelope` frame up the backend socket.
-fn emit_envelope(task_id: &str, env: tinyplace::types::SessionEnvelopeV2) {
+fn emit_envelope(task_id: &str, env: envelope::HarnessEnvelope) {
let envelope = match serde_json::to_value(&env) {
Ok(v) => v,
Err(err) => {
diff --git a/src/openhuman/platform/socket/medulla/payloads.rs b/src/openhuman/platform/socket/medulla/payloads.rs
index 1ecc03c2ed..57e3a358e7 100644
--- a/src/openhuman/platform/socket/medulla/payloads.rs
+++ b/src/openhuman/platform/socket/medulla/payloads.rs
@@ -4,8 +4,7 @@
//!
//! See `docs/specs/session-streaming-api-spec.md` §6 in the medulla repo. All
//! payloads are camelCase on the wire to match the backend's Socket.IO
-//! conventions (the harness *envelope* they carry stays snake_case — that is
-//! the tinyplace v2 wire format, decoded/encoded by [`super::envelope`]).
+//! conventions (the harness envelope they carry stays snake_case).
use serde::{Deserialize, Serialize};
@@ -54,14 +53,12 @@ pub struct TaskAbort {
// ─────────────────────────────────────────────────────────────────────────────
/// `medulla:task_envelope` — one live-stream frame for a task, carrying a
-/// `tinyplace.harness.session.v2` envelope (see [`super::envelope`]).
+/// native Medulla harness envelope (see [`super::envelope`]).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TaskEnvelope {
pub task_id: String,
- /// A serialized [`tinyplace::types::SessionEnvelopeV2`]. Kept as raw JSON so
- /// this struct stays a thin transport wrapper and never re-derives the
- /// envelope kinds.
+ /// A serialized [`super::envelope::HarnessEnvelope`].
pub envelope: serde_json::Value,
}
@@ -140,10 +137,9 @@ pub struct CapabilitiesResult {
/// One saved workflow graph as advertised to the backend — enough to choose it
/// and explain the choice, never the graph itself.
///
-/// Field-compatible with the tiny.place `WorkflowAdvert`
-/// (`medulla-public/src/sdk/src/tinyplace/frames/types.rs`) and with the
-/// `WorkflowDescriptor` port in medulla-v1, so an advert crossing this boundary
-/// needs no translation layer on either side. `name`/`description` skip
+/// Field-compatible with the `WorkflowDescriptor` port in medulla-v1, so an
+/// advert crossing this boundary needs no translation layer on either side.
+/// `name`/`description` skip
/// serialization when empty for exactly that reason: the Rust advert already
/// omits its empty strings, the port therefore declares them optional, and the
/// backend passes an absent key through as absent rather than fabricating `""`.
diff --git a/src/openhuman/security/approval/gate.rs b/src/openhuman/security/approval/gate.rs
index 2d2e7987ae..1063042c58 100644
--- a/src/openhuman/security/approval/gate.rs
+++ b/src/openhuman/security/approval/gate.rs
@@ -2798,7 +2798,7 @@ mod tests {
/// Regression for #5508 / #5499: an external-effect scheduling tool
/// (`cron_add`) that runs on a freshly-spawned, turn-less task — the exact
- /// shape of `hosted::orchestration::effect_executor::run_local_agent`, which
+ /// shape of a hosted effect executor, which
/// fires the local sub-agent from a bare `tokio::spawn` with no agent turn on
/// the stack — must NOT be `Unknown`-denied once the spawn site scopes an
/// explicit `AgentTurnOrigin::Cli` (the residual site PR #5465 did not cover).
diff --git a/src/openhuman/security/approval/redact.rs b/src/openhuman/security/approval/redact.rs
index e3712f7293..2313e06c1e 100644
--- a/src/openhuman/security/approval/redact.rs
+++ b/src/openhuman/security/approval/redact.rs
@@ -273,7 +273,7 @@ mod tests {
let args = json!({
"recipient": "@alice",
"plaintext": "meet me at the usual spot",
- "associatedData": { "topic": "tinyplace dm" }
+ "associatedData": { "topic": "private message" }
});
let red = redact_args(&args);
@@ -293,7 +293,7 @@ mod tests {
"got {:?}",
red["recipient"]
);
- assert_eq!(red["associatedData"]["topic"], "tinyplace dm");
+ assert_eq!(red["associatedData"]["topic"], "private message");
}
#[test]
@@ -325,7 +325,7 @@ mod tests {
}
#[test]
- fn tinyplace_write_content_fields_are_redacted() {
+ fn network_write_content_fields_are_redacted() {
let args = json!({
"title": "Build my thing",
"description": "Long private task brief",
@@ -352,7 +352,7 @@ mod tests {
}
#[test]
- fn tinyplace_profile_update_fields_are_redacted() {
+ fn profile_update_fields_are_redacted() {
let args = json!({
"cryptoId": "did:example:alice",
"update": {
diff --git a/src/openhuman/security/credentials/ops.rs b/src/openhuman/security/credentials/ops.rs
index ee35ba5fb2..3f9919d61d 100644
--- a/src/openhuman/security/credentials/ops.rs
+++ b/src/openhuman/security/credentials/ops.rs
@@ -164,50 +164,6 @@ pub async fn start_login_gated_services(config: &Config) {
));
}
- // 6. Orchestration hosted-client: read-sync loop + world-diff uploader +
- // one-shot history migration. Idempotent (aborts a prior session's loops
- // first); no-op when orchestration is disabled. Runs here so both startup
- // (already logged in) and a fresh login start the hosted-client tail.
- //
- // Gated on the `hosted` domain family. `start_hosted_client_services`
- // lives in `hosted::orchestration`, which `DomainSet` can switch off —
- // and a gated domain is supposed to have no live surface at all, its
- // background loops included. Starting it anyway is not merely untidy:
- // the loop's first act is a backend call with the stored session, and a
- // rejection flips the scheduler gate to signed-out, which then fails
- // `verify_session_active` for every subsequent turn. An embedder running
- // `DomainSet::embedded()` (hosted: false) with its own inference
- // endpoint would watch unrelated turns fail with SESSION_EXPIRED.
- //
- // Read the domain set BEFORE the spawn: `CoreContext::current()` resolves
- // a task-local, which a spawned task does not inherit. Absent a context
- // (a direct CLI call, a unit test) the answer is "enabled", preserving
- // the previous behaviour exactly.
- {
- let hosted_enabled = crate::core::runtime::context::CoreContext::current()
- .map(|ctx| ctx.domains().hosted)
- .unwrap_or(true);
- if hosted_enabled {
- let config = config.clone();
- tasks.push((
- "orchestration",
- tokio::spawn(async move {
- let step = std::time::Instant::now();
- crate::openhuman::hosted::orchestration::start_hosted_client_services(&config)
- .await;
- log::debug!(
- "[services] orchestration hosted-client started ({} ms)",
- step.elapsed().as_millis()
- );
- }),
- ));
- } else {
- log::debug!(
- "[services] orchestration hosted-client skipped — the `hosted` domain family is off"
- );
- }
- }
-
let total = tasks.len();
let mut failed = 0usize;
for (name, task) in tasks {
@@ -255,9 +211,6 @@ pub async fn stop_login_gated_services(config: &Config) {
// logged out). Symmetric with start_login_gated_services step 3b.
crate::openhuman::voice::always_on::stop();
- // 7. Orchestration hosted-client loops (read-sync + world-diff uploader).
- crate::openhuman::hosted::orchestration::stop_hosted_client_services();
-
log::info!("[services] all login-gated services stopped");
}
@@ -635,7 +588,7 @@ async fn store_session_inner(
);
logs.push("conversation persistence bound to active workspace".to_string());
- // Start all login-gated services (voice, orchestration, and local AI).
+ // Start all login-gated services (voice and local AI).
// Uses the effective config so services see the user-scoped workspace
// directory.
start_login_gated_services(&effective_config).await;
@@ -830,7 +783,7 @@ pub async fn clear_session(config: &Config) -> Result<RpcOutcome<serde_json::Val
}
}
- // Stop all login-gated services (voice, orchestration, and local AI) so
+ // Stop all login-gated services (voice and local AI) so
// they don't run as orphan processes after logout, consuming RAM/CPU with
// no user context to operate against.
stop_login_gated_services(config).await;
diff --git a/src/openhuman/security/credentials/ops_tests.rs b/src/openhuman/security/credentials/ops_tests.rs
index b5e6ea7bab..d244a5bb13 100644
--- a/src/openhuman/security/credentials/ops_tests.rs
+++ b/src/openhuman/security/credentials/ops_tests.rs
@@ -1390,13 +1390,10 @@ async fn start_login_gated_services_completes_with_all_services_disabled() {
let mut config = Config::default();
// Every service is disabled so each `start_if_enabled` is a no-op: the test
// exercises the concurrent spawn/await machinery (the changed code) without
- // touching the mic, a model, the screen, or the network. orchestration
- // defaults ENABLED, so it must be turned off explicitly; the rest are set
- // too, independent of future default changes.
+ // touching the mic, a model, the screen, or the network.
config.local_ai.runtime_enabled = false;
config.voice_server.auto_start = false;
config.voice_server.always_on_enabled = false;
- config.orchestration.enabled = false;
// Bound the wait so a serial-blocking regression (or a hung join) fails the
// test instead of hanging CI. Every service no-ops, so this resolves almost
diff --git a/src/openhuman/security/policy/types.rs b/src/openhuman/security/policy/types.rs
index 73bb8ee69d..9649c0d13d 100644
--- a/src/openhuman/security/policy/types.rs
+++ b/src/openhuman/security/policy/types.rs
@@ -203,7 +203,9 @@ pub(super) const WORKSPACE_INTERNAL_DIRS: &[&str] = &[
// internal index. Keep legacy state inaccessible to agent file tools.
"codegraph",
".openhuman",
- "tinyplace", // Signal session store + future tinyplace state; agent-write forbidden
+ // A removed relay domain may leave encrypted identity/session state in an
+ // upgraded workspace. Keep that legacy directory private.
+ "tinyplace",
];
/// Files directly under `workspace_dir` that hold secrets or persona config
diff --git a/src/openhuman/tinyplace/manifest.rs b/src/openhuman/tinyplace/manifest.rs
deleted file mode 100644
index a355e381bf..0000000000
--- a/src/openhuman/tinyplace/manifest.rs
+++ /dev/null
@@ -1,7187 +0,0 @@
-//! tiny.place command manifest — the **single source of truth** for which SDK
-//! methods are wired into OpenHuman's JSON-RPC layer.
-//!
-//! ### Append-point convention
-//!
-//! The `// === AGENT-WORLD SECTION MANIFEST (append rows here) ===` banner is
-//! the first append point for the six fan-out section agents. Adding a new
-//! section = appending rows to [`tinyplace_handlers`] and adding the matching
-//! schemas to [`all_tinyplace_controller_schemas`] in `schemas.rs`.
-//!
-//! ### Handler shape (uniform)
-//!
-//! Each handler:
-//! 1. Deserialises params from a `Map<String, Value>`.
-//! 2. Calls `ops::global_state().client().await?` to obtain the lazily-built
-//! [`tinyplace::TinyPlaceClient`].
-//! 3. Calls the SDK method.
-//! 4. Maps the error via `ops::map_err`.
-//! 5. Serialises the result with `serde_json::to_value`.
-
-use std::collections::HashMap;
-use std::fmt::Write as _;
-use std::time::Duration;
-
-use base64::Engine as _;
-use serde_json::{Map, Value};
-
-use crate::core::all::ControllerFuture;
-use crate::openhuman::tinyplace::ops::{global_state, map_err};
-use crate::openhuman::tinyplace::payment::{
- ensure_backend_mint_matches, ensure_cluster_matches, fulfill_payment, PaymentContext,
-};
-use crate::openhuman::util::redact::redact;
-
-const LOG_PREFIX: &str = "[tinyplace]";
-
-/// Identity registration settlement retry budget — the on-chain transfer is
-/// broadcast immediately, but the backend may not see enough confirmations on
-/// the first re-submit. Mirrors the TS SDK's poll loop (~60s total).
-const REGISTER_SETTLE_MAX_ATTEMPTS: usize = 30;
-const REGISTER_SETTLE_DELAY: Duration = Duration::from_secs(2);
-
-// ── Helpers ───────────────────────────────────────────────────────────────────
-
-fn to_value<T: serde::Serialize>(v: T) -> Result<Value, String> {
- serde_json::to_value(v).map_err(|e| format!("tinyplace serialise: {e}"))
-}
-
-fn get_opt_str<'a>(params: &'a Map<String, Value>, key: &str) -> Option<&'a str> {
- params.get(key).and_then(Value::as_str)
-}
-
-fn req_str<'a>(params: &'a Map<String, Value>, key: &str) -> Result<&'a str, String> {
- get_opt_str(params, key).ok_or_else(|| format!("missing required param '{key}'"))
-}
-
-fn req_nonblank_str(params: &Map<String, Value>, key: &str) -> Result<String, String> {
- let value = req_str(params, key)?.trim();
- if value.is_empty() {
- Err(format!("missing required param '{key}'"))
- } else {
- Ok(value.to_string())
- }
-}
-
-fn encode_path_segment(raw: &str) -> String {
- let mut out = String::with_capacity(raw.len());
- for byte in raw.bytes() {
- if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
- out.push(byte as char);
- } else {
- write!(&mut out, "%{byte:02X}").expect("writing to String cannot fail");
- }
- }
- out
-}
-
-fn contact_path(agent_id: &str, suffix: Option<&str>) -> String {
- match suffix {
- Some(suffix) => format!("/contacts/{}/{}", encode_path_segment(agent_id), suffix),
- None => format!("/contacts/{}", encode_path_segment(agent_id)),
- }
-}
-
-fn contact_query(params: &Map<String, Value>) -> Vec<(String, String)> {
- let source = params
- .get("params")
- .and_then(Value::as_object)
- .unwrap_or(params);
- let mut query = Vec::new();
- for key in ["limit", "offset"] {
- if let Some(value) = source.get(key).and_then(Value::as_i64) {
- query.push((key.to_string(), value.to_string()));
- }
- }
- query
-}
-
-// ── Handler implementations ───────────────────────────────────────────────────
-
-// === AGENT-WORLD SECTION MANIFEST (append rows here) ===
-// Each block = one `manifest row`. Format:
-// pub(crate) fn handle_tinyplace_<domain>_<method>(params: Map<String, Value>) -> ControllerFuture { … }
-// The handler is then referenced in `schemas.rs` via all_tinyplace_registered_controllers().
-
-// ── Directory: list_agents ────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_directory_list_agents(
- _params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- log::debug!("{LOG_PREFIX} directory_list_agents (raw passthrough)");
- let client = global_state().client().await?;
- // The SDK types AgentCardSummary.skills/tags as Vec<String>, but the backend
- // returns them as objects ({ id, name }) — so the SDK's typed list_agents()
- // fails to deserialize ("invalid type: map, expected a string"). Fetch the
- // raw JSON instead and let the renderer normalise the shape (its
- // getSkills/toLabel helpers already handle string-or-object). Query params
- // are unused by the current sections; add query support here if needed.
- let result: serde_json::Value = client
- .http()
- .get("/directory/agents", &[])
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Directory: get_agent ──────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_directory_get_agent(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_str(&params, "agentId")?.to_string();
- log::debug!("{LOG_PREFIX} directory_get_agent agent_id={agent_id}");
- let client = global_state().client().await?;
- let result = client
- .directory
- .get_agent(&agent_id)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Directory: resolve ───────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_directory_resolve(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let name = req_str(&params, "name")?.to_string();
- log::debug!("{LOG_PREFIX} directory_resolve name={name}");
- let client = global_state().client().await?;
-
- // Try registry first.
- match client.directory.resolve(&name).await {
- Ok(resolved) if resolved.identity.is_some() || resolved.agent.is_some() => {
- // Registry hit — return the full response as-is.
- return to_value(resolved);
- }
- Ok(_) => {
- // Registry returned 200 but with no identity and no agent card.
- // Fall through to the directory-card fallback.
- log::debug!(
- "{LOG_PREFIX} directory_resolve: registry miss for '{name}', \
- trying directory card fallback"
- );
- }
- Err(e) if e.status() == Some(404) => {
- // Registry 404 — agent may be directory-only; fall through.
- log::debug!(
- "{LOG_PREFIX} directory_resolve: registry 404 for '{name}', \
- trying directory card fallback"
- );
- }
- Err(e) => return Err(map_err(e)),
- }
-
- // Directory-card fallback: query by username.
- match directory_card_fallback(client, &name).await {
- Some(card) => {
- log::debug!(
- "{LOG_PREFIX} directory_resolve: found '{name}' via directory card \
- crypto_id={}",
- card.crypto_id
- );
- // Synthesise a ResolveResponse from the agent card so the
- // frontend gets the same shape regardless of code path.
- let response = tinyplace::types::ResolveResponse {
- identity: None,
- agent: Some(card),
- };
- to_value(response)
- }
- None => Err(format!(
- "No agent found for \"{name}\". \
- Check the handle or paste their wallet address directly."
- )),
- }
- })
-}
-
-// ── Directory: reverse ───────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_directory_reverse(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let crypto_id = req_str(&params, "cryptoId")?.to_string();
- log::debug!("{LOG_PREFIX} directory_reverse crypto_id={crypto_id}");
- let client = global_state().client().await?;
- let result = client
- .directory
- .reverse(&crypto_id)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Directory: list_identities ───────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_directory_list_identities(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} directory_list_identities params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::IdentityListingQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid directory list_identities params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- let result = client
- .directory
- .list_identities(query_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Directory: skills ────────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_directory_skills(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} directory_skills params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::api::directory::DirectorySkillsParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid directory skills params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- let result = client
- .directory
- .skills(query_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Explorer: overview ────────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_explorer_overview(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!("{LOG_PREFIX} explorer_overview");
- let client = global_state().client().await?;
- let result = client.explorer.overview().await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Search: unified ───────────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_search_unified(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let query = req_str(&params, "query")?.to_string();
- log::debug!("{LOG_PREFIX} search_unified query={query}");
- let client = global_state().client().await?;
- let result = client.search.unified(&query).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-// === AGENT-WORLD SECTION MANIFEST (append rows here) ===
-// Each block = one `manifest row`. Format:
-// pub(crate) fn handle_tinyplace_<domain>_<method>(params: Map<String, Value>) -> ControllerFuture { … }
-// The handler is then referenced in `schemas.rs` via all_tinyplace_registered_controllers().
-
-// ── Profiles: get ────────────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_profiles_get(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let username = req_str(&params, "username")?.to_string();
- log::debug!("{LOG_PREFIX} profiles_get username={username}");
- let client = global_state().client().await?;
- let result = client.profiles.get(&username).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Profiles: activity ───────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_profiles_activity(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let username = req_str(&params, "username")?.to_string();
- log::debug!("{LOG_PREFIX} profiles_activity username={username}");
- let client = global_state().client().await?;
- let result = client.profiles.activity(&username).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Profiles: groups ─────────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_profiles_groups(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let username = req_str(&params, "username")?.to_string();
- log::debug!("{LOG_PREFIX} profiles_groups username={username}");
- let client = global_state().client().await?;
- let result = client.profiles.groups(&username).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Profiles: broadcasts ─────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_profiles_broadcasts(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let username = req_str(&params, "username")?.to_string();
- log::debug!("{LOG_PREFIX} profiles_broadcasts username={username}");
- let client = global_state().client().await?;
- let result = client
- .profiles
- .broadcasts(&username)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Profiles: attestations ───────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_profiles_attestations(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let username = req_str(&params, "username")?.to_string();
- log::debug!("{LOG_PREFIX} profiles_attestations username={username}");
- let client = global_state().client().await?;
- let result = client
- .profiles
- .attestations(&username)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Profiles: agent_card ─────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_profiles_agent_card(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let username = req_str(&params, "username")?.to_string();
- log::debug!("{LOG_PREFIX} profiles_agent_card username={username}");
- let client = global_state().client().await?;
- let result = client
- .profiles
- .agent_card(&username)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Users: get ───────────────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_users_get(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let crypto_id = req_str(&params, "cryptoId")?.to_string();
- log::debug!("{LOG_PREFIX} users_get crypto_id={crypto_id}");
- let client = global_state().client().await?;
- let result = client.users.get(&crypto_id).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Users: update_profile ────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_users_update_profile(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let crypto_id = req_str(&params, "cryptoId")?.to_string();
- let update_value = params.get("update").cloned().unwrap_or(Value::Null);
- let update: tinyplace::types::UserProfileUpdate = serde_json::from_value(update_value)
- .map_err(|e| format!("invalid users update_profile params: {e}"))?;
- log::debug!("{LOG_PREFIX} users_update_profile crypto_id={crypto_id}");
- let client = global_state().client().await?;
- let result = client
- .users
- .update_profile(&crypto_id, update)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_identity_floor(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let length = params.get("length").and_then(Value::as_i64);
- log::debug!("{LOG_PREFIX} marketplace_identity_floor length={length:?}");
- let client = global_state().client().await?;
- // IdentityFloor derives Serialize via the types module.
- let result = client
- .marketplace
- .identity_floor(length)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_identity_sale_history(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let name = req_str(&params, "name")?.to_string();
- log::debug!("{LOG_PREFIX} marketplace_identity_sale_history name={name}");
- let client = global_state().client().await?;
- // IdentitySaleHistoryResponse only derives Deserialize; serialize the inner vec.
- let result = client
- .marketplace
- .identity_sale_history(&name)
- .await
- .map_err(map_err)?;
- let history = to_value(result.history)?;
- Ok(serde_json::json!({ "history": history }))
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_list_bids(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let listing_id = req_str(&params, "listingId")?.to_string();
- log::debug!("{LOG_PREFIX} marketplace_list_bids listing_id={listing_id}");
- let client = global_state().client().await?;
- // BidsResponse only derives Deserialize; serialize the inner vec.
- let result = client
- .marketplace
- .list_bids(&listing_id)
- .await
- .map_err(map_err)?;
- let bids = to_value(result.bids)?;
- Ok(serde_json::json!({ "bids": bids }))
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_list_identities(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let limit = params.get("limit").and_then(Value::as_i64);
- let status = get_opt_str(&params, "status").map(str::to_string);
- log::debug!("{LOG_PREFIX} marketplace_list_identities limit={limit:?} status={status:?}");
- let client = global_state().client().await?;
- // IdentitiesResponse only derives Deserialize; serialize the inner vec.
- let result = client
- .marketplace
- .list_identities(limit, status.as_deref())
- .await
- .map_err(map_err)?;
- let identities = to_value(result.identities)?;
- Ok(serde_json::json!({ "identities": identities }))
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_list_offers(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let name = get_opt_str(&params, "name").map(str::to_string);
- let buyer = get_opt_str(&params, "buyer").map(str::to_string);
- log::debug!("{LOG_PREFIX} marketplace_list_offers name={name:?} buyer={buyer:?}");
- let client = global_state().client().await?;
- use tinyplace::api::marketplace::OfferQueryParams;
- let query_params = OfferQueryParams {
- name,
- buyer,
- ..Default::default()
- };
- // OffersResponse only derives Deserialize; serialize the inner vec.
- let result = client
- .marketplace
- .list_offers(Some(&query_params))
- .await
- .map_err(map_err)?;
- let offers = to_value(result.offers)?;
- Ok(serde_json::json!({ "offers": offers }))
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_recent(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!("{LOG_PREFIX} marketplace_recent");
- let client = global_state().client().await?;
- // RecentSalesResponse only derives Deserialize; serialize the inner vec.
- let result = client.marketplace.recent().await.map_err(map_err)?;
- let sales = to_value(result.sales)?;
- Ok(serde_json::json!({ "sales": sales }))
- })
-}
-
-pub(crate) fn handle_tinyplace_registry_get(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let name = req_str(&params, "name")?.to_string();
- log::debug!("{LOG_PREFIX} registry_get name={name}");
- let client = global_state().client().await?;
- let result = client.registry.get(&name).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-/// Register a `@handle` via the x402 confirm-before-spend flow.
-///
-/// Two-call contract (the renderer drives it):
-/// - `confirmed` omitted/false → returns the 402 `challenge` plus the wallet's
-/// USDC balance + address so the UI can render a confirm card. **No funds move.**
-/// - `confirmed: true` → fulfils the payment on-chain (devnet-guarded) and
-/// re-submits the registration with the signed payment map, retrying while the
-/// settlement confirms. **This is the only branch that spends.**
-///
-/// The free tier (backend returns the identity without a 402) short-circuits to
-/// `{ identity }` on the first call regardless of `confirmed`.
-pub(crate) fn handle_tinyplace_registry_register(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let username = req_str(&params, "username")?.trim().to_string();
- if username.is_empty() {
- return Err("missing required param 'username'".to_string());
- }
- let confirmed = params
- .get("confirmed")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- let actor_type = get_opt_str(&params, "actorType")
- .filter(|s| !s.is_empty())
- .unwrap_or("human")
- .to_string();
- let primary = params.get("primary").and_then(Value::as_bool);
- log::debug!(
- "{LOG_PREFIX} registry_register username={username} confirmed={confirmed} \
- actor_type={actor_type} primary={primary:?}"
- );
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
-
- // payment = None on the probe call so the backend issues the 402.
- let base_req = tinyplace::api::registry::RegisterRequest {
- username: username.clone(),
- crypto_id: signer.agent_id(),
- public_key: Some(signer.public_key_base64()),
- actor_type: Some(actor_type),
- primary,
- ..Default::default()
- };
-
- // ── Phase A: probe for the 402 challenge (or a free-tier identity). ──
- let challenge = match client.registry.register(base_req.clone()).await {
- Ok(identity) => {
- log::debug!("{LOG_PREFIX} registry_register free-tier ok username={username}");
- let _ =
- publish_directory_card_for_identity(client, signer.as_ref(), &identity).await;
- return to_value(serde_json::json!({ "identity": identity }));
- }
- Err(e) => match e.payment_required() {
- Some(pr) => pr.payment.clone(),
- None => return Err(map_err(e)),
- },
- };
- log::debug!(
- "{LOG_PREFIX} registry_register 402 challenge network={:?} asset={:?} amount={:?}",
- challenge.network,
- challenge.asset,
- challenge.amount,
- );
-
- // ── Unconfirmed: surface the challenge + balance, spend nothing. ──
- if !confirmed {
- let (wallet_balance, wallet_address) = wallet_usdc_balance(&signer.agent_id()).await;
- return to_value(serde_json::json!({
- "challenge": challenge,
- "walletBalance": wallet_balance,
- "walletAddress": wallet_address,
- }));
- }
-
- // ── Confirmed: cluster guards, pay on-chain, re-submit with the map. ──
- if let Some(network) = challenge.network.as_deref() {
- ensure_cluster_matches(network)?;
- }
- ensure_backend_mint_matches(client).await?;
-
- let mut extra_metadata = HashMap::new();
- extra_metadata.insert("identity".to_string(), format!("@{username}"));
- let fulfilled = fulfill_payment(
- &challenge,
- signer.as_ref(),
- PaymentContext {
- purpose: "identity.register".to_string(),
- nonce_prefix: "register".to_string(),
- extra_metadata,
- },
- )
- .await?;
- let on_chain_tx = fulfilled.on_chain_tx.clone();
-
- let mut paid_req = base_req;
- paid_req.payment = Some(fulfilled.payment_map);
-
- // Re-submit, retrying while the settlement confirms on-chain.
- let mut last_err = String::new();
- for attempt in 1..=REGISTER_SETTLE_MAX_ATTEMPTS {
- match client.registry.register(paid_req.clone()).await {
- Ok(identity) => {
- log::debug!(
- "{LOG_PREFIX} registry_register settled username={username} attempt={attempt}"
- );
- let _ = publish_directory_card_for_identity(client, signer.as_ref(), &identity)
- .await;
- return to_value(serde_json::json!({
- "identity": identity,
- "payment": { "onChainTx": on_chain_tx },
- }));
- }
- Err(e) if is_retryable_settlement_error(&e) => {
- last_err = e.to_string();
- log::debug!(
- "{LOG_PREFIX} registry_register settlement pending \
- attempt={attempt}/{REGISTER_SETTLE_MAX_ATTEMPTS}: {last_err}"
- );
- tokio::time::sleep(REGISTER_SETTLE_DELAY).await;
- }
- Err(e) => {
- // Non-retryable failure after we already paid — surface the
- // tx so the user/support can reconcile.
- return Err(format!(
- "registration failed after payment (onChainTx={on_chain_tx}): {}",
- map_err(e)
- ));
- }
- }
- }
-
- // ── Exhausted retries: recover via a fresh availability lookup. ──
- log::warn!(
- "{LOG_PREFIX} registry_register settlement retries exhausted username={username} \
- onChainTx={on_chain_tx}; attempting recovery via registry.get"
- );
- if let Ok(avail) = client.registry.get(&username).await {
- if let Some(identity) = avail.identity {
- if identity.crypto_id == signer.agent_id() {
- log::debug!(
- "{LOG_PREFIX} registry_register recovered owned identity username={username}"
- );
- let _ = publish_directory_card_for_identity(client, signer.as_ref(), &identity)
- .await;
- return to_value(serde_json::json!({
- "identity": identity,
- "payment": { "onChainTx": on_chain_tx },
- }));
- }
- }
- }
- Err(format!(
- "registration paid but not confirmed in time (onChainTx={on_chain_tx}); \
- last error: {last_err}"
- ))
- })
-}
-
-/// Fetch the wallet's Solana USDC balance for the confirm card. Best-effort:
-/// returns `(None, address)` if the balance lookup fails so the UI can still
-/// render (it falls back to letting the backend reject an underfunded payment).
-async fn wallet_usdc_balance(address: &str) -> (Option<Value>, String) {
- // The wallet's `balances()` only reports NATIVE assets (SOL/ETH/…), never SPL
- // tokens — so query the SPL USDC balance directly via
- // `getTokenAccountsByOwner` for the cluster's USDC mint. RPC failure → None
- // (UI shows "Unknown"); RPC ok but no token account → 0.
- //
- // TAURI-RUST / #4202: query tiny.place's own Solana settlement RPC FIRST, not
- // the bare public cluster RPC. tiny.place settles on its own RPC — the chain
- // where agent token accounts are actually funded — so reading the balance
- // from the public `api.mainnet-beta.solana.com` endpoint (which also rate-
- // limits / restricts `getTokenAccountsByOwner`) returned None and the confirm
- // card showed "Unknown" even with a funded, connected wallet. Use the same
- // ordered endpoints the payment path broadcasts through (tiny.place RPC →
- // public cluster fallback), so the displayed balance matches the chain the
- // payment will actually settle on.
- let mint = crate::openhuman::web3::wallet::solana_cluster().usdc_mint();
- let endpoints = crate::openhuman::web3::wallet::tinyplace_solana_rpc_endpoints();
- let body = serde_json::json!({
- "jsonrpc": "2.0",
- "id": 1,
- "method": "getTokenAccountsByOwner",
- "params": [address, { "mint": mint }, { "encoding": "jsonParsed" }],
- });
- let client = reqwest::Client::new();
- // Try each endpoint in priority order; only advance to the next one on a
- // transport / parse / malformed-shape failure (the endpoint couldn't give an
- // authoritative answer). A well-formed `/result/value` — including an empty
- // array (no token account = a real zero balance) — is authoritative and
- // returns immediately.
- let mut accounts: Option<Vec<Value>> = None;
- for rpc_url in &endpoints {
- // A settlement endpoint may embed a private provider token in its
- // path/query; redact to scheme+host before it reaches the logs.
- let safe_url = crate::openhuman::web3::wallet::redact_rpc_url(rpc_url);
- let json: Value = match client.post(rpc_url).json(&body).send().await {
- Ok(resp) => match resp.json().await {
- Ok(j) => j,
- Err(e) => {
- log::warn!("{LOG_PREFIX} usdc balance: rpc parse failed at {safe_url}: {e}");
- continue;
- }
- },
- Err(e) => {
- log::warn!("{LOG_PREFIX} usdc balance: rpc send failed at {safe_url}: {e}");
- continue;
- }
- };
- match json.pointer("/result/value").and_then(Value::as_array) {
- Some(value) => {
- accounts = Some(value.clone());
- break;
- }
- None => {
- log::warn!("{LOG_PREFIX} usdc balance: unexpected rpc shape at {safe_url}");
- continue;
- }
- }
- }
- let Some(accounts) = accounts else {
- log::warn!(
- "{LOG_PREFIX} usdc balance: no endpoint returned a usable response \
- (tried {} endpoint(s))",
- endpoints.len()
- );
- return (None, address.to_string());
- };
- // No token account = the ATA was never created = a real zero balance.
- let token_amount = accounts
- .first()
- .and_then(|acct| acct.pointer("/account/data/parsed/info/tokenAmount"));
- let (raw, formatted, decimals) = match token_amount {
- Some(ta) => (
- ta.get("amount")
- .and_then(Value::as_str)
- .unwrap_or("0")
- .to_string(),
- ta.get("uiAmountString")
- .and_then(Value::as_str)
- .unwrap_or("0")
- .to_string(),
- ta.get("decimals").and_then(Value::as_u64).unwrap_or(6),
- ),
- None => ("0".to_string(), "0".to_string(), 6),
- };
- log::debug!("{LOG_PREFIX} usdc balance for {address}: {formatted} USDC (mint={mint})");
- (
- Some(serde_json::json!({
- "raw": raw,
- "formatted": formatted,
- "decimals": decimals,
- "assetSymbol": "USDC",
- })),
- address.to_string(),
- )
-}
-
-/// A re-submitted registration returns a 402 again while the on-chain transfer
-/// is still confirming. Retry only those settlement-timing errors — never a hard
-/// rejection (which would loop pointlessly and delay the failure).
-fn is_retryable_settlement_error(e: &tinyplace::Error) -> bool {
- let mut hay = e.to_string();
- if let Some(pr) = e.payment_required() {
- if let Some(msg) = &pr.error {
- hay.push_str(msg);
- }
- }
- if let Some(body) = e.body() {
- hay.push_str(&body.to_string());
- }
- settlement_error_is_retryable(e.status(), &hay)
-}
-
-/// Pure settlement-retry decision (no SDK error type — unit-tested directly).
-/// Only a `402` whose message indicates the on-chain transfer is still
-/// confirming is retryable.
-fn settlement_error_is_retryable(status: Option<u16>, message: &str) -> bool {
- if status != Some(402) {
- return false;
- }
- let hay = message.to_lowercase();
- hay.contains("transaction not found")
- || hay.contains("not found")
- || hay.contains("insufficient confirmation")
- || hay.contains("not yet")
- || hay.contains("pending")
-}
-
-// ── Marketplace buy (x402) ─────────────────────────────────────────────────────
-
-/// Outcome of a post-payment re-submit loop that could not return a result.
-enum SettleFailure {
- /// A hard, non-retryable backend rejection (already mapped to a string).
- Hard(String),
- /// The settlement never confirmed within the retry budget.
- Exhausted(String),
-}
-
-/// Re-submit a paid domain request, retrying only while the on-chain settlement
-/// confirms (a `402` with a settlement-timing message). Shared by buy/bid/offer.
-async fn settle_retry<F, Fut, T>(label: &str, mut submit: F) -> Result<T, SettleFailure>
-where
- F: FnMut() -> Fut,
- Fut: std::future::Future<Output = Result<T, tinyplace::Error>>,
-{
- let mut last_err = String::new();
- for attempt in 1..=REGISTER_SETTLE_MAX_ATTEMPTS {
- match submit().await {
- Ok(value) => return Ok(value),
- Err(e) if is_retryable_settlement_error(&e) => {
- last_err = e.to_string();
- log::debug!(
- "{LOG_PREFIX} {label} settlement pending \
- attempt={attempt}/{REGISTER_SETTLE_MAX_ATTEMPTS}: {last_err}"
- );
- tokio::time::sleep(REGISTER_SETTLE_DELAY).await;
- }
- Err(e) => return Err(SettleFailure::Hard(map_err(e))),
- }
- }
- Err(SettleFailure::Exhausted(last_err))
-}
-
-/// Buy a marketplace product via the x402 confirm-before-spend flow.
-///
-/// Params `{ id, confirmed? }`. `confirmed:false` → `{ challenge, walletBalance,
-/// walletAddress }` (no spend). `confirmed:true` → pays on-chain and completes
-/// the purchase, returning `{ result, payment: { onChainTx } }`.
-pub(crate) fn handle_tinyplace_marketplace_buy_product(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let product_id = req_str(&params, "id")?.trim().to_string();
- if product_id.is_empty() {
- return Err("missing required param 'id'".to_string());
- }
- let confirmed = params
- .get("confirmed")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- log::debug!("{LOG_PREFIX} marketplace_buy_product id={product_id} confirmed={confirmed}");
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
-
- let base_req = tinyplace::types::ProductBuyRequest {
- buyer_crypto_id: Some(signer.agent_id()),
- ..Default::default()
- };
-
- let challenge = match client
- .marketplace
- .buy_product(&product_id, base_req.clone())
- .await
- {
- Ok(purchase) => return to_value(serde_json::json!({ "result": purchase })),
- Err(e) => match e.payment_required() {
- Some(pr) => pr.payment.clone(),
- None => return Err(map_err(e)),
- },
- };
-
- if !confirmed {
- let (wallet_balance, wallet_address) = wallet_usdc_balance(&signer.agent_id()).await;
- return to_value(serde_json::json!({
- "challenge": challenge,
- "walletBalance": wallet_balance,
- "walletAddress": wallet_address,
- }));
- }
-
- if let Some(network) = challenge.network.as_deref() {
- ensure_cluster_matches(network)?;
- }
- ensure_backend_mint_matches(client).await?;
- let mut extra_metadata = HashMap::new();
- extra_metadata.insert("productId".to_string(), product_id.clone());
- let fulfilled = fulfill_payment(
- &challenge,
- signer.as_ref(),
- PaymentContext {
- purpose: "marketplace.buy_product".to_string(),
- nonce_prefix: "buy".to_string(),
- extra_metadata,
- },
- )
- .await?;
- let on_chain_tx = fulfilled.on_chain_tx.clone();
-
- let mut paid_req = base_req;
- paid_req.payment = Some(fulfilled.payment_map);
- match settle_retry("buy_product", || {
- client
- .marketplace
- .buy_product(&product_id, paid_req.clone())
- })
- .await
- {
- Ok(purchase) => to_value(serde_json::json!({
- "result": purchase,
- "payment": { "onChainTx": on_chain_tx },
- })),
- Err(SettleFailure::Hard(m)) => Err(format!(
- "purchase failed after payment (onChainTx={on_chain_tx}): {m}"
- )),
- Err(SettleFailure::Exhausted(last)) => Err(format!(
- "purchase paid but not confirmed in time (onChainTx={on_chain_tx}); \
- last error: {last}"
- )),
- }
- })
-}
-
-/// Buy an identity listing (a `@handle` at its fixed price) via the same x402
-/// confirm-before-spend flow. Params `{ id, confirmed? }` where `id` is the
-/// listing id.
-pub(crate) fn handle_tinyplace_marketplace_buy_identity(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let listing_id = req_str(&params, "id")?.trim().to_string();
- if listing_id.is_empty() {
- return Err("missing required param 'id'".to_string());
- }
- let confirmed = params
- .get("confirmed")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- log::debug!("{LOG_PREFIX} marketplace_buy_identity id={listing_id} confirmed={confirmed}");
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
-
- // buyer left empty → the connected signing key is the actor; the SDK
- // auto-signs the canonical identity.buy payload.
- let base_req = tinyplace::types::IdentityBuyRequest {
- buyer: String::new(),
- buyer_crypto_id: signer.agent_id(),
- buyer_public_key: Some(signer.public_key_base64()),
- ..Default::default()
- };
-
- let challenge = match client
- .marketplace
- .buy_identity_listing(&listing_id, base_req.clone())
- .await
- {
- Ok(sale) => return to_value(serde_json::json!({ "result": sale })),
- Err(e) => match e.payment_required() {
- Some(pr) => pr.payment.clone(),
- None => return Err(map_err(e)),
- },
- };
-
- if !confirmed {
- let (wallet_balance, wallet_address) = wallet_usdc_balance(&signer.agent_id()).await;
- return to_value(serde_json::json!({
- "challenge": challenge,
- "walletBalance": wallet_balance,
- "walletAddress": wallet_address,
- }));
- }
-
- if let Some(network) = challenge.network.as_deref() {
- ensure_cluster_matches(network)?;
- }
- ensure_backend_mint_matches(client).await?;
- let mut extra_metadata = HashMap::new();
- extra_metadata.insert("listingId".to_string(), listing_id.clone());
- let fulfilled = fulfill_payment(
- &challenge,
- signer.as_ref(),
- PaymentContext {
- purpose: "marketplace.buy_identity".to_string(),
- nonce_prefix: "buy".to_string(),
- extra_metadata,
- },
- )
- .await?;
- let on_chain_tx = fulfilled.on_chain_tx.clone();
-
- // The signed payload depends on request fields; clearing the stale
- // signature lets the SDK re-sign with the payment attached.
- let mut paid_req = base_req;
- paid_req.payment = Some(fulfilled.payment_map);
- paid_req.signature = None;
- match settle_retry("buy_identity", || {
- client
- .marketplace
- .buy_identity_listing(&listing_id, paid_req.clone())
- })
- .await
- {
- Ok(sale) => to_value(serde_json::json!({
- "result": sale,
- "payment": { "onChainTx": on_chain_tx },
- })),
- Err(SettleFailure::Hard(m)) => Err(format!(
- "purchase failed after payment (onChainTx={on_chain_tx}): {m}"
- )),
- Err(SettleFailure::Exhausted(last)) => Err(format!(
- "purchase paid but not confirmed in time (onChainTx={on_chain_tx}); \
- last error: {last}"
- )),
- }
- })
-}
-
-// ── Marketplace bid / offer (x402 commitments) ─────────────────────────────────
-
-/// Build a [`tinyplace::types::MarketplacePrice`] from params. `network` is
-/// required (the renderer passes the listing's price network so the x402
-/// authorization targets the right chain); `asset` defaults to USDC.
-fn price_from_params(
- params: &Map<String, Value>,
-) -> Result<tinyplace::types::MarketplacePrice, String> {
- let amount = req_str(params, "amount")?.trim().to_string();
- if amount.is_empty() {
- return Err("missing required param 'amount'".to_string());
- }
- let asset = get_opt_str(params, "asset")
- .filter(|s| !s.is_empty())
- .unwrap_or("USDC")
- .to_string();
- let network = req_str(params, "network")?.trim().to_string();
- if network.is_empty() {
- return Err("missing required param 'network'".to_string());
- }
- Ok(tinyplace::types::MarketplacePrice {
- amount,
- asset,
- network,
- })
-}
-
-/// Place a bid on an identity auction listing. The SDK builds and signs the
-/// x402 authorization (an "up-to" commitment) internally — **no on-chain
-/// transfer happens here**; the bid settles on acceptance. May 402 if the
-/// backend requires a deposit (surfaced as PAYMENT_REQUIRED to the renderer).
-///
-/// Params `{ listingId, amount, asset?, network }`.
-pub(crate) fn handle_tinyplace_marketplace_bid(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let listing_id = req_str(&params, "listingId")?.trim().to_string();
- if listing_id.is_empty() {
- return Err("missing required param 'listingId'".to_string());
- }
- let price = price_from_params(&params)?;
- log::debug!(
- "{LOG_PREFIX} marketplace_bid listing_id={listing_id} amount={} asset={} network={}",
- price.amount,
- price.asset,
- price.network,
- );
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
-
- let bid = tinyplace::types::IdentityBid {
- bidder: Some(signer.agent_id()),
- bidder_crypto_id: Some(signer.agent_id()),
- bidder_public_key: Some(signer.public_key_base64()),
- price: Some(price),
- ..Default::default()
- };
- let result = client
- .marketplace
- .place_bid_with_payment(
- &listing_id,
- bid,
- tinyplace::api::marketplace::IdentityBidPaymentOptions,
- )
- .await
- .map_err(map_err)?;
-
- // Return the updated listing only — never the raw signed authorization map.
- to_value(serde_json::json!({
- "result": result.updated_listing,
- "committed": true,
- }))
- })
-}
-
-/// Make an offer to buy an identity (`@handle`) at a chosen price. Like bids,
-/// the SDK builds and signs the x402 authorization internally — **no on-chain
-/// transfer here**; the offer settles on acceptance.
-///
-/// Params `{ name, amount, asset?, network }`.
-pub(crate) fn handle_tinyplace_marketplace_offer(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let name = req_str(&params, "name")?.trim().to_string();
- if name.is_empty() {
- return Err("missing required param 'name'".to_string());
- }
- let price = price_from_params(&params)?;
- log::debug!(
- "{LOG_PREFIX} marketplace_offer name={name} amount={} asset={} network={}",
- price.amount,
- price.asset,
- price.network,
- );
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
-
- let offer = tinyplace::types::IdentityOffer {
- name: Some(name),
- buyer: Some(signer.agent_id()),
- buyer_crypto_id: Some(signer.agent_id()),
- buyer_public_key: Some(signer.public_key_base64()),
- price: Some(price),
- ..Default::default()
- };
- let result = client
- .marketplace
- .create_offer_with_payment(
- offer,
- tinyplace::api::marketplace::IdentityOfferPaymentOptions,
- )
- .await
- .map_err(map_err)?;
-
- to_value(serde_json::json!({
- "result": result.offer,
- "committed": true,
- }))
- })
-}
-
-pub(crate) fn handle_tinyplace_artifacts_get(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let artifact_id = req_str(&params, "artifactId")?.to_string();
- let actor_id = get_opt_str(&params, "actorId").map(str::to_string);
- log::debug!("{LOG_PREFIX} artifacts_get artifact_id={artifact_id} actor_id={actor_id:?}");
- let client = global_state().client().await?;
- let result = client
- .artifacts
- .get(&artifact_id, actor_id.as_deref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_artifacts_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} artifacts_list params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::ArtifactQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid artifacts list params: {e}"))
- })
- .transpose()?;
- let actor_id = get_opt_str(&params, "actorId").map(str::to_string);
-
- let client = global_state().client().await?;
- let result = client
- .artifacts
- .list(query_params.as_ref(), actor_id.as_deref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_escrow_get(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let escrow_id = req_str(&params, "escrowId")?.to_string();
- log::debug!("{LOG_PREFIX} escrow_get escrow_id={escrow_id}");
- let client = global_state().client().await?;
- let result = client.escrow.get(&escrow_id).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_escrow_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} escrow_list params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::EscrowQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid escrow list params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- let result = client
- .escrow
- .list(query_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_jobs_get(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let job_id = req_str(&params, "jobId")?.to_string();
- log::debug!("{LOG_PREFIX} jobs_get job_id={job_id}");
- let client = global_state().client().await?;
- let result = client.jobs.get(&job_id).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_jobs_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} jobs_list params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::JobQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid jobs list params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- let result = client
- .jobs
- .list(query_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_browse(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} marketplace_browse params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::ProductQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid marketplace browse params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- let result = client
- .marketplace
- .browse_marketplace(query_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_categories(
- _params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- log::debug!("{LOG_PREFIX} marketplace_categories");
- let client = global_state().client().await?;
- let result = client.marketplace.categories().await.map_err(map_err)?;
- to_value(CategoriesWrapper {
- categories: result.categories,
- })
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_featured(
- _params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- log::debug!("{LOG_PREFIX} marketplace_featured");
- let client = global_state().client().await?;
- let result = client.marketplace.featured().await.map_err(map_err)?;
- to_value(FeaturedWrapper {
- items: result.items,
- })
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_get_product(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let product_id = req_str(&params, "productId")?.to_string();
- log::debug!("{LOG_PREFIX} marketplace_get_product product_id={product_id}");
- let client = global_state().client().await?;
- let result = client
- .marketplace
- .get_product(&product_id)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_list_product_reviews(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let product_id = req_str(&params, "productId")?.to_string();
- log::debug!("{LOG_PREFIX} marketplace_list_product_reviews product_id={product_id}");
- let client = global_state().client().await?;
- let result = client
- .marketplace
- .list_product_reviews(&product_id)
- .await
- .map_err(map_err)?;
- to_value(ProductReviewsWrapper {
- reviews: result.reviews,
- })
- })
-}
-
-pub(crate) fn handle_tinyplace_marketplace_list_products(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} marketplace_list_products params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::ProductQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid marketplace list_products params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- let result = client
- .marketplace
- .list_products(query_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(ProductsWrapper {
- products: result.products,
- })
- })
-}
-
-// Serialize wrappers for marketplace responses (from #5).
-#[derive(serde::Serialize)]
-struct ProductsWrapper {
- products: Vec<tinyplace::types::Product>,
-}
-
-#[derive(serde::Serialize)]
-struct CategoriesWrapper {
- categories: Vec<tinyplace::types::MarketplaceCategory>,
-}
-
-#[derive(serde::Serialize)]
-struct FeaturedWrapper {
- items: Vec<serde_json::Value>,
-}
-
-#[derive(serde::Serialize)]
-struct ProductReviewsWrapper {
- reviews: Vec<tinyplace::types::ProductReview>,
-}
-
-pub(crate) fn handle_tinyplace_broadcasts_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} broadcasts_list params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::BroadcastQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid broadcasts list params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- let result = client
- .broadcasts
- .list(query_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_channels_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} channels_list params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::api::channels::ChannelQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid channels list params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- match client.channels.list(query_params.as_ref()).await {
- Ok(result) => to_value(result),
- Err(e) => match channels_list_degrade(&e) {
- Some(empty) => {
- log::debug!(
- "{LOG_PREFIX} channels_list endpoint unavailable -> empty list (status={:?})",
- e.status()
- );
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-/// The staging backend exposes no `/channels` route (only `/search/channels`),
-/// so the endpoint 404s. Degrade a 404 to an empty channel list rather than
-/// surfacing a hard error to the Messages UI; propagate every other error.
-pub(crate) fn channels_list_degrade(e: &tinyplace::Error) -> Option<Value> {
- if e.status() == Some(404) {
- Some(serde_json::json!({ "channels": [] }))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_groups_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} groups_list params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::GroupQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid groups list params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- let result = client
- .groups
- .list(query_params.as_ref())
- .await
- .map_err(map_err)?;
- // GroupListResponse doesn't implement Serialize; serialize its inner vec.
- to_value(result.groups)
- })
-}
-
-pub(crate) fn handle_tinyplace_inbox_counts(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let owner: Option<String> = params
- .get("owner")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string());
- log::debug!("{LOG_PREFIX} inbox_counts owner={owner:?}");
-
- let client = global_state().client().await?;
- let result = client
- .inbox
- .counts(owner.as_deref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_inbox_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} inbox_list params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::api::inbox::InboxQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid inbox list params: {e}"))
- })
- .transpose()?;
- let owner: Option<String> = params
- .get("owner")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string());
-
- let client = global_state().client().await?;
- match client
- .inbox
- .list(query_params.as_ref(), owner.as_deref())
- .await
- {
- Ok(result) => to_value(result),
- Err(e) => match inbox_list_degrade(&e) {
- Some(empty) => {
- log::debug!(
- "{LOG_PREFIX} inbox_list deserialization failed (likely empty inbox) -> empty: {e}"
- );
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-/// An empty inbox comes back as `{"items": null}`, which fails the SDK's
-/// non-optional `items: Vec<InboxItem>` deserialization. Treat that
-/// serialization failure as an empty inbox; propagate every other error.
-pub(crate) fn inbox_list_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({
- "items": [],
- "cursor": null,
- "unreadCount": 0,
- "totalCount": 0,
- }))
- } else {
- None
- }
-}
-
-fn opt_owner(params: &Map<String, Value>) -> Option<String> {
- params
- .get("owner")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
-}
-
-pub(crate) fn handle_tinyplace_broadcasts_subscribe(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let broadcast_id = req_str(&params, "broadcastId")?.to_string();
- log::debug!("{LOG_PREFIX} broadcasts_subscribe broadcast_id={broadcast_id}");
- let client = global_state().client().await?;
- let result = client
- .broadcasts
- .subscribe(&broadcast_id, None)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_broadcasts_unsubscribe(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let broadcast_id = req_str(&params, "broadcastId")?.to_string();
- log::debug!("{LOG_PREFIX} broadcasts_unsubscribe broadcast_id={broadcast_id}");
- let client = global_state().client().await?;
- client
- .broadcasts
- .unsubscribe(&broadcast_id, None)
- .await
- .map_err(map_err)?;
- to_value(serde_json::json!({ "ok": true }))
- })
-}
-
-pub(crate) fn handle_tinyplace_channels_join(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let channel_id = req_str(&params, "channelId")?.to_string();
- log::debug!("{LOG_PREFIX} channels_join channel_id={channel_id}");
- let client = global_state().client().await?;
- let result = client
- .channels
- .join(&channel_id, None)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_channels_leave(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let channel_id = req_str(&params, "channelId")?.to_string();
- log::debug!("{LOG_PREFIX} channels_leave channel_id={channel_id}");
- let client = global_state().client().await?;
- client
- .channels
- .leave(&channel_id, None)
- .await
- .map_err(map_err)?;
- to_value(serde_json::json!({ "ok": true }))
- })
-}
-
-pub(crate) fn handle_tinyplace_groups_join(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let group_id = req_str(&params, "groupId")?.to_string();
- log::debug!("{LOG_PREFIX} groups_join group_id={group_id}");
- let client = global_state().client().await?;
- let result = client.groups.join(&group_id, None).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_groups_leave(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let group_id = req_str(&params, "groupId")?.to_string();
- log::debug!("{LOG_PREFIX} groups_leave group_id={group_id}");
- let client = global_state().client().await?;
- // Leaving = removing ourselves; the SDK exposes no `groups.leave`.
- let me = client
- .http()
- .signer()
- .map(|s| s.agent_id())
- .ok_or_else(|| "tinyplace signer unavailable; cannot leave group".to_string())?;
-
- // Pre-check membership before calling remove_member so we return a
- // clear error instead of leaking a raw HTTP 400 from the backend when
- // the user is not a member.
- match client.groups.members(&group_id).await {
- Ok(resp) => {
- if !resp.members.iter().any(|m| m.agent_id == me) {
- log::warn!(
- "{LOG_PREFIX} groups_leave: agent {me} is not a member of {group_id}"
- );
- return Err(format!(
- "you are not a member of group {group_id}; cannot leave"
- ));
- }
- }
- Err(e) => {
- // If the membership list itself is unavailable (network, 404, etc.)
- // we log a warning and fall through — the backend will reject if
- // the agent truly is not a member.
- log::warn!(
- "{LOG_PREFIX} groups_leave: membership check failed for {group_id}: {e}; \
- proceeding with remove_member"
- );
- }
- }
-
- client
- .groups
- .remove_member(&group_id, &me, None)
- .await
- .map_err(map_err)?;
- to_value(serde_json::json!({ "ok": true }))
- })
-}
-
-pub(crate) fn handle_tinyplace_inbox_archive(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let item_id = req_str(&params, "itemId")?.to_string();
- let owner = opt_owner(&params);
- log::debug!("{LOG_PREFIX} inbox_archive item_id={item_id} owner={owner:?}");
- let client = global_state().client().await?;
- let result = client
- .inbox
- .archive(&item_id, owner.as_deref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_inbox_mark_all_read(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let clear_params: Option<tinyplace::api::inbox::InboxClearParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid inbox mark_all_read params: {e}"))
- })
- .transpose()?;
- let owner = opt_owner(&params);
- log::debug!("{LOG_PREFIX} inbox_mark_all_read owner={owner:?}");
- let client = global_state().client().await?;
- let result = client
- .inbox
- .mark_all_read(clear_params.as_ref(), owner.as_deref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_inbox_mark_read(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let item_id = req_str(&params, "itemId")?.to_string();
- let owner = opt_owner(&params);
- log::debug!("{LOG_PREFIX} inbox_mark_read item_id={item_id} owner={owner:?}");
- let client = global_state().client().await?;
- let result = client
- .inbox
- .mark_read(&item_id, owner.as_deref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_inbox_remove(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let item_id = req_str(&params, "itemId")?.to_string();
- let owner = opt_owner(&params);
- log::debug!("{LOG_PREFIX} inbox_remove item_id={item_id} owner={owner:?}");
- let client = global_state().client().await?;
- client
- .inbox
- .remove(&item_id, owner.as_deref())
- .await
- .map_err(map_err)?;
- to_value(serde_json::json!({ "ok": true }))
- })
-}
-
-pub(crate) fn handle_tinyplace_inbox_unarchive(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let item_id = req_str(&params, "itemId")?.to_string();
- let owner = opt_owner(&params);
- log::debug!("{LOG_PREFIX} inbox_unarchive item_id={item_id} owner={owner:?}");
- let client = global_state().client().await?;
- let result = client
- .inbox
- .unarchive(&item_id, owner.as_deref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Follows handlers ─────────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_follows_follow(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_str(&params, "agentId")?.to_string();
- log::debug!("{LOG_PREFIX} follows_follow agent_id={agent_id}");
- let client = global_state().client().await?;
- let result = client.follows.follow(&agent_id).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_follows_unfollow(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_str(&params, "agentId")?.to_string();
- log::debug!("{LOG_PREFIX} follows_unfollow agent_id={agent_id}");
- let client = global_state().client().await?;
- client.follows.unfollow(&agent_id).await.map_err(map_err)?;
- to_value(serde_json::json!({ "ok": true }))
- })
-}
-
-pub(crate) fn handle_tinyplace_follows_followers(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_str(&params, "agentId")?.to_string();
- log::debug!("{LOG_PREFIX} follows_followers agent_id={agent_id}");
- let list_params: Option<tinyplace::types::FollowListParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid follows followers params: {e}"))
- })
- .transpose()?;
- let client = global_state().client().await?;
- let result = client
- .follows
- .followers(&agent_id, list_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_follows_following(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_str(&params, "agentId")?.to_string();
- log::debug!("{LOG_PREFIX} follows_following agent_id={agent_id}");
- let list_params: Option<tinyplace::types::FollowListParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid follows following params: {e}"))
- })
- .transpose()?;
- let client = global_state().client().await?;
- let result = client
- .follows
- .following(&agent_id, list_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_follows_stats(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_str(&params, "agentId")?.to_string();
- log::debug!("{LOG_PREFIX} follows_stats agent_id={agent_id}");
- let client = global_state().client().await?;
- let result = client.follows.stats(&agent_id).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_follows_feed(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} follows_feed params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let feed_params: Option<tinyplace::types::FeedListParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid follows feed params: {e}"))
- })
- .transpose()?;
- let client = global_state().client().await?;
- let result = client
- .follows
- .feed(feed_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Feedback handlers ─────────────────────────────────────────────────────────
-// TODO(staging): verify /feedback is deployed on staging-api.tiny.place before
-// integration testing.
-
-pub(crate) fn handle_tinyplace_feedback_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} feedback_list params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let list_params: Option<tinyplace::types::FeedbackListParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid feedback list params: {e}"))
- })
- .transpose()?;
- let client = global_state().client().await?;
- let result = client
- .feedback
- .list(list_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_feedback_get(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let feedback_id = req_str(&params, "feedbackId")?.to_string();
- log::debug!("{LOG_PREFIX} feedback_get feedback_id={feedback_id}");
- let client = global_state().client().await?;
- let result = client.feedback.get(&feedback_id).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_feedback_create(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let title = req_str(&params, "title")?.trim().to_string();
- if title.is_empty() {
- return Err("missing required param 'title'".to_string());
- }
- let description = req_str(&params, "description")?.trim().to_string();
- if description.is_empty() {
- return Err("missing required param 'description'".to_string());
- }
- let category = get_opt_str(&params, "category")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- log::debug!("{LOG_PREFIX} feedback_create title={title} category={category:?}");
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
-
- let feedback = tinyplace::types::FeedbackCreate {
- feedback_id: None,
- author: signer.agent_id(),
- title,
- description,
- category,
- };
-
- let result = client.feedback.create(feedback).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_feedback_vote(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let feedback_id = req_str(&params, "feedbackId")?.to_string();
- let vote = req_str(&params, "vote")?.to_string();
- if vote != "up" && vote != "down" {
- return Err(format!(
- "invalid vote value '{vote}': must be 'up' or 'down'"
- ));
- }
- log::debug!("{LOG_PREFIX} feedback_vote feedback_id={feedback_id} vote={vote}");
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
-
- let vote_req = tinyplace::types::FeedbackVoteRequest {
- voter: signer.agent_id(),
- vote,
- };
-
- let result = client
- .feedback
- .vote(&feedback_id, vote_req)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Jobs write handlers ───────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_jobs_create(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let title = req_str(&params, "title")?.trim().to_string();
- if title.is_empty() {
- return Err("missing required param 'title'".to_string());
- }
- let budget_amount = req_str(&params, "budgetAmount")?.trim().to_string();
- if budget_amount.is_empty() {
- return Err("missing required param 'budgetAmount'".to_string());
- }
- let budget_asset = req_str(&params, "budgetAsset")?.trim().to_string();
- if budget_asset.is_empty() {
- return Err("missing required param 'budgetAsset'".to_string());
- }
- let description = get_opt_str(&params, "description")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- let category = get_opt_str(&params, "category")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- let budget_chain = get_opt_str(&params, "budgetChain")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- let proposal_deadline = get_opt_str(&params, "proposalDeadline")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- // Skills: optional JSON array of strings
- let skills: Option<Vec<String>> = params
- .get("skills")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid 'skills' param: {e}"))
- })
- .transpose()?;
-
- log::debug!("{LOG_PREFIX} jobs_create title={title} category={category:?}");
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- let request = tinyplace::types::JobCreateRequest {
- client: actor,
- title,
- description,
- category,
- skills,
- budget: tinyplace::types::JobBudget {
- amount: budget_amount,
- asset: budget_asset,
- chain: budget_chain,
- },
- on_chain: None,
- proposal_deadline,
- };
-
- let result = client.jobs.create(&request).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_jobs_cancel(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let job_id = req_str(&params, "jobId")?.to_string();
- log::debug!("{LOG_PREFIX} jobs_cancel job_id={job_id}");
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- let result = client.jobs.cancel(&job_id, &actor).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_jobs_apply(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let job_id = req_str(&params, "jobId")?.to_string();
- let cover_letter = get_opt_str(&params, "coverLetter")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- let bid_amount = get_opt_str(&params, "bidAmount")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- let estimated_delivery = get_opt_str(&params, "estimatedDelivery")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- let past_work: Option<Vec<String>> = params
- .get("pastWork")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid 'pastWork' param: {e}"))
- })
- .transpose()?;
-
- log::debug!("{LOG_PREFIX} jobs_apply job_id={job_id}");
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- let request = tinyplace::types::ProposalCreateRequest {
- candidate: actor,
- cover_letter,
- bid_amount,
- estimated_delivery,
- past_work,
- };
-
- let result = client
- .jobs
- .apply(&job_id, &request)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_jobs_list_proposals(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- use tinyplace::api::jobs::ProposalQueryParams;
-
- let job_id = req_str(&params, "jobId")?.to_string();
- let status = get_opt_str(&params, "status")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- let limit = params.get("limit").and_then(|v| v.as_i64());
- let offset = params.get("offset").and_then(|v| v.as_i64());
-
- log::debug!("{LOG_PREFIX} jobs_list_proposals job_id={job_id} status={status:?}");
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- let query_params = ProposalQueryParams {
- status,
- limit,
- offset,
- };
-
- let result = client
- .jobs
- .list_proposals(&job_id, &actor, Some(&query_params))
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_jobs_get_proposal(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let job_id = req_str(&params, "jobId")?.to_string();
- let proposal_id = req_str(&params, "proposalId")?.to_string();
- log::debug!("{LOG_PREFIX} jobs_get_proposal job_id={job_id} proposal_id={proposal_id}");
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- let result = client
- .jobs
- .get_proposal(&job_id, &proposal_id, &actor)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_jobs_shortlist_proposal(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let job_id = req_str(&params, "jobId")?.to_string();
- let proposal_id = req_str(&params, "proposalId")?.to_string();
- log::debug!(
- "{LOG_PREFIX} jobs_shortlist_proposal job_id={job_id} proposal_id={proposal_id}"
- );
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- let result = client
- .jobs
- .shortlist_proposal(&job_id, &proposal_id, &actor)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_jobs_withdraw_proposal(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let job_id = req_str(&params, "jobId")?.to_string();
- let proposal_id = req_str(&params, "proposalId")?.to_string();
- log::debug!(
- "{LOG_PREFIX} jobs_withdraw_proposal job_id={job_id} proposal_id={proposal_id}"
- );
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- let result = client
- .jobs
- .withdraw_proposal(&job_id, &proposal_id, &actor)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_jobs_select(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let job_id = req_str(&params, "jobId")?.to_string();
- let proposal_id = req_str(&params, "proposalId")?.to_string();
- let network = get_opt_str(&params, "network")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- log::debug!(
- "{LOG_PREFIX} jobs_select job_id={job_id} proposal_id={proposal_id} network={network:?}"
- );
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- let result = client
- .jobs
- .select(&job_id, &actor, &proposal_id, network.as_deref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_jobs_open_dispute(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let job_id = req_str(&params, "jobId")?.to_string();
- let reason = req_str(&params, "reason")?.trim().to_string();
- if reason.is_empty() {
- return Err("missing required param 'reason'".to_string());
- }
- log::debug!("{LOG_PREFIX} jobs_open_dispute job_id={job_id}");
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- let result = client
- .jobs
- .open_dispute(&job_id, &actor, &reason)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_jobs_adjudicate_dispute(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let job_id = req_str(&params, "jobId")?.to_string();
- log::debug!("{LOG_PREFIX} jobs_adjudicate_dispute job_id={job_id}");
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- let result = client
- .jobs
- .adjudicate_dispute(&job_id, &actor)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Groups invite/role management ────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_groups_set_member_role(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let group_id = req_str(&params, "groupId")?.to_string();
- let agent_id = req_str(&params, "agentId")?.to_string();
- let role = req_str(&params, "role")?.to_string();
- log::debug!(
- "{LOG_PREFIX} groups_set_member_role group_id={group_id} agent_id={agent_id} role={role}"
- );
- let client = global_state().client().await?;
- let result = client
- .groups
- .set_member_role(&group_id, &agent_id, &role, None)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_groups_create_invite(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let group_id = req_str(&params, "groupId")?.to_string();
- log::debug!("{LOG_PREFIX} groups_create_invite group_id={group_id}");
-
- let client = global_state().client().await?;
- let actor = client
- .http()
- .signer()
- .map(|s| s.agent_id())
- .ok_or_else(|| "tinyplace signer unavailable; cannot create invite".to_string())?;
-
- let request: Option<tinyplace::types::GroupInviteCreateRequest> = params
- .get("request")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid groups create_invite request: {e}"))
- })
- .transpose()?;
-
- let result = client
- .groups
- .create_invite(&group_id, &actor, request)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_groups_list_invites(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let group_id = req_str(&params, "groupId")?.to_string();
- log::debug!("{LOG_PREFIX} groups_list_invites group_id={group_id}");
-
- let client = global_state().client().await?;
- let actor = client
- .http()
- .signer()
- .map(|s| s.agent_id())
- .ok_or_else(|| "tinyplace signer unavailable; cannot list invites".to_string())?;
-
- let result = client
- .groups
- .list_invites(&group_id, &actor)
- .await
- .map_err(map_err)?;
- // GroupInvitesResponse doesn't derive Serialize; serialize the inner vec.
- to_value(result.invites)
- })
-}
-
-pub(crate) fn handle_tinyplace_groups_preview_invite(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let group_id = req_str(&params, "groupId")?.to_string();
- let token = req_str(&params, "token")?.to_string();
- log::debug!("{LOG_PREFIX} groups_preview_invite group_id={group_id} token=<redacted>");
- let client = global_state().client().await?;
- let result = client
- .groups
- .preview_invite(&group_id, &token)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_groups_revoke_invite(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let group_id = req_str(&params, "groupId")?.to_string();
- let token = req_str(&params, "token")?.to_string();
- log::debug!("{LOG_PREFIX} groups_revoke_invite group_id={group_id} token=<redacted>");
-
- let client = global_state().client().await?;
- let actor = client
- .http()
- .signer()
- .map(|s| s.agent_id())
- .ok_or_else(|| "tinyplace signer unavailable; cannot revoke invite".to_string())?;
-
- client
- .groups
- .revoke_invite(&group_id, &token, &actor)
- .await
- .map_err(map_err)?;
- to_value(serde_json::json!({ "ok": true }))
- })
-}
-
-pub(crate) fn handle_tinyplace_groups_redeem_invite(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let group_id = req_str(&params, "groupId")?.to_string();
- let token = req_str(&params, "token")?.to_string();
- log::debug!("{LOG_PREFIX} groups_redeem_invite group_id={group_id} token=<redacted>");
-
- let client = global_state().client().await?;
- let me = client
- .http()
- .signer()
- .map(|s| s.agent_id())
- .ok_or_else(|| "tinyplace signer unavailable; cannot redeem invite".to_string())?;
-
- let result = client
- .groups
- .redeem_invite(&group_id, &token, &me)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Registry export handler ───────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_registry_export(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let name = req_str(&params, "name")?.to_string();
- log::debug!("{LOG_PREFIX} registry_export name={name}");
- let client = global_state().client().await?;
- let result = client.registry.export(&name).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-/// Assign one of the wallet's purchased handles as its **primary** (active)
-/// identity. The backend clears the primary flag on the wallet's other names
-/// (one primary per wallet), so this is how a user who owns multiple identities
-/// switches which handle is shown as active across feed / profile / directory
-/// (#4198). ANTI-SPOOF: the owning wallet is proven by the request signature the
-/// SDK attaches from the unlocked signer, never from params — so a caller can
-/// only re-point their *own* wallet's primary.
-pub(crate) fn handle_tinyplace_registry_assign_primary(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let name = req_str(&params, "name")?
- .trim()
- .trim_start_matches('@')
- .to_string();
- if name.is_empty() {
- return Err("missing required param 'name'".to_string());
- }
- log::debug!("{LOG_PREFIX} registry_assign_primary name={name}");
- let client = global_state().client().await?;
- let identity = client
- .registry
- .assign_primary(&name)
- .await
- .map_err(map_err)?;
- to_value(serde_json::json!({ "identity": identity }))
- })
-}
-
-fn transfer_allowed_by_primary_state(primary: Option<bool>) -> bool {
- primary == Some(false)
-}
-
-/// Transfer one of the wallet's handles to another tiny.place identity
-/// (gift / account move, #4929). DESTRUCTIVE and irreversible for the sender:
-/// on success the recipient becomes the sole owner of `name`.
-///
-/// The recipient is given as a `recipient` handle (with or without a leading
-/// @) — we resolve it to the recipient's `cryptoId` + `publicKey` via
-/// `registry.get`, so the caller never has to know raw key material and an
-/// unresolvable recipient fails **closed** before anything is signed. The
-/// SDK attaches the owning wallet's signature over the transfer payload, so
-/// the backend only lets a caller transfer a handle their *own* wallet owns.
-///
-/// Ordering (read-only preflight → sign+POST → real read-back):
-/// 1. Resolve the recipient and validate it is a live registration whose
-/// `available`/`status` don't flag a stale/expired record (M2, #4998).
-/// 2. Read the sender's *own* current ownership. If it already reads back as
-/// the recipient — a retry after a lost-but-applied POST — return the
-/// existing state without re-signing (idempotency, M1, #4998), and reject a
-/// self-transfer / unregistered / primary handle before signing.
-/// 3. Sign + POST the transfer.
-/// 4. **Read-back via `registry.get`**, NOT the POST response body. The POST has
-/// already returned 2xx by this point, so a mismatch means "submitted but
-/// unconfirmed", never "did not happen" — we never claim the handle wasn't
-/// reassigned, because the handler cannot know that (B1, #4998).
-pub(crate) fn handle_tinyplace_registry_transfer(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let name = req_str(&params, "name")?
- .trim()
- .trim_start_matches('@')
- .to_string();
- if name.is_empty() {
- return Err("missing required param 'name'".to_string());
- }
- let recipient = req_str(&params, "recipient")?
- .trim()
- .trim_start_matches('@')
- .to_string();
- if recipient.is_empty() {
- return Err("missing required param 'recipient'".to_string());
- }
- // Cheap reject before any network/signing: a self-transfer burns a
- // signature as a no-op and would read back as trivially "confirmed".
- if name.eq_ignore_ascii_case(&recipient) {
- return Err("cannot transfer a handle to itself".to_string());
- }
- // Never log the handle or recipient — both are user-identifying.
- log::debug!("{LOG_PREFIX} registry_transfer requested");
-
- let client = global_state().client().await?;
-
- // (1) Resolve the recipient handle to a verified cryptoId + publicKey.
- // An unknown/expired/available recipient fails closed here, before we
- // sign. We query with the `@`-prefixed form, matching the proven
- // availability path (`useHandleAvailability` → registry.get(`@handle`)).
- let availability = client
- .registry
- .get(&format!("@{recipient}"))
- .await
- .map_err(map_err)?;
- let (recipient_crypto_id, recipient_public_key) =
- validate_recipient_availability(&availability)?;
- log::debug!("{LOG_PREFIX} registry_transfer recipient resolved");
-
- // (2) Read the sender's own current ownership BEFORE signing. This
- // hoisted, side-effect-free read lets us (a) short-circuit a retry whose
- // transfer already landed, and (b) reject a not-registered / primary
- // handle with the right diagnosis — separately from the nonexistent case.
- let own = client
- .registry
- .get(&format!("@{name}"))
- .await
- .map_err(map_err)?;
- match preflight_own_handle(&own, &recipient_crypto_id) {
- OwnHandlePreflight::AlreadyTransferred => {
- // Idempotency (M1): the handle already reads back as the
- // recipient — a prior POST landed but its response was lost. Do
- // NOT re-sign; report the existing state.
- log::debug!("{LOG_PREFIX} registry_transfer already applied; idempotent no-op");
- return to_value(serde_json::json!({
- "identity": own.identity,
- "alreadyTransferred": true,
- }));
- }
- OwnHandlePreflight::Reject(message) => {
- log::warn!("{LOG_PREFIX} registry_transfer rejected in preflight");
- return Err(message);
- }
- OwnHandlePreflight::Proceed => {}
- }
-
- // (3) Sign + POST the transfer.
- let request = tinyplace::types::IdentityTransferRequest {
- crypto_id: recipient_crypto_id.clone(),
- public_key: recipient_public_key,
- ..Default::default()
- };
- client
- .registry
- .transfer(&name, request)
- .await
- .map_err(map_err)?;
-
- // (4) Real read-back: re-query the registry rather than trusting the POST
- // response body (`Identity::crypto_id` is `#[serde(default)]`, so an
- // enveloped/renamed/partial body deserializes to "" and would falsely
- // fail a transfer that DID land — B1). The transfer is already submitted,
- // so an unconfirmed read-back is "submitted but unconfirmed", NOT "did
- // not happen": we must never tell the user they still own it.
- let readback_identity = client
- .registry
- .get(&format!("@{name}"))
- .await
- .ok()
- .and_then(|r| r.identity);
- let confirmed_owner = readback_identity
- .as_ref()
- .map(|i| i.crypto_id.trim().to_string())
- .unwrap_or_default();
- match classify_transfer_readback(&confirmed_owner, &recipient_crypto_id) {
- TransferReadback::Confirmed => {
- log::debug!("{LOG_PREFIX} registry_transfer confirmed by read-back");
- // Return the identity from the SAME read-back we confirmed against
- // (no redundant second GET — the confirmed owner is already here).
- to_value(serde_json::json!({ "identity": readback_identity, "confirmed": true }))
- }
- TransferReadback::Unconfirmed => {
- log::warn!("{LOG_PREFIX} registry_transfer submitted but unconfirmed by read-back");
- Err(
- "handle transfer was submitted but could not be confirmed. Do not retry \
- until you have checked the handle's current owner."
- .to_string(),
- )
- }
- }
- })
-}
-
-/// Validate a recipient's availability lookup before a transfer (#4998, M2).
-///
-/// Returns the recipient's `(cryptoId, publicKey)` when it is a live
-/// registration, or an error when the record is stale/expired/incomplete — so
-/// an irreversible transfer never targets a wallet the recipient may no longer
-/// control at that `@handle`. Pure, so the policy is unit-testable without a
-/// live registry.
-fn validate_recipient_availability(
- availability: &tinyplace::types::AvailabilityResponse,
-) -> Result<(String, String), String> {
- // A registered handle reads back as NOT available. `available == true` means
- // the name is currently free (never registered, or expired-and-released),
- // so any attached `identity` is stale — refuse rather than transfer to it.
- if availability.available {
- return Err(
- "recipient handle is not currently registered; refusing to transfer".to_string(),
- );
- }
- let identity = availability
- .identity
- .as_ref()
- .ok_or("recipient handle is not registered on tiny.place")?;
- // An expired identity carries a stale owner record even before the name is
- // released back to `available` — never send an irreversible transfer to it.
- if identity.status.trim().eq_ignore_ascii_case("expired") {
- return Err("recipient handle has expired; refusing to transfer".to_string());
- }
- let crypto_id = identity.crypto_id.trim().to_string();
- let public_key = identity.public_key.trim().to_string();
- if crypto_id.is_empty() || public_key.is_empty() {
- return Err(
- "recipient identity is missing key material; cannot transfer safely".to_string(),
- );
- }
- Ok((crypto_id, public_key))
-}
-
-/// Outcome of the pre-sign check on the sender's own handle (#4998, M1/M2).
-#[derive(Debug, PartialEq, Eq)]
-enum OwnHandlePreflight {
- /// The handle already reads back as owned by the recipient — a retry after a
- /// lost-but-applied POST. Return the existing state; do NOT re-sign.
- AlreadyTransferred,
- /// Safe to proceed to signing + POST.
- Proceed,
- /// Reject before signing with this message.
- Reject(String),
-}
-
-/// Decide whether to proceed with, short-circuit, or reject a transfer based on
-/// the sender's own current ownership. Pure, so unit-testable without a client.
-fn preflight_own_handle(
- own: &tinyplace::types::AvailabilityResponse,
- recipient_crypto_id: &str,
-) -> OwnHandlePreflight {
- let Some(identity) = own.identity.as_ref() else {
- // Not registered at all — a distinct diagnosis from the primary case, so
- // a nonexistent handle doesn't get "mark it non-primary" (M2 tail).
- return OwnHandlePreflight::Reject(
- "this handle is not registered on tiny.place".to_string(),
- );
- };
- // Idempotency (M1): already owned by the recipient — a prior transfer landed.
- if identity.crypto_id.trim() == recipient_crypto_id {
- return OwnHandlePreflight::AlreadyTransferred;
- }
- // A primary (active) handle is locked from transfer server-side; mirror that
- // client-side so a direct JSON-RPC caller can't bypass the UI gate.
- if !transfer_allowed_by_primary_state(identity.primary) {
- return OwnHandlePreflight::Reject(
- "cannot transfer this handle while it is your active (primary) handle; make \
- another handle active first"
- .to_string(),
- );
- }
- OwnHandlePreflight::Proceed
-}
-
-/// Outcome of the post-transfer read-back confirmation (#4998, B1).
-#[derive(Debug, PartialEq, Eq)]
-enum TransferReadback {
- /// The registry reads back the recipient as the current owner.
- Confirmed,
- /// The read-back neither confirms nor refutes reassignment — the POST is
- /// already submitted, so this is "submitted but unconfirmed", never a claim
- /// that the transfer did not happen.
- Unconfirmed,
-}
-
-/// Classify the post-transfer read-back. Only a non-empty owner that equals the
-/// recipient confirms; anything else (empty/enveloped body, mismatch, failed
-/// read) is treated as unconfirmed. Pure, so unit-testable without a client.
-fn classify_transfer_readback(
- confirmed_owner: &str,
- recipient_crypto_id: &str,
-) -> TransferReadback {
- if !confirmed_owner.is_empty() && confirmed_owner == recipient_crypto_id {
- TransferReadback::Confirmed
- } else {
- TransferReadback::Unconfirmed
- }
-}
-
-// ── Users email verification ────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_users_start_email_verification(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let crypto_id = req_str(&params, "cryptoId")?.to_string();
- let email = req_str(&params, "email")?.trim().to_string();
- if email.is_empty() {
- return Err("missing required param 'email'".to_string());
- }
- log::debug!(
- "{LOG_PREFIX} users_start_email_verification crypto_id={crypto_id} email=<redacted>"
- );
- let client = global_state().client().await?;
- let request = tinyplace::types::UserEmailVerificationRequest {
- email,
- ..Default::default()
- };
- let result = client
- .users
- .start_email_verification(&crypto_id, request)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_users_confirm_email_verification(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let crypto_id = req_str(&params, "cryptoId")?.to_string();
- let email = req_str(&params, "email")?.trim().to_string();
- if email.is_empty() {
- return Err("missing required param 'email'".to_string());
- }
- let code = req_str(&params, "code")?.trim().to_string();
- if code.is_empty() {
- return Err("missing required param 'code'".to_string());
- }
- log::debug!(
- "{LOG_PREFIX} users_confirm_email_verification crypto_id={crypto_id} email=<redacted>"
- );
- let client = global_state().client().await?;
- let request = tinyplace::types::UserEmailVerificationConfirmRequest {
- email,
- code,
- ..Default::default()
- };
- let result = client
- .users
- .confirm_email_verification(&crypto_id, request)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Solana handlers ─────────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_solana_info(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!("{LOG_PREFIX} solana_info");
- let client = global_state().client().await?;
- let result = client.solana.info().await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_solana_call(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let method = req_str(&params, "method")?.trim().to_string();
- if method.is_empty() {
- return Err("missing required param 'method'".to_string());
- }
- let rpc_params: Option<serde_json::Value> =
- params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v.clone()) });
- let id: Option<serde_json::Value> =
- params
- .get("id")
- .and_then(|v| if v.is_null() { None } else { Some(v.clone()) });
- log::debug!("{LOG_PREFIX} solana_call method={method}");
- let client = global_state().client().await?;
- let result: serde_json::Value = client
- .solana
- .call::<serde_json::Value>(&method, rpc_params, id)
- .await
- .map_err(map_err)?;
- Ok(result)
- })
-}
-
-// ── Streams section ────────────────────────────────────────────────────────────
-
-/// Start a tinyplace WebSocket stream.
-pub(crate) fn handle_tinyplace_streams_start(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let kind_str = req_str(&params, "streamType")?.to_string();
- let kind_str_trimmed = kind_str.trim();
- if kind_str_trimmed.is_empty() {
- return Err("missing required param 'streamType'".to_string());
- }
- let kind = match kind_str_trimmed {
- "inbox" => super::streams::StreamKind::Inbox,
- "conversation" => super::streams::StreamKind::Conversation,
- "feed" => super::streams::StreamKind::Feed,
- _ => return Err(format!("unsupported streamType: {kind_str_trimmed}")),
- };
-
- // conversation and feed streams require a target id (conversation_id /
- // feed handle respectively); inbox is a singleton with no target.
- let target_id = params
- .get("streamId")
- .and_then(|v| v.as_str())
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
-
- if kind == super::streams::StreamKind::Conversation && target_id.is_none() {
- return Err("streamId is required for conversation streams".to_string());
- }
- if kind == super::streams::StreamKind::Feed && target_id.is_none() {
- return Err("streamId is required for feed streams".to_string());
- }
-
- log::debug!(
- "{LOG_PREFIX} streams_start kind={kind_str_trimmed} target_id={:?}",
- target_id
- );
-
- let client = global_state().client().await?;
- let stream_id = super::streams::global_stream_manager()
- .start_stream(kind, target_id, client)
- .await?;
-
- to_value(serde_json::json!({ "streamId": stream_id }))
- })
-}
-
-/// Stop a tinyplace WebSocket stream.
-pub(crate) fn handle_tinyplace_streams_stop(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let stream_id = req_str(&params, "streamId")?.to_string();
- let stream_id_trimmed = stream_id.trim();
- if stream_id_trimmed.is_empty() {
- return Err("missing required param 'streamId'".to_string());
- }
-
- log::debug!("{LOG_PREFIX} streams_stop stream_id={stream_id_trimmed}");
-
- super::streams::global_stream_manager()
- .stop_stream(stream_id_trimmed)
- .await?;
-
- to_value(serde_json::json!({ "ok": true }))
- })
-}
-
-/// List active tinyplace WebSocket streams.
-pub(crate) fn handle_tinyplace_streams_list(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!("{LOG_PREFIX} streams_list");
- let entries = super::streams::global_stream_manager().list_streams().await;
- to_value(serde_json::json!({ "streams": entries }))
- })
-}
-
-// ── Signal key management ─────────────────────────────────────────────────────
-//
-// The `FileSessionStore` methods are defined via the `SessionStore` async trait.
-// We bring the trait into scope so the compiler resolves them correctly.
-use std::sync::Arc;
-
-use tinyplace::signal::session::SignalSession;
-use tinyplace::signal::store::SessionStore;
-
-/// Get the `Arc<dyn Signer>` from the client or fail with a clear message.
-///
-/// SECURITY: the signer holds the Ed25519 signing key in memory. The returned
-/// Arc is the *same* instance the `TinyPlaceClient` uses — no new key material
-/// is created.
-fn require_signer(
- client: &tinyplace::TinyPlaceClient,
-) -> std::result::Result<std::sync::Arc<dyn tinyplace::Signer>, String> {
- client
- .http()
- .signer()
- .ok_or_else(|| "no signer configured — unlock wallet to manage Signal keys".to_string())
-}
-
-/// Bootstrap Signal keys: generate signed pre-key + one-time pre-keys, store
-/// locally in the encrypted `FileSessionStore`, publish to the backend, and
-/// return the resulting `KeyHealth`.
-///
-/// SECURITY: only PUBLIC keys are serialised for upload. Private key bytes
-/// remain in the encrypted `FileSessionStore` on disk.
-pub(crate) fn handle_tinyplace_signal_provision(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let pre_key_count = params
- .get("preKeyCount")
- .and_then(Value::as_u64)
- .unwrap_or(100) as usize;
- log::debug!("{LOG_PREFIX} signal_provision pre_key_count={pre_key_count}");
-
- // 1. Acquire store, client, signer.
- let store = crate::openhuman::tinyplace::signal_store::global_signal_store().await?;
- let client = global_state().client().await?;
- let signer = require_signer(client)?;
- let agent_id = signer.agent_id();
- log::debug!("{LOG_PREFIX} signal_provision agent_id={agent_id}");
-
- // 2. Identity key published to /keys = the wallet's Ed25519 public key.
- // The backend verifies the pre-key signatures against it (they are
- // signed by the wallet's Ed25519 signer) and serves it in the bundle;
- // peers convert it to X25519 for DH. SECURITY: public key only.
- let identity_key_b64 = signer.public_key_base64();
-
- // 3. Generate + store signed pre-key.
- let spk_id = format!(
- "spk_{}",
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs()
- );
- let spk = tinyplace::signal::keys::generate_signed_pre_key(signer.as_ref(), &spk_id)
- .await
- .map_err(|e| format!("generate signed pre-key: {e}"))?;
- store
- .store_signed_pre_key(spk.clone())
- .await
- .map_err(|e| format!("store signed pre-key: {e}"))?;
- log::debug!("{LOG_PREFIX} signal_provision stored signed pre-key id={spk_id}");
-
- // 4. Generate + store one-time pre-keys.
- let start_id = store
- .all_pre_keys()
- .await
- .map_err(|e| format!("list pre-keys: {e}"))?
- .len() as u64;
- let pre_keys =
- tinyplace::signal::keys::generate_pre_keys(signer.as_ref(), start_id, pre_key_count)
- .await
- .map_err(|e| format!("generate pre-keys: {e}"))?;
- for pk in &pre_keys {
- store
- .store_pre_key(pk.clone())
- .await
- .map_err(|e| format!("store pre-key: {e}"))?;
- }
- log::debug!(
- "{LOG_PREFIX} signal_provision stored {count} one-time pre-keys (start_id={start_id})",
- count = pre_keys.len()
- );
-
- // 5. Serialise for upload — ONLY public keys leave this process.
- let spk_wire = tinyplace::signal::keys::serialize_pre_key(&spk);
- let otpk_wires: Vec<tinyplace::types::SignedKey> = pre_keys
- .iter()
- .map(tinyplace::signal::keys::serialize_pre_key)
- .collect();
-
- // 6. Upload signed pre-key.
- client
- .keys
- .rotate_signed_pre_key(
- &agent_id,
- &tinyplace::types::SignedPreKeyRequest {
- identity_key: Some(identity_key_b64.clone()),
- signed_pre_key: spk_wire,
- },
- )
- .await
- .map_err(map_err)?;
- log::debug!("{LOG_PREFIX} signal_provision uploaded signed pre-key");
-
- // 7. Upload one-time pre-keys.
- client
- .keys
- .upload_pre_keys(
- &agent_id,
- &tinyplace::types::PreKeysRequest {
- identity_key: Some(identity_key_b64),
- pre_keys: otpk_wires,
- },
- )
- .await
- .map_err(map_err)?;
- log::debug!(
- "{LOG_PREFIX} signal_provision uploaded {count} one-time pre-keys",
- count = pre_keys.len()
- );
-
- // 8. Return key health.
- let health = client.keys.health(&agent_id).await.map_err(map_err)?;
- log::info!(
- "{LOG_PREFIX} signal_provision complete agent_id={agent_id} \
- otpk_count={} low={}",
- health.one_time_pre_key_count,
- health.low_one_time_pre_keys
- );
- to_value(health)
- })
-}
-
-/// Generate and upload additional one-time pre-keys (replenishment). Does NOT
-/// generate a new signed pre-key.
-pub(crate) fn handle_tinyplace_signal_upload_pre_keys(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let count = params.get("count").and_then(Value::as_u64).unwrap_or(100) as usize;
- log::debug!("{LOG_PREFIX} signal_upload_pre_keys count={count}");
-
- let store = crate::openhuman::tinyplace::signal_store::global_signal_store().await?;
- let client = global_state().client().await?;
- let signer = require_signer(client)?;
- let agent_id = signer.agent_id();
-
- // Publish the wallet's Ed25519 public key as the identity key (the
- // backend verifies pre-key signatures against it and serves it in the
- // bundle; peers convert it to X25519 for DH). SECURITY: public key only.
- let identity_key_b64 = signer.public_key_base64();
-
- let start_id = store
- .all_pre_keys()
- .await
- .map_err(|e| format!("list pre-keys: {e}"))?
- .len() as u64;
- let pre_keys = tinyplace::signal::keys::generate_pre_keys(signer.as_ref(), start_id, count)
- .await
- .map_err(|e| format!("generate pre-keys: {e}"))?;
-
- for pk in &pre_keys {
- store
- .store_pre_key(pk.clone())
- .await
- .map_err(|e| format!("store pre-key: {e}"))?;
- }
-
- let wires: Vec<tinyplace::types::SignedKey> = pre_keys
- .iter()
- .map(tinyplace::signal::keys::serialize_pre_key)
- .collect();
-
- client
- .keys
- .upload_pre_keys(
- &agent_id,
- &tinyplace::types::PreKeysRequest {
- identity_key: Some(identity_key_b64),
- pre_keys: wires,
- },
- )
- .await
- .map_err(map_err)?;
-
- let health = client.keys.health(&agent_id).await.map_err(map_err)?;
- log::info!(
- "{LOG_PREFIX} signal_upload_pre_keys complete count={count} \
- otpk_count={} low={}",
- health.one_time_pre_key_count,
- health.low_one_time_pre_keys
- );
- to_value(health)
- })
-}
-
-/// Generate a new signed pre-key, store locally, and upload. Existing one-time
-/// pre-keys are unaffected.
-pub(crate) fn handle_tinyplace_signal_rotate_signed_pre_key(
- _params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- log::debug!("{LOG_PREFIX} signal_rotate_signed_pre_key");
-
- let store = crate::openhuman::tinyplace::signal_store::global_signal_store().await?;
- let client = global_state().client().await?;
- let signer = require_signer(client)?;
- let agent_id = signer.agent_id();
-
- // Publish the wallet's Ed25519 public key as the identity key (the
- // backend verifies pre-key signatures against it and serves it in the
- // bundle; peers convert it to X25519 for DH). SECURITY: public key only.
- let identity_key_b64 = signer.public_key_base64();
-
- let key_id = format!(
- "spk_{}",
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs()
- );
- let spk = tinyplace::signal::keys::generate_signed_pre_key(signer.as_ref(), &key_id)
- .await
- .map_err(|e| format!("generate signed pre-key: {e}"))?;
-
- store
- .store_signed_pre_key(spk.clone())
- .await
- .map_err(|e| format!("store signed pre-key: {e}"))?;
-
- client
- .keys
- .rotate_signed_pre_key(
- &agent_id,
- &tinyplace::types::SignedPreKeyRequest {
- identity_key: Some(identity_key_b64),
- signed_pre_key: tinyplace::signal::keys::serialize_pre_key(&spk),
- },
- )
- .await
- .map_err(map_err)?;
-
- log::info!("{LOG_PREFIX} signal_rotate_signed_pre_key complete key_id={key_id}");
- to_value(serde_json::json!({ "ok": true, "keyId": key_id }))
- })
-}
-
-/// Fetch a peer's published Signal pre-key bundle (public endpoint, no auth).
-/// The `get_bundle` endpoint does not require a signer or the signal store.
-/// Accepts @handles and bare handle names in addition to raw crypto_ids; the
-/// identifier is resolved to a canonical crypto_id via directory.resolve before
-/// the bundle lookup.
-pub(crate) fn handle_tinyplace_signal_get_bundle(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let raw_agent_id = req_str(&params, "agentId")?.to_string();
- log::debug!("{LOG_PREFIX} signal_get_bundle raw_agent_id='{raw_agent_id}'");
- let client = global_state().client().await?;
-
- // Resolve the identifier (handle or crypto_id) before the bundle lookup.
- let agent_id = resolve_recipient_to_agent_id(client, &raw_agent_id).await?;
- log::debug!("{LOG_PREFIX} signal_get_bundle resolved agent_id={agent_id}");
-
- let result = match client.keys.get_bundle(&agent_id).await {
- Ok(b) => b,
- Err(e) if e.status() == Some(404) => {
- return Err(format!(
- "Recipient has not set up encrypted messaging yet. \
- They need to provision Signal keys before receiving DMs. \
- (agent_id: {agent_id})"
- ));
- }
- Err(e) => return Err(map_err(e)),
- };
- to_value(result)
- })
-}
-
-/// Whether a failed relay read in [`handle_tinyplace_signal_key_status`] means
-/// "this agent has not published anything yet" rather than "the relay is unwell".
-///
-/// A 404 from `GET /keys/<id>/health` or `GET /directory/agents/<id>` is the
-/// **expected** answer for an agent whose Signal keys are not yet published —
-/// precisely the precondition [`ensure_signal_keys_published`] exists to
-/// remove, and which `handle_tinyplace_signal_register_encryption_key` repairs
-/// by building the card when the directory 404s. So a 404 here is the state the
-/// very next step fixes, not a fault.
-///
-/// This is the same classification the rest of this file already makes at six
-/// other sites (`Err(e) if e.status() == Some(404)`); the two probe arms below
-/// were the only ones that lacked it, which is why they logged at `warn` on the
-/// orchestration supervisor's 15-second timer forever (#5627).
-///
-/// Named rather than inlined so the rule is unit-testable without a relay —
-/// deliberately narrow: **only** 404. A 500 from a broken relay must stay
-/// warn-worthy, or a genuine outage becomes as quiet as a fresh install.
-pub(super) fn is_not_published_yet(e: &tinyplace::Error) -> bool {
- e.status() == Some(404)
-}
-
-/// Whether a relay 404 is the **benign first-run** state rather than an
-/// actionable inconsistency.
-///
-/// A 404 alone is not enough to tell the two apart, which is what the first
-/// revision of this fix got wrong (#5809 review). `signal_provision` writes the
-/// local store *before* its network calls, so:
-///
-/// - **nothing provisioned locally** → nothing was ever uploaded; the 404 is
-/// the ordinary first-run answer and belongs at `debug`;
-/// - **local keys present** → the upload never landed, or the backend lost the
-/// record. The agent believes itself ready while peers 404 on its bundle, and
-/// `ensure_signal_keys_published` derives readiness from the local store, so
-/// it stops probing and nothing else will report it. That must stay a `warn`.
-///
-/// This is the narrower of the two remedies the review offered — demote only
-/// when the remaining state confirms a genuinely unpublished identity — rather
-/// than folding remote health into the readiness decision, which would change
-/// `ensure_signal_keys_published`'s retry semantics.
-pub(super) fn is_first_run_gap(e: &tinyplace::Error, has_local_keys: bool) -> bool {
- is_not_published_yet(e) && !has_local_keys
-}
-
-/// Local + remote key status for the current user. Remote health degrades
-/// gracefully if the backend is unreachable.
-pub(crate) fn handle_tinyplace_signal_key_status(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!("{LOG_PREFIX} signal_key_status");
-
- let store = crate::openhuman::tinyplace::signal_store::global_signal_store().await?;
- let client = global_state().client().await?;
- let signer = require_signer(client)?;
- let agent_id = signer.agent_id();
-
- let local_pre_key_count = store
- .all_pre_keys()
- .await
- .map_err(|e| format!("list pre-keys: {e}"))?
- .len();
- let has_active_spk = store.active_signed_pre_key().await.is_ok();
-
- // Has this identity ever been through provisioning locally?
- //
- // This is what separates the two states a relay 404 can mean, and the
- // reason the demotion below is narrower than "any 404" (#5809 review):
- //
- // - **Nothing provisioned locally** → nothing was ever uploaded, so a
- // 404 is the ordinary first-run answer. Quiet.
- // - **Local keys exist** → `signal_provision` writes the local store
- // *before* its network calls, so local-without-remote means the
- // upload never landed, or the backend lost the record. The agent
- // looks ready to itself while peers 404 on its bundle, and
- // `ensure_signal_keys_published` will stop probing. That is an
- // actionable inconsistency and has to stay a warning.
- let has_local_keys = has_active_spk || local_pre_key_count > 0;
-
- // Best-effort remote health — degrade gracefully.
- let remote = match client.keys.health(&agent_id).await {
- Ok(h) => {
- log::debug!(
- "{LOG_PREFIX} signal_key_status remote otpk_count={} low={}",
- h.one_time_pre_key_count,
- h.low_one_time_pre_keys
- );
- Some(h)
- }
- Err(e) if is_first_run_gap(&e, has_local_keys) => {
- // Expected on a fresh identity: nothing provisioned locally, so
- // nothing was ever uploaded and the relay has no health record.
- // `remote: null` is the correct answer and the supervisor's next
- // cycle publishes.
- log::debug!(
- "{LOG_PREFIX} signal_key_status: no keys provisioned yet for agent {} (first run)",
- redact(&agent_id)
- );
- None
- }
- Err(e) if is_not_published_yet(&e) => {
- // Local keys exist but the relay has no health record for them:
- // provisioning wrote the local store and the upload did not
- // land. Peers will 404 on this agent's bundle while it believes
- // itself ready, so this stays a warning.
- log::warn!(
- "{LOG_PREFIX} signal_key_status: {local_pre_key_count} local pre-key(s) but the \
- relay has no key record for agent {} — provisioning did not reach the relay; \
- peers cannot fetch this agent's bundle",
- redact(&agent_id)
- );
- None
- }
- Err(e) => {
- log::warn!("{LOG_PREFIX} signal_key_status remote health fetch failed: {e}");
- None
- }
- };
-
- let remote_json = remote.and_then(|h| serde_json::to_value(h).ok());
-
- // Best-effort directory check — is encryptionPublicKey published
- // AND does it match the current identity key? A stale key (from a
- // previous wallet) should show as NOT published so the user
- // re-registers.
- // Bounded: once a card exists, fetching it hits the relay; a degraded
- // relay must degrade this to "not published" (like the Err arm), never
- // hang the caller (self_identity → the orchestration identity card).
- let card_fetch = tokio::time::timeout(
- std::time::Duration::from_secs(5),
- client.directory.get_agent(&agent_id),
- )
- .await;
- let encryption_key_published = match card_fetch {
- Ok(Ok(card)) => {
- let published_key = card
- .metadata
- .as_ref()
- .and_then(|m| m.get("encryptionPublicKey"));
- // The card advertises the Ed25519 identity key (the addressable
- // messaging key where the bundle + mailbox live), not the X25519
- // DH key — see `signal_register_encryption_key`. Compare against
- // that so readiness reflects what peers actually resolve.
- let current_key_b64 = signer.public_key_base64();
- let matches = published_key
- .map(|pk| pk == &current_key_b64)
- .unwrap_or(false);
- if published_key.is_some() && !matches {
- log::warn!(
- "{LOG_PREFIX} signal_key_status published encryption key does NOT \
- match current identity — re-register to update"
- );
- }
- log::debug!("{LOG_PREFIX} signal_key_status encryption_key_published={matches}");
- matches
- }
- Ok(Err(e)) if is_first_run_gap(&e, has_local_keys) => {
- // Expected on a fresh identity: nothing provisioned locally, so
- // registration has not run and no card exists yet.
- // `signal_register_encryption_key` builds one on this same 404,
- // so this is the state the next step repairs, not a failure.
- log::debug!(
- "{LOG_PREFIX} signal_key_status: no directory card yet for agent {} (first run)",
- redact(&agent_id)
- );
- false
- }
- Ok(Err(e)) if is_not_published_yet(&e) => {
- // Provisioning has run locally but the card is absent —
- // registration failed after the keys were written, or the
- // backend lost the card. Not a first-run state.
- log::warn!(
- "{LOG_PREFIX} signal_key_status: keys provisioned locally but no directory card \
- for agent {} — registration did not complete; this agent is not discoverable",
- redact(&agent_id)
- );
- false
- }
- Ok(Err(e)) => {
- log::warn!("{LOG_PREFIX} signal_key_status directory card fetch failed: {e}");
- false
- }
- Err(_) => {
- log::warn!(
- "{LOG_PREFIX} signal_key_status directory card fetch timed out (relay slow)"
- );
- false
- }
- };
-
- to_value(serde_json::json!({
- "agentId": agent_id,
- "localPreKeyCount": local_pre_key_count,
- "hasActiveSignedPreKey": has_active_spk,
- "remote": remote_json,
- "encryptionKeyPublished": encryption_key_published,
- }))
- })
-}
-
-/// Idempotently make this agent **discoverable** so peers can encrypt replies to
-/// it — the precondition for the orchestration receive loop. Mirrors the two
-/// manual UI actions (Messaging → "Set up encryption keys" + "Make
-/// discoverable") but runs automatically: provision pre-keys if missing, then
-/// publish the encryption (identity) key to the directory card if not already
-/// advertised.
-///
-/// Returns `Ok(true)` once the agent is confirmed discoverable
-/// (`encryptionKeyPublished`), `Ok(false)` if a publish step was attempted but
-/// the status could not yet be confirmed, and `Err` when prerequisites are
-/// missing (e.g. wallet locked → no signer). Callers retry on `Ok(false)`/`Err`.
-///
-/// Cheap on the steady state: when keys are already provisioned and published it
-/// performs only the status probe and returns without mutating anything.
-pub async fn ensure_signal_keys_published() -> Result<bool, String> {
- // 1. Probe current readiness. This requires a signer (unlocked wallet); it
- // surfaces as an Err the caller retries on.
- let status = handle_tinyplace_signal_key_status(Map::new()).await?;
- let keys_ready = status
- .get("hasActiveSignedPreKey")
- .and_then(Value::as_bool)
- .unwrap_or(false)
- && status
- .get("localPreKeyCount")
- .and_then(Value::as_u64)
- .unwrap_or(0)
- > 0;
- let published = status
- .get("encryptionKeyPublished")
- .and_then(Value::as_bool)
- .unwrap_or(false);
-
- if keys_ready && published {
- log::debug!("{LOG_PREFIX} ensure_signal_keys_published: already discoverable");
- return Ok(true);
- }
-
- // 2. Provision pre-keys if missing (signed pre-key + one-time pre-keys).
- if !keys_ready {
- log::info!("{LOG_PREFIX} ensure_signal_keys_published: provisioning pre-keys");
- handle_tinyplace_signal_provision(Map::new()).await?;
- }
-
- // 3. Advertise the encryption (identity) key on the directory card so peers
- // can resolve the prekey bundle and encrypt to this agent.
- if !published {
- log::info!("{LOG_PREFIX} ensure_signal_keys_published: publishing encryption key");
- handle_tinyplace_signal_register_encryption_key(Map::new()).await?;
- }
-
- // 4. Re-probe so the caller can confirm the agent is now discoverable and
- // stop retrying.
- let after = handle_tinyplace_signal_key_status(Map::new()).await?;
- let now_published = after
- .get("encryptionKeyPublished")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- log::info!("{LOG_PREFIX} ensure_signal_keys_published: done published={now_published}");
- Ok(now_published)
-}
-
-// ── Signal messaging helpers ──────────────────────────────────────────────────
-
-/// Decode a base64-encoded 32-byte value.
-fn decode_32_byte_b64(b64: &str, label: &str) -> std::result::Result<[u8; 32], String> {
- let bytes = base64::engine::general_purpose::STANDARD
- .decode(b64)
- .map_err(|e| format!("invalid base64 for {label}: {e}"))?;
- if bytes.len() != 32 {
- return Err(format!("{label}: expected 32 bytes, got {}", bytes.len()));
- }
- let mut arr = [0u8; 32];
- arr.copy_from_slice(&bytes);
- Ok(arr)
-}
-
-/// Decode a peer's published identity key (from a fetched key bundle) into the
-/// X25519 public key used for X3DH / Double-Ratchet Diffie-Hellman.
-///
-/// The backend stores and serves the wallet's **Ed25519** public key as the
-/// bundle identity key — it verifies signed/one-time pre-key signatures against
-/// it (`ed25519.Verify(identityKey, ...)`) and re-validates on every fetch. So
-/// the served identity key is Ed25519; convert it to its Montgomery (X25519)
-/// form, which equals the peer's X25519 identity public key derived from the
-/// same wallet seed, so DH stays consistent on both ends.
-fn decode_identity_key(b64: &str) -> std::result::Result<[u8; 32], String> {
- let ed_pub = decode_32_byte_b64(b64, "identity_key")?;
- tinyplace::signal::crypto::ed25519_pub_to_x25519_pub(&ed_pub)
- .map_err(|e| format!("identity_key is not a valid Ed25519 public key: {e}"))
-}
-
-fn decode_ed25519_pub(
- agent: &tinyplace::types::AgentCard,
-) -> std::result::Result<[u8; 32], String> {
- let b64 = agent
- .public_key
- .as_ref()
- .ok_or("peer directory entry has no publicKey — cannot verify bundle")?;
- decode_32_byte_b64(b64, "peer Ed25519 publicKey")
-}
-
-// ── Recipient resolution helpers ──────────────────────────────────────────────
-
-/// Quick heuristic: Solana/wallet base58 public keys are 32–44 chars of the
-/// Bitcoin base58 alphabet [1-9A-HJ-NP-Za-km-z] with no 0/I/O/l.
-/// False negatives (short base58 strings treated as handles) are safe — they
-/// get an extra directory.resolve call rather than a wrong key lookup.
-fn looks_like_base58_pubkey(s: &str) -> bool {
- s.len() >= 32
- && s.len() <= 44
- && s.chars().all(|c| {
- matches!(c,
- '1'..='9' | 'A'..='H' | 'J'..='N' | 'P'..='Z' | 'a'..='k' | 'm'..='z')
- })
-}
-
-/// Case-insensitive username match across a slice of agent cards.
-///
-/// Extracted as a pure function so it can be unit-tested without a live HTTP
-/// client.
-fn match_agent_card_by_username<'a>(
- cards: &'a [tinyplace::types::AgentCard],
- name: &str,
-) -> Option<&'a tinyplace::types::AgentCard> {
- let name_lower = name.to_lowercase();
- cards.iter().find(|a| {
- a.username
- .as_deref()
- .map(|u| u.to_lowercase() == name_lower)
- .unwrap_or(false)
- })
-}
-
-/// Query the agent directory for a card whose `username` matches `name`
-/// (case-insensitive). Uses the server-side `username` filter when available
-/// (limit 20) and falls back to a client-side match in the returned page.
-///
-/// Returns `None` if no matching card is found.
-async fn directory_card_fallback(
- client: &tinyplace::TinyPlaceClient,
- name: &str,
-) -> Option<tinyplace::types::AgentCard> {
- let query = tinyplace::types::AgentQueryParams {
- username: Some(name.to_string()),
- limit: Some(20),
- ..Default::default()
- };
- log::debug!("{LOG_PREFIX} directory_card_fallback: querying agents with username='{name}'");
- match client.directory.list_agents(Some(&query)).await {
- Ok(resp) => {
- if resp.agents.len() == 20 {
- log::debug!(
- "{LOG_PREFIX} directory_card_fallback: page full (20 agents) for '{name}', \
- result may be truncated"
- );
- }
- match_agent_card_by_username(&resp.agents, name).cloned()
- }
- Err(e) => {
- log::debug!(
- "{LOG_PREFIX} directory_card_fallback: list_agents failed for '{name}': {}",
- e
- );
- None
- }
- }
-}
-
-/// Resolve a recipient identifier (handle, wallet address, or crypto_id) to
-/// the canonical `crypto_id` used by the `/keys/{id}/bundle` endpoint.
-///
-/// Resolution rules:
-/// 1. Starts with `@` → strip `@` and resolve via `directory.resolve`.
-/// 2. Looks like a base58 public key (32–44 chars, valid alphabet) → use as-is
-/// (it IS the crypto_id; attempting resolve is unnecessary and fragile).
-/// 3. Anything else → treat as a bare handle name and call `directory.resolve`.
-/// 4. If the registry lookup returns 404 or no identity/agent, fall back to a
-/// directory-card search by username (`list_agents?username=…`).
-///
-/// SECURITY: never log private key material — only the resolved crypto_id
-/// (public wallet address) is emitted to logs.
-async fn resolve_recipient_to_agent_id(
- client: &tinyplace::TinyPlaceClient,
- raw_recipient: &str,
-) -> std::result::Result<String, String> {
- let trimmed = raw_recipient.trim();
-
- let lookup_name = if let Some(without_at) = trimmed.strip_prefix('@') {
- // Explicit @handle — resolve it.
- without_at
- } else if looks_like_base58_pubkey(trimmed) {
- // Already a crypto_id — pass through without a round-trip.
- log::debug!(
- "{LOG_PREFIX} resolve_recipient: '{trimmed}' looks like a crypto_id, using directly"
- );
- return Ok(trimmed.to_string());
- } else {
- // Bare handle name — resolve it.
- trimmed
- };
-
- log::debug!("{LOG_PREFIX} resolve_recipient: resolving handle '{lookup_name}' via registry");
-
- // ── Step 1: try the registry ─────────────────────────────────────────────
- let registry_result = client.directory.resolve(lookup_name).await;
- match registry_result {
- Ok(resolved) => {
- // Prefer the registered identity's crypto_id; fall back to the agent card.
- if let Some(identity) = resolved.identity {
- let crypto_id = identity.crypto_id.clone();
- log::debug!(
- "{LOG_PREFIX} resolve_recipient: handle '{lookup_name}' -> crypto_id={crypto_id}"
- );
- return Ok(crypto_id);
- } else if let Some(agent) = resolved.agent {
- let crypto_id = agent.crypto_id.clone();
- log::debug!(
- "{LOG_PREFIX} resolve_recipient: handle '{lookup_name}' resolved via \
- registry agent card -> crypto_id={crypto_id}"
- );
- return Ok(crypto_id);
- }
- // Registry returned 200 but empty — fall through to directory.
- log::debug!(
- "{LOG_PREFIX} resolve_recipient: registry returned empty for '{lookup_name}', \
- trying directory card fallback"
- );
- }
- Err(e) if e.status() == Some(404) => {
- // 404 from the registry — agent may be directory-only; fall through.
- log::debug!(
- "{LOG_PREFIX} resolve_recipient: registry 404 for '{lookup_name}', \
- trying directory card fallback"
- );
- }
- Err(e) => {
- return Err(format!(
- "failed to resolve recipient '{trimmed}': {}",
- map_err(e)
- ));
- }
- }
-
- // ── Step 2: directory-card fallback ──────────────────────────────────────
- if let Some(card) = directory_card_fallback(client, lookup_name).await {
- let crypto_id = card.crypto_id.clone();
- log::debug!(
- "{LOG_PREFIX} resolve_recipient: '{lookup_name}' found via directory card \
- -> crypto_id={crypto_id}"
- );
- return Ok(crypto_id);
- }
-
- Err(format!(
- "No agent found for \"{lookup_name}\". \
- Check the handle or paste their wallet address directly."
- ))
-}
-
-pub(crate) fn handle_tinyplace_signal_send_message(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let recipient = req_str(&params, "recipient")?.to_string();
- let plaintext = req_str(&params, "plaintext")?.to_string();
- log::debug!(
- "{LOG_PREFIX} signal_send_message raw_recipient='{recipient}' len={}",
- plaintext.len()
- );
-
- // Obtain our identity public key and an Arc-wrapped store for SignalSession.
- let store = crate::openhuman::tinyplace::signal_store::global_signal_store_arc().await?;
- let client = global_state().client().await?;
- let signer = require_signer(client)?;
- let our_agent_id = signer.agent_id();
- let our_identity_pub = store
- .identity_x25519_key_pair()
- .await
- .map_err(|e| format!("identity key: {e}"))?
- .public_key;
-
- // Resolve the recipient identifier (@handle, bare handle, or crypto_id) to
- // the canonical crypto_id before any key-bundle or directory lookup.
- let agent_id = resolve_recipient_to_agent_id(client, &recipient).await?;
- log::debug!("{LOG_PREFIX} signal_send_message resolved to agent_id={agent_id}");
-
- // Fetch recipient's published key bundle (always needed for the X25519
- // identity key used in associated-data computation, even for existing
- // sessions). Provide a user-friendly error when the recipient has not yet
- // provisioned Signal keys (404 from the backend).
- let bundle = match client.keys.get_bundle(&agent_id).await {
- Ok(b) => b,
- Err(e) if e.status() == Some(404) => {
- return Err(format!(
- "Recipient has not set up encrypted messaging yet. \
- They need to provision Signal keys before receiving DMs. \
- (resolved agent_id: {agent_id})"
- ));
- }
- Err(e) => return Err(map_err(e)),
- };
- // Ed25519 -> X25519 conversion: the backend serves the Ed25519 identity;
- // SignalSession::encrypt takes the X25519 form. decode_identity_key
- // performs this conversion and must be preserved.
- let their_x25519_identity = decode_identity_key(&bundle.identity_key)?;
-
- // Determine whether this is a new session (needs full X3DH bundle + Ed25519
- // key for signature verification) or an existing session (no bundle needed).
- let signal_session = SignalSession::new(
- Arc::clone(&store) as Arc<dyn SessionStore>,
- our_identity_pub,
- );
- let has_session = signal_session
- .has_session(&agent_id)
- .await
- .map_err(|e| format!("check session: {e}"))?;
-
- let (bundle_opt, ed25519_opt) = if has_session {
- log::debug!("{LOG_PREFIX} signal_send_message using existing session for {agent_id}");
- (None, None)
- } else {
- log::debug!("{LOG_PREFIX} signal_send_message establishing new session for {agent_id}");
- let peer_entry = client
- .directory
- .get_agent(&agent_id)
- .await
- .map_err(map_err)?;
- let peer_ed25519_pub = decode_ed25519_pub(&peer_entry)?;
- (Some(bundle), Some(peer_ed25519_pub))
- };
-
- // Encrypt via SDK SignalSession.
- //
- // SECURITY INVARIANT: if encryption fails we abort immediately — plaintext
- // is NEVER sent and the session is NOT stored (store_session runs after
- // ratchet_encrypt inside SignalSession::encrypt, so a failure before that
- // point leaves no partial state).
- let encrypted = signal_session
- .encrypt(
- &agent_id,
- &their_x25519_identity,
- plaintext.as_bytes(),
- bundle_opt.as_ref(),
- ed25519_opt.as_ref(),
- )
- .await
- .map_err(|e| {
- log::error!(
- "{LOG_PREFIX} signal_send_message ENCRYPTION FAILED for {agent_id}: {e} \
- — aborting send (plaintext will NOT be sent)"
- );
- format!("encryption failed — message NOT sent: {e}")
- })?;
-
- // Map EncryptedMessage -> MessageEnvelope (wire-format preserving).
- // Field correspondence is verified in phase-signalsession-spec.md §4.
- // Use the resolved agent_id (not raw recipient) so the backend routes correctly.
- let envelope = tinyplace::types::MessageEnvelope {
- // The backend requires a non-empty client-generated message id
- // (POST /messages rejects an empty id with "message id, from, and to
- // are required"). The SDK's send() only fills timestamp, not id.
- id: uuid::Uuid::new_v4().to_string(),
- from: our_agent_id.clone(),
- to: agent_id.clone(),
- timestamp: String::new(),
- device_id: 1,
- envelope_type: encrypted.message_type.clone(), // "PREKEY_BUNDLE" or "CIPHERTEXT"
- body: encrypted.body.clone(),
- content_hint: Some("DEFAULT".to_string()),
- signal: Some(encrypted.signal.clone()),
- };
-
- let sent = client.messages.send(envelope).await.map_err(map_err)?;
- log::info!(
- "{LOG_PREFIX} signal_send_message sent encrypted message to={agent_id} \
- id={} type={} len={}",
- sent.id,
- sent.envelope_type,
- sent.body.len()
- );
- to_value(serde_json::json!({
- "messageId": sent.id,
- "timestamp": sent.timestamp,
- "encrypted": true,
- }))
- })
-}
-
-/// Decrypt a single inbound Signal DM envelope to its plaintext body.
-///
-/// Shared by the `signal_decrypt_message` controller and the orchestration
-/// ingest path. NOTE: `SignalSession::decrypt` advances the double ratchet and
-/// consumes one-time pre-keys — it is NOT idempotent. Callers that may re-see
-/// the same envelope must dedupe by message id BEFORE calling this.
-pub(crate) async fn decrypt_envelope(
- envelope: &tinyplace::types::MessageEnvelope,
-) -> Result<String, String> {
- log::debug!(
- "{LOG_PREFIX} decrypt_envelope from={} type={} id={}",
- envelope.from,
- envelope.envelope_type,
- envelope.id
- );
-
- // Obtain our identity public key and an Arc-wrapped store for SignalSession.
- let store = crate::openhuman::tinyplace::signal_store::global_signal_store_arc().await?;
- let client = global_state().client().await?;
- let our_identity_pub = store
- .identity_x25519_key_pair()
- .await
- .map_err(|e| format!("identity key: {e}"))?
- .public_key;
-
- let sender = envelope.from.clone();
-
- // Fetch sender's published key bundle to obtain their X25519 identity key.
- // Ed25519 -> X25519 conversion via decode_identity_key — must be preserved.
- let sender_bundle = client.keys.get_bundle(&sender).await.map_err(map_err)?;
- let sender_x25519_identity = decode_identity_key(&sender_bundle.identity_key)?;
-
- // Decrypt via SDK SignalSession.
- //
- // SignalSession::decrypt handles both PREKEY_BUNDLE and CIPHERTEXT paths
- // internally (via process_pre_key_message), including one-time pre-key
- // consumption, x3dh_respond, ratchet_decrypt, and store_session.
- let signal_session = SignalSession::new(
- Arc::clone(&store) as Arc<dyn SessionStore>,
- our_identity_pub,
- );
- let plaintext_bytes = signal_session
- .decrypt(&sender, &sender_x25519_identity, envelope)
- .await
- .map_err(|e| format!("decryption failed: {e}"))?;
-
- let plaintext = String::from_utf8(plaintext_bytes)
- .map_err(|e| format!("plaintext is not valid UTF-8: {e}"))?;
- log::info!(
- "{LOG_PREFIX} decrypt_envelope decrypted from={sender} id={} len={}",
- envelope.id,
- plaintext.len()
- );
- Ok(plaintext)
-}
-
-/// Acknowledge (delete) a delivered message from the relay mailbox. Shared by
-/// the `messages_acknowledge` controller and orchestration ingest.
-pub(crate) async fn acknowledge_message(message_id: &str) -> Result<(), String> {
- let client = global_state().client().await?;
- let signer = require_signer(client)?;
- client
- .messages
- .acknowledge(message_id, &signer.agent_id())
- .await
- .map_err(map_err)?;
- Ok(())
-}
-
-pub(crate) fn handle_tinyplace_signal_decrypt_message(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let envelope_val = params
- .get("envelope")
- .ok_or("missing required param 'envelope'")?;
- let envelope: tinyplace::types::MessageEnvelope =
- serde_json::from_value(envelope_val.clone())
- .map_err(|e| format!("invalid envelope: {e}"))?;
- let plaintext = decrypt_envelope(&envelope).await?;
- to_value(serde_json::json!({
- "plaintext": plaintext,
- "from": envelope.from,
- "messageId": envelope.id,
- }))
- })
-}
-
-pub(crate) fn handle_tinyplace_messages_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let limit = params.get("limit").and_then(Value::as_i64);
- log::debug!("{LOG_PREFIX} messages_list limit={limit:?}");
- let client = global_state().client().await?;
- let signer = require_signer(client)?;
- match client.messages.list(&signer.agent_id(), limit).await {
- Ok(result) => to_value(result),
- Err(e) => match messages_list_degrade(&e) {
- Some(empty) => {
- log::debug!(
- "{LOG_PREFIX} messages_list deserialization failed (likely empty thread) -> empty: {e}"
- );
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-/// An empty message thread comes back as `{"messages": null}`, which fails the
-/// SDK's non-optional `messages: Vec<MessageEnvelope>` deserialization. Treat
-/// that serialization failure as an empty thread; propagate every other error.
-pub(crate) fn messages_list_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({ "messages": [] }))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_messages_acknowledge(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let message_id = req_str(&params, "messageId")?.to_string();
- log::debug!("{LOG_PREFIX} messages_acknowledge id={message_id}");
- acknowledge_message(&message_id).await?;
- to_value(serde_json::json!({ "ok": true }))
- })
-}
-
-// ── Contacts: signed social graph for encrypted direct messages ─────────────
-
-pub(crate) fn handle_tinyplace_contacts_request(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_nonblank_str(&params, "agentId")?;
- log::debug!("{LOG_PREFIX} contacts_request agent_id={agent_id}");
- let client = global_state().client().await?;
- let result: Value = client
- .http()
- .post_agent_auth::<Value, ()>(&contact_path(&agent_id, None), None)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_contacts_accept(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_nonblank_str(&params, "agentId")?;
- log::debug!("{LOG_PREFIX} contacts_accept agent_id={agent_id}");
- let client = global_state().client().await?;
- let result: Value = client
- .http()
- .post_agent_auth::<Value, ()>(&contact_path(&agent_id, Some("accept")), None)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_contacts_remove(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_nonblank_str(&params, "agentId")?;
- log::debug!("{LOG_PREFIX} contacts_remove agent_id={agent_id}");
- let client = global_state().client().await?;
- let result: Value = client
- .http()
- .delete_agent_auth::<Value, ()>(&contact_path(&agent_id, None), None)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_contacts_block(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_nonblank_str(&params, "agentId")?;
- log::debug!("{LOG_PREFIX} contacts_block agent_id={agent_id}");
- let client = global_state().client().await?;
- let result: Value = client
- .http()
- .post_agent_auth::<Value, ()>(&contact_path(&agent_id, Some("block")), None)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_contacts_unblock(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_nonblank_str(&params, "agentId")?;
- log::debug!("{LOG_PREFIX} contacts_unblock agent_id={agent_id}");
- let client = global_state().client().await?;
- let result: Value = client
- .http()
- .post_agent_auth::<Value, ()>(&contact_path(&agent_id, Some("unblock")), None)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_contacts_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let query = contact_query(&params);
- log::debug!("{LOG_PREFIX} contacts_list query={query:?}");
- let client = global_state().client().await?;
- let result: Value = client
- .http()
- .get_agent_auth("/contacts", &query)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_contacts_requests(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let query = contact_query(&params);
- log::debug!("{LOG_PREFIX} contacts_requests query={query:?}");
- let client = global_state().client().await?;
- let result: Value = client
- .http()
- .get_agent_auth("/contacts/requests", &query)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_contacts_status(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let agent_id = req_nonblank_str(&params, "agentId")?;
- log::debug!("{LOG_PREFIX} contacts_status agent_id={agent_id}");
- let client = global_state().client().await?;
- let result: Value = client
- .http()
- .get_agent_auth(&contact_path(&agent_id, Some("status")), &[])
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_contacts_stats(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!("{LOG_PREFIX} contacts_stats");
- let client = global_state().client().await?;
- let result: Value = client
- .http()
- .get_agent_auth("/contacts/stats", &[])
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Signal: encryption key registration (0D) ────────────────────────────────
-
-/// Publish the user's Ed25519 identity key (the addressable cryptoId, where the
-/// Signal prekey bundle + mailbox live) on their directory card as
-/// `metadata.encryptionPublicKey`. This makes the user discoverable for
-/// encrypted DMs via `find_agent_by_encryption_key`; peers derive the X25519 DH
-/// key from the fetched bundle themselves.
-///
-/// SECURITY: only the PUBLIC key is published.
-pub(crate) fn handle_tinyplace_signal_register_encryption_key(
- _params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- log::debug!("{LOG_PREFIX} signal_register_encryption_key");
-
- // 1. Acquire client and signer.
- let client = global_state().client().await?;
- let signer = require_signer(client)?;
- let agent_id = signer.agent_id();
-
- // 2. The messaging key peers resolve from this directory card must be the
- // wallet's **Ed25519 identity key** — that is the addressable identity
- // where the Signal prekey bundle is published (`/keys/<cryptoId>/bundle`)
- // and where the mailbox is keyed. Peers derive the X25519 DH key from
- // the bundle's identity key themselves (see `decode_identity_key`), so
- // they never need a separate X25519 key advertised here. Publishing the
- // X25519 key instead made every peer resolve to a *bundle-less* key and
- // 404 on the bundle fetch — the exact reason inbound DMs never reached
- // this agent. Advertise the identity key so resolution + delivery align.
- let encryption_key_b64 = signer.public_key_base64();
- log::debug!("{LOG_PREFIX} signal_register_encryption_key advertising identity key (value not logged)");
-
- // 3. Fetch current AgentCard to preserve existing fields. A wallet that
- // has Signal keys but no directory presence yet (e.g. it registered a
- // @handle but was never upserted as an agent) 404s here — in that
- // case create a fresh minimal card so "Make discoverable" still works,
- // best-effort enriching name/username from the registered identity.
- let mut card = match client.directory.get_agent(&agent_id).await {
- Ok(card) => {
- log::debug!(
- "{LOG_PREFIX} signal_register_encryption_key fetched existing card for {agent_id}"
- );
- card
- }
- Err(e) if e.status() == Some(404) => {
- log::debug!(
- "{LOG_PREFIX} signal_register_encryption_key no card for {agent_id} -> creating one"
- );
- let identity = client
- .directory
- .reverse(&agent_id)
- .await
- .ok()
- .and_then(|r| {
- // Prefer the wallet's primary handle; otherwise any handle.
- let mut ids = r.identities;
- ids.iter()
- .position(|i| i.primary == Some(true))
- .map(|idx| ids.swap_remove(idx))
- .or_else(|| ids.into_iter().next())
- });
- build_default_agent_card(&agent_id, &signer.public_key_base64(), identity.as_ref())
- }
- Err(e) => return Err(map_err(e)),
- };
-
- // 4. Merge encryptionPublicKey into metadata.
- let metadata = card
- .metadata
- .get_or_insert_with(std::collections::HashMap::new);
- metadata.insert(
- "encryptionPublicKey".to_string(),
- encryption_key_b64.clone(),
- );
-
- // 5. Upsert the card with the updated metadata.
- let updated = client
- .directory
- .upsert_agent(&agent_id, &card)
- .await
- .map_err(map_err)?;
- log::info!("{LOG_PREFIX} signal_register_encryption_key published for {agent_id}");
-
- to_value(serde_json::json!({
- "ok": true,
- "encryptionKey": encryption_key_b64,
- "agentId": agent_id,
- "updatedAt": updated.updated_at,
- }))
- })
-}
-
-/// Publish a directory card for a newly registered identity.
-///
-/// Called after every successful `registry_register` path (free-tier, paid
-/// settlement, recovery). The directory card makes the identity discoverable in
-/// `GET /directory/agents` and `GET /directory/identities` listings.
-///
-/// **Best-effort**: any failure is logged and swallowed so that a directory
-/// publish hiccup never rolls back the already-completed registry write.
-///
-/// **Anti-spoof**: `agent_id` is sourced from `signer.agent_id()` (the wallet's
-/// crypto identity), not from user-supplied params.
-async fn publish_directory_card_for_identity(
- client: &tinyplace::TinyPlaceClient,
- signer: &dyn tinyplace::Signer,
- identity: &tinyplace::types::Identity,
-) {
- let agent_id = signer.agent_id();
- let public_key_b64 = signer.public_key_base64();
- log::debug!("[tinyplace] post-register: publishing directory card for {agent_id}");
-
- // Fetch existing card to preserve custom fields; on 404 build a fresh one;
- // on any other error bail out early (best-effort).
- let mut card = match client.directory.get_agent(&agent_id).await {
- Ok(existing) => {
- log::debug!(
- "[tinyplace] post-register: updating existing directory card for {agent_id}"
- );
- let mut c = existing;
- // Refresh name/username from the newly registered identity.
- c.username = Some(identity.username.clone());
- c.name = identity.username.clone();
- c
- }
- Err(e) if e.status() == Some(404) => {
- log::debug!(
- "[tinyplace] post-register: no existing card for {agent_id} — creating one"
- );
- build_default_agent_card(&agent_id, &public_key_b64, Some(identity))
- }
- Err(e) => {
- log::warn!(
- "[tinyplace] post-register: directory card fetch failed for {agent_id}: {e}"
- );
- return;
- }
- };
-
- // Anti-spoof: ensure the card's agent_id/crypto_id matches the signer.
- card.agent_id = agent_id.clone();
- card.crypto_id = agent_id.clone();
-
- match client.directory.upsert_agent(&agent_id, &card).await {
- Ok(_) => {
- log::info!("[tinyplace] post-register: directory card published for {agent_id}");
- }
- Err(e) => {
- log::warn!("[tinyplace] post-register: directory upsert failed for {agent_id}: {e}");
- }
- }
-}
-
-/// Build a minimal `AgentCard` for a wallet that has no directory presence yet,
-/// so it can publish its encryption key and become discoverable. When the wallet
-/// owns a registered identity, its handle seeds `name`/`username`; otherwise the
-/// agent id is used. The backend assigns authoritative timestamps on upsert, so
-/// the `created_at`/`updated_at` we send are placeholders.
-pub(crate) fn build_default_agent_card(
- agent_id: &str,
- public_key_b64: &str,
- identity: Option<&tinyplace::types::Identity>,
-) -> tinyplace::types::AgentCard {
- let now = chrono::Utc::now().to_rfc3339();
- let username = identity.map(|i| i.username.clone());
- let name = username.clone().unwrap_or_else(|| agent_id.to_string());
- tinyplace::types::AgentCard {
- agent_id: agent_id.to_string(),
- name,
- description: None,
- username,
- crypto_id: agent_id.to_string(),
- actor_type: identity.map(|_| "human".to_string()),
- public_key: Some(public_key_b64.to_string()),
- url: None,
- endpoint: None,
- supported_interfaces: None,
- skills: None,
- capabilities: None,
- tags: None,
- payment_methods: None,
- payment_requirements: None,
- groups: None,
- docs: None,
- webhooks: None,
- metadata: None,
- signature: None,
- created_at: now.clone(),
- updated_at: now,
- viewer_is_following: None,
- }
-}
-
-// ── GraphQL: Social Feed ─────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_graphql_home_feed(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let limit = params.get("limit").and_then(Value::as_i64);
- let offset = params.get("offset").and_then(Value::as_i64);
- let include_self = params.get("includeSelf").and_then(Value::as_bool);
- log::debug!(
- "{LOG_PREFIX} graphql_home_feed limit={limit:?} offset={offset:?} include_self={include_self:?}"
- );
- let client = global_state().client().await?;
- // home_feed uses GraphQLAuth::Agent — requires a configured signer.
- let _signer = require_signer(client)?;
- match client.graphql.home_feed(limit, offset, include_self).await {
- Ok(result) => to_value(result),
- Err(e) => match graphql_home_feed_degrade(&e) {
- Some(empty) => {
- log::debug!(
- "{LOG_PREFIX} graphql_home_feed deserialization failed (likely empty feed) -> empty: {e}"
- );
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-/// The backend may return `{"items": null}` for an empty home feed, which
-/// fails the SDK's `items: Vec<GqlHomeFeedItem>` deserialization. Treat
-/// serialization failures as an empty feed; propagate every other error.
-pub(crate) fn graphql_home_feed_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({ "items": [], "count": 0 }))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_graphql_posts(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let handle = req_str(&params, "handle")?.to_string();
- let limit = params.get("limit").and_then(Value::as_i64);
- let before = params.get("before").and_then(Value::as_i64);
- let viewer = get_opt_str(&params, "viewer").map(|s| s.to_string());
- log::debug!("{LOG_PREFIX} graphql_posts handle={handle} limit={limit:?} before={before:?}");
- let sdk_params = tinyplace::api::graphql::PostGraphQLParams {
- limit,
- before,
- viewer,
- };
- let client = global_state().client().await?;
- match client.graphql.posts(&handle, Some(&sdk_params)).await {
- Ok(result) => to_value(result),
- Err(e) => match graphql_posts_degrade(&e) {
- Some(empty) => {
- log::debug!("{LOG_PREFIX} graphql_posts deserialization failed -> empty: {e}");
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-/// Empty user feed may return `{"posts": null}`. Degrade like inbox_list.
-pub(crate) fn graphql_posts_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({ "posts": [], "count": 0 }))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_graphql_post(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let handle = req_str(&params, "handle")?.to_string();
- let post_id = req_str(&params, "postId")?.to_string();
- let viewer = get_opt_str(&params, "viewer").map(|s| s.to_string());
- let comment_limit = params.get("commentLimit").and_then(Value::as_i64);
- let comment_after = params.get("commentAfter").and_then(Value::as_i64);
- let liker_limit = params.get("likerLimit").and_then(Value::as_i64);
- let liker_offset = params.get("likerOffset").and_then(Value::as_i64);
- log::debug!(
- "{LOG_PREFIX} graphql_post handle={handle} post_id={post_id} comment_limit={comment_limit:?}"
- );
- let sdk_params = tinyplace::api::graphql::PostDetailGraphQLParams {
- viewer,
- comment_limit,
- comment_after,
- liker_limit,
- liker_offset,
- };
- let client = global_state().client().await?;
- let result = client
- .graphql
- .post(&handle, &post_id, Some(&sdk_params))
- .await
- .map_err(map_err)?;
- // SDK returns Option<GqlPostDetail> — null means post not found.
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_graphql_post_comments(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let post_id = req_str(&params, "postId")?.to_string();
- let feed_id = get_opt_str(&params, "feedId").map(|s| s.to_string());
- let limit = params.get("limit").and_then(Value::as_i64);
- let after = params.get("after").and_then(Value::as_i64);
- log::debug!(
- "{LOG_PREFIX} graphql_post_comments post_id={post_id} limit={limit:?} after={after:?}"
- );
- let sdk_params = tinyplace::api::graphql::CommentGraphQLParams {
- feed_id,
- limit,
- after,
- };
- let client = global_state().client().await?;
- let result = client
- .graphql
- .post_comments(&post_id, Some(&sdk_params))
- .await
- .map_err(map_err)?;
- // Returns Vec<GqlComment> — wrap in an object for consistent RPC shape.
- to_value(serde_json::json!({ "comments": result }))
- })
-}
-
-pub(crate) fn handle_tinyplace_graphql_post_likers(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let post_id = req_str(&params, "postId")?.to_string();
- let limit = params.get("limit").and_then(Value::as_i64);
- let offset = params.get("offset").and_then(Value::as_i64);
- log::debug!(
- "{LOG_PREFIX} graphql_post_likers post_id={post_id} limit={limit:?} offset={offset:?}"
- );
- let sdk_params = tinyplace::api::graphql::PaginationGraphQLParams { limit, offset };
- let client = global_state().client().await?;
- let result = client
- .graphql
- .post_likers(&post_id, Some(&sdk_params))
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── GraphQL: Ledger ──────────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_graphql_ledger_transactions(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} graphql_ledger_transactions params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::LedgerListParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid ledger_transactions params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- // GraphQLAuth::None — no signer required; the ledger is public.
- match client
- .graphql
- .ledger_transactions(query_params.as_ref())
- .await
- {
- Ok(result) => to_value(result),
- Err(e) => match graphql_ledger_transactions_degrade(&e) {
- Some(empty) => {
- log::debug!(
- "{LOG_PREFIX} graphql_ledger_transactions deserialization failed -> empty: {e}"
- );
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-/// The backend may return `{"transactions": null}` for an empty ledger.
-/// Degrade Serialization errors to an empty result; propagate everything else.
-pub(crate) fn graphql_ledger_transactions_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({ "transactions": [], "count": 0 }))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_graphql_ledger_transaction(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let id = req_str(&params, "id")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_ledger_transaction id={id}");
- let client = global_state().client().await?;
- // GraphQLAuth::None — no signer required.
- let result = client
- .graphql
- .ledger_transaction(&id)
- .await
- .map_err(map_err)?;
- // Returns Option<GqlLedgerTransaction> — null means tx not found.
- to_value(result)
- })
-}
-
-// ── GraphQL: Jobs Board ────────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_graphql_jobs(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} graphql_jobs params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::JobQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid graphql_jobs params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- // GraphQLAuth::None — no signer required; the jobs board is public.
- match client.graphql.jobs(query_params.as_ref()).await {
- Ok(result) => to_value(result),
- Err(e) => match graphql_jobs_degrade(&e) {
- Some(empty) => {
- log::debug!("{LOG_PREFIX} graphql_jobs deserialization failed -> empty: {e}");
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-/// The backend may return `{"jobs": null}` for an empty jobs board.
-/// Degrade Serialization errors to an empty result; propagate everything else.
-pub(crate) fn graphql_jobs_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({ "jobs": [], "count": 0 }))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_graphql_job(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let id = req_str(&params, "id")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_job id={id}");
- let client = global_state().client().await?;
- // GraphQLAuth::None — no signer required.
- let result = client.graphql.job(&id).await.map_err(map_err)?;
- // Returns Option<GqlJobPosting> — null means job not found.
- to_value(result)
- })
-}
-
-// ── GraphQL: Bounties ─────────────────────────────────────────────────────────
-
-pub(crate) fn handle_tinyplace_graphql_bounties(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} graphql_bounties params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- // BountyGraphQLParams isn't Deserialize, so build it from the optional
- // filter object by hand (all fields optional). Reject malformed input
- // rather than silently dropping it — a mistyped `limit`/`creator` must
- // not degrade into an unfiltered public list.
- let query_params: Option<tinyplace::api::graphql::BountyGraphQLParams> = match params
- .get("params")
- {
- None | Some(Value::Null) => None,
- Some(Value::Object(obj)) => {
- let str_field = |key: &str| -> Result<Option<String>, String> {
- match obj.get(key) {
- None | Some(Value::Null) => Ok(None),
- Some(Value::String(s)) => Ok(Some(s.clone())),
- Some(_) => Err(format!("graphql_bounties param '{key}' must be a string")),
- }
- };
- let int_field = |key: &str| -> Result<Option<i64>, String> {
- match obj.get(key) {
- None | Some(Value::Null) => Ok(None),
- Some(v) => v.as_i64().map(Some).ok_or_else(|| {
- format!("graphql_bounties param '{key}' must be an integer")
- }),
- }
- };
- Some(tinyplace::api::graphql::BountyGraphQLParams {
- status: str_field("status")?,
- creator: str_field("creator")?,
- limit: int_field("limit")?,
- offset: int_field("offset")?,
- })
- }
- Some(_) => return Err("graphql_bounties 'params' must be an object".to_string()),
- };
-
- let client = global_state().client().await?;
- // GraphQLAuth::None — bounties are public.
- match client.graphql.bounties(query_params.as_ref()).await {
- Ok(result) => to_value(result),
- Err(e) => match graphql_bounties_degrade(&e) {
- Some(empty) => {
- log::debug!(
- "{LOG_PREFIX} graphql_bounties deserialization failed -> empty: {e}"
- );
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-/// The backend may return `{"bounties": null}` for an empty board. Degrade
-/// Serialization errors to an empty list; propagate everything else.
-pub(crate) fn graphql_bounties_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!([]))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_graphql_bounty(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let id = req_str(&params, "id")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_bounty id={id}");
- let client = global_state().client().await?;
- // GraphQLAuth::None — no signer required.
- let result = client.graphql.bounty(&id).await.map_err(map_err)?;
- // Returns Option<GqlBounty> — null means bounty not found.
- to_value(result)
- })
-}
-
-// ── GraphQL: Profile + Identity ───────────────────────────────────────────────
-
-fn graphql_params_object<'a>(
- params: &'a Map<String, Value>,
- method: &str,
-) -> Result<Option<&'a Map<String, Value>>, String> {
- match params.get("params") {
- None | Some(Value::Null) => Ok(None),
- Some(Value::Object(obj)) => Ok(Some(obj)),
- Some(_) => Err(format!("{method} 'params' must be an object")),
- }
-}
-
-fn graphql_opt_string(
- obj: &Map<String, Value>,
- method: &str,
- key: &str,
-) -> Result<Option<String>, String> {
- match obj.get(key) {
- None | Some(Value::Null) => Ok(None),
- Some(Value::String(s)) => Ok(Some(s.clone())),
- Some(_) => Err(format!("{method} param '{key}' must be a string")),
- }
-}
-
-fn graphql_opt_i64(
- obj: &Map<String, Value>,
- method: &str,
- key: &str,
-) -> Result<Option<i64>, String> {
- match obj.get(key) {
- None | Some(Value::Null) => Ok(None),
- Some(v) => v
- .as_i64()
- .map(Some)
- .ok_or_else(|| format!("{method} param '{key}' must be an integer")),
- }
-}
-
-fn graphql_opt_string_vec(
- obj: &Map<String, Value>,
- method: &str,
- key: &str,
-) -> Result<Option<Vec<String>>, String> {
- match obj.get(key) {
- None | Some(Value::Null) => Ok(None),
- Some(Value::Array(values)) => values
- .iter()
- .map(|value| {
- value
- .as_str()
- .map(str::to_string)
- .ok_or_else(|| format!("{method} param '{key}' must be an array of strings"))
- })
- .collect::<Result<Vec<_>, _>>()
- .map(Some),
- Some(_) => Err(format!(
- "{method} param '{key}' must be an array of strings"
- )),
- }
-}
-
-fn parse_identity_listing_params(
- params: &Map<String, Value>,
- method: &str,
-) -> Result<Option<tinyplace::api::graphql::IdentityListingGraphQLParams>, String> {
- let Some(obj) = graphql_params_object(params, method)? else {
- return Ok(None);
- };
- Ok(Some(
- tinyplace::api::graphql::IdentityListingGraphQLParams {
- query: match graphql_opt_string(obj, method, "query")? {
- Some(query) => Some(query),
- None => graphql_opt_string(obj, method, "q")?,
- },
- tag: graphql_opt_string(obj, method, "tag")?,
- tags: graphql_opt_string_vec(obj, method, "tags")?,
- category: graphql_opt_string(obj, method, "category")?,
- seller: graphql_opt_string(obj, method, "seller")?,
- min_price: graphql_opt_string(obj, method, "minPrice")?,
- max_price: graphql_opt_string(obj, method, "maxPrice")?,
- sort_by: graphql_opt_string(obj, method, "sortBy")?,
- length: graphql_opt_i64(obj, method, "length")?,
- limit: graphql_opt_i64(obj, method, "limit")?,
- offset: graphql_opt_i64(obj, method, "offset")?,
- },
- ))
-}
-
-fn parse_pagination_params(
- params: &Map<String, Value>,
- method: &str,
-) -> Result<Option<tinyplace::api::graphql::PaginationGraphQLParams>, String> {
- let Some(obj) = graphql_params_object(params, method)? else {
- return Ok(None);
- };
- Ok(Some(tinyplace::api::graphql::PaginationGraphQLParams {
- limit: graphql_opt_i64(obj, method, "limit")?,
- offset: graphql_opt_i64(obj, method, "offset")?,
- }))
-}
-
-pub(crate) fn handle_tinyplace_graphql_agents(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} graphql_agents params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::AgentQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid graphql_agents params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- match client.graphql.agents(query_params.as_ref()).await {
- Ok(result) => to_value(result),
- Err(e) => match graphql_agents_degrade(&e) {
- Some(empty) => {
- log::debug!("{LOG_PREFIX} graphql_agents deserialization failed -> empty: {e}");
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-pub(crate) fn graphql_agents_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({ "agents": [], "count": 0 }))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_graphql_products(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} graphql_products params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::ProductQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid graphql_products params: {e}"))
- })
- .transpose()?;
-
- let client = global_state().client().await?;
- match client.graphql.products(query_params.as_ref()).await {
- Ok(result) => to_value(result),
- Err(e) => match graphql_products_degrade(&e) {
- Some(empty) => {
- log::debug!(
- "{LOG_PREFIX} graphql_products deserialization failed -> empty: {e}"
- );
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-pub(crate) fn graphql_products_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({ "products": [], "count": 0 }))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_graphql_product(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let id = req_str(&params, "id")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_product id={id}");
- let client = global_state().client().await?;
- let result = client.graphql.product(&id).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_graphql_identity_listings(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} graphql_identity_listings params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params = parse_identity_listing_params(&params, "graphql_identity_listings")?;
- let client = global_state().client().await?;
- match client
- .graphql
- .identity_listings(query_params.as_ref())
- .await
- {
- Ok(result) => to_value(result),
- Err(e) => match graphql_identity_listings_degrade(&e) {
- Some(empty) => {
- log::debug!(
- "{LOG_PREFIX} graphql_identity_listings deserialization failed -> empty: {e}"
- );
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-pub(crate) fn graphql_identity_listings_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({ "identities": [], "count": 0 }))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_graphql_identity_listing(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let id = req_str(&params, "id")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_identity_listing id={id}");
- let query_params = match graphql_params_object(&params, "graphql_identity_listing")? {
- None => None,
- Some(obj) => Some(
- tinyplace::api::graphql::IdentityListingDetailGraphQLParams {
- bid_limit: graphql_opt_i64(obj, "graphql_identity_listing", "bidLimit")?,
- bid_offset: graphql_opt_i64(obj, "graphql_identity_listing", "bidOffset")?,
- history_limit: graphql_opt_i64(
- obj,
- "graphql_identity_listing",
- "historyLimit",
- )?,
- history_offset: graphql_opt_i64(
- obj,
- "graphql_identity_listing",
- "historyOffset",
- )?,
- },
- ),
- };
- let client = global_state().client().await?;
- let result = client
- .graphql
- .identity_listing(&id, query_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_graphql_identity_bids(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let listing_id = req_str(&params, "listingId")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_identity_bids listing_id={listing_id}");
- let query_params = parse_pagination_params(&params, "graphql_identity_bids")?;
- let client = global_state().client().await?;
- let result = client
- .graphql
- .identity_bids(&listing_id, query_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_graphql_identity_offers(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} graphql_identity_offers params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params = match graphql_params_object(&params, "graphql_identity_offers")? {
- None => None,
- Some(obj) => Some(tinyplace::api::graphql::IdentityOfferGraphQLParams {
- agent: graphql_opt_string(obj, "graphql_identity_offers", "agent")?,
- buyer: graphql_opt_string(obj, "graphql_identity_offers", "buyer")?,
- name: graphql_opt_string(obj, "graphql_identity_offers", "name")?,
- status: graphql_opt_string(obj, "graphql_identity_offers", "status")?,
- limit: graphql_opt_i64(obj, "graphql_identity_offers", "limit")?,
- offset: graphql_opt_i64(obj, "graphql_identity_offers", "offset")?,
- }),
- };
- let client = global_state().client().await?;
- let result = client
- .graphql
- .identity_offers(query_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_graphql_identity_sales(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let name = req_str(&params, "name")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_identity_sales name={name}");
- let query_params = parse_pagination_params(&params, "graphql_identity_sales")?;
- let client = global_state().client().await?;
- let result = client
- .graphql
- .identity_sales(&name, query_params.as_ref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_graphql_profile(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let username = req_str(&params, "username")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_profile username={username}");
- let client = global_state().client().await?;
- // GraphQLAuth::None — no signer required.
- let result = client.graphql.profile(&username).await.map_err(map_err)?;
- // Returns Option<GqlProfile> — null means profile not found.
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_graphql_user(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let crypto_id = req_str(&params, "cryptoId")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_user crypto_id={crypto_id}");
- let client = global_state().client().await?;
- // GraphQLAuth::None — no signer required.
- let result = client.graphql.user(&crypto_id).await.map_err(map_err)?;
- // Returns Option<GqlProfile> — null means no profile for this crypto_id.
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_graphql_identity(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let username = req_str(&params, "username")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_identity username={username}");
- let client = global_state().client().await?;
- // GraphQLAuth::None — no signer required.
- let result = client.graphql.identity(&username).await.map_err(map_err)?;
- // Returns Option<GqlIdentity> — null means identity not found.
- to_value(result)
- })
-}
-
-/// The backend may return `{"identities": null}` for a wallet with no handles.
-/// Degrade Serialization errors to an empty array; propagate everything else.
-pub(crate) fn graphql_identities_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!([]))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_graphql_identities(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let crypto_id = req_str(&params, "cryptoId")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_identities crypto_id={crypto_id}");
- let client = global_state().client().await?;
- // GraphQLAuth::None — no signer required.
- let result = match client.graphql.identities(&crypto_id).await {
- Ok(identities) => identities,
- Err(e) => match graphql_identities_degrade(&e) {
- Some(empty) => {
- log::debug!(
- "{LOG_PREFIX} graphql_identities deserialization failed -> empty: {e}"
- );
- // Wrap empty array in the RPC envelope shape for consistency.
- return to_value(serde_json::json!({ "identities": empty }));
- }
- None => return Err(map_err(e)),
- },
- };
- // Wrap Vec<Identity> in a named key for consistent RPC shape.
- to_value(serde_json::json!({ "identities": result }))
- })
-}
-
-pub(crate) fn handle_tinyplace_graphql_agent_card(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let id = req_str(&params, "id")?.to_string();
- log::debug!("{LOG_PREFIX} graphql_agent_card id={id}");
- let client = global_state().client().await?;
- // GraphQLAuth::None — no signer required.
- let result = client.graphql.agent_card(&id).await.map_err(map_err)?;
- // Returns Option<AgentCard> — null means agent card not found.
- to_value(result)
- })
-}
-
-// ── Directory: find by encryption key (0D) ──────────────────────────────────
-
-/// Reverse-lookup: find the agent advertising a given encryption public key.
-/// Returns the full `AgentCard` or `null` if no agent advertises it.
-pub(crate) fn handle_tinyplace_directory_find_by_encryption_key(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let encryption_key = req_str(&params, "encryptionKey")?.to_string();
- log::debug!("{LOG_PREFIX} directory_find_by_encryption_key (key not logged for brevity)");
- let client = global_state().client().await?;
- let result = client
- .directory
- .find_agent_by_encryption_key(&encryption_key)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Feeds write surface (Phase A) ─────────────────────────────────────────────
-
-/// Create a new post on a feed owned by the signer.
-/// `handle` identifies the target feed but the backend enforces that the signer
-/// owns it via `post_directory_auth_as`. Actor is NEVER accepted from params.
-pub(crate) fn handle_tinyplace_feeds_create_post(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let body = req_str(&params, "body")?.trim().to_string();
- if body.is_empty() {
- return Err("missing required param 'body'".to_string());
- }
- let content_type = get_opt_str(&params, "contentType")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
-
- let client = global_state().client().await?;
- // Post to the SIGNER's OWN feed. The handle is resolved server-side from
- // the wallet (its crypto id is a valid feed handle) — never accepted from
- // the client — so this works for every wallet, registered @handle or not,
- // and a caller cannot post to a feed they don't own.
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let handle = signer.agent_id();
-
- log::debug!(
- "{LOG_PREFIX} feeds_create_post handle={handle} body_len={}",
- body.len()
- );
-
- let post_create = tinyplace::types::PostCreate {
- body,
- content_type,
- post_id: None,
- };
- let result = client
- .feeds
- .create_post(&handle, &post_create)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-/// Delete a post from the SIGNER's OWN feed. The handle is resolved server-side
-/// from the wallet (owner-only) — never accepted from the client.
-pub(crate) fn handle_tinyplace_feeds_delete_post(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let post_id = req_str(&params, "postId")?.trim().to_string();
- if post_id.is_empty() {
- return Err("missing required param 'postId'".to_string());
- }
-
- let client = global_state().client().await?;
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let handle = signer.agent_id();
-
- log::debug!("{LOG_PREFIX} feeds_delete_post handle={handle} post_id={post_id}");
-
- client
- .feeds
- .delete_post(&handle, &post_id)
- .await
- .map_err(map_err)?;
- Ok(serde_json::json!({ "ok": true }))
- })
-}
-
-/// Add a comment to a post. Author is resolved from the wallet signer — NEVER
-/// from client-supplied params.
-pub(crate) fn handle_tinyplace_feeds_add_comment(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let handle = req_str(&params, "handle")?.trim().to_string();
- if handle.is_empty() {
- return Err("missing required param 'handle'".to_string());
- }
- let post_id = req_str(&params, "postId")?.trim().to_string();
- if post_id.is_empty() {
- return Err("missing required param 'postId'".to_string());
- }
- let body = req_str(&params, "body")?.trim().to_string();
- if body.is_empty() {
- return Err("missing required param 'body'".to_string());
- }
-
- let client = global_state().client().await?;
- // ANTI-SPOOF: author is always the wallet signer, never from params.
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let author = signer.agent_id();
-
- log::debug!(
- "{LOG_PREFIX} feeds_add_comment handle={handle} post_id={post_id} author={author}"
- );
-
- let comment_create = tinyplace::types::CommentCreate {
- body,
- comment_id: None,
- };
- let result = client
- .feeds
- .add_comment(&handle, &post_id, &author, &comment_create)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-/// Delete a comment. Actor is resolved from the wallet signer — NEVER from
-/// client-supplied params.
-pub(crate) fn handle_tinyplace_feeds_delete_comment(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let handle = req_str(&params, "handle")?.trim().to_string();
- if handle.is_empty() {
- return Err("missing required param 'handle'".to_string());
- }
- let post_id = req_str(&params, "postId")?.trim().to_string();
- if post_id.is_empty() {
- return Err("missing required param 'postId'".to_string());
- }
- let comment_id = req_str(&params, "commentId")?.trim().to_string();
- if comment_id.is_empty() {
- return Err("missing required param 'commentId'".to_string());
- }
-
- let client = global_state().client().await?;
- // ANTI-SPOOF: actor is always the wallet signer, never from params.
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- log::debug!(
- "{LOG_PREFIX} feeds_delete_comment handle={handle} post_id={post_id} \
- comment_id={comment_id} actor={actor}"
- );
-
- client
- .feeds
- .delete_comment(&handle, &post_id, &comment_id, &actor)
- .await
- .map_err(map_err)?;
- Ok(serde_json::json!({ "ok": true }))
- })
-}
-
-/// Like a post. Actor is resolved from the wallet signer — NEVER from params.
-/// Idempotent.
-pub(crate) fn handle_tinyplace_feeds_like_post(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let handle = req_str(&params, "handle")?.trim().to_string();
- if handle.is_empty() {
- return Err("missing required param 'handle'".to_string());
- }
- let post_id = req_str(&params, "postId")?.trim().to_string();
- if post_id.is_empty() {
- return Err("missing required param 'postId'".to_string());
- }
-
- let client = global_state().client().await?;
- // ANTI-SPOOF: actor is always the wallet signer, never from params.
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- log::debug!("{LOG_PREFIX} feeds_like_post handle={handle} post_id={post_id} actor={actor}");
-
- let result = client
- .feeds
- .like_post(&handle, &post_id, &actor)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-/// Unlike a post. Actor is resolved from the wallet signer — NEVER from params.
-/// Idempotent.
-pub(crate) fn handle_tinyplace_feeds_unlike_post(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let handle = req_str(&params, "handle")?.trim().to_string();
- if handle.is_empty() {
- return Err("missing required param 'handle'".to_string());
- }
- let post_id = req_str(&params, "postId")?.trim().to_string();
- if post_id.is_empty() {
- return Err("missing required param 'postId'".to_string());
- }
-
- let client = global_state().client().await?;
- // ANTI-SPOOF: actor is always the wallet signer, never from params.
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
-
- log::debug!(
- "{LOG_PREFIX} feeds_unlike_post handle={handle} post_id={post_id} actor={actor}"
- );
-
- let result = client
- .feeds
- .unlike_post(&handle, &post_id, &actor)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-// ── Bounties section (Phase B) ────────────────────────────────────────────────
-
-/// BountyListResponse.bounties is a bare Vec<Bounty> — a null/missing field
-/// fails deserialization. Degrade to an empty list.
-pub(crate) fn bounties_list_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({ "bounties": [] }))
- } else {
- None
- }
-}
-
-/// BountySubmissionsResponse.submissions is a bare Vec<BountySubmission>.
-pub(crate) fn bounties_submissions_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({ "submissions": [] }))
- } else {
- None
- }
-}
-
-/// BountyCommentsResponse.comments is a bare Vec<BountyComment>.
-pub(crate) fn bounties_comments_degrade(e: &tinyplace::Error) -> Option<Value> {
- if matches!(e, tinyplace::Error::Serialization(_)) {
- Some(serde_json::json!({ "comments": [] }))
- } else {
- None
- }
-}
-
-pub(crate) fn handle_tinyplace_bounties_list(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- log::debug!(
- "{LOG_PREFIX} bounties_list params_keys={:?}",
- params.keys().collect::<Vec<_>>()
- );
- let query_params: Option<tinyplace::types::BountyQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid bounties list params: {e}"))
- })
- .transpose()?;
- let client = global_state().client().await?;
- match client.bounties.list(query_params.as_ref()).await {
- Ok(result) => to_value(result),
- Err(e) => match bounties_list_degrade(&e) {
- Some(empty) => {
- log::debug!("{LOG_PREFIX} bounties_list deserialization failed -> empty: {e}");
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-pub(crate) fn handle_tinyplace_bounties_get(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let bounty_id = req_str(&params, "bountyId")?.to_string();
- log::debug!("{LOG_PREFIX} bounties_get bounty_id={bounty_id}");
- let client = global_state().client().await?;
- let result = client.bounties.get(&bounty_id).await.map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_bounties_create(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let title = req_str(&params, "title")?.trim().to_string();
- if title.is_empty() {
- return Err("missing required param 'title'".to_string());
- }
- let description = req_str(&params, "description")?.trim().to_string();
- if description.is_empty() {
- return Err("missing required param 'description'".to_string());
- }
- let amount = req_str(&params, "amount")?.trim().to_string();
- if amount.is_empty() {
- return Err("missing required param 'amount'".to_string());
- }
- let asset = get_opt_str(&params, "asset")
- .filter(|s| !s.is_empty())
- .unwrap_or("USDC")
- .to_string();
- let deadline = get_opt_str(&params, "deadline")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- let duration_days = params.get("durationDays").and_then(Value::as_i64);
- let confirmed = params
- .get("confirmed")
- .and_then(Value::as_bool)
- .unwrap_or(false);
-
- log::debug!(
- "{LOG_PREFIX} bounties_create title={title} amount={amount} asset={asset} confirmed={confirmed}"
- );
-
- let client = global_state().client().await?;
- // ANTI-SPOOF: creator resolved from signer, never from params.
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let creator = signer.agent_id();
-
- let request = tinyplace::types::BountyCreateRequest {
- creator: Some(creator.clone()),
- creator_crypto_id: Some(creator),
- title,
- description,
- amount,
- asset: Some(asset),
- deadline,
- duration_days,
- payment: None,
- };
-
- // The backend funds the reward into escrow at creation time via x402, so
- // creating a bounty is a confirm-before-spend flow (same as register/buy):
- // probe without payment to get the 402 challenge, then re-create with the
- // signed payment map once the user confirms.
- let challenge = match client.bounties.create(&request).await {
- Ok(bounty) => {
- // No payment required (free / already-funded) — return as-is.
- log::debug!("{LOG_PREFIX} bounties_create no payment needed");
- return to_value(serde_json::json!({ "bounty": bounty }));
- }
- Err(e) => match e.payment_required() {
- Some(pr) => pr.payment.clone(),
- None => return Err(map_err(e)),
- },
- };
- log::debug!(
- "{LOG_PREFIX} bounties_create 402 challenge network={:?} asset={:?} amount={:?}",
- challenge.network,
- challenge.asset,
- challenge.amount,
- );
-
- // Unconfirmed: surface the challenge + balance, spend nothing.
- if !confirmed {
- let (wallet_balance, wallet_address) = wallet_usdc_balance(&signer.agent_id()).await;
- return to_value(serde_json::json!({
- "challenge": challenge,
- "walletBalance": wallet_balance,
- "walletAddress": wallet_address,
- }));
- }
-
- // Confirmed: cluster guards, pay on-chain, re-create with the payment map.
- if let Some(network) = challenge.network.as_deref() {
- ensure_cluster_matches(network)?;
- }
- ensure_backend_mint_matches(client).await?;
-
- let mut extra_metadata = HashMap::new();
- extra_metadata.insert("title".to_string(), request.title.clone());
- let fulfilled = fulfill_payment(
- &challenge,
- signer.as_ref(),
- PaymentContext {
- purpose: "bounties.create".to_string(),
- nonce_prefix: "bounty".to_string(),
- extra_metadata,
- },
- )
- .await?;
- let on_chain_tx = fulfilled.on_chain_tx.clone();
-
- let mut funded_request = request.clone();
- funded_request.payment = Some(fulfilled.payment_map.clone());
-
- match settle_retry("bounties_create", || {
- client.bounties.create(&funded_request)
- })
- .await
- {
- Ok(bounty) => to_value(serde_json::json!({
- "bounty": bounty,
- "payment": { "onChainTx": on_chain_tx },
- })),
- Err(SettleFailure::Hard(m)) => Err(format!(
- "bounty creation failed after payment (onChainTx={on_chain_tx}): {m}"
- )),
- Err(SettleFailure::Exhausted(last)) => Err(format!(
- "bounty paid but not confirmed in time (onChainTx={on_chain_tx}); last error: {last}"
- )),
- }
- })
-}
-
-pub(crate) fn handle_tinyplace_bounties_cancel(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let bounty_id = req_str(&params, "bountyId")?.to_string();
- log::debug!("{LOG_PREFIX} bounties_cancel bounty_id={bounty_id}");
- let client = global_state().client().await?;
- // ANTI-SPOOF: creator resolved from signer, never from params.
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let creator = signer.agent_id();
- let result = client
- .bounties
- .cancel(&bounty_id, &creator)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_bounties_submit(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let bounty_id = req_str(&params, "bountyId")?.to_string();
- let url = req_str(&params, "url")?.trim().to_string();
- if url.is_empty() {
- return Err("missing required param 'url'".to_string());
- }
- let title = get_opt_str(&params, "title")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- let note = get_opt_str(&params, "note")
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- log::debug!("{LOG_PREFIX} bounties_submit bounty_id={bounty_id} url={url}");
-
- let client = global_state().client().await?;
- // ANTI-SPOOF: submitter resolved from signer, never from params.
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let submitter = signer.agent_id();
-
- let request = tinyplace::types::BountySubmissionCreateRequest {
- submitter: Some(submitter),
- submitter_crypto_id: None,
- url,
- title,
- note,
- };
- let result = client
- .bounties
- .submit(&bounty_id, &request)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_bounties_list_submissions(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let bounty_id = req_str(&params, "bountyId")?.to_string();
- log::debug!("{LOG_PREFIX} bounties_list_submissions bounty_id={bounty_id}");
- let query_params: Option<tinyplace::types::BountySubmissionQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid bounties list_submissions params: {e}"))
- })
- .transpose()?;
- let client = global_state().client().await?;
- match client
- .bounties
- .list_submissions(&bounty_id, query_params.as_ref())
- .await
- {
- Ok(result) => to_value(result),
- Err(e) => match bounties_submissions_degrade(&e) {
- Some(empty) => {
- log::debug!("{LOG_PREFIX} bounties_list_submissions degrade -> empty: {e}");
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-pub(crate) fn handle_tinyplace_bounties_comment(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let bounty_id = req_str(&params, "bountyId")?.to_string();
- let body = req_str(&params, "body")?.trim().to_string();
- if body.is_empty() {
- return Err("missing required param 'body'".to_string());
- }
- log::debug!("{LOG_PREFIX} bounties_comment bounty_id={bounty_id}");
-
- let client = global_state().client().await?;
- // ANTI-SPOOF: author resolved from signer, never from params.
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let author = signer.agent_id();
-
- let request = tinyplace::types::BountyCommentCreateRequest {
- author: Some(author),
- author_crypto_id: None,
- body,
- };
- let result = client
- .bounties
- .comment(&bounty_id, &request)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_bounties_list_comments(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let bounty_id = req_str(&params, "bountyId")?.to_string();
- log::debug!("{LOG_PREFIX} bounties_list_comments bounty_id={bounty_id}");
- let query_params: Option<tinyplace::types::BountyCommentQueryParams> = params
- .get("params")
- .and_then(|v| if v.is_null() { None } else { Some(v) })
- .map(|v| {
- serde_json::from_value(v.clone())
- .map_err(|e| format!("invalid bounties list_comments params: {e}"))
- })
- .transpose()?;
- let client = global_state().client().await?;
- match client
- .bounties
- .list_comments(&bounty_id, query_params.as_ref())
- .await
- {
- Ok(result) => to_value(result),
- Err(e) => match bounties_comments_degrade(&e) {
- Some(empty) => {
- log::debug!("{LOG_PREFIX} bounties_list_comments degrade -> empty: {e}");
- to_value(empty)
- }
- None => Err(map_err(e)),
- },
- }
- })
-}
-
-pub(crate) fn handle_tinyplace_bounties_run_council(
- params: Map<String, Value>,
-) -> ControllerFuture {
- Box::pin(async move {
- let bounty_id = req_str(&params, "bountyId")?.to_string();
- log::debug!("{LOG_PREFIX} bounties_run_council bounty_id={bounty_id}");
- let client = global_state().client().await?;
- // ANTI-SPOOF: actor resolved from signer, never from params.
- let signer = client
- .http()
- .signer()
- .ok_or("tiny.place signer unavailable; unlock your wallet")?;
- let actor = signer.agent_id();
- let result = client
- .bounties
- .run_council(&bounty_id, &actor)
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-pub(crate) fn handle_tinyplace_bounties_approve(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let bounty_id = req_str(&params, "bountyId")?.to_string();
- let submission_id = get_opt_str(&params, "submissionId").map(|s| s.to_string());
- log::debug!(
- "{LOG_PREFIX} bounties_approve bounty_id={bounty_id} \
- submission_id={submission_id:?}"
- );
- let client = global_state().client().await?;
- // NOTE: approve uses post_admin auth on the SDK side. The backend
- // enforces the admin gate. If the caller is not an admin, the backend
- // rejects with 403. The v1 UI hides this button entirely.
- let result = client
- .bounties
- .approve(&bounty_id, submission_id.as_deref())
- .await
- .map_err(map_err)?;
- to_value(result)
- })
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use futures::executor::block_on;
-
- /// A missing/blank `username` is rejected before any client/network work.
- #[test]
- fn register_requires_username() {
- let err = block_on(handle_tinyplace_registry_register(Map::new())).unwrap_err();
- assert!(err.contains("username"), "got: {err}");
-
- let mut params = Map::new();
- params.insert("username".to_string(), Value::String(" ".to_string()));
- let err = block_on(handle_tinyplace_registry_register(params)).unwrap_err();
- assert!(err.contains("username"), "got: {err}");
- }
-
- /// #4929: transfer rejects a missing/blank `name` or `recipient` before any
- /// client/network work — the destructive path never runs on bad input.
- #[test]
- fn transfer_requires_name_and_recipient() {
- // Missing name.
- let err = block_on(handle_tinyplace_registry_transfer(Map::new())).unwrap_err();
- assert!(err.contains("name"), "got: {err}");
-
- // A bare "@" normalizes to an empty name and is rejected before any
- // client/network work (the destructive path never runs).
- let mut params = Map::new();
- params.insert("name".to_string(), Value::String("@".to_string()));
- params.insert("recipient".to_string(), Value::String("bravo".to_string()));
- let err = block_on(handle_tinyplace_registry_transfer(params)).unwrap_err();
- assert!(err.contains("name"), "got: {err}");
-
- // Name present, recipient missing.
- let mut params = Map::new();
- params.insert("name".to_string(), Value::String("alpha".to_string()));
- let err = block_on(handle_tinyplace_registry_transfer(params)).unwrap_err();
- assert!(err.contains("recipient"), "got: {err}");
-
- // Name present, recipient blank → still rejected.
- let mut params = Map::new();
- params.insert("name".to_string(), Value::String("alpha".to_string()));
- params.insert("recipient".to_string(), Value::String(" ".to_string()));
- let err = block_on(handle_tinyplace_registry_transfer(params)).unwrap_err();
- assert!(err.contains("recipient"), "got: {err}");
- }
-
- /// #4929: transfer eligibility fails closed when the registry omits the
- /// primary flag; only an explicit `false` may reach the destructive path.
- #[test]
- fn transfer_requires_explicit_non_primary_state() {
- assert!(!transfer_allowed_by_primary_state(None));
- assert!(!transfer_allowed_by_primary_state(Some(true)));
- assert!(transfer_allowed_by_primary_state(Some(false)));
- }
-
- // ── #4998 destructive-path coverage (B1 read-back, M1 idempotency, M2
- // recipient validation) — the pure policy helpers the async handler
- // delegates to, so the irreversible-transfer decisions are unit-tested. ──
-
- fn test_identity(
- crypto_id: &str,
- status: &str,
- primary: Option<bool>,
- ) -> tinyplace::types::Identity {
- tinyplace::types::Identity {
- username: "handle".to_string(),
- crypto_id: crypto_id.to_string(),
- public_key: if crypto_id.is_empty() {
- String::new()
- } else {
- "pubkey".to_string()
- },
- registered_at: String::new(),
- expires_at: String::new(),
- status: status.to_string(),
- registration_tx: None,
- payment_methods: None,
- primary,
- subnames: None,
- signature: None,
- payment: None,
- last_renewal_tx: None,
- updated_at: String::new(),
- }
- }
-
- fn availability(
- available: bool,
- identity: Option<tinyplace::types::Identity>,
- ) -> tinyplace::types::AvailabilityResponse {
- tinyplace::types::AvailabilityResponse {
- available,
- name: "@handle".to_string(),
- identity,
- lifecycle: None,
- }
- }
-
- /// M2: a recipient whose name is currently `available` (free / released) is
- /// refused even if a stale `identity` record is attached — never transfer to
- /// a wallet the recipient may no longer control at that @handle.
- #[test]
- fn recipient_available_is_refused() {
- let avail = availability(
- true,
- Some(test_identity("recipientCid", "active", Some(false))),
- );
- let err = validate_recipient_availability(&avail).unwrap_err();
- assert!(err.contains("not currently registered"), "got: {err}");
- }
-
- /// M2: a recipient with no identity record at all fails closed.
- #[test]
- fn recipient_missing_identity_is_refused() {
- let err = validate_recipient_availability(&availability(false, None)).unwrap_err();
- assert!(err.contains("not registered on tiny.place"), "got: {err}");
- }
-
- /// M2: an EXPIRED recipient identity (stale owner record before release) is
- /// refused — case-insensitively.
- #[test]
- fn recipient_expired_status_is_refused() {
- for status in ["expired", "EXPIRED", "Expired"] {
- let avail = availability(
- false,
- Some(test_identity("recipientCid", status, Some(false))),
- );
- let err = validate_recipient_availability(&avail).unwrap_err();
- assert!(err.contains("expired"), "status {status} → {err}");
- }
- }
-
- /// M2: a recipient missing key material can't be transferred to safely.
- #[test]
- fn recipient_missing_key_material_is_refused() {
- let avail = availability(false, Some(test_identity("", "active", Some(false))));
- let err = validate_recipient_availability(&avail).unwrap_err();
- assert!(err.contains("missing key material"), "got: {err}");
- }
-
- /// A live, registered recipient resolves to its (cryptoId, publicKey).
- #[test]
- fn recipient_live_resolves_key_material() {
- let avail = availability(
- false,
- Some(test_identity("recipientCid", "active", Some(false))),
- );
- let (cid, pk) = validate_recipient_availability(&avail).unwrap();
- assert_eq!(cid, "recipientCid");
- assert_eq!(pk, "pubkey");
- }
-
- /// M1 idempotency: when the sender's own handle ALREADY reads back as the
- /// recipient (a retry after a lost-but-applied POST), the preflight
- /// short-circuits and must NOT re-sign.
- #[test]
- fn preflight_already_transferred_short_circuits() {
- let own = availability(
- false,
- Some(test_identity("recipientCid", "active", Some(false))),
- );
- assert_eq!(
- preflight_own_handle(&own, "recipientCid"),
- OwnHandlePreflight::AlreadyTransferred
- );
- }
-
- /// M2 tail: a nonexistent own-handle gets the right diagnosis, NOT the
- /// "mark it non-primary" message.
- #[test]
- fn preflight_unregistered_own_handle_is_distinct() {
- match preflight_own_handle(&availability(true, None), "recipientCid") {
- OwnHandlePreflight::Reject(msg) => {
- assert!(msg.contains("not registered"), "got: {msg}");
- assert!(
- !msg.contains("primary"),
- "must not misdiagnose as primary: {msg}"
- );
- }
- other => panic!("expected Reject, got {other:?}"),
- }
- }
-
- /// A primary (active) own-handle is rejected before signing.
- #[test]
- fn preflight_primary_handle_is_rejected() {
- let own = availability(false, Some(test_identity("ownerCid", "active", Some(true))));
- match preflight_own_handle(&own, "recipientCid") {
- OwnHandlePreflight::Reject(msg) => assert!(msg.contains("active"), "got: {msg}"),
- other => panic!("expected Reject, got {other:?}"),
- }
- // Missing primary flag also fails closed.
- let own_none = availability(false, Some(test_identity("ownerCid", "active", None)));
- assert!(matches!(
- preflight_own_handle(&own_none, "recipientCid"),
- OwnHandlePreflight::Reject(_)
- ));
- }
-
- /// A non-primary own-handle owned by someone other than the recipient
- /// proceeds to signing.
- #[test]
- fn preflight_non_primary_proceeds() {
- let own = availability(
- false,
- Some(test_identity("ownerCid", "active", Some(false))),
- );
- assert_eq!(
- preflight_own_handle(&own, "recipientCid"),
- OwnHandlePreflight::Proceed
- );
- }
-
- /// B1: the read-back confirms ONLY when the registry returns a non-empty
- /// owner equal to the recipient. An empty owner (enveloped/renamed/partial
- /// body, or a failed read) is "unconfirmed" — never a claim the transfer
- /// didn't happen.
- #[test]
- fn readback_confirms_only_on_matching_nonempty_owner() {
- assert_eq!(
- classify_transfer_readback("recipientCid", "recipientCid"),
- TransferReadback::Confirmed
- );
- // Empty owner (default-deserialized crypto_id "" from an enveloped body).
- assert_eq!(
- classify_transfer_readback("", "recipientCid"),
- TransferReadback::Unconfirmed
- );
- // Owner reads back as someone else.
- assert_eq!(
- classify_transfer_readback("otherCid", "recipientCid"),
- TransferReadback::Unconfirmed
- );
- // Defensive: an empty recipient never vacuously confirms on an empty read.
- assert_eq!(
- classify_transfer_readback("", ""),
- TransferReadback::Unconfirmed
- );
- }
-
- /// A self-transfer is rejected before any network/signing work.
- #[test]
- fn transfer_rejects_self_transfer() {
- let mut params = Map::new();
- params.insert("name".to_string(), Value::String("@alpha".to_string()));
- params.insert("recipient".to_string(), Value::String("alpha".to_string()));
- let err = block_on(handle_tinyplace_registry_transfer(params)).unwrap_err();
- assert!(err.contains("itself"), "got: {err}");
- }
-
- /// Buy handlers reject a missing/blank `id` before any client/network work.
- #[test]
- fn buy_handlers_require_id() {
- for handler in [
- handle_tinyplace_marketplace_buy_product as fn(Map<String, Value>) -> ControllerFuture,
- handle_tinyplace_marketplace_buy_identity,
- ] {
- let err = block_on(handler(Map::new())).unwrap_err();
- assert!(err.contains("'id'"), "got: {err}");
-
- let mut params = Map::new();
- params.insert("id".to_string(), Value::String(" ".to_string()));
- let err = block_on(handler(params)).unwrap_err();
- assert!(err.contains("'id'"), "got: {err}");
- }
- }
-
- /// Bid/offer handlers validate their required params before any network work.
- #[test]
- fn bid_offer_validate_params() {
- // bid: missing listingId.
- let err = block_on(handle_tinyplace_marketplace_bid(Map::new())).unwrap_err();
- assert!(err.contains("listingId"), "got: {err}");
- // bid: listingId present but amount missing.
- let mut p = Map::new();
- p.insert("listingId".to_string(), Value::String("l1".into()));
- let err = block_on(handle_tinyplace_marketplace_bid(p)).unwrap_err();
- assert!(err.contains("amount"), "got: {err}");
- // offer: missing name.
- let err = block_on(handle_tinyplace_marketplace_offer(Map::new())).unwrap_err();
- assert!(err.contains("name"), "got: {err}");
- }
-
- #[test]
- fn price_from_params_defaults_asset_and_requires_network() {
- let mut p = Map::new();
- p.insert("amount".to_string(), Value::String("100".into()));
- // network missing → Err.
- assert!(price_from_params(&p).unwrap_err().contains("network"));
- // network present → defaults asset to USDC.
- p.insert("network".to_string(), Value::String("solana-devnet".into()));
- let price = price_from_params(&p).unwrap();
- assert_eq!(price.amount, "100");
- assert_eq!(price.asset, "USDC");
- assert_eq!(price.network, "solana-devnet");
- // explicit asset is honoured.
- p.insert("asset".to_string(), Value::String("SOL".into()));
- assert_eq!(price_from_params(&p).unwrap().asset, "SOL");
- }
-
- /// #4202: the confirm-card balance must be read from tiny.place's own Solana
- /// settlement RPC (the chain where agent token accounts are funded), not the
- /// bare public cluster RPC. We point `TINYPLACE_SOLANA_RPC_URL` at a mock
- /// that answers `getTokenAccountsByOwner`; the balance must come back as
- /// `Some` with the parsed USDC amount. Before the fix `wallet_usdc_balance`
- /// queried the public cluster directly and ignored this endpoint, so the
- /// confirm card showed "Unknown".
- // `wallet_usdc_balance` resolves the USDC mint and RPC endpoints through
- // `crate::openhuman::web3::wallet`, which the `web3` stub disables — so without
- // the feature the balance is unconditionally None and this test asserts a
- // capability that is not compiled in.
- #[cfg(feature = "web3")]
- #[tokio::test]
- async fn wallet_usdc_balance_reads_from_tinyplace_settlement_rpc() {
- let _lock = crate::openhuman::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
-
- let app = axum::Router::new().route(
- "/",
- axum::routing::post(|| async {
- axum::Json(serde_json::json!({
- "jsonrpc": "2.0",
- "id": 1,
- "result": {
- "context": { "slot": 1 },
- "value": [{
- "account": { "data": { "parsed": { "info": { "tokenAmount": {
- "amount": "12500000",
- "decimals": 6,
- "uiAmount": 12.5,
- "uiAmountString": "12.5"
- }}}}}
- }]
- }
- }))
- }),
- );
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
- let url = format!("http://127.0.0.1:{}/", addr.port());
-
- unsafe {
- std::env::set_var("TINYPLACE_SOLANA_RPC_URL", &url);
- }
- let (balance, address) = wallet_usdc_balance("OwnerAddr1111111111").await;
- unsafe {
- std::env::remove_var("TINYPLACE_SOLANA_RPC_URL");
- }
-
- assert_eq!(address, "OwnerAddr1111111111");
- let balance = balance.expect("balance must resolve from the tiny.place settlement RPC");
- assert_eq!(
- balance.get("formatted").and_then(Value::as_str),
- Some("12.5")
- );
- assert_eq!(
- balance.get("assetSymbol").and_then(Value::as_str),
- Some("USDC")
- );
- assert_eq!(balance.get("decimals").and_then(Value::as_u64), Some(6));
- }
-
- // ── GraphQL Feed handler param validation ────────────────────────────────
-
- /// graphql_posts requires `handle`.
- #[test]
- fn graphql_posts_requires_handle() {
- let err = block_on(handle_tinyplace_graphql_posts(Map::new())).unwrap_err();
- assert!(err.contains("handle"), "got: {err}");
- }
-
- /// graphql_post requires `handle` and `postId`.
- #[test]
- fn graphql_post_requires_handle_and_post_id() {
- let err = block_on(handle_tinyplace_graphql_post(Map::new())).unwrap_err();
- assert!(err.contains("handle"), "got: {err}");
-
- let mut p = Map::new();
- p.insert("handle".to_string(), Value::String("alice".into()));
- let err = block_on(handle_tinyplace_graphql_post(p)).unwrap_err();
- assert!(err.contains("postId"), "got: {err}");
- }
-
- /// graphql_post_comments requires `postId`.
- #[test]
- fn graphql_post_comments_requires_post_id() {
- let err = block_on(handle_tinyplace_graphql_post_comments(Map::new())).unwrap_err();
- assert!(err.contains("postId"), "got: {err}");
- }
-
- /// graphql_post_likers requires `postId`.
- #[test]
- fn graphql_post_likers_requires_post_id() {
- let err = block_on(handle_tinyplace_graphql_post_likers(Map::new())).unwrap_err();
- assert!(err.contains("postId"), "got: {err}");
- }
-
- /// graphql_home_feed has no required params — it should fail at
- /// global_state/client initialization (no wallet in unit tests),
- /// NOT at param extraction.
- #[test]
- fn graphql_home_feed_fails_at_client_not_params() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- let err = rt
- .block_on(handle_tinyplace_graphql_home_feed(Map::new()))
- .unwrap_err();
- assert!(!err.contains("missing required param"), "got: {err}");
- }
-
- /// Degrade helpers return empty results for Serialization errors, and
- /// propagate non-serialization errors (InvalidArgument).
- #[test]
- fn graphql_degrade_helpers_return_empty_on_serialization() {
- // Construct a real serde_json::Error by deserializing invalid JSON.
- let raw_ser_err: serde_json::Error =
- serde_json::from_str::<serde_json::Value>("{invalid json}").unwrap_err();
- let ser_err = tinyplace::Error::Serialization(raw_ser_err);
- assert!(graphql_home_feed_degrade(&ser_err).is_some());
- assert!(graphql_posts_degrade(&ser_err).is_some());
-
- // Non-serialization errors should NOT be degraded.
- let other = tinyplace::Error::InvalidArgument("bad arg".into());
- assert!(graphql_home_feed_degrade(&other).is_none());
- assert!(graphql_posts_degrade(&other).is_none());
- }
-
- /// graphql_ledger_transaction requires `id`.
- #[test]
- fn graphql_ledger_transaction_requires_id() {
- let err = block_on(handle_tinyplace_graphql_ledger_transaction(Map::new())).unwrap_err();
- assert!(err.contains("id"), "got: {err}");
- }
-
- /// graphql_ledger_transactions has no required params — should fail at
- /// client init (no wallet in unit tests), NOT at param extraction.
- #[test]
- fn graphql_ledger_transactions_fails_at_client_not_params() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- let err = rt
- .block_on(handle_tinyplace_graphql_ledger_transactions(Map::new()))
- .unwrap_err();
- assert!(!err.contains("missing required param"), "got: {err}");
- }
-
- /// Degrade helper returns empty for Serialization errors.
- #[test]
- fn graphql_ledger_degrade_returns_empty_on_serialization() {
- let raw_ser_err: serde_json::Error =
- serde_json::from_str::<serde_json::Value>("{invalid json}").unwrap_err();
- let ser_err = tinyplace::Error::Serialization(raw_ser_err);
- assert!(graphql_ledger_transactions_degrade(&ser_err).is_some());
-
- let other = tinyplace::Error::InvalidArgument("bad arg".into());
- assert!(graphql_ledger_transactions_degrade(&other).is_none());
- }
-
- // ── GraphQL Jobs handler param validation ───────────────────────────────
-
- /// graphql_jobs has no required params — should fail at
- /// client init (no wallet in unit tests), NOT at param extraction.
- #[test]
- fn graphql_jobs_fails_at_client_not_params() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- let err = rt
- .block_on(handle_tinyplace_graphql_jobs(Map::new()))
- .unwrap_err();
- assert!(!err.contains("missing required param"), "got: {err}");
- }
-
- /// graphql_job requires `id`.
- #[test]
- fn graphql_job_requires_id() {
- let err = block_on(handle_tinyplace_graphql_job(Map::new())).unwrap_err();
- assert!(err.contains("id"), "got: {err}");
- }
-
- /// Degrade helper returns empty for Serialization errors.
- #[test]
- fn graphql_jobs_degrade_returns_empty_on_serialization() {
- let raw_ser_err: serde_json::Error =
- serde_json::from_str::<serde_json::Value>("{invalid json}").unwrap_err();
- let ser_err = tinyplace::Error::Serialization(raw_ser_err);
- assert!(graphql_jobs_degrade(&ser_err).is_some());
-
- let other = tinyplace::Error::InvalidArgument("bad arg".into());
- assert!(graphql_jobs_degrade(&other).is_none());
- }
-
- #[test]
- fn settlement_retry_only_on_confirming_402s() {
- // Retryable: 402 with a settlement-timing message.
- assert!(settlement_error_is_retryable(
- Some(402),
- "Transaction not found on chain yet"
- ));
- assert!(settlement_error_is_retryable(
- Some(402),
- "payment pending: insufficient confirmations"
- ));
- // Not retryable: non-402, or a 402 with an unrelated/hard message.
- assert!(!settlement_error_is_retryable(
- Some(400),
- "transaction not found"
- ));
- assert!(!settlement_error_is_retryable(
- Some(402),
- "handle already taken"
- ));
- assert!(!settlement_error_is_retryable(None, "transport error"));
- }
-
- /// Follow/unfollow handlers reject a missing `agentId` before any client work.
- #[test]
- fn follows_handlers_require_agent_id() {
- for handler in [
- handle_tinyplace_follows_follow as fn(Map<String, Value>) -> ControllerFuture,
- handle_tinyplace_follows_unfollow,
- handle_tinyplace_follows_followers,
- handle_tinyplace_follows_following,
- handle_tinyplace_follows_stats,
- ] {
- let err = block_on(handler(Map::new())).unwrap_err();
- assert!(err.contains("agentId"), "got: {err}");
- }
- }
-
- /// Contact write/status handlers reject a missing or blank peer id before
- /// wallet/client initialization.
- #[test]
- fn contacts_handlers_require_agent_id() {
- for handler in [
- handle_tinyplace_contacts_request as fn(Map<String, Value>) -> ControllerFuture,
- handle_tinyplace_contacts_accept,
- handle_tinyplace_contacts_remove,
- handle_tinyplace_contacts_block,
- handle_tinyplace_contacts_unblock,
- handle_tinyplace_contacts_status,
- ] {
- let err = block_on(handler(Map::new())).unwrap_err();
- assert!(err.contains("agentId"), "got: {err}");
-
- let mut params = Map::new();
- params.insert("agentId".to_string(), Value::String(" ".to_string()));
- let err = block_on(handler(params)).unwrap_err();
- assert!(err.contains("agentId"), "got: {err}");
- }
- }
-
- #[test]
- fn contacts_path_segments_are_encoded() {
- assert_eq!(
- contact_path("agent/with space", Some("status")),
- "/contacts/agent%2Fwith%20space/status"
- );
- }
-
- #[test]
- fn contacts_query_accepts_nested_or_top_level_pagination() {
- let mut nested = Map::new();
- nested.insert(
- "params".to_string(),
- serde_json::json!({ "limit": 20, "offset": 40 }),
- );
- assert_eq!(
- contact_query(&nested),
- vec![
- ("limit".to_string(), "20".to_string()),
- ("offset".to_string(), "40".to_string())
- ]
- );
-
- let mut top_level = Map::new();
- top_level.insert("limit".to_string(), Value::Number(10.into()));
- assert_eq!(
- contact_query(&top_level),
- vec![("limit".to_string(), "10".to_string())]
- );
- }
-
- /// registry_export rejects a missing `name` before any client work.
- #[test]
- fn registry_export_requires_name() {
- let err = block_on(handle_tinyplace_registry_export(Map::new())).unwrap_err();
- assert!(err.contains("name"), "got: {err}");
- }
-
- /// Feedback get/vote handlers reject missing required params before any client work.
- #[test]
- fn feedback_handlers_require_params() {
- // feedback_get requires feedbackId.
- let err = block_on(handle_tinyplace_feedback_get(Map::new())).unwrap_err();
- assert!(err.contains("feedbackId"), "got: {err}");
-
- // feedback_vote requires feedbackId.
- let err = block_on(handle_tinyplace_feedback_vote(Map::new())).unwrap_err();
- assert!(err.contains("feedbackId"), "got: {err}");
-
- // feedback_vote requires vote (feedbackId present but vote missing).
- let mut p = Map::new();
- p.insert("feedbackId".to_string(), Value::String("fb-1".into()));
- let err = block_on(handle_tinyplace_feedback_vote(p)).unwrap_err();
- assert!(err.contains("vote"), "got: {err}");
-
- // feedback_vote rejects invalid vote value.
- let mut p = Map::new();
- p.insert("feedbackId".to_string(), Value::String("fb-1".into()));
- p.insert("vote".to_string(), Value::String("sideways".into()));
- let err = block_on(handle_tinyplace_feedback_vote(p)).unwrap_err();
- assert!(err.contains("must be 'up' or 'down'"), "got: {err}");
-
- // feedback_create requires title.
- let err = block_on(handle_tinyplace_feedback_create(Map::new())).unwrap_err();
- assert!(err.contains("title"), "got: {err}");
-
- // feedback_create requires description (title present but description missing).
- let mut p = Map::new();
- p.insert("title".to_string(), Value::String("A great idea".into()));
- let err = block_on(handle_tinyplace_feedback_create(p)).unwrap_err();
- assert!(err.contains("description"), "got: {err}");
-
- // feedback_create rejects blank title.
- let mut p = Map::new();
- p.insert("title".to_string(), Value::String(" ".into()));
- let err = block_on(handle_tinyplace_feedback_create(p)).unwrap_err();
- assert!(err.contains("title"), "got: {err}");
- }
-
- /// Groups invite/role handlers reject missing required params before any client work.
- #[test]
- fn groups_invite_handlers_require_params() {
- // set_member_role requires groupId, agentId, role.
- let err = block_on(handle_tinyplace_groups_set_member_role(Map::new())).unwrap_err();
- assert!(err.contains("groupId"), "got: {err}");
-
- let mut p = Map::new();
- p.insert("groupId".to_string(), Value::String("g-1".into()));
- let err = block_on(handle_tinyplace_groups_set_member_role(p)).unwrap_err();
- assert!(err.contains("agentId"), "got: {err}");
-
- let mut p = Map::new();
- p.insert("groupId".to_string(), Value::String("g-1".into()));
- p.insert("agentId".to_string(), Value::String("agent-1".into()));
- let err = block_on(handle_tinyplace_groups_set_member_role(p)).unwrap_err();
- assert!(err.contains("role"), "got: {err}");
-
- // create_invite requires groupId.
- let err = block_on(handle_tinyplace_groups_create_invite(Map::new())).unwrap_err();
- assert!(err.contains("groupId"), "got: {err}");
-
- // list_invites requires groupId.
- let err = block_on(handle_tinyplace_groups_list_invites(Map::new())).unwrap_err();
- assert!(err.contains("groupId"), "got: {err}");
-
- // preview_invite requires groupId and token.
- let err = block_on(handle_tinyplace_groups_preview_invite(Map::new())).unwrap_err();
- assert!(err.contains("groupId"), "got: {err}");
-
- let mut p = Map::new();
- p.insert("groupId".to_string(), Value::String("g-1".into()));
- let err = block_on(handle_tinyplace_groups_preview_invite(p)).unwrap_err();
- assert!(err.contains("token"), "got: {err}");
-
- // revoke_invite requires groupId and token.
- let err = block_on(handle_tinyplace_groups_revoke_invite(Map::new())).unwrap_err();
- assert!(err.contains("groupId"), "got: {err}");
-
- let mut p = Map::new();
- p.insert("groupId".to_string(), Value::String("g-1".into()));
- let err = block_on(handle_tinyplace_groups_revoke_invite(p)).unwrap_err();
- assert!(err.contains("token"), "got: {err}");
-
- // redeem_invite requires groupId and token.
- let err = block_on(handle_tinyplace_groups_redeem_invite(Map::new())).unwrap_err();
- assert!(err.contains("groupId"), "got: {err}");
-
- let mut p = Map::new();
- p.insert("groupId".to_string(), Value::String("g-1".into()));
- let err = block_on(handle_tinyplace_groups_redeem_invite(p)).unwrap_err();
- assert!(err.contains("token"), "got: {err}");
- }
-
- /// Email verification handlers validate required params before any client work.
- #[test]
- fn email_verification_handlers_require_params() {
- // start requires cryptoId.
- let err =
- block_on(handle_tinyplace_users_start_email_verification(Map::new())).unwrap_err();
- assert!(err.contains("cryptoId"), "got: {err}");
-
- // start requires email (cryptoId present but email missing).
- let mut p = Map::new();
- p.insert("cryptoId".to_string(), Value::String("wallet-1".into()));
- let err = block_on(handle_tinyplace_users_start_email_verification(p)).unwrap_err();
- assert!(err.contains("email"), "got: {err}");
-
- // start rejects blank email.
- let mut p = Map::new();
- p.insert("cryptoId".to_string(), Value::String("wallet-1".into()));
- p.insert("email".to_string(), Value::String(" ".into()));
- let err = block_on(handle_tinyplace_users_start_email_verification(p)).unwrap_err();
- assert!(err.contains("email"), "got: {err}");
-
- // confirm requires cryptoId.
- let err =
- block_on(handle_tinyplace_users_confirm_email_verification(Map::new())).unwrap_err();
- assert!(err.contains("cryptoId"), "got: {err}");
-
- // confirm requires email (cryptoId present but email missing).
- let mut p = Map::new();
- p.insert("cryptoId".to_string(), Value::String("wallet-1".into()));
- let err = block_on(handle_tinyplace_users_confirm_email_verification(p)).unwrap_err();
- assert!(err.contains("email"), "got: {err}");
-
- // confirm requires code (cryptoId + email present but code missing).
- let mut p = Map::new();
- p.insert("cryptoId".to_string(), Value::String("wallet-1".into()));
- p.insert(
- "email".to_string(),
- Value::String("[email protected]".into()),
- );
- let err = block_on(handle_tinyplace_users_confirm_email_verification(p)).unwrap_err();
- assert!(err.contains("code"), "got: {err}");
-
- // confirm rejects blank code.
- let mut p = Map::new();
- p.insert("cryptoId".to_string(), Value::String("wallet-1".into()));
- p.insert(
- "email".to_string(),
- Value::String("[email protected]".into()),
- );
- p.insert("code".to_string(), Value::String(" ".into()));
- let err = block_on(handle_tinyplace_users_confirm_email_verification(p)).unwrap_err();
- assert!(err.contains("code"), "got: {err}");
- }
-
- /// solana_call rejects a missing/blank `method` before any client work.
- #[test]
- fn solana_call_requires_method() {
- let err = block_on(handle_tinyplace_solana_call(Map::new())).unwrap_err();
- assert!(err.contains("method"), "got: {err}");
-
- let mut params = Map::new();
- params.insert("method".to_string(), Value::String(" ".to_string()));
- let err = block_on(handle_tinyplace_solana_call(params)).unwrap_err();
- assert!(err.contains("method"), "got: {err}");
- }
-
- /// streams_start rejects a missing/blank streamType.
- #[test]
- fn streams_start_requires_stream_type() {
- let err = block_on(handle_tinyplace_streams_start(Map::new())).unwrap_err();
- assert!(err.contains("streamType"), "got: {err}");
-
- let mut params = Map::new();
- params.insert("streamType".to_string(), Value::String(" ".to_string()));
- let err = block_on(handle_tinyplace_streams_start(params)).unwrap_err();
- assert!(err.contains("streamType"), "got: {err}");
- }
-
- /// streams_start rejects an unsupported streamType.
- #[test]
- fn streams_start_rejects_unknown_type() {
- let mut params = Map::new();
- params.insert(
- "streamType".to_string(),
- Value::String("unknown".to_string()),
- );
- let err = block_on(handle_tinyplace_streams_start(params)).unwrap_err();
- assert!(err.contains("unsupported streamType"), "got: {err}");
- }
-
- /// streams_start rejects a conversation stream without a streamId.
- #[test]
- fn streams_start_conversation_requires_stream_id() {
- let mut params = Map::new();
- params.insert(
- "streamType".to_string(),
- Value::String("conversation".to_string()),
- );
- let err = block_on(handle_tinyplace_streams_start(params)).unwrap_err();
- assert!(err.contains("streamId"), "got: {err}");
- }
-
- /// streams_start rejects a feed stream without a streamId (the feed handle).
- /// Regression for #4926: "feed" is a valid streamType but, like
- /// "conversation", it is target-scoped and must carry a streamId.
- #[test]
- fn streams_start_feed_requires_stream_id() {
- let mut params = Map::new();
- params.insert("streamType".to_string(), Value::String("feed".to_string()));
- let err = block_on(handle_tinyplace_streams_start(params)).unwrap_err();
- assert!(err.contains("streamId"), "got: {err}");
- // And it must NOT be rejected as an unsupported streamType.
- assert!(!err.contains("unsupported"), "got: {err}");
- }
-
- /// streams_stop rejects a missing/blank streamId.
- #[test]
- fn streams_stop_requires_stream_id() {
- let err = block_on(handle_tinyplace_streams_stop(Map::new())).unwrap_err();
- assert!(err.contains("streamId"), "got: {err}");
-
- let mut params = Map::new();
- params.insert("streamId".to_string(), Value::String(" ".to_string()));
- let err = block_on(handle_tinyplace_streams_stop(params)).unwrap_err();
- assert!(err.contains("streamId"), "got: {err}");
- }
-
- /// `signal_provision` has no required params; it must fail at `global_signal_store`
- /// (wallet/config not available in unit tests), NOT at param extraction.
- /// Uses a Tokio runtime because `global_signal_store` internally calls
- /// `load_config_with_timeout` which requires Tokio.
- #[test]
- fn signal_provision_fails_at_store_not_params() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- let err = rt
- .block_on(handle_tinyplace_signal_provision(Map::new()))
- .unwrap_err();
- assert!(!err.contains("missing required param"), "got: {err}");
- }
-
- /// `signal_upload_pre_keys` has no required params; same as above.
- #[test]
- fn signal_upload_pre_keys_fails_at_store_not_params() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- let err = rt
- .block_on(handle_tinyplace_signal_upload_pre_keys(Map::new()))
- .unwrap_err();
- assert!(!err.contains("missing required param"), "got: {err}");
- }
-
- /// `signal_rotate_signed_pre_key` has no required params; same as above.
- #[test]
- fn signal_rotate_fails_at_store_not_params() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- let err = rt
- .block_on(handle_tinyplace_signal_rotate_signed_pre_key(Map::new()))
- .unwrap_err();
- assert!(!err.contains("missing required param"), "got: {err}");
- }
-
- /// `signal_key_status` has no required params; same as above.
- #[test]
- fn signal_key_status_fails_at_store_not_params() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- let err = rt
- .block_on(handle_tinyplace_signal_key_status(Map::new()))
- .unwrap_err();
- assert!(!err.contains("missing required param"), "got: {err}");
- }
-
- // ── looks_like_base58_pubkey heuristic ───────────────────────────────────
-
- #[test]
- fn base58_pubkey_heuristic_accepts_valid_keys() {
- // 44-char base58 string using all valid alphabet chars
- assert!(
- looks_like_base58_pubkey("61KcG5aGLqpnJz2fXyzABCDEFGHJKLMNPQRSTUVWXY"),
- "44-char valid base58 must match"
- );
- // 32-char minimum
- assert!(
- looks_like_base58_pubkey("11111111111111111111111111111111"),
- "32-char all-1s must match (system program)"
- );
- }
-
- #[test]
- fn base58_pubkey_heuristic_rejects_handles_and_invalid() {
- assert!(
- !looks_like_base58_pubkey("@alice"),
- "@ prefix must not match"
- );
- assert!(
- !looks_like_base58_pubkey("alice"),
- "too short to be a pubkey"
- );
- assert!(!looks_like_base58_pubkey(""), "empty must not match");
- // Contains '!' which is outside the base58 alphabet
- assert!(
- !looks_like_base58_pubkey("61KcG5aGLqpn!Jz2fXyzABCDEFGHJKLMNPQRSTUVWX"),
- "invalid char must not match"
- );
- // Contains '0' which is NOT in base58 (confused with 'O')
- assert!(
- !looks_like_base58_pubkey("61KcG5aGLqpnJz2fXyzABCDEFGHJKLMNPQRS0UVWXY"),
- "zero char not in base58 alphabet"
- );
- }
-
- #[test]
- fn base58_pubkey_heuristic_rejects_45_char_string() {
- // 45 chars is too long for a 32-byte base58 pubkey (valid range is 32..=44)
- let s = "61KcG5aGLqpnJz2fXyzABCDEFGHJKLMNPQRSTUVWXYZ12";
- assert_eq!(s.len(), 45, "test fixture must be exactly 45 chars");
- assert!(
- !looks_like_base58_pubkey(s),
- "45-char string must not match"
- );
- }
-
- /// `signal_get_bundle` rejects a missing `agentId` before any resolution.
- #[test]
- fn signal_get_bundle_requires_agent_id() {
- let err = block_on(handle_tinyplace_signal_get_bundle(Map::new())).unwrap_err();
- assert!(err.contains("agentId"), "got: {err}");
- }
-
- #[test]
- fn signal_send_requires_recipient_and_plaintext() {
- let mut params = Map::new();
- params.insert("plaintext".into(), Value::String("hello".into()));
- let err = block_on(handle_tinyplace_signal_send_message(params)).unwrap_err();
- assert!(err.contains("recipient"), "got: {err}");
- let mut params = Map::new();
- params.insert("recipient".into(), Value::String("peer123".into()));
- let err = block_on(handle_tinyplace_signal_send_message(params)).unwrap_err();
- assert!(err.contains("plaintext"), "got: {err}");
- }
-
- #[test]
- fn signal_decrypt_requires_envelope() {
- let err = block_on(handle_tinyplace_signal_decrypt_message(Map::new())).unwrap_err();
- assert!(err.contains("envelope"), "got: {err}");
- }
-
- #[test]
- fn messages_list_fails_at_client_not_params() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- let err = rt
- .block_on(handle_tinyplace_messages_list(Map::new()))
- .unwrap_err();
- assert!(!err.contains("missing required param"), "got: {err}");
- }
-
- #[test]
- fn messages_acknowledge_requires_message_id() {
- let err = block_on(handle_tinyplace_messages_acknowledge(Map::new())).unwrap_err();
- assert!(err.contains("messageId"), "got: {err}");
- }
-
- #[test]
- fn signal_send_never_sends_plaintext_on_encryption_failure() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- let mut params = Map::new();
- params.insert("recipient".into(), Value::String("test_peer".into()));
- params.insert("plaintext".into(), Value::String("secret message".into()));
- let err = rt
- .block_on(handle_tinyplace_signal_send_message(params))
- .unwrap_err();
- assert!(!err.contains("missing required param"), "got: {err}");
- assert!(
- !err.contains("secret message"),
- "plaintext leaked in error message: {err}"
- );
- }
-
- // ── Encryption key registration + discovery (0D) ─────────────────────────
-
- #[test]
- fn directory_find_by_encryption_key_requires_param() {
- let err =
- block_on(handle_tinyplace_directory_find_by_encryption_key(Map::new())).unwrap_err();
- assert!(err.contains("encryptionKey"), "got: {err}");
- }
-
- /// Verify the register handler has no required params: an empty `Map` must
- /// never produce a missing-param error.
- ///
- /// Deliberately tolerates success. This used to `unwrap_err()`, on the
- /// assumption that the call always fails at `global_signal_store` because
- /// no store is running. That holds only while the process-global store is
- /// uninitialized — once any other test in the binary initializes it, the
- /// call succeeds and `unwrap_err()` panics. The property under test is
- /// about *param validation*, which an `Ok` satisfies just as well as a
- /// non-param error, so asserting on the error only when there is one keeps
- /// the intent and drops the dependency on global state.
- #[test]
- fn signal_register_encryption_key_fails_at_store_not_params() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- if let Err(err) = rt.block_on(handle_tinyplace_signal_register_encryption_key(Map::new())) {
- assert!(
- !err.contains("missing required param"),
- "should not fail on params: {err}"
- );
- }
- }
-
- #[test]
- fn directory_find_by_encryption_key_with_valid_param_fails_at_client() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- let mut params = Map::new();
- params.insert(
- "encryptionKey".into(),
- Value::String("dGVzdA==".into()), // valid base64
- );
- // Tolerates success: the property is that a *valid* key gets past param
- // validation, which an `Ok` demonstrates. Requiring a client-init
- // failure would couple the test to whether a client happens to be
- // reachable in this process.
- if let Err(err) = rt.block_on(handle_tinyplace_directory_find_by_encryption_key(params)) {
- // Must get past param validation; fails at client initialization.
- assert!(!err.contains("encryptionKey"), "got: {err}");
- }
- }
-
- /// Verify that the error path from register_encryption_key does not contain
- /// any base64 key material in the error message.
- #[test]
- fn signal_register_encryption_key_does_not_leak_key_material() {
- let rt = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
- // Tolerates success for the same reason as
- // `signal_register_encryption_key_fails_at_store_not_params`: this
- // calls the same handler, so it carries the same latent dependency on
- // an uninitialized global store. There is nothing to leak when there is
- // no error.
- if let Err(err) = rt.block_on(handle_tinyplace_signal_register_encryption_key(Map::new())) {
- // The error should not contain base64-encoded key fragments.
- // Since we fail before getting a key, this is a structural test:
- // the handler's error messages don't embed raw key values.
- assert!(
- !err.contains("=="),
- "error should not contain base64 fragments: {err}"
- );
- }
- }
-
- /// Verify all 10 Jobs write handlers reject missing required params.
- ///
- /// Actor (client/candidate) is NEVER read from params — it is always derived
- /// from the wallet signer. These tests only exercise param-validation logic;
- /// they cannot reach the SDK call (no running tiny.place client in unit tests).
- #[test]
- fn jobs_write_handlers_require_params() {
- // ── jobs_create ───────────────────────────────────────────────────────
-
- // Blank Map → must complain about 'title'
- let err = block_on(handle_tinyplace_jobs_create(Map::new())).unwrap_err();
- assert!(err.contains("title"), "jobs_create missing title: {err}");
-
- // title present, budgetAmount absent
- {
- let mut p = Map::new();
- p.insert("title".into(), Value::String("Build a bot".into()));
- let err = block_on(handle_tinyplace_jobs_create(p)).unwrap_err();
- assert!(
- err.contains("budgetAmount"),
- "jobs_create missing budgetAmount: {err}"
- );
- }
-
- // title + budgetAmount present, budgetAsset absent
- {
- let mut p = Map::new();
- p.insert("title".into(), Value::String("Build a bot".into()));
- p.insert("budgetAmount".into(), Value::String("100".into()));
- let err = block_on(handle_tinyplace_jobs_create(p)).unwrap_err();
- assert!(
- err.contains("budgetAsset"),
- "jobs_create missing budgetAsset: {err}"
- );
- }
-
- // Blank title must be rejected
- {
- let mut p = Map::new();
- p.insert("title".into(), Value::String(" ".into()));
- p.insert("budgetAmount".into(), Value::String("100".into()));
- p.insert("budgetAsset".into(), Value::String("USDC".into()));
- let err = block_on(handle_tinyplace_jobs_create(p)).unwrap_err();
- assert!(err.contains("title"), "jobs_create blank title: {err}");
- }
-
- // ── jobs_cancel ───────────────────────────────────────────────────────
-
- let err = block_on(handle_tinyplace_jobs_cancel(Map::new())).unwrap_err();
- assert!(err.contains("jobId"), "jobs_cancel missing jobId: {err}");
-
- // ── jobs_apply ────────────────────────────────────────────────────────
-
- let err = block_on(handle_tinyplace_jobs_apply(Map::new())).unwrap_err();
- assert!(err.contains("jobId"), "jobs_apply missing jobId: {err}");
-
- // ── jobs_list_proposals ───────────────────────────────────────────────
-
- let err = block_on(handle_tinyplace_jobs_list_proposals(Map::new())).unwrap_err();
- assert!(
- err.contains("jobId"),
- "jobs_list_proposals missing jobId: {err}"
- );
-
- // ── jobs_get_proposal ─────────────────────────────────────────────────
-
- let err = block_on(handle_tinyplace_jobs_get_proposal(Map::new())).unwrap_err();
- assert!(
- err.contains("jobId"),
- "jobs_get_proposal missing jobId: {err}"
- );
-
- // jobId present, proposalId absent
- {
- let mut p = Map::new();
- p.insert("jobId".into(), Value::String("job-1".into()));
- let err = block_on(handle_tinyplace_jobs_get_proposal(p)).unwrap_err();
- assert!(
- err.contains("proposalId"),
- "jobs_get_proposal missing proposalId: {err}"
- );
- }
-
- // ── jobs_shortlist_proposal ───────────────────────────────────────────
-
- let err = block_on(handle_tinyplace_jobs_shortlist_proposal(Map::new())).unwrap_err();
- assert!(
- err.contains("jobId"),
- "jobs_shortlist_proposal missing jobId: {err}"
- );
-
- {
- let mut p = Map::new();
- p.insert("jobId".into(), Value::String("job-1".into()));
- let err = block_on(handle_tinyplace_jobs_shortlist_proposal(p)).unwrap_err();
- assert!(
- err.contains("proposalId"),
- "jobs_shortlist_proposal missing proposalId: {err}"
- );
- }
-
- // ── jobs_withdraw_proposal ────────────────────────────────────────────
-
- let err = block_on(handle_tinyplace_jobs_withdraw_proposal(Map::new())).unwrap_err();
- assert!(
- err.contains("jobId"),
- "jobs_withdraw_proposal missing jobId: {err}"
- );
-
- {
- let mut p = Map::new();
- p.insert("jobId".into(), Value::String("job-1".into()));
- let err = block_on(handle_tinyplace_jobs_withdraw_proposal(p)).unwrap_err();
- assert!(
- err.contains("proposalId"),
- "jobs_withdraw_proposal missing proposalId: {err}"
- );
- }
-
- // ── jobs_select ───────────────────────────────────────────────────────
-
- let err = block_on(handle_tinyplace_jobs_select(Map::new())).unwrap_err();
- assert!(err.contains("jobId"), "jobs_select missing jobId: {err}");
-
- {
- let mut p = Map::new();
- p.insert("jobId".into(), Value::String("job-1".into()));
- let err = block_on(handle_tinyplace_jobs_select(p)).unwrap_err();
- assert!(
- err.contains("proposalId"),
- "jobs_select missing proposalId: {err}"
- );
- }
-
- // ── jobs_open_dispute ─────────────────────────────────────────────────
-
- let err = block_on(handle_tinyplace_jobs_open_dispute(Map::new())).unwrap_err();
- assert!(
- err.contains("jobId"),
- "jobs_open_dispute missing jobId: {err}"
- );
-
- // jobId present, reason absent
- {
- let mut p = Map::new();
- p.insert("jobId".into(), Value::String("job-1".into()));
- let err = block_on(handle_tinyplace_jobs_open_dispute(p)).unwrap_err();
- assert!(
- err.contains("reason"),
- "jobs_open_dispute missing reason: {err}"
- );
- }
-
- // Blank reason must be rejected
- {
- let mut p = Map::new();
- p.insert("jobId".into(), Value::String("job-1".into()));
- p.insert("reason".into(), Value::String(" ".into()));
- let err = block_on(handle_tinyplace_jobs_open_dispute(p)).unwrap_err();
- assert!(
- err.contains("reason"),
- "jobs_open_dispute blank reason: {err}"
- );
- }
-
- // ── jobs_adjudicate_dispute ───────────────────────────────────────────
-
- let err = block_on(handle_tinyplace_jobs_adjudicate_dispute(Map::new())).unwrap_err();
- assert!(
- err.contains("jobId"),
- "jobs_adjudicate_dispute missing jobId: {err}"
- );
- }
-
- // ── Feeds write surface param validation (Phase A) ───────────────────────
-
- /// feeds_create_post requires non-blank `handle` then non-blank `body`.
- #[test]
- fn feeds_create_post_requires_body_not_handle() {
- // `body` is required and validated before any client/signer access.
- let err = block_on(handle_tinyplace_feeds_create_post(Map::new())).unwrap_err();
- assert!(err.contains("body"), "got: {err}");
- // The owner handle is resolved server-side from the signer, so the
- // handler must NOT read a client-supplied 'handle'.
- assert!(
- !err.contains("handle"),
- "handle must not be a client param: {err}"
- );
- }
-
- /// feeds_delete_post requires `postId`; the owner handle is signer-derived.
- #[test]
- fn feeds_delete_post_requires_post_id_not_handle() {
- let err = block_on(handle_tinyplace_feeds_delete_post(Map::new())).unwrap_err();
- assert!(err.contains("postId"), "got: {err}");
- assert!(
- !err.contains("handle"),
- "handle must not be a client param: {err}"
- );
- }
-
- /// feeds_add_comment requires `handle`, `postId`, then `body`.
- #[test]
- fn feeds_add_comment_requires_handle_post_id_and_body() {
- let err = block_on(handle_tinyplace_feeds_add_comment(Map::new())).unwrap_err();
- assert!(err.contains("handle"), "got: {err}");
- let mut p = Map::new();
- p.insert("handle".into(), Value::String("alice".into()));
- let err = block_on(handle_tinyplace_feeds_add_comment(p)).unwrap_err();
- assert!(err.contains("postId"), "got: {err}");
- let mut p2 = Map::new();
- p2.insert("handle".into(), Value::String("alice".into()));
- p2.insert("postId".into(), Value::String("p1".into()));
- let err = block_on(handle_tinyplace_feeds_add_comment(p2)).unwrap_err();
- assert!(err.contains("body"), "got: {err}");
- }
-
- /// feeds_delete_comment requires `handle` at minimum.
- #[test]
- fn feeds_delete_comment_requires_params() {
- let err = block_on(handle_tinyplace_feeds_delete_comment(Map::new())).unwrap_err();
- assert!(err.contains("handle"), "got: {err}");
- }
-
- /// Both like and unlike handlers require `handle` then `postId`.
- /// This test also verifies that the `actor` is NOT read from params:
- /// both handlers fail at param extraction (before any client/network work),
- /// and neither produces an error mentioning "actor".
- #[test]
- fn feeds_like_unlike_require_handle_and_post_id() {
- for handler in [
- handle_tinyplace_feeds_like_post as fn(Map<String, Value>) -> ControllerFuture,
- handle_tinyplace_feeds_unlike_post,
- ] {
- let err = block_on(handler(Map::new())).unwrap_err();
- assert!(err.contains("handle"), "got: {err}");
- // actor is server-derived — must not appear in the error message
- assert!(
- !err.contains("actor"),
- "actor must never come from params; got: {err}"
- );
- let mut p = Map::new();
- p.insert("handle".into(), Value::String("alice".into()));
- let err = block_on(handler(p)).unwrap_err();
- assert!(err.contains("postId"), "got: {err}");
- }
- }
-
- // ── Bounties handlers (Phase B) ───────────────────────────────────────────
-
- /// Degrade helpers return empty results for Serialization errors, and
- /// propagate non-serialization errors.
- #[test]
- fn bounties_degrade_helpers_return_empty_on_serialization() {
- let raw_ser_err: serde_json::Error =
- serde_json::from_str::<serde_json::Value>("{invalid json}").unwrap_err();
- let ser_err = tinyplace::Error::Serialization(raw_ser_err);
- assert!(bounties_list_degrade(&ser_err).is_some());
- assert!(bounties_submissions_degrade(&ser_err).is_some());
- assert!(bounties_comments_degrade(&ser_err).is_some());
-
- let other = tinyplace::Error::InvalidArgument("bad arg".into());
- assert!(bounties_list_degrade(&other).is_none());
- assert!(bounties_submissions_degrade(&other).is_none());
- assert!(bounties_comments_degrade(&other).is_none());
- }
-
- /// bounties_create rejects blank title before any client work.
- #[test]
- fn bounties_create_rejects_blank_title() {
- let mut params = Map::new();
- params.insert("title".to_string(), Value::String("".to_string()));
- params.insert("description".to_string(), Value::String("desc".to_string()));
- params.insert("amount".to_string(), Value::String("100".to_string()));
- let result = block_on(handle_tinyplace_bounties_create(params));
- assert!(result.is_err());
- assert!(
- result.unwrap_err().contains("title"),
- "expected 'title' in error"
- );
- }
-
- /// bounties_create rejects missing amount before any client work.
- #[test]
- fn bounties_create_rejects_missing_amount() {
- let mut params = Map::new();
- params.insert("title".to_string(), Value::String("test".to_string()));
- params.insert("description".to_string(), Value::String("desc".to_string()));
- let result = block_on(handle_tinyplace_bounties_create(params));
- assert!(result.is_err());
- assert!(
- result.unwrap_err().contains("amount"),
- "expected 'amount' in error"
- );
- }
-
- /// registry_assign_primary rejects a blank/@-only name before any client
- /// work (#4198) — the trim + strip-@ must not leave an empty handle that
- /// would hit the backend.
- #[test]
- fn registry_assign_primary_rejects_blank_name() {
- let mut params = Map::new();
- params.insert("name".to_string(), Value::String(" @ ".to_string()));
- let result = block_on(handle_tinyplace_registry_assign_primary(params));
- assert!(result.is_err());
- assert!(
- result.unwrap_err().contains("name"),
- "expected 'name' in error"
- );
- }
-
- /// bounties_submit rejects blank url before any client work.
- #[test]
- fn bounties_submit_rejects_blank_url() {
- let mut params = Map::new();
- params.insert("bountyId".to_string(), Value::String("b1".to_string()));
- params.insert("url".to_string(), Value::String("".to_string()));
- let result = block_on(handle_tinyplace_bounties_submit(params));
- assert!(result.is_err());
- assert!(
- result.unwrap_err().contains("url"),
- "expected 'url' in error"
- );
- }
-
- /// bounties_comment rejects blank body before any client work.
- #[test]
- fn bounties_comment_rejects_blank_body() {
- let mut params = Map::new();
- params.insert("bountyId".to_string(), Value::String("b1".to_string()));
- params.insert("body".to_string(), Value::String(" ".to_string()));
- let result = block_on(handle_tinyplace_bounties_comment(params));
- assert!(result.is_err());
- assert!(
- result.unwrap_err().contains("body"),
- "expected 'body' in error"
- );
- }
-
- /// ANTI-SPOOF: bounties_create, bounties_cancel, bounties_submit, bounties_comment,
- /// and bounties_run_council must NOT read actor/creator/submitter/author from params.
- /// These handlers fail at param extraction or client init — never at an actor param.
- #[test]
- fn bounties_write_handlers_do_not_accept_actor_from_params() {
- // bounties_create: fails on title before any actor check
- let err = block_on(handle_tinyplace_bounties_create(Map::new())).unwrap_err();
- assert!(err.contains("title"), "got: {err}");
- assert!(
- !err.contains("creator"),
- "creator must not be a client param: {err}"
- );
-
- // bounties_cancel: fails on bountyId before any actor check
- let err = block_on(handle_tinyplace_bounties_cancel(Map::new())).unwrap_err();
- assert!(err.contains("bountyId"), "got: {err}");
- assert!(
- !err.contains("creator"),
- "creator must not be a client param: {err}"
- );
-
- // bounties_submit: fails on bountyId before any actor check
- let err = block_on(handle_tinyplace_bounties_submit(Map::new())).unwrap_err();
- assert!(err.contains("bountyId"), "got: {err}");
- assert!(
- !err.contains("submitter"),
- "submitter must not be a client param: {err}"
- );
-
- // bounties_comment: fails on bountyId before any actor check
- let err = block_on(handle_tinyplace_bounties_comment(Map::new())).unwrap_err();
- assert!(err.contains("bountyId"), "got: {err}");
- assert!(
- !err.contains("author"),
- "author must not be a client param: {err}"
- );
-
- // bounties_run_council: fails on bountyId before any actor check
- let err = block_on(handle_tinyplace_bounties_run_council(Map::new())).unwrap_err();
- assert!(err.contains("bountyId"), "got: {err}");
- assert!(
- !err.contains("actor"),
- "actor must not be a client param: {err}"
- );
- }
-
- // ── match_agent_card_by_username — pure matching logic ───────────────────
-
- fn make_test_card(agent_id: &str, username: Option<&str>) -> tinyplace::types::AgentCard {
- tinyplace::types::AgentCard {
- agent_id: agent_id.to_string(),
- name: agent_id.to_string(),
- description: None,
- username: username.map(str::to_string),
- crypto_id: format!("crypto-{agent_id}"),
- actor_type: None,
- public_key: None,
- url: None,
- endpoint: None,
- supported_interfaces: None,
- skills: None,
- capabilities: None,
- tags: None,
- payment_methods: None,
- payment_requirements: None,
- groups: None,
- docs: None,
- webhooks: None,
- metadata: None,
- signature: None,
- created_at: "2026-01-01T00:00:00Z".to_string(),
- updated_at: "2026-01-01T00:00:00Z".to_string(),
- viewer_is_following: None,
- }
- }
-
- /// Directory-card matcher finds an exact username match.
- #[test]
- fn match_agent_card_exact_username_hit() {
- let cards = vec![
- make_test_card("agent-1", Some("alice")),
- make_test_card("agent-2", Some("stevejobs")),
- make_test_card("agent-3", Some("bob")),
- ];
- let found = match_agent_card_by_username(&cards, "stevejobs");
- assert!(found.is_some(), "should find stevejobs");
- assert_eq!(found.unwrap().crypto_id, "crypto-agent-2");
- }
-
- /// Directory-card matcher is case-insensitive.
- #[test]
- fn match_agent_card_case_insensitive() {
- let cards = vec![make_test_card("agent-1", Some("SteveJobs"))];
- let found = match_agent_card_by_username(&cards, "stevejobs");
- assert!(found.is_some(), "case-insensitive match must succeed");
- }
-
- /// Directory-card matcher returns None when no card has the given username.
- #[test]
- fn match_agent_card_miss() {
- let cards = vec![
- make_test_card("agent-1", Some("alice")),
- make_test_card("agent-2", None), // no username
- ];
- let found = match_agent_card_by_username(&cards, "notexist");
- assert!(found.is_none(), "should return None when no match");
- }
-
- /// Directory-card matcher skips cards with no username without panicking.
- #[test]
- fn match_agent_card_skips_cards_without_username() {
- let cards = vec![
- make_test_card("agent-1", None),
- make_test_card("agent-2", None),
- make_test_card("agent-3", Some("target")),
- ];
- let found = match_agent_card_by_username(&cards, "target");
- assert!(found.is_some(), "should find the card that has a username");
- assert_eq!(found.unwrap().agent_id, "agent-3");
- }
-
- /// looks_like_base58_pubkey passthrough: resolve_recipient should NOT call
- /// directory.resolve for a raw crypto_id — it short-circuits and returns it
- /// directly. We can verify this by supplying a valid 44-char base58 string
- /// which, without a live client, would error if it tried to resolve.
- ///
- /// Because `resolve_recipient_to_agent_id` requires a live client we test
- /// the passthrough indirectly via `looks_like_base58_pubkey`.
- #[test]
- fn base58_passthrough_identified_correctly() {
- // 44-char valid base58 — same as used elsewhere in this test suite.
- let key = "61KcG5aGLqpnJz2fXyzABCDEFGHJKLMNPQRSTUVWXY";
- assert!(
- looks_like_base58_pubkey(key),
- "44-char base58 must be identified as a crypto_id to skip resolution"
- );
- }
-
- /// Resolver error message does NOT expose the raw 404 HTTP text.
- /// The error string produced when no agent is found must be human-readable
- /// and must not look like a raw network error.
- #[test]
- fn resolve_not_found_error_is_human_readable() {
- // Test the error message produced in handle_tinyplace_directory_resolve
- // when both registry and directory miss — replicated here as the literal
- // format used in the production code.
- let name = "unknownuser";
- let err = format!(
- "No agent found for \"{name}\". \
- Check the handle or paste their wallet address directly."
- );
- assert!(
- err.contains("unknownuser"),
- "error must name the handle: {err}"
- );
- assert!(
- !err.contains("404"),
- "error must not expose raw HTTP status: {err}"
- );
- assert!(
- !err.contains("not found"),
- "error must not use raw 404 body text: {err}"
- );
- }
-}
diff --git a/src/openhuman/tinyplace/mod.rs b/src/openhuman/tinyplace/mod.rs
deleted file mode 100644
index 3f2daf3dad..0000000000
--- a/src/openhuman/tinyplace/mod.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-//! **tiny.place** A2A social-network integration — core domain.
-//!
-//! Namespace: `tinyplace`. RPC methods: `openhuman.tinyplace_*`.
-//!
-//! Controllers are registered in the **internal** registry (callable by the
-//! renderer via `core_rpc_relay` but NOT advertised to agents via tool listings
-//! or schema discovery). See [`schemas`] for the registration and
-//! [`manifest`] for the handler implementations.
-//!
-//! ## Architecture
-//!
-//! ```text
-//! Renderer (invoke 'core_rpc_relay', method='openhuman.tinyplace_*')
-//! └─► src/core/all.rs build_internal_only_controllers()
-//! └─► schemas::all_tinyplace_registered_controllers()
-//! └─► manifest::handle_tinyplace_*()
-//! └─► state::TinyPlaceState::client()
-//! └─► tinyplace::TinyPlaceClient
-//! ```
-//!
-//! ## Seed derivation
-//!
-//! `TinyPlaceState::client()` calls `wallet::tinyplace_signer_seed()` on first
-//! access. The seed is derived via the same SLIP-0010 path used for all Solana
-//! signing (`m/44'/501'/0'/0'`); the wallet key becomes the tiny.place identity.
-//! The seed is never logged, persisted, or returned across any IPC boundary.
-//!
-//! ## Marketplace scope (seller-side writes are web-only)
-//!
-//! The identity marketplace **write** handlers here are buyer-side only: buy a
-//! listing, bid, and make an offer. Seller-side *writes* — listing a handle for
-//! sale and accepting / rejecting offers — are **web-only on tiny.place** (the
-//! backend exposes no seller write routes). Seller-side *reads* do exist:
-//! `marketplace_list_offers` takes a `name` filter for offers targeting a handle
-//! you own. The desktop Trading tab links sellers to the web app for the actions
-//! it cannot perform. See #4920.
-//!
-//! ## Feed scope (post media is web-only)
-//!
-//! Feed posts here are **text-only**. Attaching images / GIFs to a post is
-//! **web-only on tiny.place**: the backend serves no media field — neither the
-//! write-side `PostCreate` nor the read-side `Post` / `GqlPost` in the vendored
-//! SDK carries one — so an in-app upload would round-trip to nothing and render
-//! nowhere. The desktop feed composer links users to the web app to attach
-//! media instead of dead-ending. See #4924.
-
-mod manifest;
-pub(crate) use manifest::{
- acknowledge_message, decrypt_envelope, ensure_signal_keys_published,
- handle_tinyplace_contacts_list, handle_tinyplace_directory_get_agent,
- handle_tinyplace_directory_reverse, handle_tinyplace_signal_key_status,
- handle_tinyplace_signal_provision, handle_tinyplace_signal_register_encryption_key,
- handle_tinyplace_signal_send_message,
-};
-pub(crate) mod ops;
-mod payment;
-mod schemas;
-pub(crate) mod signal_store;
-mod state;
-pub(crate) mod streams;
-
-#[cfg(test)]
-mod signal_e2e_tests;
-#[cfg(test)]
-mod tests;
-
-pub use schemas::{all_tinyplace_controller_schemas, all_tinyplace_registered_controllers};
diff --git a/src/openhuman/tinyplace/ops.rs b/src/openhuman/tinyplace/ops.rs
deleted file mode 100644
index 47521a08b1..0000000000
--- a/src/openhuman/tinyplace/ops.rs
+++ /dev/null
@@ -1,109 +0,0 @@
-//! Business logic helpers for the tiny.place domain.
-//!
-//! Provides the error-mapping function (`map_err`) used by all handlers and the
-//! process-global accessor for [`crate::openhuman::tinyplace::state::TinyPlaceState`].
-
-use std::sync::OnceLock;
-
-use crate::openhuman::tinyplace::state::TinyPlaceState;
-
-const LOG_PREFIX: &str = "[tinyplace]";
-
-// ── Process-global state ─────────────────────────────────────────────────────
-
-static TINYPLACE_STATE: OnceLock<TinyPlaceState> = OnceLock::new();
-
-/// Return the process-global [`TinyPlaceState`], initialising it from the
-/// environment on first access.
-pub(crate) fn global_state() -> &'static TinyPlaceState {
- TINYPLACE_STATE.get_or_init(TinyPlaceState::from_env)
-}
-
-/// Active relay endpoint the tiny.place client talks to, plus a coarse network
-/// label the renderer surfaces as a badge. A base URL containing `staging`
-/// resolves to `"staging"`; anything else is treated as `"prod"`.
-///
-/// This reads only the configured base URL (no client build, no wallet unlock),
-/// so it is safe to call at any time.
-pub(crate) fn relay_endpoint() -> (String, &'static str) {
- let base_url = global_state().base_url.clone();
- let network = relay_network_label(&base_url);
- (base_url, network)
-}
-
-/// Coarse network label for a relay base URL: `staging` when the host carries a
-/// `staging` marker, else `prod`. Kept pure so it is unit-testable without the
-/// process-global state.
-pub(crate) fn relay_network_label(base_url: &str) -> &'static str {
- if base_url.contains("staging") {
- "staging"
- } else {
- "prod"
- }
-}
-
-// ── Error mapping ─────────────────────────────────────────────────────────────
-
-/// Map a SDK [`tinyplace::Error`] to a [`String`] the controller layer returns.
-///
-/// - `402 Payment Required` → `"PAYMENT_REQUIRED:<json>"` prefix (renderer parses
-/// this into a typed `PaymentRequiredError`).
-/// - Other HTTP errors → logged at `warn` with status code, returned as plain string.
-/// - Transport / serialization errors → logged at `error`.
-pub(crate) fn map_err(e: tinyplace::Error) -> String {
- if let Some(challenge) = e.payment_required() {
- log::warn!("{LOG_PREFIX} 402 payment_required: {challenge:?}");
- let body = serde_json::to_string(challenge).unwrap_or_default();
- return format!("PAYMENT_REQUIRED:{body}");
- }
- if let Some(status) = e.status() {
- // Surface the backend's response body (it usually carries the actual
- // validation reason) to both the log and the returned error string, so
- // the UI shows *why* a request failed, not just the status + path.
- let reason = e
- .body()
- .and_then(extract_error_reason)
- .filter(|s| !s.is_empty());
- match &reason {
- Some(r) => log::warn!("{LOG_PREFIX} http {status}: {e} — {r}"),
- None => log::warn!("{LOG_PREFIX} http {status}: {e}"),
- }
- return match reason {
- Some(r) => format!("{e}: {r}"),
- None => e.to_string(),
- };
- }
- log::error!("{LOG_PREFIX} error: {e}");
- e.to_string()
-}
-
-/// Pull a human-readable reason out of an HTTP error body. Backends return it
-/// under varying keys (`error`, `message`, `detail`) or as a bare string.
-fn extract_error_reason(body: &serde_json::Value) -> Option<String> {
- match body {
- serde_json::Value::String(s) => Some(s.clone()),
- serde_json::Value::Object(map) => map
- .get("error")
- .or_else(|| map.get("message"))
- .or_else(|| map.get("detail"))
- .and_then(|v| v.as_str().map(str::to_string))
- .or_else(|| Some(body.to_string())),
- serde_json::Value::Null => None,
- other => Some(other.to_string()),
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn relay_network_label_classifies_staging_and_prod() {
- assert_eq!(
- relay_network_label("https://staging-api.tiny.place"),
- "staging"
- );
- assert_eq!(relay_network_label("https://api.tiny.place"), "prod");
- assert_eq!(relay_network_label(""), "prod");
- }
-}
diff --git a/src/openhuman/tinyplace/payment.rs b/src/openhuman/tinyplace/payment.rs
deleted file mode 100644
index 56b72c446a..0000000000
--- a/src/openhuman/tinyplace/payment.rs
+++ /dev/null
@@ -1,886 +0,0 @@
-//! x402 payment fulfillment bridge — **section-agnostic**.
-//!
-//! Turns a `402 Payment Required` [`PaymentChallenge`] into a signed
-//! [`X402PaymentMap`] by paying on-chain through the OpenHuman wallet and then
-//! signing the x402 authorization with the tiny.place identity key.
-//!
-//! The flow is shared verbatim across register / buy / bid / offer; callers
-//! parameterise the purpose and any extra signed metadata via [`PaymentContext`].
-//!
-//! ## What this module does NOT do
-//!
-//! - It does **not** build the canonical message, sign it, or flatten the map —
-//! that lives in the SDK ([`tinyplace::x402::build_x402_payment_map`]).
-//! - It does **not** *pick* a Solana cluster — `challenge.network` is passed
-//! through verbatim and the asset is routed by symbol. It exposes an
-//! *advisory* [`ensure_cluster_matches`] check (Risk R6); it does NOT block,
-//! because tiny.place labels every cluster with the mainnet genesis, so the
-//! challenge network is not an authoritative cluster signal. Cluster alignment
-//! is governed by `OPENHUMAN_SOLANA_CLUSTER` + operator config.
-//! - It does **not** expose an RPC controller. The section write-handlers
-//! (register / marketplace, in later PRs) call [`fulfill_payment`] and attach
-//! the returned payment map to their domain request.
-//!
-//! Marketplace write handlers (buy / bid / offer) are still pending, so a few
-//! helpers here are not yet referenced; keep the targeted allows until those
-//! PRs land rather than deleting otherwise-correct code.
-
-use std::collections::HashMap;
-
-use tinyplace::signer::Signer;
-use tinyplace::x402::{
- build_x402_payment_map, generate_nonce, X402PaymentAuthorizationOptions, X402PaymentMap,
- X402PaymentReferenceOptions,
-};
-use tinyplace::PaymentChallenge;
-
-use crate::openhuman::web3::wallet::rpc::with_tinyplace_solana_endpoints;
-use crate::openhuman::web3::wallet::{
- execute_prepared, prepare_transfer, solana_cluster, tinyplace_solana_rpc_endpoints,
- ExecutePreparedParams, PrepareTransferParams, SolanaCluster, WalletChain,
-};
-
-const LOG_PREFIX: &str = "[tinyplace-pay]";
-
-/// Reject a challenge whose expiry is within this many seconds of now — leaves
-/// headroom for the on-chain broadcast + verification round-trip.
-const EXPIRY_SKEW_SECS: i64 = 30;
-
-// ── Public types ──────────────────────────────────────────────────────────────
-
-/// Caller-supplied purpose + extra metadata. Parameterises the otherwise
-/// identical register / buy / bid / offer flows.
-#[derive(Debug, Clone)]
-pub(crate) struct PaymentContext {
- /// Folded into the signed metadata as `purpose` (e.g. `"identity.register"`,
- /// `"marketplace.buy"`).
- pub(crate) purpose: String,
- /// Nonce prefix used when the challenge omits a nonce (e.g. `"register"` →
- /// `register_<hex>`).
- pub(crate) nonce_prefix: String,
- /// Extra signed metadata (e.g. `{ "identity": "@handle" }`,
- /// `{ "listingId": "…" }`).
- pub(crate) extra_metadata: HashMap<String, String>,
-}
-
-/// Result of a completed on-chain payment plus its signed x402 authorization.
-#[derive(Debug, Clone)]
-pub(crate) struct FulfilledPayment {
- /// The flat x402 payment map to attach to the domain request.
- pub(crate) payment_map: X402PaymentMap,
- /// The on-chain Solana transaction signature that moved the funds.
- pub(crate) on_chain_tx: String,
- /// The wallet quote id the transfer was executed under. Surfaced for
- /// diagnostics/audit; not all callers read it (the register handler only
- /// needs `on_chain_tx`).
- #[allow(dead_code)]
- pub(crate) quote_id: String,
-}
-
-// ── Internal types ────────────────────────────────────────────────────────────
-
-/// A challenge whose required fields have been validated and asset-routed.
-#[derive(Debug, Clone)]
-struct ValidatedChallenge {
- network: String,
- asset: String,
- amount: String,
- to: String,
- nonce: Option<String>,
- expires_at: Option<String>,
- /// `None` for native SOL, `Some("USDC")` for the SPL token.
- asset_symbol: Option<String>,
-}
-
-// ── Pure helpers (unit-tested; no network, no funds) ──────────────────────────
-
-/// Whether `asset` names USDC — either the `"USDC"` symbol or a known USDC SPL
-/// mint address. The backend's x402 challenge identifies the payment currency
-/// by its on-chain mint, so the registration/buy flows see the mint here rather
-/// than the symbol (#4199). Both the mainnet and devnet mints are accepted; a
-/// cross-cluster mismatch is caught safely by the cluster/mint guards below, so
-/// recognising both here only widens *which* USDC mint is allowed through, not
-/// which chain settles.
-fn asset_is_usdc(asset: &str) -> bool {
- asset.eq_ignore_ascii_case("USDC")
- || asset == SolanaCluster::Mainnet.usdc_mint()
- || asset == SolanaCluster::Devnet.usdc_mint()
-}
-
-/// Validate required challenge fields, check expiry, and route the asset.
-fn validate_challenge(challenge: &PaymentChallenge) -> Result<ValidatedChallenge, String> {
- let asset = non_empty(&challenge.asset).ok_or("x402 challenge missing 'asset'")?;
- let amount = non_empty(&challenge.amount).ok_or("x402 challenge missing 'amount'")?;
- let to = non_empty(&challenge.to).ok_or("x402 challenge missing 'to'")?;
- let network = non_empty(&challenge.network).ok_or("x402 challenge missing 'network'")?;
-
- // Route the challenge asset to a wallet transfer asset. The backend's x402
- // challenge identifies USDC by its **SPL mint address**, not the `"USDC"`
- // symbol, so a literal-symbol match alone rejected every real registration
- // payment with `unsupported x402 asset: <mint>` (#4199). Accept the `"USDC"`
- // symbol and any known USDC mint (mainnet/devnet); the cluster guards below
- // keep a cross-cluster mint from mis-settling.
- let asset_symbol = if asset.eq_ignore_ascii_case("SOL") {
- None
- } else if asset_is_usdc(&asset) {
- Some("USDC".to_string())
- } else {
- // Never surface the raw on-chain asset identifier to the user — log it
- // for support/diagnostics and return human-readable copy (#4199).
- log::warn!("{LOG_PREFIX} rejecting unsupported x402 asset (not USDC/SOL): {asset}");
- return Err("Payment asset not supported — please contact support.".to_string());
- };
-
- let expires_at = non_empty(&challenge.expires_at);
- if let Some(expiry) = &expires_at {
- if is_expired(expiry) {
- return Err("payment challenge expired".to_string());
- }
- }
-
- Ok(ValidatedChallenge {
- network,
- asset,
- amount,
- to,
- nonce: non_empty(&challenge.nonce),
- expires_at,
- asset_symbol,
- })
-}
-
-/// Map a validated challenge to wallet transfer params (asset routing lives here).
-fn to_transfer_params(v: &ValidatedChallenge) -> PrepareTransferParams {
- PrepareTransferParams {
- chain: WalletChain::Solana,
- to_address: v.to.clone(),
- amount_raw: v.amount.clone(),
- asset_symbol: v.asset_symbol.clone(),
- evm_network: None,
- }
-}
-
-/// Build and sign the x402 payment map via the SDK. Offline — needs only a
-/// signer. The `on_chain_tx` is attached to the payment **references**
-/// (`onChainTx`/`tx`/`transaction`), never to the `signature` field (which is
-/// the off-chain Ed25519 authorization signature).
-async fn build_payment_map(
- signer: &dyn Signer,
- v: &ValidatedChallenge,
- on_chain_tx: &str,
- ctx: &PaymentContext,
-) -> Result<X402PaymentMap, String> {
- let mut metadata = ctx.extra_metadata.clone();
- metadata.insert("purpose".to_string(), ctx.purpose.clone());
-
- // Prefer the challenge nonce; otherwise mint one with the caller's prefix so
- // the SDK default ("pay") does not leak in.
- let nonce = v
- .nonce
- .clone()
- .unwrap_or_else(|| generate_nonce(Some(&ctx.nonce_prefix)));
-
- let options = X402PaymentAuthorizationOptions {
- network: v.network.clone(),
- asset: v.asset.clone(),
- amount: v.amount.clone(),
- from: Some(signer.agent_id()),
- to: v.to.clone(),
- nonce: Some(nonce),
- expires_at: v.expires_at.clone(),
- metadata: Some(metadata),
- references: X402PaymentReferenceOptions {
- on_chain_tx: Some(on_chain_tx.to_string()),
- tx: Some(on_chain_tx.to_string()),
- transaction: Some(on_chain_tx.to_string()),
- ..Default::default()
- },
- // scheme (→ "exact"), expires_in_ms, domain (→ "tiny.place") and
- // public_key_base64 (→ from signer) all take SDK defaults.
- ..Default::default()
- };
-
- build_x402_payment_map(signer, options)
- .await
- .map_err(|e| format!("x402 authorization signing failed: {e}"))
-}
-
-// ── Devnet guard (Risk R6) ────────────────────────────────────────────────────
-
-/// CAIP-2 genesis-hash references for the public Solana clusters.
-const MAINNET_GENESIS_PREFIX: &str = "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
-const DEVNET_GENESIS_PREFIX: &str = "EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
-
-/// Loosely classify a challenge's `network` string into a Solana cluster.
-///
-/// Recognises both the human form (`"solana-devnet"`, `"…mainnet…"`) and the
-/// CAIP-2 genesis-hash form (`"solana:5eykt4…"`). Returns `None` when the
-/// format is unrecognised — the backend remains the source of truth, so an
-/// unknown network is allowed through rather than blocked.
-fn classify_network(network: &str) -> Option<SolanaCluster> {
- let lower = network.to_lowercase();
- if lower.contains("devnet") {
- return Some(SolanaCluster::Devnet);
- }
- if lower.contains("mainnet") {
- return Some(SolanaCluster::Mainnet);
- }
- // Testnet is unsupported; treat as unknown (None) so we never silently map
- // it onto mainnet/devnet.
- if network.contains(DEVNET_GENESIS_PREFIX) {
- return Some(SolanaCluster::Devnet);
- }
- if network.contains(MAINNET_GENESIS_PREFIX) {
- return Some(SolanaCluster::Mainnet);
- }
- None
-}
-
-/// Advisory cluster check (does **not** block).
-///
-/// The original design hard-blocked when the challenge's `network` genesis hash
-/// implied a different cluster than [`solana_cluster`]. That premise is wrong for
-/// tiny.place: the backend hard-codes the CAIP-2 Solana network to the **mainnet
-/// genesis** (`solana:5eykt4…`) for *every* deployment — including devnet — and
-/// only switches the real settlement chain via its `SOLANA_RPC_URL` /
-/// `SOLANA_USDC_MINT` env (confirmed against the backend's `/payments/supported`,
-/// which returns the **devnet** USDC mint on staging). So the challenge label
-/// carries no reliable cluster signal, and a genesis-based hard block wrongly
-/// rejects valid devnet payments.
-///
-/// Cluster alignment is therefore governed by explicit config
-/// (`OPENHUMAN_SOLANA_CLUSTER`) + the operator pointing the wallet at the same
-/// chain the backend settles on. The wallet only ever transfers the configured
-/// cluster's USDC mint, so a true mismatch fails *safely* at verification (the
-/// backend never credits a tx it can't see) rather than mis-spending. We log a
-/// warning when the (advisory) label looks inconsistent.
-///
-/// The robust cross-check is now implemented as [`ensure_backend_mint_matches`],
-/// which compares `solana_cluster().usdc_mint()` against the backend's
-/// `solana.info()` USDC asset address. This advisory network-label check is
-/// retained for observability (it logs when the label looks inconsistent).
-pub(crate) fn ensure_cluster_matches(network: &str) -> Result<(), String> {
- cluster_guard(solana_cluster(), network)
-}
-
-/// Pure advisory check (no env access — testable in isolation). Always returns
-/// `Ok`; logs a warning when the challenge label implies a different cluster than
-/// configured (tiny.place's label is not authoritative — see
-/// [`ensure_cluster_matches`]).
-fn cluster_guard(configured: SolanaCluster, network: &str) -> Result<(), String> {
- match classify_network(network) {
- Some(challenge_cluster) if challenge_cluster != configured => {
- log::warn!(
- "{LOG_PREFIX} advisory: challenge network label='{network}' implies \
- {challenge_cluster:?} but wallet configured for {configured:?}; tiny.place labels \
- every cluster with the mainnet genesis, so proceeding — ensure the backend \
- settles on {configured:?} (its /payments/supported USDC mint should match)"
- );
- }
- other => {
- log::debug!(
- "{LOG_PREFIX} cluster guard ok: network='{network}' classified={other:?} \
- configured={configured:?}"
- );
- }
- }
- Ok(())
-}
-
-/// Pure mint cross-check: compares the configured wallet's USDC mint against
-/// the backend's reported USDC mint from `solana.info()`.
-///
-/// - **Both match** → Ok (the common case).
-/// - **Mismatch** → Err with a clear diagnostic (e.g. configured=mainnet
-/// EPjFWdd… but backend reports devnet 4zMMC9…).
-/// - **Backend USDC not found** (`backend_usdc_mint` is None) → Ok with a
-/// log (the backend might not list USDC; fail-open).
-///
-/// This is the "does the wallet agree with the backend" check the TODO at
-/// line 233-236 asked for. It replaces the genesis-based label check with
-/// an authoritative mint comparison.
-fn mint_cross_check(configured_mint: &str, backend_usdc_mint: Option<&str>) -> Result<(), String> {
- match backend_usdc_mint {
- Some(backend_mint) if backend_mint == configured_mint => {
- log::debug!(
- "{LOG_PREFIX} mint cross-check ok: configured={configured_mint} \
- backend={backend_mint}"
- );
- Ok(())
- }
- Some(backend_mint) => {
- // TRUE MISMATCH — this is the real-funds protection case.
- Err(format!(
- "cluster mismatch: wallet configured USDC mint={configured_mint} but \
- the backend reports USDC mint={backend_mint}; refusing to spend — \
- check OPENHUMAN_SOLANA_CLUSTER and the backend's Solana config"
- ))
- }
- None => {
- // Backend did not report a USDC asset in solana.info().assets.
- // Fail-open: the backend might be running an older version or USDC is
- // not configured. The payment will still fail safely at verification
- // if there is a real mismatch.
- log::warn!(
- "{LOG_PREFIX} mint cross-check: backend solana.info() did not include a \
- USDC asset; cannot verify against configured mint={configured_mint}; \
- proceeding (fail-open)"
- );
- Ok(())
- }
- }
-}
-
-/// Async mint cross-check: fetches `client.solana.info()`, finds the USDC
-/// asset, and compares its mint address against the configured wallet's
-/// `solana_cluster().usdc_mint()`.
-///
-/// **Fail-open on transient errors**: if the fetch fails (backend
-/// unreachable, endpoint not deployed), logs a warning and returns Ok.
-/// Only blocks on a CONFIRMED mint mismatch where both sides returned.
-pub(crate) async fn ensure_backend_mint_matches(
- client: &tinyplace::TinyPlaceClient,
-) -> Result<(), String> {
- let configured_mint = solana_cluster().usdc_mint();
-
- let chain_info = match client.solana.info().await {
- Ok(info) => info,
- Err(e) => {
- log::warn!(
- "{LOG_PREFIX} mint cross-check: solana.info() failed ({e}); \
- proceeding without mint verification (fail-open)"
- );
- return Ok(());
- }
- };
-
- log::debug!(
- "{LOG_PREFIX} mint cross-check: backend network='{}' assets_count={}",
- chain_info.network,
- chain_info.assets.len(),
- );
-
- let backend_usdc_mint = chain_info
- .assets
- .iter()
- .find(|a| a.symbol == "USDC")
- .and_then(|a| a.address.as_deref());
-
- mint_cross_check(configured_mint, backend_usdc_mint)
-}
-
-// ── High-level orchestrator (thin; logic delegated to the tested helpers) ─────
-
-/// Validate the challenge, pay on-chain (`prepare_transfer` + `execute_prepared`
-/// with `confirmed: true`), sign the x402 authorization, and return the payment
-/// map plus on-chain tx and quote id.
-///
-/// Spends real funds when it reaches the wallet calls — callers MUST gate this
-/// behind an explicit, user-confirmed action.
-pub(crate) async fn fulfill_payment(
- challenge: &PaymentChallenge,
- signer: &dyn Signer,
- ctx: PaymentContext,
-) -> Result<FulfilledPayment, String> {
- let v = validate_challenge(challenge)?;
- log::debug!(
- "{LOG_PREFIX} fulfill purpose={} asset={} amount={} to={}",
- ctx.purpose,
- v.asset,
- v.amount,
- truncate(&v.to),
- );
-
- // Run the prepare + broadcast inside the tiny.place Solana endpoint scope so
- // both hit the tiny.place settlement RPC (where agent accounts are funded),
- // falling back to the public cluster only if that endpoint is unreachable.
- // Scoped to this task — general wallet ops are unaffected.
- let endpoints = tinyplace_solana_rpc_endpoints();
- log::debug!(
- "{LOG_PREFIX} settlement solana endpoints={} (primary + fallbacks)",
- endpoints.len()
- );
- let (quote_id, on_chain_tx) = with_tinyplace_solana_endpoints(endpoints, async {
- let prepared = prepare_transfer(to_transfer_params(&v)).await?.value;
- let quote_id = prepared.quote_id;
- log::debug!("{LOG_PREFIX} prepared transfer quote_id={quote_id}");
-
- let exec = execute_prepared(ExecutePreparedParams {
- quote_id: quote_id.clone(),
- confirmed: true,
- })
- .await?
- .value;
- Ok::<(String, String), String>((quote_id, exec.transaction_hash))
- })
- .await?;
- log::debug!(
- "{LOG_PREFIX} transfer broadcast tx={} quote_id={quote_id}",
- truncate(&on_chain_tx),
- );
-
- let payment_map = build_payment_map(signer, &v, &on_chain_tx, &ctx).await?;
- log::debug!(
- "{LOG_PREFIX} x402 authorization signed purpose={} nonce_present_in_challenge={}",
- ctx.purpose,
- v.nonce.is_some(),
- );
-
- Ok(FulfilledPayment {
- payment_map,
- on_chain_tx,
- quote_id,
- })
-}
-
-// ── Small helpers ─────────────────────────────────────────────────────────────
-
-/// Trim + treat empty as absent.
-fn non_empty(field: &Option<String>) -> Option<String> {
- field
- .as_ref()
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty())
-}
-
-/// True when `expires_at` parses to a time within [`EXPIRY_SKEW_SECS`] of now.
-/// Lenient on parse failure: logs and treats the challenge as non-expired (the
-/// backend remains the source of truth on expiry).
-fn is_expired(expires_at: &str) -> bool {
- match chrono::DateTime::parse_from_rfc3339(expires_at) {
- Ok(exp) => {
- let cutoff = chrono::Utc::now() + chrono::Duration::seconds(EXPIRY_SKEW_SECS);
- exp.with_timezone(&chrono::Utc) < cutoff
- }
- Err(e) => {
- log::warn!(
- "{LOG_PREFIX} could not parse challenge expiry '{expires_at}': {e}; \
- treating as non-expired"
- );
- false
- }
- }
-}
-
-/// Truncate an identifier for logs (`head…tail`). Char-based so it never panics
-/// on a multi-byte UTF-8 boundary. Never used on secret material.
-fn truncate(s: &str) -> String {
- let count = s.chars().count();
- if count <= 12 {
- s.to_string()
- } else {
- let head: String = s.chars().take(6).collect();
- let tail: String = s.chars().skip(count - 4).collect();
- format!("{head}…{tail}")
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use base64::engine::{general_purpose::STANDARD as B64, Engine as _};
- use ed25519_dalek::{Signature, SigningKey, Verifier};
- use tinyplace::signer::LocalSigner;
- use tinyplace::x402::{build_canonical_message, X402AuthorizationFields};
-
- const TEST_SEED: [u8; 32] = [7u8; 32];
-
- fn test_signer() -> LocalSigner {
- LocalSigner::from_seed(&TEST_SEED).expect("test seed is 32 bytes")
- }
-
- fn future_expiry() -> String {
- (chrono::Utc::now() + chrono::Duration::minutes(10))
- .format("%Y-%m-%dT%H:%M:%S%.3fZ")
- .to_string()
- }
-
- fn past_expiry() -> String {
- (chrono::Utc::now() - chrono::Duration::minutes(10))
- .format("%Y-%m-%dT%H:%M:%S%.3fZ")
- .to_string()
- }
-
- fn mock_challenge(asset: &str) -> PaymentChallenge {
- PaymentChallenge {
- scheme: Some("exact".into()),
- network: Some("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp".into()),
- asset: Some(asset.into()),
- amount: Some("10000000".into()),
- to: Some("FaciL1tatorBase58Recipient0000000000000000".into()),
- expires_at: Some(future_expiry()),
- ..Default::default()
- }
- }
-
- fn test_ctx() -> PaymentContext {
- let mut extra = HashMap::new();
- extra.insert("identity".to_string(), "@tester".to_string());
- PaymentContext {
- purpose: "identity.register".to_string(),
- nonce_prefix: "register".to_string(),
- extra_metadata: extra,
- }
- }
-
- // ── validate_challenge / asset routing ────────────────────────────────────
-
- #[test]
- fn validate_usdc_routes_to_spl() {
- let v = validate_challenge(&mock_challenge("USDC")).expect("valid");
- assert_eq!(v.asset_symbol.as_deref(), Some("USDC"));
- assert_eq!(v.asset, "USDC");
- assert_eq!(v.amount, "10000000");
- assert_eq!(v.to, "FaciL1tatorBase58Recipient0000000000000000");
- }
-
- #[test]
- fn validate_sol_routes_to_native() {
- let v = validate_challenge(&mock_challenge("SOL")).expect("valid");
- assert_eq!(v.asset_symbol, None);
- assert_eq!(v.asset, "SOL");
- }
-
- #[test]
- fn validate_rejects_unsupported_asset_without_leaking_identifier() {
- // #4199: the user-facing error must be human-readable and must NOT echo
- // the raw asset identifier (symbol or on-chain mint).
- let err = validate_challenge(&mock_challenge("WBTC")).unwrap_err();
- assert_eq!(err, "Payment asset not supported — please contact support.");
- assert!(!err.contains("WBTC"), "raw asset leaked to user: {err}");
-
- // A bogus mint address must likewise not be surfaced.
- let err = validate_challenge(&mock_challenge(
- "So1BogusMint1111111111111111111111111111111",
- ))
- .unwrap_err();
- assert_eq!(err, "Payment asset not supported — please contact support.");
- assert!(!err.contains("BogusMint"), "raw mint leaked to user: {err}");
- }
-
- #[test]
- fn validate_accepts_usdc_spl_mint_addresses() {
- // #4199: the backend sends USDC by its SPL mint, not the "USDC" symbol.
- // Both cluster mints must route to the SPL transfer.
- for mint in [
- SolanaCluster::Mainnet.usdc_mint(),
- SolanaCluster::Devnet.usdc_mint(),
- ] {
- let v = validate_challenge(&mock_challenge(mint)).expect("mint accepted");
- assert_eq!(v.asset_symbol.as_deref(), Some("USDC"));
- // The signed authorization echoes the backend-issued asset verbatim.
- assert_eq!(v.asset, mint);
- }
- }
-
- #[test]
- fn validate_rejects_missing_amount_or_to() {
- let mut c = mock_challenge("USDC");
- c.amount = None;
- assert!(validate_challenge(&c).unwrap_err().contains("amount"));
-
- let mut c = mock_challenge("USDC");
- c.to = Some(" ".into()); // whitespace counts as absent
- assert!(validate_challenge(&c).unwrap_err().contains("'to'"));
-
- let mut c = mock_challenge("USDC");
- c.network = None;
- assert!(validate_challenge(&c).unwrap_err().contains("network"));
- }
-
- #[test]
- fn validate_rejects_expired_challenge() {
- let mut c = mock_challenge("USDC");
- c.expires_at = Some(past_expiry());
- assert!(validate_challenge(&c).unwrap_err().contains("expired"));
- }
-
- #[test]
- fn validate_accepts_future_expiry() {
- let mut c = mock_challenge("USDC");
- c.expires_at = Some(future_expiry());
- assert!(validate_challenge(&c).is_ok());
- // Unparseable expiry is lenient (non-expired), not a hard failure.
- c.expires_at = Some("not-a-timestamp".into());
- assert!(validate_challenge(&c).is_ok());
- }
-
- // ── cluster guard (devnet R6; pure, env-independent) ──────────────────────
-
- #[test]
- fn classify_network_recognises_human_and_genesis_forms() {
- assert_eq!(
- classify_network("solana-devnet"),
- Some(SolanaCluster::Devnet)
- );
- assert_eq!(
- classify_network("solana-mainnet-beta"),
- Some(SolanaCluster::Mainnet)
- );
- // CAIP-2 genesis-hash references.
- assert_eq!(
- classify_network("solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1xyz"),
- Some(SolanaCluster::Devnet)
- );
- assert_eq!(
- classify_network("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"),
- Some(SolanaCluster::Mainnet)
- );
- // Unrecognised → None (allowed through; backend is source of truth).
- assert_eq!(classify_network("solana:someunknownhash"), None);
- assert_eq!(classify_network("solana-testnet"), None);
- }
-
- #[test]
- fn cluster_guard_is_advisory_never_blocks() {
- // Match → Ok.
- assert!(cluster_guard(SolanaCluster::Devnet, "solana-devnet").is_ok());
- assert!(cluster_guard(SolanaCluster::Mainnet, "solana-mainnet").is_ok());
- // Mismatch → still Ok (advisory only; tiny.place labels every cluster with
- // the mainnet genesis, so the label is not authoritative). This is the
- // exact case that previously blocked valid devnet payments.
- assert!(cluster_guard(SolanaCluster::Devnet, "solana-mainnet").is_ok());
- assert!(cluster_guard(
- SolanaCluster::Devnet,
- "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
- )
- .is_ok());
- assert!(cluster_guard(SolanaCluster::Mainnet, "solana-devnet").is_ok());
- // Unknown network → Ok regardless of configured cluster.
- assert!(cluster_guard(SolanaCluster::Devnet, "solana:unknownhash").is_ok());
- }
-
- #[test]
- fn ensure_cluster_matches_never_blocks() {
- // Env-independent: advisory check is Ok for any network, including the
- // mainnet-genesis label tiny.place emits on devnet.
- assert!(ensure_cluster_matches("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp").is_ok());
- assert!(ensure_cluster_matches("solana:unparseable-network-id").is_ok());
- }
-
- // ── mint cross-check (pure, no env, no network) ─────────────────────────
-
- /// Known USDC mint addresses for the test assertions.
- const MAINNET_USDC: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
- const DEVNET_USDC: &str = "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU";
-
- #[test]
- fn mint_cross_check_match_devnet() {
- // configured=devnet, backend=devnet → Ok
- assert!(mint_cross_check(DEVNET_USDC, Some(DEVNET_USDC)).is_ok());
- }
-
- #[test]
- fn mint_cross_check_match_mainnet() {
- // configured=mainnet, backend=mainnet → Ok
- assert!(mint_cross_check(MAINNET_USDC, Some(MAINNET_USDC)).is_ok());
- }
-
- #[test]
- fn mint_cross_check_mismatch_configured_mainnet_backend_devnet() {
- // configured=mainnet, backend=devnet → Err (the real-funds danger case)
- let err = mint_cross_check(MAINNET_USDC, Some(DEVNET_USDC)).unwrap_err();
- assert!(
- err.contains("cluster mismatch"),
- "error should mention mismatch, got: {err}"
- );
- assert!(
- err.contains(MAINNET_USDC),
- "error should cite the configured mint, got: {err}"
- );
- assert!(
- err.contains(DEVNET_USDC),
- "error should cite the backend mint, got: {err}"
- );
- }
-
- #[test]
- fn mint_cross_check_mismatch_configured_devnet_backend_mainnet() {
- // configured=devnet, backend=mainnet → Err
- let err = mint_cross_check(DEVNET_USDC, Some(MAINNET_USDC)).unwrap_err();
- assert!(err.contains("cluster mismatch"), "got: {err}");
- }
-
- #[test]
- fn mint_cross_check_backend_usdc_not_found() {
- // Backend did not include a USDC asset → Ok (fail-open)
- assert!(mint_cross_check(MAINNET_USDC, None).is_ok());
- assert!(mint_cross_check(DEVNET_USDC, None).is_ok());
- }
-
- #[test]
- fn mint_cross_check_with_unknown_mint() {
- // Backend reports an unknown mint → Err (mismatch)
- let err = mint_cross_check(DEVNET_USDC, Some("SomeOtherMintAddress123")).unwrap_err();
- assert!(err.contains("cluster mismatch"), "got: {err}");
- }
-
- // ── truncate (log helper) ─────────────────────────────────────────────────
-
- #[test]
- fn truncate_is_char_boundary_safe() {
- // ASCII base58/base64 (the real inputs) abbreviate as head…tail.
- assert_eq!(truncate("5SoLaNaTxSignature0000"), "5SoLaN…0000");
- assert_eq!(truncate("short"), "short");
- // Multi-byte UTF-8 must not panic on a byte-boundary slice.
- let multibyte = "日本語のながいテキストです1234";
- let out = truncate(multibyte); // would panic with byte slicing
- assert!(out.contains('…'));
- }
-
- // ── to_transfer_params ────────────────────────────────────────────────────
-
- #[test]
- fn transfer_params_shape() {
- let v = validate_challenge(&mock_challenge("USDC")).unwrap();
- let p = to_transfer_params(&v);
- assert_eq!(p.chain, WalletChain::Solana);
- assert_eq!(p.to_address, v.to);
- assert_eq!(p.amount_raw, "10000000");
- assert_eq!(p.asset_symbol.as_deref(), Some("USDC"));
- assert!(p.evm_network.is_none());
- }
-
- // ── build_payment_map (offline; deterministic test signer) ────────────────
-
- async fn build_map(asset: &str, ctx: &PaymentContext, on_chain_tx: &str) -> X402PaymentMap {
- let signer = test_signer();
- let v = validate_challenge(&mock_challenge(asset)).unwrap();
- build_payment_map(&signer, &v, on_chain_tx, ctx)
- .await
- .expect("payment map")
- }
-
- #[tokio::test]
- async fn payment_map_has_core_fields() {
- let signer = test_signer();
- let map = build_map(
- "USDC",
- &test_ctx(),
- "5SoLaNaTxSignature000000000000000000000000",
- )
- .await;
- assert_eq!(map.get("scheme").map(String::as_str), Some("exact"));
- assert_eq!(
- map.get("network").map(String::as_str),
- Some("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp")
- );
- assert_eq!(map.get("asset").map(String::as_str), Some("USDC"));
- assert_eq!(map.get("amount").map(String::as_str), Some("10000000"));
- assert_eq!(
- map.get("from").map(String::as_str),
- Some(signer.agent_id().as_str())
- );
- assert_eq!(
- map.get("to").map(String::as_str),
- Some("FaciL1tatorBase58Recipient0000000000000000")
- );
- assert!(map.contains_key("nonce"));
- assert!(map.contains_key("expiresAt"));
- assert!(map.contains_key("signature"));
- }
-
- #[tokio::test]
- async fn on_chain_tx_in_references_not_signature() {
- let tx = "5SoLaNaTxSignature000000000000000000000000";
- let map = build_map("USDC", &test_ctx(), tx).await;
- // On-chain tx is carried as references, top-level and in signed metadata.
- assert_eq!(map.get("onChainTx").map(String::as_str), Some(tx));
- assert_eq!(map.get("tx").map(String::as_str), Some(tx));
- assert_eq!(map.get("transaction").map(String::as_str), Some(tx));
- // The `signature` field is the off-chain Ed25519 authorization sig — NOT
- // the on-chain tx signature.
- assert_ne!(map.get("signature").map(String::as_str), Some(tx));
- let sig = map.get("signature").expect("signature present");
- let raw = B64.decode(sig).expect("signature is base64");
- assert_eq!(raw.len(), 64, "Ed25519 signature is 64 bytes");
- }
-
- #[tokio::test]
- async fn purpose_and_extra_metadata_in_map() {
- let map = build_map(
- "USDC",
- &test_ctx(),
- "5SoLaNaTx000000000000000000000000000000000",
- )
- .await;
- assert_eq!(
- map.get("metadata.purpose").map(String::as_str),
- Some("identity.register")
- );
- assert_eq!(
- map.get("metadata.identity").map(String::as_str),
- Some("@tester")
- );
- }
-
- #[tokio::test]
- async fn nonce_prefix_used_when_challenge_nonce_absent() {
- // mock_challenge leaves nonce = None.
- let map = build_map(
- "USDC",
- &test_ctx(),
- "5SoLaNaTx000000000000000000000000000000000",
- )
- .await;
- let nonce = map.get("nonce").expect("nonce");
- assert!(nonce.starts_with("register_"), "got: {nonce}");
- }
-
- #[tokio::test]
- async fn challenge_nonce_preferred_when_present() {
- let signer = test_signer();
- let mut c = mock_challenge("USDC");
- c.nonce = Some("challenge-supplied-nonce".into());
- let v = validate_challenge(&c).unwrap();
- let map = build_payment_map(
- &signer,
- &v,
- "5SoLaNaTx000000000000000000000000000000000",
- &test_ctx(),
- )
- .await
- .unwrap();
- assert_eq!(
- map.get("nonce").map(String::as_str),
- Some("challenge-supplied-nonce")
- );
- }
-
- #[tokio::test]
- async fn signature_verifies_against_pubkey() {
- // Reconstruct the signed canonical message from the flattened map and
- // verify the authorization signature against the signer's public key —
- // exactly what the backend does.
- let tx = "5SoLaNaTxSignature000000000000000000000000";
- let map = build_map("USDC", &test_ctx(), tx).await;
-
- let metadata: HashMap<String, String> = map
- .iter()
- .filter_map(|(k, val)| {
- k.strip_prefix("metadata.")
- .map(|kk| (kk.to_string(), val.clone()))
- })
- .collect();
- let fields = X402AuthorizationFields {
- scheme: map["scheme"].clone(),
- network: map["network"].clone(),
- asset: map["asset"].clone(),
- amount: map["amount"].clone(),
- from: map["from"].clone(),
- to: map["to"].clone(),
- nonce: map["nonce"].clone(),
- expires_at: map["expiresAt"].clone(),
- metadata: Some(metadata),
- };
- let canonical = build_canonical_message(&fields);
-
- let sig_bytes = B64.decode(&map["signature"]).expect("base64 signature");
- let signature = Signature::from_slice(&sig_bytes).expect("64-byte signature");
- let verifying_key = SigningKey::from_bytes(&TEST_SEED).verifying_key();
-
- verifying_key
- .verify(canonical.as_bytes(), &signature)
- .expect("authorization signature verifies over the canonical message");
- }
-}
diff --git a/src/openhuman/tinyplace/schemas.rs b/src/openhuman/tinyplace/schemas.rs
deleted file mode 100644
index fe2a83af0e..0000000000
--- a/src/openhuman/tinyplace/schemas.rs
+++ /dev/null
@@ -1,3736 +0,0 @@
-//! Controller schemas and registered-controller list for the tinyplace namespace.
-//!
-//! These controllers are registered in the **internal** registry (callable via
-//! `core_rpc_relay` by the renderer, but NOT advertised to agents via tool
-//! listings or schema discovery).
-//!
-//! RPC method names follow the standard pattern:
-//! `openhuman.tinyplace_<function>`
-//! e.g. `openhuman.tinyplace_directory_list_agents`.
-
-use crate::core::all::RegisteredController;
-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-
-use crate::openhuman::tinyplace::manifest::{
- handle_tinyplace_artifacts_get,
- handle_tinyplace_artifacts_list,
- // Bounties section (Phase B)
- handle_tinyplace_bounties_approve,
- handle_tinyplace_bounties_cancel,
- handle_tinyplace_bounties_comment,
- handle_tinyplace_bounties_create,
- handle_tinyplace_bounties_get,
- handle_tinyplace_bounties_list,
- handle_tinyplace_bounties_list_comments,
- handle_tinyplace_bounties_list_submissions,
- handle_tinyplace_bounties_run_council,
- handle_tinyplace_bounties_submit,
- handle_tinyplace_broadcasts_list,
- handle_tinyplace_broadcasts_subscribe,
- handle_tinyplace_broadcasts_unsubscribe,
- handle_tinyplace_channels_join,
- handle_tinyplace_channels_leave,
- handle_tinyplace_channels_list,
- handle_tinyplace_contacts_accept,
- handle_tinyplace_contacts_block,
- handle_tinyplace_contacts_list,
- handle_tinyplace_contacts_remove,
- handle_tinyplace_contacts_request,
- handle_tinyplace_contacts_requests,
- handle_tinyplace_contacts_stats,
- handle_tinyplace_contacts_status,
- handle_tinyplace_contacts_unblock,
- handle_tinyplace_directory_find_by_encryption_key,
- handle_tinyplace_directory_get_agent,
- handle_tinyplace_directory_list_agents,
- handle_tinyplace_directory_list_identities,
- handle_tinyplace_directory_resolve,
- handle_tinyplace_directory_reverse,
- handle_tinyplace_directory_skills,
- handle_tinyplace_escrow_get,
- handle_tinyplace_escrow_list,
- handle_tinyplace_explorer_overview,
- handle_tinyplace_feedback_create,
- handle_tinyplace_feedback_get,
- handle_tinyplace_feedback_list,
- handle_tinyplace_feedback_vote,
- // Feeds write surface handlers (Phase A)
- handle_tinyplace_feeds_add_comment,
- handle_tinyplace_feeds_create_post,
- handle_tinyplace_feeds_delete_comment,
- handle_tinyplace_feeds_delete_post,
- handle_tinyplace_feeds_like_post,
- handle_tinyplace_feeds_unlike_post,
- handle_tinyplace_follows_feed,
- handle_tinyplace_follows_follow,
- handle_tinyplace_follows_followers,
- handle_tinyplace_follows_following,
- handle_tinyplace_follows_stats,
- handle_tinyplace_follows_unfollow,
- // GraphQL Profile + Identity handlers
- handle_tinyplace_graphql_agent_card,
- handle_tinyplace_graphql_agents,
- handle_tinyplace_graphql_bounties,
- handle_tinyplace_graphql_bounty,
- // GraphQL Social Feed handlers
- handle_tinyplace_graphql_home_feed,
- handle_tinyplace_graphql_identities,
- handle_tinyplace_graphql_identity,
- handle_tinyplace_graphql_identity_bids,
- handle_tinyplace_graphql_identity_listing,
- handle_tinyplace_graphql_identity_listings,
- handle_tinyplace_graphql_identity_offers,
- handle_tinyplace_graphql_identity_sales,
- // GraphQL Jobs handlers
- handle_tinyplace_graphql_job,
- handle_tinyplace_graphql_jobs,
- // GraphQL Ledger handlers
- handle_tinyplace_graphql_ledger_transaction,
- handle_tinyplace_graphql_ledger_transactions,
- handle_tinyplace_graphql_post,
- handle_tinyplace_graphql_post_comments,
- handle_tinyplace_graphql_post_likers,
- handle_tinyplace_graphql_posts,
- handle_tinyplace_graphql_product,
- handle_tinyplace_graphql_products,
- handle_tinyplace_graphql_profile,
- handle_tinyplace_graphql_user,
- handle_tinyplace_groups_create_invite,
- handle_tinyplace_groups_join,
- handle_tinyplace_groups_leave,
- handle_tinyplace_groups_list,
- handle_tinyplace_groups_list_invites,
- handle_tinyplace_groups_preview_invite,
- handle_tinyplace_groups_redeem_invite,
- handle_tinyplace_groups_revoke_invite,
- handle_tinyplace_groups_set_member_role,
- handle_tinyplace_inbox_archive,
- handle_tinyplace_inbox_counts,
- handle_tinyplace_inbox_list,
- handle_tinyplace_inbox_mark_all_read,
- handle_tinyplace_inbox_mark_read,
- handle_tinyplace_inbox_remove,
- handle_tinyplace_inbox_unarchive,
- handle_tinyplace_jobs_adjudicate_dispute,
- handle_tinyplace_jobs_apply,
- handle_tinyplace_jobs_cancel,
- handle_tinyplace_jobs_create,
- handle_tinyplace_jobs_get,
- handle_tinyplace_jobs_get_proposal,
- handle_tinyplace_jobs_list,
- handle_tinyplace_jobs_list_proposals,
- handle_tinyplace_jobs_open_dispute,
- handle_tinyplace_jobs_select,
- handle_tinyplace_jobs_shortlist_proposal,
- handle_tinyplace_jobs_withdraw_proposal,
- handle_tinyplace_marketplace_bid,
- handle_tinyplace_marketplace_browse,
- handle_tinyplace_marketplace_buy_identity,
- handle_tinyplace_marketplace_buy_product,
- handle_tinyplace_marketplace_categories,
- handle_tinyplace_marketplace_featured,
- handle_tinyplace_marketplace_get_product,
- handle_tinyplace_marketplace_identity_floor,
- handle_tinyplace_marketplace_identity_sale_history,
- handle_tinyplace_marketplace_list_bids,
- handle_tinyplace_marketplace_list_identities,
- handle_tinyplace_marketplace_list_offers,
- handle_tinyplace_marketplace_list_product_reviews,
- handle_tinyplace_marketplace_list_products,
- handle_tinyplace_marketplace_offer,
- handle_tinyplace_marketplace_recent,
- handle_tinyplace_messages_acknowledge,
- handle_tinyplace_messages_list,
- handle_tinyplace_profiles_activity,
- handle_tinyplace_profiles_agent_card,
- handle_tinyplace_profiles_attestations,
- handle_tinyplace_profiles_broadcasts,
- handle_tinyplace_profiles_get,
- handle_tinyplace_profiles_groups,
- handle_tinyplace_registry_assign_primary,
- handle_tinyplace_registry_export,
- handle_tinyplace_registry_get,
- handle_tinyplace_registry_register,
- handle_tinyplace_registry_transfer,
- handle_tinyplace_search_unified,
- handle_tinyplace_signal_decrypt_message,
- handle_tinyplace_signal_get_bundle,
- handle_tinyplace_signal_key_status,
- handle_tinyplace_signal_provision,
- handle_tinyplace_signal_register_encryption_key,
- handle_tinyplace_signal_rotate_signed_pre_key,
- handle_tinyplace_signal_send_message,
- handle_tinyplace_signal_upload_pre_keys,
- handle_tinyplace_solana_call,
- handle_tinyplace_solana_info,
- handle_tinyplace_streams_list,
- handle_tinyplace_streams_start,
- handle_tinyplace_streams_stop,
- handle_tinyplace_users_confirm_email_verification,
- handle_tinyplace_users_get,
- handle_tinyplace_users_start_email_verification,
- handle_tinyplace_users_update_profile,
-};
-
-// ── Schema helpers ────────────────────────────────────────────────────────────
-
-fn optional_object(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment,
- required: false,
- }
-}
-
-fn required_object(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Json,
- comment,
- required: true,
- }
-}
-
-fn required_string(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::String,
- comment,
- required: true,
- }
-}
-
-fn json_output(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Json,
- comment,
- required: true,
- }
-}
-
-// ── Schema definitions ────────────────────────────────────────────────────────
-
-fn optional_product_query_params() -> FieldSchema {
- optional_object(
- "params",
- "Optional ProductQueryParams (q, category, seller, tags, minPrice, maxPrice, sortBy, limit, offset).",
- )
-}
-
-fn schema_directory_list_agents() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "directory_list_agents",
- description:
- "List agents in the tiny.place directory, optionally filtered by query params.",
- inputs: vec![optional_object(
- "params",
- "Optional AgentQueryParams (limit, cursor, q, skill, tag, etc.).",
- )],
- outputs: vec![json_output(
- "result",
- "ListAgentsResponse containing a list of AgentCard objects.",
- )],
- }
-}
-
-fn schema_directory_get_agent() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "directory_get_agent",
- description: "Fetch a single agent's card from the tiny.place directory by agent ID.",
- inputs: vec![required_string(
- "agentId",
- "The agent's base58 Solana address / tiny.place identity.",
- )],
- outputs: vec![json_output("result", "AgentCard for the requested agent.")],
- }
-}
-
-fn schema_directory_resolve() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "directory_resolve",
- description:
- "Resolve a tiny.place name (e.g. 'alice.agent') to its identity and agent card.",
- inputs: vec![required_string(
- "name",
- "The tiny.place name or handle to resolve.",
- )],
- outputs: vec![json_output(
- "result",
- "ResolveResponse with identity and optional AgentCard.",
- )],
- }
-}
-
-fn schema_directory_reverse() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "directory_reverse",
- description:
- "Reverse-lookup a crypto_id (base58 Solana address) to its tiny.place identities.",
- inputs: vec![required_string(
- "cryptoId",
- "The base58 Solana address / crypto identity to look up.",
- )],
- outputs: vec![json_output(
- "result",
- "ReverseResponse with the crypto_id, associated identities, and optional agent list.",
- )],
- }
-}
-
-fn schema_directory_list_identities() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "directory_list_identities",
- description: "List identity listings in the tiny.place directory, with optional filtering.",
- inputs: vec![optional_object(
- "params",
- "Optional IdentityListingQueryParams (q, tag, category, seller, price range, etc.).",
- )],
- outputs: vec![json_output(
- "result",
- "DirectoryIdentityListingsResponse with identity listings and optional cursor.",
- )],
- }
-}
-
-fn schema_directory_skills() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "directory_skills",
- description: "Search for agent skills registered in the tiny.place directory.",
- inputs: vec![optional_object(
- "params",
- "Optional DirectorySkillsParams (q, limit, cursor).",
- )],
- outputs: vec![json_output(
- "result",
- "AgentSearchResponse with matched agents and optional cursor.",
- )],
- }
-}
-
-fn schema_explorer_overview() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "explorer_overview",
- description:
- "Return the public tiny.place explorer overview (network stats, recent transactions).",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "ExplorerOverview with network-wide summary data.",
- )],
- }
-}
-
-fn schema_search_unified() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "search_unified",
- description:
- "Run a unified search across agents, groups, channels, and broadcasts on tiny.place.",
- inputs: vec![required_string("query", "Free-text search query.")],
- outputs: vec![json_output("result", "SearchResponse with ranked matches.")],
- }
-}
-
-// ── Profiles schemas ──────────────────────────────────────────────────────────
-
-fn schema_profiles_get() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "profiles_get",
- description: "Fetch the public agent profile for a given tiny.place username.",
- inputs: vec![required_string(
- "username",
- "The tiny.place @handle / username to look up.",
- )],
- outputs: vec![json_output(
- "result",
- "AgentProfile for the requested user.",
- )],
- }
-}
-
-fn schema_profiles_activity() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "profiles_activity",
- description: "Fetch recent on-chain activity for a given tiny.place username.",
- inputs: vec![required_string(
- "username",
- "The tiny.place @handle to look up.",
- )],
- outputs: vec![json_output(
- "result",
- "ProfileActivity containing recent transactions and events.",
- )],
- }
-}
-
-fn schema_profiles_groups() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "profiles_groups",
- description: "List groups a given tiny.place username is a member of.",
- inputs: vec![required_string(
- "username",
- "The tiny.place @handle to look up.",
- )],
- outputs: vec![json_output(
- "result",
- "ProfileGroupsResponse containing an array of ProfileGroupMembership.",
- )],
- }
-}
-
-fn schema_profiles_broadcasts() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "profiles_broadcasts",
- description: "Fetch broadcasts published by a given tiny.place username.",
- inputs: vec![required_string(
- "username",
- "The tiny.place @handle to look up.",
- )],
- outputs: vec![json_output(
- "result",
- "ProfileBroadcastsResponse containing an array of ProfileBroadcast.",
- )],
- }
-}
-
-fn schema_profiles_attestations() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "profiles_attestations",
- description: "Fetch trust attestations for a given tiny.place username.",
- inputs: vec![required_string(
- "username",
- "The tiny.place @handle to look up.",
- )],
- outputs: vec![json_output(
- "result",
- "ProfileAttestationsResponse containing an array of ProfileAttestation.",
- )],
- }
-}
-
-fn schema_profiles_agent_card() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "profiles_agent_card",
- description: "Fetch the machine-readable AgentCard for a given tiny.place username.",
- inputs: vec![required_string(
- "username",
- "The tiny.place @handle to look up.",
- )],
- outputs: vec![json_output("result", "AgentCard for the requested user.")],
- }
-}
-
-// ── Users schemas ─────────────────────────────────────────────────────────────
-
-fn schema_users_get() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "users_get",
- description: "Fetch a wallet's User profile by its cryptoId.",
- inputs: vec![required_string(
- "cryptoId",
- "The wallet's base58 Solana address / cryptoId.",
- )],
- outputs: vec![json_output(
- "result",
- "User profile for the given cryptoId.",
- )],
- }
-}
-
-fn schema_users_update_profile() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "users_update_profile",
- description:
- "Update the signed-in wallet's User profile (display name, bio, avatar, links, tags).",
- inputs: vec![
- required_string("cryptoId", "The wallet's base58 Solana address / cryptoId."),
- FieldSchema {
- name: "update",
- ty: TypeSchema::Json,
- comment:
- "UserProfileUpdate object (displayName, bio, avatar, links, tags, actorType).",
- required: true,
- },
- ],
- outputs: vec![json_output(
- "result",
- "Updated User profile after the write.",
- )],
- }
-}
-
-// ── Public exports ────────────────────────────────────────────────────────────
-
-fn optional_integer(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Option(Box::new(TypeSchema::I64)),
- comment,
- required: false,
- }
-}
-fn optional_string(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment,
- required: false,
- }
-}
-fn schema_marketplace_identity_floor() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_identity_floor",
- description:
- "Fetch the floor price for identity names of a given character length on the marketplace.",
- inputs: vec![optional_integer(
- "length",
- "Character length to query the floor price for (e.g. 3 for 3-char handles).",
- )],
- outputs: vec![json_output(
- "result",
- "IdentityFloor { length, price: MarketplacePrice }.",
- )],
- }
-}
-fn schema_marketplace_identity_sale_history() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_identity_sale_history",
- description: "Fetch the full sale history for a specific @handle identity.",
- inputs: vec![required_string(
- "name",
- "The handle to look up sale history for (with leading @).",
- )],
- outputs: vec![json_output(
- "result",
- "IdentitySaleHistoryResponse { history: IdentitySale[] }.",
- )],
- }
-}
-fn schema_marketplace_list_bids() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_list_bids",
- description: "List bids on a specific identity auction listing.",
- inputs: vec![required_string(
- "listingId",
- "The listing ID to retrieve bids for.",
- )],
- outputs: vec![json_output(
- "result",
- "BidsResponse { bids: IdentityBid[] }.",
- )],
- }
-}
-fn schema_marketplace_list_identities() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_list_identities",
- description:
- "List identity (@handle) listings currently for sale on the tiny.place marketplace.",
- inputs: vec![
- optional_integer("limit", "Maximum number of results to return."),
- optional_string("status", "Filter by listing status, e.g. 'active'."),
- ],
- outputs: vec![json_output(
- "result",
- "IdentitiesResponse { identities: IdentityListing[] }.",
- )],
- }
-}
-fn schema_marketplace_list_offers() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_list_offers",
- description: "List pending identity offers, optionally filtered by target handle or buyer.",
- inputs: vec![
- optional_string(
- "name",
- "Filter by the @handle the offer targets (for sellers).",
- ),
- optional_string(
- "buyer",
- "Filter by buyer identity (review your own outstanding offers).",
- ),
- ],
- outputs: vec![json_output(
- "result",
- "OffersResponse { offers: IdentityOffer[] }.",
- )],
- }
-}
-fn schema_marketplace_recent() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_recent",
- description: "List the most recent completed identity sales on the tiny.place marketplace.",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "RecentSalesResponse { sales: IdentitySale[] }.",
- )],
- }
-}
-fn schema_registry_get() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "registry_get",
- description:
- "Check the availability of a @handle and return its identity if it is registered.",
- inputs: vec![required_string(
- "name",
- "The handle to look up (with or without a leading @).",
- )],
- outputs: vec![json_output(
- "result",
- "AvailabilityResponse { available, name, identity? }.",
- )],
- }
-}
-
-fn buy_confirmed_input() -> FieldSchema {
- FieldSchema {
- name: "confirmed",
- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
- comment: "When true, fulfils the x402 payment on-chain and completes the purchase. \
- Defaults to false (challenge-only, no spend).",
- required: false,
- }
-}
-
-fn schema_marketplace_buy_product() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_buy_product",
- description:
- "Buy a marketplace product via x402 confirm-before-spend. confirmed=false returns the \
- 402 challenge + wallet balance (no spend); confirmed=true pays and completes the buy.",
- inputs: vec![
- required_string("id", "The product ID to buy."),
- buy_confirmed_input(),
- ],
- outputs: vec![json_output(
- "result",
- "Either { result: ProductPurchase }, { challenge, walletBalance, walletAddress } \
- (unconfirmed), or { result: ProductPurchase, payment: { onChainTx } } (paid).",
- )],
- }
-}
-
-fn schema_marketplace_buy_identity() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_buy_identity",
- description:
- "Buy an identity listing (a @handle at its fixed price) via x402 confirm-before-spend. \
- confirmed=false returns the challenge + balance; confirmed=true pays and completes.",
- inputs: vec![
- required_string("id", "The identity listing ID to buy."),
- buy_confirmed_input(),
- ],
- outputs: vec![json_output(
- "result",
- "Either { result: IdentitySale }, { challenge, walletBalance, walletAddress } \
- (unconfirmed), or { result: IdentitySale, payment: { onChainTx } } (paid).",
- )],
- }
-}
-
-fn price_inputs() -> Vec<FieldSchema> {
- vec![
- required_string("amount", "Bid/offer amount in the asset's base units."),
- FieldSchema {
- name: "asset",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Asset symbol (defaults to USDC).",
- required: false,
- },
- required_string(
- "network",
- "Solana network for the x402 authorization (e.g. the listing's price network).",
- ),
- ]
-}
-
-fn schema_marketplace_bid() -> ControllerSchema {
- let mut inputs = vec![required_string(
- "listingId",
- "The auction listing ID to bid on.",
- )];
- inputs.extend(price_inputs());
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_bid",
- description:
- "Place a bid on an identity auction listing. The SDK builds and signs the x402 \
- authorization (an up-to commitment); no on-chain transfer happens until acceptance.",
- inputs,
- outputs: vec![json_output(
- "result",
- "{ result: IdentityListing (updated), committed: true }.",
- )],
- }
-}
-
-fn schema_marketplace_offer() -> ControllerSchema {
- let mut inputs = vec![required_string(
- "name",
- "The @handle to make an offer on (with or without a leading @).",
- )];
- inputs.extend(price_inputs());
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_offer",
- description:
- "Make an offer to buy an identity (@handle). The SDK builds and signs the x402 \
- authorization; no on-chain transfer happens until the offer is accepted.",
- inputs,
- outputs: vec![json_output(
- "result",
- "{ result: IdentityOffer, committed: true }.",
- )],
- }
-}
-
-fn schema_registry_register() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "registry_register",
- description:
- "Register a @handle via x402 confirm-before-spend. Call with confirmed=false to get the \
- 402 challenge + wallet balance (no spend); confirmed=true pays on-chain and registers.",
- inputs: vec![
- required_string("username", "The handle to register (with or without a leading @)."),
- FieldSchema {
- name: "confirmed",
- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
- comment: "When true, fulfils the x402 payment on-chain and registers. \
- Defaults to false (challenge-only, no spend).",
- required: false,
- },
- FieldSchema {
- name: "actorType",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Self-declared actor type recorded on the wallet's profile \
- (\"human\"/\"agent\"). Defaults to \"human\".",
- required: false,
- },
- FieldSchema {
- name: "primary",
- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
- comment: "Request this name be assigned as the wallet's primary handle.",
- required: false,
- },
- ],
- outputs: vec![json_output(
- "result",
- "Either { identity } (registered), { challenge, walletBalance, walletAddress } \
- (unconfirmed), or { identity, payment: { onChainTx } } (paid).",
- )],
- }
-}
-
-fn schema_artifacts_get() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "artifacts_get",
- description: "Fetch a single artifact by its ID.",
- inputs: vec![
- required_string("artifactId", "The artifact's unique identifier."),
- FieldSchema {
- name: "actorId",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional agent identity to act as.",
- required: false,
- },
- ],
- outputs: vec![json_output("result", "Artifact object.")],
- }
-}
-
-fn schema_artifacts_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "artifacts_list",
- description: "List encrypted artifacts owned by or shared with the acting agent.",
- inputs: vec![
- optional_object(
- "params",
- "Optional ArtifactQueryParams (role, status, referenceKind, referenceId, limit, cursor).",
- ),
- FieldSchema {
- name: "actorId",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional agent identity to act as.",
- required: false,
- },
- ],
- outputs: vec![json_output(
- "result",
- "ArtifactListResult { artifacts: Artifact[]; cursor?: string }.",
- )],
- }
-}
-
-fn schema_escrow_get() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "escrow_get",
- description: "Fetch a single escrow contract by its ID.",
- inputs: vec![required_string(
- "escrowId",
- "The escrow's unique identifier.",
- )],
- outputs: vec![json_output("result", "Escrow object.")],
- }
-}
-
-fn schema_escrow_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "escrow_list",
- description: "List escrow contracts associated with the authenticated agent.",
- inputs: vec![optional_object(
- "params",
- "Optional EscrowQueryParams (role, status, limit, offset).",
- )],
- outputs: vec![json_output(
- "result",
- "EscrowListResponse { escrows: Escrow[] }.",
- )],
- }
-}
-
-fn schema_jobs_get() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_get",
- description: "Fetch a single job posting by its ID.",
- inputs: vec![required_string(
- "jobId",
- "The job posting's unique identifier.",
- )],
- outputs: vec![json_output("result", "JobPosting object.")],
- }
-}
-
-fn schema_jobs_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_list",
- description: "List job postings on the tiny.place marketplace.",
- inputs: vec![optional_object(
- "params",
- "Optional JobQueryParams (status, skill, q, limit, offset).",
- )],
- outputs: vec![json_output(
- "result",
- "JobListResponse { jobs: JobPosting[] }.",
- )],
- }
-}
-
-fn schema_jobs_create() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_create",
- description: "Post a new job to the tiny.place marketplace. Actor is resolved from the wallet signer.",
- inputs: vec![
- required_string("title", "Job title (non-blank)."),
- required_string("budgetAmount", "Budget amount (e.g. '100')."),
- required_string("budgetAsset", "Budget asset symbol (e.g. 'USDC')."),
- optional_string("description", "Job description."),
- optional_string("category", "Job category tag."),
- optional_string("budgetChain", "Optional chain for the budget (e.g. 'solana')."),
- optional_string("proposalDeadline", "Optional ISO-8601 deadline for proposals."),
- optional_object("skills", "Optional array of required skill strings."),
- ],
- outputs: vec![json_output("result", "JobPosting object for the newly created job.")],
- }
-}
-
-fn schema_jobs_cancel() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_cancel",
- description: "Cancel a job posting. Actor is resolved from the wallet signer.",
- inputs: vec![required_string(
- "jobId",
- "The job posting's unique identifier.",
- )],
- outputs: vec![json_output("result", "Updated JobPosting object.")],
- }
-}
-
-fn schema_jobs_apply() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_apply",
- description: "Submit a proposal for a job. Candidate is resolved from the wallet signer.",
- inputs: vec![
- required_string("jobId", "The job posting's unique identifier."),
- optional_string("coverLetter", "Optional cover letter text."),
- optional_string("bidAmount", "Optional bid amount string."),
- optional_string(
- "estimatedDelivery",
- "Optional estimated delivery date (ISO-8601).",
- ),
- optional_object("pastWork", "Optional array of past-work URL strings."),
- ],
- outputs: vec![json_output(
- "result",
- "Proposal object for the submitted application.",
- )],
- }
-}
-
-fn schema_jobs_list_proposals() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_list_proposals",
- description: "List proposals for a job. Restricted to the job's client (resolved from wallet signer).",
- inputs: vec![
- required_string("jobId", "The job posting's unique identifier."),
- optional_string("status", "Optional filter by proposal status."),
- optional_integer("limit", "Maximum number of proposals to return."),
- optional_integer("offset", "Pagination offset."),
- ],
- outputs: vec![json_output(
- "result",
- "ProposalListResponse { proposals: Proposal[] }.",
- )],
- }
-}
-
-fn schema_jobs_get_proposal() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_get_proposal",
- description: "Fetch a single proposal by ID. Actor is resolved from the wallet signer.",
- inputs: vec![
- required_string("jobId", "The job posting's unique identifier."),
- required_string("proposalId", "The proposal's unique identifier."),
- ],
- outputs: vec![json_output("result", "Proposal object.")],
- }
-}
-
-fn schema_jobs_shortlist_proposal() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_shortlist_proposal",
- description: "Shortlist a proposal as a client. Actor is resolved from the wallet signer.",
- inputs: vec![
- required_string("jobId", "The job posting's unique identifier."),
- required_string("proposalId", "The proposal's unique identifier."),
- ],
- outputs: vec![json_output("result", "Updated Proposal object.")],
- }
-}
-
-fn schema_jobs_withdraw_proposal() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_withdraw_proposal",
- description: "Withdraw a submitted proposal as a candidate. Actor is resolved from the wallet signer.",
- inputs: vec![
- required_string("jobId", "The job posting's unique identifier."),
- required_string("proposalId", "The proposal's unique identifier."),
- ],
- outputs: vec![json_output("result", "Updated Proposal object.")],
- }
-}
-
-fn schema_jobs_select() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_select",
- description: "Select a proposal/candidate for a job, spawning an escrow contract. Client is resolved from the wallet signer.",
- inputs: vec![
- required_string("jobId", "The job posting's unique identifier."),
- required_string("proposalId", "The proposal to select."),
- optional_string("network", "Optional network override (e.g. 'solana')."),
- ],
- outputs: vec![json_output(
- "result",
- "SelectCandidateResult { job: JobPosting, contract_escrow_id: String }.",
- )],
- }
-}
-
-fn schema_jobs_open_dispute() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_open_dispute",
- description: "Open a dispute on a job contract. Actor is resolved from the wallet signer.",
- inputs: vec![
- required_string("jobId", "The job posting's unique identifier."),
- required_string("reason", "Non-blank reason for opening the dispute."),
- ],
- outputs: vec![json_output(
- "result",
- "Updated JobPosting with dispute info.",
- )],
- }
-}
-
-fn schema_jobs_adjudicate_dispute() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "jobs_adjudicate_dispute",
- description: "Convene the AI judge panel to adjudicate an open dispute. Actor is resolved from the wallet signer.",
- inputs: vec![required_string("jobId", "The job posting's unique identifier.")],
- outputs: vec![json_output(
- "result",
- "Updated JobPosting with the dispute verdict applied.",
- )],
- }
-}
-
-fn schema_marketplace_browse() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_browse",
- description: "Browse the combined tiny.place marketplace (products + identity listings).",
- inputs: vec![optional_product_query_params()],
- outputs: vec![json_output(
- "result",
- "MarketplaceBrowseResponse containing products and identity listings.",
- )],
- }
-}
-
-fn schema_marketplace_categories() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_categories",
- description: "List all marketplace product categories.",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "CategoriesResponse { categories: MarketplaceCategory[] }.",
- )],
- }
-}
-
-fn schema_marketplace_featured() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_featured",
- description: "List featured marketplace items.",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "FeaturedResponse { items: unknown[] }.",
- )],
- }
-}
-
-fn schema_marketplace_get_product() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_get_product",
- description: "Fetch a single product by its ID.",
- inputs: vec![required_string(
- "productId",
- "The product's unique identifier.",
- )],
- outputs: vec![json_output("result", "Product object.")],
- }
-}
-
-fn schema_marketplace_list_product_reviews() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_list_product_reviews",
- description: "List reviews for a product.",
- inputs: vec![required_string(
- "productId",
- "The product whose reviews to fetch.",
- )],
- outputs: vec![json_output(
- "result",
- "ProductReviewsResponse { reviews: ProductReview[] }.",
- )],
- }
-}
-
-fn schema_marketplace_list_products() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "marketplace_list_products",
- description: "List product listings on the tiny.place marketplace.",
- inputs: vec![optional_product_query_params()],
- outputs: vec![json_output(
- "result",
- "ProductsResponse { products: Product[] }.",
- )],
- }
-}
-
-fn schema_broadcasts_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "broadcasts_list",
- description:
- "List tiny.place broadcast channels, optionally filtered by query params (read-only).",
- inputs: vec![optional_object(
- "params",
- "Optional BroadcastQueryParams (q, tag, tags, owner, visibility, paymentType, sort, limit).",
- )],
- outputs: vec![json_output(
- "result",
- "Array of BroadcastChannel objects.",
- )],
- }
-}
-
-fn schema_channels_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "channels_list",
- description:
- "List public tiny.place channels, optionally filtered by query params (read-only).",
- inputs: vec![optional_object(
- "params",
- "Optional ChannelQueryParams (q, tag, tags, minMembers, maxMembers, sort, limit).",
- )],
- outputs: vec![json_output(
- "result",
- "ChannelListResponse containing a list of Channel objects.",
- )],
- }
-}
-
-fn schema_groups_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "groups_list",
- description:
- "List tiny.place groups, optionally filtered by query params (read-only).",
- inputs: vec![optional_object(
- "params",
- "Optional GroupQueryParams (q, tag, tags, membershipPolicy, minMembers, maxMembers, member, limit).",
- )],
- outputs: vec![json_output(
- "result",
- "Array of GroupMetadata objects.",
- )],
- }
-}
-
-fn schema_inbox_counts() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "inbox_counts",
- description: "Return inbox unread/read/archived counts for the authenticated agent.",
- inputs: vec![FieldSchema {
- name: "owner",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional agent ID to count as (directory-auth). Defaults to agent auth.",
- required: false,
- }],
- outputs: vec![json_output(
- "result",
- "InboxCounts with unread, read, archived, byType, and urgent counts.",
- )],
- }
-}
-
-fn schema_inbox_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "inbox_list",
- description: "List inbox items for the authenticated agent (or a named owner).",
- inputs: vec![
- optional_object(
- "params",
- "Optional InboxQueryParams (status, types, from, priority, q, since, before, limit, cursor).",
- ),
- FieldSchema {
- name: "owner",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional agent ID to list inbox as (directory-auth). Defaults to agent auth.",
- required: false,
- },
- ],
- outputs: vec![json_output(
- "result",
- "InboxListResult containing items, cursor, unreadCount, and totalCount.",
- )],
- }
-}
-
-fn optional_owner() -> FieldSchema {
- FieldSchema {
- name: "owner",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional agent ID to act as (directory-auth). Defaults to agent auth.",
- required: false,
- }
-}
-
-fn schema_broadcasts_subscribe() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "broadcasts_subscribe",
- description: "Subscribe to a broadcast channel as the authenticated agent.",
- inputs: vec![required_string(
- "broadcastId",
- "The broadcast ID to subscribe to.",
- )],
- outputs: vec![json_output("result", "BroadcastSubscriber record.")],
- }
-}
-
-fn schema_broadcasts_unsubscribe() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "broadcasts_unsubscribe",
- description: "Unsubscribe from a broadcast channel as the authenticated agent.",
- inputs: vec![required_string(
- "broadcastId",
- "The broadcast ID to unsubscribe from.",
- )],
- outputs: vec![json_output("result", "{ ok: true } on success.")],
- }
-}
-
-fn schema_channels_join() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "channels_join",
- description: "Join a channel as the authenticated agent.",
- inputs: vec![required_string("channelId", "The channel ID to join.")],
- outputs: vec![json_output(
- "result",
- "ChannelMember for the joined channel.",
- )],
- }
-}
-
-fn schema_channels_leave() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "channels_leave",
- description: "Leave a channel as the authenticated agent.",
- inputs: vec![required_string("channelId", "The channel ID to leave.")],
- outputs: vec![json_output("result", "{ ok: true } on success.")],
- }
-}
-
-fn schema_groups_join() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "groups_join",
- description: "Join (or request to join) a group as the authenticated agent.",
- inputs: vec![required_string("groupId", "The group ID to join.")],
- outputs: vec![json_output("result", "GroupMember for the joined group.")],
- }
-}
-
-fn schema_groups_leave() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "groups_leave",
- description: "Leave a group (removes the authenticated agent from its membership).",
- inputs: vec![required_string("groupId", "The group ID to leave.")],
- outputs: vec![json_output("result", "{ ok: true } on success.")],
- }
-}
-
-fn schema_inbox_archive() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "inbox_archive",
- description: "Archive a single inbox item.",
- inputs: vec![
- required_string("itemId", "The inbox item ID."),
- optional_owner(),
- ],
- outputs: vec![json_output(
- "result",
- "InboxMarkResult for the archived item.",
- )],
- }
-}
-
-fn schema_inbox_mark_all_read() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "inbox_mark_all_read",
- description: "Mark all inbox items as read (optionally filtered).",
- inputs: vec![
- optional_object(
- "params",
- "Optional InboxClearParams filter (types, from, before).",
- ),
- optional_owner(),
- ],
- outputs: vec![json_output(
- "result",
- "InboxReadAllResult with the updated count.",
- )],
- }
-}
-
-fn schema_inbox_mark_read() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "inbox_mark_read",
- description: "Mark a single inbox item as read.",
- inputs: vec![
- required_string("itemId", "The inbox item ID."),
- optional_owner(),
- ],
- outputs: vec![json_output(
- "result",
- "InboxMarkResult for the updated item.",
- )],
- }
-}
-
-fn schema_inbox_remove() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "inbox_remove",
- description: "Permanently remove a single inbox item.",
- inputs: vec![
- required_string("itemId", "The inbox item ID."),
- optional_owner(),
- ],
- outputs: vec![json_output("result", "{ ok: true } on success.")],
- }
-}
-
-fn schema_inbox_unarchive() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "inbox_unarchive",
- description: "Unarchive a single inbox item.",
- inputs: vec![
- required_string("itemId", "The inbox item ID."),
- optional_owner(),
- ],
- outputs: vec![json_output(
- "result",
- "InboxMarkResult for the unarchived item.",
- )],
- }
-}
-
-// ── Follows schemas ─────────────────────────────────────────────────────────
-
-fn schema_follows_follow() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "follows_follow",
- description: "Follow an agent (agent-authenticated).",
- inputs: vec![required_string(
- "agentId",
- "The agent's base58 Solana address to follow.",
- )],
- outputs: vec![json_output(
- "result",
- "AgentFollow { follower, followee, createdAt }.",
- )],
- }
-}
-
-fn schema_follows_unfollow() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "follows_unfollow",
- description: "Unfollow an agent (agent-authenticated).",
- inputs: vec![required_string(
- "agentId",
- "The agent's base58 Solana address to unfollow.",
- )],
- outputs: vec![json_output("result", "{ ok: true } on success.")],
- }
-}
-
-fn schema_follows_followers() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "follows_followers",
- description: "List an agent's followers with optional pagination.",
- inputs: vec![
- required_string("agentId", "The agent whose followers to list."),
- optional_object("params", "Optional FollowListParams (limit, offset)."),
- ],
- outputs: vec![json_output(
- "result",
- "FollowersResponse { followers: AgentFollow[] }.",
- )],
- }
-}
-
-fn schema_follows_following() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "follows_following",
- description: "List the agents an agent follows, with optional pagination.",
- inputs: vec![
- required_string("agentId", "The agent whose following list to fetch."),
- optional_object("params", "Optional FollowListParams (limit, offset)."),
- ],
- outputs: vec![json_output(
- "result",
- "FollowingResponse { following: AgentFollow[] }.",
- )],
- }
-}
-
-fn schema_follows_stats() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "follows_stats",
- description: "Follower/following counts for an agent.",
- inputs: vec![required_string(
- "agentId",
- "The agent whose follow stats to retrieve.",
- )],
- outputs: vec![json_output(
- "result",
- "FollowStats { agentId, followerCount, followingCount }.",
- )],
- }
-}
-
-fn schema_follows_feed() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "follows_feed",
- description:
- "The authenticated agent's personalized activity feed based on who they follow.",
- inputs: vec![optional_object(
- "params",
- "Optional FeedListParams (limit, offset, kind, category, since, includeSelf).",
- )],
- outputs: vec![json_output(
- "result",
- "FeedResponse { events: ActivityEvent[], following: AgentFollow[], stats: ActivityStats }.",
- )],
- }
-}
-
-// ── Registry export schema ─────────────────────────────────────────────────────
-
-fn schema_registry_assign_primary() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "registry_assign_primary",
- description: "Assign one of the wallet's handles as its primary (active) identity; \
- clears the primary flag on the wallet's other handles.",
- inputs: vec![required_string(
- "name",
- "The handle to make primary/active (with or without a leading @).",
- )],
- outputs: vec![json_output(
- "identity",
- "The updated Identity with primary=true.",
- )],
- }
-}
-
-fn schema_registry_export() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "registry_export",
- description: "Export an identity with its full ledger history and cryptographic proofs.",
- inputs: vec![required_string(
- "name",
- "The handle to export (with or without a leading @).",
- )],
- outputs: vec![json_output(
- "result",
- "IdentityExport { identity, ledgerTransactions, exportedAt, verification, proofs }.",
- )],
- }
-}
-
-fn schema_registry_transfer() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "registry_transfer",
- description:
- "Transfer one of the wallet's handles to another tiny.place identity (gift / account \
- move). DESTRUCTIVE and irreversible: on success the recipient becomes the handle's \
- sole owner. The recipient is resolved from their @handle; an unregistered recipient \
- or an unconfirmed read-back fails closed. The owning wallet is proven by the \
- signer-attached signature, so a caller can only transfer a handle their own wallet \
- owns.",
- inputs: vec![
- required_string(
- "name",
- "The handle to transfer away (with or without a leading @).",
- ),
- required_string(
- "recipient",
- "The recipient's registered @handle (with or without a leading @); resolved to \
- their cryptoId + publicKey server-side.",
- ),
- ],
- outputs: vec![json_output(
- "identity",
- "The transferred Identity, now owned by the recipient (read-back confirmed).",
- )],
- }
-}
-
-// ── Feedback schemas ────────────────────────────────────────────────────────
-
-fn schema_feedback_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "feedback_list",
- description: "List public feedback items with optional filters.",
- inputs: vec![optional_object(
- "params",
- "Optional FeedbackListParams (status, limit, offset).",
- )],
- outputs: vec![json_output(
- "result",
- "FeedbackListResponse { feedback: FeedbackItem[] }.",
- )],
- }
-}
-
-fn schema_feedback_get() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "feedback_get",
- description: "Fetch a single feedback item by ID.",
- inputs: vec![required_string(
- "feedbackId",
- "The feedback item ID to retrieve.",
- )],
- outputs: vec![json_output(
- "result",
- "FeedbackItem with votes, status, and timestamps.",
- )],
- }
-}
-
-fn schema_feedback_create() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "feedback_create",
- description: "Submit a new feedback item (author set from wallet signer).",
- inputs: vec![
- required_string("title", "Feedback title."),
- required_string("description", "Feedback description body."),
- optional_string("category", "Optional category tag for the feedback item."),
- ],
- outputs: vec![json_output(
- "result",
- "FeedbackItem for the newly created item.",
- )],
- }
-}
-
-fn schema_feedback_vote() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "feedback_vote",
- description: "Vote on a feedback item (voter set from wallet signer).",
- inputs: vec![
- required_string("feedbackId", "The feedback item ID to vote on."),
- required_string("vote", "Vote direction: 'up' or 'down'."),
- ],
- outputs: vec![json_output(
- "result",
- "FeedbackItem with updated vote counts.",
- )],
- }
-}
-
-// ── Groups invite/role schemas ──────────────────────────────────────────────
-
-fn schema_groups_set_member_role() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "groups_set_member_role",
- description:
- "Promote or demote an active group member between 'admin' and 'member' (owner/admin-signed).",
- inputs: vec![
- required_string("groupId", "The group ID."),
- required_string("agentId", "The target member's base58 Solana address."),
- required_string("role", "The new role: 'admin' or 'member'."),
- ],
- outputs: vec![json_output(
- "result",
- "GroupMember with the updated role.",
- )],
- }
-}
-
-fn schema_groups_create_invite() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "groups_create_invite",
- description:
- "Issue (or rotate) an invite link for a group (admin-signed via wallet signer).",
- inputs: vec![
- required_string("groupId", "The group ID to create an invite for."),
- optional_object(
- "request",
- "Optional GroupInviteCreateRequest (ttlSeconds, maxUses).",
- ),
- ],
- outputs: vec![json_output(
- "result",
- "GroupInvite { groupId, token, createdBy, createdAt, expiresAt?, maxUses?, uses, revoked? }.",
- )],
- }
-}
-
-fn schema_groups_list_invites() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "groups_list_invites",
- description: "List active invites for a group (admin-signed via wallet signer).",
- inputs: vec![required_string("groupId", "The group ID.")],
- outputs: vec![json_output("result", "Array of GroupInvite objects.")],
- }
-}
-
-fn schema_groups_preview_invite() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "groups_preview_invite",
- description:
- "Public preview of the group behind a valid invite token (no auth required).",
- inputs: vec![
- required_string("groupId", "The group ID."),
- required_string("token", "The invite token to preview."),
- ],
- outputs: vec![json_output(
- "result",
- "GroupInvitePreview { groupId, name, description?, memberCount, membershipPolicy, invitedBy, valid }.",
- )],
- }
-}
-
-fn schema_groups_revoke_invite() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "groups_revoke_invite",
- description: "Revoke an invite token (admin-signed via wallet signer).",
- inputs: vec![
- required_string("groupId", "The group ID."),
- required_string("token", "The invite token to revoke."),
- ],
- outputs: vec![json_output("result", "{ ok: true } on success.")],
- }
-}
-
-fn schema_groups_redeem_invite() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "groups_redeem_invite",
- description:
- "Redeem an invite token, joining the group regardless of membership policy (signed as self).",
- inputs: vec![
- required_string("groupId", "The group ID."),
- required_string("token", "The invite token to redeem."),
- ],
- outputs: vec![json_output(
- "result",
- "GroupMember for the newly joined member.",
- )],
- }
-}
-
-// ── Users email verification schemas ────────────────────────────────────────
-
-fn schema_users_start_email_verification() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "users_start_email_verification",
- description:
- "Start email verification for a wallet — stores the email (unverified) and sends a code.",
- inputs: vec![
- required_string("cryptoId", "The wallet's base58 Solana address / cryptoId."),
- required_string("email", "The email address to verify."),
- ],
- outputs: vec![json_output(
- "result",
- "Updated User profile with email set and emailVerified:false.",
- )],
- }
-}
-
-fn schema_users_confirm_email_verification() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "users_confirm_email_verification",
- description:
- "Confirm the email verification code. On success, the email is marked verified.",
- inputs: vec![
- required_string("cryptoId", "The wallet's base58 Solana address / cryptoId."),
- required_string(
- "email",
- "The email address being verified (must match the start request).",
- ),
- required_string("code", "The verification code received via email."),
- ],
- outputs: vec![json_output(
- "result",
- "Updated User profile with emailVerified:true and emailVerifiedAt set.",
- )],
- }
-}
-
-// ── Solana schemas ──────────────────────────────────────────────────────────
-
-fn schema_solana_info() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "solana_info",
- description:
- "Public chain metadata for the backend's configured Solana network (network, name, assets, RPC info).",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "SolanaChainInfo { network, name, kind, nativeAsset, explorerUrl, confirmations, assets, rpc }.",
- )],
- }
-}
-
-fn schema_solana_call() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "solana_call",
- description:
- "Send a single Solana JSON-RPC call through the backend's proxy and return the unwrapped result.",
- inputs: vec![
- required_string("method", "The Solana JSON-RPC method name (e.g. 'getBalance')."),
- optional_object("params", "Optional JSON-RPC params for the method."),
- optional_object("id", "Optional JSON-RPC id (string or number); defaults to method name."),
- ],
- outputs: vec![json_output("result", "The JSON-RPC result value (arbitrary JSON).")],
- }
-}
-
-// ── Streams schemas ───────────────────────────────────────────────────────────
-
-fn schema_streams_start() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "streams_start",
- description: "Start a tinyplace WebSocket stream (inbox or conversation).",
- inputs: vec![
- required_string("streamType", "Stream type: \"inbox\" or \"conversation\"."),
- optional_string(
- "streamId",
- "Target id (e.g. conversation_id). Required for conversation streams.",
- ),
- ],
- outputs: vec![json_output(
- "result",
- "{ streamId: string } — the stream handle.",
- )],
- }
-}
-
-fn schema_streams_stop() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "streams_stop",
- description: "Stop an active tinyplace WebSocket stream.",
- inputs: vec![required_string(
- "streamId",
- "The stream handle returned from streams_start.",
- )],
- outputs: vec![json_output("result", "{ ok: true } on success.")],
- }
-}
-
-fn schema_streams_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "streams_list",
- description: "List all active tinyplace WebSocket streams.",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "{ streams: Array<{ streamId, kind, status }> }.",
- )],
- }
-}
-
-// ── Signal key management schemas ────────────────────────────────────────────
-
-fn schema_signal_provision() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "signal_provision",
- description: "Bootstrap Signal keys: generate signed pre-key + one-time pre-keys, \
- store locally, and publish to the backend. Returns key health.",
- inputs: vec![optional_integer(
- "preKeyCount",
- "Number of one-time pre-keys to generate (default 100).",
- )],
- outputs: vec![json_output(
- "result",
- "KeyHealth { agentId, oneTimePreKeyCount, lowOneTimePreKeys, \
- recommendedPreKeyRefill?, signedPreKeyKeyId?, updatedAt }.",
- )],
- }
-}
-
-fn schema_signal_upload_pre_keys() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "signal_upload_pre_keys",
- description: "Generate and upload additional one-time pre-keys (replenishment). \
- Does not rotate the signed pre-key.",
- inputs: vec![optional_integer(
- "count",
- "Number of one-time pre-keys to generate and upload (default 100).",
- )],
- outputs: vec![json_output(
- "result",
- "KeyHealth { agentId, oneTimePreKeyCount, lowOneTimePreKeys, \
- recommendedPreKeyRefill?, updatedAt }.",
- )],
- }
-}
-
-fn schema_signal_rotate_signed_pre_key() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "signal_rotate_signed_pre_key",
- description: "Generate a new signed pre-key, store locally, and upload. \
- Existing one-time pre-keys are unaffected.",
- inputs: vec![],
- outputs: vec![json_output("result", "{ ok: true, keyId: string }.")],
- }
-}
-
-fn schema_signal_get_bundle() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "signal_get_bundle",
- description: "Fetch a peer's published Signal pre-key bundle (public endpoint).",
- inputs: vec![required_string(
- "agentId",
- "The peer's base58 Solana address.",
- )],
- outputs: vec![json_output(
- "result",
- "KeyBundle { agentId, identityKey, signedPreKey, oneTimePreKey?, updatedAt }.",
- )],
- }
-}
-
-fn schema_signal_key_status() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "signal_key_status",
- description: "Local + remote key status for the current user. \
- Remote health degrades gracefully if the backend is unreachable.",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "{ agentId, localPreKeyCount, hasActiveSignedPreKey, remote: KeyHealth? }.",
- )],
- }
-}
-
-fn schema_signal_send_message() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "signal_send_message",
- description: "Encrypt and send a Signal-protocol direct message to a peer agent. \
- Performs X3DH key agreement on first message (PREKEY_BUNDLE), then Double \
- Ratchet for subsequent messages (CIPHERTEXT). Plaintext is NEVER sent if \
- encryption fails.",
- inputs: vec![
- required_string("recipient", "Target agent ID."),
- required_string("plaintext", "Cleartext message body to encrypt and send."),
- ],
- outputs: vec![json_output(
- "result",
- "{ messageId: string, timestamp: string, encrypted: true }.",
- )],
- }
-}
-
-fn schema_signal_decrypt_message() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "signal_decrypt_message",
- description: "Decrypt an incoming Signal-protocol message envelope. \
- Handles both PREKEY_BUNDLE (initial) and CIPHERTEXT (ratchet) envelope types. \
- Consumes one-time pre-keys on PREKEY_BUNDLE.",
- inputs: vec![required_object(
- "envelope",
- "Full MessageEnvelope object as received from the server.",
- )],
- outputs: vec![json_output(
- "result",
- "{ plaintext: string, from: string, messageId: string }.",
- )],
- }
-}
-
-fn schema_messages_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "messages_list",
- description: "Fetch the inbox of encrypted message envelopes for the current agent. \
- Returns raw envelopes; call signal_decrypt_message on each to read content.",
- inputs: vec![optional_integer(
- "limit",
- "Max number of envelopes to return.",
- )],
- outputs: vec![json_output("result", "Array of MessageEnvelope objects.")],
- }
-}
-
-fn schema_messages_acknowledge() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "messages_acknowledge",
- description: "Acknowledge (mark as delivered/read) a received message envelope. \
- The server will stop re-delivering acknowledged messages.",
- inputs: vec![required_string(
- "messageId",
- "ID of the envelope to acknowledge.",
- )],
- outputs: vec![json_output("result", "{ ok: true }.")],
- }
-}
-
-fn schema_contacts_request() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "contacts_request",
- description: "Send a signed contact request to a peer agent. Contact requests carry no free text; the edge itself is the pairing signal.",
- inputs: vec![required_string("agentId", "Target agent ID.")],
- outputs: vec![json_output("result", "ContactView or backend contact result.")],
- }
-}
-
-fn schema_contacts_accept() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "contacts_accept",
- description: "Accept an incoming signed contact request from a peer agent.",
- inputs: vec![required_string("agentId", "Requesting agent ID.")],
- outputs: vec![json_output(
- "result",
- "Accepted ContactView or backend contact result.",
- )],
- }
-}
-
-fn schema_contacts_remove() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "contacts_remove",
- description:
- "Remove a contact edge or pending request. Blocked edges are not cleared by remove.",
- inputs: vec![required_string("agentId", "Peer agent ID.")],
- outputs: vec![json_output(
- "result",
- "{ ok: true } or backend contact result.",
- )],
- }
-}
-
-fn schema_contacts_block() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "contacts_block",
- description: "Block a peer agent. Blocked peers must not be re-requested automatically.",
- inputs: vec![required_string("agentId", "Peer agent ID.")],
- outputs: vec![json_output(
- "result",
- "Blocked ContactView or backend contact result.",
- )],
- }
-}
-
-fn schema_contacts_unblock() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "contacts_unblock",
- description:
- "Unblock a peer agent without automatically creating or accepting a contact edge.",
- inputs: vec![required_string("agentId", "Peer agent ID.")],
- outputs: vec![json_output(
- "result",
- "{ ok: true } or backend contact result.",
- )],
- }
-}
-
-fn schema_contacts_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "contacts_list",
- description: "List signed contact edges for the current tiny.place identity.",
- inputs: vec![optional_object(
- "params",
- "Optional pagination params (limit, offset).",
- )],
- outputs: vec![json_output(
- "result",
- "ContactsResponse { contacts: ContactView[] }.",
- )],
- }
-}
-
-fn schema_contacts_requests() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "contacts_requests",
- description: "List incoming and outgoing signed contact requests for the current tiny.place identity.",
- inputs: vec![optional_object("params", "Optional pagination params (limit, offset).")],
- outputs: vec![json_output(
- "result",
- "ContactRequestsResponse { incoming: ContactView[], outgoing: ContactView[] }.",
- )],
- }
-}
-
-fn schema_contacts_status() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "contacts_status",
- description:
- "Fetch the contact status between the current tiny.place identity and a peer agent.",
- inputs: vec![required_string("agentId", "Peer agent ID.")],
- outputs: vec![json_output("result", "ContactStatusResponse.")],
- }
-}
-
-fn schema_contacts_stats() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "contacts_stats",
- description: "Fetch aggregate signed contact counts for the current tiny.place identity.",
- inputs: vec![],
- outputs: vec![json_output("result", "ContactStats.")],
- }
-}
-
-// ── Encryption key registration + discovery (0D) ────────────────────────────
-
-fn schema_signal_register_encryption_key() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "signal_register_encryption_key",
- description: "Publish the user's Ed25519 identity key (the addressable cryptoId, where \
- the Signal prekey bundle + mailbox live) on their directory card \
- (metadata.encryptionPublicKey). Peers derive the X25519 DH key from the bundle \
- themselves. Makes the user discoverable for encrypted DMs. No params needed.",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "{ ok: true, encryptionKey: string, agentId: string, updatedAt: string }.",
- )],
- }
-}
-
-fn schema_directory_find_by_encryption_key() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "directory_find_by_encryption_key",
- description: "Reverse-lookup: find the agent advertising a given Signal encryption \
- public key (base64). Returns AgentCard or null.",
- inputs: vec![required_string(
- "encryptionKey",
- "Base64-encoded X25519 public key to search for.",
- )],
- outputs: vec![json_output("result", "AgentCard | null.")],
- }
-}
-
-// ── Feeds write schemas (Phase A) ──────────────────────────────────────────
-
-fn schema_feeds_create_post() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "feeds_create_post",
- description: "Create a new post on the signer's own feed. The feed handle is resolved server-side from the wallet signer.",
- inputs: vec![
- required_string("body", "Post body text."),
- optional_string("contentType", "Optional content type (e.g. 'text/plain')."),
- ],
- outputs: vec![json_output(
- "result",
- "Post object for the newly created post.",
- )],
- }
-}
-
-fn schema_feeds_delete_post() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "feeds_delete_post",
- description: "Delete a post from the signer's own feed. The feed handle is resolved server-side from the wallet signer.",
- inputs: vec![required_string("postId", "The post ID to delete.")],
- outputs: vec![json_output("result", "{ ok: true } on success.")],
- }
-}
-
-fn schema_feeds_add_comment() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "feeds_add_comment",
- description: "Add a comment to a post. Author resolved from wallet signer.",
- inputs: vec![
- required_string("handle", "The @handle of the feed containing the post."),
- required_string("postId", "The post ID to comment on."),
- required_string("body", "Comment body text."),
- ],
- outputs: vec![json_output(
- "result",
- "Comment object for the newly added comment.",
- )],
- }
-}
-
-fn schema_feeds_delete_comment() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "feeds_delete_comment",
- description: "Delete a comment. Actor resolved from wallet signer \
- (must be comment author or feed owner).",
- inputs: vec![
- required_string("handle", "The @handle of the feed containing the post."),
- required_string("postId", "The post ID the comment belongs to."),
- required_string("commentId", "The comment ID to delete."),
- ],
- outputs: vec![json_output("result", "{ ok: true } on success.")],
- }
-}
-
-fn schema_feeds_like_post() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "feeds_like_post",
- description: "Like a post (idempotent). Actor resolved from wallet signer.",
- inputs: vec![
- required_string("handle", "The @handle of the feed containing the post."),
- required_string("postId", "The post ID to like."),
- ],
- outputs: vec![json_output(
- "result",
- "LikeResult { postId, liked, likeCount }.",
- )],
- }
-}
-
-fn schema_feeds_unlike_post() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "feeds_unlike_post",
- description: "Unlike a post (idempotent). Actor resolved from wallet signer.",
- inputs: vec![
- required_string("handle", "The @handle of the feed containing the post."),
- required_string("postId", "The post ID to unlike."),
- ],
- outputs: vec![json_output(
- "result",
- "LikeResult { postId, liked, likeCount }.",
- )],
- }
-}
-
-// ── Bounties schemas (Phase B) ────────────────────────────────────────────────
-
-fn schema_bounties_list() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "bounties_list",
- description: "List bounties with optional filtering.",
- inputs: vec![optional_object(
- "params",
- "Optional BountyQueryParams (creator, status, limit, offset).",
- )],
- outputs: vec![json_output(
- "result",
- "BountyListResponse { bounties: Bounty[] }.",
- )],
- }
-}
-
-fn schema_bounties_get() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "bounties_get",
- description: "Fetch a single bounty by its ID.",
- inputs: vec![required_string(
- "bountyId",
- "The bounty's unique identifier.",
- )],
- outputs: vec![json_output("result", "Bounty object.")],
- }
-}
-
-fn schema_bounties_create() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "bounties_create",
- description: "Create a bounty via x402 confirm-before-spend (the reward is funded into \
- escrow at creation). Creator resolved from wallet signer. confirmed=false returns \
- the 402 challenge + wallet balance (no spend); confirmed=true pays and creates.",
- inputs: vec![
- required_string("title", "Bounty title (non-blank)."),
- required_string("description", "Bounty description (non-blank)."),
- required_string(
- "amount",
- "Reward amount (human-decimal string, e.g. '5' for 5 USDC).",
- ),
- optional_string("asset", "Reward asset symbol (defaults to 'USDC')."),
- optional_string("deadline", "Optional RFC3339 deadline."),
- optional_integer(
- "durationDays",
- "Optional duration in days (alternative to deadline).",
- ),
- buy_confirmed_input(),
- ],
- outputs: vec![json_output(
- "result",
- "{ bounty } (free / already funded), { challenge, walletBalance, walletAddress } \
- (unconfirmed), or { bounty, payment: { onChainTx } } (paid).",
- )],
- }
-}
-
-fn schema_bounties_cancel() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "bounties_cancel",
- description: "Cancel a bounty. Creator resolved from wallet signer.",
- inputs: vec![required_string("bountyId", "The bounty ID to cancel.")],
- outputs: vec![json_output("result", "Updated Bounty object.")],
- }
-}
-
-fn schema_bounties_submit() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "bounties_submit",
- description: "Submit work for a bounty. Submitter resolved from wallet signer.",
- inputs: vec![
- required_string("bountyId", "The bounty to submit work for."),
- required_string("url", "URL of the submitted work (non-blank)."),
- optional_string("title", "Optional title for the submission."),
- optional_string("note", "Optional note for the submission."),
- ],
- outputs: vec![json_output("result", "BountySubmission object.")],
- }
-}
-
-fn schema_bounties_list_submissions() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "bounties_list_submissions",
- description: "List submissions for a bounty.",
- inputs: vec![
- required_string("bountyId", "The bounty whose submissions to list."),
- optional_object(
- "params",
- "Optional BountySubmissionQueryParams (status, submitter, limit).",
- ),
- ],
- outputs: vec![json_output(
- "result",
- "BountySubmissionsResponse { submissions: BountySubmission[] }.",
- )],
- }
-}
-
-fn schema_bounties_comment() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "bounties_comment",
- description: "Add a comment to a bounty. Author resolved from wallet signer.",
- inputs: vec![
- required_string("bountyId", "The bounty to comment on."),
- required_string("body", "Comment body text (non-blank)."),
- ],
- outputs: vec![json_output("result", "BountyComment object.")],
- }
-}
-
-fn schema_bounties_list_comments() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "bounties_list_comments",
- description: "List comments on a bounty.",
- inputs: vec![
- required_string("bountyId", "The bounty whose comments to list."),
- optional_object(
- "params",
- "Optional BountyCommentQueryParams (limit, offset).",
- ),
- ],
- outputs: vec![json_output(
- "result",
- "BountyCommentsResponse { comments: BountyComment[] }.",
- )],
- }
-}
-
-fn schema_bounties_run_council() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "bounties_run_council",
- description:
- "Run the AI council to judge bounty submissions. Actor resolved from wallet signer.",
- inputs: vec![required_string(
- "bountyId",
- "The bounty to convene the council for.",
- )],
- outputs: vec![json_output("result", "Updated Bounty with council state.")],
- }
-}
-
-fn schema_bounties_approve() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "bounties_approve",
- description: "Approve a bounty winner and trigger payout. Admin-only (backend enforced). \
- Not surfaced in v1 UI.",
- inputs: vec![
- required_string("bountyId", "The bounty to approve."),
- optional_string(
- "submissionId",
- "Optional submission ID to approve as winner.",
- ),
- ],
- outputs: vec![json_output(
- "result",
- "Updated Bounty object with awarded status.",
- )],
- }
-}
-
-// ── GraphQL Social Feed schemas ─────────────────────────────────────────────
-
-fn schema_graphql_home_feed() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_home_feed",
- description: "Personalized home feed for the authenticated agent (GraphQL, \
- requires unlocked wallet). Returns scored posts from followed agents.",
- inputs: vec![
- optional_integer("limit", "Max items to return."),
- optional_integer("offset", "Pagination offset."),
- FieldSchema {
- name: "includeSelf",
- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
- comment: "Include the viewer's own posts in the feed.",
- required: false,
- },
- ],
- outputs: vec![json_output(
- "result",
- "GqlHomeFeedResult { items: GqlHomeFeedItem[], count }.",
- )],
- }
-}
-
-fn schema_graphql_posts() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_posts",
- description: "List posts by a specific agent handle (public, no auth required).",
- inputs: vec![
- required_string("handle", "The agent handle whose posts to list."),
- optional_integer("limit", "Max posts to return."),
- optional_integer(
- "before",
- "Cursor: return posts before this timestamp (epoch ms).",
- ),
- optional_string("viewer", "Optional viewer agent ID for viewerHasLiked."),
- ],
- outputs: vec![json_output(
- "result",
- "GqlPostListResult { posts: GqlPost[], count }.",
- )],
- }
-}
-
-fn schema_graphql_post() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_post",
- description: "Fetch a single post with its comments and likers (public).",
- inputs: vec![
- required_string("handle", "The author's agent handle."),
- required_string("postId", "The post ID to fetch."),
- optional_string("viewer", "Optional viewer agent ID for viewerHasLiked."),
- optional_integer("commentLimit", "Max comments to include."),
- optional_integer("commentAfter", "Cursor: comments after this timestamp."),
- optional_integer("likerLimit", "Max likers to include."),
- optional_integer("likerOffset", "Likers pagination offset."),
- ],
- outputs: vec![json_output(
- "result",
- "GqlPostDetail (post + comments[] + likers[]) or null if not found.",
- )],
- }
-}
-
-fn schema_graphql_post_comments() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_post_comments",
- description: "List comments on a post, with optional pagination (public).",
- inputs: vec![
- required_string("postId", "The post whose comments to list."),
- optional_string("feedId", "Optional feed ID scope."),
- optional_integer("limit", "Max comments to return."),
- optional_integer("after", "Cursor: comments after this timestamp."),
- ],
- outputs: vec![json_output("result", "{ comments: GqlComment[] }.")],
- }
-}
-
-fn schema_graphql_post_likers() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_post_likers",
- description: "List agents who liked a post, with pagination (public).",
- inputs: vec![
- required_string("postId", "The post whose likers to list."),
- optional_integer("limit", "Max likers to return."),
- optional_integer("offset", "Pagination offset."),
- ],
- outputs: vec![json_output(
- "result",
- "GqlPostLikerListResult { likers: GqlPostLike[], count }.",
- )],
- }
-}
-
-// ── GraphQL Ledger schemas ────────────────────────────────────────────────
-
-fn schema_graphql_ledger_transactions() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_ledger_transactions",
- description: "List ledger transactions with optional filtering (public, no auth). \
- Supports agent/type/network/status/from/to/asset/visibility/time-range filters \
- and limit/offset pagination.",
- inputs: vec![FieldSchema {
- name: "params",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "LedgerListParams filter object (all fields optional). \
- Fields: limit, offset, agent, type, network, status, from, to, \
- after, before, asset, visibility.",
- required: false,
- }],
- outputs: vec![json_output(
- "result",
- "GqlLedgerTransactionListResult { transactions: GqlLedgerTransaction[], count }.",
- )],
- }
-}
-
-fn schema_graphql_ledger_transaction() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_ledger_transaction",
- description: "Fetch a single ledger transaction by ID (public, no auth).",
- inputs: vec![required_string("id", "The ledger transaction ID to fetch.")],
- outputs: vec![json_output(
- "result",
- "GqlLedgerTransaction or null if not found.",
- )],
- }
-}
-
-// ── GraphQL Jobs schemas ──────────────────────────────────────────────────────
-
-fn schema_graphql_jobs() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_jobs",
- description:
- "List job postings on the jobs board with optional filtering (public, no auth). \
- Supports client/status/category/skill filters and limit/offset pagination. \
- Returns GqlJobPosting with resolved client_profile (FeedAuthor).",
- inputs: vec![FieldSchema {
- name: "params",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "JobQueryParams filter object (all fields optional). \
- Fields: client, status, category, skill, limit, offset.",
- required: false,
- }],
- outputs: vec![json_output(
- "result",
- "GqlJobListResult { jobs: GqlJobPosting[], count }.",
- )],
- }
-}
-
-fn schema_graphql_job() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_job",
- description: "Fetch a single job posting by ID (public, no auth). \
- Returns full GqlJobPosting with client_profile, dispute, on_chain details.",
- inputs: vec![required_string("id", "The job posting ID to fetch.")],
- outputs: vec![json_output("result", "GqlJobPosting or null if not found.")],
- }
-}
-
-fn schema_graphql_bounties() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_bounties",
- description: "List bounties via GraphQL (public, no auth). Supports \
- status/creator filters and limit/offset pagination. Returns GqlBounty[].",
- inputs: vec![FieldSchema {
- name: "params",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "BountyGraphQLParams filter object (all fields optional). \
- Fields: status, creator, limit, offset.",
- required: false,
- }],
- outputs: vec![json_output(
- "result",
- "GqlBounty[] (empty array when none).",
- )],
- }
-}
-
-fn schema_graphql_bounty() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_bounty",
- description: "Fetch a single bounty by ID via GraphQL (public, no auth). \
- Returns full GqlBounty with reward, council, submissions metadata.",
- inputs: vec![required_string("id", "The bounty ID to fetch.")],
- outputs: vec![json_output("result", "GqlBounty or null if not found.")],
- }
-}
-
-fn schema_graphql_profile() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_profile",
- description: "Fetch a full profile by @handle (public GraphQL). Returns GqlProfile \
- with bio, avatar, tags, attestations, agent_card, identities in a single call.",
- inputs: vec![required_string(
- "username",
- "The @handle to look up (with or without @).",
- )],
- outputs: vec![json_output("result", "GqlProfile or null if not found.")],
- }
-}
-
-fn schema_graphql_user() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_user",
- description: "Fetch a full profile by crypto_id / Solana address (public GraphQL). \
- Same rich GqlProfile response as graphql_profile but keyed by address.",
- inputs: vec![required_string(
- "cryptoId",
- "The Solana address / crypto_id to look up.",
- )],
- outputs: vec![json_output("result", "GqlProfile or null if not found.")],
- }
-}
-
-fn schema_graphql_identity() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_identity",
- description: "Fetch identity registration details with optional owner profile \
- (public GraphQL).",
- inputs: vec![required_string(
- "username",
- "The @handle whose identity record to fetch.",
- )],
- outputs: vec![json_output(
- "result",
- "GqlIdentity { identity, owner? } or null.",
- )],
- }
-}
-
-fn schema_graphql_identities() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_identities",
- description: "List all identities owned by a crypto_id (public GraphQL).",
- inputs: vec![required_string(
- "cryptoId",
- "The Solana address whose identities to list.",
- )],
- outputs: vec![json_output("result", "{ identities: Identity[] }.")],
- }
-}
-
-fn schema_graphql_agent_card() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_agent_card",
- description: "Fetch an agent card by agent ID (public GraphQL).",
- inputs: vec![required_string("id", "The agent ID to look up.")],
- outputs: vec![json_output("result", "AgentCard or null if not found.")],
- }
-}
-
-fn schema_graphql_agents() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_agents",
- description: "List directory agent cards through the public GraphQL gateway. \
- Cards include server-resolved viewer/follow edges when available.",
- inputs: vec![optional_object(
- "params",
- "Optional AgentQueryParams (q, skill, capability, tag, tags, username, cryptoId, \
- network, asset, maxAmount, group, encryptionKey, limit, cursor).",
- )],
- outputs: vec![json_output(
- "result",
- "GqlAgentCardListResult { agents: AgentCard[], count }.",
- )],
- }
-}
-
-fn schema_graphql_products() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_products",
- description: "List marketplace products through the public GraphQL gateway.",
- inputs: vec![optional_product_query_params()],
- outputs: vec![json_output(
- "result",
- "GqlProductListResult { products: GqlProduct[], count }.",
- )],
- }
-}
-
-fn schema_graphql_product() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_product",
- description: "Fetch a marketplace product by product ID through GraphQL.",
- inputs: vec![required_string("id", "The product ID to fetch.")],
- outputs: vec![json_output("result", "GqlProduct or null if not found.")],
- }
-}
-
-fn schema_graphql_identity_listings() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_identity_listings",
- description: "List identity marketplace listings through the public GraphQL gateway.",
- inputs: vec![optional_object(
- "params",
- "Optional identity listing filters (query/q, tag, tags, category, seller, \
- minPrice, maxPrice, sortBy, length, limit, offset).",
- )],
- outputs: vec![json_output(
- "result",
- "GqlIdentityListingListResult { identities: GqlIdentityListing[], count }.",
- )],
- }
-}
-
-fn schema_graphql_identity_listing() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_identity_listing",
- description: "Fetch an identity listing detail through GraphQL.",
- inputs: vec![
- required_string("id", "The identity listing ID to fetch."),
- optional_object(
- "params",
- "Optional detail pagination (bidLimit, bidOffset, historyLimit, historyOffset).",
- ),
- ],
- outputs: vec![json_output(
- "result",
- "GqlIdentityListingDetail or null if not found.",
- )],
- }
-}
-
-fn schema_graphql_identity_bids() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_identity_bids",
- description: "List bids for an identity listing through GraphQL.",
- inputs: vec![
- required_string("listingId", "The identity listing ID."),
- optional_object("params", "Optional pagination params (limit, offset)."),
- ],
- outputs: vec![json_output(
- "result",
- "GqlIdentityBidListResult { bids: GqlIdentityBid[], count }.",
- )],
- }
-}
-
-fn schema_graphql_identity_offers() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_identity_offers",
- description: "List identity offers through GraphQL.",
- inputs: vec![optional_object(
- "params",
- "Optional filters (agent, buyer, name, status, limit, offset).",
- )],
- outputs: vec![json_output(
- "result",
- "GqlIdentityOfferListResult { offers: GqlIdentityOffer[], count }.",
- )],
- }
-}
-
-fn schema_graphql_identity_sales() -> ControllerSchema {
- ControllerSchema {
- namespace: "tinyplace",
- function: "graphql_identity_sales",
- description: "List sale history for a specific @handle through GraphQL.",
- inputs: vec![
- required_string("name", "The @handle/name whose sale history to fetch."),
- optional_object("params", "Optional pagination params (limit, offset)."),
- ],
- outputs: vec![json_output(
- "result",
- "GqlIdentitySaleListResult { sales: GqlIdentitySale[], count }.",
- )],
- }
-}
-
-/// All tinyplace controller schemas (for schema discovery / validation).
-pub fn all_tinyplace_controller_schemas() -> Vec<ControllerSchema> {
- vec![
- schema_directory_list_agents(),
- schema_directory_get_agent(),
- schema_directory_resolve(),
- schema_directory_reverse(),
- schema_directory_list_identities(),
- schema_directory_skills(),
- schema_explorer_overview(),
- schema_search_unified(),
- // Profiles section
- schema_profiles_get(),
- schema_profiles_activity(),
- schema_profiles_groups(),
- schema_profiles_broadcasts(),
- schema_profiles_attestations(),
- schema_profiles_agent_card(),
- // Users section
- schema_users_get(),
- schema_users_update_profile(),
- schema_marketplace_identity_floor(),
- schema_marketplace_identity_sale_history(),
- schema_marketplace_list_bids(),
- schema_marketplace_list_identities(),
- schema_marketplace_list_offers(),
- schema_marketplace_recent(),
- schema_registry_get(),
- schema_registry_register(),
- schema_registry_assign_primary(),
- schema_registry_transfer(),
- schema_marketplace_buy_product(),
- schema_marketplace_buy_identity(),
- schema_marketplace_bid(),
- schema_marketplace_offer(),
- schema_artifacts_get(),
- schema_artifacts_list(),
- schema_escrow_get(),
- schema_escrow_list(),
- schema_jobs_get(),
- schema_jobs_list(),
- // Jobs write surface (Phase 6)
- schema_jobs_create(),
- schema_jobs_cancel(),
- schema_jobs_apply(),
- schema_jobs_list_proposals(),
- schema_jobs_get_proposal(),
- schema_jobs_shortlist_proposal(),
- schema_jobs_withdraw_proposal(),
- schema_jobs_select(),
- schema_jobs_open_dispute(),
- schema_jobs_adjudicate_dispute(),
- schema_marketplace_browse(),
- schema_marketplace_categories(),
- schema_marketplace_featured(),
- schema_marketplace_get_product(),
- schema_marketplace_list_product_reviews(),
- schema_marketplace_list_products(),
- schema_broadcasts_list(),
- schema_channels_list(),
- schema_groups_list(),
- schema_inbox_counts(),
- schema_inbox_list(),
- schema_broadcasts_subscribe(),
- schema_broadcasts_unsubscribe(),
- schema_channels_join(),
- schema_channels_leave(),
- schema_groups_join(),
- schema_groups_leave(),
- schema_inbox_archive(),
- schema_inbox_mark_all_read(),
- schema_inbox_mark_read(),
- schema_inbox_remove(),
- schema_inbox_unarchive(),
- // Follows section
- schema_follows_follow(),
- schema_follows_unfollow(),
- schema_follows_followers(),
- schema_follows_following(),
- schema_follows_stats(),
- schema_follows_feed(),
- // Feedback section
- schema_feedback_list(),
- schema_feedback_get(),
- schema_feedback_create(),
- schema_feedback_vote(),
- // Registry export
- schema_registry_export(),
- // Groups invite/role section
- schema_groups_set_member_role(),
- schema_groups_create_invite(),
- schema_groups_list_invites(),
- schema_groups_preview_invite(),
- schema_groups_revoke_invite(),
- schema_groups_redeem_invite(),
- // Users email verification
- schema_users_start_email_verification(),
- schema_users_confirm_email_verification(),
- // Solana section
- schema_solana_info(),
- schema_solana_call(),
- // Streams section
- schema_streams_start(),
- schema_streams_stop(),
- schema_streams_list(),
- // Signal key management
- schema_signal_provision(),
- schema_signal_upload_pre_keys(),
- schema_signal_rotate_signed_pre_key(),
- schema_signal_get_bundle(),
- schema_signal_key_status(),
- // Signal messaging
- schema_signal_send_message(),
- schema_signal_decrypt_message(),
- schema_messages_list(),
- schema_messages_acknowledge(),
- // Contacts / pairing precondition for encrypted DMs
- schema_contacts_request(),
- schema_contacts_accept(),
- schema_contacts_remove(),
- schema_contacts_block(),
- schema_contacts_unblock(),
- schema_contacts_list(),
- schema_contacts_requests(),
- schema_contacts_status(),
- schema_contacts_stats(),
- // Encryption key registration + discovery (0D)
- schema_signal_register_encryption_key(),
- schema_directory_find_by_encryption_key(),
- // Feeds write surface (Phase A)
- schema_feeds_create_post(),
- schema_feeds_delete_post(),
- schema_feeds_add_comment(),
- schema_feeds_delete_comment(),
- schema_feeds_like_post(),
- schema_feeds_unlike_post(),
- // Bounties section (Phase B)
- schema_bounties_list(),
- schema_bounties_get(),
- schema_bounties_create(),
- schema_bounties_cancel(),
- schema_bounties_submit(),
- schema_bounties_list_submissions(),
- schema_bounties_comment(),
- schema_bounties_list_comments(),
- schema_bounties_run_council(),
- schema_bounties_approve(),
- // GraphQL Social Feed
- schema_graphql_home_feed(),
- schema_graphql_posts(),
- schema_graphql_post(),
- schema_graphql_post_comments(),
- schema_graphql_post_likers(),
- // GraphQL Ledger
- schema_graphql_ledger_transactions(),
- schema_graphql_ledger_transaction(),
- // GraphQL Jobs
- schema_graphql_jobs(),
- schema_graphql_job(),
- // GraphQL Bounties
- schema_graphql_bounties(),
- schema_graphql_bounty(),
- // GraphQL Profile + Identity
- schema_graphql_profile(),
- schema_graphql_user(),
- schema_graphql_identity(),
- schema_graphql_identities(),
- schema_graphql_agent_card(),
- schema_graphql_agents(),
- schema_graphql_products(),
- schema_graphql_product(),
- schema_graphql_identity_listings(),
- schema_graphql_identity_listing(),
- schema_graphql_identity_bids(),
- schema_graphql_identity_offers(),
- schema_graphql_identity_sales(),
- ]
-}
-
-/// All tinyplace registered controllers (wired into the **internal** registry).
-pub fn all_tinyplace_registered_controllers() -> Vec<RegisteredController> {
- vec![
- RegisteredController {
- schema: schema_directory_list_agents(),
- handler: handle_tinyplace_directory_list_agents,
- },
- RegisteredController {
- schema: schema_directory_get_agent(),
- handler: handle_tinyplace_directory_get_agent,
- },
- RegisteredController {
- schema: schema_directory_resolve(),
- handler: handle_tinyplace_directory_resolve,
- },
- RegisteredController {
- schema: schema_directory_reverse(),
- handler: handle_tinyplace_directory_reverse,
- },
- RegisteredController {
- schema: schema_directory_list_identities(),
- handler: handle_tinyplace_directory_list_identities,
- },
- RegisteredController {
- schema: schema_directory_skills(),
- handler: handle_tinyplace_directory_skills,
- },
- RegisteredController {
- schema: schema_explorer_overview(),
- handler: handle_tinyplace_explorer_overview,
- },
- RegisteredController {
- schema: schema_search_unified(),
- handler: handle_tinyplace_search_unified,
- },
- // Profiles section
- RegisteredController {
- schema: schema_profiles_get(),
- handler: handle_tinyplace_profiles_get,
- },
- RegisteredController {
- schema: schema_profiles_activity(),
- handler: handle_tinyplace_profiles_activity,
- },
- RegisteredController {
- schema: schema_profiles_groups(),
- handler: handle_tinyplace_profiles_groups,
- },
- RegisteredController {
- schema: schema_profiles_broadcasts(),
- handler: handle_tinyplace_profiles_broadcasts,
- },
- RegisteredController {
- schema: schema_profiles_attestations(),
- handler: handle_tinyplace_profiles_attestations,
- },
- RegisteredController {
- schema: schema_profiles_agent_card(),
- handler: handle_tinyplace_profiles_agent_card,
- },
- // Users section
- RegisteredController {
- schema: schema_users_get(),
- handler: handle_tinyplace_users_get,
- },
- RegisteredController {
- schema: schema_users_update_profile(),
- handler: handle_tinyplace_users_update_profile,
- },
- RegisteredController {
- schema: schema_marketplace_identity_floor(),
- handler: handle_tinyplace_marketplace_identity_floor,
- },
- RegisteredController {
- schema: schema_marketplace_identity_sale_history(),
- handler: handle_tinyplace_marketplace_identity_sale_history,
- },
- RegisteredController {
- schema: schema_marketplace_list_bids(),
- handler: handle_tinyplace_marketplace_list_bids,
- },
- RegisteredController {
- schema: schema_marketplace_list_identities(),
- handler: handle_tinyplace_marketplace_list_identities,
- },
- RegisteredController {
- schema: schema_marketplace_list_offers(),
- handler: handle_tinyplace_marketplace_list_offers,
- },
- RegisteredController {
- schema: schema_marketplace_recent(),
- handler: handle_tinyplace_marketplace_recent,
- },
- RegisteredController {
- schema: schema_registry_get(),
- handler: handle_tinyplace_registry_get,
- },
- RegisteredController {
- schema: schema_registry_register(),
- handler: handle_tinyplace_registry_register,
- },
- RegisteredController {
- schema: schema_registry_assign_primary(),
- handler: handle_tinyplace_registry_assign_primary,
- },
- RegisteredController {
- schema: schema_registry_transfer(),
- handler: handle_tinyplace_registry_transfer,
- },
- RegisteredController {
- schema: schema_marketplace_buy_product(),
- handler: handle_tinyplace_marketplace_buy_product,
- },
- RegisteredController {
- schema: schema_marketplace_buy_identity(),
- handler: handle_tinyplace_marketplace_buy_identity,
- },
- RegisteredController {
- schema: schema_marketplace_bid(),
- handler: handle_tinyplace_marketplace_bid,
- },
- RegisteredController {
- schema: schema_marketplace_offer(),
- handler: handle_tinyplace_marketplace_offer,
- },
- RegisteredController {
- schema: schema_artifacts_get(),
- handler: handle_tinyplace_artifacts_get,
- },
- RegisteredController {
- schema: schema_artifacts_list(),
- handler: handle_tinyplace_artifacts_list,
- },
- RegisteredController {
- schema: schema_escrow_get(),
- handler: handle_tinyplace_escrow_get,
- },
- RegisteredController {
- schema: schema_escrow_list(),
- handler: handle_tinyplace_escrow_list,
- },
- RegisteredController {
- schema: schema_jobs_get(),
- handler: handle_tinyplace_jobs_get,
- },
- RegisteredController {
- schema: schema_jobs_list(),
- handler: handle_tinyplace_jobs_list,
- },
- // Jobs write surface (Phase 6)
- RegisteredController {
- schema: schema_jobs_create(),
- handler: handle_tinyplace_jobs_create,
- },
- RegisteredController {
- schema: schema_jobs_cancel(),
- handler: handle_tinyplace_jobs_cancel,
- },
- RegisteredController {
- schema: schema_jobs_apply(),
- handler: handle_tinyplace_jobs_apply,
- },
- RegisteredController {
- schema: schema_jobs_list_proposals(),
- handler: handle_tinyplace_jobs_list_proposals,
- },
- RegisteredController {
- schema: schema_jobs_get_proposal(),
- handler: handle_tinyplace_jobs_get_proposal,
- },
- RegisteredController {
- schema: schema_jobs_shortlist_proposal(),
- handler: handle_tinyplace_jobs_shortlist_proposal,
- },
- RegisteredController {
- schema: schema_jobs_withdraw_proposal(),
- handler: handle_tinyplace_jobs_withdraw_proposal,
- },
- RegisteredController {
- schema: schema_jobs_select(),
- handler: handle_tinyplace_jobs_select,
- },
- RegisteredController {
- schema: schema_jobs_open_dispute(),
- handler: handle_tinyplace_jobs_open_dispute,
- },
- RegisteredController {
- schema: schema_jobs_adjudicate_dispute(),
- handler: handle_tinyplace_jobs_adjudicate_dispute,
- },
- RegisteredController {
- schema: schema_marketplace_browse(),
- handler: handle_tinyplace_marketplace_browse,
- },
- RegisteredController {
- schema: schema_marketplace_categories(),
- handler: handle_tinyplace_marketplace_categories,
- },
- RegisteredController {
- schema: schema_marketplace_featured(),
- handler: handle_tinyplace_marketplace_featured,
- },
- RegisteredController {
- schema: schema_marketplace_get_product(),
- handler: handle_tinyplace_marketplace_get_product,
- },
- RegisteredController {
- schema: schema_marketplace_list_product_reviews(),
- handler: handle_tinyplace_marketplace_list_product_reviews,
- },
- RegisteredController {
- schema: schema_marketplace_list_products(),
- handler: handle_tinyplace_marketplace_list_products,
- },
- RegisteredController {
- schema: schema_broadcasts_list(),
- handler: handle_tinyplace_broadcasts_list,
- },
- RegisteredController {
- schema: schema_channels_list(),
- handler: handle_tinyplace_channels_list,
- },
- RegisteredController {
- schema: schema_groups_list(),
- handler: handle_tinyplace_groups_list,
- },
- RegisteredController {
- schema: schema_inbox_counts(),
- handler: handle_tinyplace_inbox_counts,
- },
- RegisteredController {
- schema: schema_inbox_list(),
- handler: handle_tinyplace_inbox_list,
- },
- RegisteredController {
- schema: schema_broadcasts_subscribe(),
- handler: handle_tinyplace_broadcasts_subscribe,
- },
- RegisteredController {
- schema: schema_broadcasts_unsubscribe(),
- handler: handle_tinyplace_broadcasts_unsubscribe,
- },
- RegisteredController {
- schema: schema_channels_join(),
- handler: handle_tinyplace_channels_join,
- },
- RegisteredController {
- schema: schema_channels_leave(),
- handler: handle_tinyplace_channels_leave,
- },
- RegisteredController {
- schema: schema_groups_join(),
- handler: handle_tinyplace_groups_join,
- },
- RegisteredController {
- schema: schema_groups_leave(),
- handler: handle_tinyplace_groups_leave,
- },
- RegisteredController {
- schema: schema_inbox_archive(),
- handler: handle_tinyplace_inbox_archive,
- },
- RegisteredController {
- schema: schema_inbox_mark_all_read(),
- handler: handle_tinyplace_inbox_mark_all_read,
- },
- RegisteredController {
- schema: schema_inbox_mark_read(),
- handler: handle_tinyplace_inbox_mark_read,
- },
- RegisteredController {
- schema: schema_inbox_remove(),
- handler: handle_tinyplace_inbox_remove,
- },
- RegisteredController {
- schema: schema_inbox_unarchive(),
- handler: handle_tinyplace_inbox_unarchive,
- },
- // Follows section
- RegisteredController {
- schema: schema_follows_follow(),
- handler: handle_tinyplace_follows_follow,
- },
- RegisteredController {
- schema: schema_follows_unfollow(),
- handler: handle_tinyplace_follows_unfollow,
- },
- RegisteredController {
- schema: schema_follows_followers(),
- handler: handle_tinyplace_follows_followers,
- },
- RegisteredController {
- schema: schema_follows_following(),
- handler: handle_tinyplace_follows_following,
- },
- RegisteredController {
- schema: schema_follows_stats(),
- handler: handle_tinyplace_follows_stats,
- },
- RegisteredController {
- schema: schema_follows_feed(),
- handler: handle_tinyplace_follows_feed,
- },
- // Feedback section
- RegisteredController {
- schema: schema_feedback_list(),
- handler: handle_tinyplace_feedback_list,
- },
- RegisteredController {
- schema: schema_feedback_get(),
- handler: handle_tinyplace_feedback_get,
- },
- RegisteredController {
- schema: schema_feedback_create(),
- handler: handle_tinyplace_feedback_create,
- },
- RegisteredController {
- schema: schema_feedback_vote(),
- handler: handle_tinyplace_feedback_vote,
- },
- // Registry export
- RegisteredController {
- schema: schema_registry_export(),
- handler: handle_tinyplace_registry_export,
- },
- // Groups invite/role section
- RegisteredController {
- schema: schema_groups_set_member_role(),
- handler: handle_tinyplace_groups_set_member_role,
- },
- RegisteredController {
- schema: schema_groups_create_invite(),
- handler: handle_tinyplace_groups_create_invite,
- },
- RegisteredController {
- schema: schema_groups_list_invites(),
- handler: handle_tinyplace_groups_list_invites,
- },
- RegisteredController {
- schema: schema_groups_preview_invite(),
- handler: handle_tinyplace_groups_preview_invite,
- },
- RegisteredController {
- schema: schema_groups_revoke_invite(),
- handler: handle_tinyplace_groups_revoke_invite,
- },
- RegisteredController {
- schema: schema_groups_redeem_invite(),
- handler: handle_tinyplace_groups_redeem_invite,
- },
- // Users email verification
- RegisteredController {
- schema: schema_users_start_email_verification(),
- handler: handle_tinyplace_users_start_email_verification,
- },
- RegisteredController {
- schema: schema_users_confirm_email_verification(),
- handler: handle_tinyplace_users_confirm_email_verification,
- },
- // Solana section
- RegisteredController {
- schema: schema_solana_info(),
- handler: handle_tinyplace_solana_info,
- },
- RegisteredController {
- schema: schema_solana_call(),
- handler: handle_tinyplace_solana_call,
- },
- // Streams section
- RegisteredController {
- schema: schema_streams_start(),
- handler: handle_tinyplace_streams_start,
- },
- RegisteredController {
- schema: schema_streams_stop(),
- handler: handle_tinyplace_streams_stop,
- },
- RegisteredController {
- schema: schema_streams_list(),
- handler: handle_tinyplace_streams_list,
- },
- // Signal key management
- RegisteredController {
- schema: schema_signal_provision(),
- handler: handle_tinyplace_signal_provision,
- },
- RegisteredController {
- schema: schema_signal_upload_pre_keys(),
- handler: handle_tinyplace_signal_upload_pre_keys,
- },
- RegisteredController {
- schema: schema_signal_rotate_signed_pre_key(),
- handler: handle_tinyplace_signal_rotate_signed_pre_key,
- },
- RegisteredController {
- schema: schema_signal_get_bundle(),
- handler: handle_tinyplace_signal_get_bundle,
- },
- RegisteredController {
- schema: schema_signal_key_status(),
- handler: handle_tinyplace_signal_key_status,
- },
- // Signal messaging
- RegisteredController {
- schema: schema_signal_send_message(),
- handler: handle_tinyplace_signal_send_message,
- },
- RegisteredController {
- schema: schema_signal_decrypt_message(),
- handler: handle_tinyplace_signal_decrypt_message,
- },
- RegisteredController {
- schema: schema_messages_list(),
- handler: handle_tinyplace_messages_list,
- },
- RegisteredController {
- schema: schema_messages_acknowledge(),
- handler: handle_tinyplace_messages_acknowledge,
- },
- // Contacts / pairing precondition for encrypted DMs
- RegisteredController {
- schema: schema_contacts_request(),
- handler: handle_tinyplace_contacts_request,
- },
- RegisteredController {
- schema: schema_contacts_accept(),
- handler: handle_tinyplace_contacts_accept,
- },
- RegisteredController {
- schema: schema_contacts_remove(),
- handler: handle_tinyplace_contacts_remove,
- },
- RegisteredController {
- schema: schema_contacts_block(),
- handler: handle_tinyplace_contacts_block,
- },
- RegisteredController {
- schema: schema_contacts_unblock(),
- handler: handle_tinyplace_contacts_unblock,
- },
- RegisteredController {
- schema: schema_contacts_list(),
- handler: handle_tinyplace_contacts_list,
- },
- RegisteredController {
- schema: schema_contacts_requests(),
- handler: handle_tinyplace_contacts_requests,
- },
- RegisteredController {
- schema: schema_contacts_status(),
- handler: handle_tinyplace_contacts_status,
- },
- RegisteredController {
- schema: schema_contacts_stats(),
- handler: handle_tinyplace_contacts_stats,
- },
- // Encryption key registration + discovery (0D)
- RegisteredController {
- schema: schema_signal_register_encryption_key(),
- handler: handle_tinyplace_signal_register_encryption_key,
- },
- RegisteredController {
- schema: schema_directory_find_by_encryption_key(),
- handler: handle_tinyplace_directory_find_by_encryption_key,
- },
- // Feeds write surface (Phase A)
- RegisteredController {
- schema: schema_feeds_create_post(),
- handler: handle_tinyplace_feeds_create_post,
- },
- RegisteredController {
- schema: schema_feeds_delete_post(),
- handler: handle_tinyplace_feeds_delete_post,
- },
- RegisteredController {
- schema: schema_feeds_add_comment(),
- handler: handle_tinyplace_feeds_add_comment,
- },
- RegisteredController {
- schema: schema_feeds_delete_comment(),
- handler: handle_tinyplace_feeds_delete_comment,
- },
- RegisteredController {
- schema: schema_feeds_like_post(),
- handler: handle_tinyplace_feeds_like_post,
- },
- RegisteredController {
- schema: schema_feeds_unlike_post(),
- handler: handle_tinyplace_feeds_unlike_post,
- },
- // Bounties section (Phase B)
- RegisteredController {
- schema: schema_bounties_list(),
- handler: handle_tinyplace_bounties_list,
- },
- RegisteredController {
- schema: schema_bounties_get(),
- handler: handle_tinyplace_bounties_get,
- },
- RegisteredController {
- schema: schema_bounties_create(),
- handler: handle_tinyplace_bounties_create,
- },
- RegisteredController {
- schema: schema_bounties_cancel(),
- handler: handle_tinyplace_bounties_cancel,
- },
- RegisteredController {
- schema: schema_bounties_submit(),
- handler: handle_tinyplace_bounties_submit,
- },
- RegisteredController {
- schema: schema_bounties_list_submissions(),
- handler: handle_tinyplace_bounties_list_submissions,
- },
- RegisteredController {
- schema: schema_bounties_comment(),
- handler: handle_tinyplace_bounties_comment,
- },
- RegisteredController {
- schema: schema_bounties_list_comments(),
- handler: handle_tinyplace_bounties_list_comments,
- },
- RegisteredController {
- schema: schema_bounties_run_council(),
- handler: handle_tinyplace_bounties_run_council,
- },
- RegisteredController {
- schema: schema_bounties_approve(),
- handler: handle_tinyplace_bounties_approve,
- },
- // GraphQL Social Feed
- RegisteredController {
- schema: schema_graphql_home_feed(),
- handler: handle_tinyplace_graphql_home_feed,
- },
- RegisteredController {
- schema: schema_graphql_posts(),
- handler: handle_tinyplace_graphql_posts,
- },
- RegisteredController {
- schema: schema_graphql_post(),
- handler: handle_tinyplace_graphql_post,
- },
- RegisteredController {
- schema: schema_graphql_post_comments(),
- handler: handle_tinyplace_graphql_post_comments,
- },
- RegisteredController {
- schema: schema_graphql_post_likers(),
- handler: handle_tinyplace_graphql_post_likers,
- },
- // GraphQL Ledger
- RegisteredController {
- schema: schema_graphql_ledger_transactions(),
- handler: handle_tinyplace_graphql_ledger_transactions,
- },
- RegisteredController {
- schema: schema_graphql_ledger_transaction(),
- handler: handle_tinyplace_graphql_ledger_transaction,
- },
- // GraphQL Jobs
- RegisteredController {
- schema: schema_graphql_jobs(),
- handler: handle_tinyplace_graphql_jobs,
- },
- RegisteredController {
- schema: schema_graphql_job(),
- handler: handle_tinyplace_graphql_job,
- },
- // GraphQL Bounties
- RegisteredController {
- schema: schema_graphql_bounties(),
- handler: handle_tinyplace_graphql_bounties,
- },
- RegisteredController {
- schema: schema_graphql_bounty(),
- handler: handle_tinyplace_graphql_bounty,
- },
- // GraphQL Profile + Identity
- RegisteredController {
- schema: schema_graphql_profile(),
- handler: handle_tinyplace_graphql_profile,
- },
- RegisteredController {
- schema: schema_graphql_user(),
- handler: handle_tinyplace_graphql_user,
- },
- RegisteredController {
- schema: schema_graphql_identity(),
- handler: handle_tinyplace_graphql_identity,
- },
- RegisteredController {
- schema: schema_graphql_identities(),
- handler: handle_tinyplace_graphql_identities,
- },
- RegisteredController {
- schema: schema_graphql_agent_card(),
- handler: handle_tinyplace_graphql_agent_card,
- },
- RegisteredController {
- schema: schema_graphql_agents(),
- handler: handle_tinyplace_graphql_agents,
- },
- RegisteredController {
- schema: schema_graphql_products(),
- handler: handle_tinyplace_graphql_products,
- },
- RegisteredController {
- schema: schema_graphql_product(),
- handler: handle_tinyplace_graphql_product,
- },
- RegisteredController {
- schema: schema_graphql_identity_listings(),
- handler: handle_tinyplace_graphql_identity_listings,
- },
- RegisteredController {
- schema: schema_graphql_identity_listing(),
- handler: handle_tinyplace_graphql_identity_listing,
- },
- RegisteredController {
- schema: schema_graphql_identity_bids(),
- handler: handle_tinyplace_graphql_identity_bids,
- },
- RegisteredController {
- schema: schema_graphql_identity_offers(),
- handler: handle_tinyplace_graphql_identity_offers,
- },
- RegisteredController {
- schema: schema_graphql_identity_sales(),
- handler: handle_tinyplace_graphql_identity_sales,
- },
- ]
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn schema_and_controller_lists_match() {
- assert_eq!(
- all_tinyplace_controller_schemas().len(),
- all_tinyplace_registered_controllers().len(),
- "schema list and registered list must be the same length"
- );
- }
-
- #[test]
- fn schema_namespace_is_tinyplace() {
- for schema in all_tinyplace_controller_schemas() {
- assert_eq!(schema.namespace, "tinyplace");
- }
- }
-
- #[test]
- fn rpc_method_names_have_correct_prefix() {
- use crate::core::all::rpc_method_name;
- for controller in all_tinyplace_registered_controllers() {
- let method = rpc_method_name(&controller.schema);
- assert!(
- method.starts_with("openhuman.tinyplace_"),
- "method {method} does not start with openhuman.tinyplace_"
- );
- }
- }
-
- /// Verify the six feeds write handlers (Phase A) are registered with correct method names.
- #[test]
- fn feeds_write_handlers_are_registered() {
- use crate::core::all::rpc_method_name;
- let expected = [
- "openhuman.tinyplace_feeds_create_post",
- "openhuman.tinyplace_feeds_delete_post",
- "openhuman.tinyplace_feeds_add_comment",
- "openhuman.tinyplace_feeds_delete_comment",
- "openhuman.tinyplace_feeds_like_post",
- "openhuman.tinyplace_feeds_unlike_post",
- ];
- let registered: Vec<String> = all_tinyplace_registered_controllers()
- .into_iter()
- .map(|c| rpc_method_name(&c.schema))
- .collect();
- for method in &expected {
- assert!(
- registered.contains(&method.to_string()),
- "expected handler for {method} to be registered, found: {registered:?}"
- );
- }
- }
-
- /// Verify the five GraphQL Social Feed handlers are registered with correct method names.
- #[test]
- fn graphql_feed_handlers_are_registered() {
- use crate::core::all::rpc_method_name;
- let expected = [
- "openhuman.tinyplace_graphql_home_feed",
- "openhuman.tinyplace_graphql_posts",
- "openhuman.tinyplace_graphql_post",
- "openhuman.tinyplace_graphql_post_comments",
- "openhuman.tinyplace_graphql_post_likers",
- ];
- let registered: Vec<String> = all_tinyplace_registered_controllers()
- .into_iter()
- .map(|c| rpc_method_name(&c.schema))
- .collect();
- for method in &expected {
- assert!(
- registered.contains(&method.to_string()),
- "expected handler for {method} to be registered, found: {registered:?}"
- );
- }
- }
-
- /// Verify the two GraphQL Ledger handlers are registered with correct method names.
- #[test]
- fn graphql_ledger_handlers_are_registered() {
- use crate::core::all::rpc_method_name;
- let expected = [
- "openhuman.tinyplace_graphql_ledger_transactions",
- "openhuman.tinyplace_graphql_ledger_transaction",
- ];
- let registered: Vec<String> = all_tinyplace_registered_controllers()
- .into_iter()
- .map(|c| rpc_method_name(&c.schema))
- .collect();
- for method in &expected {
- assert!(
- registered.contains(&method.to_string()),
- "expected handler for {method} to be registered, found: {registered:?}"
- );
- }
- }
-
- /// Verify the two GraphQL Jobs handlers are registered with correct method names.
- #[test]
- fn graphql_jobs_handlers_are_registered() {
- use crate::core::all::rpc_method_name;
- let expected = [
- "openhuman.tinyplace_graphql_jobs",
- "openhuman.tinyplace_graphql_job",
- ];
- let registered: Vec<String> = all_tinyplace_registered_controllers()
- .into_iter()
- .map(|c| rpc_method_name(&c.schema))
- .collect();
- for method in &expected {
- assert!(
- registered.contains(&method.to_string()),
- "expected handler for {method} to be registered, found: {registered:?}"
- );
- }
- }
-
- /// Verify the five GraphQL Profile + Identity handlers are registered with correct method names.
- #[test]
- fn graphql_profile_identity_handlers_are_registered() {
- use crate::core::all::rpc_method_name;
- let expected = [
- "openhuman.tinyplace_graphql_profile",
- "openhuman.tinyplace_graphql_user",
- "openhuman.tinyplace_graphql_identity",
- "openhuman.tinyplace_graphql_identities",
- "openhuman.tinyplace_graphql_agent_card",
- ];
- let registered: Vec<String> = all_tinyplace_registered_controllers()
- .into_iter()
- .map(|c| rpc_method_name(&c.schema))
- .collect();
- for method in &expected {
- assert!(
- registered.contains(&method.to_string()),
- "expected handler for {method} to be registered, found: {registered:?}"
- );
- }
- }
-
- /// Verify the four new Directory section handlers are wired in and have the
- /// expected RPC method names.
- #[test]
- fn directory_section_handlers_are_registered() {
- use crate::core::all::rpc_method_name;
- let expected = [
- "openhuman.tinyplace_directory_resolve",
- "openhuman.tinyplace_directory_reverse",
- "openhuman.tinyplace_directory_list_identities",
- "openhuman.tinyplace_directory_skills",
- ];
- let registered: Vec<String> = all_tinyplace_registered_controllers()
- .into_iter()
- .map(|c| rpc_method_name(&c.schema))
- .collect();
- for method in &expected {
- assert!(
- registered.contains(&method.to_string()),
- "expected handler for {method} to be registered, found: {registered:?}"
- );
- }
- }
-
- /// Verify all 11 Bounties handlers (Phase B) are registered with correct method names.
- #[test]
- fn bounties_handlers_are_registered() {
- use crate::core::all::rpc_method_name;
- let expected = [
- "openhuman.tinyplace_bounties_list",
- "openhuman.tinyplace_bounties_get",
- "openhuman.tinyplace_bounties_create",
- "openhuman.tinyplace_bounties_cancel",
- "openhuman.tinyplace_bounties_submit",
- "openhuman.tinyplace_bounties_list_submissions",
- "openhuman.tinyplace_bounties_comment",
- "openhuman.tinyplace_bounties_list_comments",
- "openhuman.tinyplace_bounties_run_council",
- "openhuman.tinyplace_bounties_approve",
- ];
- let registered: Vec<String> = all_tinyplace_registered_controllers()
- .into_iter()
- .map(|c| rpc_method_name(&c.schema))
- .collect();
- for method in &expected {
- assert!(
- registered.contains(&method.to_string()),
- "expected handler for {method} to be registered, found: {registered:?}"
- );
- }
- }
-}
diff --git a/src/openhuman/tinyplace/signal_e2e_tests.rs b/src/openhuman/tinyplace/signal_e2e_tests.rs
deleted file mode 100644
index 0d0a1b169d..0000000000
--- a/src/openhuman/tinyplace/signal_e2e_tests.rs
+++ /dev/null
@@ -1,518 +0,0 @@
-//! Full local E2E round-trip tests for Signal protocol.
-use std::collections::HashMap;
-use std::sync::Arc;
-
-use base64::Engine as _;
-use tinyplace::signal::crypto::{ed25519_seed_to_x25519_keypair, generate_x25519_keypair};
-use tinyplace::signal::keys::{generate_pre_keys, generate_signed_pre_key, serialize_pre_key};
-use tinyplace::signal::ratchet::{ratchet_decrypt, ratchet_encrypt};
-use tinyplace::signal::session::SignalSession;
-use tinyplace::signal::store::{SessionState, SessionStore};
-use tinyplace::signal::x3dh::{build_associated_data, x3dh_initiate, x3dh_respond, X3DHBundle};
-use tinyplace::types::{KeyBundle, MessageEnvelope};
-
-use crate::openhuman::security::keyring::SecretStore;
-use crate::openhuman::tinyplace::signal_store::FileSessionStore;
-
-#[tokio::test]
-async fn signal_e2e_round_trip_alice_bob() {
- let alice_dir = tempfile::tempdir().unwrap();
- let bob_dir = tempfile::tempdir().unwrap();
- let alice_seed = [1u8; 32];
- let bob_seed = [2u8; 32];
- let alice_identity = ed25519_seed_to_x25519_keypair(&alice_seed);
- let bob_identity = ed25519_seed_to_x25519_keypair(&bob_seed);
- let alice_ss = SecretStore::new(alice_dir.path(), true);
- let bob_ss = SecretStore::new(bob_dir.path(), true);
- let alice_store = FileSessionStore::new(
- alice_identity.clone(),
- alice_dir.path().join("signal"),
- alice_ss,
- )
- .await
- .unwrap();
- let bob_store =
- FileSessionStore::new(bob_identity.clone(), bob_dir.path().join("signal"), bob_ss)
- .await
- .unwrap();
- let bob_signer = tinyplace::LocalSigner::from_seed(&bob_seed).unwrap();
- let bob_spk = generate_signed_pre_key(&bob_signer as &dyn tinyplace::Signer, "spk_test")
- .await
- .unwrap();
- bob_store
- .store_signed_pre_key(bob_spk.clone())
- .await
- .unwrap();
- let bob_otpks = generate_pre_keys(&bob_signer as &dyn tinyplace::Signer, 0, 5)
- .await
- .unwrap();
- for pk in &bob_otpks {
- bob_store.store_pre_key(pk.clone()).await.unwrap();
- }
- let bob_bundle = X3DHBundle {
- identity_key: bob_identity.public_key,
- signed_pre_key_id: bob_spk.key_id.clone(),
- signed_pre_key: bob_spk.key_pair.public_key,
- one_time_pre_key_id: Some(bob_otpks[0].key_id.clone()),
- one_time_pre_key: Some(bob_otpks[0].key_pair.public_key),
- };
- let x3dh_result = x3dh_initiate(&alice_identity, &bob_bundle);
- let mut alice_session = x3dh_result.session;
- let ad = build_associated_data(&alice_identity.public_key, &bob_identity.public_key);
- let plaintext = b"Hello Bob, this is a secret message!";
- let ratchet_msg = ratchet_encrypt(&mut alice_session, plaintext, &ad).unwrap();
- alice_store
- .store_session("bob", alice_session.clone())
- .await
- .unwrap();
- let bob_otpk_pair = &bob_otpks[0];
- let mut bob_session = x3dh_respond(
- &bob_identity,
- &bob_spk.key_pair,
- &alice_identity.public_key,
- &x3dh_result.ephemeral_public_key,
- Some(&bob_otpk_pair.key_pair),
- );
- let ad_bob = build_associated_data(&alice_identity.public_key, &bob_identity.public_key);
- let decrypted = ratchet_decrypt(&mut bob_session, &ratchet_msg, &ad_bob).unwrap();
- assert_eq!(
- decrypted, plaintext,
- "decrypted plaintext must match original"
- );
- bob_store
- .store_session("alice", bob_session.clone())
- .await
- .unwrap();
- bob_store
- .remove_pre_key(&bob_otpks[0].key_id)
- .await
- .unwrap();
- let remaining = bob_store.all_pre_keys().await.unwrap();
- assert_eq!(remaining.len(), 4, "one-time pre-key should be consumed");
- let reply = b"Hello Alice, message received!";
- let reply_msg = ratchet_encrypt(&mut bob_session, reply, &ad_bob).unwrap();
- bob_store
- .store_session("alice", bob_session.clone())
- .await
- .unwrap();
- let mut alice_session = alice_store.session("bob").await.unwrap().unwrap();
- let decrypted_reply = ratchet_decrypt(&mut alice_session, &reply_msg, &ad).unwrap();
- assert_eq!(decrypted_reply, reply, "Alice must decrypt Bob's reply");
- alice_store
- .store_session("bob", alice_session)
- .await
- .unwrap();
- let mut alice_session = alice_store.session("bob").await.unwrap().unwrap();
- let mut messages = Vec::new();
- for i in 0..5 {
- let msg_text = format!("Message #{i} from Alice").into_bytes();
- let msg = ratchet_encrypt(&mut alice_session, &msg_text, &ad).unwrap();
- messages.push((msg, msg_text));
- }
- alice_store
- .store_session("bob", alice_session)
- .await
- .unwrap();
- let mut bob_session = bob_store.session("alice").await.unwrap().unwrap();
- for (msg, expected) in &messages {
- let decrypted = ratchet_decrypt(&mut bob_session, msg, &ad_bob).unwrap();
- assert_eq!(&decrypted, expected);
- }
- bob_store.store_session("alice", bob_session).await.unwrap();
-}
-
-#[test]
-fn signal_e2e_no_plaintext_on_failure() {
- let identity = generate_x25519_keypair();
- let mut broken_session = SessionState {
- dh_send_key_pair: generate_x25519_keypair(),
- dh_recv_public_key: None,
- root_key: [0u8; 32],
- send_chain_key: None,
- recv_chain_key: None,
- send_message_number: 0,
- recv_message_number: 0,
- previous_chain_length: 0,
- skipped_keys: HashMap::new(),
- };
- let ad = build_associated_data(&identity.public_key, &[42u8; 32]);
- let result = ratchet_encrypt(&mut broken_session, b"secret", &ad);
- assert!(
- result.is_err(),
- "ratchet_encrypt MUST fail when DH ratchet cannot be performed"
- );
-}
-
-#[test]
-fn associated_data_binds_both_identities() {
- let alice = [1u8; 32];
- let bob = [2u8; 32];
- let ad = build_associated_data(&alice, &bob);
- assert_eq!(ad.len(), 64);
- assert_eq!(&ad[..32], &alice);
- assert_eq!(&ad[32..], &bob);
- let ad_swapped = build_associated_data(&bob, &alice);
- assert_ne!(ad, ad_swapped);
-}
-
-// ── SignalSession conformance tests ───────────────────────────────────────────
-//
-// These tests prove that `SignalSession::encrypt` + `SignalSession::decrypt`
-// backed by our `FileSessionStore` produce byte-compatible output with the
-// existing low-level round trip. They are the safety net for Phase 5.
-
-/// Helper: build an isolated `FileSessionStore` wrapped in `Arc`.
-async fn arc_test_store(
- seed: [u8; 32],
-) -> (
- Arc<crate::openhuman::tinyplace::signal_store::FileSessionStore>,
- tempfile::TempDir,
-) {
- let dir = tempfile::tempdir().unwrap();
- let secret_store = SecretStore::new(dir.path(), true);
- let identity = ed25519_seed_to_x25519_keypair(&seed);
- let store = crate::openhuman::tinyplace::signal_store::FileSessionStore::new(
- identity,
- dir.path().join("signal"),
- secret_store,
- )
- .await
- .unwrap();
- (Arc::new(store), dir)
-}
-
-/// Helper: turn an `EncryptedMessage` into a `MessageEnvelope` — the same
-/// mapping our production handler uses.
-fn encrypted_to_envelope(
- msg: &tinyplace::signal::session::EncryptedMessage,
- from: &str,
- to: &str,
-) -> MessageEnvelope {
- MessageEnvelope {
- id: String::new(),
- from: from.to_string(),
- to: to.to_string(),
- timestamp: String::new(),
- device_id: 1,
- envelope_type: msg.message_type.clone(),
- body: msg.body.clone(),
- content_hint: Some("DEFAULT".to_string()),
- signal: Some(msg.signal.clone()),
- }
-}
-
-/// Full Alice <-> Bob round trip through `SignalSession` + `FileSessionStore`.
-///
-/// Proves:
-/// - PREKEY_BUNDLE on first send, CIPHERTEXT on subsequent sends.
-/// - Bob decrypts Alice's initial message correctly.
-/// - Bob replies and Alice decrypts.
-/// - Ratchet advances correctly over 5 additional messages each way.
-/// - `FileSessionStore` persistence is exercised (sessions loaded from disk
-/// across store calls).
-#[tokio::test]
-async fn signal_session_round_trip_alice_bob() {
- let alice_seed = [11u8; 32];
- let bob_seed = [22u8; 32];
- let alice_identity = ed25519_seed_to_x25519_keypair(&alice_seed);
- let bob_identity = ed25519_seed_to_x25519_keypair(&bob_seed);
-
- let (alice_store, _alice_dir) = arc_test_store(alice_seed).await;
- let (bob_store, _bob_dir) = arc_test_store(bob_seed).await;
-
- // Build Bob's pre-keys and KeyBundle (mirrors production: X25519 identity
- // key encoded as base64, signed pre-key + one-time pre-key serialised to
- // `SignedKey` wire form).
- let bob_signer = tinyplace::LocalSigner::from_seed(&bob_seed).unwrap();
- let bob_spk = generate_signed_pre_key(&bob_signer as &dyn tinyplace::Signer, "spk_sess_test")
- .await
- .unwrap();
- bob_store
- .store_signed_pre_key(bob_spk.clone())
- .await
- .unwrap();
-
- let bob_otpks = generate_pre_keys(&bob_signer as &dyn tinyplace::Signer, 0, 3)
- .await
- .unwrap();
- for pk in &bob_otpks {
- bob_store.store_pre_key(pk.clone()).await.unwrap();
- }
-
- let bob_bundle = KeyBundle {
- agent_id: "bob".to_string(),
- identity_key: base64::engine::general_purpose::STANDARD.encode(bob_identity.public_key),
- signed_pre_key: serialize_pre_key(&bob_spk),
- one_time_pre_key: Some(serialize_pre_key(&bob_otpks[0])),
- updated_at: String::new(),
- };
-
- // Construct SignalSession instances.
- let alice_session = SignalSession::new(
- Arc::clone(&alice_store) as Arc<dyn SessionStore>,
- alice_identity.public_key,
- );
- let bob_session = SignalSession::new(
- Arc::clone(&bob_store) as Arc<dyn SessionStore>,
- bob_identity.public_key,
- );
-
- // Ed25519 identity for bob (in a real handler this is the directory entry's
- // public_key after decode_ed25519_pub; in tests we use the signer's key).
- let bob_ed25519_pub = *bob_signer.public_key();
-
- // ── Alice -> Bob: first message (PREKEY_BUNDLE) ───────────────────────────
- let msg1_plaintext = b"Hello Bob via SignalSession!";
- let encrypted1 = alice_session
- .encrypt(
- "bob",
- &bob_identity.public_key,
- msg1_plaintext,
- Some(&bob_bundle),
- Some(&bob_ed25519_pub),
- )
- .await
- .unwrap();
- assert_eq!(
- encrypted1.message_type,
- tinyplace::signal::session::TYPE_PREKEY_BUNDLE,
- "first message must be PREKEY_BUNDLE"
- );
-
- let env1 = encrypted_to_envelope(&encrypted1, "alice", "bob");
- let decrypted1 = bob_session
- .decrypt("alice", &alice_identity.public_key, &env1)
- .await
- .unwrap();
- assert_eq!(
- decrypted1, msg1_plaintext,
- "Bob must decrypt Alice's first message"
- );
-
- // ── Bob -> Alice: reply (CIPHERTEXT — existing session, no bundle) ─────────
- let reply_plaintext = b"Hi Alice, got your message!";
- let encrypted_reply = bob_session
- .encrypt(
- "alice",
- &alice_identity.public_key,
- reply_plaintext,
- None,
- None,
- )
- .await
- .unwrap();
- assert_eq!(
- encrypted_reply.message_type,
- tinyplace::signal::session::TYPE_CIPHERTEXT,
- "Bob's reply must be CIPHERTEXT"
- );
-
- let env_reply = encrypted_to_envelope(&encrypted_reply, "bob", "alice");
- let decrypted_reply = alice_session
- .decrypt("bob", &bob_identity.public_key, &env_reply)
- .await
- .unwrap();
- assert_eq!(
- decrypted_reply, reply_plaintext,
- "Alice must decrypt Bob's reply"
- );
-
- // ── Ratchet exercises: 5 messages Alice -> Bob, then 5 Bob -> Alice ───────
- for i in 0..5 {
- let msg = format!("Ratchet message #{i} from Alice").into_bytes();
- let enc = alice_session
- .encrypt("bob", &bob_identity.public_key, &msg, None, None)
- .await
- .unwrap();
- assert_eq!(
- enc.message_type,
- tinyplace::signal::session::TYPE_CIPHERTEXT
- );
- let env = encrypted_to_envelope(&enc, "alice", "bob");
- let dec = bob_session
- .decrypt("alice", &alice_identity.public_key, &env)
- .await
- .unwrap();
- assert_eq!(dec, msg, "Ratchet message #{i} must round-trip");
- }
-
- for i in 0..5 {
- let msg = format!("Ratchet message #{i} from Bob").into_bytes();
- let enc = bob_session
- .encrypt("alice", &alice_identity.public_key, &msg, None, None)
- .await
- .unwrap();
- let env = encrypted_to_envelope(&enc, "bob", "alice");
- let dec = alice_session
- .decrypt("bob", &bob_identity.public_key, &env)
- .await
- .unwrap();
- assert_eq!(dec, msg, "Bob ratchet message #{i} must round-trip");
- }
-
- // Both sessions must be persisted.
- assert!(
- alice_session.has_session("bob").await.unwrap(),
- "Alice's session with Bob must be persisted"
- );
- assert!(
- bob_session.has_session("alice").await.unwrap(),
- "Bob's session with Alice must be persisted"
- );
-}
-
-/// Cross-interop: encrypt with the low-level API, decrypt with `SignalSession`;
-/// then encrypt with `SignalSession`, decrypt with the low-level API.
-///
-/// This is the strongest proof that the Phase 5 refactor does not change
-/// wire format or session state — both code paths must interoperate perfectly.
-#[tokio::test]
-async fn signal_session_cross_interop_low_level() {
- let alice_seed = [33u8; 32];
- let bob_seed = [44u8; 32];
- let alice_identity = ed25519_seed_to_x25519_keypair(&alice_seed);
- let bob_identity = ed25519_seed_to_x25519_keypair(&bob_seed);
-
- let alice_dir = tempfile::tempdir().unwrap();
- let bob_dir = tempfile::tempdir().unwrap();
-
- let alice_ss = SecretStore::new(alice_dir.path(), true);
- let bob_ss = SecretStore::new(bob_dir.path(), true);
-
- let alice_store_raw = crate::openhuman::tinyplace::signal_store::FileSessionStore::new(
- alice_identity.clone(),
- alice_dir.path().join("signal"),
- alice_ss,
- )
- .await
- .unwrap();
-
- let bob_store_raw = crate::openhuman::tinyplace::signal_store::FileSessionStore::new(
- bob_identity.clone(),
- bob_dir.path().join("signal"),
- bob_ss,
- )
- .await
- .unwrap();
-
- // Bob pre-keys.
- let bob_signer = tinyplace::LocalSigner::from_seed(&bob_seed).unwrap();
- let bob_spk = generate_signed_pre_key(&bob_signer as &dyn tinyplace::Signer, "spk_xop")
- .await
- .unwrap();
- bob_store_raw
- .store_signed_pre_key(bob_spk.clone())
- .await
- .unwrap();
- let bob_otpks = generate_pre_keys(&bob_signer as &dyn tinyplace::Signer, 10, 2)
- .await
- .unwrap();
- for pk in &bob_otpks {
- bob_store_raw.store_pre_key(pk.clone()).await.unwrap();
- }
-
- // ── Alice encrypts with LOW-LEVEL API ─────────────────────────────────────
- let bob_bundle_x3dh = X3DHBundle {
- identity_key: bob_identity.public_key,
- signed_pre_key_id: bob_spk.key_id.clone(),
- signed_pre_key: bob_spk.key_pair.public_key,
- one_time_pre_key_id: Some(bob_otpks[0].key_id.clone()),
- one_time_pre_key: Some(bob_otpks[0].key_pair.public_key),
- };
- let x3dh_result = x3dh_initiate(&alice_identity, &bob_bundle_x3dh);
- let mut alice_low_session = x3dh_result.session.clone();
- let ad = build_associated_data(&alice_identity.public_key, &bob_identity.public_key);
- let low_msg = ratchet_encrypt(&mut alice_low_session, b"low-level to session", &ad).unwrap();
- alice_store_raw
- .store_session("bob", alice_low_session)
- .await
- .unwrap();
-
- // Build the wire envelope exactly as the production handler does.
- let envelope_from_low = MessageEnvelope {
- id: String::new(),
- from: "alice".to_string(),
- to: "bob".to_string(),
- timestamp: String::new(),
- device_id: 1,
- envelope_type: "PREKEY_BUNDLE".to_string(),
- body: base64::engine::general_purpose::STANDARD.encode(&low_msg.ciphertext),
- content_hint: Some("DEFAULT".to_string()),
- signal: Some(tinyplace::types::SignalMetadata {
- ephemeral_key: Some(
- base64::engine::general_purpose::STANDARD.encode(x3dh_result.ephemeral_public_key),
- ),
- signed_pre_key_id: Some(x3dh_result.signed_pre_key_id.clone()),
- one_time_pre_key_id: x3dh_result.one_time_pre_key_id.clone(),
- ratchet_key: Some(
- base64::engine::general_purpose::STANDARD.encode(low_msg.header.public_key),
- ),
- message_number: Some(low_msg.header.message_number as i64),
- previous_chain_length: Some(low_msg.header.previous_chain_length as i64),
- ..Default::default()
- }),
- };
-
- // ── Bob decrypts with SignalSession ───────────────────────────────────────
- let bob_arc = Arc::new(bob_store_raw);
- let bob_sig_session = SignalSession::new(
- Arc::clone(&bob_arc) as Arc<dyn SessionStore>,
- bob_identity.public_key,
- );
- let decrypted_by_session = bob_sig_session
- .decrypt("alice", &alice_identity.public_key, &envelope_from_low)
- .await
- .unwrap();
- assert_eq!(
- decrypted_by_session, b"low-level to session",
- "SignalSession must decrypt a message encrypted by the low-level API"
- );
-
- // ── Bob encrypts with SignalSession (existing session) ────────────────────
- let bob_reply_enc = bob_sig_session
- .encrypt(
- "alice",
- &alice_identity.public_key,
- b"session to low-level",
- None,
- None,
- )
- .await
- .unwrap();
- assert_eq!(
- bob_reply_enc.message_type,
- tinyplace::signal::session::TYPE_CIPHERTEXT
- );
-
- // ── Alice decrypts with LOW-LEVEL API ─────────────────────────────────────
- let reply_ciphertext = base64::engine::general_purpose::STANDARD
- .decode(&bob_reply_enc.body)
- .unwrap();
- let reply_signal = &bob_reply_enc.signal;
- use tinyplace::signal::ratchet::{RatchetHeader, RatchetMessage};
- let ratchet_key_bytes: [u8; 32] = base64::engine::general_purpose::STANDARD
- .decode(reply_signal.ratchet_key.as_ref().unwrap())
- .unwrap()
- .try_into()
- .unwrap();
- let reply_msg = RatchetMessage {
- header: RatchetHeader {
- public_key: ratchet_key_bytes,
- message_number: reply_signal.message_number.unwrap_or(0) as u32,
- previous_chain_length: reply_signal.previous_chain_length.unwrap_or(0) as u32,
- },
- ciphertext: reply_ciphertext,
- };
- let mut alice_session_loaded = alice_store_raw.session("bob").await.unwrap().unwrap();
- let ad_alice = build_associated_data(&alice_identity.public_key, &bob_identity.public_key);
- // AD on decrypt: [sender || recipient] = [bob || alice]
- let ad_recv = build_associated_data(&bob_identity.public_key, &alice_identity.public_key);
- let decrypted_by_low =
- ratchet_decrypt(&mut alice_session_loaded, &reply_msg, &ad_recv).unwrap();
- assert_eq!(
- decrypted_by_low, b"session to low-level",
- "Low-level API must decrypt a message encrypted by SignalSession"
- );
- // Suppress unused variable warning for ad_alice.
- let _ = ad_alice;
-}
diff --git a/src/openhuman/tinyplace/signal_store.rs b/src/openhuman/tinyplace/signal_store.rs
deleted file mode 100644
index 0a8848c76f..0000000000
--- a/src/openhuman/tinyplace/signal_store.rs
+++ /dev/null
@@ -1,1105 +0,0 @@
-//! Durable encrypted Signal session store for the tiny.place domain.
-//!
-//! [`FileSessionStore`] implements the [`tinyplace::signal::store::SessionStore`]
-//! async trait with encrypted-at-rest persistence under
-//! `{workspace_dir}/tinyplace/signal/`.
-//!
-//! ## Security model
-//!
-//! - **Identity key**: derived in-memory from the wallet seed via
-//! [`tinyplace::signal::crypto::ed25519_seed_to_x25519_keypair`]. Never written
-//! to disk. If the wallet is locked the store cannot be built.
-//! - **Pre-keys and sessions**: serialised to JSON, encrypted with
-//! [`crate::openhuman::security::keyring::SecretStore`] (ChaCha20-Poly1305, OS keychain
-//! master key), then written atomically. Raw private-key bytes never appear in
-//! plaintext on disk.
-//! - **Agent-write protection**: `{workspace_dir}/tinyplace/` is listed in
-//! `WORKSPACE_INTERNAL_DIRS` so agent tools cannot touch these files.
-//!
-//! ## Storage layout
-//!
-//! ```text
-//! {workspace_dir}/tinyplace/signal/
-//! signed_pre_keys/{key_id}.enc
-//! pre_keys/{key_id}.enc
-//! sessions/{address}.enc
-//! active_signed_pre_key.enc ← encrypted key_id string
-//! ```
-//!
-//! ## Concurrency
-//!
-//! A single `tokio::sync::Mutex<Cache>` serialises every operation, including
-//! the disk I/O, so cache and disk are always consistent. Operations are fast
-//! (small files, local SSD) so contention is minimal.
-
-use std::collections::HashMap;
-use std::io::Write as _;
-use std::path::{Path, PathBuf};
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde::{Deserialize, Serialize};
-use tokio::sync::OnceCell;
-
-use tinyplace::error::{Error, Result};
-use tinyplace::signal::crypto::{ed25519_seed_to_x25519_keypair, X25519KeyPair};
-use tinyplace::signal::keys::{PreKeyPair, SignedPreKeyPair};
-use tinyplace::signal::store::{SessionState, SessionStore};
-
-use crate::openhuman::security::keyring::SecretStore;
-
-// ── Serde mirror types ────────────────────────────────────────────────────────
-//
-// The SDK types (`X25519KeyPair`, `PreKeyPair`, `SessionState`) derive only
-// `Debug + Clone` — no `Serialize`/`Deserialize`. We define local mirrors with
-// field-for-field parity and trivial conversion functions.
-
-#[derive(Serialize, Deserialize)]
-struct SerializableKeyPair {
- public_key: [u8; 32],
- private_key: [u8; 32],
-}
-
-#[derive(Serialize, Deserialize)]
-struct SerializablePreKey {
- key_id: String,
- key_pair: SerializableKeyPair,
- /// `Vec<u8>` serialises as a JSON array of integers, which is fine because
- /// the JSON is immediately encrypted and never human-readable.
- signature: Vec<u8>,
-}
-
-#[derive(Serialize, Deserialize)]
-struct SerializableSession {
- dh_send_key_pair: SerializableKeyPair,
- #[serde(default)]
- dh_recv_public_key: Option<[u8; 32]>,
- root_key: [u8; 32],
- #[serde(default)]
- send_chain_key: Option<[u8; 32]>,
- #[serde(default)]
- recv_chain_key: Option<[u8; 32]>,
- #[serde(default)]
- send_message_number: u32,
- #[serde(default)]
- recv_message_number: u32,
- #[serde(default)]
- previous_chain_length: u32,
- #[serde(default)]
- skipped_keys: HashMap<String, [u8; 32]>,
-}
-
-// ── Conversion helpers ────────────────────────────────────────────────────────
-
-fn to_serializable_key_pair(kp: &X25519KeyPair) -> SerializableKeyPair {
- SerializableKeyPair {
- public_key: kp.public_key,
- private_key: kp.private_key,
- }
-}
-
-fn from_serializable_key_pair(s: SerializableKeyPair) -> X25519KeyPair {
- X25519KeyPair {
- public_key: s.public_key,
- private_key: s.private_key,
- }
-}
-
-fn to_serializable_pre_key(pk: &PreKeyPair) -> SerializablePreKey {
- SerializablePreKey {
- key_id: pk.key_id.clone(),
- key_pair: to_serializable_key_pair(&pk.key_pair),
- signature: pk.signature.clone(),
- }
-}
-
-fn from_serializable_pre_key(s: SerializablePreKey) -> PreKeyPair {
- PreKeyPair {
- key_id: s.key_id,
- key_pair: from_serializable_key_pair(s.key_pair),
- signature: s.signature,
- }
-}
-
-fn to_serializable_session(sess: &SessionState) -> SerializableSession {
- SerializableSession {
- dh_send_key_pair: to_serializable_key_pair(&sess.dh_send_key_pair),
- dh_recv_public_key: sess.dh_recv_public_key,
- root_key: sess.root_key,
- send_chain_key: sess.send_chain_key,
- recv_chain_key: sess.recv_chain_key,
- send_message_number: sess.send_message_number,
- recv_message_number: sess.recv_message_number,
- previous_chain_length: sess.previous_chain_length,
- skipped_keys: sess.skipped_keys.clone(),
- }
-}
-
-fn from_serializable_session(s: SerializableSession) -> SessionState {
- SessionState {
- dh_send_key_pair: from_serializable_key_pair(s.dh_send_key_pair),
- dh_recv_public_key: s.dh_recv_public_key,
- root_key: s.root_key,
- send_chain_key: s.send_chain_key,
- recv_chain_key: s.recv_chain_key,
- send_message_number: s.send_message_number,
- recv_message_number: s.recv_message_number,
- previous_chain_length: s.previous_chain_length,
- skipped_keys: s.skipped_keys,
- }
-}
-
-// ── Filename sanitisation ─────────────────────────────────────────────────────
-
-/// Sanitise a key-id or address for use as a filename component.
-///
-/// Replaces filesystem-unsafe characters with `_` and caps at 200 chars.
-/// The SDK generates IDs like `pk_0`, `pk_1`, `spk_<timestamp>` and Solana
-/// base58 addresses — all safe, but we sanitise defensively.
-fn sanitize(name: &str) -> String {
- let sanitized: String = name
- .chars()
- .map(|c| match c {
- '/' | '\\' | '\0' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
- c => c,
- })
- .take(200)
- .collect();
-
- if sanitized.is_empty() || sanitized == "." || sanitized == ".." {
- "_".to_string()
- } else {
- sanitized
- }
-}
-
-// ── In-memory cache ───────────────────────────────────────────────────────────
-
-struct Cache {
- signed_pre_keys: HashMap<String, PreKeyPair>,
- pre_keys: HashMap<String, PreKeyPair>,
- sessions: HashMap<String, SessionState>,
- active_signed_pre_key_id: Option<String>,
- /// Set to `true` after the initial cold-load from disk.
- warm: bool,
-}
-
-// ── FileSessionStore ──────────────────────────────────────────────────────────
-
-/// Encrypted, file-backed [`SessionStore`] for the tiny.place Signal protocol.
-///
-/// See the module doc for the full security model and storage layout.
-pub(crate) struct FileSessionStore {
- /// X25519 identity key pair. Held in memory only — never written to disk.
- identity: X25519KeyPair,
-
- /// Root directory: `{workspace_dir}/tinyplace/signal/`.
- dir: PathBuf,
-
- /// Encrypts/decrypts file content using the OS keychain-backed ChaCha20 key.
- secret_store: SecretStore,
-
- /// In-memory cache + I/O lock. A single mutex serialises every operation so
- /// the cache and disk are always consistent.
- cache: tokio::sync::Mutex<Cache>,
-}
-
-impl FileSessionStore {
- /// Construct a new store, creating the directory tree and warming the cache.
- ///
- /// `identity` — X25519 key pair derived from the wallet seed (caller's responsibility).
- /// `dir` — the root directory (`{workspace_dir}/tinyplace/signal/`).
- /// `secret_store` — handle to the process-wide ChaCha20 encryption layer.
- pub(crate) async fn new(
- identity: X25519KeyPair,
- dir: PathBuf,
- secret_store: SecretStore,
- ) -> std::result::Result<Self, String> {
- // Create the subdirectory tree.
- for sub in &["signed_pre_keys", "pre_keys", "sessions"] {
- tokio::fs::create_dir_all(dir.join(sub))
- .await
- .map_err(|e| {
- format!(
- "[signal_store] failed to create dir {}/{sub}: {e}",
- dir.display()
- )
- })?;
- }
-
- let store = Self {
- identity,
- dir,
- secret_store,
- cache: tokio::sync::Mutex::new(Cache {
- signed_pre_keys: HashMap::new(),
- pre_keys: HashMap::new(),
- sessions: HashMap::new(),
- active_signed_pre_key_id: None,
- warm: false,
- }),
- };
-
- // Warm the cache by loading all existing files from disk.
- store.warm_cache().await?;
-
- log::info!(
- "[signal_store] initialized dir={} (identity key not logged)",
- store.dir.display()
- );
- Ok(store)
- }
-
- // ── Encrypt / decrypt helpers ─────────────────────────────────────────────
-
- /// Serialise `json` to `enc2:<hex>` via ChaCha20-Poly1305, then write
- /// atomically to `path` (temp-file + rename).
- ///
- /// SECURITY: this is the ONLY write path in this module. All writes go
- /// through here; no plaintext ever reaches `std::fs::write` directly.
- fn encrypt_and_write(&self, path: &Path, json: &str) -> std::result::Result<(), String> {
- let encrypted = self
- .secret_store
- .encrypt(json)
- .map_err(|e| format!("[signal_store] encrypt failed for {}: {e}", path.display()))?;
-
- // Atomic write: write to a temp file in the same directory, then rename.
- // Using the same directory as the destination avoids cross-device rename
- // failures (which would silently leave state inconsistent).
- let parent = path
- .parent()
- .ok_or_else(|| format!("[signal_store] no parent dir for {}", path.display()))?;
-
- let mut temp = tempfile::NamedTempFile::new_in(parent)
- .map_err(|e| format!("[signal_store] temp file in {}: {e}", parent.display()))?;
-
- temp.write_all(encrypted.as_bytes())
- .map_err(|e| format!("[signal_store] write temp for {}: {e}", path.display()))?;
-
- temp.as_file()
- .sync_all()
- .map_err(|e| format!("[signal_store] sync temp for {}: {e}", path.display()))?;
-
- temp.persist(path)
- .map_err(|e| format!("[signal_store] persist {}: {}", path.display(), e.error))?;
-
- Ok(())
- }
-
- /// Read `path`, decrypt via `SecretStore`, and return the JSON plaintext.
- ///
- /// Returns `Ok(None)` when the file does not exist (expected for cold starts
- /// and after removals). Returns `Err` for any other I/O or decryption error.
- fn read_and_decrypt(&self, path: &Path) -> std::result::Result<Option<String>, String> {
- match std::fs::read_to_string(path) {
- Ok(contents) => {
- let plaintext = self.secret_store.decrypt(&contents).map_err(|e| {
- format!("[signal_store] decrypt failed for {}: {e}", path.display())
- })?;
- Ok(Some(plaintext))
- }
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
- Err(e) => Err(format!(
- "[signal_store] read failed for {}: {e}",
- path.display()
- )),
- }
- }
-
- // ── Cache warming ─────────────────────────────────────────────────────────
-
- /// Load all existing encrypted files from disk into the in-memory cache.
- ///
- /// Called once at construction time. Corrupt or unreadable files are logged
- /// and skipped — the store remains usable for all other keys.
- async fn warm_cache(&self) -> std::result::Result<(), String> {
- let mut cache = self.cache.lock().await;
- if cache.warm {
- return Ok(());
- }
-
- // 1. Load the active signed pre-key ID.
- let active_path = self.dir.join("active_signed_pre_key.enc");
- if let Some(active_id) = self.read_and_decrypt(&active_path)? {
- cache.active_signed_pre_key_id = Some(active_id.trim().to_string());
- }
-
- // 2. Load all signed pre-keys.
- let spk_dir = self.dir.join("signed_pre_keys");
- if spk_dir.exists() {
- for entry in std::fs::read_dir(&spk_dir)
- .map_err(|e| format!("[signal_store] read signed_pre_keys dir: {e}"))?
- {
- let entry =
- entry.map_err(|e| format!("[signal_store] read signed_pre_keys entry: {e}"))?;
- let path = entry.path();
- if path.extension().and_then(|e| e.to_str()) == Some("enc") {
- match self.read_and_decrypt(&path) {
- Ok(Some(json)) => match serde_json::from_str::<SerializablePreKey>(&json) {
- Ok(spk) => {
- let pk = from_serializable_pre_key(spk);
- cache.signed_pre_keys.insert(pk.key_id.clone(), pk);
- }
- Err(e) => log::warn!(
- "[signal_store] skipping corrupt signed pre-key {}: {e}",
- path.display()
- ),
- },
- Ok(None) => {
- // File disappeared between readdir and read — harmless.
- }
- Err(e) => log::warn!(
- "[signal_store] skipping unreadable signed pre-key {}: {e}",
- path.display()
- ),
- }
- }
- }
- }
-
- // 3. Load all one-time pre-keys.
- let pk_dir = self.dir.join("pre_keys");
- if pk_dir.exists() {
- for entry in std::fs::read_dir(&pk_dir)
- .map_err(|e| format!("[signal_store] read pre_keys dir: {e}"))?
- {
- let entry =
- entry.map_err(|e| format!("[signal_store] read pre_keys entry: {e}"))?;
- let path = entry.path();
- if path.extension().and_then(|e| e.to_str()) == Some("enc") {
- match self.read_and_decrypt(&path) {
- Ok(Some(json)) => match serde_json::from_str::<SerializablePreKey>(&json) {
- Ok(pk_s) => {
- let pk = from_serializable_pre_key(pk_s);
- cache.pre_keys.insert(pk.key_id.clone(), pk);
- }
- Err(e) => log::warn!(
- "[signal_store] skipping corrupt pre-key {}: {e}",
- path.display()
- ),
- },
- Ok(None) => {}
- Err(e) => log::warn!(
- "[signal_store] skipping unreadable pre-key {}: {e}",
- path.display()
- ),
- }
- }
- }
- }
-
- // 4. Load all sessions.
- let sess_dir = self.dir.join("sessions");
- if sess_dir.exists() {
- for entry in std::fs::read_dir(&sess_dir)
- .map_err(|e| format!("[signal_store] read sessions dir: {e}"))?
- {
- let entry =
- entry.map_err(|e| format!("[signal_store] read sessions entry: {e}"))?;
- let path = entry.path();
- if path.extension().and_then(|e| e.to_str()) == Some("enc") {
- match self.read_and_decrypt(&path) {
- Ok(Some(json)) => {
- match serde_json::from_str::<SerializableSession>(&json) {
- Ok(s) => {
- // Reconstruct the address from the filename stem.
- if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
- cache
- .sessions
- .insert(stem.to_string(), from_serializable_session(s));
- }
- }
- Err(e) => log::warn!(
- "[signal_store] skipping corrupt session {}: {e}",
- path.display()
- ),
- }
- }
- Ok(None) => {}
- Err(e) => log::warn!(
- "[signal_store] skipping unreadable session {}: {e}",
- path.display()
- ),
- }
- }
- }
- }
-
- cache.warm = true;
- log::info!(
- "[signal_store] cache warmed: {} signed_pre_keys, {} pre_keys, {} sessions, \
- active_spk={}",
- cache.signed_pre_keys.len(),
- cache.pre_keys.len(),
- cache.sessions.len(),
- cache.active_signed_pre_key_id.is_some(),
- );
- Ok(())
- }
-}
-
-// ── SessionStore trait implementation ─────────────────────────────────────────
-
-#[async_trait]
-impl SessionStore for FileSessionStore {
- /// Return the identity X25519 key pair derived from the wallet seed.
- ///
- /// The private key is held in memory only and is never persisted to disk.
- async fn identity_x25519_key_pair(&self) -> Result<X25519KeyPair> {
- log::debug!("[signal_store] identity_x25519_key_pair (key not logged)");
- Ok(self.identity.clone())
- }
-
- async fn signed_pre_key(&self, key_id: &str) -> Result<Option<SignedPreKeyPair>> {
- let cache = self.cache.lock().await;
- Ok(cache.signed_pre_keys.get(key_id).cloned())
- }
-
- async fn active_signed_pre_key(&self) -> Result<SignedPreKeyPair> {
- let cache = self.cache.lock().await;
- let key_id = cache
- .active_signed_pre_key_id
- .as_ref()
- .ok_or_else(|| Error::InvalidArgument("No active signed pre-key".into()))?;
- cache
- .signed_pre_keys
- .get(key_id)
- .cloned()
- .ok_or_else(|| Error::InvalidArgument("Active signed pre-key not found".into()))
- }
-
- /// Store a signed pre-key and mark it as the active signed pre-key.
- ///
- /// Mirrors [`tinyplace::signal::memory_store::MemorySessionStore::store_signed_pre_key`]
- /// exactly: storing a signed pre-key always sets it as the active one.
- ///
- /// Disk writes happen **before** the cache update so that a crash leaves
- /// the cache stale but never loses data (the old active key remains valid
- /// on disk and will be loaded correctly on restart).
- async fn store_signed_pre_key(&self, pre_key: SignedPreKeyPair) -> Result<()> {
- let key_id = pre_key.key_id.clone();
- let json = serde_json::to_string(&to_serializable_pre_key(&pre_key)).map_err(|e| {
- Error::InvalidArgument(format!("[signal_store] serialize signed pre-key: {e}"))
- })?;
-
- let path = self
- .dir
- .join("signed_pre_keys")
- .join(format!("{}.enc", sanitize(&key_id)));
- self.encrypt_and_write(&path, &json)
- .map_err(Error::InvalidArgument)?;
-
- // Also persist the active signed pre-key ID.
- let active_path = self.dir.join("active_signed_pre_key.enc");
- self.encrypt_and_write(&active_path, &key_id)
- .map_err(Error::InvalidArgument)?;
-
- let mut cache = self.cache.lock().await;
- cache.signed_pre_keys.insert(key_id.clone(), pre_key);
- cache.active_signed_pre_key_id = Some(key_id);
- log::debug!("[signal_store] stored signed pre-key (id not logged for safety)");
- Ok(())
- }
-
- async fn pre_key(&self, key_id: &str) -> Result<Option<PreKeyPair>> {
- let cache = self.cache.lock().await;
- Ok(cache.pre_keys.get(key_id).cloned())
- }
-
- async fn remove_pre_key(&self, key_id: &str) -> Result<()> {
- let path = self
- .dir
- .join("pre_keys")
- .join(format!("{}.enc", sanitize(key_id)));
- if path.exists() {
- std::fs::remove_file(&path).map_err(|e| {
- Error::InvalidArgument(format!("[signal_store] remove pre-key file: {e}"))
- })?;
- }
- let mut cache = self.cache.lock().await;
- cache.pre_keys.remove(key_id);
- log::debug!("[signal_store] removed pre-key key_id={key_id}");
- Ok(())
- }
-
- async fn store_pre_key(&self, pre_key: PreKeyPair) -> Result<()> {
- let key_id = pre_key.key_id.clone();
- let json = serde_json::to_string(&to_serializable_pre_key(&pre_key)).map_err(|e| {
- Error::InvalidArgument(format!("[signal_store] serialize pre-key: {e}"))
- })?;
-
- let path = self
- .dir
- .join("pre_keys")
- .join(format!("{}.enc", sanitize(&key_id)));
- self.encrypt_and_write(&path, &json)
- .map_err(Error::InvalidArgument)?;
-
- let mut cache = self.cache.lock().await;
- cache.pre_keys.insert(key_id, pre_key);
- log::debug!("[signal_store] stored pre-key");
- Ok(())
- }
-
- async fn all_pre_keys(&self) -> Result<Vec<PreKeyPair>> {
- let cache = self.cache.lock().await;
- Ok(cache.pre_keys.values().cloned().collect())
- }
-
- async fn session(&self, address: &str) -> Result<Option<SessionState>> {
- let cache = self.cache.lock().await;
- Ok(cache.sessions.get(address).cloned())
- }
-
- async fn store_session(&self, address: &str, session: SessionState) -> Result<()> {
- let json = serde_json::to_string(&to_serializable_session(&session)).map_err(|e| {
- Error::InvalidArgument(format!("[signal_store] serialize session: {e}"))
- })?;
-
- let path = self
- .dir
- .join("sessions")
- .join(format!("{}.enc", sanitize(address)));
- self.encrypt_and_write(&path, &json)
- .map_err(Error::InvalidArgument)?;
-
- let mut cache = self.cache.lock().await;
- cache.sessions.insert(address.to_string(), session);
- log::debug!("[signal_store] stored session for address (not logged)");
- Ok(())
- }
-
- async fn remove_session(&self, address: &str) -> Result<()> {
- let path = self
- .dir
- .join("sessions")
- .join(format!("{}.enc", sanitize(address)));
- if path.exists() {
- std::fs::remove_file(&path).map_err(|e| {
- Error::InvalidArgument(format!("[signal_store] remove session file: {e}"))
- })?;
- }
- let mut cache = self.cache.lock().await;
- cache.sessions.remove(address);
- log::debug!("[signal_store] removed session for address (not logged)");
- Ok(())
- }
-}
-
-// ── Process-global accessor ───────────────────────────────────────────────────
-
-/// Process-global [`FileSessionStore`] instance, stored as `Arc` so it can be
-/// shared with [`tinyplace::signal::session::SignalSession::new`] which takes
-/// `Arc<dyn SessionStore>`.
-///
-/// Built lazily on first call to [`global_signal_store`] or
-/// [`global_signal_store_arc`]. Uses [`tokio::sync::OnceCell`] because
-/// initialisation is async.
-static SIGNAL_STORE: OnceCell<Arc<FileSessionStore>> = OnceCell::const_new();
-
-/// Shared initialisation — builds the `FileSessionStore` and wraps it in an
-/// `Arc`. Called by both `global_signal_store` and `global_signal_store_arc`.
-async fn init_signal_store() -> std::result::Result<Arc<FileSessionStore>, String> {
- log::debug!("[signal_store] initializing global signal store");
-
- // 1. Derive the identity key from the wallet seed.
- // The seed is never logged or persisted.
- let seed = crate::openhuman::web3::wallet::tinyplace_signer_seed().await?;
- let identity = ed25519_seed_to_x25519_keypair(&seed);
- log::debug!("[signal_store] identity key derived (key not logged)");
-
- // 2. Resolve workspace_dir from config.
- let config = crate::openhuman::config::rpc::load_config_with_timeout().await?;
- let store_dir = config.workspace_dir.join("tinyplace").join("signal");
-
- // 3. Build a SecretStore backed by the same keychain master key that
- // protects wallet credentials. The `openhuman_dir` is the parent
- // of `config_path` (e.g. `~/.openhuman/users/<id>/`).
- let openhuman_dir = config
- .config_path
- .parent()
- .map(PathBuf::from)
- .unwrap_or_else(|| PathBuf::from("."));
- let secret_store = SecretStore::new(&openhuman_dir, true);
-
- // 4. Construct and wrap in Arc (warms the cache).
- let store = FileSessionStore::new(identity, store_dir, secret_store).await?;
- Ok(Arc::new(store))
-}
-
-/// Return a `&'static`-deref reference to the process-global [`FileSessionStore`],
-/// building it on first access.
-///
-/// Requires:
-/// 1. The wallet to be unlocked (for `tinyplace_signer_seed()`).
-/// 2. The config to be loaded (for `workspace_dir` and `SecretStore`).
-///
-/// Returns `Err` if the wallet is locked, the keychain is unavailable, or the
-/// workspace directory cannot be created. There is **no plaintext fallback** —
-/// if encryption is unavailable the store fails loudly.
-pub(crate) async fn global_signal_store() -> std::result::Result<&'static FileSessionStore, String>
-{
- SIGNAL_STORE
- .get_or_try_init(|| async { init_signal_store().await })
- .await
- .map(|arc| arc.as_ref())
-}
-
-/// Return an `Arc`-wrapped handle to the process-global [`FileSessionStore`],
-/// for use with [`tinyplace::signal::session::SignalSession::new`] which requires
-/// `Arc<dyn SessionStore>`.
-///
-/// Clones the `Arc` from `SIGNAL_STORE` (cheap — one atomic increment).
-/// All existing callers of `global_signal_store()` are unaffected.
-pub(crate) async fn global_signal_store_arc() -> std::result::Result<Arc<FileSessionStore>, String>
-{
- SIGNAL_STORE
- .get_or_try_init(|| async { init_signal_store().await })
- .await
- .map(Arc::clone)
-}
-
-// ── Tests ─────────────────────────────────────────────────────────────────────
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use tinyplace::signal::crypto::generate_x25519_keypair;
-
- // ── Test helpers ──────────────────────────────────────────────────────────
-
- /// Build an isolated [`FileSessionStore`] in a temporary directory.
- ///
- /// `SecretStore::new(dir, true)` uses the file-backend key in `cfg(test)`,
- /// so no OS keychain is needed in tests.
- async fn test_store() -> (FileSessionStore, tempfile::TempDir) {
- let dir = tempfile::tempdir().unwrap();
- let secret_store = SecretStore::new(dir.path(), true);
- let seed = [42u8; 32];
- let identity = ed25519_seed_to_x25519_keypair(&seed);
- let store = FileSessionStore::new(identity, dir.path().join("signal"), secret_store)
- .await
- .unwrap();
- (store, dir)
- }
-
- fn test_pre_key(key_id: &str) -> PreKeyPair {
- PreKeyPair {
- key_id: key_id.to_string(),
- key_pair: generate_x25519_keypair(),
- signature: vec![1, 2, 3, 4, 5],
- }
- }
-
- fn test_session() -> SessionState {
- let mut skipped_keys = HashMap::new();
- skipped_keys.insert("abcdef:1".to_string(), [99u8; 32]);
- SessionState {
- dh_send_key_pair: generate_x25519_keypair(),
- dh_recv_public_key: Some([7u8; 32]),
- root_key: [42u8; 32],
- send_chain_key: Some([11u8; 32]),
- recv_chain_key: Some([22u8; 32]),
- send_message_number: 5,
- recv_message_number: 3,
- previous_chain_length: 2,
- skipped_keys,
- }
- }
-
- // ── Test 1: round_trip_pre_key ────────────────────────────────────────────
-
- /// Store a pre-key and retrieve it; verify all fields survive the
- /// serialize → encrypt → write → read → decrypt → deserialize round trip.
- #[tokio::test]
- async fn round_trip_pre_key() {
- let (store, _dir) = test_store().await;
- let pk = test_pre_key("pk_42");
- store.store_pre_key(pk.clone()).await.unwrap();
- let loaded = store.pre_key("pk_42").await.unwrap().expect("should exist");
- assert_eq!(loaded.key_id, "pk_42");
- assert_eq!(loaded.key_pair.public_key, pk.key_pair.public_key);
- assert_eq!(loaded.key_pair.private_key, pk.key_pair.private_key);
- assert_eq!(loaded.signature, pk.signature);
- }
-
- // ── Test 2: round_trip_session ────────────────────────────────────────────
-
- /// Store a session and retrieve it; verify all fields including skipped_keys,
- /// dh_recv_public_key, and chain keys.
- #[tokio::test]
- async fn round_trip_session() {
- let (store, _dir) = test_store().await;
- let session = test_session();
- store
- .store_session("peer_abc", session.clone())
- .await
- .unwrap();
- let loaded = store
- .session("peer_abc")
- .await
- .unwrap()
- .expect("should exist");
- assert_eq!(loaded.root_key, session.root_key);
- assert_eq!(loaded.send_message_number, session.send_message_number);
- assert_eq!(loaded.recv_message_number, session.recv_message_number);
- assert_eq!(loaded.previous_chain_length, session.previous_chain_length);
- assert_eq!(
- loaded.dh_send_key_pair.private_key,
- session.dh_send_key_pair.private_key
- );
- assert_eq!(
- loaded.dh_send_key_pair.public_key,
- session.dh_send_key_pair.public_key
- );
- assert_eq!(loaded.dh_recv_public_key, session.dh_recv_public_key);
- assert_eq!(loaded.send_chain_key, session.send_chain_key);
- assert_eq!(loaded.recv_chain_key, session.recv_chain_key);
- assert_eq!(loaded.skipped_keys.len(), session.skipped_keys.len());
- assert_eq!(
- loaded.skipped_keys.get("abcdef:1"),
- session.skipped_keys.get("abcdef:1")
- );
- }
-
- // ── Test 3: remove_pre_key_deletes ────────────────────────────────────────
-
- /// After removing a pre-key, `pre_key()` returns `None` and the `.enc`
- /// file is gone from disk.
- #[tokio::test]
- async fn remove_pre_key_deletes() {
- let (store, dir) = test_store().await;
- store.store_pre_key(test_pre_key("pk_del")).await.unwrap();
- // Verify it exists.
- assert!(store.pre_key("pk_del").await.unwrap().is_some());
- let enc_path = dir.path().join("signal/pre_keys/pk_del.enc");
- assert!(enc_path.exists(), "enc file should exist before remove");
- // Remove it.
- store.remove_pre_key("pk_del").await.unwrap();
- assert!(store.pre_key("pk_del").await.unwrap().is_none());
- assert!(!enc_path.exists(), "enc file should be gone after remove");
- }
-
- // ── Test 4: remove_session_deletes ────────────────────────────────────────
-
- /// After removing a session, `session()` returns `None` and the file is gone.
- #[tokio::test]
- async fn remove_session_deletes() {
- let (store, dir) = test_store().await;
- store
- .store_session("peer_del", test_session())
- .await
- .unwrap();
- assert!(store.session("peer_del").await.unwrap().is_some());
- let enc_path = dir.path().join("signal/sessions/peer_del.enc");
- assert!(enc_path.exists());
- store.remove_session("peer_del").await.unwrap();
- assert!(store.session("peer_del").await.unwrap().is_none());
- assert!(!enc_path.exists());
- }
-
- // ── Test 5: all_pre_keys_returns_all ─────────────────────────────────────
-
- /// Store 5 pre-keys; `all_pre_keys()` must return exactly those 5.
- #[tokio::test]
- async fn all_pre_keys_returns_all() {
- let (store, _dir) = test_store().await;
- for i in 0..5u32 {
- store
- .store_pre_key(test_pre_key(&format!("pk_{i}")))
- .await
- .unwrap();
- }
- let all = store.all_pre_keys().await.unwrap();
- assert_eq!(all.len(), 5);
- let ids: std::collections::HashSet<_> = all.iter().map(|pk| pk.key_id.as_str()).collect();
- for i in 0..5u32 {
- assert!(ids.contains(format!("pk_{i}").as_str()), "missing pk_{i}");
- }
- }
-
- // ── Test 6: signed_pre_key_sets_active ───────────────────────────────────
-
- /// Storing a signed pre-key sets it as active; storing a second one
- /// replaces the active reference.
- #[tokio::test]
- async fn signed_pre_key_sets_active() {
- let (store, _dir) = test_store().await;
- let spk1 = test_pre_key("spk_1");
- store.store_signed_pre_key(spk1.clone()).await.unwrap();
- let active = store.active_signed_pre_key().await.unwrap();
- assert_eq!(active.key_id, "spk_1");
- assert_eq!(active.key_pair.public_key, spk1.key_pair.public_key);
-
- let spk2 = test_pre_key("spk_2");
- store.store_signed_pre_key(spk2.clone()).await.unwrap();
- let active2 = store.active_signed_pre_key().await.unwrap();
- assert_eq!(active2.key_id, "spk_2");
- assert_eq!(active2.key_pair.public_key, spk2.key_pair.public_key);
-
- // Both SPKs are still retrievable by ID.
- assert!(store.signed_pre_key("spk_1").await.unwrap().is_some());
- assert!(store.signed_pre_key("spk_2").await.unwrap().is_some());
- }
-
- // ── Test 7: active_signed_pre_key_errors_when_none ───────────────────────
-
- /// On a fresh store with no signed pre-keys, `active_signed_pre_key()`
- /// returns `Err` containing "No active signed pre-key".
- #[tokio::test]
- async fn active_signed_pre_key_errors_when_none() {
- let (store, _dir) = test_store().await;
- let err = store.active_signed_pre_key().await.unwrap_err();
- let msg = err.to_string();
- assert!(
- msg.contains("No active signed pre-key"),
- "unexpected error: {msg}"
- );
- }
-
- // ── Test 8: identity_key_deterministic_from_seed ─────────────────────────
-
- /// Two stores built from the same seed must return identical identity key pairs
- /// (both public and private components).
- #[tokio::test]
- async fn identity_key_deterministic_from_seed() {
- let dir1 = tempfile::tempdir().unwrap();
- let dir2 = tempfile::tempdir().unwrap();
- let seed = [77u8; 32];
- let ss1 = SecretStore::new(dir1.path(), true);
- let ss2 = SecretStore::new(dir2.path(), true);
-
- let store1 = FileSessionStore::new(
- ed25519_seed_to_x25519_keypair(&seed),
- dir1.path().join("signal"),
- ss1,
- )
- .await
- .unwrap();
- let store2 = FileSessionStore::new(
- ed25519_seed_to_x25519_keypair(&seed),
- dir2.path().join("signal"),
- ss2,
- )
- .await
- .unwrap();
-
- let kp1 = store1.identity_x25519_key_pair().await.unwrap();
- let kp2 = store2.identity_x25519_key_pair().await.unwrap();
- assert_eq!(kp1.public_key, kp2.public_key, "public keys must match");
- assert_eq!(kp1.private_key, kp2.private_key, "private keys must match");
- }
-
- // ── Test 9: identity_key_differs_for_different_seeds ─────────────────────
-
- /// Two stores built from different seeds must produce different identity keys.
- #[tokio::test]
- async fn identity_key_differs_for_different_seeds() {
- let dir1 = tempfile::tempdir().unwrap();
- let dir2 = tempfile::tempdir().unwrap();
- let seed_a = [10u8; 32];
- let seed_b = [20u8; 32];
-
- let store_a = FileSessionStore::new(
- ed25519_seed_to_x25519_keypair(&seed_a),
- dir1.path().join("signal"),
- SecretStore::new(dir1.path(), true),
- )
- .await
- .unwrap();
-
- let store_b = FileSessionStore::new(
- ed25519_seed_to_x25519_keypair(&seed_b),
- dir2.path().join("signal"),
- SecretStore::new(dir2.path(), true),
- )
- .await
- .unwrap();
-
- let kp_a = store_a.identity_x25519_key_pair().await.unwrap();
- let kp_b = store_b.identity_x25519_key_pair().await.unwrap();
- assert_ne!(kp_a.public_key, kp_b.public_key, "public keys must differ");
- assert_ne!(
- kp_a.private_key, kp_b.private_key,
- "private keys must differ"
- );
- }
-
- // ── Test 10: encrypted_at_rest_verification ───────────────────────────────
-
- /// SECURITY TEST: after storing a pre-key, the raw `.enc` file on disk must:
- /// - Start with `"enc2:"` (ChaCha20-Poly1305 ciphertext, NOT plaintext JSON).
- /// - Not be valid JSON (i.e. `serde_json::from_str` fails).
- /// - Not contain the hex-encoded private key bytes (defence-in-depth).
- #[tokio::test]
- async fn encrypted_at_rest_verification() {
- let (store, dir) = test_store().await;
- let pk = test_pre_key("pk_enc_check");
- store.store_pre_key(pk.clone()).await.unwrap();
-
- let enc_path = dir.path().join("signal/pre_keys/pk_enc_check.enc");
- let raw = std::fs::read_to_string(&enc_path).expect("enc file must exist");
-
- // Must start with the enc2: prefix.
- assert!(
- raw.starts_with("enc2:"),
- "raw file must be enc2: ciphertext, got: {raw:.80}"
- );
-
- // Must NOT be parseable as JSON (it's hex-encoded ciphertext).
- let json_result = serde_json::from_str::<serde_json::Value>(&raw);
- assert!(
- json_result.is_err(),
- "raw file must NOT be valid JSON (got unexpected Ok)"
- );
-
- // Must NOT contain the hex-encoded private key bytes.
- let private_key_hex = hex_encode(&pk.key_pair.private_key);
- assert!(
- !raw.contains(&private_key_hex),
- "raw file must not contain hex-encoded private key bytes"
- );
- }
-
- // ── Test 11: restart_survival ─────────────────────────────────────────────
-
- /// Data written by one store instance must be readable by a new instance
- /// constructed against the same directory (simulates app restart).
- #[tokio::test]
- async fn restart_survival() {
- let dir = tempfile::tempdir().unwrap();
- let seed = [42u8; 32];
-
- // First store instance: write data.
- {
- let secret_store = SecretStore::new(dir.path(), true);
- let store = FileSessionStore::new(
- ed25519_seed_to_x25519_keypair(&seed),
- dir.path().join("signal"),
- secret_store,
- )
- .await
- .unwrap();
- store
- .store_pre_key(test_pre_key("pk_restart"))
- .await
- .unwrap();
- store
- .store_session("peer_restart", test_session())
- .await
- .unwrap();
- }
- // store is dropped here.
-
- // Second store instance: read data back.
- let secret_store2 = SecretStore::new(dir.path(), true);
- let store2 = FileSessionStore::new(
- ed25519_seed_to_x25519_keypair(&seed),
- dir.path().join("signal"),
- secret_store2,
- )
- .await
- .unwrap();
-
- let pk = store2.pre_key("pk_restart").await.unwrap();
- assert!(pk.is_some(), "pre-key must survive restart");
- assert_eq!(pk.unwrap().key_id, "pk_restart");
-
- let sess = store2.session("peer_restart").await.unwrap();
- assert!(sess.is_some(), "session must survive restart");
- assert_eq!(sess.unwrap().root_key, [42u8; 32]);
- }
-
- // ── Test 12: corrupt_file_logs_warning_and_skips ─────────────────────────
-
- /// A corrupt `.enc` file in a category directory must not prevent store
- /// construction. The corrupt entry is skipped; all other entries load
- /// correctly.
- #[tokio::test]
- async fn corrupt_file_logs_warning_and_skips() {
- let dir = tempfile::tempdir().unwrap();
- let signal_dir = dir.path().join("signal");
- // Create the directory tree manually.
- std::fs::create_dir_all(signal_dir.join("pre_keys")).unwrap();
- std::fs::create_dir_all(signal_dir.join("signed_pre_keys")).unwrap();
- std::fs::create_dir_all(signal_dir.join("sessions")).unwrap();
-
- // Write garbage into a pre_key slot.
- std::fs::write(signal_dir.join("pre_keys/corrupt.enc"), b"not-enc2-garbage").unwrap();
-
- // Also write a valid pre-key to ensure the store loads what it can.
- let seed = [42u8; 32];
- let secret_store_pre = SecretStore::new(dir.path(), true);
- {
- let store = FileSessionStore::new(
- ed25519_seed_to_x25519_keypair(&seed),
- signal_dir.clone(),
- secret_store_pre,
- )
- .await
- .unwrap();
- // This store was built against the corrupt file — it should succeed.
- // It won't have the corrupt entry in the cache.
- let all = store.all_pre_keys().await.unwrap();
- assert!(
- all.iter().all(|pk| pk.key_id != "corrupt"),
- "corrupt entry must be absent from cache"
- );
- }
-
- // Write a valid pre-key now, then re-open to confirm the corrupt file
- // is still skipped while the valid one loads.
- let secret_store2 = SecretStore::new(dir.path(), true);
- {
- let store = FileSessionStore::new(
- ed25519_seed_to_x25519_keypair(&seed),
- signal_dir.clone(),
- secret_store2.clone(),
- )
- .await
- .unwrap();
- store.store_pre_key(test_pre_key("pk_valid")).await.unwrap();
- }
-
- let secret_store3 = SecretStore::new(dir.path(), true);
- let store3 = FileSessionStore::new(
- ed25519_seed_to_x25519_keypair(&seed),
- signal_dir,
- secret_store3,
- )
- .await
- .unwrap();
-
- let all = store3.all_pre_keys().await.unwrap();
- let ids: Vec<_> = all.iter().map(|pk| pk.key_id.as_str()).collect();
- assert!(ids.contains(&"pk_valid"), "valid key must load");
- assert!(!ids.contains(&"corrupt"), "corrupt key must be skipped");
- }
-
- // ── Test 13: session_not_found_returns_none ───────────────────────────────
-
- /// On a fresh store, `session("nonexistent")` returns `Ok(None)`.
- #[tokio::test]
- async fn session_not_found_returns_none() {
- let (store, _dir) = test_store().await;
- let result = store.session("nonexistent").await.unwrap();
- assert!(result.is_none());
- }
-
- // ── Test 14: pre_key_not_found_returns_none ───────────────────────────────
-
- /// On a fresh store, `pre_key("nonexistent")` returns `Ok(None)`.
- #[tokio::test]
- async fn pre_key_not_found_returns_none() {
- let (store, _dir) = test_store().await;
- let result = store.pre_key("nonexistent").await.unwrap();
- assert!(result.is_none());
- }
-
- // ── Internal helper ───────────────────────────────────────────────────────
-
- /// Hex-encode bytes for use in the encrypted-at-rest assertion.
- fn hex_encode(bytes: &[u8]) -> String {
- bytes.iter().map(|b| format!("{b:02x}")).collect()
- }
-}
diff --git a/src/openhuman/tinyplace/state.rs b/src/openhuman/tinyplace/state.rs
deleted file mode 100644
index af29d87a18..0000000000
--- a/src/openhuman/tinyplace/state.rs
+++ /dev/null
@@ -1,155 +0,0 @@
-//! Shared client state for the tiny.place domain.
-//!
-//! [`TinyPlaceState`] holds a lazily-initialised [`tinyplace::TinyPlaceClient`].
-//! The client cannot be built at startup because the signer seed requires an
-//! async decrypt of the wallet's encrypted mnemonic and the wallet may be
-//! locked at launch time. We build it once on first access and cache it.
-//!
-//! The state is stored in a process-global `OnceLock` (see [`global_state`])
-//! because controller handlers are `fn(Map<String,Value>) -> ControllerFuture`
-//! with no injected state argument.
-
-use std::sync::Arc;
-
-use tokio::sync::OnceCell;
-
-use tinyplace::{LocalSigner, TinyPlaceClient, TinyPlaceClientOptions};
-
-const LOG_PREFIX: &str = "[tinyplace]";
-
-/// Production tiny.place relay/API host — the default outside a staging build.
-const TINYPLACE_PROD_BASE_URL: &str = "https://api.tiny.place";
-/// Staging tiny.place relay/API host — the default when the OpenHuman app env
-/// is `staging` and no explicit `TINYPLACE_API_BASE_URL` is set.
-const TINYPLACE_STAGING_BASE_URL: &str = "https://staging-api.tiny.place";
-
-/// Shared tiny.place state: lazy-built client keyed to one base URL.
-pub(crate) struct TinyPlaceState {
- /// Lazily initialised on first [`TinyPlaceState::client`] call.
- client: OnceCell<TinyPlaceClient>,
- /// Backend base URL (from `TINYPLACE_API_BASE_URL`, else app-env default).
- pub(crate) base_url: String,
-}
-
-impl TinyPlaceState {
- /// Build from the environment.
- ///
- /// Base URL precedence: an explicit `TINYPLACE_API_BASE_URL` always wins;
- /// otherwise the default follows the OpenHuman app environment so a staging
- /// build talks to staging tiny.place and a production build talks to prod
- /// (previously the default was hardcoded to prod regardless of app env,
- /// which silently 404'd a staging instance against prod tiny.place).
- pub(crate) fn from_env() -> Self {
- let explicit = std::env::var("TINYPLACE_API_BASE_URL").ok();
- let app_env = crate::api::config::app_env_from_env();
- let base_url = resolve_base_url(explicit.as_deref(), app_env.as_deref());
- log::debug!(
- "{LOG_PREFIX} state created base_url={base_url} app_env={}",
- app_env.as_deref().unwrap_or("<unset>")
- );
- Self {
- client: OnceCell::new(),
- base_url,
- }
- }
-
- /// Return (or lazily build) the shared [`TinyPlaceClient`].
- ///
- /// On first call: derives the signer seed from the wallet, constructs the
- /// client, and caches it. Subsequent calls return the cached instance.
- ///
- /// Returns `Err` if the wallet is locked/unconfigured or the seed derivation
- /// fails — the renderer should surface an "unlock wallet" prompt.
- pub(crate) async fn client(&self) -> Result<&TinyPlaceClient, String> {
- self.client
- .get_or_try_init(|| async {
- log::debug!("{LOG_PREFIX} building client base_url={}", self.base_url);
- // Derive 32-byte Ed25519 seed from the user's Solana wallet key.
- // The seed is consumed immediately; never logged or persisted.
- let seed = crate::openhuman::web3::wallet::tinyplace_signer_seed().await?;
- let signer: Arc<dyn tinyplace::Signer> = Arc::new(
- LocalSigner::from_seed(&seed)
- .map_err(|e| format!("tinyplace signer init: {e}"))?,
- );
- log::debug!("{LOG_PREFIX} signer ready agent_id={}", signer.agent_id());
- Ok::<TinyPlaceClient, String>(TinyPlaceClient::new(TinyPlaceClientOptions {
- base_url: self.base_url.clone(),
- signer: Some(signer),
- ..Default::default()
- }))
- })
- .await
- }
-}
-
-/// Resolve the tiny.place base URL from an explicit override + app env.
-///
-/// A non-blank explicit value (from `TINYPLACE_API_BASE_URL`) always wins.
-/// Blank/whitespace is treated as unset (mirrors `wallet::defaults` handling)
-/// so it can't produce an invalid base URL. With no explicit override, the
-/// default tracks the app environment: staging → staging host, else prod.
-fn resolve_base_url(explicit: Option<&str>, app_env: Option<&str>) -> String {
- if let Some(url) = explicit.map(str::trim).filter(|value| !value.is_empty()) {
- return url.to_string();
- }
- default_base_url_for_app_env(app_env).to_string()
-}
-
-/// The tiny.place host to default to for a given OpenHuman app environment.
-fn default_base_url_for_app_env(app_env: Option<&str>) -> &'static str {
- if crate::api::config::is_staging_app_env(app_env) {
- TINYPLACE_STAGING_BASE_URL
- } else {
- TINYPLACE_PROD_BASE_URL
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn explicit_override_always_wins() {
- // Even a staging app env must not override an explicit URL.
- assert_eq!(
- resolve_base_url(Some("https://custom.example"), Some("staging")),
- "https://custom.example"
- );
- assert_eq!(
- resolve_base_url(Some(" https://trimmed.example "), None),
- "https://trimmed.example"
- );
- }
-
- #[test]
- fn blank_override_falls_through_to_app_env_default() {
- // Blank/whitespace is treated as unset.
- assert_eq!(
- resolve_base_url(Some(" "), Some("staging")),
- TINYPLACE_STAGING_BASE_URL
- );
- assert_eq!(resolve_base_url(Some(""), None), TINYPLACE_PROD_BASE_URL);
- }
-
- #[test]
- fn default_follows_app_env() {
- assert_eq!(
- default_base_url_for_app_env(Some("staging")),
- TINYPLACE_STAGING_BASE_URL
- );
- assert_eq!(
- default_base_url_for_app_env(Some("STAGING")),
- TINYPLACE_STAGING_BASE_URL
- );
- assert_eq!(
- default_base_url_for_app_env(Some("production")),
- TINYPLACE_PROD_BASE_URL
- );
- // Unknown / unset env defaults to prod.
- assert_eq!(default_base_url_for_app_env(None), TINYPLACE_PROD_BASE_URL);
- assert_eq!(
- default_base_url_for_app_env(Some("dev")),
- TINYPLACE_PROD_BASE_URL
- );
- }
-}
diff --git a/src/openhuman/tinyplace/streams.rs b/src/openhuman/tinyplace/streams.rs
deleted file mode 100644
index 3051f686ee..0000000000
--- a/src/openhuman/tinyplace/streams.rs
+++ /dev/null
@@ -1,395 +0,0 @@
-//! Tinyplace WebSocket stream manager.
-//!
-//! Holds active WebSocket connections keyed by a stream ID string. Each
-//! connection is driven by a spawned tokio task that loops `recv()` and
-//! publishes events to the global event bus.
-//!
-//! ## Lifecycle
-//!
-//! 1. Caller invokes `start_stream(kind, target_id, client)`.
-//! 2. The manager derives a stable `stream_id`, checks the cap, then spawns a
-//! `recv_loop` task that calls `ws_handle.connect().await` and loops.
-//! 3. Each message is published as `DomainEvent::TinyPlaceStreamMessage`.
-//! 4. Status transitions are published as `DomainEvent::TinyPlaceStreamStatusChanged`.
-//! 5. `stop_stream` / `stop_all` abort the spawned task and clean up the registry.
-//!
-//! **No auto-reconnect in v1.** If the WS drops the stream enters `disconnected`
-//! status and the frontend can call `start` again.
-
-use std::collections::HashMap;
-
-use tokio::sync::Mutex;
-use tokio::task::JoinHandle;
-
-use crate::core::bus::BUS;
-use crate::core::events::DomainEvent;
-
-const LOG_PREFIX: &str = "[tinyplace::streams]";
-
-/// Maximum number of concurrent tinyplace WebSocket streams.
-pub(crate) const MAX_CONCURRENT_STREAMS: usize = 5;
-
-// ── Types ─────────────────────────────────────────────────────────────────────
-
-/// Stream kinds supported in v1.
-#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub(crate) enum StreamKind {
- Inbox,
- Conversation,
- /// A single feed's live post/comment/like stream, keyed by feed handle.
- Feed,
-}
-
-/// Metadata for an active stream (returned to the renderer).
-#[derive(Debug, Clone, serde::Serialize)]
-#[serde(rename_all = "camelCase")]
-pub(crate) struct StreamEntry {
- pub stream_id: String,
- pub kind: StreamKind,
- pub status: StreamStatus,
-}
-
-/// Lifecycle status of a stream.
-#[derive(Debug, Clone, serde::Serialize)]
-#[serde(rename_all = "snake_case")]
-pub(crate) enum StreamStatus {
- Connecting,
- Connected,
- Disconnected,
- Failed,
-}
-
-impl StreamStatus {
- fn as_str(&self) -> &'static str {
- match self {
- Self::Connecting => "connecting",
- Self::Connected => "connected",
- Self::Disconnected => "disconnected",
- Self::Failed => "failed",
- }
- }
-}
-
-/// Internal handle for a running stream task.
-pub(crate) struct ActiveStream {
- pub(crate) kind: StreamKind,
- pub(crate) task: JoinHandle<()>,
- /// The original target id (e.g. conversation_id). Empty for inbox.
- #[allow(dead_code)]
- pub(crate) target_id: String,
-}
-
-// ── Stream ID helpers ─────────────────────────────────────────────────────────
-
-/// Compute the canonical stream_id for a given kind + target.
-pub(crate) fn stream_id_for(kind: StreamKind, target_id: Option<&str>) -> String {
- match kind {
- StreamKind::Inbox => "inbox".to_string(),
- StreamKind::Conversation => format!("conversation:{}", target_id.unwrap_or("")),
- StreamKind::Feed => format!("feed:{}", target_id.unwrap_or("")),
- }
-}
-
-// ── StreamManager ─────────────────────────────────────────────────────────────
-
-/// Process-global stream registry.
-pub(crate) struct StreamManager {
- pub(crate) streams: Mutex<HashMap<String, ActiveStream>>,
-}
-
-impl StreamManager {
- /// Build a new, empty manager.
- pub(crate) fn new() -> Self {
- Self {
- streams: Mutex::new(HashMap::new()),
- }
- }
-
- /// Start a WebSocket stream. Returns the stable `stream_id`.
- ///
- /// Idempotent: if the stream_id already exists, returns it immediately.
- /// Returns `Err` if the registry is at `MAX_CONCURRENT_STREAMS`.
- pub(crate) async fn start_stream(
- &self,
- kind: StreamKind,
- target_id: Option<String>,
- client: &tinyplace::TinyPlaceClient,
- ) -> Result<String, String> {
- let stream_id = stream_id_for(kind.clone(), target_id.as_deref());
-
- {
- let map = self.streams.lock().await;
- // Idempotent: already running.
- if map.contains_key(&stream_id) {
- log::debug!(
- "{LOG_PREFIX} start_stream stream_id={stream_id} already active — returning existing"
- );
- return Ok(stream_id);
- }
- // Cap check.
- if map.len() >= MAX_CONCURRENT_STREAMS {
- return Err(format!(
- "tinyplace stream cap reached ({MAX_CONCURRENT_STREAMS} concurrent streams max)"
- ));
- }
- }
-
- // Build the WebSocket handle from the SDK.
- let ws_handle = match &kind {
- StreamKind::Inbox => client.inbox.stream(),
- StreamKind::Conversation => {
- let conv_id = target_id.as_deref().unwrap_or("");
- client.conversations.stream(conv_id, None, None)
- }
- StreamKind::Feed => {
- let handle = target_id.as_deref().unwrap_or("");
- client.feeds.stream(handle, None)
- }
- };
-
- // Publish connecting status.
- let kind_str = kind_to_str(&kind);
- publish_status(&stream_id, "connecting");
-
- log::debug!(
- "{LOG_PREFIX} start_stream stream_id={stream_id} kind={kind_str} — spawning recv_loop"
- );
-
- // Spawn the recv loop.
- let task = {
- let stream_id_task = stream_id.clone();
- let kind_task = kind.clone();
- tokio::spawn(async move {
- recv_loop(ws_handle, stream_id_task, kind_task).await;
- })
- };
-
- // Register in the map.
- {
- let mut map = self.streams.lock().await;
- map.insert(
- stream_id.clone(),
- ActiveStream {
- kind,
- task,
- target_id: target_id.unwrap_or_default(),
- },
- );
- }
-
- Ok(stream_id)
- }
-
- /// Stop a stream by id. Idempotent — if not found, returns `Ok(())`.
- pub(crate) async fn stop_stream(&self, stream_id: &str) -> Result<(), String> {
- let entry = {
- let mut map = self.streams.lock().await;
- map.remove(stream_id)
- };
- match entry {
- None => {
- log::debug!("{LOG_PREFIX} stop_stream stream_id={stream_id} not found — no-op");
- Ok(())
- }
- Some(active) => {
- active.task.abort();
- publish_status(stream_id, "disconnected");
- log::debug!("{LOG_PREFIX} stop_stream stream_id={stream_id} aborted");
- Ok(())
- }
- }
- }
-
- /// Stop all active streams. Called during app shutdown.
- pub(crate) async fn stop_all(&self) {
- let mut map = self.streams.lock().await;
- for (stream_id, active) in map.drain() {
- active.task.abort();
- publish_status(&stream_id, "disconnected");
- log::debug!("{LOG_PREFIX} stop_all aborted stream_id={stream_id}");
- }
- }
-
- /// List metadata for all active streams.
- pub(crate) async fn list_streams(&self) -> Vec<StreamEntry> {
- let map = self.streams.lock().await;
- map.iter()
- .map(|(stream_id, active)| {
- let status = if active.task.is_finished() {
- StreamStatus::Disconnected
- } else {
- StreamStatus::Connected
- };
- StreamEntry {
- stream_id: stream_id.clone(),
- kind: active.kind.clone(),
- status,
- }
- })
- .collect()
- }
-}
-
-// ── Global accessor ───────────────────────────────────────────────────────────
-
-static GLOBAL_STREAM_MANAGER: std::sync::OnceLock<StreamManager> = std::sync::OnceLock::new();
-
-/// Return the process-global [`StreamManager`], lazy-initialised on first call.
-pub(crate) fn global_stream_manager() -> &'static StreamManager {
- GLOBAL_STREAM_MANAGER.get_or_init(StreamManager::new)
-}
-
-// ── Internal helpers ──────────────────────────────────────────────────────────
-
-fn kind_to_str(kind: &StreamKind) -> &'static str {
- match kind {
- StreamKind::Inbox => "inbox",
- StreamKind::Conversation => "conversation",
- StreamKind::Feed => "feed",
- }
-}
-
-fn publish_status(stream_id: &str, status: &'static str) {
- BUS.publish(DomainEvent::TinyPlaceStreamStatusChanged {
- stream_id: stream_id.to_string(),
- status: status.to_string(),
- });
-}
-
-/// The per-stream async receive loop. Connects then loops over `recv()`.
-/// Cleans itself up from the registry on exit (best-effort; `stop_stream`
-/// already handles the authoritative remove via `abort()`).
-async fn recv_loop(
- ws_handle: tinyplace::websocket::TinyPlaceWebSocket,
- stream_id: String,
- kind: StreamKind,
-) {
- let kind_str = kind_to_str(&kind).to_string();
-
- // Connect.
- log::debug!("{LOG_PREFIX} recv_loop stream_id={stream_id} connecting...");
- let mut connection = match ws_handle.connect().await {
- Ok(conn) => conn,
- Err(e) => {
- log::warn!("{LOG_PREFIX} recv_loop stream_id={stream_id} connect failed: {e}");
- publish_status(&stream_id, StreamStatus::Failed.as_str());
- // Self-remove from the registry so a new start is possible.
- if let Some(mgr) = GLOBAL_STREAM_MANAGER.get() {
- mgr.streams.lock().await.remove(&stream_id);
- }
- return;
- }
- };
-
- publish_status(&stream_id, StreamStatus::Connected.as_str());
- log::debug!("{LOG_PREFIX} recv_loop stream_id={stream_id} connected");
-
- // Message loop.
- loop {
- match connection.recv().await {
- Some(Ok(value)) => {
- log::trace!("{LOG_PREFIX} recv_loop stream_id={stream_id} message received");
- BUS.publish(DomainEvent::TinyPlaceStreamMessage {
- stream_id: stream_id.clone(),
- kind: kind_str.clone(),
- message: value,
- });
- }
- Some(Err(e)) => {
- log::warn!("{LOG_PREFIX} recv_loop stream_id={stream_id} error: {e}");
- publish_status(&stream_id, StreamStatus::Failed.as_str());
- break;
- }
- None => {
- log::debug!(
- "{LOG_PREFIX} recv_loop stream_id={stream_id} server closed connection"
- );
- publish_status(&stream_id, StreamStatus::Disconnected.as_str());
- break;
- }
- }
- }
-
- // Self-remove from the registry (best-effort; abort already removed it if
- // stop_stream was called first).
- if let Some(mgr) = GLOBAL_STREAM_MANAGER.get() {
- mgr.streams.lock().await.remove(&stream_id);
- }
-
- log::debug!("{LOG_PREFIX} recv_loop stream_id={stream_id} exited");
-}
-
-// ── Tests ─────────────────────────────────────────────────────────────────────
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[tokio::test]
- async fn stream_id_formatting() {
- assert_eq!(stream_id_for(StreamKind::Inbox, None), "inbox");
- assert_eq!(
- stream_id_for(StreamKind::Conversation, Some("abc123")),
- "conversation:abc123"
- );
- // Feed streams are keyed by feed handle (#4926).
- assert_eq!(stream_id_for(StreamKind::Feed, Some("alice")), "feed:alice");
- assert_eq!(stream_id_for(StreamKind::Feed, None), "feed:");
- }
-
- #[tokio::test]
- async fn list_streams_empty_on_init() {
- let mgr = StreamManager::new();
- let entries = mgr.list_streams().await;
- assert!(entries.is_empty());
- }
-
- #[tokio::test]
- async fn stop_nonexistent_stream_is_ok() {
- let mgr = StreamManager::new();
- let result = mgr.stop_stream("nonexistent").await;
- assert!(result.is_ok());
- }
-
- #[tokio::test]
- async fn max_concurrent_streams_enforced() {
- let mgr = StreamManager::new();
- // Simulate filling the map with dummy entries.
- {
- let mut map = mgr.streams.lock().await;
- for i in 0..MAX_CONCURRENT_STREAMS {
- map.insert(
- format!("dummy-{i}"),
- ActiveStream {
- kind: StreamKind::Inbox,
- task: tokio::spawn(async {}),
- target_id: String::new(),
- },
- );
- }
- }
- // The map is now at capacity.
- let map = mgr.streams.lock().await;
- assert_eq!(map.len(), MAX_CONCURRENT_STREAMS);
- }
-
- #[tokio::test]
- async fn stop_all_clears_registry() {
- let mgr = StreamManager::new();
- {
- let mut map = mgr.streams.lock().await;
- map.insert(
- "test-1".to_string(),
- ActiveStream {
- kind: StreamKind::Inbox,
- task: tokio::spawn(async {}),
- target_id: String::new(),
- },
- );
- }
- mgr.stop_all().await;
- let entries = mgr.list_streams().await;
- assert!(entries.is_empty());
- }
-}
diff --git a/src/openhuman/tinyplace/tests.rs b/src/openhuman/tinyplace/tests.rs
deleted file mode 100644
index c322758326..0000000000
--- a/src/openhuman/tinyplace/tests.rs
+++ /dev/null
@@ -1,715 +0,0 @@
-//! Unit tests for the tinyplace domain.
-//!
-//! `signer_round_trip`: derives the 32-byte Ed25519 seed from the same test
-//! mnemonic the wallet uses (SLIP-0010 `m/44'/501'/0'/0'`), builds a
-//! `tinyplace::LocalSigner`, and asserts `agent_id()` matches the wallet's
-//! known base58 Solana address (pinned at `wallet/chains/solana.rs:693`).
-//!
-//! `map_err_tests`: synthetic `tinyplace::Error` values map to the expected
-//! string representations.
-
-// ── Signer round-trip ─────────────────────────────────────────────────────────
-
-// Derives a key from a BIP-39 mnemonic, so it needs `coins-bip39` — which now
-// belongs to the `web3` gate.
-#[cfg(all(test, feature = "web3"))]
-mod signer_round_trip {
- use coins_bip39::{English, Mnemonic};
- use ed25519_dalek::SigningKey;
- use hmac::{Hmac, Mac};
- use sha2::Sha512;
- use tinyplace::Signer; // brings the `agent_id()` trait method into scope for `LocalSigner`
-
- /// SLIP-0010 Ed25519 child-key derivation (all-hardened path).
- /// Mirrors `wallet/chains/solana.rs:94-116`.
- fn slip10_ed25519_derive(seed: &[u8], path: &[u32]) -> [u8; 32] {
- type HmacSha512 = Hmac<Sha512>;
- let mut mac = HmacSha512::new_from_slice(b"ed25519 seed").unwrap();
- mac.update(seed);
- let i = mac.finalize().into_bytes();
- let mut key = [0u8; 32];
- let mut chain_code = [0u8; 32];
- key.copy_from_slice(&i[..32]);
- chain_code.copy_from_slice(&i[32..]);
- for index in path {
- let hardened = *index | 0x8000_0000;
- let mut mac = HmacSha512::new_from_slice(&chain_code).unwrap();
- mac.update(&[0u8]);
- mac.update(&key);
- mac.update(&hardened.to_be_bytes());
- let i = mac.finalize().into_bytes();
- key.copy_from_slice(&i[..32]);
- chain_code.copy_from_slice(&i[32..]);
- }
- key
- }
-
- /// Derive the 32-byte SLIP-0010 seed from a BIP39 mnemonic, mirroring the
- /// path taken by `wallet/chains/solana.rs:141-153`.
- fn derive_seed_bytes(mnemonic_str: &str, path_indices: &[u32]) -> [u8; 32] {
- let mnemonic: Mnemonic<English> = mnemonic_str.trim().parse().expect("valid mnemonic");
- let seed = mnemonic.to_seed(None).expect("seed derivation");
- slip10_ed25519_derive(&seed, path_indices)
- }
-
- #[test]
- fn seed_to_agent_id_matches_wallet_known_address() {
- // Generic test mnemonic (not a real wallet — safe to commit per project
- // rules: "never hardcode real names/emails in tests, use generic placeholders").
- // This is the BIP39 standard test vector "abandon×11 about".
- let mnemonic =
- "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
-
- // Derive the 32-byte secret: m/44'/501'/0'/0' (all-hardened, Solana path).
- let secret = derive_seed_bytes(
- mnemonic,
- &[
- 44 | 0x8000_0000,
- 501 | 0x8000_0000,
- 0 | 0x8000_0000,
- 0 | 0x8000_0000,
- ],
- );
-
- // Build tiny.place LocalSigner from the same bytes tinyplace_signer_seed() returns.
- let signer = tinyplace::LocalSigner::from_seed(&secret)
- .expect("LocalSigner::from_seed must succeed");
-
- // Verify the agent_id (base58 Solana address) matches the wallet's known fixture.
- // Pinned at wallet/chains/solana.rs:693.
- assert_eq!(
- signer.agent_id(),
- "HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk",
- "tiny.place agent_id must round-trip to the wallet's Solana address for the same mnemonic"
- );
-
- // Verify the dalek SigningKey produces the same public key when constructed
- // from the same 32-byte secret (belt-and-suspenders parity check).
- let dalek_key = SigningKey::from_bytes(&secret);
- let dalek_pubkey = bs58::encode(dalek_key.verifying_key().to_bytes()).into_string();
- assert_eq!(
- dalek_pubkey,
- signer.agent_id(),
- "dalek verifying_key and LocalSigner.agent_id() must agree"
- );
- }
-}
-
-// ── map_err tests ─────────────────────────────────────────────────────────────
-
-#[cfg(test)]
-mod map_err_tests {
- use crate::openhuman::tinyplace::ops::map_err;
- use tinyplace::error::{HttpError, PaymentChallenge, PaymentRequiredChallenge};
-
- #[test]
- fn http_404_maps_to_plain_string() {
- let http_err = HttpError {
- status: 404,
- message: "HTTP 404: /directory/agents/missing".to_string(),
- body: serde_json::Value::Null,
- headers: Default::default(),
- payment_required: None,
- };
- let err = tinyplace::Error::Http(Box::new(http_err));
- let s = map_err(err);
- assert!(
- !s.starts_with("PAYMENT_REQUIRED:"),
- "404 must not produce PAYMENT_REQUIRED prefix"
- );
- assert!(
- s.contains("404"),
- "404 error string must mention status code"
- );
- }
-
- #[test]
- fn http_402_maps_to_payment_required_prefix() {
- let challenge = PaymentRequiredChallenge {
- error: Some("payment required".to_string()),
- payment: PaymentChallenge {
- scheme: Some("x402".to_string()),
- amount: Some("0.01".to_string()),
- ..Default::default()
- },
- };
- let http_err = HttpError {
- status: 402,
- message: "HTTP 402: Payment Required".to_string(),
- body: serde_json::Value::Null,
- headers: Default::default(),
- payment_required: Some(challenge),
- };
- let err = tinyplace::Error::Http(Box::new(http_err));
- let s = map_err(err);
- assert!(
- s.starts_with("PAYMENT_REQUIRED:"),
- "402 error must have PAYMENT_REQUIRED: prefix, got: {s}"
- );
- // Must be valid JSON after the prefix
- let json_part = &s["PAYMENT_REQUIRED:".len()..];
- serde_json::from_str::<serde_json::Value>(json_part)
- .expect("PAYMENT_REQUIRED payload must be valid JSON");
- }
-}
-
-// ── Inbox write-handler param validation ──────────────────────────────────────
-//
-// The item-targeting inbox writes require `itemId` and must error at param
-// validation — before constructing the client or hitting the network. Awaiting
-// the handler future with empty params exercises exactly that path.
-
-#[cfg(test)]
-mod inbox_write_handlers {
- use serde_json::Map;
-
- use crate::openhuman::tinyplace::manifest::{
- handle_tinyplace_inbox_archive, handle_tinyplace_inbox_mark_read,
- handle_tinyplace_inbox_remove, handle_tinyplace_inbox_unarchive,
- };
-
- #[tokio::test]
- async fn mark_read_requires_item_id() {
- let err = handle_tinyplace_inbox_mark_read(Map::new())
- .await
- .unwrap_err();
- assert!(err.contains("itemId"), "got: {err}");
- }
-
- #[tokio::test]
- async fn archive_requires_item_id() {
- let err = handle_tinyplace_inbox_archive(Map::new())
- .await
- .unwrap_err();
- assert!(err.contains("itemId"), "got: {err}");
- }
-
- #[tokio::test]
- async fn unarchive_requires_item_id() {
- let err = handle_tinyplace_inbox_unarchive(Map::new())
- .await
- .unwrap_err();
- assert!(err.contains("itemId"), "got: {err}");
- }
-
- #[tokio::test]
- async fn remove_requires_item_id() {
- let err = handle_tinyplace_inbox_remove(Map::new()).await.unwrap_err();
- assert!(err.contains("itemId"), "got: {err}");
- }
-}
-
-// ── Channel / broadcast / group membership-handler param validation ────────────
-
-#[cfg(test)]
-mod membership_handlers {
- use serde_json::Map;
-
- use crate::openhuman::tinyplace::manifest::{
- handle_tinyplace_broadcasts_subscribe, handle_tinyplace_broadcasts_unsubscribe,
- handle_tinyplace_channels_join, handle_tinyplace_channels_leave,
- handle_tinyplace_groups_join, handle_tinyplace_groups_leave,
- };
-
- #[tokio::test]
- async fn channels_join_requires_channel_id() {
- let err = handle_tinyplace_channels_join(Map::new())
- .await
- .unwrap_err();
- assert!(err.contains("channelId"), "got: {err}");
- }
-
- #[tokio::test]
- async fn channels_leave_requires_channel_id() {
- let err = handle_tinyplace_channels_leave(Map::new())
- .await
- .unwrap_err();
- assert!(err.contains("channelId"), "got: {err}");
- }
-
- #[tokio::test]
- async fn broadcasts_subscribe_requires_broadcast_id() {
- let err = handle_tinyplace_broadcasts_subscribe(Map::new())
- .await
- .unwrap_err();
- assert!(err.contains("broadcastId"), "got: {err}");
- }
-
- #[tokio::test]
- async fn broadcasts_unsubscribe_requires_broadcast_id() {
- let err = handle_tinyplace_broadcasts_unsubscribe(Map::new())
- .await
- .unwrap_err();
- assert!(err.contains("broadcastId"), "got: {err}");
- }
-
- #[tokio::test]
- async fn groups_join_requires_group_id() {
- let err = handle_tinyplace_groups_join(Map::new()).await.unwrap_err();
- assert!(err.contains("groupId"), "got: {err}");
- }
-
- #[tokio::test]
- async fn groups_leave_requires_group_id() {
- let err = handle_tinyplace_groups_leave(Map::new()).await.unwrap_err();
- assert!(err.contains("groupId"), "got: {err}");
- }
-}
-
-// ── Messages graceful-degrade helpers (staging endpoint gaps) ──────────────────
-
-#[cfg(test)]
-mod messages_degrade {
- use std::collections::HashMap;
-
- use crate::openhuman::tinyplace::manifest::{
- channels_list_degrade, inbox_list_degrade, messages_list_degrade,
- };
-
- /// Synthetic `Error::Http` with an arbitrary status and no payment challenge.
- fn http_error(status: u16) -> tinyplace::Error {
- tinyplace::Error::Http(Box::new(tinyplace::error::HttpError {
- status,
- message: format!("HTTP {status}: /test"),
- body: serde_json::Value::Null,
- headers: HashMap::new(),
- payment_required: None,
- }))
- }
-
- /// A real serde_json error (the SDK's `Error::Serialization` source).
- fn serialization_error() -> tinyplace::Error {
- let err = serde_json::from_str::<i64>("\"not a number\"").unwrap_err();
- tinyplace::Error::Serialization(err)
- }
-
- #[test]
- fn channels_404_degrades_to_empty_list() {
- let degraded = channels_list_degrade(&http_error(404)).expect("404 should degrade");
- assert_eq!(degraded, serde_json::json!({ "channels": [] }));
- }
-
- #[test]
- fn channels_non_404_propagates() {
- assert!(channels_list_degrade(&http_error(500)).is_none());
- assert!(channels_list_degrade(&serialization_error()).is_none());
- }
-
- #[test]
- fn inbox_serialization_error_degrades_to_empty() {
- let degraded =
- inbox_list_degrade(&serialization_error()).expect("serialization error should degrade");
- assert_eq!(
- degraded,
- serde_json::json!({
- "items": [],
- "cursor": null,
- "unreadCount": 0,
- "totalCount": 0,
- })
- );
- }
-
- #[test]
- fn inbox_non_serialization_propagates() {
- assert!(inbox_list_degrade(&http_error(500)).is_none());
- }
-
- #[test]
- fn messages_serialization_error_degrades_to_empty() {
- let degraded = messages_list_degrade(&serialization_error())
- .expect("serialization error should degrade");
- assert_eq!(degraded, serde_json::json!({ "messages": [] }));
- }
-
- #[test]
- fn messages_non_serialization_propagates() {
- assert!(messages_list_degrade(&http_error(500)).is_none());
- }
-}
-
-// ── Identity-key publish/convert round-trip (the /keys bundle contract) ─────────
-//
-// The backend stores and serves the wallet's Ed25519 public key as the bundle
-// identity key (it verifies pre-key signatures against it). Peers must convert
-// that Ed25519 key to X25519 (Montgomery) for Diffie-Hellman. This test pins the
-// invariant that makes publish-Ed25519 + convert-on-consume consistent: the
-// converted published key MUST equal the X25519 identity public key the owner
-// derives from the same wallet seed for its own DH.
-
-#[cfg(test)]
-mod identity_key_publish {
- use base64::Engine as _;
- use tinyplace::signal::crypto::{ed25519_pub_to_x25519_pub, ed25519_seed_to_x25519_keypair};
- use tinyplace::Signer;
-
- #[test]
- fn published_ed25519_converts_to_owner_x25519_identity() {
- // Arbitrary deterministic test seed (not a real wallet).
- let seed = [7u8; 32];
-
- // The owner's own X25519 DH identity, derived from the seed.
- let our_x25519 = ed25519_seed_to_x25519_keypair(&seed);
-
- // The Ed25519 wallet public key we publish to /keys (base64).
- let signer = tinyplace::LocalSigner::from_seed(&seed).expect("signer from seed");
- let ed_bytes: [u8; 32] = base64::engine::general_purpose::STANDARD
- .decode(signer.public_key_base64())
- .expect("base64 pubkey")
- .try_into()
- .expect("32-byte ed25519 pubkey");
-
- // A peer converting our published Ed25519 key must land on our X25519 identity.
- let converted = ed25519_pub_to_x25519_pub(&ed_bytes).expect("ed25519 -> x25519");
- assert_eq!(
- converted, our_x25519.public_key,
- "converted published Ed25519 identity must equal the owner's X25519 DH identity"
- );
- }
-}
-
-// ── Make-discoverable card builder ─────────────────────────────────────────────
-
-#[cfg(test)]
-mod default_agent_card {
- use crate::openhuman::tinyplace::manifest::build_default_agent_card;
-
- fn identity(username: &str, primary: bool) -> tinyplace::types::Identity {
- tinyplace::types::Identity {
- username: username.to_string(),
- crypto_id: "AgentIdBase58".to_string(),
- public_key: "pk".to_string(),
- registered_at: "2026-01-01T00:00:00Z".to_string(),
- expires_at: "2027-01-01T00:00:00Z".to_string(),
- status: "active".to_string(),
- registration_tx: None,
- payment_methods: None,
- primary: Some(primary),
- subnames: None,
- signature: None,
- payment: None,
- last_renewal_tx: None,
- updated_at: "2026-01-01T00:00:00Z".to_string(),
- }
- }
-
- #[test]
- fn uses_registered_handle_when_present() {
- let card =
- build_default_agent_card("AgentIdBase58", "pubkeyb64", Some(&identity("alice", true)));
- assert_eq!(card.agent_id, "AgentIdBase58");
- assert_eq!(card.crypto_id, "AgentIdBase58");
- assert_eq!(card.name, "alice");
- assert_eq!(card.username.as_deref(), Some("alice"));
- assert_eq!(card.public_key.as_deref(), Some("pubkeyb64"));
- // Timestamps are non-empty placeholders (backend reassigns on upsert).
- assert!(!card.created_at.is_empty());
- assert!(!card.updated_at.is_empty());
- }
-
- #[test]
- fn falls_back_to_agent_id_without_identity() {
- let card = build_default_agent_card("AgentIdBase58", "pubkeyb64", None);
- assert_eq!(card.name, "AgentIdBase58");
- assert_eq!(card.username, None);
- }
-}
-
-// ── GraphQL Profile + Identity handler param-validation tests ─────────────────
-
-#[cfg(test)]
-mod graphql_profile_handlers {
- use crate::openhuman::tinyplace::manifest::{
- handle_tinyplace_graphql_agent_card, handle_tinyplace_graphql_identities,
- handle_tinyplace_graphql_identity, handle_tinyplace_graphql_profile,
- handle_tinyplace_graphql_user,
- };
- use serde_json::Map;
-
- #[tokio::test]
- async fn graphql_profile_requires_username() {
- let err = handle_tinyplace_graphql_profile(Map::new())
- .await
- .unwrap_err();
- assert!(err.contains("username"), "got: {err}");
- }
-
- #[tokio::test]
- async fn graphql_user_requires_crypto_id() {
- let err = handle_tinyplace_graphql_user(Map::new()).await.unwrap_err();
- assert!(err.contains("cryptoId"), "got: {err}");
- }
-
- #[tokio::test]
- async fn graphql_identity_requires_username() {
- let err = handle_tinyplace_graphql_identity(Map::new())
- .await
- .unwrap_err();
- assert!(err.contains("username"), "got: {err}");
- }
-
- #[tokio::test]
- async fn graphql_identities_requires_crypto_id() {
- let err = handle_tinyplace_graphql_identities(Map::new())
- .await
- .unwrap_err();
- assert!(err.contains("cryptoId"), "got: {err}");
- }
-
- #[tokio::test]
- async fn graphql_agent_card_requires_id() {
- let err = handle_tinyplace_graphql_agent_card(Map::new())
- .await
- .unwrap_err();
- assert!(err.contains("id"), "got: {err}");
- }
-}
-
-// ── graphql_identities_degrade helper tests ───────────────────────────────────
-
-#[cfg(test)]
-mod graphql_identities_degrade_tests {
- use crate::openhuman::tinyplace::manifest::graphql_identities_degrade;
-
- fn serialization_error() -> tinyplace::Error {
- let err = serde_json::from_str::<i64>("\"not a number\"").unwrap_err();
- tinyplace::Error::Serialization(err)
- }
-
- #[test]
- fn serialization_error_degrades_to_empty_array() {
- let degraded = graphql_identities_degrade(&serialization_error())
- .expect("serialization error should degrade");
- assert_eq!(degraded, serde_json::json!([]));
- }
-
- #[test]
- fn non_serialization_error_propagates() {
- // Use a non-Serialization error variant — these must NOT degrade.
- let signing_err = tinyplace::Error::Signing("key error".to_string());
- assert!(
- graphql_identities_degrade(&signing_err).is_none(),
- "non-serialization errors should not degrade"
- );
- }
-}
-
-// ── publish_directory_card_for_identity tests ─────────────────────────────────
-//
-// The helper is `async fn` and calls `client.directory.{get_agent,upsert_agent}`.
-// We test the pure building logic via `build_default_agent_card` (already covered
-// in the `default_agent_card` module above) plus the anti-spoof and error-handling
-// branches via the exported constants that determine the helper's behaviour.
-
-#[cfg(test)]
-mod publish_directory_card_tests {
- use std::collections::HashMap;
-
- use crate::openhuman::tinyplace::manifest::build_default_agent_card;
-
- fn make_identity(username: &str) -> tinyplace::types::Identity {
- tinyplace::types::Identity {
- username: username.to_string(),
- crypto_id: "TestAgentId111".to_string(),
- public_key: "testpub".to_string(),
- registered_at: "2026-01-01T00:00:00Z".to_string(),
- expires_at: "2027-01-01T00:00:00Z".to_string(),
- status: "active".to_string(),
- registration_tx: None,
- payment_methods: None,
- primary: Some(true),
- subnames: None,
- signature: None,
- payment: None,
- last_renewal_tx: None,
- updated_at: "2026-01-01T00:00:00Z".to_string(),
- }
- }
-
- /// The card built for a fresh 404 path uses the identity username and the
- /// supplied agent_id / public_key_b64 from the signer — NOT from user params.
- #[test]
- fn card_built_from_identity_has_correct_fields() {
- let identity = make_identity("@newhandle");
- let card = build_default_agent_card("SignerAgentId222", "pub64==", Some(&identity));
-
- // agent_id and crypto_id are sourced from the signer argument.
- assert_eq!(card.agent_id, "SignerAgentId222");
- assert_eq!(card.crypto_id, "SignerAgentId222");
- // Name and username come from the registered identity.
- assert_eq!(card.name, "@newhandle");
- assert_eq!(card.username.as_deref(), Some("@newhandle"));
- // Public key comes from the signer's key material.
- assert_eq!(card.public_key.as_deref(), Some("pub64=="));
- }
-
- /// When no identity is provided (should not happen in the post-register path,
- /// but guards future callers), the card falls back to the agent_id as name.
- #[test]
- fn card_without_identity_falls_back_to_agent_id_as_name() {
- let card = build_default_agent_card("FallbackAgent333", "pk64==", None);
- assert_eq!(card.name, "FallbackAgent333");
- assert_eq!(card.username, None);
- assert_eq!(card.agent_id, "FallbackAgent333");
- assert_eq!(card.crypto_id, "FallbackAgent333");
- }
-
- /// Anti-spoof invariant: build_default_agent_card always sets agent_id and
- /// crypto_id from the first argument (the signer's agent_id), and
- /// `publish_directory_card_for_identity` enforces this on the "existing card"
- /// path too by overwriting them before upsert. Verify the helper does NOT
- /// propagate a card with a different crypto_id.
- #[test]
- fn build_default_card_enforces_signer_agent_id() {
- // Simulate a card that arrived with a different agent_id (e.g., corrupted
- // existing card). The builder always overwrites.
- let identity = make_identity("@handle");
- let card = build_default_agent_card("TrustedSignerId444", "pubkey", Some(&identity));
- // The card was built under "TrustedSignerId444" — not some other id.
- assert_eq!(card.agent_id, "TrustedSignerId444");
- assert_eq!(card.crypto_id, "TrustedSignerId444");
- }
-
- /// Verify that a 404 http_error matches the status branch used in
- /// `publish_directory_card_for_identity` (e.status() == Some(404)).
- #[test]
- fn http_404_error_status_is_some_404() {
- let http_err = tinyplace::error::HttpError {
- status: 404,
- message: "HTTP 404: /directory/agents/missing".to_string(),
- body: serde_json::Value::Null,
- headers: HashMap::new(),
- payment_required: None,
- };
- let err = tinyplace::Error::Http(Box::new(http_err));
- assert_eq!(
- err.status(),
- Some(404),
- "404 status must match the branch guard in publish_directory_card_for_identity"
- );
- }
-
- /// A non-404 HTTP error (e.g. 503) does NOT match the 404 branch — the helper
- /// logs a warning and returns without calling upsert. Verify the branch guard.
- #[test]
- fn http_503_error_status_is_not_404() {
- let http_err = tinyplace::error::HttpError {
- status: 503,
- message: "HTTP 503: Service Unavailable".to_string(),
- body: serde_json::Value::Null,
- headers: HashMap::new(),
- payment_required: None,
- };
- let err = tinyplace::Error::Http(Box::new(http_err));
- assert_ne!(
- err.status(),
- Some(404),
- "503 must not match the 404 branch (early-return without upsert)"
- );
- }
-}
-
-// ── #5627: not-yet-published probe classification ─────────────────────────────
-
-#[cfg(test)]
-mod signal_key_status_probe_classification_tests {
- use crate::openhuman::tinyplace::manifest::{is_first_run_gap, is_not_published_yet};
- use tinyplace::error::HttpError;
-
- fn http_err(status: u16, message: &str) -> tinyplace::Error {
- tinyplace::Error::Http(Box::new(HttpError {
- status,
- message: message.to_string(),
- body: serde_json::Value::Null,
- headers: Default::default(),
- payment_required: None,
- }))
- }
-
- /// A 404 from either probe is the **expected** answer for an agent that has
- /// not published its Signal keys yet — the precondition
- /// `ensure_signal_keys_published` exists to remove, and which
- /// `signal_register_encryption_key` repairs by building the card on this
- /// same 404. Classified as not-published, it logs at `debug`; misclassified,
- /// it logs at `warn` on the orchestration supervisor's 15-second timer
- /// forever, on every instance (#5627).
- #[test]
- fn a_404_from_either_probe_is_not_published_yet() {
- for path in [
- "HTTP 404: /keys/EJXoqJp6CYtme1pJ8qT94avpsa5Ji3UdMZqdCH3MnvxE/health",
- "HTTP 404: /directory/agents/EJXoqJp6CYtme1pJ8qT94avpsa5Ji3UdMZqdCH3MnvxE",
- ] {
- assert!(
- is_not_published_yet(&http_err(404, path)),
- "a 404 is the expected not-yet-published state, not a warning: {path}"
- );
- }
- }
-
- /// The demotion must stay narrow. A relay that is genuinely unwell has to
- /// keep reaching `warn`, or a real outage becomes as quiet as a fresh
- /// install — which is the failure mode of over-correcting this class of bug.
- #[test]
- fn any_other_status_stays_warn_worthy() {
- for status in [400u16, 401, 403, 408, 429, 500, 502, 503, 504] {
- assert!(
- !is_not_published_yet(&http_err(status, "HTTP error: /keys/x/health")),
- "HTTP {status} is not a not-yet-published state and must stay warn-worthy"
- );
- }
- }
-
- /// #5809 review (Codex P2) — a 404 is only benign when **nothing** has been
- /// provisioned locally.
- ///
- /// `signal_provision` writes the local store before its network calls, so
- /// local-keys-without-remote means the upload never landed or the backend
- /// lost the record. In that state the agent believes itself ready while
- /// peers 404 on its bundle, and `ensure_signal_keys_published` derives
- /// readiness from the local store alone — so it stops probing and nothing
- /// else reports it. Demoting that to `debug` would silence the only signal.
- #[test]
- fn a_404_with_local_keys_present_is_not_first_run_and_must_still_warn() {
- let not_found = http_err(404, "HTTP 404: /keys/<id>/health");
- assert!(
- !is_first_run_gap(&not_found, true),
- "local keys present means provisioning ran: a 404 is an inconsistency, not first run"
- );
- assert!(
- is_first_run_gap(&not_found, false),
- "nothing provisioned locally: a 404 is the ordinary first-run state"
- );
- }
-
- /// The local-key signal must not rescue a non-404. A 500 is warn-worthy
- /// whatever the local store holds — otherwise a fresh install would silence
- /// a broken relay.
- #[test]
- fn local_key_state_never_makes_a_non_404_look_like_first_run() {
- for status in [400u16, 401, 403, 429, 500, 503] {
- for has_local_keys in [false, true] {
- assert!(
- !is_first_run_gap(&http_err(status, "relay error"), has_local_keys),
- "HTTP {status} is never a first-run gap (has_local_keys={has_local_keys})"
- );
- }
- }
- }
-
- /// A non-HTTP failure has no status at all — `Error::status()` returns
- /// `None` for every variant except `Http`. `None != Some(404)`, so these
- /// must stay warn-worthy: a signer that cannot sign is a real fault, not an
- /// agent that has simply not published yet.
- #[test]
- fn a_statusless_error_stays_warn_worthy() {
- for err in [
- tinyplace::Error::Signing("no signer available".to_string()),
- tinyplace::Error::InvalidArgument("empty agent id".to_string()),
- ] {
- assert!(
- !is_not_published_yet(&err),
- "a statusless error is not a not-yet-published state: {err}"
- );
- }
- }
-}
diff --git a/src/openhuman/tools/mod.rs b/src/openhuman/tools/mod.rs
index 82430c569f..6c082e805a 100644
--- a/src/openhuman/tools/mod.rs
+++ b/src/openhuman/tools/mod.rs
@@ -32,7 +32,6 @@ pub use crate::openhuman::flows::memory_tools::*;
#[cfg(feature = "flows")]
#[cfg(feature = "flows")]
pub use crate::openhuman::flows::tools::*;
-pub use crate::openhuman::hosted::orchestration::tools::*;
pub use crate::openhuman::integrations::composio::tools::*;
pub use crate::openhuman::integrations::task_sources::tools::*;
pub use crate::openhuman::integrations::tools::*;
diff --git a/src/openhuman/tools/ops.rs b/src/openhuman/tools/ops.rs
index bbe20fbb03..04ac02f16c 100644
--- a/src/openhuman/tools/ops.rs
+++ b/src/openhuman/tools/ops.rs
@@ -276,21 +276,6 @@ pub fn all_tools_with_runtime(
Box::new(ResolveTimeTool::new()),
Box::new(DetectToolsTool::new()),
Box::new(InstallToolTool::new(security.clone())),
- // Orchestration session-history read tools — browse persisted
- // OpenHuman↔agent transcripts. Read-only; workspace-internal store access.
- Box::new(
- crate::openhuman::hosted::orchestration::tools::ListSessionsTool::new(config.clone()),
- ),
- Box::new(
- crate::openhuman::hosted::orchestration::tools::ReadSessionTool::new(config.clone()),
- ),
- // List the agent's tiny.place contacts (browse-loop entry point).
- Box::new(crate::openhuman::hosted::orchestration::tools::ListContactsTool),
- // Send-on-behalf: DM another agent for the user. Linked-peers-only,
- // reuse-or-mint per-peer session id; Write-class external effect.
- Box::new(
- crate::openhuman::hosted::orchestration::tools::SendToAgentTool::new(config.clone()),
- ),
Box::new(CronAddTool::new(config.clone(), security.clone())),
Box::new(CronListTool::new(config.clone())),
Box::new(CronRemoveTool::new(config.clone())),
@@ -1399,8 +1384,6 @@ fn tool_group(name: &str) -> crate::core::all::DomainGroup {
if name.starts_with("orchestration_") {
return DomainGroup::Hosted;
}
- // Relay owns no agent tools since the `tinyplace_*` family was removed —
- // see `TOOL_LESS` in `ops_tests.rs`, which is what keeps that honest.
// Desktop: shell-facing surfaces.
if name.starts_with("dashboard_") {
return DomainGroup::Desktop;
diff --git a/src/openhuman/tools/ops_tests.rs b/src/openhuman/tools/ops_tests.rs
index 58c0453e69..5d6491f601 100644
--- a/src/openhuman/tools/ops_tests.rs
+++ b/src/openhuman/tools/ops_tests.rs
@@ -2424,7 +2424,6 @@ const REPRESENTATIVE: &[(&str, crate::core::all::DomainGroup)] = {
("run_workflow", G::Skills),
("cron_add", G::Automation),
("composio_execute", G::Integrations),
- ("orchestration_list_sessions", G::Hosted),
("dashboard_model_health", G::Desktop),
("node_exec", G::Runtimes),
("tinyjuice_retrieve", G::Inference),
@@ -2438,19 +2437,10 @@ const TOOL_LESS: &[crate::core::all::DomainGroup] = {
// `Modules` is the loader, not a capability: a loaded module's own surface
// is reached through whichever domain calls it (documents go through the
// document tools), so the family itself owns no agent tool.
- // `Relay` joined this list when the `tinyplace_*` agent-tool family was
- // removed: the domain still exists and still serves its controllers, it
- // just advertises no agent tool any more. `Channels` joined it for the same
- // reason when the three `whatsapp_data_*` tools went — the channel runtime,
+ // `Channels` joined this list when the three `whatsapp_data_*` tools went —
+ // the channel runtime,
// its controllers and its inbound dispatch are all still there.
- &[
- G::Config,
- G::Security,
- G::Medulla,
- G::Modules,
- G::Relay,
- G::Channels,
- ]
+ &[G::Config, G::Security, G::Medulla, G::Modules, G::Channels]
};
// ---- tool_capability() drift guard (M5.3) ----------------------------------
diff --git a/src/openhuman/web3/mod.rs b/src/openhuman/web3/mod.rs
index c65defd169..403030d729 100644
--- a/src/openhuman/web3/mod.rs
+++ b/src/openhuman/web3/mod.rs
@@ -39,8 +39,8 @@ pub mod types;
// Ungated family members: `wallet` and `x402` are facades in their own right —
// each keeps its own `stub.rs` and gates its real submodules on the same
// default-ON `web3` feature. Always-compiled callers resolve through those
-// stubs (`tinyplace/*` -> `wallet`, `tools/impl/network/http_request.rs` ->
-// `x402`), so these declarations must NOT carry a `#[cfg]`.
+// stubs (`tools/impl/network/http_request.rs` -> `x402`), so these
+// declarations must NOT carry a `#[cfg]`.
pub mod wallet;
pub mod x402;
diff --git a/src/openhuman/web3/wallet/chains/solana.rs b/src/openhuman/web3/wallet/chains/solana.rs
index 7d6879ad92..e973327603 100644
--- a/src/openhuman/web3/wallet/chains/solana.rs
+++ b/src/openhuman/web3/wallet/chains/solana.rs
@@ -687,47 +687,6 @@ pub async fn lookup_tx(hash: &str) -> Result<TxLookupInfo, String> {
})
}
-/// Returns the 32-byte Ed25519 seed for the tiny.place `LocalSigner`, derived
-/// from the user's primary Solana wallet key via the same SLIP-0010 path used
-/// for all Solana signing operations.
-///
-/// The seed is consumed immediately by the caller and **never logged, never
-/// returned across any IPC boundary, never persisted**. Mirrors the exact
-/// derivation at `wallet/chains/solana.rs:369–376`.
-pub(crate) async fn tinyplace_signer_seed() -> Result<[u8; 32], String> {
- log::debug!("[tinyplace] deriving signer seed from Solana wallet key");
- let config = config_rpc::load_config_with_timeout().await?;
- let secret = secret_material(WalletChain::Solana).await?;
- let mnemonic = crate::openhuman::security::encryption::rpc::decrypt_secret(
- &config,
- &secret.encrypted_mnemonic,
- )
- .await?
- .value;
- let signing_secret = tinywallet_bus::wire::SecretMaterial {
- mnemonic,
- derivation_path: secret.derivation_path.clone(),
- chain: tinywallet_bus::Chain::Solana,
- };
-
- // The one path that brings a private key back into this process. Every
- // other Solana operation signs inside the module and never sees one; this
- // cannot, because tiny.place's `LocalSigner::from_seed` takes a seed and
- // has no way to be handed a message to sign instead. Replacing that seam is
- // what it would take to remove this call.
- //
- // The key travels as the reply to a confidential call, so it is delivered
- // to this connection and never fanned out, monitored, or carried to a peer.
- let exported = crate::openhuman::modules::wallet::export_key(&config, &signing_secret)
- .await
- .map_err(|e| format!("failed to export the Solana signer seed: {e}"))?;
- let bytes = hex_to_bytes(&exported.secret_key_hex)?;
- // Never logged: the log below omits the seed.
- log::debug!("[tinyplace] signer seed derived (seed not logged)");
- <[u8; 32]>::try_from(bytes.as_slice())
- .map_err(|_| "the wallet module returned a malformed Solana seed".to_string())
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/openhuman/web3/wallet/defaults.rs b/src/openhuman/web3/wallet/defaults.rs
index 6f83a38ceb..3141b0efdb 100644
--- a/src/openhuman/web3/wallet/defaults.rs
+++ b/src/openhuman/web3/wallet/defaults.rs
@@ -19,9 +19,6 @@ const TRONSCAN_TX_BASE: &str = "https://tronscan.org/#/transaction/";
const DEFAULT_BTC_REST_URL: &str = "https://blockstream.info/api";
const DEFAULT_SOLANA_RPC_URL: &str = "https://api.mainnet-beta.solana.com";
-/// Default tiny.place API base (mirrors `tinyplace::state`) — used to derive the
-/// tiny.place Solana settlement RPC when no explicit override is set.
-const TINYPLACE_API_BASE_DEFAULT: &str = "https://api.tiny.place";
const DEVNET_SOLANA_RPC_URL: &str = "https://api.devnet.solana.com";
const DEFAULT_TRON_REST_URL: &str = "https://api.trongrid.io";
@@ -35,8 +32,7 @@ const SOLANA_USDC_MINT_DEVNET: &str = "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDn
///
/// Drives **both** the default Solana RPC endpoint and the USDC SPL mint, so a
/// devnet x402 payment challenge's on-chain transfer lands on devnet with the
-/// devnet mint rather than mainnet. Pair `OPENHUMAN_SOLANA_CLUSTER=devnet` with
-/// a staging `TINYPLACE_API_BASE_URL` when testing tiny.place on devnet.
+/// devnet mint rather than mainnet.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SolanaCluster {
Mainnet,
@@ -243,49 +239,6 @@ pub fn rpc_url_for_chain(chain: WalletChain) -> String {
}
}
-/// Ordered Solana JSON-RPC endpoints used **only for tiny.place settlement
-/// broadcasts** — primary first, fallback after.
-///
-/// tiny.place settles on its own Solana RPC (the chain where agent accounts are
-/// actually funded); broadcasting to the generic public cluster RPC is what
-/// produces "AccountNotFound / debit an account but found no record of a prior
-/// credit". So the tiny.place payment path tries the tiny.place RPC first and
-/// only falls back to the public cluster on a *transport-level* failure (the
-/// endpoint is unreachable), never on a well-formed JSON-RPC error (an
-/// authoritative answer such as a real insufficient-funds result).
-///
-/// Priority:
-/// 1. tiny.place's own Solana RPC — `TINYPLACE_SOLANA_RPC_URL` if set, else
-/// derived from the tiny.place API base (`<TINYPLACE_API_BASE_URL>/solana/rpc`,
-/// default `https://api.tiny.place/solana/rpc`) so it tracks prod/staging.
-/// 2. `solana_cluster().rpc_url()` — public mainnet (or devnet) as fallback.
-///
-/// General wallet operations are unaffected — they keep using the single
-/// [`rpc_url_for_chain`] endpoint.
-pub fn tinyplace_solana_rpc_endpoints() -> Vec<String> {
- let mut endpoints: Vec<String> = vec![
- tinyplace_solana_rpc_url(),
- solana_cluster().rpc_url().to_string(),
- ];
-
- // De-dup while preserving order (the override may equal the public URL).
- let mut seen = std::collections::HashSet::new();
- endpoints.retain(|url| seen.insert(url.clone()));
- endpoints
-}
-
-/// tiny.place's Solana settlement RPC — explicit `TINYPLACE_SOLANA_RPC_URL`
-/// override, else `<TINYPLACE_API_BASE_URL>/solana/rpc` (default base
-/// `https://api.tiny.place`).
-fn tinyplace_solana_rpc_url() -> String {
- if let Some(url) = env_nonempty("TINYPLACE_SOLANA_RPC_URL") {
- return url;
- }
- let base = env_nonempty("TINYPLACE_API_BASE_URL")
- .unwrap_or_else(|| TINYPLACE_API_BASE_DEFAULT.to_string());
- format!("{}/solana/rpc", base.trim_end_matches('/'))
-}
-
/// Trimmed value of `env_var`, or `None` when unset/blank.
fn env_nonempty(env_var: &str) -> Option<String> {
std::env::var(env_var)
@@ -671,83 +624,4 @@ mod tests {
assert_eq!(solana_cluster(), SolanaCluster::Mainnet);
});
}
-
- // ── tiny.place Solana settlement endpoints ────────────────────────────────
- //
- // These read TINYPLACE_* env in addition to the cluster, so serialise them
- // under the same lock as the cluster tests and always restore prior values.
- fn with_tinyplace_env<T>(
- rpc_url: Option<&str>,
- api_base: Option<&str>,
- cluster: Option<&str>,
- f: impl FnOnce() -> T,
- ) -> T {
- let _guard = CLUSTER_ENV_LOCK
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- let prev_rpc = std::env::var("TINYPLACE_SOLANA_RPC_URL").ok();
- let prev_base = std::env::var("TINYPLACE_API_BASE_URL").ok();
- let prev_cluster = std::env::var("OPENHUMAN_SOLANA_CLUSTER").ok();
- let set = |key: &str, val: Option<&str>| match val {
- Some(v) => std::env::set_var(key, v),
- None => std::env::remove_var(key),
- };
- set("TINYPLACE_SOLANA_RPC_URL", rpc_url);
- set("TINYPLACE_API_BASE_URL", api_base);
- set("OPENHUMAN_SOLANA_CLUSTER", cluster);
- // Catch panics (e.g. assertion failures) so env is always restored —
- // otherwise a failing test leaks process-global env into later tests.
- let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
- set("TINYPLACE_SOLANA_RPC_URL", prev_rpc.as_deref());
- set("TINYPLACE_API_BASE_URL", prev_base.as_deref());
- set("OPENHUMAN_SOLANA_CLUSTER", prev_cluster.as_deref());
- match out {
- Ok(v) => v,
- Err(panic) => std::panic::resume_unwind(panic),
- }
- }
-
- #[test]
- fn tinyplace_endpoints_default_to_api_tiny_place_then_public_mainnet() {
- with_tinyplace_env(None, None, None, || {
- assert_eq!(
- tinyplace_solana_rpc_endpoints(),
- vec![
- "https://api.tiny.place/solana/rpc".to_string(),
- DEFAULT_SOLANA_RPC_URL.to_string(),
- ]
- );
- });
- }
-
- #[test]
- fn tinyplace_endpoints_derive_primary_from_api_base() {
- with_tinyplace_env(None, Some("https://staging-api.tiny.place/"), None, || {
- // Trailing slash trimmed; primary tracks the configured API base.
- assert_eq!(
- tinyplace_solana_rpc_endpoints()[0],
- "https://staging-api.tiny.place/solana/rpc"
- );
- });
- }
-
- #[test]
- fn tinyplace_endpoints_explicit_override_wins_as_primary() {
- with_tinyplace_env(Some("https://my-rpc.example/rpc"), None, None, || {
- let endpoints = tinyplace_solana_rpc_endpoints();
- assert_eq!(endpoints[0], "https://my-rpc.example/rpc");
- assert_eq!(endpoints[1], DEFAULT_SOLANA_RPC_URL);
- });
- }
-
- #[test]
- fn tinyplace_endpoints_dedup_when_primary_equals_public() {
- with_tinyplace_env(Some(DEFAULT_SOLANA_RPC_URL), None, None, || {
- // Primary == public fallback collapses to a single endpoint.
- assert_eq!(
- tinyplace_solana_rpc_endpoints(),
- vec![DEFAULT_SOLANA_RPC_URL.to_string()]
- );
- });
- }
}
diff --git a/src/openhuman/web3/wallet/mod.rs b/src/openhuman/web3/wallet/mod.rs
index fc9316d186..c3b0651c98 100644
--- a/src/openhuman/web3/wallet/mod.rs
+++ b/src/openhuman/web3/wallet/mod.rs
@@ -12,12 +12,9 @@
//! exposes the same public surface that always-on / other-gated callers depend
//! on (`WALLET_NOT_CONFIGURED_MESSAGE`, `status`, `secret_material`,
//! `WalletChain`, `prepare_transfer`, `execute_prepared`, the prepare/execute
-//! param + result types, `solana_cluster` / `SolanaCluster` /
-//! `tinyplace_solana_rpc_endpoints`, `tinyplace_signer_seed`, the `rpc`
+//! param + result types, `solana_cluster` / `SolanaCluster`, the `rpc`
//! submodule, `prepared_quotes_for_test`, and the controller-registration
-//! entry points) with no-op / disabled-error bodies — so tinyplace on-chain
-//! payments degrade to graceful "wallet disabled" errors rather than failing
-//! to compile. Signatures MUST match the real ones;
+//! entry points) with no-op / disabled-error bodies. Signatures MUST match the real ones;
//! the disabled build
//! (`cargo check --no-default-features`) is
//! the only thing that catches drift.
@@ -49,16 +46,12 @@ pub(crate) mod test_support;
#[cfg(feature = "web3")]
pub use abi::encode_erc20_transfer;
-/// 32-byte Ed25519 seed for the tiny.place LocalSigner. Derived from the user's
-/// primary Solana wallet key via SLIP-0010; consumed in-process and never exposed.
-#[cfg(feature = "web3")]
-pub(crate) use chains::solana::tinyplace_signer_seed;
#[cfg(feature = "web3")]
pub use defaults::{
asset_catalog, default_rpc_url, env_var_for_chain, evm_asset_catalog, explorer_tx_url,
find_asset, find_asset_for_network, network_defaults, rpc_source_for_chain, rpc_url_for_chain,
- rpc_url_for_evm_network, solana_cluster, tinyplace_solana_rpc_endpoints, EvmNetwork, RpcSource,
- SolanaCluster, WalletAssetDefinition, WalletNetworkDefaults,
+ rpc_url_for_evm_network, solana_cluster, EvmNetwork, RpcSource, SolanaCluster,
+ WalletAssetDefinition, WalletNetworkDefaults,
};
#[cfg(feature = "web3")]
pub use execution::{
@@ -79,10 +72,6 @@ pub use ops::{
reveal_recovery_phrase, setup, status, RevealRecoveryPhraseResult, WalletAccount, WalletChain,
WalletSetupParams, WalletSetupSource, WalletStatus, WALLET_NOT_CONFIGURED_MESSAGE,
};
-/// Reduce an RPC URL to `scheme://host` for logging so private provider tokens
-/// embedded in the path/query never reach the logs.
-#[cfg(feature = "web3")]
-pub(crate) use rpc::redact_rpc_url;
#[cfg(feature = "web3")]
pub use schemas::{
all_controller_schemas, all_registered_controllers, all_wallet_controller_schemas,
diff --git a/src/openhuman/web3/wallet/ops.rs b/src/openhuman/web3/wallet/ops.rs
index d4eb62d359..b0710613cc 100644
--- a/src/openhuman/web3/wallet/ops.rs
+++ b/src/openhuman/web3/wallet/ops.rs
@@ -21,7 +21,7 @@ const WALLET_STATE_FILENAME: &str = "wallet-state.json";
///
/// This is an expected user-state (the user simply has not created a wallet),
/// not an internal failure. Downstream boundaries that surface this condition
-/// — e.g. the `tinyplace` client builder — match against this constant to
+/// match against this constant to
/// classify it as `expected_user_state` so it stays out of Sentry. Keep it a
/// shared constant so the producer here and any classifier cannot drift apart.
pub const WALLET_NOT_CONFIGURED_MESSAGE: &str = "wallet is not configured; run wallet setup first";
diff --git a/src/openhuman/web3/wallet/rpc.rs b/src/openhuman/web3/wallet/rpc.rs
index 2de04a5ba9..40c64bc1fe 100644
--- a/src/openhuman/web3/wallet/rpc.rs
+++ b/src/openhuman/web3/wallet/rpc.rs
@@ -40,29 +40,6 @@ fn client() -> reqwest::Client {
SHARED_CLIENT.clone()
}
-tokio::task_local! {
- /// Ordered Solana RPC endpoints active for the current async task. Set only
- /// by the tiny.place settlement path (see [`with_tinyplace_solana_endpoints`])
- /// so Solana `rpc_call`s made while broadcasting a tiny.place payment try the
- /// tiny.place RPC first and fall back to the public cluster. Unset for all
- /// general wallet operations.
- static TINYPLACE_SOLANA_ENDPOINTS: Vec<String>;
-}
-
-/// Run `fut` with the tiny.place Solana failover endpoint list active for any
-/// Solana [`rpc_call`] made within it. Scoped to the current async task, so
-/// concurrent general wallet operations are unaffected.
-pub async fn with_tinyplace_solana_endpoints<F, T>(endpoints: Vec<String>, fut: F) -> T
-where
- F: std::future::Future<Output = T>,
-{
- TINYPLACE_SOLANA_ENDPOINTS.scope(endpoints, fut).await
-}
-
-fn active_tinyplace_endpoints() -> Option<Vec<String>> {
- TINYPLACE_SOLANA_ENDPOINTS.try_with(|e| e.clone()).ok()
-}
-
/// Distinguishes an endpoint being unreachable/broken (retry the next fallback)
/// from a healthy endpoint returning an authoritative JSON-RPC error (do NOT
/// fall back — e.g. a real insufficient-funds result must surface as-is).
@@ -73,60 +50,14 @@ enum RpcCallError {
/// JSON-RPC POST against a chain's default/override endpoint.
///
-/// For Solana, when a tiny.place settlement scope is active
-/// ([`with_tinyplace_solana_endpoints`]) the call fails over across the
-/// tiny.place → public endpoint list on transport errors. All other chains and
-/// non-tiny.place Solana calls use the single configured endpoint.
pub async fn rpc_call<T: DeserializeOwned>(
chain: WalletChain,
method: &str,
params: Value,
) -> Result<T, String> {
- if chain == WalletChain::Solana {
- if let Some(endpoints) = active_tinyplace_endpoints() {
- return rpc_call_failover(&endpoints, method, params).await;
- }
- }
rpc_call_to(&rpc_url_for_chain(chain), method, params).await
}
-/// Try each endpoint in order, advancing only on transport-level failures.
-async fn rpc_call_failover<T: DeserializeOwned>(
- endpoints: &[String],
- method: &str,
- params: Value,
-) -> Result<T, String> {
- let total = endpoints.len();
- let mut last_transport: Option<String> = None;
- for (idx, url) in endpoints.iter().enumerate() {
- match rpc_call_to_inner::<T>(url, method, params.clone()).await {
- Ok(value) => {
- if idx > 0 {
- log::warn!(
- "{LOG_PREFIX} tinyplace solana rpc: {method} succeeded on fallback \
- endpoint #{idx} ({})",
- redact_rpc_url(url)
- );
- }
- return Ok(value);
- }
- // Authoritative answer from a healthy endpoint — surface it, never
- // fall back (e.g. a genuine simulation/insufficient-funds error).
- Err(RpcCallError::Rpc(message)) => return Err(message),
- Err(RpcCallError::Transport(message)) => {
- log::warn!(
- "{LOG_PREFIX} tinyplace solana rpc: endpoint #{idx}/{total} ({}) unreachable \
- for {method}, trying fallback: {message}",
- redact_rpc_url(url)
- );
- last_transport = Some(message);
- }
- }
- }
- Err(last_transport
- .unwrap_or_else(|| format!("wallet RPC: no Solana endpoints configured for {method}")))
-}
-
/// JSON-RPC POST against a specific EVM network's RPC URL.
pub async fn evm_rpc_call<T: DeserializeOwned>(
network: EvmNetwork,
diff --git a/src/openhuman/web3/wallet/stub.rs b/src/openhuman/web3/wallet/stub.rs
index 3d329c1965..478710ab15 100644
--- a/src/openhuman/web3/wallet/stub.rs
+++ b/src/openhuman/web3/wallet/stub.rs
@@ -14,12 +14,6 @@
//!
//! Consumers covered here (all outside `wallet`, so all must keep compiling):
//! - `core/jsonrpc.rs` — `WALLET_NOT_CONFIGURED_MESSAGE`
-//! - `tinyplace/payment.rs` — `prepare_transfer`, `execute_prepared`, the
-//! param/result types, `SolanaCluster`, `solana_cluster`,
-//! `tinyplace_solana_rpc_endpoints`, `rpc::with_tinyplace_solana_endpoints`
-//! - `tinyplace/manifest.rs` — `solana_cluster`, `tinyplace_solana_rpc_endpoints`,
-//! `redact_rpc_url`, `SolanaCluster::usdc_mint`
-//! - `tinyplace/signal_store.rs`, `tinyplace/state.rs` — `tinyplace_signer_seed`
//! - `test_support/introspect.rs` — `prepared_quotes_for_test`,
//! `PreparedTransaction`
//! - `core/all.rs` — `all_wallet_registered_controllers`
@@ -103,10 +97,8 @@ pub(crate) async fn secret_material(_chain: WalletChain) -> Result<WalletSecretM
// PreparedTransaction, ExecutionResult, prepared_quotes_for_test}`)
// ---------------------------------------------------------------------------
-/// Inputs to `prepare_transfer`. Mirrors the fields `tinyplace/payment.rs`
-/// sets. `evm_network` is `Option<()>` (the real `Option<EvmNetwork>` cannot be
-/// named with `defaults` compiled out); the only external constructor passes
-/// `None`, so the placeholder is behaviourally identical.
+/// Inputs to `prepare_transfer`. `evm_network` is `Option<()>` because the
+/// real `Option<EvmNetwork>` cannot be named with `defaults` compiled out.
#[derive(Debug, Clone)]
pub struct PrepareTransferParams {
pub chain: WalletChain,
@@ -123,18 +115,16 @@ pub struct ExecutePreparedParams {
pub confirmed: bool,
}
-/// A prepared quote. Out-of-module callers read `quote_id` (`tinyplace`) and
-/// serialize the collection (`test_support`); `Serialize` + that field are the
-/// only requirements. The real type is far richer.
+/// A prepared quote. Test support serializes this collection; the real type is
+/// far richer.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PreparedTransaction {
pub quote_id: String,
}
-/// Result of an execute. Out-of-module callers read `transaction_hash`
-/// (`tinyplace/payment.rs`); `execute_prepared` never returns `Ok`, so it is
-/// never actually produced.
+/// Result of an execute. `execute_prepared` never returns `Ok`, so it is
+/// never actually produced in the disabled build.
#[derive(Debug, Clone)]
pub struct ExecutionResult {
pub transaction_hash: String,
@@ -165,22 +155,11 @@ pub fn prepared_quotes_for_test() -> Vec<PreparedTransaction> {
Vec::new()
}
-/// Disabled: the tiny.place signer seed derives from the Solana wallet key,
-/// which does not exist. Callers `?`-propagate → "unlock wallet" prompt.
-pub(crate) async fn tinyplace_signer_seed() -> Result<[u8; 32], String> {
- log::debug!(
- "[wallet-stub] tinyplace_signer_seed requested (web3 disabled) — returning disabled error"
- );
- Err(DISABLED_MSG.to_string())
-}
-
// ---------------------------------------------------------------------------
-// Solana cluster metadata (mirrors `defaults::{SolanaCluster, solana_cluster,
-// tinyplace_solana_rpc_endpoints}`)
+// Solana cluster metadata (mirrors `defaults::{SolanaCluster, solana_cluster}`)
// ---------------------------------------------------------------------------
-/// Public Solana clusters. Mirrors [`super::defaults::SolanaCluster`] including
-/// the `usdc_mint` accessor `tinyplace/{payment,manifest}.rs` call.
+/// Public Solana clusters. Mirrors [`super::defaults::SolanaCluster`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SolanaCluster {
Mainnet,
@@ -204,41 +183,6 @@ pub fn solana_cluster() -> SolanaCluster {
SolanaCluster::Mainnet
}
-/// Always empty: the wallet is compiled out, so there are no settlement
-/// endpoints. `tinyplace/manifest.rs`'s balance loop therefore no-ops and the
-/// balance shows as unknown — the correct degraded state.
-pub fn tinyplace_solana_rpc_endpoints() -> Vec<String> {
- Vec::new()
-}
-
-// ---------------------------------------------------------------------------
-// rpc submodule (mirrors `rpc::{redact_rpc_url, with_tinyplace_solana_endpoints}`)
-// ---------------------------------------------------------------------------
-
-pub(crate) mod rpc {
- /// Redact an RPC URL for logging. With the wallet disabled we never build
- /// real endpoints, but `tinyplace/manifest.rs` still calls this on any URL
- /// it iterates; return a constant so no token can ever leak.
- pub(crate) fn redact_rpc_url(_raw: &str) -> String {
- "<rpc-redacted>".to_string()
- }
-
- /// Run `fut` unchanged — there is no tiny.place endpoint scope to install
- /// when the wallet is compiled out. Matches the real generic signature so
- /// `tinyplace/payment.rs` type-checks; the future itself resolves to a
- /// disabled error from `prepare_transfer`.
- pub(crate) async fn with_tinyplace_solana_endpoints<F, T>(_endpoints: Vec<String>, fut: F) -> T
- where
- F: std::future::Future<Output = T>,
- {
- fut.await
- }
-}
-
-/// Re-export mirrors the real `pub(crate) use rpc::redact_rpc_url;` so
-/// `wallet::redact_rpc_url` resolves at the module root for `tinyplace`.
-pub(crate) use rpc::redact_rpc_url;
-
// ---------------------------------------------------------------------------
// Agent-tool facade (mirrors `pub mod tools`, re-exported via tools/mod.rs)
// ---------------------------------------------------------------------------
@@ -267,7 +211,7 @@ pub fn all_wallet_controller_schemas() -> Vec<ControllerSchema> {
// This module is only compiled when the `web3` feature is OFF (see the
// `#[cfg(not(feature = "web3"))] mod stub;` gate in `super`), so a plain
// `#[cfg(test)]` here already runs only in the disabled build — it locks in the
-// degraded contract that always-on callers (tinyplace payments) depend on.
+// degraded contract that always-on callers depend on.
#[cfg(test)]
mod tests {
use super::*;
@@ -316,18 +260,9 @@ mod tests {
assert_eq!(err, DISABLED_MSG);
}
- #[tokio::test]
- async fn tinyplace_signer_seed_is_disabled_error() {
- let err = tinyplace_signer_seed()
- .await
- .expect_err("no signer seed derives when the wallet is compiled out");
- assert_eq!(err, DISABLED_MSG);
- }
-
#[test]
- fn prepared_quotes_and_rpc_endpoints_are_empty() {
+ fn prepared_quotes_are_empty() {
assert!(prepared_quotes_for_test().is_empty());
- assert!(tinyplace_solana_rpc_endpoints().is_empty());
}
#[test]
diff --git a/src/openhuman/web3/wallet/transport.rs b/src/openhuman/web3/wallet/transport.rs
index 96953d88df..c744a1ad47 100644
--- a/src/openhuman/web3/wallet/transport.rs
+++ b/src/openhuman/web3/wallet/transport.rs
@@ -10,7 +10,6 @@
//!
//! - **endpoint resolution**, including the `OPENHUMAN_WALLET_RPC_<CHAIN>`
//! overrides the e2e tests point at a mock;
-//! - **failover** across the tiny.place Solana endpoint list;
//! - **URL redaction**, so an endpoint carrying an API key never reaches a log;
//! - the shared `reqwest` client and its connection pool.
//!