Compare commits

..
Author SHA1 Message Date
Julius Marminge de7f96038b feat(worktrees): add safe inventory, pruning, and revival
- Add worktree inventory, safety validation, pruning, and reaping
- Expose worktree management through server RPC and settings UI
- Restore missing worktrees when threads resume
2026-07-28 13:58:54 +02:00
283 changed files with 4429 additions and 40313 deletions

No files matched your search

-19
View File
@@ -99,22 +99,3 @@ jobs:
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
hermes_plugin:
name: Hermes Plugin
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 5
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Lint
run: pipx run ruff check integrations/hermes-t3-gateway
- name: Test
run: python -m unittest discover -s integrations/hermes-t3-gateway/tests -v
-2
View File
@@ -35,5 +35,3 @@ node_modules/
*.log
.env*
!.env.example
__pycache__/
*.py[cod]
+175
View File
@@ -0,0 +1,175 @@
# Worktree Management v1
## Problem
t3code creates a worktree per thread (`~/.t3/worktrees/<project>/t3code-<hash>`, branch
`t3code/<8hex>`) but has almost no lifecycle management. With the settled system, threads
are rarely deleted anymore, so worktrees accumulate unboundedly (real case: 186 worktrees).
Current state:
- No worktree registry. A worktree exists only as the denormalized `worktree_path` column on
`projection_threads` (`apps/server/src/persistence/Layers/ProjectionThreads.ts:41`). Nothing
records creation time, last use, or dirty state.
- The only cleanup path is the interactive "delete worktree too?" dialog when deleting the
last thread that uses one (`apps/web/src/hooks/useThreadActions.ts:253-397`). It is
desktop-only (requires `localApi`), so web users always leak worktrees. `thread.delete`
on the server never touches the worktree (`apps/server/src/orchestration/decider.ts:381-401`).
- `git worktree prune` is never invoked anywhere.
- Settling (`settled_override`/`settled_at`) is a projection-level soft-hide; it has no effect
on the worktree, so settled threads pin their worktrees forever.
- Checkpoint refs (`refs/t3/checkpoints/...`) live in the shared ref store, not in the
worktree's private git dir, so removing a worktree does not lose checkpoints. Branches are
likewise repo-level. This is what makes lossless revival possible.
## Decisions (locked)
1. **Worktrees only in v1.** No branch deletion, no checkpoint-ref GC. Branches are cheap and
keeping them makes revival trivial. Merged-branch cleanup can be a later tier.
2. **No safety-snapshot-before-delete.** Auto-prune only ever touches *safe* worktrees. Users
may force-delete a dirty worktree, but the UI must make clear that this is destructive and
the uncommitted state cannot be restored later — that's on them.
3. **Never auto-prune dirty worktrees.** Instead, surface them in the Worktrees settings page
as "needs attention": e.g. *"This worktree has had no activity for N days, but has
uncommitted changes so it won't be deleted automatically."*
4. **Global policy settings only.** Per-project overrides are an application-wide capability
we don't have yet; out of scope.
5. **Orphan handling is configurable.** A setting chooses whether orphaned worktrees (no
thread references them) are deleted immediately when they become orphaned, or just fall
under the normal inactivity schedule.
6. **CLI is a stretch goal and must be super minimal** (`t3 worktrees list` / `prune`), or
dropped from v1 entirely.
## Definitions
**Worktree record** (derived, not persisted): for each entry in `git worktree list --porcelain`
under the project's worktrees dir, joined against thread rows sharing that normalized path:
- `path`, `branch`
- linked threads: id, title, effective settled state, deleted state
- `dirty` (working-tree changes, via existing `localStatus` — `GitManager.ts:856-864`)
- `unpushed` (`aheadCount` / `aheadOfDefaultCount` / `hasUpstream` via `remoteStatus`)
- `prState` (merged / open / none, already available on the remote status result)
- `lastActivity`: max of linked threads' last activity / `settled_at`; fallback to worktree
dir mtime for orphans
- `orphaned`: no non-deleted thread references the path
- `safeToPrune`: see below
**Safe to prune** = ALL of:
- no *active* (unsettled, undeleted) thread references the worktree
- working tree clean
- branch merged, or fully pushed (`hasUpstream && aheadCount == 0`), or contains no commits
beyond its recorded merge-base (`aheadOfDefaultCount == 0`)
- path is inside the managed worktrees dir and is not the project `workspaceRoot`
**Auto-prunable** = safeToPrune AND (orphaned with "delete orphans immediately" enabled, OR
`lastActivity` older than the configured inactivity window).
## Components
### 1. Worktree inventory service (server)
New Effect service (e.g. `apps/server/src/vcs/WorktreeInventory.ts`) that produces the derived
records above per project. Scan via `git worktree list --porcelain` (driver already parses
this at `GitVcsDriverCore.ts:2121-2164` for branch annotation — extract/reuse). Status via
existing `GitManager.localStatus`/`remoteStatus` (already ~1s cached). Short TTL cache on the
assembled inventory; a full status sweep across 186 worktrees is not free, so statuses should
be fetched lazily/batched and the settings page should render the list first and stream
status in.
Exposed over WS RPC alongside the existing `vcsCreateWorktree`/`vcsRemoveWorktree`
(`apps/server/src/ws.ts:1838-1849`): `vcsListWorktrees` (inventory) and
`vcsPruneWorktrees` (bulk delete of a provided safe set, server re-validates safety before
each removal — never trust the client's classification).
### 2. Worktrees settings page (web)
Follow the appearance-settings pattern:
- route `apps/web/src/routes/settings.worktrees.tsx`
- `WorktreesSettingsPanel` in `apps/web/src/components/settings/SettingsPanels.tsx`
- nav entry + path union in `apps/web/src/components/settings/SettingsSidebarNav.tsx:26-49`
Content:
- List of managed worktrees with badges: dirty, unpushed, merged, orphaned, settled-only,
linked-thread count. Sort: needs-attention first, then by lastActivity ascending.
- "Needs attention" grouping for dirty-but-inactive worktrees with the explanatory copy from
decision 3.
- Filtering (client-side over the loaded inventory — no new RPC surface):
- free-text search matching branch name, directory name, and linked thread titles
- project filter (the page is global; with several projects the list interleaves otherwise)
- status filter chips, multi-select: needs attention / safe to prune / dirty / unpushed /
orphaned / settled-only
- the bulk "Prune N safe worktrees" action operates on the *filtered* set when filters are
active, and the button label must reflect that (e.g. "Prune 12 safe worktrees (filtered)")
- filter state is ephemeral (not persisted) in v1
- Row actions: delete (safe rows: plain confirm; dirty/unpushed rows: destructive-styled
confirm spelling out that uncommitted changes / unpushed commits are permanently lost).
- Bulk action: "Prune N safe worktrees".
- Policy controls (global):
- auto-prune enabled on/off
- inactivity window: 7 / 14 (default) / 30 days
- "delete orphaned worktrees immediately" toggle
- Deleting never deletes threads; threads keep their `branch`/`worktreePath` metadata for
revival.
Open implementation question: where the policy settings persist. The sweep runs server-side,
so the policy must be server-readable — unlike e.g. `sidebarAutoSettleAfterDays`, which is a
client-side setting (`BetaSettingsPanel.tsx:12-14`). Resolve during implementation: either an
existing server-persisted settings mechanism if one exists, or a small server settings
store + RPC.
### 3. Auto-prune sweep (server)
Periodic loop on the `ProviderSessionReaper` pattern
(`apps/server/src/provider/Layers/ProviderSessionReaper.ts:106-131` — `Effect.forkScoped` +
`Schedule.spaced`), started from `serverRuntimeStartup.ts` like the reaper (`:345`). Cadence:
hourly-ish; exact interval is uninteresting as long as it also runs once shortly after startup.
Each sweep, per project: build inventory → remove auto-prunable worktrees via existing
`removeWorktree` (`GitVcsDriverCore.ts:2393-2405`, without `--force` — a non-forced
`git worktree remove` refusing due to unexpected dirt is a desirable last-line safety net) →
finish with `git worktree prune` (new driver op) to clear stale admin entries. Log a concise
summary event/line of what was removed and what was skipped-with-reason (feeds the
"needs attention" UI).
Also handle decision 5's immediate mode: when `thread.delete` orphans a worktree and the
"delete orphans immediately" setting is on, the server removes it (if safe) without any
client dialog — this replaces the desktop-only prompt path as the mechanism; the web/desktop
delete flow keeps its dialog purely as UX when the setting is off.
### 4. Revival on unsettle
When a thread becomes active again (explicit unsettle, or the existing auto-unsettle-on-
activity in `decider.ts:785-799` etc.) — or when a turn starts — and its `worktreePath` no
longer exists on disk: recreate it in `bootstrap.prepareWorktree` (`ws.ts:1011-1041`) via
`git worktree add <path> <branch>` on the thread's existing branch (branch always survives
v1 pruning). If the branch is somehow gone (user deleted it manually), fail with a clear
error offering to recreate from the base branch. Checkpoint refs survive pruning, so
diff/revert history remains intact after revival.
### 5. Minimal CLI (stretch)
`t3 worktrees list` (table from the inventory) and `t3 worktrees prune [--dry-run]`
(safe set only; no force flag in v1). New file in `apps/server/src/cli/`, patterned on
`project.ts`. Cut first if v1 needs trimming — the settings page's bulk prune covers the
acute 186-worktree cleanup.
## Build order
1. Inventory service + `vcsListWorktrees`/`vcsPruneWorktrees` RPC
2. Worktrees settings page (observability + manual/bulk delete) — solves the acute pain
3. Policy settings + auto-prune sweep + orphan-immediate handling + server-side removal on
thread delete
4. Revival on missing worktree
5. CLI (stretch)
## Out of scope for v1
- Branch deletion / checkpoint-ref GC
- Safety snapshots of dirty state before deletion
- Per-project policy overrides
- Any migration/backfill beyond what the inventory naturally surfaces (existing orphans just
show up as prunable)
+40 -127
View File
@@ -1,139 +1,52 @@
# T3 Code
# AGENTS.md
T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs (Codex, Claude Code, Cursor, Grok, OpenCode) and serves web, desktop, and mobile clients.
## Task Completion Requirements
You can think of T3 Code as an open source "bring-your-own-subscription" alternative to apps like Claude Desktop, Codex App, Cursor Glass and Conductor.
- Keep local verification focused on the files and packages changed. Run the smallest relevant test set; do not run the full workspace test suite as a routine completion step.
- Use `vp test run <test-files>` for focused built-in Vite+ tests. Use `vp run test` only when the affected package specifically requires its `test` script.
- Backend changes must include and run focused tests for the changed behavior.
- Run targeted formatting, lint, and type checks for the affected scope when available.
- Do not run repo-wide `vp check`, `vp run typecheck`, `vp run test`, or equivalent full-suite commands locally unless the user explicitly requests them. CI is responsible for the full verification suite.
- After frontend feature development or any user-visible frontend behavior change, the primary agent must run one integrated verification pass for each affected client surface after integrating the work:
- Web: use the `test-t3-app` skill. Launch one isolated environment, authenticate through the printed pairing URL, and verify the affected flow in the controlled browser.
- Mobile: use the `test-t3-mobile` skill. Connect one representative iOS Simulator or Android Emulator available on the host to one isolated environment and verify the affected flow. On compatible macOS hosts, prefer iOS for cross-platform changes and stream it through serve-sim in the T3 Code in-app browser or another available agent browser; use Android when it is the affected or viable platform.
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
## What makes T3 Code special?
## Dev Servers
We have over 100,000 users who love T3 Code. It's important we maintain the things they love as we continue to iterate on the product. Here's a brief list of the things we can never compromise on.
- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.
- Start the web stack with `vp run dev`. Add `--share` when someone needs to open it from another device on the tailnet.
- Browser dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
- Worktree paths supply stable preferred port offsets. Read the actual server and web ports from the `[dev-runner]` line because occupied ports can still shift them.
- Before handing off a `--share` URL, open its origin in a controlled browser and confirm the app loads. A successful curl is insufficient because browsers reject some otherwise reachable ports.
### 1. Open at the core
## Package Roles
T3 Code is truly open. We share our roadmap, we share how we think about things, and of course we share all our code. A large number of our users run forks. We work in the open, and should strive to stay that way.
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
- `packages/shared`: Shared runtime utilities consumed by both server and client applications. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
- `packages/client-runtime`: Shared runtime package for sharing client code across web and mobile.
### 2. Performance without compromise
## Reference Repos
Lots of apps have gotten bogged down with bad tech decisions and "slop". We have not, and we're proud of the performance of T3 Code. We regularly audit for performance regressions, often caused by sending too much data over websockets, css animations causing gpu spikes, lists being hard to render, and more. Make sure all changes are considerate of performance impact.
- Open-source Codex repo: https://github.com/openai/codex
### 3. Remote ready
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
The architecture of T3 Code's websocket layer (npx t3) enables a lot of awesome remote features. These have become core to the product. Whether users are connecting directly over their local network, using Tailscale, or leaning in fully with T3 Connect (our tunnel solution, also in this repo), we need to make sure new features are properly supported.
## Vendored Repositories
### 4. Multi-surface
This project vendors external repositories under `.repos/` as read-only reference material for coding
agents.
T3 Code has 3 key app surfaces: **web**, **desktop**, and **mobile**.
**Web** is kind of two surfaces, as we have the public facing "app.t3.codes" as well as locally hosting the web app through the `npx t3` command. Both need to be supported by all new features where reasonable.
**Desktop** is the main surface most users install first. It's a full Electron app that bundles the server runner as well. The desktop app can also be used as the host server, allowing remote connections from app.t3.codes or the mobile app.
**Mobile** is a React native app for both iOS and Android. The mobile app allows for connecting to any T3 Code server to control work remotely. It is still in early access (Testflight), but it is pretty close to shipping globally.
## A note from Theo
I like ambitious ideas, simple systems, and software that feels obvious. Do not preserve complexity just because it already exists. Do not introduce machinery because it looks architecturally impressive. Understand the real constraint, then fight for the smallest model that makes the correct behavior unsurprising.
Channel both "measure twice, cut once" and "yagni". Fight scope creep. Try to honor the dev's intent in both a minimal and realistic fashion.
The rest of this document is meant to help you navigate the codebase and make changes effectively. Think of these instructions less as "hard rules", more as "good defaults". The developer's preferences should be able to override anything here.
Of note: Most T3 Code contributions will come from T3 Code itself, often controlled remotely. This means you should be careful about accessing data, killing dev servers, and other things that may damage the T3 Code instance that the contributor is using.
## A small glossary
We need to be on the same page with terminology. When communicating, use this language:
- **you** means the agent reading this file and changing T3 Code.
- **we, us, and maintainers** mean Theo, Julius and the people building T3 Code. These are who you are talking to now.
- **user** means the person using T3 Code to direct coding agents.
- **agent** means the coding agent a user runs inside T3 Code. Depending on context, that may also include you.
- **provider** means the agent runtime or harness T3 Code talks to, such as Codex, Claude, Cursor, or OpenCode.
- **client** means the web, desktop, or mobile UI.
- **environment** means one running T3 server and the machine, filesystem, provider credentials, and state it owns.
- **project** means an environment-local workspace record rooted at a directory.
- **thread** means the durable conversation and work history for a project.
- **turn** means one user-to-agent cycle, including follow-up work such as checkpointing.
- **T3 home** means the base data directory. Runtime state normally lives below its userdata directory.
## The three ways to hurt yourself
1. **Killing by pattern.** Never `pkill -f`, `pgrep | kill`, or `kill` a PID you found by matching a name, path, or worktree string. Your own agent process has this worktree's path in its argv, and this machine runs several other dev servers at once. Kill only a PID you captured at spawn, or the owner of your port from `ss -H -ltnp` after confirming `/proc/<pid>/cwd` is your worktree.
2. **Touching the live install.** `~/.t3/userdata` is the developer's real T3 Code database, in use while you work. Read-only inspection is fine. Never start a server against it, never open it read-write, never clean it up.
3. **Baking in origins.** Never set `VITE_HTTP_URL` or `VITE_WS_URL` for dev. Dev is single-origin and Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known`. Setting them bakes localhost into the bundle and silently breaks every remote browser.
## Hit every surface
The most common defect in this repo is a change that works on the path you tested and is missing everywhere else. Before calling frontend work done, walk this list and say which entries applied:
- **Entry points.** A behavior reachable from the chat view is usually also reachable from Settings, the command palette, and a keybinding. Fixing one is not fixing the feature.
- **Clients.** Web, desktop (wraps web, adds Electron shell/IPC), and mobile (React Native, separate navigation). Shared logic lives in `packages/client-runtime`
- **Providers.** Codex, Claude, Cursor, Grok, and OpenCode each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here".
- **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow.
- **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug.
- **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real.
- **Docs.** `docs/` mirrors this structure. Behavior changes that a user would notice belong in `docs/user/`; architecture changes in `docs/architecture/`; new vocabulary in `docs/reference/encyclopedia.md`.
## Dev servers
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
- `--share` publishes over the tailnet. Do not open the URL when you use this, just send it to the user with the pairing code included in url
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to.
- Stop what you started, by the PID you tracked. See rule 1.
## Test data
An empty database is a bad test. Seed your worktree's `.t3` instead of pointing at live state:
- Copy from `~/.t3/dev`, never from `~/.t3/userdata`.
- Copy `state.sqlite` together with its `-wal` and `-shm` siblings, and only while no server has the source open. A live copy is a corrupt copy.
- Bring `secrets` and `settings.json` only if the flow under test needs them.
- Copy in, never symlink. Data flows one way: into your sandbox, never back out.
## Verifying
- Smallest proof that the change works. `vp test run <files>` for the tests you touched, targeted lint and typecheck for the scope you changed.
- **Do not run repo-wide checks.** No `vp check`, no `vp run -r test`, no `vp run -r typecheck` unless I ask. CI owns the full suite.
- Backend behavior changes ship with focused tests for that behavior.
- The server is event-sourced and its async flows emit typed receipts. Wait on receipts and worker drains, never on sleeps or polling. A test that needs a timeout to pass is wrong.
- Upon request, user-visible frontend changes should get one integrated pass in a real client: `test-t3-app` for web, `test-t3-mobile` for mobile. The primary agent does this once after integrating. Subagents do not launch their own dev servers. Ask permission before doing computer use or spinning up browsers.
## Pull requests
- Never make a PR unless the developer explicitly asks you to do so.
- Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`.
- Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work.
- **Rebase onto latest main before opening.** Stale branches conflict and burn a review round.
- UI changes need before/after images. Motion or timing needs a short video.
- One concern per PR. If the description says "also", split it.
- When babysitting: poll checks and comments newer than the last push, verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit.
## How it works
Clients send typed WebSocket requests. The server turns them into _commands_, a pure _decider_ turns commands into persisted _events_, and a _projector_ derives the read model the UI renders. Provider CLIs run as subprocesses; per-provider _adapters_ translate their native protocols into orchestration events. Side effects run in queue-backed _reactors_ that emit _receipts_ when milestones land. Each turn ends with a _checkpoint_, a hidden git ref, so the app can diff and restore.
Full glossary with file links: `docs/reference/encyclopedia.md`
## Where code lives
- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` and `docs/operations/effect-fn-checklist.md` before writing Effect code.
- `apps/web` - React/Vite UI. `apps/desktop` wraps it, `apps/mobile` is React Native, `apps/marketing` is the site.
- `packages/contracts` - Effect/Schema contracts. Schema only, no runtime logic.
- `packages/shared` - shared runtime utils, subpath exports, no barrel.
- `packages/client-runtime` - client code shared by web and mobile.
- `.repos/` - vendored read-only references. Prefer their patterns over invented ones. Never edit or import from them. Sync with `vpr sync:repos` when bumping the matching dependency.
## Taste
- Complexity belongs at the adapter boundary. Orchestration stays pure, UI stays dumb.
- Inferred types over annotations. `any` is the enemy.
- Comments describe how a thing is used, and move when the code moves. To be used mostly to describe functions, not to annotate every line of behavior.
- Our users drive agents all day and notice a dropped frame, a lying spinner, and a stale label. No continuously repainting animations; they peg the GPU on high-refresh displays.
- If a rule here fights the task in front of you, say so loudly and get a human sign-off before breaking it.
## Additional tips
- Don't verify with browsers or computer use unless the user explicitly agrees or requests it.
- Security is important, but should not be over-indexed on, especially for dev mode/maintainer-only features.
- Prefer examples and patterns from the vendored source code over generated guesses or web search results.
- Do not edit files under `.repos/` unless explicitly asked.
- Do not import from `.repos/`; application code must continue importing from normal package dependencies.
- Manage vendored subtrees with `vpr sync:repos`; use `vpr sync:repos --repo <id>` to sync one configured repository.
- When updating a dependency with a configured vendored subtree, sync that subtree in the same change so
`.repos/` matches the installed dependency version.
- When writing Effect code, read `.repos/effect-smol/LLMS.md` first and inspect `.repos/effect-smol/` for
examples of idiomatic usage, tests, module structure, and API design.
- When writing relay infrastructure code with Alchemy, inspect `.repos/alchemy-effect/` for examples of
idiomatic usage, tests, module structure, and API design.
+5 -17
View File
@@ -1,36 +1,24 @@
# T3 Code
T3 Code is an "agent harness control surface". It enables control of the agents on your machine with a best-in-class mobile app, [web app](https://app.t3.codes) and [Electron-based desktop app](https://t3.codes).
Works with your subscriptions on Claude Code, Codex, Cursor, Grok Build, and OpenCode. If they're set up on your computer, T3 Code can control them.
## "Wait, what are you selling me?"
Nothing. We built T3 Code because we wanted the best possible development experience with agents. We were inspired by existing solutions like the Codex desktop app, Conductor, Claude Desktop and Cursor Glass, but none met our bar.
We wanted something performant, remote-ready, and truly open. If we ever go the wrong direction, we want you to have everything you need to fork and build the editor that you want.
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
## Installation
> [!WARNING]
> T3 Code currently supports Codex, Claude, Cursor, Grok Build and OpenCode. Install and authenticate at least one provider before use:
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login`
> - Grok Build: install [Grok Build CLI](https://x.ai/cli) and run `grok login`
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
### Try it out (install-free)
The easiest way to test T3 Code is to run the server in your terminal:
### Run without installing
```bash
npx t3@latest
```
This will launch T3 Code's backend on your machine as well as the local web app to control your agents.
Tip: Use `npx t3@latest --help` for the full CLI reference.
### Desktop app
@@ -59,7 +47,7 @@ yay -S t3code-bin
We are very very early in this project. Expect bugs.
We are (mostly) not accepting contributions yet. Small fixes may be considered. Big features will not be.
We are not accepting contributions yet.
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
@@ -42,12 +42,6 @@ function makeDatabase() {
removed.push(id);
values.delete(id);
}),
clearCacheKind: (environmentId, kind) =>
Effect.sync(() => {
for (const key of values.keys()) {
if (key.startsWith(`${environmentId}:${kind}:`)) values.delete(key);
}
}),
clearEnvironmentCache: (environmentId) =>
Effect.sync(() => {
for (const key of values.keys()) {
@@ -86,36 +80,6 @@ describe("mobile SQLite environment cache store", () => {
}),
);
it.effect("removes one persisted VCS ref snapshot", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
yield* store.removeVcsRefs(ENVIRONMENT_ID, "/repo");
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
expect(memory.removed).toContain(cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo"));
}),
);
it.effect("clears every persisted VCS ref snapshot in one environment", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
const otherEnvironmentId = EnvironmentId.make("environment-2");
yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo-worktree", REFS);
yield* store.saveVcsRefs(otherEnvironmentId, "/repo", REFS);
yield* store.clearVcsRefs(ENVIRONMENT_ID);
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo-worktree")).toEqual(Option.none());
expect(yield* store.loadVcsRefs(otherEnvironmentId, "/repo")).toEqual(Option.some(REFS));
}),
);
it.effect("clears one environment without touching another", () =>
Effect.gen(function* () {
const memory = makeDatabase();
@@ -223,16 +223,6 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
.pipe(Effect.mapError(mapDatabaseError("save-vcs-refs")));
},
),
removeVcsRefs: Effect.fn("MobileEnvironmentCache.removeVcsRefs")((environmentId, cwd) =>
database
.removeCache(environmentId, "vcs-refs", cwd)
.pipe(Effect.mapError(mapDatabaseError("remove-vcs-refs"))),
),
clearVcsRefs: Effect.fn("MobileEnvironmentCache.clearVcsRefs")((environmentId) =>
database
.clearCacheKind(environmentId, "vcs-refs")
.pipe(Effect.mapError(mapDatabaseError("clear-vcs-refs"))),
),
clear: Effect.fn("MobileEnvironmentCache.clear")((environmentId) =>
database
.clearEnvironmentCache(environmentId)
@@ -13,7 +13,6 @@ function makeProject(
return {
workspaceRoot: `/workspaces/${input.id}`,
repositoryIdentity: null,
agentInstanceId: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-01T00:00:00.000Z",
@@ -3,7 +3,6 @@ import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useEffect, useMemo, useState } from "react";
import { selectWorkspaceProjects } from "../../lib/repositoryGroups";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
@@ -60,12 +59,10 @@ export function HomeRouteScreen() {
} = useHomeListOptions(availableEnvironmentIds);
const selectedEnvironmentId = listOptions.selectedEnvironmentId;
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
// Filter menu = picker: agent projects are excluded here, while the thread
// list below still receives the full list so agent threads stay visible.
const projectFilterOptions = useMemo(
() =>
buildHomeProjectScopes({
projects: selectWorkspaceProjects(projects),
projects,
environmentId: selectedEnvironmentId,
projectGroupingMode: listOptions.projectGroupingMode,
}).map((scope) => ({
+109 -128
View File
@@ -24,7 +24,6 @@ import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { selectWorkspaceProjects } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
@@ -37,13 +36,12 @@ import {
ThreadListRow,
ThreadListShowMoreRow,
} from "../threads/thread-list-items";
import { ThreadListV2PendingRow, ThreadListV2Row } from "../threads/thread-list-v2-items";
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
import {
buildThreadListV2Items,
buildThreadListV2ListItems,
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
type ThreadListV2ListItem,
type ThreadListV2Item,
} from "../threads/threadListV2";
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
import {
@@ -551,100 +549,50 @@ export function HomeScreen(props: HomeScreenProps) {
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
// range) the boundary string is identical and the chain would die.
}, [nextSnoozeWakeAt, snoozeWakeTick]);
// Queued tasks are not thread shells, so the v2 partition never sees them;
// they are spliced in below the active block and stay visible and deletable
// while their environment is offline. Same environment scope and search
// filter as the list itself.
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
const v2PendingTasks = useMemo(
() =>
props.pendingTasks.filter(
(pendingTask) =>
(props.selectedEnvironmentId === null ||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
(v2ScopedProjectKeys === null ||
v2ScopedProjectKeys.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
)) &&
(v2SearchQuery.length === 0 ||
pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
),
[props.pendingTasks, props.selectedEnvironmentId, v2ScopedProjectKeys, v2SearchQuery],
);
const threadListV2Items = useMemo(
() =>
buildThreadListV2ListItems({
items: threadListV2Layout.items,
pendingTasks: v2PendingTasks,
}),
[threadListV2Layout.items, v2PendingTasks],
);
const threadListV2Items = threadListV2Layout.items;
const renderV2Item = useCallback(
({ item }: { readonly item: ThreadListV2ListItem }) => {
if (item.type === "v2-pending") {
const pendingScopeKey = scopedProjectKey(
item.pendingTask.message.environmentId,
item.pendingTask.creation.projectId,
);
return (
<ThreadListV2PendingRow
pendingTask={item.pendingTask}
project={projectByKey.get(pendingScopeKey) ?? null}
projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
environmentLabel={
Object.keys(props.savedConnectionsById).length > 1
? (props.savedConnectionsById[item.pendingTask.message.environmentId]
?.environmentLabel ?? null)
: null
}
showPendingDivider={item.showPendingDivider}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
);
}
const thread = item.item.thread;
return (
<ThreadListV2Row
thread={thread}
variant={item.item.variant}
showSettledDivider={item.item.showSettledDivider}
project={
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
}
projectTitle={v2ProjectTitleByProjectKey.get(
scopedProjectKey(thread.environmentId, thread.projectId),
)}
providerDriver={
serverConfigs
.get(thread.environmentId)
?.providers.find(
(provider) =>
provider.instanceId ===
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
)?.driver ?? null
}
environmentLabel={
Object.keys(props.savedConnectionsById).length > 1
? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
: null
}
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={handleSettleThread}
onUnsettleThread={handleUnsettleThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
);
},
({ item }: { readonly item: ThreadListV2Item }) => (
<ThreadListV2Row
thread={item.thread}
variant={item.variant}
showSettledDivider={item.showSettledDivider}
project={
projectByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
null
}
projectTitle={v2ProjectTitleByProjectKey.get(
scopedProjectKey(item.thread.environmentId, item.thread.projectId),
)}
providerDriver={
serverConfigs
.get(item.thread.environmentId)
?.providers.find(
(provider) =>
provider.instanceId ===
(item.thread.session?.providerInstanceId ?? item.thread.modelSelection.instanceId),
)?.driver ?? null
}
environmentLabel={
Object.keys(props.savedConnectionsById).length > 1
? (props.savedConnectionsById[item.thread.environmentId]?.environmentLabel ?? null)
: null
}
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
settlementSupported={settlementEnvironmentIds.has(item.thread.environmentId)}
onSettleThread={handleSettleThread}
onUnsettleThread={handleUnsettleThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
projectCwdByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
null
}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
),
[
handleChangeRequestState,
handleDeleteThread,
@@ -655,8 +603,6 @@ export function HomeScreen(props: HomeScreenProps) {
projectByKey,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
props.onSelectPendingTask,
props.onSelectThread,
props.savedConnectionsById,
serverConfigs,
@@ -664,7 +610,10 @@ export function HomeScreen(props: HomeScreenProps) {
v2ProjectTitleByProjectKey,
],
);
const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
const v2KeyExtractor = useCallback(
(item: ThreadListV2Item) => `${item.thread.environmentId}:${item.thread.id}`,
[],
);
const extraData = useMemo(
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
@@ -774,9 +723,7 @@ export function HomeScreen(props: HomeScreenProps) {
const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState);
const emptyState = deriveEmptyState({
catalogState: props.catalogState,
// "No projects found" counts real workspaces: a synthetic agent project
// is not something the user added, so it must not suppress the hint.
projectCount: selectWorkspaceProjects(props.projects).length,
projectCount: props.projects.length,
});
const connectionStatus =
shouldShowConnectionStatus && Platform.OS !== "ios" ? (
@@ -841,9 +788,41 @@ export function HomeScreen(props: HomeScreenProps) {
</>
);
// v2 renders queued offline tasks above the thread cards — they are not
// thread shells, so the v2 item builder never sees them, but they must
// stay visible and deletable while their environment is offline. They
// respect the same environment scope and search filter as the list.
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
const v2PendingTasks = props.pendingTasks.filter(
(pendingTask) =>
(props.selectedEnvironmentId === null ||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
(v2ScopedProjectKeys === null ||
v2ScopedProjectKeys.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
)) &&
(v2SearchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
);
// Project scoping lives in the header filter menu (no inline chip row on
// mobile — the menu is the one filter surface).
const v2ListHeader = listHeader;
const v2ListHeader = (
<>
{listHeader}
{v2PendingTasks.map((pendingTask, index) => (
<PendingTaskListRow
key={pendingTask.message.messageId}
variant="compact"
pendingTask={pendingTask}
environmentLabel={
props.savedConnectionsById[pendingTask.message.environmentId]?.environmentLabel ?? null
}
isLast={index === v2PendingTasks.length - 1}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
))}
</>
);
const listEmpty = !hasResults ? (
hasSearchQuery ? (
@@ -867,33 +846,37 @@ export function HomeScreen(props: HomeScreenProps) {
// is empty. Search outranks the scope — "No results" names the actionable
// fact when a query is active. Snoozed threads outrank the rest: "No
// threads yet" over an inbox that is merely all-snoozed reads as data
// loss.
// loss. Pending tasks render in the header, so the list showing them
// isn't empty in the user's eyes.
const v2SnoozedCount = threadListV2Layout.snoozedCount;
const v2ListEmpty = hasSearchQuery ? (
v2SnoozedCount > 0 ? (
// The snoozed threads already passed this search filter: "No
// results" would claim nothing matched when matches are merely
// parked.
const v2ListEmpty =
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
v2SnoozedCount > 0 ? (
// The snoozed threads already passed this search filter: "No
// results" would claim nothing matched when matches are merely
// parked.
<EmptyState
title={
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
}
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
/>
) : (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
)
) : v2SnoozedCount > 0 ? (
<EmptyState
title={v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`}
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
detail="Snoozed threads return when their wake time passes."
/>
) : v2ScopedProjectGroup !== null ? (
<EmptyState
title={`No threads in ${v2ScopedProjectGroup.title}`}
detail="Choose another project or create a new task."
/>
) : (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
)
) : v2SnoozedCount > 0 ? (
<EmptyState
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
detail="Snoozed threads return when their wake time passes."
/>
) : v2ScopedProjectGroup !== null ? (
<EmptyState
title={`No threads in ${v2ScopedProjectGroup.title}`}
detail="Choose another project or create a new task."
/>
) : (
listEmpty
);
listEmpty
);
if (threadListV2Enabled) {
return (
@@ -905,8 +888,6 @@ export function HomeScreen(props: HomeScreenProps) {
keyExtractor={v2KeyExtractor}
extraData={{
projectByKey,
projectCwdByKey,
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
serverConfigs,
savedConnectionsById: props.savedConnectionsById,
}}
@@ -25,7 +25,6 @@ function makeProject(id: string, title: string): EnvironmentProject {
title,
workspaceRoot: `/workspaces/${id}`,
repositoryIdentity: null,
agentInstanceId: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-01T00:00:00.000Z",
@@ -17,7 +17,6 @@ function makeProject(
return {
workspaceRoot: `/workspaces/${input.id}`,
repositoryIdentity: null,
agentInstanceId: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-01T00:00:00.000Z",
@@ -56,11 +56,6 @@ export function buildHomeProjectScopes(input: {
readonly environmentId: EnvironmentId | null;
readonly projectGroupingMode: SidebarProjectGroupingMode;
}): ReadonlyArray<HomeProjectScope> {
// NOTE: agent projects are deliberately *not* filtered here. This builder
// feeds both the project filter menu (a picker — callers pass an
// agent-free list, see `selectWorkspaceProjects`) and the thread list
// itself. Excluding agent projects here would silently drop every agent
// thread from mobile, which has no Agents surface to show them in instead.
const projects = input.projects.filter(
(project) => input.environmentId === null || project.environmentId === input.environmentId,
);
@@ -310,9 +305,6 @@ export function buildHomeThreadGroups(input: {
workspaceRoot:
pendingTask.creation.projectCwd ?? String(pendingTask.creation.projectId),
repositoryIdentity: null,
// A queued task always targets a real workspace; agent projects
// never enqueue through this path.
agentInstanceId: null,
defaultModelSelection: null,
scripts: [],
createdAt: pendingTask.message.createdAt,
@@ -10,16 +10,16 @@ import {
sortAddProjectProviderSources,
type AddProjectRemoteSource,
} from "@t3tools/client-runtime/operations/projects";
import {
canPreloadBrowsePath,
createBrowseNavigationCoordinator,
filterFilesystemBrowseEntries,
getFilesystemBrowsePath,
} from "@t3tools/client-runtime/state/filesystem";
import {
appendBrowsePathSegment,
canNavigateUp,
ensureBrowseDirectoryPath,
getBrowseDirectoryPath,
getBrowseLeafPathSegment,
getBrowseParentPath,
hasTrailingPathSeparator,
inferProjectTitleFromPath,
isFilesystemBrowseQuery,
} from "@t3tools/client-runtime/state/projects";
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
import { StackActions, useNavigation } from "@react-navigation/native";
@@ -32,7 +32,6 @@ import * as Cause from "effect/Cause";
import * as Order from "effect/Order";
import { AsyncResult } from "effect/unstable/reactivity";
import { cn } from "../../lib/cn";
import { selectWorkspaceProjects } from "../../lib/repositoryGroups";
import { useProjects, useServerConfigs } from "../../state/entities";
import { filesystemEnvironment } from "../../state/filesystem";
@@ -46,10 +45,7 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { uuidv4 } from "../../lib/uuid";
import { useAtomCommand } from "../../state/use-atom-command";
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
import {
useRemoteEnvironmentRuntime,
useSavedRemoteConnections,
} from "../../state/use-remote-environment-registry";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
interface EnvironmentOption {
readonly environmentId: EnvironmentId;
@@ -65,6 +61,11 @@ const environmentOptionOrder = Order.mapInput(
(environment: EnvironmentOption) => ({ label: environment.label }),
);
const browseEntryOrder = Order.mapInput(
Order.String,
(entry: { readonly name: string }) => entry.name,
);
function platformFromOs(os: string | null | undefined): string {
if (os === "windows") return "Win32";
if (os === "darwin") return "MacIntel";
@@ -227,63 +228,6 @@ function ProjectPathInput(props: {
);
}
function useBrowsePathInput(environment: EnvironmentOption | null) {
const [pathInput, commitPathInput] = useState(() =>
getAddProjectInitialQuery(environment?.baseDirectory),
);
const environmentRuntime = useRemoteEnvironmentRuntime(environment?.environmentId ?? null);
const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
reportFailure: false,
reportDefect: false,
});
const [browseNavigation] = useState(createBrowseNavigationCoordinator);
const [isBrowseNavigating, setIsBrowseNavigating] = useState(false);
const setPathInput = useCallback(
(path: string) => {
browseNavigation.invalidate();
setIsBrowseNavigating(false);
commitPathInput(path);
},
[browseNavigation],
);
const navigateToBrowsePath = useCallback(
async (path: string) => {
setIsBrowseNavigating(true);
const committed = await browseNavigation.run(
async () => {
if (environment && canPreloadBrowsePath(environmentRuntime?.connectionState)) {
await loadBrowsePath({
environmentId: environment.environmentId,
input: { partialPath: path },
});
}
},
() => commitPathInput(path),
);
if (committed) {
setIsBrowseNavigating(false);
}
return committed;
},
[browseNavigation, environment, environmentRuntime?.connectionState, loadBrowsePath],
);
useEffect(() => {
if (environment) {
setPathInput(getAddProjectInitialQuery(environment.baseDirectory));
}
}, [environment, setPathInput]);
useEffect(
() => () => {
browseNavigation.invalidate();
},
[browseNavigation],
);
return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath };
}
function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
const serverConfigByEnvironmentId = useServerConfigs();
const { savedConnectionsById } = useSavedRemoteConnections();
@@ -497,9 +441,7 @@ export function AddProjectSourceScreen() {
function useCreateProject(environment: EnvironmentOption | null) {
const navigation = useNavigation();
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
// Dedupe against real projects only: an agent's synthetic directory should
// never make "add project" bounce the user into an agent thread.
const projects = selectWorkspaceProjects(useProjects());
const projects = useProjects();
return useCallback(
async (workspaceRoot: string) => {
@@ -650,16 +592,22 @@ function FolderBrowser(props: {
readonly environment: EnvironmentOption;
readonly pathInput: string;
readonly setPathInput: (path: string) => void;
readonly navigateToBrowsePath: (path: string) => Promise<boolean>;
}) {
const accentColor = useThemeColor("--color-icon-muted");
const browsePath = useMemo(
() => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
const browseDirectoryPath = useMemo(
() =>
isFilesystemBrowseQuery(props.pathInput, props.environment.platform)
? getBrowseDirectoryPath(props.pathInput)
: "",
[props.environment.platform, props.pathInput],
);
const browseFilterQuery =
browseDirectoryPath.length > 0 && !hasTrailingPathSeparator(props.pathInput)
? getBrowseLeafPathSegment(props.pathInput).toLowerCase()
: "";
const browseInput = useMemo(
() => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
[browsePath.directoryPath],
() => (browseDirectoryPath.length > 0 ? { partialPath: browseDirectoryPath } : null),
[browseDirectoryPath],
);
const browseState = useEnvironmentQuery(
browseInput === null
@@ -669,10 +617,20 @@ function FolderBrowser(props: {
input: browseInput,
}),
);
const { visibleEntries: visibleBrowseEntries } = useMemo(
() => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browsePath.filterQuery),
[browsePath.filterQuery, browseState.data?.entries],
const visibleBrowseEntries = useMemo(
() =>
Arr.sort(
Arr.filter(
browseState.data?.entries ?? [],
(entry) =>
!entry.name.startsWith(".") && entry.name.toLowerCase().startsWith(browseFilterQuery),
),
browseEntryOrder,
),
[browseFilterQuery, browseState.data?.entries],
);
const parentBrowsePath = getBrowseParentPath(browseDirectoryPath);
const canBrowseUpPath = canNavigateUp(browseDirectoryPath);
return (
<>
@@ -684,7 +642,7 @@ function FolderBrowser(props: {
<ActivityIndicator color={accentColor} />
</View>
) : null}
{browsePath.canBrowseUp ? (
{canBrowseUpPath ? (
<ListRow
title=".."
icon={
@@ -698,9 +656,7 @@ function FolderBrowser(props: {
isFirst
right={null}
onPress={() => {
if (browsePath.parentPath) {
void props.navigateToBrowsePath(browsePath.parentPath);
}
if (parentBrowsePath) props.setPathInput(parentBrowsePath);
}}
/>
) : null}
@@ -709,15 +665,15 @@ function FolderBrowser(props: {
key={entry.fullPath}
title={entry.name}
icon={<SymbolView name="folder" size={17} tintColor={accentColor} type="monochrome" />}
isFirst={index === 0 && !browsePath.canBrowseUp}
isFirst={index === 0 && !canBrowseUpPath}
right={null}
onPress={() => {
const nextPath =
browsePath.directoryPath.length > 0
? appendBrowsePathSegment(browsePath.directoryPath, entry.name)
: ensureBrowseDirectoryPath(entry.fullPath);
void props.navigateToBrowsePath(nextPath);
}}
onPress={() =>
props.setPathInput(
browseDirectoryPath.length > 0
? appendBrowsePathSegment(browseDirectoryPath, entry.name)
: ensureBrowseDirectoryPath(entry.fullPath),
)
}
/>
))}
</ListSection>
@@ -728,13 +684,19 @@ function FolderBrowser(props: {
export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
const environment = useEnvironmentFromParam(props.environmentId);
const createProject = useCreateProject(environment);
const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
useBrowsePathInput(environment);
const [pathInput, setPathInput] = useState(() =>
getAddProjectInitialQuery(environment?.baseDirectory),
);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!environment) return;
setPathInput(getAddProjectInitialQuery(environment.baseDirectory));
}, [environment]);
const submitPath = useCallback(async () => {
if (!environment || isBrowseNavigating || isSubmitting) return;
if (!environment || isSubmitting) return;
setError(null);
const resolved = resolveAddProjectPath({
rawPath: pathInput,
@@ -752,7 +714,7 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st
setError(errorMessage(Cause.squash(result.cause)));
}
setIsSubmitting(false);
}, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
}, [createProject, environment, isSubmitting, pathInput]);
return (
<AddProjectShell>
@@ -766,13 +728,12 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st
/>
<PrimaryActionButton
label="Add project"
disabled={isBrowseNavigating || isSubmitting}
disabled={isSubmitting}
onPress={() => void submitPath()}
loading={isSubmitting}
/>
<FolderBrowser
environment={environment}
navigateToBrowsePath={navigateToBrowsePath}
pathInput={pathInput}
setPathInput={setPathInput}
/>
@@ -796,13 +757,19 @@ export function AddProjectDestinationScreen(props: {
const createProject = useCreateProject(environment);
const remoteUrl = stringParam(props.remoteUrl);
const repositoryTitle = stringParam(props.repositoryTitle);
const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
useBrowsePathInput(environment);
const [pathInput, setPathInput] = useState(() =>
getAddProjectInitialQuery(environment?.baseDirectory),
);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!environment) return;
setPathInput(getAddProjectInitialQuery(environment.baseDirectory));
}, [environment]);
const submitPath = useCallback(async () => {
if (!environment || !remoteUrl || isBrowseNavigating || isSubmitting) return;
if (!environment || !remoteUrl || isSubmitting) return;
setError(null);
const resolved = resolveAddProjectPath({
rawPath: pathInput,
@@ -831,15 +798,7 @@ export function AddProjectDestinationScreen(props: {
}
}
setIsSubmitting(false);
}, [
cloneRepository,
createProject,
environment,
isBrowseNavigating,
isSubmitting,
pathInput,
remoteUrl,
]);
}, [cloneRepository, createProject, environment, isSubmitting, pathInput, remoteUrl]);
return (
<AddProjectShell>
@@ -861,13 +820,12 @@ export function AddProjectDestinationScreen(props: {
/>
<PrimaryActionButton
label="Clone project"
disabled={isBrowseNavigating || isSubmitting || !remoteUrl}
disabled={isSubmitting || !remoteUrl}
onPress={() => void submitPath()}
loading={isSubmitting}
/>
<FolderBrowser
environment={environment}
navigateToBrowsePath={navigateToBrowsePath}
pathInput={pathInput}
setPathInput={setPathInput}
/>
@@ -14,7 +14,6 @@ const projects: ReadonlyArray<EnvironmentProject> = [
title: "T3 Code",
workspaceRoot: "/workspace/t3code",
repositoryIdentity: null,
agentInstanceId: null,
defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
scripts: [],
createdAt: "2026-07-16T08:00:00.000Z",
@@ -26,7 +25,6 @@ const projects: ReadonlyArray<EnvironmentProject> = [
title: "React",
workspaceRoot: "/workspace/react",
repositoryIdentity: null,
agentInstanceId: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-07-16T08:00:00.000Z",
@@ -44,7 +44,6 @@ import {
} from "../../state/use-composer-drafts";
import { useProjects } from "../../state/entities";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { selectWorkspaceProjects } from "../../lib/repositoryGroups";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
@@ -74,12 +73,7 @@ export function NewTaskDraftScreen(props: {
/** Durable native share inbox item to merge into this project draft. */
readonly incomingShareId?: string;
}) {
// Filtered wholesale: mobile has no agent surface, so a route (or share
// reservation) pointing at a synthetic agent project should fall through to
// "return to the project picker" rather than open a draft against an empty
// agent directory.
const allProjects = useProjects();
const projects = useMemo(() => selectWorkspaceProjects(allProjects), [allProjects]);
const projects = useProjects();
const createProjectThread = useCreateProjectThread();
const flow = useNewTaskFlow();
const navigation = useNavigation();
@@ -270,12 +264,7 @@ export function NewTaskDraftScreen(props: {
return;
}
// Guard on the *unfiltered* catalog. `projects` drops synthetic agent
// projects, so an agent-only environment is indistinguishable from a
// catalog that has not loaded yet — and a route pointing at an agent
// project then found no directProject, skipped this branch, and left the
// screen on "Loading task" with nothing left to resolve it.
if (allProjects.length > 0) {
if (projects.length > 0) {
// Never fall through to the flow provider's temporary first-project
// default. Return to the picker with the share id intact so the user
// can choose an available destination.
@@ -295,7 +284,6 @@ export function NewTaskDraftScreen(props: {
navigation.dispatch(StackActions.replace("NewTask"));
}, [
allProjects,
logicalProjects,
projects,
props.initialProjectRef,
@@ -21,13 +21,12 @@ import { ControlPillMenu } from "../../components/ControlPill";
import { SymbolView } from "../../components/AppSymbol";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { selectWorkspaceProjects } from "../../lib/repositoryGroups";
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
import { useThemeColor } from "../../lib/useThemeColor";
import { useProjects, useThreadShells } from "../../state/entities";
import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
import { environmentServerConfigsAtom } from "../../state/server";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
import { useWorkspaceState } from "../../state/workspace";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
@@ -63,21 +62,26 @@ import {
ThreadListRow,
ThreadListShowMoreRow,
} from "./thread-list-items";
import { ThreadListV2PendingRow, ThreadListV2Row } from "./thread-list-v2-items";
import { ThreadListV2Row } from "./thread-list-v2-items";
import {
buildThreadListV2Items,
buildThreadListV2ListItems,
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
type ThreadListV2ListItem,
type ThreadListV2Item,
} from "./threadListV2";
/** The sidebar list serves both lists: v1 grouped items or, when the Thread
List v2 beta is on, flat v2 rows with queued tasks spliced in, and a settled
List v2 beta is on, queued offline tasks, flat v2 rows, and a settled
"Show more" pager. */
type SidebarListItem =
| HomeListItem
| ThreadListV2ListItem
| {
readonly type: "v2-pending-task";
readonly key: string;
readonly pendingTask: PendingNewTask;
readonly isLast: boolean;
}
| { readonly type: "v2-thread"; readonly key: string; readonly item: ThreadListV2Item }
| { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
/**
@@ -220,19 +224,13 @@ function ThreadNavigationSidebarPane(
}),
[options.projectGroupingMode, options.selectedEnvironmentId, projects],
);
// The scope list above stays complete so agent threads remain visible and
// scopable; only the *picker* built from it drops agent projects.
const projectFilterOptions = useMemo(
() =>
buildHomeProjectScopes({
projects: selectWorkspaceProjects(projects),
environmentId: options.selectedEnvironmentId,
projectGroupingMode: options.projectGroupingMode,
}).map((scope) => ({
projectScopes.map((scope) => ({
key: scope.key,
label: scope.title,
})),
[options.projectGroupingMode, options.selectedEnvironmentId, projects],
[projectScopes],
);
const projectTitleByProjectKey = useMemo(
() =>
@@ -475,11 +473,11 @@ function ThreadNavigationSidebarPane(
}, [nextSnoozeWakeAt, snoozeWakeTick]);
const listItems = useMemo<readonly SidebarListItem[]>(() => {
if (!threadListV2Enabled) return listLayout.items;
// Queued offline tasks are not thread shells, so the v2 item builder
// never sees them; the shared splice puts them below the active block
// (mirrors the compact Home v2 list) where they stay visible and
// deletable while their environment is offline. Same environment scope
// and search filter as the list.
// Queued offline tasks render above the thread rows (mirrors the
// compact Home v2 list): they are not thread shells, so the v2 item
// builder never sees them, but they must stay visible and deletable
// while their environment is offline. Same environment scope and
// search filter as the list.
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
const v2PendingTasks = pendingTasks.filter(
(pendingTask) =>
@@ -492,10 +490,19 @@ function ThreadNavigationSidebarPane(
(v2SearchQuery.length === 0 ||
pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
);
const items: SidebarListItem[] = buildThreadListV2ListItems({
items: threadListV2Layout.items,
pendingTasks: v2PendingTasks,
});
const items: SidebarListItem[] = v2PendingTasks.map((pendingTask, index) => ({
type: "v2-pending-task" as const,
key: `v2-pending:${pendingTask.message.messageId}`,
pendingTask,
isLast: index === v2PendingTasks.length - 1,
}));
for (const item of threadListV2Layout.items) {
items.push({
type: "v2-thread" as const,
key: scopedThreadKey(item.thread.environmentId, item.thread.id),
item,
});
}
if (threadListV2Layout.hiddenSettledCount > 0) {
items.push({
type: "v2-show-more",
@@ -683,26 +690,13 @@ function ThreadNavigationSidebarPane(
onScroll: handleScroll,
onScrollBeginDrag: handleScrollBeginDrag,
});
// Project shells load after the first rows draw, so the maps they feed have
// to bust the recycler's memoization — otherwise a row keeps the blank
// favicon and fallback title it was first rendered with.
const listExtraData = useMemo(
() => ({
selectedThreadKey: props.selectedThreadKey ?? "",
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
savedConnectionsById,
serverConfigs,
}),
[
props.selectedThreadKey,
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
savedConnectionsById,
serverConfigs,
],
[props.selectedThreadKey, savedConnectionsById, serverConfigs],
);
const sidebarItemsAreEqual = useCallback(
(previous: SidebarListItem, item: SidebarListItem): boolean => {
@@ -717,19 +711,16 @@ function ThreadNavigationSidebarPane(
if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
return previous.hiddenCount === item.hiddenCount;
}
if (previous.type === "v2-pending" && item.type === "v2-pending") {
return (
previous.pendingTask === item.pendingTask &&
previous.showPendingDivider === item.showPendingDivider
);
if (previous.type === "v2-pending-task" && item.type === "v2-pending-task") {
return previous.pendingTask === item.pendingTask && previous.isLast === item.isLast;
}
if (
previous.type === "v2-thread" ||
previous.type === "v2-show-more" ||
previous.type === "v2-pending" ||
previous.type === "v2-pending-task" ||
item.type === "v2-thread" ||
item.type === "v2-show-more" ||
item.type === "v2-pending"
item.type === "v2-pending-task"
) {
return false;
}
@@ -757,29 +748,20 @@ function ThreadNavigationSidebarPane(
const renderListItem = useCallback(
({ item }: { readonly item: SidebarListItem }) => {
switch (item.type) {
case "v2-pending": {
const pendingScopeKey = scopedProjectKey(
item.pendingTask.message.environmentId,
item.pendingTask.creation.projectId,
);
case "v2-pending-task":
return (
<ThreadListV2PendingRow
<PendingTaskListRow
variant="sidebar"
pendingTask={item.pendingTask}
project={projectByKey.get(pendingScopeKey) ?? null}
projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
environmentLabel={
Object.keys(savedConnectionsById).length > 1
? (savedConnectionsById[item.pendingTask.message.environmentId]
?.environmentLabel ?? null)
: null
savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
null
}
pane="sidebar"
showPendingDivider={item.showPendingDivider}
isLast={item.isLast}
onSelectPendingTask={openPendingTask}
onDeletePendingTask={confirmDeletePendingTask}
/>
);
}
case "v2-thread": {
const thread = item.item.thread;
const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
@@ -23,7 +23,7 @@ import type { TurnCommandMetadata } from "../../lib/commandMetadata";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { groupProjectsByRepository, selectWorkspaceProjects } from "../../lib/repositoryGroups";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { appAtomRegistry } from "../../state/atom-registry";
import {
@@ -168,12 +168,7 @@ type NewTaskFlowContextValue = {
const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(null);
export function NewTaskFlowProvider(props: React.PropsWithChildren) {
// Every use of this list is part of choosing a destination for a new task,
// so synthetic agent projects are excluded once, here, rather than at each
// of the environment/project selection sites below. Memoized because the
// downstream grouping/selection memos take it as a dependency.
const allProjects = useProjects();
const projects = useMemo(() => selectWorkspaceProjects(allProjects), [allProjects]);
const projects = useProjects();
const threads = useThreadShells();
const { savedConnectionsById } = useSavedRemoteConnections();
@@ -264,9 +259,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
// fabricated path.
workspaceRoot: creation.projectCwd ?? "",
repositoryIdentity: null,
// A queued task always targets a real workspace; agent projects never
// enqueue through this path.
agentInstanceId: null,
defaultModelSelection: editingPendingTask.modelSelection ?? null,
scripts: [],
createdAt: editingPendingTask.createdAt,
@@ -14,7 +14,6 @@ import { ProviderIcon } from "../../components/ProviderIcon";
import { cn } from "../../lib/cn";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
@@ -69,9 +68,7 @@ const LEGACY_MENU_ACTIONS: MenuAction[] = [
/** Rounded-row radius shared with the v1 sidebar rows. */
const SIDEBAR_V2_ROW_RADIUS = 12;
/** Section label + rule: the only structure in an otherwise flat list. */
export const ThreadListV2SectionDivider = memo(function ThreadListV2SectionDivider(props: {
readonly label: string;
export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivider(props: {
readonly pane?: "screen" | "sidebar";
}) {
const borderColor = useThemeColor("--color-border");
@@ -82,127 +79,12 @@ export const ThreadListV2SectionDivider = memo(function ThreadListV2SectionDivid
props.pane === "sidebar" ? "px-3" : "px-5",
)}
>
<Text className="text-xs font-t3-medium text-foreground-tertiary">{props.label}</Text>
<Text className="text-xs font-t3-medium text-foreground-tertiary">Settled</Text>
<View className="h-px flex-1" style={{ backgroundColor: borderColor }} />
</View>
);
});
const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
/**
* A queued new task, in the same idiom as an active v2 row: it is work the
* user wrote, so it reads like the threads it will become. "Queued" takes
* the status slot — the state is the one thing that differs — and stays
* uncolored because nothing is asked of the user; the environment is simply
* not reachable yet.
*/
export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props: {
readonly pendingTask: PendingNewTask;
readonly project: EnvironmentProject | null;
readonly projectTitle?: string;
readonly environmentLabel: string | null;
readonly pane?: "screen" | "sidebar";
/** Draws the "Pending" divider above the first queued row. */
readonly showPendingDivider: boolean;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
}) {
const { pendingTask, onSelectPendingTask, onDeletePendingTask } = props;
const drawerColor = useThemeColor("--color-drawer");
const pressedBackgroundColor = useThemeColor("--color-subtle");
const sidebarPane = props.pane === "sidebar";
const projectTitle =
props.projectTitle ?? props.project?.title ?? pendingTask.creation.projectTitle ?? "";
const branch = pendingTask.creation.branch;
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "delete") onDeletePendingTask(pendingTask);
},
[onDeletePendingTask, pendingTask],
);
const rowContent = (
<>
<View className="flex-row items-center gap-1.5">
{props.project ? (
<ProjectFavicon
environmentId={pendingTask.message.environmentId}
size={15}
projectTitle={projectTitle}
workspaceRoot={props.project.workspaceRoot}
/>
) : null}
<Text className="flex-1 text-sm font-t3-medium text-foreground-muted" numberOfLines={1}>
{projectTitle}
</Text>
<Text className="text-xs text-foreground-tertiary">Queued</Text>
</View>
{/* One line, unlike the two an active row allows: a queued title is
derived from the whole prompt rather than written as a title, so the
second line is usually a stray word or emoji rather than meaning. */}
<Text className="mt-1 text-base font-t3-medium text-foreground" numberOfLines={1}>
{pendingTask.title}
</Text>
{branch || props.environmentLabel ? (
<Text className="mt-1 text-xs text-foreground-muted" numberOfLines={1}>
{branch ? (
<Text className="text-xs text-foreground-muted" style={{ fontFamily: MONO_FONT }}>
{branch}
</Text>
) : null}
{branch && props.environmentLabel ? " · " : null}
{props.environmentLabel ? (
<Text className="text-xs text-foreground-tertiary">{props.environmentLabel}</Text>
) : null}
</Text>
) : null}
</>
);
return (
<>
{props.showPendingDivider ? (
<ThreadListV2SectionDivider label="Pending" pane={props.pane} />
) : null}
<ControlPillMenu
actions={PENDING_TASK_MENU_ACTIONS}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
>
<Pressable
accessibilityHint="Opens the queued task for editing"
accessibilityLabel={pendingTask.title}
accessibilityRole="button"
onPress={() => onSelectPendingTask(pendingTask)}
style={
sidebarPane
? ({ pressed }) => ({
backgroundColor: pressed ? pressedBackgroundColor : drawerColor,
borderRadius: SIDEBAR_V2_ROW_RADIUS,
paddingHorizontal: 12,
paddingVertical: 10,
})
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
}
>
{sidebarPane ? (
rowContent
) : (
<View className="bg-screen">
<View className="px-5 py-2.5">{rowContent}</View>
<View className="ml-5 h-px bg-border-subtle" />
</View>
)}
</Pressable>
</ControlPillMenu>
</>
);
});
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly thread: EnvironmentThreadShell;
readonly variant: "card" | "slim";
@@ -541,9 +423,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
return (
<>
{props.showSettledDivider ? (
<ThreadListV2SectionDivider label="Settled" pane={props.pane} />
) : null}
{props.showSettledDivider ? <ThreadListV2SettledDivider pane={props.pane} /> : null}
<ThreadSwipeable
backgroundColor={sidebarPane ? drawerColor : screenColor}
compactActions={variant === "slim"}
@@ -1,19 +1,9 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import {
CommandId,
EnvironmentId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import {
buildThreadListV2Items,
buildThreadListV2ListItems,
resolveThreadListV2Enabled,
resolveThreadListV2Status,
sortThreadsForListV2,
@@ -350,88 +340,3 @@ describe("buildThreadListV2Items settled paging", () => {
]);
});
});
function makePendingTask(id: string): PendingNewTask {
return {
message: {
environmentId,
threadId: ThreadId.make(`thread-${id}`),
messageId: MessageId.make(id),
commandId: CommandId.make(`command-${id}`),
text: id,
attachments: [],
createdAt: NOW,
creation: {
projectId: ProjectId.make("project-1"),
workspaceMode: "worktree",
branch: null,
worktreePath: null,
},
},
creation: {
projectId: ProjectId.make("project-1"),
workspaceMode: "worktree",
branch: null,
worktreePath: null,
},
title: id,
};
}
describe("buildThreadListV2ListItems", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "active" }),
makeThread({
id: ThreadId.make("settled"),
title: "settled",
settledOverride: "settled",
settledAt: NOW,
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
it("splices queued tasks between the active block and the settled tail", () => {
const items = buildThreadListV2ListItems({
items: layout.items,
pendingTasks: [makePendingTask("queued-1"), makePendingTask("queued-2")],
});
expect(
items.map((item) =>
item.type === "v2-pending" ? item.pendingTask.title : item.item.thread.id,
),
).toEqual(["active", "queued-1", "queued-2", "settled"]);
// Only the leading queued row labels the section, exactly like Settled.
expect(
items.filter((item) => item.type === "v2-pending" && item.showPendingDivider),
).toHaveLength(1);
});
it("ends the list with queued tasks when nothing has settled yet", () => {
const activeOnly = buildThreadListV2Items({
threads: [makeThread({ id: ThreadId.make("active"), title: "active" })],
environmentId: null,
searchQuery: "",
now: NOW,
});
const items = buildThreadListV2ListItems({
items: activeOnly.items,
pendingTasks: [makePendingTask("queued-1")],
});
expect(items.map((item) => item.type)).toEqual(["v2-thread", "v2-pending"]);
});
it("leaves the thread order untouched when nothing is queued", () => {
const items = buildThreadListV2ListItems({ items: layout.items, pendingTasks: [] });
expect(items.map((item) => item.key)).toEqual([
`v2-thread:${environmentId}:active`,
`v2-thread:${environmentId}:settled`,
]);
});
});
@@ -2,8 +2,6 @@ import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/stat
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
/**
* Thread List v2 model, ported from the web sidebar v2
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
@@ -115,60 +113,6 @@ export interface ThreadListV2Layout {
readonly nextSnoozeWakeAt: string | null;
}
export interface ThreadListV2ThreadListItem {
readonly type: "v2-thread";
readonly key: string;
readonly item: ThreadListV2Item;
}
export interface ThreadListV2PendingListItem {
readonly type: "v2-pending";
readonly key: string;
readonly pendingTask: PendingNewTask;
/** First queued row after the active block draws the PENDING divider. */
readonly showPendingDivider: boolean;
}
export type ThreadListV2ListItem = ThreadListV2ThreadListItem | ThreadListV2PendingListItem;
/**
* Splices queued tasks between the active block and the settled tail, so the
* list reads active → pending → settled. Queued work sits below the live
* threads because nothing can happen to it until its environment returns:
* it is waiting, not asking. Shared by the compact Home list and the iPad
* sidebar so both order and label the sections identically.
*/
export function buildThreadListV2ListItems(input: {
readonly items: ReadonlyArray<ThreadListV2Item>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
}): ThreadListV2ListItem[] {
const threadItems = input.items.map(
(item): ThreadListV2ListItem => ({
type: "v2-thread",
key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
item,
}),
);
if (input.pendingTasks.length === 0) return threadItems;
const pendingItems = input.pendingTasks.map(
(pendingTask, index): ThreadListV2ListItem => ({
type: "v2-pending",
key: `v2-pending:${pendingTask.message.messageId}`,
pendingTask,
showPendingDivider: index === 0,
}),
);
// The settled tail begins at the row that draws the SETTLED divider; with
// no settled rows the queued block simply ends the list.
const settledStart = threadItems.findIndex(
(entry) => entry.type === "v2-thread" && entry.item.showSettledDivider,
);
return settledStart === -1
? [...threadItems, ...pendingItems]
: [...threadItems.slice(0, settledStart), ...pendingItems, ...threadItems.slice(settledStart)];
}
/**
* Partitions visible threads into the active card block (creation order) and
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
+1 -49
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vite-plus/test";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { groupProjectsByRepository, isAgentProject } from "./repositoryGroups";
import { groupProjectsByRepository } from "./repositoryGroups";
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
function makeProject(
@@ -11,7 +11,6 @@ function makeProject(
return {
workspaceRoot: `/workspaces/${input.id}`,
repositoryIdentity: null,
agentInstanceId: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-04-01T00:00:00.000Z",
@@ -191,50 +190,3 @@ describe("groupProjectsByRepository", () => {
expect(groups[0]?.subtitle).toBeNull();
});
});
describe("agent project exclusion", () => {
const environmentId = EnvironmentId.make("env-local");
const agentInstanceId = ProviderInstanceId.make("hermes_workstation");
it("keeps a project with no reported agent instance", () => {
// Older snapshots omit `agentInstanceId` entirely; that must read as an
// ordinary project, not as an agent.
expect(
isAgentProject(
makeProject({ environmentId, id: ProjectId.make("project-legacy"), title: "Legacy" }),
),
).toBe(false);
});
it("identifies a synthetic agent project", () => {
expect(
isAgentProject(
makeProject({
environmentId,
id: ProjectId.make("project-agent"),
title: "Workstation",
agentInstanceId,
}),
),
).toBe(true);
});
it("omits agent projects from repository groups", () => {
const workspace = makeProject({
environmentId,
id: ProjectId.make("project-real"),
title: "Real",
});
const agent = makeProject({
environmentId,
id: ProjectId.make("project-agent"),
title: "Workstation",
agentInstanceId,
});
const groups = groupProjectsByRepository({ projects: [workspace, agent], threads: [] });
expect(groups).toHaveLength(1);
expect(groups[0]?.projects[0]?.project.id).toBe(workspace.id);
});
});
+1 -25
View File
@@ -58,34 +58,10 @@ function deriveProjectLatestActivity(
return latestThread?.updatedAt ?? latestThread?.createdAt ?? project.updatedAt;
}
/**
* True for the synthetic project row backing an agent instance
* (`OrchestrationProjectShell.agentInstanceId`). Such a row is a legal project
* with a real — but empty — workspace directory, created only so an agent
* thread can satisfy `project_id NOT NULL`. It is never a workspace the user
* chose, so it must not appear in any surface that offers a project to pick.
*/
export function isAgentProject(project: Pick<EnvironmentProject, "agentInstanceId">): boolean {
// `!= null` on purpose: the contract decodes a default of `null`, but an
// older snapshot (or a partial fixture) can omit the field entirely, and
// "not reported" must mean "ordinary project", never "agent".
return project.agentInstanceId != null;
}
/** Drop synthetic agent projects from a list destined for a picker. */
export function selectWorkspaceProjects<
TProject extends Pick<EnvironmentProject, "agentInstanceId">,
>(projects: ReadonlyArray<TProject>): TProject[] {
return projects.filter((project) => !isAgentProject(project));
}
export function groupProjectsByRepository(rawInput: {
export function groupProjectsByRepository(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}): ReadonlyArray<RepositoryGroup> {
// This grouping only ever feeds the "choose a project" screens, so the
// exclusion lives here rather than at each call site.
const input = { ...rawInput, projects: selectWorkspaceProjects(rawInput.projects) };
const threadsByProjectKey = new Map<string, EnvironmentThreadShell[]>();
for (const thread of input.threads) {
@@ -46,7 +46,6 @@ const MobileDatabaseOperation = Schema.Literals([
"load-cache",
"save-cache",
"remove-cache",
"clear-cache-kind",
"clear-environment-cache",
"clear-all-caches",
"inspect-caches",
@@ -204,10 +203,6 @@ export class MobileDatabase extends Context.Service<
kind: ClientCacheKind,
cacheKey: string,
) => Effect.Effect<void, MobileDatabaseError>;
readonly clearCacheKind: (
environmentId: EnvironmentId,
kind: ClientCacheKind,
) => Effect.Effect<void, MobileDatabaseError>;
readonly clearEnvironmentCache: (
environmentId: EnvironmentId,
) => Effect.Effect<void, MobileDatabaseError>;
@@ -327,17 +322,6 @@ const makeAvailable = Effect.gen(function* () {
catch: databaseError("remove-cache"),
}).pipe(Effect.asVoid),
),
clearCacheKind: Effect.fn("MobileDatabase.clearCacheKind")((environmentId, kind) =>
Effect.tryPromise({
try: () =>
database.runAsync(
"DELETE FROM client_cache WHERE environment_id = ? AND kind = ?",
environmentId,
kind,
),
catch: databaseError("clear-cache-kind"),
}).pipe(Effect.asVoid),
),
clearEnvironmentCache: Effect.fn("MobileDatabase.clearEnvironmentCache")((environmentId) =>
Effect.tryPromise({
try: () =>
@@ -408,7 +392,6 @@ function makeUnavailable(error: MobileDatabaseError): MobileDatabase["Service"]
loadCache: () => fail,
saveCache: () => fail,
removeCache: () => fail,
clearCacheKind: () => fail,
clearEnvironmentCache: () => fail,
clearAllCaches: fail,
inspectCaches: fail,
+1 -8
View File
@@ -23,7 +23,6 @@ export type AgentActivityPhase =
| "running"
| "waiting_for_approval"
| "waiting_for_input"
| "notification"
| "completed"
| "failed"
| "stale";
@@ -82,8 +81,6 @@ export function AgentActivity(
return isLightScheme ? "#d97706" : "#fcd34d"; // amber-600 / amber-300
case "waiting_for_input":
return isLightScheme ? "#4f46e5" : "#a5b4fc"; // indigo-600 / indigo-300
case "notification":
return isLightScheme ? "#7c3aed" : "#c4b5fd"; // violet-600 / violet-300
case "failed":
return isLightScheme ? "#dc2626" : "#fca5a5"; // red-600 / red-300
case "completed":
@@ -100,9 +97,7 @@ export function AgentActivity(
const phasePriority = (phase: AgentActivityPhase): number => {
if (phase === "waiting_for_approval" || phase === "waiting_for_input") return 0;
if (phase === "failed") return 1;
// A proactive delivery is unread news, so it outranks finished/stale rows
// but never a human who is actually blocked.
if (phase === "running" || phase === "starting" || phase === "notification") return 2;
if (phase === "running" || phase === "starting") return 2;
return 3;
};
const ordered = [...props.activities].sort(
@@ -168,8 +163,6 @@ export function AgentActivity(
return "exclamationmark.circle.fill";
case "waiting_for_input":
return "questionmark.circle.fill";
case "notification":
return "bell.badge.fill";
case "failed":
return "xmark.octagon.fill";
case "completed":
@@ -76,6 +76,7 @@ import * as WorkspacePaths from "../src/workspace/WorkspacePaths.ts";
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
import { WorktreeService } from "../src/vcs/WorktreeService.ts";
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
import * as AgentAwarenessRelay from "../src/relay/AgentAwarenessRelay.ts";
@@ -379,6 +380,11 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(providerRegistryLayer),
Layer.provide(persistenceLayer),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(
Layer.mock(WorktreeService, {
reviveWorktree: () => Effect.succeed({ revived: false }),
}),
),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
+1 -34
View File
@@ -10,35 +10,7 @@ import {
} from "./attachmentPaths.ts";
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
/**
* Extensions a generic file attachment may take on disk. The extension is
* derived from the declared mime rather than the client-supplied filename —
* the asset route later re-derives the served content type from it, so this
* map is what keeps a video playing as a video and everything unknown pinned
* to inert `.bin`.
*/
const FILE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
"application/gzip": ".gz",
"application/json": ".json",
"application/pdf": ".pdf",
"application/zip": ".zip",
"audio/mpeg": ".mp3",
"audio/ogg": ".ogg",
"audio/wav": ".wav",
"text/csv": ".csv",
"text/markdown": ".md",
"text/plain": ".txt",
"video/mp4": ".mp4",
"video/quicktime": ".mov",
"video/webm": ".webm",
};
const SAFE_FILE_EXTENSIONS = new Set(Object.values(FILE_EXTENSION_BY_MIME_TYPE));
const ATTACHMENT_FILENAME_EXTENSIONS = [
...SAFE_IMAGE_FILE_EXTENSIONS,
...SAFE_FILE_EXTENSIONS,
".bin",
];
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
@@ -91,11 +63,6 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
});
return `${attachment.id}${extension}`;
}
case "file": {
const extension =
FILE_EXTENSION_BY_MIME_TYPE[attachment.mimeType.trim().toLowerCase()] ?? ".bin";
return `${attachment.id}${extension}`;
}
}
}
@@ -86,7 +86,6 @@ describe("CheckpointDiffQuery.layer", () => {
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getActiveAgentProject: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () =>
@@ -107,8 +106,6 @@ describe("CheckpointDiffQuery.layer", () => {
});
}),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
hasThreadNotificationDelivery: () => Effect.succeed(false),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -197,14 +194,11 @@ describe("CheckpointDiffQuery.layer", () => {
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getActiveAgentProject: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
hasThreadNotificationDelivery: () => Effect.succeed(false),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -283,14 +277,11 @@ describe("CheckpointDiffQuery.layer", () => {
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getActiveAgentProject: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
hasThreadNotificationDelivery: () => Effect.succeed(false),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -354,14 +345,11 @@ describe("CheckpointDiffQuery.layer", () => {
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getActiveAgentProject: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
hasThreadNotificationDelivery: () => Effect.succeed(false),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -410,14 +398,11 @@ describe("CheckpointDiffQuery.layer", () => {
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getActiveAgentProject: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
hasThreadNotificationDelivery: () => Effect.succeed(false),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
+1 -1
View File
@@ -1794,7 +1794,7 @@ export const make = Effect.gen(function* () {
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
const findLocalHeadBranch = Effect.fn("findLocalHeadBranch")(function* (cwd: string) {
const result = yield* gitCore.listRefs({ cwd, refresh: true });
const result = yield* gitCore.listRefs({ cwd });
const localBranch = result.refs.find(
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
);
+1 -2
View File
@@ -1,5 +1,4 @@
import { expect, it } from "@effect/vitest";
import { describe } from "vite-plus/test";
import { describe, expect, it } from "vite-plus/test";
import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
-69
View File
@@ -14,7 +14,6 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { cast } from "effect/Function";
import {
Headers,
HttpBody,
HttpClient,
HttpClientResponse,
@@ -30,7 +29,6 @@ import * as ServerConfig from "./config.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
import {
annotateEnvironmentRequest,
@@ -44,73 +42,6 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
const GZIP_MIN_BYTES = 1024;
function acceptsGzip(value: string | undefined): boolean {
if (!value) return false;
const accepted = new Map(
value.split(",").map((entry) => {
const [coding = "", ...parameters] = entry.trim().toLowerCase().split(";");
const quality = parameters
.map((parameter) => parameter.trim().match(/^q=(.+)$/)?.[1])
.find((parameter) => parameter !== undefined);
return [coding, quality === undefined ? 1 : Number(quality)] as const;
}),
);
return (accepted.get("gzip") ?? accepted.get("*") ?? 0) > 0;
}
function varyByAcceptEncoding(value: string | undefined): string {
if (!value) return "Accept-Encoding";
const values = new Set(value.split(",").map((entry) => entry.trim().toLowerCase()));
return values.has("*") || values.has("accept-encoding") ? value : `${value}, Accept-Encoding`;
}
const compressHttpResponse = Effect.fnUntraced(function* (
response: HttpServerResponse.HttpServerResponse,
acceptEncoding: string | undefined,
) {
const body = response.body;
if (
body._tag !== "Uint8Array" ||
body.contentLength < GZIP_MIN_BYTES ||
!body.contentType.startsWith("application/json") ||
response.headers["content-encoding"]
) {
return response;
}
const variedResponse = HttpServerResponse.setHeader(
response,
"vary",
varyByAcceptEncoding(response.headers.vary),
);
if (!acceptsGzip(acceptEncoding)) return variedResponse;
const compression = yield* HttpResponseCompression.HttpResponseCompression;
const headers = Headers.set(
Headers.remove(variedResponse.headers, "content-length"),
"content-encoding",
"gzip",
);
return compression.gzip(body.body, {
status: response.status,
statusText: response.statusText,
headers,
cookies: response.cookies,
contentType: body.contentType,
});
});
export const httpCompressionLayer = HttpRouter.middleware(
(httpEffect) =>
Effect.flatMap(
Effect.all([httpEffect, HttpServerRequest.HttpServerRequest]),
([response, request]) => compressHttpResponse(response, request.headers["accept-encoding"]),
),
{ global: true },
);
export const browserApiCorsLayer = Layer.unwrap(
Effect.gen(function* () {
@@ -1,29 +0,0 @@
import { expect, it } from "@effect/vitest";
import * as NodeStream from "node:stream";
import * as Effect from "effect/Effect";
import * as HttpResponseCompression from "./HttpResponseCompression.ts";
it.effect("uses a native Node stream", () =>
Effect.gen(function* () {
const compression = yield* HttpResponseCompression.HttpResponseCompression;
const response = compression.gzip(new Uint8Array(), {});
expect(response.body._tag).toBe("Raw");
if (response.body._tag === "Raw") {
expect(response.body.body).toBeInstanceOf(NodeStream.Readable);
}
}).pipe(Effect.provide(HttpResponseCompression.layerNode)),
);
it.effect("uses a native Web stream for Bun", () =>
Effect.gen(function* () {
const compression = yield* HttpResponseCompression.HttpResponseCompression;
const response = compression.gzip(new Uint8Array(), {});
expect(response.body._tag).toBe("Raw");
if (response.body._tag === "Raw") {
expect(response.body.body).toBeInstanceOf(ReadableStream);
}
}).pipe(Effect.provide(HttpResponseCompression.layerBun)),
);
@@ -1,36 +0,0 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
export class HttpResponseCompression extends Context.Service<
HttpResponseCompression,
{
readonly gzip: (
body: Uint8Array,
options: HttpServerResponse.Options,
) => HttpServerResponse.HttpServerResponse;
}
>()("t3/httpCompression/HttpResponseCompression") {}
export const layerNode = Layer.effect(
HttpResponseCompression,
Effect.gen(function* () {
const NodeZlib = yield* Effect.promise(() => import("node:zlib"));
return {
gzip: (body, options) => {
const stream = NodeZlib.createGzip();
stream.end(body);
return HttpServerResponse.raw(stream, options);
},
};
}),
);
export const layerBun = Layer.succeed(HttpResponseCompression, {
gzip: (body, options) =>
HttpServerResponse.raw(
new Response(body).body!.pipeThrough(new CompressionStream("gzip")),
options,
),
});
@@ -201,52 +201,6 @@ export function projectActivityPayload(
};
}
/**
* Matches the validity rule in the web client's
* `deriveLatestContextWindowSnapshot`: rows without a finite, non-negative
* `usedTokens` are skipped during its backward walk, so they must not shadow
* an earlier resolvable row here.
*/
function isResolvableContextWindowActivity(activity: OrchestrationThreadActivity): boolean {
if (activity.kind !== "context-window.updated") {
return false;
}
const payload = asRecord(activity.payload);
const usedTokens = payload?.usedTokens;
return typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0;
}
/**
* Drops all but the last resolvable context-window activity per turn from a
* snapshot. Clients only ever read the latest usage value (walking the array
* backwards), so shipping the full history — often thousands of rows on long
* threads — buys nothing. Retention is per turn rather than per thread because
* a live `thread.reverted` makes the client discard whole turns; keeping each
* turn's latest row means the meter can still resolve a value from the turns
* that survive. Malformed rows pass through untouched rather than shadowing a
* valid earlier row. Live `thread.activity-appended` events are untouched:
* newer updates still stream through and supersede the retained rows on the
* client.
*/
function dropStaleContextWindowActivities(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<OrchestrationThreadActivity> {
const latestIndexByTurn = new Map<string | null, number>();
for (let index = 0; index < activities.length; index += 1) {
if (isResolvableContextWindowActivity(activities[index]!)) {
latestIndexByTurn.set(activities[index]!.turnId, index);
}
}
if (latestIndexByTurn.size === 0) {
return activities;
}
return activities.filter(
(activity, index) =>
!isResolvableContextWindowActivity(activity) ||
latestIndexByTurn.get(activity.turnId) === index,
);
}
export function projectThreadDetailSnapshot(
snapshot: OrchestrationThreadDetailSnapshot,
): OrchestrationThreadDetailSnapshot {
@@ -254,9 +208,7 @@ export function projectThreadDetailSnapshot(
...snapshot,
thread: {
...snapshot.thread,
activities: dropStaleContextWindowActivities(snapshot.thread.activities).map(
projectActivityPayload,
),
activities: snapshot.thread.activities.map(projectActivityPayload),
},
};
}
@@ -124,7 +124,6 @@ describe("OrchestrationEngine", () => {
model: "gpt-5-codex",
},
scripts: [],
agentInstanceId: null,
createdAt: "2026-03-03T00:00:00.000Z",
updatedAt: "2026-03-03T00:00:01.000Z",
deletedAt: null,
@@ -173,7 +172,6 @@ describe("OrchestrationEngine", () => {
const layer = OrchestrationEngineLive.pipe(
Layer.provide(
Layer.succeed(ProjectionSnapshotQuery, {
getActiveAgentProject: () => Effect.succeed(Option.none()),
getCommandReadModel: () => Effect.succeed(commandReadModel),
getSnapshot: () =>
Effect.sync(() => {
@@ -203,8 +201,6 @@ describe("OrchestrationEngine", () => {
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
hasThreadNotificationDelivery: () => Effect.succeed(false),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -1429,21 +1429,6 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
assert.deepEqual(settledRows, [
{ state: "completed", completedAt: "2026-01-01T00:01:00.000Z" },
]);
// The session cleared `activeTurnId` because the turn ENDED, not
// because the thread never had one — the pointer must survive.
//
// Nulling it here used to be masked by `thread.turn-diff-completed`,
// which re-writes the id moments later. A workspaceless provider
// (Hermes) emits no diff, so the id stayed null forever, `latestTurn`
// never resolved, and every completed turn read as a queued-but-
// unadopted turn start — which blocks settling for the grace window.
const latestTurnRows = yield* sql<{ readonly latestTurnId: string | null }>`
SELECT latest_turn_id AS "latestTurnId"
FROM projection_threads
WHERE thread_id = ${threadId}
`;
assert.deepEqual(latestTurnRows, [{ latestTurnId: turnId }]);
}),
);
@@ -1667,117 +1652,6 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("replaces an assistant snapshot between legacy appended deltas", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-07-24T12:00:00.000Z";
const projectId = ProjectId.make("project-replacement");
const threadId = ThreadId.make("thread-replacement");
const messageId = MessageId.make("assistant-replacement");
yield* eventStore.append({
type: "project.created",
eventId: EventId.make("evt-replacement-1"),
aggregateKind: "project",
aggregateId: projectId,
occurredAt: now,
commandId: CommandId.make("cmd-replacement-1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-replacement-1"),
metadata: {},
payload: {
projectId,
title: "Project Replacement",
workspaceRoot: "/tmp/project-replacement",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.created",
eventId: EventId.make("evt-replacement-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-replacement-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-replacement-2"),
metadata: {},
payload: {
threadId,
projectId,
title: "Thread Replacement",
modelSelection: {
instanceId: ProviderInstanceId.make("hermes"),
model: "hermes",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
const appendMessage = (input: {
eventNumber: number;
text: string;
streaming: boolean;
textOperation?: "replace";
}) =>
eventStore.append({
type: "thread.message-sent",
eventId: EventId.make(`evt-replacement-${input.eventNumber}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make(`cmd-replacement-${input.eventNumber}`),
causationEventId: null,
correlationId: CorrelationId.make(`cmd-replacement-${input.eventNumber}`),
metadata: {},
payload: {
threadId,
messageId,
role: "assistant",
text: input.text,
turnId: null,
streaming: input.streaming,
...(input.textOperation !== undefined ? { textOperation: input.textOperation } : {}),
createdAt: now,
updatedAt: now,
},
});
yield* appendMessage({ eventNumber: 3, text: "Hello wor", streaming: true });
yield* appendMessage({
eventNumber: 4,
text: "Hello there",
streaming: true,
textOperation: "replace",
});
yield* appendMessage({ eventNumber: 5, text: "!", streaming: true });
yield* appendMessage({ eventNumber: 6, text: "", streaming: false });
yield* projectionPipeline.bootstrap;
const messageRows = yield* sql<{ readonly text: string; readonly isStreaming: unknown }>`
SELECT
text,
is_streaming AS "isStreaming"
FROM projection_thread_messages
WHERE message_id = ${messageId}
`;
assert.equal(messageRows.length, 1);
assert.equal(messageRows[0]?.text, "Hello there!");
assert.isFalse(Boolean(messageRows[0]?.isStreaming));
}),
);
it.effect(
"resolves turn-count conflicts when checkpoint completion rewrites provisional turns",
() =>
@@ -2383,193 +2257,6 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("projects notification deliveries into the message row and shell summary", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
const createdAt = "2026-07-01T09:00:00.000Z";
yield* appendAndProject({
type: "project.created",
eventId: EventId.make("evt-notify-project"),
aggregateKind: "project",
aggregateId: ProjectId.make("project-notify"),
occurredAt: createdAt,
commandId: CommandId.make("cmd-notify-project"),
causationEventId: null,
correlationId: CommandId.make("cmd-notify-project"),
metadata: {},
payload: {
projectId: ProjectId.make("project-notify"),
title: "Hermes",
workspaceRoot: "/tmp/project-notify",
defaultModelSelection: null,
scripts: [],
createdAt,
updatedAt: createdAt,
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.make("evt-notify-thread"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-notify"),
occurredAt: createdAt,
commandId: CommandId.make("cmd-notify-thread"),
causationEventId: null,
correlationId: CommandId.make("cmd-notify-thread"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-notify"),
projectId: ProjectId.make("project-notify"),
title: "Home",
modelSelection: {
instanceId: ProviderInstanceId.make("hermes"),
model: "hermes",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
updatedAt: createdAt,
},
});
const deliveredAt = "2026-07-01T09:05:00.000Z";
yield* appendAndProject({
type: "thread.notification-delivered",
eventId: EventId.make("evt-notify-delivery"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-notify"),
occurredAt: deliveredAt,
commandId: CommandId.make("cmd-notify-delivery"),
causationEventId: null,
correlationId: CommandId.make("cmd-notify-delivery"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-notify"),
messageId: MessageId.make("message-notify"),
text: "Digest ready.",
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
},
createdAt: deliveredAt,
updatedAt: deliveredAt,
},
});
const messageRows = yield* sql<{
readonly messageId: string;
readonly text: string;
readonly turnId: string | null;
readonly role: string;
readonly isStreaming: number;
readonly notification: string | null;
}>`
SELECT
message_id AS "messageId",
text,
turn_id AS "turnId",
role,
is_streaming AS "isStreaming",
notification_json AS "notification"
FROM projection_thread_messages
WHERE thread_id = 'thread-notify'
`;
assert.equal(messageRows.length, 1);
assert.equal(messageRows[0]?.messageId, "message-notify");
assert.equal(messageRows[0]?.turnId, null);
assert.equal(messageRows[0]?.role, "assistant");
assert.equal(messageRows[0]?.isStreaming, 0);
assert.deepEqual(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.parse(messageRows[0]?.notification ?? "null"),
{ kind: "cron", label: "Cron: daily-digest", deliveryId: "delivery-1" },
);
// The shell summary is what the sidebar and the push relay read; the
// provenance is invisible to them unless it is flattened here.
const threadRows = yield* sql<{
readonly updatedAt: string;
readonly latestNotification: string | null;
}>`
SELECT
updated_at AS "updatedAt",
latest_notification_json AS "latestNotification"
FROM projection_threads
WHERE thread_id = 'thread-notify'
`;
assert.equal(threadRows[0]?.updatedAt, deliveredAt);
assert.deepEqual(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.parse(threadRows[0]?.latestNotification ?? "null"),
{ kind: "cron", label: "Cron: daily-digest", deliveredAt },
);
// Media rides the same event: attachments land in attachments_json and
// a turn-scoped delivery keeps its turn id on the row.
const mediaDeliveredAt = "2026-07-01T09:06:00.000Z";
const mediaAttachment = {
type: "file",
id: "thread-notify-2c8b3f1e-0000-4000-8000-000000000001",
name: "chart.mp4",
mimeType: "video/mp4",
sizeBytes: 2_048,
} as const;
yield* appendAndProject({
type: "thread.notification-delivered",
eventId: EventId.make("evt-notify-media"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-notify"),
occurredAt: mediaDeliveredAt,
commandId: CommandId.make("cmd-notify-media"),
causationEventId: null,
correlationId: CommandId.make("cmd-notify-media"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-notify"),
messageId: MessageId.make("message-notify-media"),
text: "A caption",
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-media",
},
attachments: [mediaAttachment],
turnId: TurnId.make("turn-live"),
createdAt: mediaDeliveredAt,
updatedAt: mediaDeliveredAt,
},
});
const mediaRows = yield* sql<{
readonly turnId: string | null;
readonly attachments: string | null;
}>`
SELECT
turn_id AS "turnId",
attachments_json AS "attachments"
FROM projection_thread_messages
WHERE message_id = 'message-notify-media'
`;
assert.equal(mediaRows.length, 1);
assert.equal(mediaRows[0]?.turnId, "turn-live");
assert.deepEqual(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.parse(mediaRows[0]?.attachments ?? "null"),
[mediaAttachment],
);
}),
);
it.effect("does not fallback-retain messages whose turnId is removed by revert", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -1,7 +1,6 @@
import {
ApprovalRequestId,
type ChatAttachment,
mergeAssistantMessageText,
type OrchestrationEvent,
type OrchestrationSessionStatus,
ThreadId,
@@ -34,10 +33,7 @@ import {
type ProjectionTurn,
ProjectionTurnRepository,
} from "../../persistence/Services/ProjectionTurns.ts";
import {
type ProjectionThread,
ProjectionThreadRepository,
} from "../../persistence/Services/ProjectionThreads.ts";
import { ProjectionThreadRepository } from "../../persistence/Services/ProjectionThreads.ts";
import { ProjectionPendingApprovalRepositoryLive } from "../../persistence/Layers/ProjectionPendingApprovals.ts";
import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/ProjectionProjects.ts";
import { ProjectionStateRepositoryLive } from "../../persistence/Layers/ProjectionState.ts";
@@ -342,6 +338,9 @@ function collectThreadAttachmentRelativePaths(
const relativePaths = new Set<string>();
for (const message of messages) {
for (const attachment of message.attachments ?? []) {
if (attachment.type !== "image") {
continue;
}
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
continue;
@@ -497,7 +496,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
workspaceRoot: event.payload.workspaceRoot,
defaultModelSelection: event.payload.defaultModelSelection,
scripts: event.payload.scripts,
agentInstanceId: event.payload.agentInstanceId,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
deletedAt: null,
@@ -564,11 +562,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
]);
let latestUserMessageAt: string | null = null;
// Newest proactive delivery, flattened for shell readers that never load
// messages (sidebar rows, agent awareness). Ties break on message id so
// two deliveries stamped in the same millisecond resolve deterministically.
let latestNotification: ProjectionThread["latestNotification"] = null;
let latestNotificationKey: string | null = null;
for (const message of messages) {
if (
message.role === "user" &&
@@ -576,17 +569,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
) {
latestUserMessageAt = message.createdAt;
}
if (message.notification !== undefined) {
const key = `${message.createdAt}${message.messageId}`;
if (latestNotificationKey === null || key > latestNotificationKey) {
latestNotificationKey = key;
latestNotification = {
kind: message.notification.kind,
label: message.notification.label,
deliveredAt: message.createdAt,
};
}
}
}
const pendingApprovalCount = pendingApprovals.filter(
@@ -604,7 +586,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
pendingApprovalCount,
pendingUserInputCount,
hasActionableProposedPlan: hasActionableProposedPlan ? 1 : 0,
latestNotification,
});
});
@@ -634,7 +615,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
pendingApprovalCount: 0,
pendingUserInputCount: 0,
hasActionableProposedPlan: 0,
latestNotification: null,
deletedAt: null,
});
return;
@@ -802,7 +782,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
case "thread.message-sent":
case "thread.notification-delivered":
case "thread.proposed-plan-upserted":
case "thread.activity-appended":
case "thread.approval-response-requested":
@@ -828,19 +807,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
if (Option.isNone(existingRow)) {
return;
}
// A session clearing `activeTurnId` means the turn ENDED, not that
// the thread never had one — so retain the last known turn instead
// of nulling it. Nulling was survivable only for providers that
// emit `thread.turn-diff-completed`, which re-writes this field
// moments later. A workspaceless provider (Hermes) emits no diff,
// so the id stayed null forever and `latestTurn` never resolved —
// leaving every completed turn looking like a queued-but-unadopted
// turn start, which blocks settling for the whole grace window.
const nextLatestTurnId =
event.payload.session.activeTurnId ?? existingRow.value.latestTurnId;
yield* projectionThreadRepository.upsert({
...existingRow.value,
latestTurnId: nextLatestTurnId,
latestTurnId: event.payload.session.activeTurnId,
updatedAt: event.occurredAt,
});
yield* refreshThreadShellSummary(event.payload.threadId);
@@ -917,14 +886,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
const previousMessage = Option.getOrUndefined(existingMessage);
const nextText = Option.match(existingMessage, {
onNone: () => event.payload.text,
onSome: (message) =>
mergeAssistantMessageText(message.text, {
text: event.payload.text,
streaming: event.payload.streaming,
...(event.payload.textOperation !== undefined
? { textOperation: event.payload.textOperation }
: {}),
}),
onSome: (message) => {
if (event.payload.streaming) {
return `${message.text}${event.payload.text}`;
}
if (event.payload.text.length === 0) {
return message.text;
}
return event.payload.text;
},
});
const nextAttachments =
event.payload.attachments !== undefined
@@ -946,29 +916,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.notification-delivered": {
// No merge accounting: a delivery is written whole, never streamed,
// and a replay re-emits the identical payload (the decider rebuilds
// it from the persisted row), so the upsert is idempotent.
yield* projectionThreadMessageRepository.upsert({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
// Null for proactive deliveries; turn-scoped media names its turn
// so it sequences beside that turn's text.
turnId: event.payload.turnId ?? null,
role: "assistant",
text: event.payload.text,
notification: event.payload.notification,
...(event.payload.attachments !== undefined
? { attachments: [...event.payload.attachments] }
: {}),
isStreaming: false,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.reverted": {
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
threadId: event.payload.threadId,
@@ -275,7 +275,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
runOnWorktreeCreate: false,
},
],
agentInstanceId: null,
createdAt: "2026-02-24T00:00:00.000Z",
updatedAt: "2026-02-24T00:00:01.000Z",
deletedAt: null,
@@ -391,7 +390,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
runOnWorktreeCreate: false,
},
],
agentInstanceId: null,
createdAt: "2026-02-24T00:00:00.000Z",
updatedAt: "2026-02-24T00:00:01.000Z",
},
@@ -441,7 +439,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
hasPendingApprovals: true,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
latestNotification: null,
},
]);
@@ -1552,128 +1549,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
assert.equal(shellSnapshot.threads.length, 0);
}),
);
it.effect("finds a notification delivery in an archived thread", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_thread_messages`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES (
'thread-archived-home',
'project-1',
'Home',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
NULL,
0,
0,
0,
'2026-04-07T00:00:00.000Z',
'2026-04-07T00:00:01.000Z',
'2026-04-07T00:00:02.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_thread_messages (
message_id,
thread_id,
turn_id,
role,
text,
attachments_json,
notification_json,
is_streaming,
created_at,
updated_at
)
VALUES
(
'message-delivered',
'thread-archived-home',
NULL,
'assistant',
'Nightly brief',
NULL,
'{"kind":"cron","label":"Cron: nightly","deliveryId":"delivery-abc"}',
0,
'2026-04-07T00:00:03.000Z',
'2026-04-07T00:00:03.000Z'
),
(
'message-ordinary',
'thread-archived-home',
NULL,
'user',
'delivery-abc appears in this body, but not as provenance',
NULL,
NULL,
0,
'2026-04-07T00:00:04.000Z',
'2026-04-07T00:00:04.000Z'
)
`;
// Archiving parks a thread; it does not unwrite what is in it. The
// thread-detail read filters archived rows, so a dedupe check built on
// it reports every delivery as new and the plugin's retries append a
// duplicate per reconnect.
const detail = yield* snapshotQuery.getThreadDetailById(
ThreadId.make("thread-archived-home"),
);
assert.equal(detail._tag, "None");
assert.isTrue(
yield* snapshotQuery.hasThreadNotificationDelivery({
threadId: ThreadId.make("thread-archived-home"),
deliveryId: "delivery-abc",
}),
);
// Matched on the provenance field, not a substring of the row: a
// deliveryId a user happened to type must not suppress a real delivery.
assert.isFalse(
yield* snapshotQuery.hasThreadNotificationDelivery({
threadId: ThreadId.make("thread-archived-home"),
deliveryId: "delivery-never-written",
}),
);
// Scoped to the thread — one instance's delivery id cannot mask another's.
assert.isFalse(
yield* snapshotQuery.hasThreadNotificationDelivery({
threadId: ThreadId.make("thread-elsewhere"),
deliveryId: "delivery-abc",
}),
);
}),
);
});
it.effect(
@@ -5,7 +5,6 @@ import {
MessageId,
NonNegativeInt,
OrchestrationCheckpointFile,
OrchestrationMessageNotification,
OrchestrationProposedPlanId,
OrchestrationReadModel,
OrchestrationShellSnapshot,
@@ -23,9 +22,7 @@ import {
type OrchestrationThreadActivity,
type OrchestrationThreadShell,
ModelSelection,
OrchestrationThreadNotificationSummary,
ProjectId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
@@ -75,19 +72,12 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
Struct.assign({
isStreaming: Schema.Number,
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
notification: Schema.NullOr(Schema.fromJsonString(OrchestrationMessageNotification)),
}),
);
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
// Stored as a JSON string, like `modelSelection`. Every column the row
// schema does not decode here arrives as raw text and fails the field's
// object schema — which takes the whole thread read down with it.
latestNotification: Schema.NullOr(
Schema.fromJsonString(OrchestrationThreadNotificationSummary),
),
}),
);
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
@@ -124,9 +114,6 @@ const WorkspaceRootLookupInput = Schema.Struct({
const ProjectIdLookupInput = Schema.Struct({
projectId: ProjectId,
});
const AgentInstanceLookupInput = Schema.Struct({
agentInstanceId: ProviderInstanceId,
});
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
@@ -248,7 +235,6 @@ function mapProjectShellRow(
repositoryIdentity,
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
agentInstanceId: row.agentInstanceId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
};
@@ -322,7 +308,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
agent_instance_id AS "agentInstanceId",
created_at AS "createdAt",
updated_at AS "updatedAt",
deleted_at AS "deletedAt"
@@ -357,7 +342,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
ORDER BY created_at ASC, thread_id ASC
@@ -390,7 +374,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
@@ -425,7 +408,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
@@ -446,7 +428,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
notification_json AS "notification",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -700,7 +681,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
agent_instance_id AS "agentInstanceId",
created_at AS "createdAt",
updated_at AS "updatedAt",
deleted_at AS "deletedAt"
@@ -723,7 +703,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
agent_instance_id AS "agentInstanceId",
created_at AS "createdAt",
updated_at AS "updatedAt",
deleted_at AS "deletedAt"
@@ -734,36 +713,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
/**
* Active agent project for one provider instance.
*
* Ordered oldest-first so a duplicate — which the enrollment lock is meant
* to prevent but a crash between dispatch and commit could still leave —
* resolves to the same row every time rather than flapping between two.
*/
const getActiveAgentProjectRow = SqlSchema.findOneOption({
Request: AgentInstanceLookupInput,
Result: ProjectionProjectLookupRowSchema,
execute: ({ agentInstanceId }) =>
sql`
SELECT
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
agent_instance_id AS "agentInstanceId",
created_at AS "createdAt",
updated_at AS "updatedAt",
deleted_at AS "deletedAt"
FROM projection_projects
WHERE agent_instance_id = ${agentInstanceId}
AND deleted_at IS NULL
ORDER BY created_at ASC, project_id ASC
LIMIT 1
`,
});
const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({
Request: ProjectIdLookupInput,
Result: ProjectionThreadIdLookupRowSchema,
@@ -799,44 +748,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
// Existence, not visibility: deliberately no `archived_at IS NULL`. Selects
// only the two columns it needs so it cannot be broken by an undecoded
// JSON column elsewhere in the row.
const getThreadArchiveStateRowById = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: Schema.Struct({
archivedAt: Schema.NullOr(Schema.String),
deletedAt: Schema.NullOr(Schema.String),
}),
execute: ({ threadId }) =>
sql`
SELECT
archived_at AS "archivedAt",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE thread_id = ${threadId}
LIMIT 1
`,
});
// Dedupe, not display: deliberately no join to `projection_threads` and so
// no archive/delete filter. A delivery written into a thread the user later
// archived is still written, and treating it as absent would re-append it on
// every retry. `json_extract` rather than a LIKE over the blob, so a
// deliveryId occurring inside some other field cannot false-positive.
const findThreadNotificationDeliveryRow = SqlSchema.findOneOption({
Request: Schema.Struct({ threadId: ThreadId, deliveryId: Schema.String }),
Result: Schema.Struct({ messageId: Schema.String }),
execute: ({ threadId, deliveryId }) =>
sql`
SELECT message_id AS "messageId"
FROM projection_thread_messages
WHERE thread_id = ${threadId}
AND json_extract(notification_json, '$.deliveryId') = ${deliveryId}
LIMIT 1
`,
});
const getActiveThreadRowById = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionThreadDbRowSchema,
@@ -863,7 +774,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE thread_id = ${threadId}
@@ -885,7 +795,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
notification_json AS "notification",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -1157,7 +1066,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
role: row.role,
text: row.text,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
...(row.notification !== null ? { notification: row.notification } : {}),
turnId: row.turnId,
streaming: row.isStreaming === 1,
createdAt: row.createdAt,
@@ -1276,7 +1184,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
repositoryIdentity: repositoryIdentities.get(row.projectId) ?? null,
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
agentInstanceId: row.agentInstanceId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
@@ -1403,7 +1310,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspaceRoot: row.workspaceRoot,
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
agentInstanceId: row.agentInstanceId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
@@ -1640,7 +1546,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
latestNotification: row.latestNotification,
} satisfies OrchestrationThreadShell)
: Result.failVoid,
),
@@ -1779,7 +1684,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
latestNotification: row.latestNotification,
}),
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
@@ -1854,7 +1758,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
repositoryIdentity,
defaultModelSelection: option.value.defaultModelSelection,
scripts: option.value.scripts,
agentInstanceId: option.value.agentInstanceId,
createdAt: option.value.createdAt,
updatedAt: option.value.updatedAt,
deletedAt: option.value.deletedAt,
@@ -1864,38 +1767,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
);
const getActiveAgentProject: ProjectionSnapshotQueryShape["getActiveAgentProject"] = (
agentInstanceId,
) =>
getActiveAgentProjectRow({ agentInstanceId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getActiveAgentProject:query",
"ProjectionSnapshotQuery.getActiveAgentProject:decodeRow",
),
),
Effect.map((option) =>
Option.map(
option,
(row): OrchestrationProject => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
// Agent projects are not checkouts, so there is no remote to
// resolve — skipping the resolver keeps this off the git path
// entirely rather than paying for a lookup that returns null.
repositoryIdentity: null,
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
agentInstanceId: row.agentInstanceId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
}),
),
),
);
const getProjectShellById: ProjectionSnapshotQueryShape["getProjectShellById"] = (projectId) =>
getActiveProjectRowById({ projectId }).pipe(
Effect.mapError(
@@ -2002,26 +1873,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
});
const getThreadArchiveStateById: ProjectionSnapshotQueryShape["getThreadArchiveStateById"] = (
threadId,
) =>
getThreadArchiveStateRowById({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadArchiveStateById:query",
"ProjectionSnapshotQuery.getThreadArchiveStateById:decodeRow",
),
),
Effect.map(
Option.flatMap((row) =>
// A soft-deleted row is gone; an archived one is merely parked.
row.deletedAt !== null
? Option.none<{ readonly archivedAt: string | null }>()
: Option.some({ archivedAt: row.archivedAt }),
),
),
);
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
@@ -2077,22 +1928,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
latestNotification: threadRow.value.latestNotification,
} satisfies OrchestrationThreadShell);
});
const hasThreadNotificationDelivery: ProjectionSnapshotQueryShape["hasThreadNotificationDelivery"] =
(input) =>
findThreadNotificationDeliveryRow(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.hasThreadNotificationDelivery:query",
"ProjectionSnapshotQuery.hasThreadNotificationDelivery:decodeRow",
),
),
Effect.map(Option.isSome),
);
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
Effect.gen(function* () {
const [
@@ -2185,7 +2023,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedAt: threadRow.value.snoozedAt,
deletedAt: null,
messages: messageRows.map((row) => {
const message: OrchestrationMessage = {
const message = {
id: row.messageId,
role: row.role,
text: row.text,
@@ -2193,9 +2031,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
streaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
...(row.notification !== null ? { notification: row.notification } : {}),
};
if (row.attachments !== null) {
return Object.assign(message, { attachments: row.attachments });
}
return message;
}),
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
@@ -2272,14 +2111,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getSnapshotSequence,
getCounts,
getActiveProjectByWorkspaceRoot,
getActiveAgentProject,
getProjectShellById,
getFirstActiveThreadIdByProjectId,
getThreadCheckpointContext,
getFullThreadDiffContext,
getThreadShellById,
getThreadArchiveStateById,
hasThreadNotificationDelivery,
getThreadDetailById,
getThreadDetailSnapshot,
} satisfies ProjectionSnapshotQueryShape;
@@ -60,6 +60,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Clock from "effect/Clock";
import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { WorktreeService } from "../../vcs/WorktreeService.ts";
import * as GitWorkflowService from "../../git/GitWorkflowService.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
@@ -378,6 +379,11 @@ describe("ProviderCommandReactor", () => {
generateThreadTitle,
}),
),
Layer.provideMerge(
Layer.mock(WorktreeService, {
reviveWorktree: () => Effect.succeed({ revived: false }),
}),
),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
Layer.provideMerge(NodeServices.layer),
@@ -477,49 +483,6 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
effectIt.effect("adopts a recovered active provider turn while binding a pending start", () =>
Effect.gen(function* () {
const recoveredTurnId = asTurnId("turn-recovered-during-start");
const harness = yield* Effect.promise(() =>
createHarness({
startSessionEffect: (session) =>
Effect.succeed({
...session,
status: "running",
activeTurnId: recoveredTurnId,
}),
}),
);
const now = "2026-01-01T00:00:00.000Z";
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-recovered-provider-turn"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-recovered-provider-turn"),
role: "user",
text: "steer the recovered turn",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
const readModel = yield* Effect.promise(() => harness.readModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.status).toBe("running");
expect(thread?.session?.activeTurnId).toBe(recoveredTurnId);
expect(thread?.latestTurn).toMatchObject({
turnId: recoveredTurnId,
state: "running",
});
}),
);
effectIt.effect("projects starting before a slow provider session finishes", () =>
Effect.gen(function* () {
const releaseStart = yield* Deferred.make<void>();
@@ -1224,62 +1187,6 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("reuses a cwd-bookkept Hermes session for active follow-up guidance", async () => {
const harness = await createHarness({
threadModelSelection: {
instanceId: ProviderInstanceId.make("hermes"),
model: "hermes",
},
});
const now = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-hermes-guidance-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-hermes-guidance-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
provider: ProviderDriverKind.make("hermes"),
providerInstanceId: ProviderInstanceId.make("hermes"),
});
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-hermes-guidance-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-hermes-guidance-2"),
role: "user",
text: "follow up",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession).toHaveBeenCalledTimes(1);
expect(harness.stopSession).not.toHaveBeenCalled();
});
it("restarts an existing Codex thread on a compatible requested instance", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2273,45 +2180,45 @@ describe("ProviderCommandReactor", () => {
expect(resolvedActivity).toBeUndefined();
});
effectIt.effect(
"reacts to thread.session.stop by stopping provider session and clearing thread session state",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
yield* harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-for-stop"),
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-for-stop"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
providerInstanceId: ProviderInstanceId.make("codex_work"),
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
});
yield* harness.engine.dispatch({
type: "thread.session.stop",
commandId: CommandId.make("cmd-session-stop"),
threadId: ThreadId.make("thread-1"),
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.stopSession.mock.calls.length === 1));
const readModel = yield* Effect.promise(() => harness.readModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session).not.toBeNull();
expect(thread?.session?.status).toBe("stopped");
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
expect(thread?.session?.activeTurnId).toBeNull();
status: "ready",
providerName: "codex",
providerInstanceId: ProviderInstanceId.make("codex_work"),
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.stop",
commandId: CommandId.make("cmd-session-stop"),
threadId: ThreadId.make("thread-1"),
createdAt: now,
}),
);
await waitFor(() => harness.stopSession.mock.calls.length === 1);
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session).not.toBeNull();
expect(thread?.session?.status).toBe("stopped");
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
expect(thread?.session?.activeTurnId).toBeNull();
});
});
@@ -44,6 +44,7 @@ import {
} from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
import { WorktreeService } from "../../vcs/WorktreeService.ts";
const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
const isProviderDriverKind = Schema.is(ProviderDriverKind);
@@ -196,6 +197,7 @@ const make = Effect.gen(function* () {
const providerService = yield* ProviderService;
const providerRegistry = yield* ProviderRegistry;
const gitWorkflow = yield* GitWorkflowService;
const worktreeService = yield* WorktreeService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
@@ -495,6 +497,26 @@ const make = Effect.gen(function* () {
thread,
projects: project ? [project] : [],
});
// A pruned (or manually deleted) worktree is recreated from the thread's
// branch before the provider session starts in it.
if (thread.worktreePath !== null && thread.branch !== null && project) {
yield* worktreeService
.reviveWorktree({
workspaceRoot: project.workspaceRoot,
worktreePath: thread.worktreePath,
branch: thread.branch,
})
.pipe(
Effect.mapError(
(error) =>
new ProviderAdapterRequestError({
provider: providerErrorLabel(preferredProvider),
method: "thread.turn.start",
detail: `Could not restore the thread's worktree: ${error.message}`,
}),
),
);
}
const startProviderSession = (input?: {
readonly resumeCursor?: unknown;
@@ -530,7 +552,8 @@ const make = Effect.gen(function* () {
providerName: session.provider,
providerInstanceId: session.providerInstanceId,
runtimeMode: desiredRuntimeMode,
activeTurnId: session.activeTurnId ?? null,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: session.lastError ?? null,
updatedAt: session.updatedAt,
},
@@ -27,7 +27,6 @@ import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
@@ -36,9 +35,7 @@ import { afterEach, describe, expect, it } from "vite-plus/test";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import {
ProviderService,
type ProviderServiceShape,
@@ -195,10 +192,7 @@ async function waitForThread(
describe("ProviderRuntimeIngestion", () => {
let runtime: ManagedRuntime.ManagedRuntime<
| OrchestrationEngineService
| ProviderRuntimeIngestionService
| ProjectionSnapshotQuery
| ProjectionTurnRepository,
OrchestrationEngineService | ProviderRuntimeIngestionService | ProjectionSnapshotQuery,
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
@@ -240,13 +234,9 @@ describe("ProviderRuntimeIngestion", () => {
Layer.provide(RepositoryIdentityResolver.layer),
Layer.provide(SqlitePersistenceMemory),
);
const projectionTurnLayer = ProjectionTurnRepositoryLive.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const layer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
Layer.provideMerge(projectionTurnLayer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
@@ -257,7 +247,6 @@ describe("ProviderRuntimeIngestion", () => {
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
const turnRepository = await runtime.runPromise(Effect.service(ProjectionTurnRepository));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(ingestion.drain);
@@ -326,7 +315,6 @@ describe("ProviderRuntimeIngestion", () => {
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
emit: provider.emit,
setProviderSession: provider.setSession,
turnRepository,
drain,
};
}
@@ -958,209 +946,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("replaces streaming assistant text from authoritative snapshots without changing identity", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const now = "2026-01-01T00:00:00.000Z";
const itemId = asItemId("item-streaming-snapshot");
const turnId = asTurnId("turn-streaming-snapshot");
harness.emit({
type: "content.delta",
eventId: asEventId("evt-streaming-snapshot-delta"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: "draft",
},
});
harness.emit({
type: "content.snapshot",
eventId: asEventId("evt-streaming-snapshot-replace"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
text: "authoritative",
},
});
harness.emit({
type: "content.delta",
eventId: asEventId("evt-streaming-snapshot-tail"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: " answer",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-streaming-snapshot-completed"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === `assistant:${itemId}` &&
message.text === "authoritative answer" &&
!message.streaming,
),
);
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
1,
);
});
it("applies repeated empty snapshots idempotently to a streaming assistant message", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const now = "2026-01-01T00:00:00.000Z";
const itemId = asItemId("item-empty-snapshot");
const turnId = asTurnId("turn-empty-snapshot");
harness.emit({
type: "content.delta",
eventId: asEventId("evt-empty-snapshot-delta"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: "remove me",
},
});
for (const eventId of ["evt-empty-snapshot-one", "evt-empty-snapshot-two"]) {
harness.emit({
type: "content.snapshot",
eventId: asEventId(eventId),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
text: "",
},
});
}
harness.emit({
type: "item.completed",
eventId: asEventId("evt-empty-snapshot-completed"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === `assistant:${itemId}` && message.text === "" && !message.streaming,
),
);
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
1,
);
});
it("authoritatively replaces buffered assistant text before completion", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const itemId = asItemId("item-buffered-snapshot");
const turnId = asTurnId("turn-buffered-snapshot");
harness.emit({
type: "content.delta",
eventId: asEventId("evt-buffered-snapshot-delta"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: "draft",
},
});
harness.emit({
type: "content.snapshot",
eventId: asEventId("evt-buffered-snapshot-replace"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
text: "final",
},
});
harness.emit({
type: "content.delta",
eventId: asEventId("evt-buffered-snapshot-tail"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: " answer",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-buffered-snapshot-completed"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === `assistant:${itemId}` &&
message.text === "final answer" &&
!message.streaming,
),
);
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
1,
);
});
it("uses assistant item completion detail when no assistant deltas were streamed", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -1788,85 +1573,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(threadAfterSteer.latestTurn?.state).toBe("running");
});
effectIt.effect(
"consumes a follow-up pending start when Hermes acknowledges the active turn",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const threadId = asThreadId("thread-1");
const activeTurnId = asTurnId("turn-hermes-active");
const followUpMessageId = asMessageId("msg-hermes-follow-up");
const createdAt = "2026-01-01T00:00:00.000Z";
harness.setProviderSession({
provider: ProviderDriverKind.make("hermes"),
status: "running",
runtimeMode: "approval-required",
threadId,
createdAt,
updatedAt: createdAt,
activeTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-hermes-active-turn-started"),
provider: ProviderDriverKind.make("hermes"),
createdAt,
threadId,
turnId: activeTurnId,
});
yield* Effect.promise(() =>
waitForThread(
harness.readModel,
(thread) =>
thread.session?.status === "running" && thread.session.activeTurnId === activeTurnId,
2_000,
threadId,
),
);
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-hermes-follow-up"),
threadId,
message: {
messageId: followUpMessageId,
role: "user",
text: "steer the active Hermes turn",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:01.000Z",
});
const pendingBeforeAck = yield* harness.turnRepository.getPendingTurnStartByThreadId({
threadId,
});
expect(Option.getOrUndefined(pendingBeforeAck)?.messageId).toBe(followUpMessageId);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-hermes-follow-up-ack"),
provider: ProviderDriverKind.make("hermes"),
createdAt: "2026-01-01T00:00:02.000Z",
threadId,
turnId: activeTurnId,
});
yield* Effect.promise(() => harness.drain());
const pendingAfterAck = yield* harness.turnRepository.getPendingTurnStartByThreadId({
threadId,
});
const activeTurn = yield* harness.turnRepository.getByTurnId({
threadId,
turnId: activeTurnId,
});
expect(Option.isNone(pendingAfterAck)).toBe(true);
expect(Option.getOrUndefined(activeTurn)?.pendingMessageId).toBe(followUpMessageId);
}),
);
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
@@ -2167,97 +1873,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("treats turn.aborted as terminal and finalizes buffered assistant text", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const turnId = asTurnId("turn-aborted-buffered");
const itemId = asItemId("item-aborted-buffered");
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-before-abort"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
});
await waitForThread(
harness.readModel,
(thread) => thread.session?.status === "running" && thread.session.activeTurnId === turnId,
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-content-before-abort"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: "partial response",
},
});
harness.emit({
type: "turn.aborted",
eventId: asEventId("evt-turn-aborted"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
payload: {
reason: "Interrupted by user.",
},
});
const thread = await waitForThread(
harness.readModel,
(entry) =>
entry.session?.status === "ready" &&
entry.session.activeTurnId === null &&
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === `assistant:${itemId}` &&
message.text === "partial response" &&
!message.streaming,
),
);
expect(thread.session?.lastError).toBeNull();
const nextTurnId = asTurnId("turn-after-abort");
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-after-abort"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: nextTurnId,
});
await waitForThread(
harness.readModel,
(entry) => entry.session?.status === "running" && entry.session.activeTurnId === nextTurnId,
);
harness.emit({
type: "turn.aborted",
eventId: asEventId("evt-stale-turn-aborted"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
payload: {
reason: "Late abort for the previous turn.",
},
});
await harness.drain();
const afterStaleAbort = await harness.readModel();
const activeThread = afterStaleAbort.threads.find(
(entry) => entry.id === ThreadId.make("thread-1"),
);
expect(activeThread?.session?.status).toBe("running");
expect(activeThread?.session?.activeTurnId).toBe(nextTurnId);
});
it("flushes and completes buffered assistant text when an approval request opens", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2837,65 +2452,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("replaces a spilled buffered projection when an authoritative snapshot arrives", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const itemId = asItemId("item-buffer-spill-snapshot");
const turnId = asTurnId("turn-buffer-spill-snapshot");
harness.emit({
type: "content.delta",
eventId: asEventId("evt-buffer-spill-before-snapshot"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: "x".repeat(40_000),
},
});
harness.emit({
type: "content.snapshot",
eventId: asEventId("evt-buffer-spill-snapshot"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
text: "authoritative after spill",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-buffer-spill-snapshot-completed"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === `assistant:${itemId}` &&
message.text === "authoritative after spill" &&
!message.streaming,
),
);
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
1,
);
});
it("does not duplicate assistant completion when item.completed is followed by turn.completed", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -3202,278 +2758,6 @@ describe("ProviderRuntimeIngestion", () => {
).toBe(true);
});
it("upserts status_text provider item lifecycle into one meaningful activity", async () => {
const harness = await createHarness();
const itemId = asItemId("item-generic-activity");
const turnId = asTurnId("turn-generic-activity");
harness.emit({
type: "item.started",
eventId: asEventId("evt-generic-activity-started"),
provider: ProviderDriverKind.make("hermes"),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "status_text",
status: "inProgress",
title: "Reading skill hermes-agent",
detail: "Opening the skill instructions.",
data: { unsafeRawPayload: "not projected" },
},
});
harness.emit({
type: "item.updated",
eventId: asEventId("evt-generic-activity-updated"),
provider: ProviderDriverKind.make("hermes"),
createdAt: "2026-01-01T00:00:01.000Z",
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "status_text",
status: "inProgress",
title: "Reading skill hermes-agent",
detail: "Parsing the workflow.",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-generic-activity-completed"),
provider: ProviderDriverKind.make("hermes"),
createdAt: "2026-01-01T00:00:02.000Z",
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "status_text",
status: "completed",
title: "Read skill hermes-agent",
detail: "Skill instructions loaded.",
},
});
const activityId = `provider:hermes:item:${itemId}`;
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) =>
activity.id === activityId &&
activity.payload &&
typeof activity.payload === "object" &&
(activity.payload as Record<string, unknown>).status === "completed",
),
);
const activities = thread.activities.filter((activity) => activity.id === activityId);
const activity = activities[0];
const payload =
activity?.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: undefined;
expect(activities).toHaveLength(1);
expect(activity?.kind).toBe("provider.activity");
expect(activity?.tone).toBe("info");
expect(activity?.summary).toBe("Skill instructions loaded.");
expect(payload).toMatchObject({
itemType: "status_text",
status: "completed",
providerItemId: itemId,
title: "Read skill hermes-agent",
detail: "Skill instructions loaded.",
});
expect(payload?.data).toBeUndefined();
});
// Regression: `unknown` is the canonical "could not classify this item"
// sentinel and adapters rely on it being INERT. CodexAdapter deliberately
// emits it for item.updated; routing generic activity through it put rows
// summarized as the literal string "Provider activity" into Codex threads.
// Renderable status text has its own item type (`status_text`) instead.
it("does not create activities for the unknown item sentinel", async () => {
const harness = await createHarness();
const itemId = asItemId("item-codex-unknown");
const turnId = asTurnId("turn-codex-unknown");
harness.emit({
type: "item.updated",
eventId: asEventId("evt-codex-unknown-updated"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "unknown",
status: "inProgress",
},
});
// A tool item after it gives the poll something real to settle on, so the
// assertion is "the unknown item produced nothing" rather than a race.
harness.emit({
type: "item.started",
eventId: asEventId("evt-codex-unknown-tool"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:01.000Z",
threadId: asThreadId("thread-1"),
turnId,
itemId: asItemId("item-codex-tool"),
payload: {
itemType: "command_execution",
status: "inProgress",
title: "ls",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "tool.started",
),
);
expect(
thread.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === `provider:codex:item:${itemId}`,
),
).toBe(false);
expect(
thread.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "provider.activity",
),
).toBe(false);
});
it("attributes a late turn-less item frame to the turn that just completed", async () => {
// Plugin tool hooks run on worker threads, so a post_tool_call →
// item.completed frame can land after turn.completed and carry no turn id.
// Without a fallback the activity projects with turnId null, which the
// timeline can never fold behind the turn's "Worked for …" row.
const harness = await createHarness();
const turnId = asTurnId("turn-late-frame");
harness.emit({
type: "turn.started",
eventId: asEventId("evt-late-frame-turn-started"),
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:00.000Z",
turnId,
});
await waitForThread(
harness.readModel,
(entry) => entry.session?.activeTurnId === "turn-late-frame",
);
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-late-frame-turn-completed"),
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:10.000Z",
turnId,
payload: { state: "completed" },
});
await waitForThread(harness.readModel, (entry) => entry.session?.activeTurnId === null);
harness.emit({
type: "item.completed",
eventId: asEventId("evt-late-frame-item"),
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:10.002Z",
itemId: asItemId("item-late-frame"),
payload: {
itemType: "command_execution",
status: "completed",
title: "Ran command",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-late-frame-item",
),
);
const activity = thread.activities.find(
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-late-frame-item",
);
expect(activity?.kind).toBe("tool.completed");
expect(activity?.turnId).toBe("turn-late-frame");
});
it("leaves an item frame unattributed when no turn has ever run on the thread", async () => {
const harness = await createHarness();
harness.emit({
type: "item.completed",
eventId: asEventId("evt-orphan-frame-item"),
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:00.000Z",
itemId: asItemId("item-orphan-frame"),
payload: {
itemType: "command_execution",
status: "completed",
title: "Ran command",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-orphan-frame-item",
),
);
const activity = thread.activities.find(
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-orphan-frame-item",
);
expect(activity?.turnId).toBeNull();
});
it("keeps an explicit turn id on a frame naming a turn other than the active one", async () => {
const harness = await createHarness();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-conflict-turn-started"),
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:00.000Z",
turnId: asTurnId("turn-active"),
});
await waitForThread(
harness.readModel,
(entry) => entry.session?.activeTurnId === "turn-active",
);
harness.emit({
type: "item.completed",
eventId: asEventId("evt-conflict-item"),
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:01.000Z",
turnId: asTurnId("turn-other"),
itemId: asItemId("item-conflict"),
payload: {
itemType: "command_execution",
status: "completed",
title: "Ran command",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-conflict-item",
),
);
const activity = thread.activities.find(
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-conflict-item",
);
expect(activity?.turnId).toBe("turn-other");
});
it("consumes P1 runtime events into thread metadata, diff checkpoints, and activities", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2,7 +2,6 @@ import {
ApprovalRequestId,
type AssistantDeliveryMode,
CommandId,
EventId,
MessageId,
type OrchestrationEvent,
type OrchestrationMessage,
@@ -114,47 +113,6 @@ function toTurnId(value: TurnId | string | undefined): TurnId | undefined {
return value === undefined ? undefined : TurnId.make(String(value));
}
/**
* How long after a turn settles a turn-less provider frame is still treated as
* belonging to that turn. Plugin tool hooks run on worker threads, so a
* `post_tool_call` → `item.completed` frame can land after `turn.completed`;
* without attribution such an activity can never be folded behind the turn's
* "Worked for …" row and renders below the final answer instead.
*/
const LATE_ACTIVITY_TURN_ATTRIBUTION_GRACE_MS = 30_000;
export interface RecentlySettledTurn {
readonly turnId: TurnId;
readonly settledAt: string;
}
/**
* Turn id to stamp on activities produced by a frame that carries none. The
* session's active turn wins; once the turn has closed, the turn that just
* settled still claims frames landing inside a short trailing window.
*/
export function resolveActivityFallbackTurnId(input: {
readonly activeTurnId: TurnId | null;
readonly recentlySettledTurn: RecentlySettledTurn | null;
readonly at: string;
}): TurnId | null {
if (input.activeTurnId !== null) {
return input.activeTurnId;
}
const settled = input.recentlySettledTurn;
if (!settled) {
return null;
}
const atMs = Date.parse(input.at);
const settledAtMs = Date.parse(settled.settledAt);
if (!Number.isFinite(atMs) || !Number.isFinite(settledAtMs)) {
return null;
}
// Frames stamped before the turn closed always belong to it; frames stamped
// after it only within the grace window.
return atMs - settledAtMs <= LATE_ACTIVITY_TURN_ATTRIBUTION_GRACE_MS ? settled.turnId : null;
}
function toApprovalRequestId(value: string | undefined): ApprovalRequestId | undefined {
return value === undefined ? undefined : ApprovalRequestId.make(value);
}
@@ -348,47 +306,6 @@ function requestKindFromCanonicalRequestType(
}
}
function genericProviderActivityId(event: ProviderRuntimeEvent): EventId {
return EventId.make(
event.itemId
? `provider:${event.provider}:item:${event.itemId}`
: `provider:${event.provider}:event:${event.eventId}`,
);
}
function genericProviderActivity(
event: Extract<
ProviderRuntimeEvent,
{ type: "item.started" | "item.updated" | "item.completed" }
>,
maybeSequence: { readonly sequence?: number },
): OrchestrationThreadActivity {
const title = event.payload.title ? truncateDetail(event.payload.title, 120) : undefined;
const detail = event.payload.detail ? truncateDetail(event.payload.detail) : undefined;
const status =
event.payload.status ?? (event.type === "item.completed" ? "completed" : "inProgress");
return {
id: genericProviderActivityId(event),
createdAt: event.createdAt,
tone: "info",
kind: "provider.activity",
// Status text is the interesting part here; the title is a generic label
// ("Hermes activity"). Prefer the detail so the row reads as the status the
// provider is actually reporting.
summary: detail ? truncateDetail(detail, 120) : (title ?? "Working…"),
payload: {
itemType: event.payload.itemType,
status,
...(event.itemId ? { providerItemId: event.itemId } : {}),
...(title ? { title } : {}),
...(detail ? { detail } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
};
}
export function runtimeEventToActivities(
event: ProviderRuntimeEvent,
taskTitle?: string,
@@ -697,9 +614,6 @@ export function runtimeEventToActivities(
}
case "item.updated": {
if (event.payload.itemType === "status_text") {
return [genericProviderActivity(event, maybeSequence)];
}
if (!isToolLifecycleItemType(event.payload.itemType)) {
return [];
}
@@ -723,9 +637,6 @@ export function runtimeEventToActivities(
}
case "item.completed": {
if (event.payload.itemType === "status_text") {
return [genericProviderActivity(event, maybeSequence)];
}
if (!isToolLifecycleItemType(event.payload.itemType)) {
return [];
}
@@ -748,9 +659,6 @@ export function runtimeEventToActivities(
}
case "item.started": {
if (event.payload.itemType === "status_text") {
return [genericProviderActivity(event, maybeSequence)];
}
if (!isToolLifecycleItemType(event.payload.itemType)) {
return [];
}
@@ -825,16 +733,6 @@ const make = Effect.gen(function* () {
lookup: () => Effect.succeed(""),
});
// The projection nulls the thread's latest turn id the moment the session
// stops running, so a frame arriving right after turn.completed can no
// longer see the turn it belongs to. Remember the turn that just settled
// per thread so late frames can still be attributed to it.
const recentlySettledTurnByThreadId = yield* Cache.make<ThreadId, RecentlySettledTurn | null>({
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
lookup: () => Effect.succeed(null),
});
const rememberTaskDescription = (threadId: ThreadId, taskId: string, description: string) =>
Cache.set(taskDescriptionByTaskKey, providerTaskKey(threadId, taskId), description);
@@ -1001,9 +899,6 @@ const make = Effect.gen(function* () {
),
);
const replaceBufferedAssistantText = (messageId: MessageId, text: string) =>
Cache.set(bufferedAssistantTextByMessageId, messageId, text);
const takeBufferedAssistantText = (messageId: MessageId) =>
Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
Effect.flatMap((existingText) =>
@@ -1317,7 +1212,6 @@ const make = Effect.gen(function* () {
key.startsWith(prefix) ? Cache.invalidate(taskDescriptionByTaskKey, key) : Effect.void,
{ concurrency: 1 },
).pipe(Effect.asVoid);
yield* Cache.invalidate(recentlySettledTurnByThreadId, threadId);
});
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn(
@@ -1424,11 +1318,6 @@ const make = Effect.gen(function* () {
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
const getRecentlySettledTurn = () =>
Cache.getOption(recentlySettledTurnByThreadId, thread.id).pipe(
Effect.map(Option.getOrNull),
);
// A turn.started that conflicts with the active turn is legitimate when
// the server itself has a turn start pending for this thread AND the
// provider session already tracks the event's turn as its active turn:
@@ -1454,7 +1343,6 @@ const make = Effect.gen(function* () {
case "turn.started":
return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart;
case "turn.completed":
case "turn.aborted":
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
return false;
}
@@ -1479,8 +1367,7 @@ const make = Effect.gen(function* () {
event.type === "session.exited" ||
event.type === "thread.started" ||
event.type === "turn.started" ||
event.type === "turn.completed" ||
event.type === "turn.aborted"
event.type === "turn.completed"
) {
const status = (() => {
switch (event.type) {
@@ -1496,8 +1383,6 @@ const make = Effect.gen(function* () {
return normalizeRuntimeTurnState(event.payload.state) === "failed"
? "error"
: "ready";
case "turn.aborted":
return "ready";
case "session.started":
case "thread.started":
// Provider thread/session start notifications can arrive during an
@@ -1508,9 +1393,7 @@ const make = Effect.gen(function* () {
const nextActiveTurnId =
event.type === "turn.started"
? (eventTurnId ?? null)
: event.type === "turn.completed" ||
event.type === "turn.aborted" ||
event.type === "session.exited"
: event.type === "turn.completed" || event.type === "session.exited"
? null
: event.type === "session.state.changed" &&
!sessionStatusAllowsActiveTurn(
@@ -1567,19 +1450,6 @@ const make = Effect.gen(function* () {
},
createdAt: now,
});
// Record the turn the session is leaving so frames that land after
// it (tool-hook completions on provider worker threads) can still be
// attributed to it. A new turn opening clears the memo.
const settlingTurnId = activeTurnId ?? eventTurnId ?? null;
if (nextActiveTurnId !== null) {
yield* Cache.set(recentlySettledTurnByThreadId, thread.id, null);
} else if (settlingTurnId !== null) {
yield* Cache.set(recentlySettledTurnByThreadId, thread.id, {
turnId: settlingTurnId,
settledAt: now,
});
}
}
}
@@ -1587,10 +1457,6 @@ const make = Effect.gen(function* () {
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
? event.payload.delta
: undefined;
const assistantSnapshot =
event.type === "content.snapshot" && event.payload.streamKind === "assistant_text"
? event.payload.text
: undefined;
const proposedPlanDelta =
event.type === "turn.proposed.delta" ? event.payload.delta : undefined;
@@ -1635,53 +1501,6 @@ const make = Effect.gen(function* () {
}
}
if (assistantSnapshot !== undefined) {
const turnId = toTurnId(event.turnId);
const assistantMessageId = yield* getOrCreateAssistantMessageId({
threadId: thread.id,
event,
...(turnId ? { turnId } : {}),
});
if (turnId) {
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
}
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
);
if (assistantDeliveryMode === "buffered") {
const detailedThread = yield* getLoadedThreadDetail();
const hasProjectedMessage =
findMessageById(detailedThread?.messages ?? [], assistantMessageId) !== undefined;
if (hasProjectedMessage) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.replace",
commandId: yield* providerCommandId(event, "assistant-snapshot-buffer-spill"),
threadId: thread.id,
messageId: assistantMessageId,
text: assistantSnapshot,
...(turnId ? { turnId } : {}),
createdAt: now,
});
yield* clearBufferedAssistantText(assistantMessageId);
} else {
yield* replaceBufferedAssistantText(assistantMessageId, assistantSnapshot);
}
} else {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.replace",
commandId: yield* providerCommandId(event, "assistant-snapshot"),
threadId: thread.id,
messageId: assistantMessageId,
text: assistantSnapshot,
...(turnId ? { turnId } : {}),
createdAt: now,
});
yield* clearBufferedAssistantText(assistantMessageId);
}
}
const pauseForUserTurnId =
event.type === "request.opened" || event.type === "user-input.requested"
? toTurnId(event.turnId)
@@ -1815,7 +1634,7 @@ const make = Effect.gen(function* () {
});
}
if (event.type === "turn.completed" || event.type === "turn.aborted") {
if (event.type === "turn.completed") {
const detailedThread = yield* getLoadedThreadDetail();
const messages = detailedThread?.messages ?? [];
const proposedPlans = detailedThread?.proposedPlans ?? [];
@@ -1945,25 +1764,7 @@ const make = Effect.gen(function* () {
}
}
// Frames that carry no turn id (late tool-hook completions, generic
// status items emitted around turn boundaries) would otherwise project
// an unattributed activity, which the timeline can never fold behind the
// turn's "Worked for …" row. Attribute them to the thread's active turn,
// or to the turn that just settled. Frames that do name a turn keep it —
// the turn-conflict gate above governs lifecycle, not attribution.
const fallbackActivityTurnId = resolveActivityFallbackTurnId({
activeTurnId,
// With a turn start pending, an unattributed frame is at least as
// likely to belong to the turn about to open as to the one that just
// closed — leave it unattributed rather than folding it into history.
recentlySettledTurn: hasPendingTurnStart ? null : yield* getRecentlySettledTurn(),
at: now,
});
const activities = runtimeEventToActivities(event, taskTitle).map((activity) =>
activity.turnId === null && fallbackActivityTurnId !== null
? { ...activity, turnId: fallbackActivityTurnId }
: activity,
);
const activities = runtimeEventToActivities(event, taskTitle);
yield* Effect.forEach(activities, (activity) =>
providerCommandId(event, "thread-activity-append").pipe(
Effect.flatMap((commandId) =>
@@ -3,10 +3,15 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Stream from "effect/Stream";
import { ProjectionThreadRepository } from "../../persistence/Services/ProjectionThreads.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as TerminalManager from "../../terminal/Manager.ts";
import { WorktreeService } from "../../vcs/WorktreeService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
ThreadDeletionReactor,
@@ -40,6 +45,10 @@ const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const terminalManager = yield* TerminalManager.TerminalManager;
const serverSettings = yield* ServerSettingsService;
const worktreeService = yield* WorktreeService;
const threadRepository = yield* ProjectionThreadRepository;
const pathService = yield* Path.Path;
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
logCleanupCauseUnlessInterrupted({
@@ -55,12 +64,47 @@ const make = Effect.gen(function* () {
threadId,
});
const pruneOrphanedWorktree = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
logCleanupCauseUnlessInterrupted({
effect: Effect.gen(function* () {
const settings = yield* serverSettings.getSettings;
if (!settings.worktrees.deleteOrphanedImmediately) {
return;
}
const thread = Option.getOrNull(yield* threadRepository.getById({ threadId }));
if (thread === null || thread.worktreePath === null) {
return;
}
const worktreePath = pathService.resolve(thread.worktreePath);
const { worktrees } = yield* worktreeService.listWorktrees({
projectId: thread.projectId,
});
const record = worktrees.find((worktree) => worktree.path === worktreePath);
// Only orphans qualify here; worktrees still referenced by settled
// threads stay on the inactivity schedule. pruneWorktrees re-checks
// full safety (clean, pushed, no active thread) before removal.
if (record === undefined || !record.orphaned || !record.safeToPrune) {
return;
}
const result = yield* worktreeService.pruneWorktrees({ paths: [record.path] });
if (result.removed.length > 0) {
yield* Effect.logInfo("thread deletion pruned orphaned worktree", {
threadId,
worktreePath: record.path,
});
}
}),
message: "thread deletion cleanup skipped orphaned worktree prune",
threadId,
});
const processThreadDeleted = Effect.fn("processThreadDeleted")(function* (
event: ThreadDeletedEvent,
) {
const { threadId } = event.payload;
yield* stopProviderSession(threadId);
yield* closeThreadTerminals(threadId);
yield* pruneOrphanedWorktree(threadId);
});
const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>
+5 -16
View File
@@ -7,7 +7,6 @@ import {
type IsoDateTime,
type OrchestrationCommand,
OrchestrationDispatchCommandError,
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
@@ -110,24 +109,16 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
(attachment) =>
Effect.gen(function* () {
const parsed = parseBase64DataUrl(attachment.dataUrl);
// The upload's declared type is trusted only after the payload's
// real mime agrees with it: an image must actually be image/*, and
// a "file" that turns out to be an image is normalized to the image
// variant so it renders inline instead of as a download card.
if (!parsed || (attachment.type === "image" && !parsed.mimeType.startsWith("image/"))) {
if (!parsed || !parsed.mimeType.startsWith("image/")) {
return yield* new OrchestrationDispatchCommandError({
message: `Invalid ${attachment.type} attachment payload for '${attachment.name}'.`,
message: `Invalid image attachment payload for '${attachment.name}'.`,
});
}
const maxBytes =
attachment.type === "image"
? PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
: PROVIDER_SEND_TURN_MAX_FILE_BYTES;
const bytes = Buffer.from(parsed.base64, "base64");
if (bytes.byteLength === 0 || bytes.byteLength > maxBytes) {
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
return yield* new OrchestrationDispatchCommandError({
message: `Attachment '${attachment.name}' is empty or too large.`,
message: `Image attachment '${attachment.name}' is empty or too large.`,
});
}
@@ -139,9 +130,7 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
}
const persistedAttachment = {
type: parsed.mimeType.toLowerCase().startsWith("image/")
? ("image" as const)
: ("file" as const),
type: "image" as const,
id: attachmentId,
name: attachment.name,
mimeType: parsed.mimeType.toLowerCase(),
-2
View File
@@ -19,7 +19,6 @@ import {
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,
ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema,
ThreadNotificationDeliveredPayload as ContractsThreadNotificationDeliveredPayloadSchema,
ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema,
ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema,
ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema,
@@ -50,7 +49,6 @@ export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;
export const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema;
export const ThreadNotificationDeliveredPayload = ContractsThreadNotificationDeliveredPayloadSchema;
export const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema;
export const ThreadTurnInterruptRequestedPayload =
@@ -17,7 +17,6 @@ import type {
OrchestrationThreadDetailSnapshot,
OrchestrationThreadShell,
ProjectId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
@@ -116,18 +115,6 @@ export interface ProjectionSnapshotQueryShape {
workspaceRoot: string,
) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;
/**
* Read the active *agent project* for one provider instance — the synthetic
* row that lets a directoryless agent thread satisfy `project_id NOT NULL`.
*
* `Option.none` means no such project exists yet (or it was soft-deleted),
* which callers treat as "create one", not as an error. See
* `getOrCreateAgentProject`.
*/
readonly getActiveAgentProject: (
agentInstanceId: ProviderInstanceId,
) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;
/**
* Read a single active project shell row by id.
*/
@@ -165,39 +152,6 @@ export interface ProjectionSnapshotQueryShape {
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThreadShell>, ProjectionRepositoryError>;
/**
* Answer "does this thread row exist", independent of archive state.
*
* Every other thread read here filters `archived_at IS NULL`, which is right
* for "what should the user see" and wrong for existence: an archived thread
* is parked, not gone. Callers holding a durable reference to a specific
* thread — the Hermes home-thread designation — need this distinction, or
* archiving reads as deletion and they replace a thread the user still has.
*
* A soft-deleted row still reports absent.
*/
readonly getThreadArchiveStateById: (
threadId: ThreadId,
) => Effect.Effect<
Option.Option<{ readonly archivedAt: string | null }>,
ProjectionRepositoryError
>;
/**
* Answer "has this proactive delivery already been written to this thread",
* independent of archive state.
*
* The idempotency check behind `deliveryId` dedupe, kept off the detail read
* for the same reason `getThreadArchiveStateById` exists: `archived_at IS
* NULL` would make an archived thread report every delivery as absent, and
* each retry of one delivery would then append another copy. Reads only the
* provenance column, so it costs nothing near the message bodies.
*/
readonly hasThreadNotificationDelivery: (input: {
readonly threadId: ThreadId;
readonly deliveryId: string;
}) => Effect.Effect<boolean, ProjectionRepositoryError>;
/**
* Read a single active thread detail snapshot by id.
*/
@@ -1,328 +0,0 @@
import { assert, it } from "@effect/vitest";
import {
type OrchestrationCommand,
type OrchestrationProject,
ProjectId,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { ServerConfig } from "../config.ts";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
import { agentWorkspaceRoot, getOrCreateAgentProject } from "./agentProjects.ts";
import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
const INSTANCE_ID = ProviderInstanceId.make("hermes-siva-local-abc123");
const BASE_DIR = "/tmp/t3-agent-projects-test";
const makeAgentProject = (overrides: Partial<OrchestrationProject> = {}): OrchestrationProject => ({
id: ProjectId.make("agent-project-1"),
title: "Hermes Siva Local",
workspaceRoot: `${BASE_DIR}/agents/${INSTANCE_ID}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
agentInstanceId: INSTANCE_ID,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
...overrides,
});
/**
* Query stub whose `getActiveAgentProject` answers from a mutable queue, so a
* test can model "absent, then present" — the shape every self-healing path
* here depends on.
*/
const makeQueryLayer = (
responses: Ref.Ref<ReadonlyArray<Option.Option<OrchestrationProject>>>,
reads: Ref.Ref<number>,
) =>
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
getActiveAgentProject: () =>
Effect.gen(function* () {
yield* Ref.update(reads, (count) => count + 1);
const queue = yield* Ref.get(responses);
const [head, ...rest] = queue;
if (head === undefined) {
return Option.none<OrchestrationProject>();
}
yield* Ref.set(responses, rest.length > 0 ? rest : [head]);
return head;
}),
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.die("unused"),
getThreadArchiveStateById: () => Effect.die("unused"),
hasThreadNotificationDelivery: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
});
const makeEngineLayer = (
dispatched: Ref.Ref<ReadonlyArray<OrchestrationCommand>>,
options: { readonly fail?: boolean } = {},
) =>
Layer.succeed(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
dispatch: (command) =>
Ref.update(dispatched, (calls) => [...calls, command]).pipe(
Effect.andThen(
options.fail
? Effect.fail(
new OrchestrationCommandInvariantError({
commandType: "project.create",
detail: "A project already exists for this workspace root.",
}),
)
: Effect.succeed({ sequence: 1 }),
),
),
streamDomainEvents: Stream.empty,
latestSequence: Effect.succeed(0),
} as OrchestrationEngine.OrchestrationEngineService["Service"]);
const configLayer = Layer.succeed(ServerConfig, {
baseDir: BASE_DIR,
} as unknown as ServerConfig["Service"]);
it("derives the workspace root under the T3 home agents directory", () => {
assert.equal(
agentWorkspaceRoot({
baseDir: "/home/user/.t3",
instanceId: INSTANCE_ID,
join: (...parts) => parts.join("/"),
}),
`/home/user/.t3/agents/${INSTANCE_ID}`,
);
});
it.effect("returns the existing project without dispatching anything", () =>
Effect.gen(function* () {
const existing = makeAgentProject();
const responses = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationProject>>>([
Option.some(existing),
]);
const reads = yield* Ref.make(0);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const project = yield* getOrCreateAgentProject({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
Layer.mergeAll(
makeQueryLayer(responses, reads),
makeEngineLayer(dispatched),
configLayer,
NodeServices.layer,
),
),
);
assert.equal(project.id, existing.id);
// The common path must stay a single indexed read — this is called as a
// precondition on every agent thread start.
assert.equal(yield* Ref.get(reads), 1);
assert.deepEqual(yield* Ref.get(dispatched), []);
}),
);
it.effect("creates the project when none exists yet", () =>
Effect.gen(function* () {
const created = makeAgentProject();
const responses = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationProject>>>([
Option.none(),
Option.some(created),
]);
const reads = yield* Ref.make(0);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const project = yield* getOrCreateAgentProject({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
Layer.mergeAll(
makeQueryLayer(responses, reads),
makeEngineLayer(dispatched),
configLayer,
NodeServices.layer,
),
),
);
assert.equal(project.id, created.id);
const commands = yield* Ref.get(dispatched);
assert.equal(commands.length, 1);
const command = commands[0];
assert.equal(command?.type, "project.create");
if (command?.type === "project.create") {
assert.equal(command.agentInstanceId, INSTANCE_ID);
assert.equal(command.createWorkspaceRootIfMissing, true);
assert.equal(command.workspaceRoot, `${BASE_DIR}/agents/${INSTANCE_ID}`);
assert.equal(command.title, "Hermes Siva Local");
}
}),
);
it.effect("self-heals a soft-deleted project by creating a fresh one", () =>
Effect.gen(function* () {
// A soft-deleted row is invisible to `getActiveAgentProject`, so this is
// indistinguishable from "never created" — which is the point: the
// instance recovers instead of being permanently unusable.
const replacement = makeAgentProject({ id: ProjectId.make("agent-project-2") });
const responses = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationProject>>>([
Option.none(),
Option.some(replacement),
]);
const reads = yield* Ref.make(0);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const project = yield* getOrCreateAgentProject({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
Layer.mergeAll(
makeQueryLayer(responses, reads),
makeEngineLayer(dispatched),
configLayer,
NodeServices.layer,
),
),
);
assert.equal(project.id, replacement.id);
}),
);
it.effect("resolves to the winner's project when a concurrent caller wins the race", () =>
Effect.gen(function* () {
// The decider rejects a second project on the same workspace root, so the
// loser sees a dispatch failure. It must re-read and use the winner's row
// rather than surfacing an error to the user.
const winner = makeAgentProject({ id: ProjectId.make("agent-project-winner") });
const responses = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationProject>>>([
Option.none(),
Option.some(winner),
]);
const reads = yield* Ref.make(0);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const project = yield* getOrCreateAgentProject({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
Layer.mergeAll(
makeQueryLayer(responses, reads),
makeEngineLayer(dispatched, { fail: true }),
configLayer,
NodeServices.layer,
),
),
);
assert.equal(project.id, winner.id);
}),
);
it.effect("surfaces the dispatch failure when no project appears after it", () =>
Effect.gen(function* () {
const responses = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationProject>>>([
Option.none(),
]);
const reads = yield* Ref.make(0);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const result = yield* Effect.result(
getOrCreateAgentProject({ instanceId: INSTANCE_ID, title: "Hermes Siva Local" }).pipe(
Effect.provide(
Layer.mergeAll(
makeQueryLayer(responses, reads),
makeEngineLayer(dispatched, { fail: true }),
configLayer,
NodeServices.layer,
),
),
),
);
// A genuine failure must not be swallowed by the race-recovery read.
assert.equal(result._tag, "Failure");
}),
);
it.effect("falls back to the dispatched row when the projection has not caught up", () =>
Effect.gen(function* () {
const responses = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationProject>>>([
Option.none(),
]);
const reads = yield* Ref.make(0);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const project = yield* getOrCreateAgentProject({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
Layer.mergeAll(
makeQueryLayer(responses, reads),
makeEngineLayer(dispatched),
configLayer,
NodeServices.layer,
),
),
);
// Dispatch succeeded but the read-back saw nothing yet: the caller still
// gets a usable project rather than an error.
assert.equal(project.agentInstanceId, INSTANCE_ID);
assert.equal(project.workspaceRoot, `${BASE_DIR}/agents/${INSTANCE_ID}`);
assert.equal(project.deletedAt, null);
}),
);
it.effect("falls back to the instance id when the nickname is blank", () =>
Effect.gen(function* () {
const responses = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationProject>>>([
Option.none(),
]);
const reads = yield* Ref.make(0);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
yield* getOrCreateAgentProject({ instanceId: INSTANCE_ID, title: " " }).pipe(
Effect.provide(
Layer.mergeAll(
makeQueryLayer(responses, reads),
makeEngineLayer(dispatched),
configLayer,
NodeServices.layer,
),
),
);
// `title` is a TrimmedNonEmptyString on the command — a blank nickname
// would be a decode failure, not a cosmetic problem.
const command = (yield* Ref.get(dispatched))[0];
if (command?.type === "project.create") {
assert.equal(command.title, INSTANCE_ID);
}
}),
);
@@ -1,147 +0,0 @@
/**
* Agent projects — the synthetic project rows that back directoryless threads.
*
* `projection_threads.project_id` is `NOT NULL`, so a thread with a provider
* that owns its own machine (Hermes) still needs a project row to point at.
* That row is *synthetic*: `agentInstanceId` is set, its workspace root is a
* real but empty directory under `<t3home>/agents/<instanceId>/`, and every
* "pick a project" surface filters it out.
*
* ## Why converge-on-read instead of create-on-enrollment
*
* The obvious design is to create the project when an instance enrolls and
* delete it when the instance is removed. That leaves the system able to reach
* states it cannot recover from on its own:
*
* - enrollment succeeds but the project dispatch fails → the instance has no
* project, forever, and every thread start fails
* - instances enrolled before this code shipped have no project at all
* - a project soft-deleted by hand (or by a removal that later gets undone)
* leaves live threads unopenable
*
* `getOrCreateAgentProject` is instead a **precondition every caller runs**,
* not a lifecycle event one caller owns. It reads, and creates only what is
* missing. Any of the states above self-heals on the next call, and callers
* never have to reason about ordering. Enrollment still calls it, but only to
* warm the row — nothing depends on that call having happened.
*
* @module orchestration/agentProjects
*/
import {
CommandId,
ProjectId,
type OrchestrationProject,
type ProviderInstanceId,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { ServerConfig } from "../config.ts";
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
/** Directory name under `<t3home>` holding one directory per agent instance. */
export const AGENT_WORKSPACE_DIR = "agents";
/**
* Workspace root for one agent instance.
*
* A real directory, not a marker string: `OrchestrationProject.workspaceRoot`
* is a non-empty string that plenty of code will happily `stat`, and handing
* it a path that cannot exist would turn a cosmetic problem into a crash.
*/
export function agentWorkspaceRoot(input: {
readonly baseDir: string;
readonly instanceId: ProviderInstanceId;
readonly join: (...parts: ReadonlyArray<string>) => string;
}): string {
return input.join(input.baseDir, AGENT_WORKSPACE_DIR, input.instanceId);
}
/**
* Resolve the agent project for one provider instance, creating it if absent.
*
* Safe to call on every request: the common path is a single indexed read.
* Callers should treat this as a precondition rather than a mutation — it is
* idempotent, and concurrent callers converge on one row (see the recovery
* read below).
*/
export const getOrCreateAgentProject = Effect.fn("getOrCreateAgentProject")(function* (input: {
readonly instanceId: ProviderInstanceId;
/** Instance nickname, used as the project title on first creation. */
readonly title: string;
}) {
const query = yield* ProjectionSnapshotQuery;
const existing = yield* query.getActiveAgentProject(input.instanceId);
if (Option.isSome(existing)) {
return existing.value;
}
const engine = yield* OrchestrationEngineService;
const serverConfig = yield* ServerConfig;
const crypto = yield* Crypto.Crypto;
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const workspaceRoot = agentWorkspaceRoot({
baseDir: serverConfig.baseDir,
instanceId: input.instanceId,
join: path.join,
});
yield* fs.makeDirectory(workspaceRoot, { recursive: true });
const projectId = ProjectId.make(yield* crypto.randomUUIDv4);
const createdAt = DateTime.formatIso(yield* DateTime.now);
const dispatched = yield* Effect.result(
engine.dispatch({
type: "project.create",
commandId: CommandId.make(yield* crypto.randomUUIDv4),
projectId,
title: input.title.trim() || input.instanceId,
workspaceRoot,
createWorkspaceRootIfMissing: true,
agentInstanceId: input.instanceId,
createdAt,
}),
);
if (dispatched._tag === "Failure") {
// The decider rejects a second project on the same workspace root, so a
// racing caller that won shows up here as a dispatch failure rather than a
// duplicate row. Re-read before surfacing the error: if the row now
// exists, the race resolved correctly and this caller can use it.
const raced = yield* query.getActiveAgentProject(input.instanceId);
if (Option.isSome(raced)) {
return raced.value;
}
return yield* Effect.fail(dispatched.failure);
}
// Read back rather than synthesizing the row locally, so the caller always
// sees exactly what the projection committed.
const created = yield* query.getActiveAgentProject(input.instanceId);
if (Option.isSome(created)) {
return created.value;
}
// The dispatch succeeded but the projection has not caught up. Returning a
// locally-built row keeps the caller moving; the next call reads the real
// one. Every field matches what the decider emitted.
return {
id: projectId,
title: input.title.trim() || input.instanceId,
workspaceRoot,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
agentInstanceId: input.instanceId,
createdAt,
updatedAt: createdAt,
deletedAt: null,
} satisfies OrchestrationProject;
});
@@ -34,7 +34,6 @@ const readModel: OrchestrationReadModel = {
model: "gpt-5-codex",
},
scripts: [],
agentInstanceId: null,
createdAt: now,
updatedAt: now,
deletedAt: null,
@@ -48,7 +47,6 @@ const readModel: OrchestrationReadModel = {
model: "gpt-5-codex",
},
scripts: [],
agentInstanceId: null,
createdAt: now,
updatedAt: now,
deletedAt: null,
@@ -1,73 +0,0 @@
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import { expect, it } from "@effect/vitest";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
it.layer(NodeServices.layer)("assistant message replacement", (it) => {
it.effect("emits a streaming replacement message event", () =>
Effect.gen(function* () {
const now = "2026-07-24T12:00:00.000Z";
const threadId = ThreadId.make("thread-replacement");
const readModel = yield* projectEvent(createEmptyReadModel(now), {
sequence: 1,
eventId: EventId.make("event-thread-created"),
aggregateKind: "thread",
aggregateId: threadId,
type: "thread.created",
occurredAt: now,
commandId: CommandId.make("command-thread-created"),
causationEventId: null,
correlationId: CommandId.make("command-thread-created"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-replacement"),
title: "Replacement",
modelSelection: {
instanceId: ProviderInstanceId.make("hermes"),
model: "hermes",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
const decided = yield* decideOrchestrationCommand({
command: {
type: "thread.message.assistant.replace",
commandId: CommandId.make("command-message-replace"),
threadId,
messageId: MessageId.make("assistant:message-1"),
text: "Hello there",
turnId: TurnId.make("turn-1"),
createdAt: now,
},
readModel,
});
const event = Array.isArray(decided) ? decided[0] : decided;
if (event?.type !== "thread.message-sent") {
throw new Error("expected thread.message-sent");
}
expect(event.payload.text).toBe("Hello there");
expect(event.payload.streaming).toBe(true);
expect(event.payload.textOperation).toBe("replace");
}),
);
});
@@ -40,7 +40,6 @@ const seedReadModel = Effect.gen(function* () {
workspaceRoot: "/tmp/project-delete",
defaultModelSelection: null,
scripts: [],
agentInstanceId: null,
createdAt: now,
updatedAt: now,
},
@@ -1,317 +0,0 @@
import {
CommandId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type ChatAttachment,
type OrchestrationReadModel,
type OrchestrationThread,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
const NOW = "2026-07-01T00:00:00.000Z";
const DELIVERED_AT = "2026-06-30T09:00:00.000Z";
const SETTLED_AT = "2026-06-29T00:00:00.000Z";
const SNOOZED_UNTIL = "2026-07-02T00:00:00.000Z";
function makeReadModel(input: {
readonly settledOverride?: OrchestrationThread["settledOverride"];
readonly snoozedUntil?: string | null;
readonly messages?: OrchestrationThread["messages"];
}): OrchestrationReadModel {
const settledOverride = input.settledOverride ?? null;
return {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Home",
modelSelection: { instanceId: ProviderInstanceId.make("hermes"), model: "hermes" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
archivedAt: null,
settledOverride,
settledAt: settledOverride === "settled" ? SETTLED_AT : null,
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: input.snoozedUntil != null ? SETTLED_AT : null,
deletedAt: null,
messages: input.messages ?? [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: NOW,
};
}
function deliverCommand(overrides: {
readonly commandId: string;
readonly kind?: "cron" | "message" | "lifecycle" | "handoff" | "other";
readonly deliveryId?: string;
readonly messageId?: string;
readonly text?: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly turnId?: TurnId;
}) {
return {
type: "thread.notification.deliver",
commandId: CommandId.make(overrides.commandId),
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make(overrides.messageId ?? "message-1"),
deliveryId: overrides.deliveryId ?? "delivery-1",
kind: overrides.kind ?? "cron",
label: "Cron: daily-digest",
text: overrides.text ?? "Digest ready.",
...(overrides.attachments !== undefined ? { attachments: overrides.attachments } : {}),
...(overrides.turnId !== undefined ? { turnId: overrides.turnId } : {}),
createdAt: NOW,
} as const;
}
const mediaAttachment: ChatAttachment = {
type: "file",
id: "thread-1-2c8b3f1e-0000-4000-8000-000000000001",
name: "chart.mp4",
mimeType: "video/mp4",
sizeBytes: 2_048,
};
const deliveredMessage: OrchestrationThread["messages"][number] = {
id: MessageId.make("message-1"),
role: "assistant",
text: "Digest ready.",
turnId: null,
streaming: false,
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
},
createdAt: DELIVERED_AT,
updatedAt: DELIVERED_AT,
};
it.layer(NodeServices.layer)("notification delivery decider", (it) => {
it.effect("appends a turnless notification message and un-settles the thread", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
command: deliverCommand({ commandId: "cmd-deliver" }),
readModel: makeReadModel({ settledOverride: "settled" }),
});
const events = Array.isArray(result) ? result : [result];
expect(events.map((event) => event.type)).toEqual([
"thread.unsettled",
"thread.notification-delivered",
]);
const unsettled = events[0];
if (unsettled?.type === "thread.unsettled") {
expect(unsettled.payload.reason).toBe("activity");
}
const delivered = events[1];
if (delivered?.type === "thread.notification-delivered") {
expect(delivered.payload.messageId).toBe("message-1");
expect(delivered.payload.text).toBe("Digest ready.");
expect(delivered.payload.notification).toEqual({
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
});
// Nothing about a delivery belongs to a turn; attributing it to the
// thread's live turn would fold it behind that turn's summary.
expect("turnId" in delivered.payload).toBe(false);
}
}),
);
it.effect("un-snoozes as well as un-settles, and does neither when neither applies", () =>
Effect.gen(function* () {
const both = yield* decideOrchestrationCommand({
command: deliverCommand({ commandId: "cmd-deliver-both" }),
readModel: makeReadModel({ settledOverride: "settled", snoozedUntil: SNOOZED_UNTIL }),
});
expect((Array.isArray(both) ? both : [both]).map((event) => event.type)).toEqual([
"thread.unsettled",
"thread.unsnoozed",
"thread.notification-delivered",
]);
const neither = yield* decideOrchestrationCommand({
command: deliverCommand({ commandId: "cmd-deliver-neither" }),
readModel: makeReadModel({}),
});
expect((Array.isArray(neither) ? neither : [neither]).map((event) => event.type)).toEqual([
"thread.notification-delivered",
]);
}),
);
it.effect("appends lifecycle notices quietly, leaving settled and snoozed state alone", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
command: deliverCommand({ commandId: "cmd-lifecycle", kind: "lifecycle" }),
readModel: makeReadModel({ settledOverride: "settled", snoozedUntil: SNOOZED_UNTIL }),
});
const events = Array.isArray(result) ? result : [result];
// Unread indicator only: a restart notice must not drag a thread the
// user has parked back into the inbox.
expect(events.map((event) => event.type)).toEqual(["thread.notification-delivered"]);
}),
);
it.effect("dedupes a replayed deliveryId without appending or waking the thread", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
// The plugin's retry queue resends with a fresh command id, a new
// message id, and possibly edited text — only deliveryId is stable.
command: deliverCommand({
commandId: "cmd-deliver-retry",
messageId: "message-retry",
text: "Digest ready (retry).",
}),
readModel: makeReadModel({
settledOverride: "settled",
snoozedUntil: SNOOZED_UNTIL,
messages: [deliveredMessage],
}),
});
const events = Array.isArray(result) ? result : [result];
// No un-settle/un-snooze: a replay is not new activity.
expect(events.map((event) => event.type)).toEqual(["thread.notification-delivered"]);
const delivered = events[0];
if (delivered?.type === "thread.notification-delivered") {
// Re-emitted from the persisted row, so reducing it a second time is
// a byte-identical no-op rather than a duplicate or an overwrite.
expect(delivered.payload.messageId).toBe("message-1");
expect(delivered.payload.text).toBe("Digest ready.");
expect(delivered.payload.createdAt).toBe(DELIVERED_AT);
expect(delivered.payload.updatedAt).toBe(DELIVERED_AT);
expect(delivered.occurredAt).toBe(DELIVERED_AT);
}
}),
);
it.effect("treats a different deliveryId on the same thread as a new delivery", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
command: deliverCommand({
commandId: "cmd-deliver-second",
deliveryId: "delivery-2",
messageId: "message-2",
text: "Second digest.",
}),
readModel: makeReadModel({
settledOverride: "settled",
messages: [deliveredMessage],
}),
});
const events = Array.isArray(result) ? result : [result];
expect(events.map((event) => event.type)).toEqual([
"thread.unsettled",
"thread.notification-delivered",
]);
const delivered = events[1];
if (delivered?.type === "thread.notification-delivered") {
expect(delivered.payload.messageId).toBe("message-2");
expect(delivered.payload.notification.deliveryId).toBe("delivery-2");
}
}),
);
it.effect("threads media attachments and turnId through the delivered payload", () =>
Effect.gen(function* () {
const turnId = TurnId.make("turn-live");
const result = yield* decideOrchestrationCommand({
command: deliverCommand({
commandId: "cmd-deliver-media",
deliveryId: "delivery-media",
messageId: "message-media",
text: "A caption",
attachments: [mediaAttachment],
turnId,
}),
readModel: makeReadModel({}),
});
const events = Array.isArray(result) ? result : [result];
const delivered = events.find((event) => event.type === "thread.notification-delivered");
if (delivered?.type === "thread.notification-delivered") {
expect(delivered.payload.attachments).toEqual([mediaAttachment]);
expect(delivered.payload.turnId).toBe(turnId);
} else {
expect.unreachable("expected a thread.notification-delivered event");
}
}),
);
it.effect("rebuilds media replays from the persisted row, not the retry's fields", () =>
Effect.gen(function* () {
const persisted: OrchestrationThread["messages"][number] = {
...deliveredMessage,
id: MessageId.make("message-media"),
text: "A caption",
turnId: TurnId.make("turn-live"),
attachments: [mediaAttachment],
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-media",
},
};
const result = yield* decideOrchestrationCommand({
// The retry names a different messageId and attachment id — its bytes
// were written under the original id, so adopting the retry's fields
// would re-point the row at files that do not exist.
command: deliverCommand({
commandId: "cmd-deliver-media-retry",
deliveryId: "delivery-media",
messageId: "message-media-retry",
text: "A caption (retry)",
attachments: [
{ ...mediaAttachment, id: "thread-1-2c8b3f1e-0000-4000-8000-00000000dead" },
],
}),
readModel: makeReadModel({ messages: [persisted] }),
});
const events = Array.isArray(result) ? result : [result];
expect(events.map((event) => event.type)).toEqual(["thread.notification-delivered"]);
const delivered = events[0];
if (delivered?.type === "thread.notification-delivered") {
expect(delivered.payload.messageId).toBe("message-media");
expect(delivered.payload.text).toBe("A caption");
expect(delivered.payload.attachments).toEqual([mediaAttachment]);
expect(delivered.payload.turnId).toBe("turn-live");
}
}),
);
it.effect("rejects a delivery for a thread that does not exist", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
...deliverCommand({ commandId: "cmd-deliver-missing" }),
threadId: ThreadId.make("thread-missing"),
},
readModel: makeReadModel({}),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
});
@@ -63,7 +63,6 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
workspaceRoot: "/tmp/scripts",
defaultModelSelection: null,
scripts: [],
agentInstanceId: null,
createdAt: now,
updatedAt: now,
},
@@ -116,7 +115,6 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
scripts: [],
agentInstanceId: null,
createdAt: now,
updatedAt: now,
},
@@ -163,7 +161,6 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
workspaceRoot: "/tmp/project-first",
defaultModelSelection: null,
scripts: [],
agentInstanceId: null,
createdAt: now,
updatedAt: now,
},
@@ -185,7 +182,6 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
workspaceRoot: "/tmp/project-second",
defaultModelSelection: null,
scripts: [],
agentInstanceId: null,
createdAt: now,
updatedAt: now,
},
@@ -230,7 +226,6 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
scripts: [],
agentInstanceId: null,
createdAt: now,
updatedAt: now,
},
@@ -328,7 +323,6 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
scripts: [],
agentInstanceId: null,
createdAt: now,
updatedAt: now,
},
@@ -407,7 +401,6 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
scripts: [],
agentInstanceId: null,
createdAt: now,
updatedAt: now,
},
-132
View File
@@ -251,7 +251,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
workspaceRoot: command.workspaceRoot,
defaultModelSelection: command.defaultModelSelection ?? null,
scripts: [],
agentInstanceId: command.agentInstanceId ?? null,
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
@@ -1019,34 +1018,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.message.assistant.replace": {
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.message-sent",
payload: {
threadId: command.threadId,
messageId: command.messageId,
role: "assistant",
text: command.text,
turnId: command.turnId ?? null,
streaming: true,
textOperation: "replace",
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
};
}
case "thread.message.assistant.complete": {
yield* requireThread({
readModel,
@@ -1197,109 +1168,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
return [unsettledEvent, activityAppendedEvent];
}
case "thread.notification.deliver": {
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
// Dedupe on deliveryId: the plugin's durable queue retries anything it
// has not seen acked, so the same delivery legitimately arrives more
// than once. Idempotency is by re-emission (see thread.settle) because
// the engine rejects a command that produces no events — but unlike
// settle, the payload must be rebuilt from the ALREADY-WRITTEN message
// rather than from the command, so reducing it a second time lands on
// byte-identical state instead of rewriting the row from a retry whose
// messageId or text may differ.
//
// NOT SUFFICIENT ON ITS OWN. This scans the in-memory read model, which
// `getCommandReadModel` builds with `messages: []` on every thread — it
// deliberately does not hydrate message bodies at boot. So this catches
// only replays of deliveries appended since the process started, and
// sees nothing after a restart. The delivery path re-checks against
// `projection_thread_messages` before dispatching
// (`hermesGatewayHttp.ts`), and that read is what actually holds across
// a restart. Keep both: this one keeps the aggregate self-consistent for
// any future caller, the other one is load-bearing.
const duplicate = thread.messages.find(
(message) => message.notification?.deliveryId === command.deliveryId,
);
// On replay these too come from the persisted row, for the same reason
// as the text: the retry's attachment ids point at files written for a
// different messageId, and adopting them would re-point the row.
const attachments = duplicate ? duplicate.attachments : command.attachments;
const turnId = duplicate ? (duplicate.turnId ?? undefined) : command.turnId;
const notificationEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: duplicate?.createdAt ?? command.createdAt,
commandId: command.commandId,
})),
type: "thread.notification-delivered",
payload: {
threadId: command.threadId,
messageId: duplicate?.id ?? command.messageId,
text: duplicate?.text ?? command.text,
notification: duplicate?.notification ?? {
kind: command.kind,
label: command.label,
deliveryId: command.deliveryId,
},
...(attachments !== undefined ? { attachments } : {}),
...(turnId !== undefined ? { turnId } : {}),
createdAt: duplicate?.createdAt ?? command.createdAt,
updatedAt: duplicate?.updatedAt ?? command.createdAt,
},
};
// A replay is not new activity: it must never wake a thread the user
// has since settled or snoozed.
if (duplicate !== undefined) {
return notificationEvent;
}
// A lifecycle notice ("agent restarted") is bookkeeping, not a claim on
// the user's attention: it appends quietly and leaves a settled or
// snoozed thread where it is. Every other kind is the agent raising its
// hand and resets the lifecycle exactly like a user message does.
if (command.kind === "lifecycle") {
return notificationEvent;
}
const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
if (thread.settledOverride !== null) {
lifecycleResetEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
});
}
if (thread.snoozedUntil != null) {
lifecycleResetEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsnoozed",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
});
}
return [...lifecycleResetEvents, notificationEvent];
}
default: {
command satisfies never;
const fallback = command as never as { type: string };
@@ -1,480 +0,0 @@
import { assert, it } from "@effect/vitest";
import {
DEFAULT_HERMES_MODEL,
HERMES_DRIVER_KIND,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationCommand,
type OrchestrationProject,
type OrchestrationThreadShell,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { ServerConfig } from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
import {
HOME_THREAD_TITLE,
getDesignatedHomeThreadId,
getOrCreateHomeThread,
isHomeThread,
readHomeThreadId,
} from "./homeThreads.ts";
import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
const INSTANCE_ID = ProviderInstanceId.make("hermes-siva-local-abc123");
const OTHER_INSTANCE_ID = ProviderInstanceId.make("hermes-other-def456");
const HOME_THREAD_ID = ThreadId.make("thread-home-1");
const BASE_DIR = "/tmp/t3-home-threads-test";
const agentProject: OrchestrationProject = {
id: ProjectId.make("agent-project-1"),
title: "Hermes Siva Local",
workspaceRoot: `${BASE_DIR}/agents/${INSTANCE_ID}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
agentInstanceId: INSTANCE_ID,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
};
const threadShell = (id: ThreadId): OrchestrationThreadShell =>
({
id,
projectId: agentProject.id,
title: HOME_THREAD_TITLE,
modelSelection: { instanceId: INSTANCE_ID, model: DEFAULT_HERMES_MODEL },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
}) as OrchestrationThreadShell;
const hermesInstance = (config: Record<string, unknown>) => ({
driver: HERMES_DRIVER_KIND,
displayName: "Hermes Siva Local",
enabled: true,
config,
});
/**
* Query stub answering thread reads from a mutable queue, so a test can model
* "designated but deleted" — the self-healing path this module exists for.
*/
const makeQueryLayer = (
threads: Ref.Ref<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>,
archiveStates?: ReadonlyArray<Option.Option<{ readonly archivedAt: string | null }>>,
) =>
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
getActiveAgentProject: () => Effect.succeed(Option.some(agentProject)),
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadArchiveStateById: () =>
Effect.gen(function* () {
if (archiveStates?.[0] !== undefined) return archiveStates[0];
// Default: mirror the shell queue, since a thread visible to the shell
// query is also present. Tests about archiving pass this explicitly.
const queue = yield* Ref.get(threads);
return Option.map(queue[0] ?? Option.none(), () => ({ archivedAt: null }));
}),
getThreadShellById: () =>
Effect.gen(function* () {
const queue = yield* Ref.get(threads);
const [head, ...rest] = queue;
if (head === undefined) return Option.none<OrchestrationThreadShell>();
yield* Ref.set(threads, rest.length > 0 ? rest : [head]);
return head;
}),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
} as unknown as ProjectionSnapshotQuery["Service"]);
const makeEngineLayer = (
dispatched: Ref.Ref<ReadonlyArray<OrchestrationCommand>>,
options: {
readonly fail?: boolean;
/**
* Runs after each command is recorded. The only hook that fires *inside*
* `getOrCreateHomeThread`, which is what lets a test land a competing
* settings write between this caller's read and its persist.
*/
readonly onDispatch?: (command: OrchestrationCommand) => Effect.Effect<void, never, never>;
} = {},
) =>
Layer.succeed(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
dispatch: (command: OrchestrationCommand) =>
Ref.update(dispatched, (calls) => [...calls, command]).pipe(
Effect.andThen(options.onDispatch ? options.onDispatch(command) : Effect.void),
Effect.andThen(
options.fail
? Effect.fail(
new OrchestrationCommandInvariantError({
commandType: "thread.create",
detail: "Simulated dispatch failure.",
}),
)
: Effect.succeed({ sequence: 1 }),
),
),
streamDomainEvents: Stream.empty,
latestSequence: Effect.succeed(0),
} as OrchestrationEngine.OrchestrationEngineService["Service"]);
const configLayer = Layer.succeed(ServerConfig, {
baseDir: BASE_DIR,
} as unknown as ServerConfig["Service"]);
const testLayer = (input: {
readonly threads: Ref.Ref<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>;
readonly dispatched: Ref.Ref<ReadonlyArray<OrchestrationCommand>>;
readonly providerInstances: Record<string, unknown>;
readonly failDispatch?: boolean;
/** Fires inside `getOrCreateHomeThread`, right after `thread.create`. */
readonly onDispatch?: (command: OrchestrationCommand) => Effect.Effect<void, never, never>;
/**
* Settings layer to use instead of a fresh one. A test that needs to write
* settings from `onDispatch` builds the layer itself so both sides share one
* store.
*/
readonly settingsLayer?: ReturnType<typeof ServerSettings.layerTest>;
/**
* Archive-state rows. Unlike the shell queue these ignore archive state, so
* a test can model "archived, therefore invisible to the shell query but
* still very much present" — the case that used to mint a second Home.
*/
readonly archiveStates?: ReadonlyArray<Option.Option<{ readonly archivedAt: string | null }>>;
}) =>
Layer.mergeAll(
makeQueryLayer(input.threads, input.archiveStates),
makeEngineLayer(input.dispatched, {
...(input.failDispatch ? { fail: true } : {}),
...(input.onDispatch ? { onDispatch: input.onDispatch } : {}),
}),
configLayer,
input.settingsLayer ??
ServerSettings.layerTest({
providerInstances: input.providerInstances,
} as never),
NodeServices.layer,
);
it("reads a designation only from a Hermes envelope", () => {
assert.equal(
readHomeThreadId(hermesInstance({ homeThreadId: HOME_THREAD_ID }) as never),
HOME_THREAD_ID,
);
assert.equal(readHomeThreadId(hermesInstance({}) as never), undefined);
// An empty string is "not designated", not a thread whose id is "".
assert.equal(readHomeThreadId(hermesInstance({ homeThreadId: "" }) as never), undefined);
// A designation on a non-Hermes envelope is not ours to honour.
assert.equal(
readHomeThreadId({ driver: "codex", homeThreadId: HOME_THREAD_ID } as never),
undefined,
);
});
it.effect("returns the designated thread without dispatching anything", () =>
Effect.gen(function* () {
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.some(threadShell(HOME_THREAD_ID)),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const resolved = yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
providerInstances: {
[INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }),
},
}),
),
);
assert.equal(resolved, HOME_THREAD_ID);
// This runs on every handshake; it must not create anything on the happy path.
assert.deepEqual(yield* Ref.get(dispatched), []);
}),
);
it.effect("creates and persists a Home thread when none is designated", () =>
Effect.gen(function* () {
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.none(),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
yield* Effect.gen(function* () {
const resolved = yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
});
const commands = yield* Ref.get(dispatched);
const created = commands.find((command) => command.type === "thread.create");
assert.isDefined(created);
if (created?.type === "thread.create") {
assert.equal(created.threadId, resolved);
assert.equal(created.title, HOME_THREAD_TITLE);
assert.equal(created.projectId, agentProject.id);
// Binds to the fixed Hermes slug, not to whatever model the plugin
// currently reports — otherwise the thread orphans on a model change.
assert.equal(created.modelSelection.model, DEFAULT_HERMES_MODEL);
}
// The designation must be durable, or the next handshake mints a second
// Home and the first one's history is stranded.
assert.equal(yield* getDesignatedHomeThreadId(INSTANCE_ID), resolved);
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
providerInstances: { [INSTANCE_ID]: hermesInstance({}) },
}),
),
);
}),
);
it.effect("self-heals a designation whose thread no longer exists", () =>
Effect.gen(function* () {
// A deleted home thread must not strand the instance: it re-designates
// rather than failing every future delivery.
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.none(),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const resolved = yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
providerInstances: {
[INSTANCE_ID]: hermesInstance({ homeThreadId: "thread-deleted-long-ago" }),
},
}),
),
);
assert.notEqual(resolved, "thread-deleted-long-ago");
const commands = yield* Ref.get(dispatched);
assert.isDefined(commands.find((command) => command.type === "thread.create"));
}),
);
it.effect("adopts a racing caller's designation when its own dispatch fails", () =>
Effect.gen(function* () {
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.none(),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
// The loser of the race sees a dispatch failure but must still return the
// winner's thread rather than surfacing an error to the handshake.
const resolved = yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
failDispatch: true,
providerInstances: {
// Designated, but the thread read says gone — so it falls through
// to create, fails, and re-reads the designation.
[INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }),
},
}),
),
);
assert.equal(resolved, HOME_THREAD_ID);
}),
);
it.effect("does not clobber a designation that landed while it was creating", () =>
Effect.gen(function* () {
// Two handshakes race: both read "no designation", both create a thread.
// The one that persists *second* must stand down rather than overwrite —
// otherwise the first caller re-read the winner's id and returned it while
// this one overwrites with its own, so the two disagree about Home and
// concurrent proactive deliveries land in two different threads.
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.none(),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const settingsLayer = ServerSettings.layerTest({
providerInstances: { [INSTANCE_ID]: hermesInstance({}) },
} as never);
yield* Effect.gen(function* () {
const settings = yield* ServerSettings.ServerSettingsService;
const resolved = yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
providerInstances: {},
settingsLayer,
// The racing caller wins the settings write while this one is
// still between `thread.create` and its own persist.
onDispatch: () =>
settings
.updateSettingsWith((latest) => ({
providerInstances: {
...latest.providerInstances,
[INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }),
},
}))
.pipe(Effect.ignore),
}),
),
);
// Both callers agree on the winner's thread, and the loser's own thread
// stays an empty thread in the agent project rather than a second Home.
assert.equal(resolved, HOME_THREAD_ID);
assert.equal(yield* getDesignatedHomeThreadId(INSTANCE_ID), HOME_THREAD_ID);
}).pipe(Effect.provide(settingsLayer));
}),
);
it.effect("recognizes any instance's home thread as undeletable", () =>
Effect.gen(function* () {
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
yield* Effect.gen(function* () {
assert.isTrue(yield* isHomeThread(HOME_THREAD_ID));
// Scans every instance, not just one — the delete path knows only a thread.
assert.isTrue(yield* isHomeThread(ThreadId.make("thread-home-2")));
assert.isFalse(yield* isHomeThread(ThreadId.make("thread-ordinary")));
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
providerInstances: {
[INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }),
[OTHER_INSTANCE_ID]: hermesInstance({ homeThreadId: "thread-home-2" }),
},
}),
),
);
}),
);
it.effect("keeps an archived Home rather than minting a replacement", () =>
Effect.gen(function* () {
// The bug this pins: `getThreadShellById` filters `archived_at IS NULL`, so
// an archived Home read as *deleted* and the self-healing path created a
// second one — stranding the real history and silently re-pointing the
// designation at an empty thread.
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.none(),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const resolved = yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
archiveStates: [Option.some({ archivedAt: "2026-01-02T00:00:00.000Z" })],
providerInstances: {
[INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }),
},
}),
),
);
assert.equal(resolved, HOME_THREAD_ID);
const commands = yield* Ref.get(dispatched);
assert.isUndefined(
commands.find((command) => command.type === "thread.create"),
"an archived Home must never be replaced by a new thread",
);
// A delivery is the agent raising its hand, so it brings the thread back
// rather than landing somewhere the user cannot see.
const unarchive = commands.find((command) => command.type === "thread.unarchive");
assert.isDefined(unarchive);
if (unarchive?.type === "thread.unarchive") {
assert.equal(unarchive.threadId, HOME_THREAD_ID);
}
}),
);
it.effect("does not un-archive a Home that was never archived", () =>
Effect.gen(function* () {
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.some(threadShell(HOME_THREAD_ID)),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
archiveStates: [Option.some({ archivedAt: null })],
providerInstances: {
[INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }),
},
}),
),
);
// The common path stays free of writes; this runs on every handshake.
assert.deepEqual(yield* Ref.get(dispatched), []);
}),
);
@@ -1,261 +0,0 @@
/**
* Home threads — the one thread per agent instance that receives its agent's
* proactive output.
*
* Hermes has a first-class "home channel" concept: a per-platform default
* destination for output nobody asked for at a specific address — a cron job's
* result, an agent-initiated `send_message`, a gateway online notice, a
* `/handoff`. Every other Hermes surface designates one interactively via
* `/sethome`. T3 designates one automatically instead, because there is no
* "current channel" here for a user to point at: threads are created on
* demand, and asking someone to pick one before their first cron job can fire
* is setup for a decision they have no basis to make.
*
* ## Converge-on-read, like agent projects
*
* `getOrCreateHomeThread` is a **precondition every caller runs**, not a
* lifecycle event one caller owns — the same reasoning as
* `getOrCreateAgentProject`, and for the same failure modes: an instance
* enrolled before this shipped has no designation, a dispatch that failed once
* would otherwise leave the instance permanently unable to receive, and a
* thread deleted out from under the designation would strand every future
* delivery. Each of those self-heals on the next handshake.
*
* ## Why settings and not a table
*
* The designation is per-instance enrollment metadata, exactly like
* `connectorUrl` and `revoked`, and it lives beside them in the Hermes
* instance's config blob. That keeps one source of truth for "facts about this
* enrollment" and avoids a migration for a single nullable id.
*
* The plugin's `T3_HOME_CHANNEL` env var is a *cache* of this value, reconciled
* on every `connection.accepted`. This module is authoritative; drift is
* bounded by one reconnect.
*
* @module orchestration/homeThreads
*/
import {
CommandId,
DEFAULT_HERMES_MODEL,
DEFAULT_PROVIDER_INTERACTION_MODE,
HERMES_DRIVER_KIND,
ThreadId,
type ProviderInstanceConfig,
type ProviderInstanceId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { ServerSettingsService } from "../serverSettings.ts";
import { getOrCreateAgentProject } from "./agentProjects.ts";
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
/**
* Title of the home thread. Plain, no emoji: it sits in the same list as the
* user's own threads and should not shout.
*/
export const HOME_THREAD_TITLE = "Home";
/** Read the designated home thread id out of a Hermes instance envelope. */
export const readHomeThreadId = (
config: ProviderInstanceConfig | undefined,
): ThreadId | undefined => {
if (!config || config.driver !== HERMES_DRIVER_KIND) return undefined;
const blob = config.config && typeof config.config === "object" ? config.config : {};
const raw = (blob as Record<string, unknown>).homeThreadId;
return typeof raw === "string" && raw !== "" ? ThreadId.make(raw) : undefined;
};
/**
* Read one instance's designation straight from settings.
*
* Callers that only need to *know* the designation — the snapshot builder, the
* delete guard — use this rather than `getOrCreateHomeThread`, so a read never
* has the side effect of creating a thread.
*/
export const getDesignatedHomeThreadId = Effect.fn("getDesignatedHomeThreadId")(function* (
instanceId: ProviderInstanceId,
) {
const settings = yield* ServerSettingsService;
const current = yield* settings.getSettings;
return readHomeThreadId(current.providerInstances[instanceId]);
});
/**
* Whether a thread is some instance's home thread, and therefore undeletable.
*
* Scans every configured instance rather than taking an instance id, because
* the delete path knows only the thread. The map is small — one entry per
* configured provider instance — and this runs once per delete.
*/
export const isHomeThread = Effect.fn("isHomeThread")(function* (threadId: ThreadId) {
const settings = yield* ServerSettingsService;
const current = yield* settings.getSettings;
for (const config of Object.values(current.providerInstances)) {
if (readHomeThreadId(config) === threadId) return true;
}
return false;
});
/**
* Read the designated thread's row regardless of archive state.
*
* The snapshot query's thread reads filter `archived_at IS NULL`, which is
* correct for "what should the user see" and wrong for "does this row exist".
* Going to the repository directly is what keeps an archived Home from looking
* deleted — and thereby keeps this module from minting a second one. A
* soft-deleted row still counts as gone.
*/
const readHomeThreadRow = Effect.fn("readHomeThreadRow")(function* (threadId: ThreadId) {
const query = yield* ProjectionSnapshotQuery;
const row = yield* query.getThreadArchiveStateById(threadId);
return Option.getOrUndefined(row);
});
/**
* Persist a designation into the instance's Hermes config blob.
*
* A compare-and-set against `expected` — the designation this caller read
* before deciding to create — rather than a blind write. Two concurrent
* callers that both mint a thread would otherwise each persist their own id,
* and the one that wrote first re-reads before the other's overwrite lands, so
* the two return *different* threads and one is orphaned from the final
* designation. Standing down when the designation moved out from under us is
* what makes the caller's re-read below an actual tiebreaker.
*
* `expected` still has to be honoured rather than "never overwrite": the
* self-healing path arrives here with a stale designation pointing at a thread
* that is really gone, and replacing exactly that value is the whole point.
*/
const persistHomeThreadId = (input: {
readonly instanceId: ProviderInstanceId;
readonly threadId: ThreadId;
/** Designation observed before creating, or `undefined` if there was none. */
readonly expected: ThreadId | undefined;
}) =>
Effect.gen(function* () {
const settings = yield* ServerSettingsService;
yield* settings.updateSettingsWith((latest) => {
// Re-read under the settings write lock: the envelope may have been
// replaced (or the driver changed) between our read and this write, and
// writing a Hermes designation onto a non-Hermes envelope would corrupt
// it. Returning an empty patch is the established no-op here.
const existing = latest.providerInstances[input.instanceId];
if (!existing || existing.driver !== HERMES_DRIVER_KIND) return {};
// Someone else designated (or re-designated) while we were creating.
// Adopt theirs; ours stays an empty thread in the agent project.
if (readHomeThreadId(existing) !== input.expected) return {};
const currentConfig =
existing.config && typeof existing.config === "object"
? (existing.config as Record<string, unknown>)
: {};
return {
providerInstances: {
...latest.providerInstances,
[input.instanceId]: {
...existing,
config: { ...currentConfig, homeThreadId: input.threadId },
},
},
};
});
});
/**
* Resolve the home thread for one provider instance, creating it if absent.
*
* Safe to call on every handshake: the common path is one settings read plus
* one indexed thread read. Idempotent, and concurrent callers converge —
* the loser of a race re-reads and adopts the winner's thread.
*/
export const getOrCreateHomeThread = Effect.fn("getOrCreateHomeThread")(function* (input: {
readonly instanceId: ProviderInstanceId;
/** Instance nickname, used as the agent project's title on first creation. */
readonly title: string;
}) {
const engine = yield* OrchestrationEngineService;
const crypto = yield* Crypto.Crypto;
const designated = yield* getDesignatedHomeThreadId(input.instanceId);
if (designated !== undefined) {
// Deliberately NOT `getThreadShellById`: that query filters
// `archived_at IS NULL`, so an archived Home reads as absent and this
// function would "self-heal" by minting a second Home — stranding the
// history in the archived one and silently re-pointing the designation.
// Archiving is a user parking a thread, not destroying it; only a row
// that is really gone justifies a replacement.
const existing = yield* readHomeThreadRow(designated);
if (existing !== undefined) {
// Un-archive rather than deliver into a hidden thread. A delivery is
// the agent raising its hand, and the same rule the decider applies to
// settled/snoozed threads applies here: incoming activity brings the
// thread back. Best-effort — a failure here must not cost the delivery.
if (existing.archivedAt !== null) {
yield* engine
.dispatch({
type: "thread.unarchive",
commandId: CommandId.make(yield* crypto.randomUUIDv4),
threadId: designated,
})
.pipe(
Effect.catchCause((cause) =>
Effect.logWarning("could not un-archive the home thread", {
instanceId: input.instanceId,
threadId: designated,
cause: Cause.pretty(cause),
}),
),
);
}
return designated;
}
}
const project = yield* getOrCreateAgentProject({
instanceId: input.instanceId,
title: input.title,
});
const threadId = ThreadId.make(yield* crypto.randomUUIDv4);
const createdAt = DateTime.formatIso(yield* DateTime.now);
const dispatched = yield* Effect.result(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make(yield* crypto.randomUUIDv4),
threadId,
projectId: project.id,
title: HOME_THREAD_TITLE,
// The same fixed slug every Hermes thread binds to — the reported model
// name is display-only, and following it here would orphan the thread
// whenever Hermes' own config changed.
modelSelection: { instanceId: input.instanceId, model: DEFAULT_HERMES_MODEL },
runtimeMode: "full-access",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
branch: null,
worktreePath: null,
createdAt,
}),
);
if (dispatched._tag === "Failure") {
// A concurrent handshake may have won and already persisted its thread.
// Re-read before surfacing the error, matching getOrCreateAgentProject.
const raced = yield* getDesignatedHomeThreadId(input.instanceId);
if (raced !== undefined) return raced;
return yield* Effect.fail(dispatched.failure);
}
yield* persistHomeThreadId({ instanceId: input.instanceId, threadId, expected: designated });
// Re-read rather than trusting our own write: if a racing caller persisted
// first, both callers must agree on one thread, and settings is the
// tiebreaker. Our orphaned thread stays as an empty thread in the project
// rather than becoming a second home.
const settled = yield* getDesignatedHomeThreadId(input.instanceId);
return settled ?? threadId;
});
@@ -1,189 +0,0 @@
import {
CommandId,
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const CREATED_AT = "2026-07-01T09:00:00.000Z";
const DELIVERED_AT = "2026-07-01T09:05:00.000Z";
function makeEvent(input: {
readonly sequence: number;
readonly type: OrchestrationEvent["type"];
readonly occurredAt: string;
readonly payload: unknown;
}): OrchestrationEvent {
return {
sequence: input.sequence,
eventId: EventId.make(`event-${input.sequence}`),
type: input.type,
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-home"),
occurredAt: input.occurredAt,
commandId: CommandId.make(`command-${input.sequence}`),
causationEventId: null,
correlationId: null,
metadata: {},
payload: input.payload as never,
} as OrchestrationEvent;
}
const threadCreatedEvent = makeEvent({
sequence: 1,
type: "thread.created",
occurredAt: CREATED_AT,
payload: {
threadId: ThreadId.make("thread-home"),
projectId: ProjectId.make("project-1"),
title: "Home",
modelSelection: { instanceId: ProviderInstanceId.make("hermes"), model: "hermes" },
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: CREATED_AT,
updatedAt: CREATED_AT,
},
});
const deliveryEvent = makeEvent({
sequence: 2,
type: "thread.notification-delivered",
occurredAt: DELIVERED_AT,
payload: {
threadId: ThreadId.make("thread-home"),
messageId: MessageId.make("notification:msg-1"),
text: "Digest ready.",
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
},
createdAt: DELIVERED_AT,
updatedAt: DELIVERED_AT,
},
});
const expectedMessage = {
id: "notification:msg-1",
role: "assistant",
text: "Digest ready.",
// A delivery belongs to no turn and is never streamed.
turnId: null,
streaming: false,
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
},
createdAt: DELIVERED_AT,
updatedAt: DELIVERED_AT,
};
it.effect("appends a notification delivery as a turnless assistant message", () =>
Effect.gen(function* () {
const created = yield* projectEvent(createEmptyReadModel(CREATED_AT), threadCreatedEvent);
const delivered = yield* projectEvent(created, deliveryEvent);
const thread = delivered.threads[0];
expect(thread?.messages).toHaveLength(1);
expect(thread?.messages[0]).toEqual(expectedMessage);
expect(thread?.updatedAt).toBe(DELIVERED_AT);
// Nothing about a delivery touches turn state — attributing it to the
// thread's live turn would fold it behind that turn's summary.
expect(thread?.latestTurn).toBeNull();
}),
);
it.effect("replays a delivery onto the same message instead of duplicating it", () =>
Effect.gen(function* () {
const created = yield* projectEvent(createEmptyReadModel(CREATED_AT), threadCreatedEvent);
const delivered = yield* projectEvent(created, deliveryEvent);
// The decider re-emits the persisted row for a replayed deliveryId, so
// reducing the event twice must be a no-op rather than an append.
const replayed = yield* projectEvent(delivered, { ...deliveryEvent, sequence: 3 });
expect(replayed.threads[0]?.messages).toHaveLength(1);
expect(replayed.threads[0]?.messages[0]).toEqual(expectedMessage);
}),
);
it.effect("projects media deliveries with attachments and an optional turnId", () =>
Effect.gen(function* () {
const created = yield* projectEvent(createEmptyReadModel(CREATED_AT), threadCreatedEvent);
const attachment = {
type: "file",
id: "thread-home-2c8b3f1e-0000-4000-8000-000000000001",
name: "chart.mp4",
mimeType: "video/mp4",
sizeBytes: 2_048,
} as const;
const delivered = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.notification-delivered",
occurredAt: DELIVERED_AT,
payload: {
threadId: ThreadId.make("thread-home"),
messageId: MessageId.make("notification:media-1"),
text: "A caption",
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-media",
},
attachments: [attachment],
turnId: "turn-live",
createdAt: DELIVERED_AT,
updatedAt: DELIVERED_AT,
},
}),
);
const message = delivered.threads[0]?.messages[0];
expect(message?.attachments).toEqual([attachment]);
// Turn-scoped media names its turn so it sequences beside the turn's text.
expect(message?.turnId).toBe("turn-live");
}),
);
it.effect("keeps deliveries alongside ordinary turn messages", () =>
Effect.gen(function* () {
const created = yield* projectEvent(createEmptyReadModel(CREATED_AT), threadCreatedEvent);
const withUserMessage = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.message-sent",
occurredAt: "2026-07-01T09:01:00.000Z",
payload: {
threadId: ThreadId.make("thread-home"),
messageId: MessageId.make("msg-user"),
role: "user",
text: "hi",
turnId: null,
streaming: false,
createdAt: "2026-07-01T09:01:00.000Z",
updatedAt: "2026-07-01T09:01:00.000Z",
},
}),
);
const delivered = yield* projectEvent(withUserMessage, { ...deliveryEvent, sequence: 3 });
expect(delivered.threads[0]?.messages.map((message) => message.id)).toEqual([
"msg-user",
"notification:msg-1",
]);
// Absence of `notification` is what marks an ordinary message; it must
// never be synthesized onto one.
expect(delivered.threads[0]?.messages[0]?.notification).toBeUndefined();
}),
);
@@ -7,7 +7,6 @@ import {
type OrchestrationEvent,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { it as effectIt } from "@effect/vitest";
import { describe, expect, it } from "vite-plus/test";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
@@ -489,83 +488,6 @@ describe("orchestration projector", () => {
expect(message?.updatedAt).toBe(completeAt);
});
effectIt.effect("replaces an assistant snapshot between legacy appended deltas", () =>
Effect.gen(function* () {
const createdAt = "2026-02-23T09:00:00.000Z";
const model = createEmptyReadModel(createdAt);
const afterCreate = yield* projectEvent(
model,
makeEvent({
sequence: 1,
type: "thread.created",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: createdAt,
commandId: "cmd-create",
payload: {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: ProviderDriverKind.make("hermes"),
model: "hermes",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
updatedAt: createdAt,
},
}),
);
const messageEvent = (input: {
sequence: number;
text: string;
streaming: boolean;
textOperation?: "replace";
}) =>
makeEvent({
sequence: input.sequence,
type: "thread.message-sent",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: createdAt,
commandId: `cmd-message-${input.sequence}`,
payload: {
threadId: "thread-1",
messageId: "assistant:msg-replace",
role: "assistant",
text: input.text,
turnId: "turn-1",
streaming: input.streaming,
...(input.textOperation !== undefined ? { textOperation: input.textOperation } : {}),
createdAt,
updatedAt: createdAt,
},
});
let projected = afterCreate;
for (const event of [
messageEvent({ sequence: 2, text: "Hello wor", streaming: true }),
messageEvent({
sequence: 3,
text: "Hello there",
streaming: true,
textOperation: "replace",
}),
messageEvent({ sequence: 4, text: "!", streaming: true }),
messageEvent({ sequence: 5, text: "", streaming: false }),
]) {
projected = yield* projectEvent(projected, event);
}
const message = projected.threads[0]?.messages[0];
expect(message?.text).toBe("Hello there!");
expect(message?.streaming).toBe(false);
}),
);
it("prunes reverted turn messages from in-memory thread snapshot", async () => {
const createdAt = "2026-02-23T10:00:00.000Z";
const model = createEmptyReadModel(createdAt);
+5 -61
View File
@@ -1,6 +1,5 @@
import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from "@t3tools/contracts";
import {
mergeAssistantMessageText,
OrchestrationCheckpointSummary,
OrchestrationMessage,
OrchestrationSession,
@@ -21,7 +20,6 @@ import {
ThreadDeletedPayload,
ThreadInteractionModeSetPayload,
ThreadMetaUpdatedPayload,
ThreadNotificationDeliveredPayload,
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
ThreadSettledPayload,
@@ -214,7 +212,6 @@ export function projectEvent(
workspaceRoot: payload.workspaceRoot,
defaultModelSelection: payload.defaultModelSelection,
scripts: payload.scripts,
agentInstanceId: payload.agentInstanceId,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
deletedAt: null,
@@ -474,13 +471,11 @@ export function projectEvent(
entry.id === message.id
? {
...entry,
text: mergeAssistantMessageText(entry.text, {
text: message.text,
streaming: message.streaming,
...(payload.textOperation !== undefined
? { textOperation: payload.textOperation }
: {}),
}),
text: message.streaming
? `${entry.text}${message.text}`
: message.text.length > 0
? message.text
: entry.text,
streaming: message.streaming,
updatedAt: message.updatedAt,
turnId: message.turnId,
@@ -723,57 +718,6 @@ export function projectEvent(
}),
);
case "thread.notification-delivered":
return Effect.gen(function* () {
const payload = yield* decodeForEvent(
ThreadNotificationDeliveredPayload,
event.payload,
event.type,
"payload",
);
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
if (!thread) {
return nextBase;
}
const message: OrchestrationMessage = yield* decodeForEvent(
OrchestrationMessage,
{
id: payload.messageId,
role: "assistant",
text: payload.text,
// A proactive delivery belongs to no turn: it arrives outside the
// turn machinery and may land while an unrelated turn is live.
// Turn-scoped media is the exception — the payload names its turn.
turnId: payload.turnId ?? null,
streaming: false,
notification: payload.notification,
...(payload.attachments !== undefined ? { attachments: payload.attachments } : {}),
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
},
event.type,
"message",
);
// Replays of an already-written delivery re-emit the persisted row, so
// replacing in place is a byte-identical no-op rather than a duplicate.
const existingMessage = thread.messages.find((entry) => entry.id === message.id);
const messages = (
existingMessage
? thread.messages.map((entry) => (entry.id === message.id ? message : entry))
: [...thread.messages, message]
).slice(-MAX_THREAD_MESSAGES);
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
messages,
updatedAt: event.occurredAt,
}),
};
});
case "thread.activity-appended":
return decodeForEvent(
ThreadActivityAppendedPayload,
@@ -36,7 +36,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root,
default_model_selection_json,
scripts_json,
agent_instance_id,
created_at,
updated_at,
deleted_at
@@ -47,7 +46,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
${row.workspaceRoot},
${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},
${JSON.stringify(row.scripts)},
${row.agentInstanceId},
${row.createdAt},
${row.updatedAt},
${row.deletedAt}
@@ -58,7 +56,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root = excluded.workspace_root,
default_model_selection_json = excluded.default_model_selection_json,
scripts_json = excluded.scripts_json,
agent_instance_id = excluded.agent_instance_id,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
deleted_at = excluded.deleted_at
@@ -76,7 +73,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
agent_instance_id AS "agentInstanceId",
created_at AS "createdAt",
updated_at AS "updatedAt",
deleted_at AS "deletedAt"
@@ -96,7 +92,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
agent_instance_id AS "agentInstanceId",
created_at AS "createdAt",
updated_at AS "updatedAt",
deleted_at AS "deletedAt"
@@ -34,7 +34,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
model: "gpt-5.4",
},
scripts: [],
agentInstanceId: null,
createdAt: "2026-03-24T00:00:00.000Z",
updatedAt: "2026-03-24T00:00:00.000Z",
deletedAt: null,
@@ -100,7 +99,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
pendingApprovalCount: 0,
pendingUserInputCount: 0,
hasActionableProposedPlan: 0,
latestNotification: null,
deletedAt: null,
});
@@ -163,7 +161,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
pendingApprovalCount: 0,
pendingUserInputCount: 0,
hasActionableProposedPlan: 0,
latestNotification: null,
deletedAt: null,
});
@@ -66,80 +66,6 @@ layer("ProjectionThreadMessageRepository", (it) => {
}),
);
it.effect("round-trips notification provenance and preserves it across later upserts", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.make("thread-notification");
const messageId = MessageId.make("message-notification");
const createdAt = "2026-07-01T09:00:00.000Z";
const notification = {
kind: "cron" as const,
label: "Cron: daily-digest",
deliveryId: "delivery-1",
};
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "assistant",
text: "Digest ready.",
notification,
isStreaming: false,
createdAt,
updatedAt: createdAt,
});
const rows = yield* repository.listByThreadId({ threadId });
assert.equal(rows.length, 1);
assert.deepEqual(rows[0]?.notification, notification);
// Same COALESCE rule as attachments: an unrelated update that omits the
// field must not erase a delivery's provenance.
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "assistant",
text: "Digest ready (edited).",
isStreaming: false,
createdAt,
updatedAt: "2026-07-01T09:00:02.000Z",
});
const rowById = yield* repository.getByMessageId({ messageId });
assert.equal(rowById._tag, "Some");
if (rowById._tag === "Some") {
assert.equal(rowById.value.text, "Digest ready (edited).");
assert.deepEqual(rowById.value.notification, notification);
}
}),
);
it.effect("leaves notification absent on ordinary messages", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.make("thread-ordinary-message");
const messageId = MessageId.make("message-ordinary");
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "user",
text: "hello",
isStreaming: false,
createdAt: "2026-07-01T09:10:00.000Z",
updatedAt: "2026-07-01T09:10:00.000Z",
});
const rows = yield* repository.listByThreadId({ threadId });
// Absent, not a synthesized default — consumers key on its absence to
// tell an ordinary message from a proactive delivery.
assert.equal(rows[0]?.notification, undefined);
}),
);
it.effect("allows explicit attachment clearing with an empty array", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
@@ -5,7 +5,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Struct from "effect/Struct";
import { ChatAttachment, OrchestrationMessageNotification } from "@t3tools/contracts";
import { ChatAttachment } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
@@ -21,7 +21,6 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
Struct.assign({
isStreaming: Schema.Number,
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
notification: Schema.NullOr(Schema.fromJsonString(OrchestrationMessageNotification)),
}),
);
@@ -38,7 +37,6 @@ function toProjectionThreadMessage(
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
...(row.notification !== null ? { notification: row.notification } : {}),
};
}
@@ -50,8 +48,6 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
execute: (row) => {
const nextAttachmentsJson =
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
const nextNotificationJson =
row.notification !== undefined ? JSON.stringify(row.notification) : null;
return sql`
INSERT INTO projection_thread_messages (
message_id,
@@ -60,7 +56,6 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
role,
text,
attachments_json,
notification_json,
is_streaming,
created_at,
updated_at
@@ -79,14 +74,6 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
WHERE message_id = ${row.messageId}
)
),
COALESCE(
${nextNotificationJson},
(
SELECT notification_json
FROM projection_thread_messages
WHERE message_id = ${row.messageId}
)
),
${row.isStreaming ? 1 : 0},
${row.createdAt},
${row.updatedAt}
@@ -101,10 +88,6 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
excluded.attachments_json,
projection_thread_messages.attachments_json
),
notification_json = COALESCE(
excluded.notification_json,
projection_thread_messages.notification_json
),
is_streaming = excluded.is_streaming,
created_at = excluded.created_at,
updated_at = excluded.updated_at
@@ -124,7 +107,6 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
notification_json AS "notification",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -146,7 +128,6 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
notification_json AS "notification",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -14,14 +14,11 @@ import {
ProjectionThreadRepository,
type ProjectionThreadRepositoryShape,
} from "../Services/ProjectionThreads.ts";
import { ModelSelection, OrchestrationThreadNotificationSummary } from "@t3tools/contracts";
import { ModelSelection } from "@t3tools/contracts";
const ProjectionThreadDbRow = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
latestNotification: Schema.NullOr(
Schema.fromJsonString(OrchestrationThreadNotificationSummary),
),
}),
);
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
@@ -31,10 +28,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
const upsertProjectionThreadRow = SqlSchema.void({
Request: ProjectionThread,
execute: (row) => {
const latestNotificationJson =
row.latestNotification === null ? null : JSON.stringify(row.latestNotification);
return sql`
execute: (row) =>
sql`
INSERT INTO projection_threads (
thread_id,
project_id,
@@ -56,7 +51,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
latest_notification_json,
deleted_at
)
VALUES (
@@ -80,7 +74,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.pendingApprovalCount},
${row.pendingUserInputCount},
${row.hasActionableProposedPlan},
${latestNotificationJson},
${row.deletedAt}
)
ON CONFLICT (thread_id)
@@ -104,10 +97,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
pending_approval_count = excluded.pending_approval_count,
pending_user_input_count = excluded.pending_user_input_count,
has_actionable_proposed_plan = excluded.has_actionable_proposed_plan,
latest_notification_json = excluded.latest_notification_json,
deleted_at = excluded.deleted_at
`;
},
`,
});
const getProjectionThreadRow = SqlSchema.findOneOption({
@@ -136,7 +127,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE thread_id = ${threadId}
@@ -169,7 +159,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE project_id = ${projectId}
@@ -47,10 +47,6 @@ import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
import Migration0035 from "./Migrations/035_ProjectionProjectsAgentInstance.ts";
import Migration0036 from "./Migrations/036_ProjectionThreadMessageNotification.ts";
import Migration0037 from "./Migrations/037_ProjectionThreadsLatestNotification.ts";
import Migration0038 from "./Migrations/038_BackfillProjectionThreadsLatestTurn.ts";
/**
* Migration loader with all migrations defined inline.
@@ -97,10 +93,6 @@ export const migrationEntries = [
[32, "AuthPairingProofKeyThumbprint", Migration0032],
[33, "ProjectionThreadsSettled", Migration0033],
[34, "ProjectionThreadsSnoozed", Migration0034],
[35, "ProjectionProjectsAgentInstance", Migration0035],
[36, "ProjectionThreadMessageNotification", Migration0036],
[37, "ProjectionThreadsLatestNotification", Migration0037],
[38, "BackfillProjectionThreadsLatestTurn", Migration0038],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -1,65 +0,0 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("035_ProjectionProjectsAgentInstance", (it) => {
it.effect("adds a nullable agent_instance_id column and its index", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 34 });
const before = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_projects)
`;
assert.ok(!before.some((column) => column.name === "agent_instance_id"));
yield* runMigrations({ toMigrationInclusive: 35 });
const after = yield* sql<{
readonly name: string;
readonly type: string;
readonly notnull: number;
readonly dflt_value: string | null;
}>`
PRAGMA table_info(projection_projects)
`;
const agentInstanceColumn = after.find((column) => column.name === "agent_instance_id");
assert.ok(agentInstanceColumn);
assert.strictEqual(agentInstanceColumn.type, "TEXT");
assert.strictEqual(agentInstanceColumn.notnull, 0);
assert.strictEqual(agentInstanceColumn.dflt_value, null);
const indexes = yield* sql<{
readonly seq: number;
readonly name: string;
readonly unique: number;
readonly origin: string;
readonly partial: number;
}>`
PRAGMA index_list(projection_projects)
`;
assert.ok(
indexes.some((index) => index.name === "idx_projection_projects_agent_instance_id"),
);
const indexColumns = yield* sql<{
readonly seqno: number;
readonly cid: number;
readonly name: string;
}>`
PRAGMA index_info('idx_projection_projects_agent_instance_id')
`;
assert.deepStrictEqual(
indexColumns.map((column) => column.name),
["agent_instance_id"],
);
}),
);
});
@@ -1,21 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_projects)
`;
if (!columns.some((column) => column.name === "agent_instance_id")) {
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN agent_instance_id TEXT
`;
}
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_projects_agent_instance_id
ON projection_projects (agent_instance_id)
`;
});
@@ -1,129 +0,0 @@
import { assert, it } from "@effect/vitest";
import { OrchestrationMessageNotification } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
import Migration036 from "./036_ProjectionThreadMessageNotification.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("036_ProjectionThreadMessageNotification", (it) => {
it.effect("adds the notification column without disturbing existing messages", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 35 });
// An ordinary message written before the column existed. Proactive
// deliveries are the exception, so every pre-existing row must survive
// the migration with no notification rather than a synthesized default.
yield* sql`
INSERT INTO projection_thread_messages (
message_id,
thread_id,
turn_id,
role,
text,
is_streaming,
created_at,
updated_at
) VALUES (
'message-1',
'thread-1',
'turn-1',
'assistant',
'an ordinary answer',
0,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z'
)
`;
yield* runMigrations({ toMigrationInclusive: 36 });
const rows = yield* sql<{
readonly message_id: string;
readonly text: string;
readonly notification_json: string | null;
}>`
SELECT message_id, text, notification_json
FROM projection_thread_messages
WHERE message_id = 'message-1'
`;
assert.equal(rows.length, 1);
assert.equal(rows[0]?.text, "an ordinary answer");
assert.equal(rows[0]?.notification_json, null);
// And the new column accepts a delivery's provenance.
yield* sql`
INSERT INTO projection_thread_messages (
message_id,
thread_id,
turn_id,
role,
text,
is_streaming,
created_at,
updated_at,
notification_json
) VALUES (
'message-2',
'thread-1',
NULL,
'assistant',
'Your digest is ready.',
0,
'2026-01-01T00:01:00.000Z',
'2026-01-01T00:01:00.000Z',
'{"kind":"cron","label":"Cron: daily-digest","deliveryId":"delivery-1"}'
)
`;
const delivered = yield* sql<{
readonly notification_json: string | null;
readonly turn_id: string | null;
}>`
SELECT notification_json, turn_id
FROM projection_thread_messages
WHERE message_id = 'message-2'
`;
assert.equal(delivered.length, 1);
// A delivery belongs to no turn — attributing it to the thread's live
// turn would fold it away behind that turn's "Worked for …" row.
assert.equal(delivered[0]?.turn_id, null);
const decodedNotification = yield* Schema.decodeUnknownEffect(
Schema.fromJsonString(OrchestrationMessageNotification),
)(delivered[0]?.notification_json ?? "");
assert.deepEqual(decodedNotification, {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
});
}),
);
it.effect("is idempotent: re-running against a migrated database is a no-op", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
// The layer shares one in-memory database across this file's tests, so
// the schema may already be at 36 here; make sure it is, then apply the
// migration effect again directly — the migrator's tracking table would
// otherwise skip it, which is exactly the protection a restored backup
// or divergent branch does not have.
yield* runMigrations({ toMigrationInclusive: 36 });
yield* Migration036;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_thread_messages)
`;
assert.equal(columns.filter((column) => column.name === "notification_json").length, 1);
}),
);
});
@@ -1,16 +0,0 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_thread_messages)
`;
if (!columns.some((column) => column.name === "notification_json")) {
yield* sql`
ALTER TABLE projection_thread_messages
ADD COLUMN notification_json TEXT
`;
}
});
@@ -1,103 +0,0 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
import Migration037 from "./037_ProjectionThreadsLatestNotification.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("037_ProjectionThreadsLatestNotification", (it) => {
it.effect("adds a nullable latest_notification_json column, leaving existing rows null", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 36 });
const before = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
assert.ok(!before.some((column) => column.name === "latest_notification_json"));
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
deleted_at
)
VALUES (
'thread-pre-037',
'project-pre-037',
'Existing thread',
'{"instanceId":"codex","model":"gpt-5.4"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-07-01T00:00:00.000Z',
'2026-07-01T00:00:00.000Z',
NULL
)
`;
yield* runMigrations({ toMigrationInclusive: 37 });
const after = yield* sql<{
readonly name: string;
readonly type: string;
readonly notnull: number;
readonly dflt_value: string | null;
}>`
PRAGMA table_info(projection_threads)
`;
const column = after.find((entry) => entry.name === "latest_notification_json");
assert.ok(column);
assert.strictEqual(column.type, "TEXT");
assert.strictEqual(column.notnull, 0);
assert.strictEqual(column.dflt_value, null);
// No backfill is needed or possible: notification_json (migration 036)
// is newer than every pre-existing row, so nothing to summarize.
const rows = yield* sql<{ readonly latestNotification: string | null }>`
SELECT latest_notification_json AS "latestNotification"
FROM projection_threads
WHERE thread_id = 'thread-pre-037'
`;
assert.deepStrictEqual(rows, [{ latestNotification: null }]);
}),
);
it.effect("is idempotent: re-running against a migrated database is a no-op", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
// The layer shares one in-memory database across this file's tests, so
// the schema may already be at 37 here; make sure it is, then apply the
// migration effect again directly — the migrator's tracking table would
// otherwise skip it, which is exactly the protection a restored backup
// or divergent branch does not have.
yield* runMigrations({ toMigrationInclusive: 37 });
yield* Migration037;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
assert.equal(
columns.filter((column) => column.name === "latest_notification_json").length,
1,
);
}),
);
});
@@ -1,27 +0,0 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
/**
* Materializes the thread's newest proactive delivery onto the shell row.
*
* Shell consumers (sidebar, agent-awareness/push) never read a thread's
* messages, so notification provenance that lives on the message row is
* invisible to them unless it is summarized here — the same reason
* `latest_user_message_at` exists.
*
* No backfill: `projection_thread_messages.notification_json` is introduced by
* migration 036, so no delivery predates this column.
*/
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "latest_notification_json")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN latest_notification_json TEXT
`;
}
});
@@ -1,164 +0,0 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
const insertThread = (sql: SqlClient.SqlClient, threadId: string, latestTurnId: string | null) =>
sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
deleted_at
)
VALUES (
${threadId},
'project-038',
'Thread',
'{"instanceId":"hermes-local","model":"hermes"}',
'full-access',
'default',
NULL,
NULL,
${latestTurnId},
'2026-07-01T00:00:00.000Z',
'2026-07-01T00:00:00.000Z',
NULL
)
`;
const insertTurn = (
sql: SqlClient.SqlClient,
threadId: string,
turnId: string,
requestedAt: string,
) =>
sql`
INSERT INTO projection_turns (
thread_id,
turn_id,
pending_message_id,
assistant_message_id,
state,
requested_at,
started_at,
completed_at,
checkpoint_files_json
)
VALUES (
${threadId},
${turnId},
NULL,
NULL,
'completed',
${requestedAt},
${requestedAt},
${requestedAt},
'[]'
)
`;
const insertPendingTurnStart = (sql: SqlClient.SqlClient, threadId: string, requestedAt: string) =>
sql`
INSERT INTO projection_turns (
thread_id,
turn_id,
pending_message_id,
assistant_message_id,
state,
requested_at,
started_at,
completed_at,
checkpoint_files_json
)
VALUES (
${threadId},
NULL,
'pending-message-038',
NULL,
'pending',
${requestedAt},
NULL,
NULL,
'[]'
)
`;
const readLatestTurnId = (sql: SqlClient.SqlClient, threadId: string) =>
sql<{ readonly latestTurnId: string | null }>`
SELECT latest_turn_id AS "latestTurnId"
FROM projection_threads
WHERE thread_id = ${threadId}
`;
layer("038_BackfillProjectionThreadsLatestTurn", (it) => {
// A single test on purpose: `it.layer` shares one in-memory database across
// the block, so a second `it.effect` would find the migration already run
// and assert against a no-op. All fixtures are written between migration 37
// and 38 so every scenario exercises the actual backfill.
it.effect("backfills nulled pointers without touching set or turnless ones", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 37 });
// Pointer nulled at turn end (the Hermes case): restore the newest turn.
yield* insertThread(sql, "thread-hermes", null);
yield* insertTurn(sql, "thread-hermes", "hermes-turn-old", "2026-07-01T00:00:00.000Z");
yield* insertTurn(sql, "thread-hermes", "hermes-turn-new", "2026-07-01T00:05:00.000Z");
// A correct pointer must survive: the backfill is a heuristic, and the
// projector's own value is authoritative wherever it exists.
yield* insertThread(sql, "thread-codex", "turn-kept");
yield* insertTurn(sql, "thread-codex", "turn-kept", "2026-07-01T00:00:00.000Z");
yield* insertTurn(sql, "thread-codex", "turn-newer", "2026-07-01T00:09:00.000Z");
// A requested-but-never-adopted turn leaves a `turn_id IS NULL` row,
// and on the stranded threads this migration targets it is often the
// NEWEST row. Selecting it would write NULL over NULL — silently
// skipping the repair of the completed turn underneath.
yield* insertThread(sql, "thread-dangling", null);
yield* insertTurn(sql, "thread-dangling", "turn-completed", "2026-07-01T00:00:00.000Z");
yield* insertPendingTurnStart(sql, "thread-dangling", "2026-07-01T00:05:00.000Z");
// Inventing a turn for a thread that never ran one would make a fresh
// thread look like it had already run one.
yield* insertThread(sql, "thread-empty", null);
// A thread whose ONLY row is a dangling pending start has no turn to
// restore — it must stay null rather than "repair" to null noisily.
yield* insertThread(sql, "thread-pending-only", null);
yield* insertPendingTurnStart(sql, "thread-pending-only", "2026-07-01T00:05:00.000Z");
yield* runMigrations({ toMigrationInclusive: 38 });
assert.deepStrictEqual(yield* readLatestTurnId(sql, "thread-hermes"), [
{ latestTurnId: "hermes-turn-new" },
]);
assert.deepStrictEqual(yield* readLatestTurnId(sql, "thread-codex"), [
{ latestTurnId: "turn-kept" },
]);
assert.deepStrictEqual(yield* readLatestTurnId(sql, "thread-dangling"), [
{ latestTurnId: "turn-completed" },
]);
assert.deepStrictEqual(yield* readLatestTurnId(sql, "thread-empty"), [
{ latestTurnId: null },
]);
assert.deepStrictEqual(yield* readLatestTurnId(sql, "thread-pending-only"), [
{ latestTurnId: null },
]);
}),
);
});
@@ -1,58 +0,0 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
/**
* Repairs `projection_threads.latest_turn_id` rows that were nulled at turn end.
*
* The `thread.session-set` projector wrote `session.activeTurnId` straight
* through, so the session going back to `ready` (activeTurnId `null`) at the
* end of a turn erased the pointer to the turn that had just finished. For
* workspace providers that damage was invisible: `thread.turn-diff-completed`
* fires moments later and re-writes the id. A provider with no workspace
* (Hermes) emits no diff, so the id stayed null permanently — `latestTurn`
* never resolved, and the settle guard read every completed turn as a
* queued-but-unadopted turn start, refusing to settle the thread for the
* length of the adoption grace window.
*
* The projector no longer nulls the field, but rows already written keep the
* stale null: projections resume from their stored sequence rather than
* replaying, so nothing re-derives them.
*
* Restores the newest turn per thread by `requested_at`, matching what the
* projector would have retained. Deliberately conservative:
*
* - Only threads whose `latest_turn_id` is currently null are touched, so a
* correct pointer is never overwritten by this heuristic.
* - Only threads that actually have a turn row are updated; the `WHERE
* EXISTS` keeps a thread that has never run a turn at null rather than
* inventing one.
* - Ties on `requested_at` (possible when a turn is steered within the same
* millisecond) break on `row_id`, which is monotonic per insert.
* - Rows with a null `turn_id` are skipped: those are pending turn-starts
* (requested but never adopted), and a dangling one is often the *newest*
* row on exactly the threads this bug stranded. Without the filter the
* subquery would select it and write NULL over NULL — silently skipping
* the repair of the completed turn underneath.
*/
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
UPDATE projection_threads
SET latest_turn_id = (
SELECT turns.turn_id
FROM projection_turns turns
WHERE turns.thread_id = projection_threads.thread_id
AND turns.turn_id IS NOT NULL
ORDER BY turns.requested_at DESC, turns.row_id DESC
LIMIT 1
)
WHERE projection_threads.latest_turn_id IS NULL
AND EXISTS (
SELECT 1
FROM projection_turns turns
WHERE turns.thread_id = projection_threads.thread_id
AND turns.turn_id IS NOT NULL
)
`;
});
@@ -6,13 +6,7 @@
*
* @module ProjectionProjectRepository
*/
import {
IsoDateTime,
ModelSelection,
ProjectId,
ProjectScript,
ProviderInstanceId,
} from "@t3tools/contracts";
import { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from "@t3tools/contracts";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Context from "effect/Context";
@@ -26,12 +20,6 @@ export const ProjectionProject = Schema.Struct({
workspaceRoot: Schema.String,
defaultModelSelection: Schema.NullOr(ModelSelection),
scripts: Schema.Array(ProjectScript),
/**
* Set for *synthetic agent projects* standing in for a provider instance
* with no workspace of its own; `null` for every real project. See
* `OrchestrationProject.agentInstanceId`.
*/
agentInstanceId: Schema.NullOr(ProviderInstanceId),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
deletedAt: Schema.NullOr(IsoDateTime),
@@ -9,7 +9,6 @@
import {
ChatAttachment,
MessageId,
OrchestrationMessageNotification,
OrchestrationMessageRole,
ThreadId,
TurnId,
@@ -29,14 +28,6 @@ export const ProjectionThreadMessage = Schema.Struct({
role: OrchestrationMessageRole,
text: Schema.String,
attachments: Schema.optional(Schema.Array(ChatAttachment)),
/**
* Proactive-delivery provenance, present only on notification rows.
*
* Optional like `attachments`, and persisted with the same
* `COALESCE(excluded, existing)` upsert rule: an ordinary update that omits
* it must not erase the provenance of a row that has it.
*/
notification: Schema.optional(OrchestrationMessageNotification),
isStreaming: Schema.Boolean,
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -10,7 +10,6 @@ import {
IsoDateTime,
ModelSelection,
NonNegativeInt,
OrchestrationThreadNotificationSummary,
ProjectId,
ProviderInteractionMode,
RuntimeMode,
@@ -45,12 +44,6 @@ export const ProjectionThread = Schema.Struct({
pendingApprovalCount: NonNegativeInt,
pendingUserInputCount: NonNegativeInt,
hasActionableProposedPlan: NonNegativeInt,
/**
* Newest proactive delivery on this thread, summarized so shell readers do
* not have to load messages. Refreshed alongside the other shell-summary
* columns; `null` on every thread that has never received a delivery.
*/
latestNotification: Schema.NullOr(OrchestrationThreadNotificationSummary),
deletedAt: Schema.NullOr(IsoDateTime),
});
export type ProjectionThread = typeof ProjectionThread.Type;
@@ -19,7 +19,6 @@ const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationPro
workspaceRoot: "/repo/project",
defaultModelSelection: null,
scripts,
agentInstanceId: null,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
@@ -37,15 +36,12 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
Effect.succeed(
workspaceRoot === project.workspaceRoot ? Option.some(project) : Option.none(),
),
getActiveAgentProject: () => Effect.succeed(Option.none()),
getProjectShellById: (projectId) =>
Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.die("unused"),
getThreadArchiveStateById: () => Effect.die("unused"),
hasThreadNotificationDelivery: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
});
@@ -1,166 +0,0 @@
import {
DEFAULT_HERMES_MODEL,
HERMES_DRIVER_KIND,
HermesSettings,
TextGenerationError,
type ServerProvider,
type ServerSettings,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ServerConfig } from "../../config.ts";
import { readHomeThreadId } from "../../orchestration/homeThreads.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { makeHermesAdapter } from "../Layers/HermesAdapter.ts";
import {
defaultProviderContinuationIdentity,
type ProviderDriver,
type ProviderInstance,
} from "../ProviderDriver.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
import { HermesGatewayBroker } from "../Services/HermesGatewayBroker.ts";
const decodeHermesSettings = Schema.decodeSync(HermesSettings);
export type HermesDriverEnv =
| Crypto.Crypto
| FileSystem.FileSystem
| ServerConfig
| ServerSettingsService;
const unsupportedTextGeneration = (
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Hermes gateway instances do not support utility text generation.",
}),
);
const makeTextGeneration = (): TextGenerationShape => ({
generateCommitMessage: () => unsupportedTextGeneration("generateCommitMessage"),
generatePrContent: () => unsupportedTextGeneration("generatePrContent"),
generateBranchName: () => unsupportedTextGeneration("generateBranchName"),
generateThreadTitle: () => unsupportedTextGeneration("generateThreadTitle"),
});
export const HermesDriver: ProviderDriver<HermesSettings, HermesDriverEnv> = {
driverKind: HERMES_DRIVER_KIND,
metadata: {
displayName: "Hermes",
supportsMultipleInstances: true,
},
configSchema: HermesSettings,
defaultConfig: () => decodeHermesSettings({}),
create: ({ instanceId, displayName, accentColor, enabled }) =>
Effect.gen(function* () {
const broker = yield* HermesGatewayBroker;
// Captured once at construction: `getSnapshot` must be context-free
// (`R = never`) because the registry calls it outside this scope.
const settings = yield* ServerSettingsService;
const adapter = yield* makeHermesAdapter({ instanceId });
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: HERMES_DRIVER_KIND,
instanceId,
});
const maintenanceCapabilities = makeManualOnlyProviderMaintenanceCapabilities({
provider: HERMES_DRIVER_KIND,
packageName: null,
});
const getSnapshot = Effect.gen(function* () {
const connected = yield* broker.isConnected(instanceId);
const status = yield* broker
.getInstanceStatus(instanceId)
.pipe(
Effect.catchTags({ HermesGatewayManagementError: () => Effect.succeed(undefined) }),
);
// Read-only: a snapshot must never create the thread as a side effect
// (this runs on every status tick). The handshake owns creation.
// A settings read that fails degrades to "no designation" rather than
// failing the whole snapshot — the pin is cosmetic, the status is not.
const currentSettings = yield* settings.getSettings.pipe(
Effect.map(Option.some),
Effect.orElseSucceed(() => Option.none<ServerSettings>()),
);
const homeThreadId = Option.isSome(currentSettings)
? readHomeThreadId(currentSettings.value.providerInstances[instanceId])
: undefined;
return {
...(homeThreadId !== undefined ? { homeThreadId } : {}),
instanceId,
driver: HERMES_DRIVER_KIND,
...(displayName ? { displayName } : {}),
...(accentColor ? { accentColor } : {}),
continuation: { groupKey: continuationIdentity.continuationKey },
showInteractionModeToggle: false,
requiresNewThreadForModelChange: true,
requiresWorkspace: false,
enabled,
installed: true,
version: status?.hermesVersion ?? null,
status: !enabled ? "disabled" : connected ? "ready" : "warning",
auth: {
status: connected ? "authenticated" : "unauthenticated",
type: "gateway",
label: status?.nickname ?? displayName ?? "Hermes",
},
checkedAt: DateTime.formatIso(DateTime.nowUnsafe()),
...(!connected && enabled
? { message: "Hermes is offline. Reconnect its T3 Code gateway plugin." }
: {}),
availability: "available",
// The slug stays `DEFAULT_HERMES_MODEL` no matter what the plugin
// reports: threads bind to it, and letting it follow Hermes' current
// config would orphan every thread whose model changed on the Hermes
// side. The reported model is used only as the human-facing name, so
// the picker says "gpt-5.6-terra" instead of a generic placeholder.
// Falls back to "Hermes" when no plugin has connected yet or the
// plugin predates the `model` field on `connection.hello`.
models: [
{
slug: DEFAULT_HERMES_MODEL,
name: status?.model ?? "Hermes",
isCustom: false,
isDefault: true,
capabilities: null,
},
],
slashCommands: [],
skills: [],
} satisfies ServerProvider;
});
const snapshot = {
maintenanceCapabilities,
getSnapshot,
refresh: getSnapshot,
streamChanges: broker.streamStatuses.pipe(
Stream.filter((status) => status.instanceId === instanceId),
Stream.mapEffect(() => getSnapshot),
),
};
return {
instanceId,
driverKind: HERMES_DRIVER_KIND,
continuationIdentity,
displayName,
accentColor,
enabled,
snapshot,
adapter,
textGeneration: makeTextGeneration(),
} satisfies ProviderInstance;
}),
};
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,213 +0,0 @@
/**
* Live {@link HermesConnectionRegistry}. See the service module for why this
* state is memory-only and how generation fencing works.
*
* @module Layers/HermesConnectionRegistry
*/
import type { ProviderInstanceId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import type {
HermesActiveConnection,
HermesConnectionRegistry,
HermesInstanceLiveness,
HermesLivenessStatusFields,
HermesObservedConnection,
} from "../Services/HermesConnectionRegistry.ts";
/** Strip the transport/scope/generation from a connection to keep as `lastSeen`. */
const toObserved = (connection: HermesActiveConnection): HermesObservedConnection => ({
pluginVersion: connection.pluginVersion,
hermesVersion: connection.hermesVersion,
capabilities: connection.capabilities,
model: connection.model,
connectedAt: connection.connectedAt,
activeSessionCount: connection.activeSessionCount,
});
/**
* Project liveness into the status fields it owns. Prefers the live connection,
* falls back to `lastSeen`, and finally to whatever the incompatible plugin
* advertised.
*/
export const livenessStatusFields = (
liveness: HermesInstanceLiveness | undefined,
): HermesLivenessStatusFields => {
const observed = liveness?.connection ?? liveness?.lastSeen;
return {
lastConnectedAt: observed?.connectedAt ?? null,
pluginVersion: observed?.pluginVersion ?? liveness?.upgradeRequired?.pluginVersion ?? null,
hermesVersion: observed?.hermesVersion ?? liveness?.upgradeRequired?.hermesVersion ?? null,
model: observed?.model ?? liveness?.upgradeRequired?.model ?? null,
activeSessionCount: liveness?.connection?.activeSessionCount ?? 0,
protocolVersion:
observed?.capabilities.protocolVersion ?? liveness?.upgradeRequired?.protocolVersion ?? null,
capabilities: observed?.capabilities ?? null,
// Exposed so consumers can tell a replacement (old socket dies as a new
// one is accepted, publishing a single `connected` status) from a
// continuous connection. Watching connectedness alone cannot.
connectionGeneration: liveness?.connection?.generation ?? null,
connected: liveness?.connection !== undefined,
upgradeRequired: liveness?.upgradeRequired !== undefined,
};
};
export const makeHermesConnectionRegistry = Effect.gen(function* () {
const states = yield* Ref.make(new Map<ProviderInstanceId, HermesInstanceLiveness>());
const generation = yield* Ref.make(0);
/** Write liveness for one instance, dropping the entry when it goes empty. */
const setLiveness = (
current: ReadonlyMap<ProviderInstanceId, HermesInstanceLiveness>,
instanceId: ProviderInstanceId,
liveness: HermesInstanceLiveness,
) => {
const next = new Map(current);
if (
liveness.connection === undefined &&
liveness.lastSeen === undefined &&
liveness.upgradeRequired === undefined
) {
next.delete(instanceId);
} else {
next.set(instanceId, liveness);
}
return next;
};
const liveness = (instanceId: ProviderInstanceId) =>
Ref.get(states).pipe(Effect.map((current) => current.get(instanceId)));
const accept: HermesConnectionRegistry["accept"] = (input) =>
Effect.gen(function* () {
const nextGeneration = yield* Ref.getAndUpdate(generation, (value) => value + 1);
// The connection scope is a child of nothing in particular: it is closed
// explicitly on disconnect/replace so per-connection fibers (ping) die
// exactly with the connection they belong to.
const scope = yield* Scope.make();
const connection: HermesActiveConnection = {
...input.observed,
generation: nextGeneration,
transport: input.transport,
scope,
};
const displaced = yield* Ref.modify(states, (current) => {
const found = current.get(input.instanceId);
return [
found?.connection,
setLiveness(current, input.instanceId, {
connection,
lastSeen: toObserved(connection),
// Accepting a compatible connection clears any stale
// upgrade-required observation for this instance.
upgradeRequired: undefined,
}),
] as const;
});
return { generation: nextGeneration, displaced };
});
const markUpgradeRequired: HermesConnectionRegistry["markUpgradeRequired"] = (input) =>
Ref.modify(states, (current) => {
const found = current.get(input.instanceId);
return [
found?.connection,
setLiveness(current, input.instanceId, {
connection: undefined,
lastSeen: found?.lastSeen,
upgradeRequired: input.upgradeRequired,
}),
] as const;
});
const recordSessionCount: HermesConnectionRegistry["recordSessionCount"] = (
registration,
activeSessionCount,
) =>
Ref.modify(states, (current) => {
const found = current.get(registration.instanceId);
// Fence inside the update so a replacement that lands between a read and
// this write cannot be clobbered.
if (found?.connection?.generation !== registration.generation) {
return [false, current] as const;
}
const connection: HermesActiveConnection = { ...found.connection, activeSessionCount };
return [
true,
setLiveness(current, registration.instanceId, {
...found,
connection,
lastSeen: toObserved(connection),
}),
] as const;
});
const disconnect: HermesConnectionRegistry["disconnect"] = (registration) =>
Effect.gen(function* () {
const retired = yield* Ref.modify(states, (current) => {
const found = current.get(registration.instanceId);
if (found?.connection?.generation !== registration.generation) {
return [undefined, current] as const;
}
return [
found.connection,
setLiveness(current, registration.instanceId, {
connection: undefined,
lastSeen: toObserved(found.connection),
upgradeRequired: found.upgradeRequired,
}),
] as const;
});
if (retired) yield* Scope.close(retired.scope, Exit.void).pipe(Effect.ignore);
return retired;
});
const clearConnection: HermesConnectionRegistry["clearConnection"] = (instanceId) =>
Effect.gen(function* () {
const cleared = yield* Ref.modify(states, (current) => {
const found = current.get(instanceId);
if (!found?.connection) return [undefined, current] as const;
return [
found.connection,
setLiveness(current, instanceId, {
connection: undefined,
lastSeen: toObserved(found.connection),
upgradeRequired: found.upgradeRequired,
}),
] as const;
});
if (cleared) yield* Scope.close(cleared.scope, Exit.void).pipe(Effect.ignore);
return cleared;
});
const forget = (instanceId: ProviderInstanceId) =>
Effect.gen(function* () {
const dropped = yield* Ref.modify(states, (current) => {
const found = current.get(instanceId);
if (!found) return [undefined, current] as const;
const next = new Map(current);
next.delete(instanceId);
return [found.connection, next] as const;
});
if (dropped) yield* Scope.close(dropped.scope, Exit.void).pipe(Effect.ignore);
});
return {
liveness,
accept,
markUpgradeRequired,
recordSessionCount,
disconnect,
clearConnection,
forget,
isConnected: (instanceId) =>
liveness(instanceId).pipe(Effect.map((found) => found?.connection !== undefined)),
transport: (instanceId) =>
liveness(instanceId).pipe(Effect.map((found) => found?.connection?.transport)),
} satisfies HermesConnectionRegistry;
});
@@ -1,106 +0,0 @@
/**
* Live {@link HermesEnrollmentStore}. See the service module for the token
* rules this upholds.
*
* @module Layers/HermesEnrollmentStore
*/
import { HermesGatewayEnrollmentToken, type ProviderInstanceId } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Ref from "effect/Ref";
import type {
HermesEnrollmentStore,
PendingEnrollment,
} from "../Services/HermesEnrollmentStore.ts";
const ENROLLMENT_TOKEN_BYTES = 32;
export interface MakeHermesEnrollmentStoreOptions {
readonly ttl: Duration.Duration;
}
export const makeHermesEnrollmentStore = (
options: MakeHermesEnrollmentStoreOptions,
): Effect.Effect<HermesEnrollmentStore, never, Crypto.Crypto> =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const enrollments = yield* Ref.make(new Map<string, PendingEnrollment>());
const mint: HermesEnrollmentStore["mint"] = (input) =>
Effect.gen(function* () {
const bytes = yield* crypto.randomBytes(ENROLLMENT_TOKEN_BYTES).pipe(Effect.orDie);
const token = HermesGatewayEnrollmentToken.make(Encoding.encodeBase64Url(bytes));
const expiresAtMillis = (yield* Clock.currentTimeMillis) + Duration.toMillis(options.ttl);
yield* Ref.update(enrollments, (current) => {
const next = new Map(current);
// Minting supersedes this instance's previous tokens so only the
// newest unconsumed token is redeemable.
for (const [pendingToken, pending] of current) {
if (pending.input.instanceId === input.instanceId) next.delete(pendingToken);
}
return next.set(token, { input, expiresAtMillis });
});
return { token, expiresAtMillis };
});
const peek: HermesEnrollmentStore["peek"] = (token) =>
Effect.gen(function* () {
const found = (yield* Ref.get(enrollments)).get(token);
if (!found) return undefined;
return found.expiresAtMillis < (yield* Clock.currentTimeMillis) ? undefined : found;
});
const consume: HermesEnrollmentStore["consume"] = (token, expected) =>
Effect.gen(function* () {
// Compare-and-swap: delete only if the entry is still the exact object
// the caller authenticated against, so a concurrent redemption or a
// re-mint in between cannot be consumed by this caller.
const claimed = yield* Ref.modify(enrollments, (current) => {
const found = current.get(token);
if (found !== expected) return [undefined, current] as const;
const next = new Map(current);
next.delete(token);
return [found, next] as const;
});
if (claimed === undefined) return undefined;
// Re-check expiry after winning the swap: the entry may have aged out
// between authentication and consumption.
return claimed.expiresAtMillis < (yield* Clock.currentTimeMillis) ? undefined : claimed;
});
const forget = (instanceId: ProviderInstanceId) =>
Ref.update(enrollments, (current) => {
const next = new Map(current);
for (const [token, pending] of current) {
if (pending.input.instanceId === instanceId) next.delete(token);
}
return next;
});
const sweep = Clock.currentTimeMillis.pipe(
Effect.flatMap((now) =>
Ref.update(enrollments, (current) => {
const next = new Map(current);
for (const [token, pending] of current) {
if (pending.expiresAtMillis < now) next.delete(token);
}
return next.size === current.size ? current : next;
}),
),
);
return {
mint,
peek,
consume,
forget,
sweep,
size: Ref.get(enrollments).pipe(Effect.map((current) => current.size)),
} satisfies HermesEnrollmentStore;
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,37 +0,0 @@
import { assert, it } from "@effect/vitest";
import {
DEFAULT_SERVER_SETTINGS,
HERMES_DRIVER_KIND,
ProviderInstanceId,
} from "@t3tools/contracts";
import { deriveProviderInstanceConfigMap } from "./ProviderInstanceRegistryHydration.ts";
it("does not synthesize a legacy default Hermes instance", () => {
const instances = deriveProviderInstanceConfigMap(DEFAULT_SERVER_SETTINGS);
assert.isUndefined(instances[ProviderInstanceId.make("hermes")]);
assert.equal(instances[ProviderInstanceId.make("codex")]?.driver, "codex");
});
it("preserves an explicit Hermes instance whose id matches the driver default", () => {
const instanceId = ProviderInstanceId.make("hermes");
const instances = deriveProviderInstanceConfigMap({
...DEFAULT_SERVER_SETTINGS,
providerInstances: {
[instanceId]: {
driver: HERMES_DRIVER_KIND,
displayName: "Research Hermes",
enabled: true,
config: {},
},
},
});
assert.deepEqual(instances[instanceId], {
driver: HERMES_DRIVER_KIND,
displayName: "Research Hermes",
enabled: true,
config: {},
});
});
@@ -18,8 +18,7 @@
* `defaultInstanceIdForDriver(driverKind)` — literally the driver kind as a
* routing slug), we synthesize an envelope from the legacy field. The
* registry decodes both flavours through the same `configSchema` and ends
* up with one uniform `ProviderInstance` per entry. Drivers such as Hermes
* that require an explicitly paired remote instance opt out of synthesis.
* up with one uniform `ProviderInstance` per entry.
*
* Explicit `providerInstances` entries always win — users can already
* override the legacy `providers.<kind>` blob by authoring a
@@ -44,7 +43,6 @@
*/
import {
defaultInstanceIdForDriver,
HERMES_DRIVER_KIND,
type ProviderInstanceConfig,
type ProviderInstanceConfigMap,
ServerSettings,
@@ -64,10 +62,9 @@ import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistry
*
* Strategy:
* 1. Copy all explicit `settings.providerInstances` entries verbatim.
* 2. For each legacy-compatible built-in driver whose
* `defaultInstanceIdForDriver(id)` key is *not* already in the explicit
* map, synthesize an entry from the matching legacy
* `settings.providers.<kind>` blob.
* 2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key
* is *not* already in the explicit map, synthesize an entry from the
* matching legacy `settings.providers.<kind>` blob.
*
* The returned map is the input the registry consumes; pure & exported
* separately so the hydration logic can be exercised by unit tests
@@ -85,12 +82,6 @@ export const deriveProviderInstanceConfigMap = (
// config always wins over the legacy mirror.
continue;
}
if (driver.driverKind === HERMES_DRIVER_KIND) {
// Hermes is configured only through explicit gateway instances. A
// synthesized legacy default would resurrect a revoked-and-removed
// instance in settings and provider pickers.
continue;
}
// Only built-in drivers have a legacy mirror; the registry's
// `providers` struct is keyed on the same literal slug as
@@ -280,24 +280,20 @@ function makeMutableServerSettingsService(
return Effect.gen(function* () {
const settingsRef = yield* Ref.make(initial);
const changes = yield* PubSub.unbounded<ContractServerSettings>();
const updateSettingsWith = (
update: (current: ContractServerSettings) => Parameters<typeof applyServerSettingsPatch>[1],
) =>
Effect.gen(function* () {
const current = yield* Ref.get(settingsRef);
const next = applyServerSettingsPatch(current, update(current));
encodeServerSettings(next);
yield* Ref.set(settingsRef, next);
yield* PubSub.publish(changes, next);
return next;
});
return {
start: Effect.void,
ready: Effect.void,
getSettings: Ref.get(settingsRef),
updateSettings: (patch) => updateSettingsWith(() => patch),
updateSettingsWith,
updateSettings: (patch) =>
Effect.gen(function* () {
const current = yield* Ref.get(settingsRef);
const next = applyServerSettingsPatch(current, patch);
encodeServerSettings(next);
yield* Ref.set(settingsRef, next);
yield* PubSub.publish(changes, next);
return next;
}),
get streamChanges() {
return Stream.fromPubSub(changes);
},
@@ -24,14 +24,12 @@
*/
import {
defaultInstanceIdForDriver,
ProviderDescribeError,
ProviderDriverKind,
type ProviderInstanceId,
type ServerProvider,
type ServerProviderUpdateState,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as FileSystem from "effect/FileSystem";
@@ -53,7 +51,6 @@ import {
resolveProviderStatusCachePath,
writeProviderStatusCache,
} from "../providerStatusCache.ts";
import { describeFromServerProvider } from "../providerDescribe.ts";
import type { ProviderInstance } from "../ProviderDriver.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
@@ -707,85 +704,12 @@ export const ProviderRegistryLive = Layer.effect(
return yield* Ref.get(providersRef);
});
const describeInstance = Effect.fn("describeInstance")(function* (
instanceId: ProviderInstanceId,
) {
const providers = yield* Ref.get(providersRef);
const provider = providers.find((candidate) => candidate.instanceId === instanceId);
if (!provider) {
return yield* new ProviderDescribeError({
code: "instance-not-found",
message: `Provider instance '${instanceId}' is not configured.`,
instanceId,
});
}
const describedAt = DateTime.formatIso(yield* DateTime.now);
const base = describeFromServerProvider({ provider, describedAt });
const instance = yield* instanceRegistry.getInstance(instanceId);
const describe = instance?.adapter.describe;
if (!describe) {
return base;
}
// Enrichment is best-effort by design: an agent that is offline right
// now must still render a page from its cached snapshot rather than an
// error screen. See `ProviderAdapterShape.describe`.
return yield* describe(base).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider describe enrichment failed; using snapshot", {
instanceId,
cause: Cause.pretty(cause),
}).pipe(Effect.as(base)),
),
);
});
const getSkillBody = Effect.fn("getSkillBody")(function* (input: {
readonly instanceId: ProviderInstanceId;
readonly skillName: string;
}) {
const instance = yield* instanceRegistry.getInstance(input.instanceId);
if (!instance) {
return yield* new ProviderDescribeError({
code: "instance-not-found",
message: `Provider instance '${input.instanceId}' is not available.`,
instanceId: input.instanceId,
});
}
const read = instance.adapter.getSkillBody;
if (!read) {
return yield* new ProviderDescribeError({
code: "unsupported",
message: "This provider cannot read skill contents.",
instanceId: input.instanceId,
});
}
return yield* read(input.skillName).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider skill body read failed", {
instanceId: input.instanceId,
skillName: input.skillName,
cause: Cause.pretty(cause),
}).pipe(
Effect.andThen(
new ProviderDescribeError({
code: "unavailable",
message: `Could not read skill '${input.skillName}'.`,
instanceId: input.instanceId,
}),
),
),
),
);
});
return {
getProviders: Ref.get(providersRef),
refresh: (provider?: ProviderDriverKind) =>
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
refreshInstance: (instanceId: ProviderInstanceId) =>
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
describeInstance,
getSkillBody,
getProviderMaintenanceCapabilitiesForInstance,
setProviderMaintenanceActionState,
get streamChanges() {
@@ -1280,170 +1280,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn");
}
}
yield* advanceTestClock(50);
routing.codex.emit({
type: "turn.completed",
eventId: asEventId("evt-runtime-status-stale-completion"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:01.000Z",
threadId: session.threadId,
turnId: asTurnId("turn-from-an-older-request"),
payload: {
state: "completed",
},
});
yield* advanceTestClock(50);
const afterStaleCompletion = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(afterStaleCompletion), true);
if (Option.isSome(afterStaleCompletion)) {
assert.equal(afterStaleCompletion.value.status, "running");
const payload = afterStaleCompletion.value.runtimePayload;
assert.equal(payload !== null && typeof payload === "object", true);
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
assert.equal(
"activeTurnId" in payload ? payload.activeTurnId : undefined,
`turn-${String(session.threadId)}`,
);
assert.equal(
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
"turn.completed",
);
}
}
routing.codex.emit({
type: "turn.completed",
eventId: asEventId("evt-runtime-status-active-completion"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:02.000Z",
threadId: session.threadId,
turnId: asTurnId(`turn-${String(session.threadId)}`),
payload: {
state: "completed",
},
});
yield* advanceTestClock(50);
const afterActiveCompletion = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(afterActiveCompletion), true);
if (Option.isSome(afterActiveCompletion)) {
assert.equal(afterActiveCompletion.value.status, "running");
const payload = afterActiveCompletion.value.runtimePayload;
assert.equal(payload !== null && typeof payload === "object", true);
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
assert.equal("cwd" in payload ? payload.cwd : undefined, session.cwd);
assert.equal(
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
"turn.completed",
);
}
}
// A *failed* completion of the active turn must persist "error". This
// shared a ternary branch with turn.started and wrote "running" for every
// settled turn, failed ones included.
yield* provider.sendTurn({
threadId: session.threadId,
input: "hello again",
attachments: [],
});
yield* advanceTestClock(50);
routing.codex.emit({
type: "turn.completed",
eventId: asEventId("evt-runtime-status-failed-completion"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:02.500Z",
threadId: session.threadId,
turnId: asTurnId(`turn-${String(session.threadId)}`),
payload: {
state: "failed",
errorMessage: "Hermes could not resume this thread after reconnecting.",
},
});
yield* advanceTestClock(50);
const afterFailedCompletion = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(afterFailedCompletion), true);
if (Option.isSome(afterFailedCompletion)) {
assert.equal(afterFailedCompletion.value.status, "error");
const payload = afterFailedCompletion.value.runtimePayload;
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
}
}
// A matching turn.aborted settles the same way, minus the error.
yield* provider.sendTurn({
threadId: session.threadId,
input: "hello once more",
attachments: [],
});
yield* advanceTestClock(50);
routing.codex.emit({
type: "turn.aborted",
eventId: asEventId("evt-runtime-status-active-abort"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:02.750Z",
threadId: session.threadId,
turnId: asTurnId(`turn-${String(session.threadId)}`),
payload: { reason: "interrupted" },
});
yield* advanceTestClock(50);
const afterAbort = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(afterAbort), true);
if (Option.isSome(afterAbort)) {
assert.equal(afterAbort.value.status, "running");
const payload = afterAbort.value.runtimePayload;
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
assert.equal(
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
"turn.aborted",
);
}
}
routing.codex.emit({
type: "session.exited",
eventId: asEventId("evt-runtime-status-session-exit"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:03.000Z",
threadId: session.threadId,
payload: {
exitKind: "error",
recoverable: true,
},
});
yield* advanceTestClock(50);
const afterSessionExit = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(afterSessionExit), true);
if (Option.isSome(afterSessionExit)) {
assert.equal(afterSessionExit.value.status, "error");
const payload = afterSessionExit.value.runtimePayload;
assert.equal(payload !== null && typeof payload === "object", true);
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
assert.equal(
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
"session.exited",
);
}
}
}),
);
@@ -162,19 +162,6 @@ function readPersistedCwd(
return trimmed.length > 0 ? trimmed : undefined;
}
function readPersistedActiveTurnId(
runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"],
): string | null | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const rawActiveTurnId =
"activeTurnId" in runtimePayload ? runtimePayload.activeTurnId : undefined;
return typeof rawActiveTurnId === "string" || rawActiveTurnId === null
? rawActiveTurnId
: undefined;
}
const dieOnMissingBindingInstanceId = (
operation: string,
payload: {
@@ -294,84 +281,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
});
});
const persistRuntimeLifecycle = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
if (
event.type !== "turn.started" &&
event.type !== "turn.completed" &&
event.type !== "turn.aborted" &&
event.type !== "session.exited"
) {
return;
}
const binding = Option.getOrUndefined(yield* directory.getBinding(event.threadId));
if (!binding || event.providerInstanceId === undefined) {
return;
}
if (
binding.provider !== event.provider ||
binding.providerInstanceId !== event.providerInstanceId
) {
yield* Effect.logWarning("provider.session.runtime.lifecycle-binding-mismatch", {
threadId: event.threadId,
eventProvider: event.provider,
eventProviderInstanceId: event.providerInstanceId,
bindingProvider: binding.provider,
bindingProviderInstanceId: binding.providerInstanceId,
eventType: event.type,
});
return;
}
const persistedActiveTurnId = readPersistedActiveTurnId(binding.runtimePayload);
const terminalMatchesActiveTurn =
(event.type === "turn.completed" || event.type === "turn.aborted") &&
event.turnId !== undefined &&
persistedActiveTurnId === event.turnId;
const isSessionExit = event.type === "session.exited";
// `turn.started` and a terminal event that closes the active turn are
// opposite transitions and must not share a branch. Folded together they
// persisted "running" for every settled turn — including a *failed* one,
// which is the lie this split removes.
//
// A non-failed terminal still writes "running": this status describes the
// session, not the turn (`toRuntimeStatus` maps both ready and running to
// it), and the settled turn is expressed by `activeTurnId: null` below.
// "stopped" is reserved for sessions that are actually gone — the reaper
// skips those, so using it for an idle session would strand it.
const status =
event.type === "turn.started"
? "running"
: terminalMatchesActiveTurn
? event.type === "turn.completed" && event.payload.state === "failed"
? "error"
: "running"
: isSessionExit
? event.payload.recoverable === true || event.payload.exitKind === "error"
? "error"
: "stopped"
: undefined;
const activeTurnId =
event.type === "turn.started"
? (event.turnId ?? persistedActiveTurnId)
: terminalMatchesActiveTurn || isSessionExit
? null
: persistedActiveTurnId;
yield* directory.upsert({
threadId: event.threadId,
provider: event.provider,
providerInstanceId: event.providerInstanceId,
...(status !== undefined ? { status } : {}),
runtimePayload: {
...(activeTurnId !== undefined ? { activeTurnId } : {}),
lastRuntimeEvent: event.type,
lastRuntimeEventAt: event.createdAt,
},
});
});
const processRuntimeEvent = (
source: {
readonly instanceId: ProviderInstanceId;
@@ -384,22 +293,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
increment(providerRuntimeEventsTotal, {
provider: canonicalEvent.provider,
eventType: canonicalEvent.type,
}).pipe(
Effect.andThen(
persistRuntimeLifecycle(canonicalEvent).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider.session.runtime.lifecycle-persist-failed", {
threadId: canonicalEvent.threadId,
provider: canonicalEvent.provider,
providerInstanceId: canonicalEvent.providerInstanceId,
eventType: canonicalEvent.type,
errorTag: causeErrorTag(cause),
}),
),
),
),
Effect.andThen(publishRuntimeEvent(canonicalEvent)),
),
}).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))),
),
);
@@ -200,13 +200,10 @@ describe("ProviderSessionReaper", () => {
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
getActiveAgentProject: () => Effect.die("unused"),
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
hasThreadNotificationDelivery: () => Effect.succeed(false),
getThreadShellById: (threadId) =>
Effect.succeed(
input.readModel.threads.find((thread) => thread.id === threadId)
@@ -1,184 +0,0 @@
import { assert, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as TestClock from "effect/testing/TestClock";
import { ProviderAdapterRequestError } from "../Errors.ts";
import { makeRequestCorrelator } from "./RequestCorrelator.ts";
const TIMEOUT = Duration.seconds(30);
const makeCorrelator = () =>
makeRequestCorrelator<string, { readonly requestId: string }>({
provider: "test",
timeout: TIMEOUT,
maxAge: Duration.seconds(90),
});
const owner = "owner-a";
it.effect("resolves a correlated response and releases the pending entry", () =>
Effect.gen(function* () {
const correlator = yield* makeCorrelator();
const pending = yield* correlator
.request({ owner, requestId: "r1", method: "test.method", send: Effect.void })
.pipe(Effect.forkChild({ startImmediately: true }));
yield* Effect.yieldNow;
assert.equal(yield* correlator.pendingCount, 1);
assert.isTrue(yield* correlator.complete("r1", { requestId: "r1" }));
assert.deepEqual(yield* Fiber.join(pending), { requestId: "r1" });
assert.equal(yield* correlator.pendingCount, 0);
}),
);
it.effect("releases the pending entry when the send fails", () =>
Effect.gen(function* () {
const correlator = yield* makeCorrelator();
const failure = yield* Effect.flip(
correlator.request({
owner,
requestId: "r-send-fail",
method: "test.method",
send: Effect.fail(
new ProviderAdapterRequestError({
provider: "test",
method: "test.method",
detail: "the transport refused the write",
}),
),
}),
);
assert.include(failure.detail, "refused");
assert.equal(yield* correlator.pendingCount, 0);
}),
);
// The send used to sit outside `restore`, so a transport write that never
// returned could not be interrupted: `Fiber.interrupt` would hang forever
// waiting for the uninterruptible region to finish. The write is now inside the
// restored region, so an interrupt lands — and the entry is still released.
it.effect("interrupts a request whose transport write never returns", () =>
Effect.gen(function* () {
const correlator = yield* makeCorrelator();
const writeStarted = yield* Deferred.make<void>();
const neverCompletes = yield* Deferred.make<void>();
const pending = yield* correlator
.request({
owner,
requestId: "r-stalled-write",
method: "test.method",
send: Deferred.succeed(writeStarted, undefined).pipe(
Effect.andThen(Deferred.await(neverCompletes)),
),
})
.pipe(Effect.forkChild({ startImmediately: true }));
yield* Deferred.await(writeStarted);
assert.equal(yield* correlator.pendingCount, 1);
// Would never return before the fix.
yield* Fiber.interrupt(pending);
assert.equal(
yield* correlator.pendingCount,
0,
"an interrupted request must not leave a pending entry behind",
);
}),
);
// `Effect.timeout` only wrapped `Deferred.await`, so the clock did not start
// until the write returned: a request over a wedged socket outlived its own
// timeout for as long as the socket stayed wedged. The timeout now covers the
// send too.
it.effect("times out a request whose transport write stalls", () =>
Effect.gen(function* () {
const correlator = yield* makeCorrelator();
const writeStarted = yield* Deferred.make<void>();
const neverCompletes = yield* Deferred.make<void>();
const pending = yield* correlator
.request({
owner,
requestId: "r-stalled-timeout",
method: "test.method",
send: Deferred.succeed(writeStarted, undefined).pipe(
Effect.andThen(Deferred.await(neverCompletes)),
),
})
.pipe(Effect.result, Effect.forkChild({ startImmediately: true }));
yield* Deferred.await(writeStarted);
yield* TestClock.adjust(Duration.seconds(31));
const outcome = yield* Fiber.join(pending);
assert.equal(outcome._tag, "Failure");
if (outcome._tag === "Failure") assert.include(outcome.failure.detail, "timed out");
assert.equal(yield* correlator.pendingCount, 0);
}),
);
// A response can land the instant the write completes. Registration happens
// uninterruptibly before the send, so `complete` always finds an entry —
// moving the send inside `restore` must not have opened that window.
it.effect("completes a response that arrives from inside the transport write", () =>
Effect.gen(function* () {
const correlator = yield* makeCorrelator();
const pending = yield* correlator
.request({
owner,
requestId: "r-immediate",
method: "test.method",
// The transport answers synchronously, before `send` even returns.
send: correlator.complete("r-immediate", { requestId: "r-immediate" }).pipe(
Effect.flatMap((completed) =>
completed
? Effect.void
: Effect.fail(
new ProviderAdapterRequestError({
provider: "test",
method: "test.method",
detail: "the response found no pending entry",
}),
),
),
),
})
.pipe(Effect.forkChild({ startImmediately: true }));
assert.deepEqual(yield* Fiber.join(pending), { requestId: "r-immediate" });
assert.equal(yield* correlator.pendingCount, 0);
}),
);
it.effect("fails every request routed over a dead owner", () =>
Effect.gen(function* () {
const correlator = yield* makeCorrelator();
const first = yield* correlator
.request({ owner, requestId: "r-own-1", method: "test.method", send: Effect.void })
.pipe(Effect.forkChild({ startImmediately: true }));
const second = yield* correlator
.request({ owner, requestId: "r-own-2", method: "test.method", send: Effect.void })
.pipe(Effect.forkChild({ startImmediately: true }));
const other = yield* correlator
.request({
owner: "owner-b",
requestId: "r-own-3",
method: "test.method",
send: Effect.void,
})
.pipe(Effect.forkChild({ startImmediately: true }));
yield* Effect.yieldNow;
yield* correlator.failOwner(owner, "the connection dropped");
assert.include((yield* Effect.flip(Fiber.join(first))).detail, "dropped");
assert.include((yield* Effect.flip(Fiber.join(second))).detail, "dropped");
assert.isUndefined(other.pollUnsafe(), "another owner's request must be untouched");
yield* correlator.complete("r-own-3", { requestId: "r-own-3" });
assert.deepEqual(yield* Fiber.join(other), { requestId: "r-own-3" });
}),
);
@@ -1,175 +0,0 @@
/**
* Live {@link RequestCorrelator} implementation.
*
* Generic over the owner key (the route a request travels over) and the
* response payload, so this is reusable by any provider with correlated
* request/response framing — see the module docs on the service for why the
* interrupt-safety and sweeping guarantees live here rather than at call sites.
*
* @module Layers/RequestCorrelator
*/
import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Ref from "effect/Ref";
import { ProviderAdapterRequestError } from "../Errors.ts";
import type { RequestCorrelator, RequestCorrelatorSend } from "../Services/RequestCorrelator.ts";
interface PendingRequest<Owner, Response> {
readonly owner: Owner;
readonly method: string;
readonly registeredAtMillis: number;
readonly deferred: Deferred.Deferred<Response, ProviderAdapterRequestError>;
}
export interface MakeRequestCorrelatorOptions {
/** Provider name stamped onto `ProviderAdapterRequestError`. */
readonly provider: string;
/** Default response timeout when a request does not override it. */
readonly timeout: Duration.Duration;
/**
* Entries older than this are reaped by `sweep`. Comfortably larger than
* `timeout` so the sweeper only ever catches entries whose own timeout
* pipeline failed to run — a normal slow request is never stolen from
* underneath its awaiting fiber.
*/
readonly maxAge: Duration.Duration;
}
export const makeRequestCorrelator = <Owner, Response>(
options: MakeRequestCorrelatorOptions,
): Effect.Effect<RequestCorrelator<Owner, Response>> =>
Effect.gen(function* () {
const pending = yield* Ref.make(new Map<string, PendingRequest<Owner, Response>>());
const requestError = (method: string, detail: string) =>
new ProviderAdapterRequestError({ provider: options.provider, method, detail });
/** Remove one entry by id. Safe to call when it is already gone. */
const release = (requestId: string) =>
Ref.update(pending, (current) => {
if (!current.has(requestId)) return current;
const next = new Map(current);
next.delete(requestId);
return next;
});
const request = (input: RequestCorrelatorSend<Owner>) =>
Effect.gen(function* () {
const deferred = yield* Deferred.make<Response, ProviderAdapterRequestError>();
const registeredAtMillis = yield* Clock.currentTimeMillis;
// Registration must not be interruptible independently of the cleanup
// that removes the entry. `uninterruptibleMask` closes that window: the
// registration is applied uninterruptibly — so a response arriving the
// instant the request is written always finds an entry to complete —
// and `ensuring` guarantees release regardless of how the rest exits.
//
// Everything after registration — the send *and* the await — lives
// inside `restore`, with the timeout inside it too. Both placements
// matter:
//
// - Send outside `restore`: a transport write that never returns is
// unkillable, and the response timeout does not start counting
// until the write returns, so a request over a wedged socket hangs
// for as long as the socket does.
// - Timeout outside `restore`: `Effect.timeout` races internally, and
// that race inherits the surrounding uninterruptible region — so an
// interrupt cannot land on the awaiting fiber even though the body
// it wraps was restored.
return yield* Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
yield* Ref.update(pending, (current) =>
new Map(current).set(input.requestId, {
owner: input.owner,
method: input.method,
registeredAtMillis,
deferred,
}),
);
return yield* restore(
input.send.pipe(
Effect.andThen(Deferred.await(deferred)),
Effect.timeout(input.timeout ?? options.timeout),
),
).pipe(
Effect.mapError((error) =>
error._tag === "TimeoutError"
? requestError(input.method, `${options.provider} request timed out.`)
: error,
),
Effect.ensuring(release(input.requestId)),
);
}),
);
});
const complete = (requestId: string, response: Response) =>
Ref.modify(pending, (current) => {
const found = current.get(requestId);
if (!found) return [undefined, current] as const;
const next = new Map(current);
next.delete(requestId);
return [found, next] as const;
}).pipe(
Effect.flatMap((found) =>
found === undefined
? Effect.succeed(false)
: Deferred.succeed(found.deferred, response).pipe(Effect.as(true)),
),
);
/**
* Extract every entry matching `select`, then fail their deferreds. The
* extraction is a single `Ref.modify` so two concurrent failures cannot
* both claim the same entry.
*/
const failMatching = (
select: (entry: PendingRequest<Owner, Response>) => boolean,
detail: (entry: PendingRequest<Owner, Response>) => string,
) =>
Ref.modify(pending, (current) => {
const claimed: Array<PendingRequest<Owner, Response>> = [];
const next = new Map(current);
for (const [requestId, entry] of current) {
if (!select(entry)) continue;
claimed.push(entry);
next.delete(requestId);
}
return [claimed, next] as const;
}).pipe(
Effect.flatMap((claimed) =>
Effect.forEach(
claimed,
(entry) => Deferred.fail(entry.deferred, requestError(entry.method, detail(entry))),
{ discard: true },
),
),
);
const failOwner = (owner: Owner, detail: string) =>
failMatching(
(entry) => entry.owner === owner,
() => detail,
);
const sweep = Clock.currentTimeMillis.pipe(
Effect.flatMap((now) =>
failMatching(
(entry) => now - entry.registeredAtMillis >= Duration.toMillis(options.maxAge),
() => `${options.provider} request was abandoned before it completed.`,
),
),
);
return {
request,
complete,
failOwner,
sweep,
pendingCount: Ref.get(pending).pipe(Effect.map((current) => current.size)),
} satisfies RequestCorrelator<Owner, Response>;
});
@@ -1,167 +0,0 @@
/**
* HermesConnectionRegistry — owner of **volatile** Hermes gateway liveness.
*
* Everything in here is deliberately memory-only and is never persisted:
* the live connection, its transport, `lastSeen`, `activeSessionCount`, the
* reported model, and the `upgrade-required` observation.
*
* Why liveness must not be persisted
* ----------------------------------
* `ProviderInstanceRegistryLive.reconcile` structurally compares each
* `ProviderInstanceConfig` envelope and closes the instance scope on **any**
* change. Closing that scope runs `HermesAdapter`'s finalizer, which calls
* `stopAll()` and sends `session.stop` to Hermes for every live thread. So
* writing something like `connectedAt` into the instance config on every
* connect would tear down every Hermes session on every reconnect.
*
* The broker (and therefore this registry) is a top-level layer that survives
* reconcile, which makes it the correct owner of liveness. The accepted
* consequence is that after a T3 server restart the UI reports "never
* connected" until the plugin dials back in. That is intended.
*
* Generation fencing
* ------------------
* Every accepted connection gets a monotonically increasing generation. All
* post-acceptance mutations are fenced on it, and the comparison happens
* *inside* the `Ref` update rather than as a separate read, so a replacement
* landing concurrently cannot be clobbered by a stale writer (TOCTOU).
*
* @module HermesConnectionRegistry
*/
import type {
HermesGatewayCapabilities,
HermesGatewayInstanceStatus,
ProviderInstanceId,
} from "@t3tools/contracts";
import type * as Effect from "effect/Effect";
import type * as Scope from "effect/Scope";
import type {
HermesGatewayConnectionRegistration,
HermesGatewayTransport,
} from "./HermesGatewayBroker.ts";
/** Observed facts about a plugin connection, independent of its transport. */
export interface HermesObservedConnection {
readonly pluginVersion: string;
readonly hermesVersion: string;
readonly capabilities: HermesGatewayCapabilities;
/** Model reported at handshake. Null when the plugin predates the field. */
readonly model: string | null;
readonly connectedAt: string;
readonly activeSessionCount: number;
}
export interface HermesActiveConnection extends HermesObservedConnection {
readonly generation: number;
readonly transport: HermesGatewayTransport;
/**
* Scope tied to this connection's lifetime. Per-connection fibers (the ping
* loop) are forked into it, so they die exactly when the connection does.
*/
readonly scope: Scope.Closeable;
}
export interface HermesUpgradeRequired {
readonly pluginVersion: string;
readonly hermesVersion: string;
readonly protocolVersion: number;
readonly model: string | null;
}
/** Volatile per-instance liveness. Absent entry means "nothing observed yet". */
export interface HermesInstanceLiveness {
readonly connection?: HermesActiveConnection | undefined;
readonly lastSeen?: HermesObservedConnection | undefined;
readonly upgradeRequired?: HermesUpgradeRequired | undefined;
}
export interface HermesAcceptedConnection {
readonly generation: number;
/**
* The connection this one displaced, if any. The caller is responsible for
* closing it — the registry never touches a transport itself, so callers can
* order the close against failing pending requests.
*/
readonly displaced: HermesActiveConnection | undefined;
}
export interface HermesConnectionRegistry {
/** Current liveness for one instance, or `undefined` if nothing observed. */
readonly liveness: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesInstanceLiveness | undefined>;
/** Accept a connection, assigning it the next generation. */
readonly accept: (input: {
readonly instanceId: ProviderInstanceId;
readonly transport: HermesGatewayTransport;
readonly observed: HermesObservedConnection;
}) => Effect.Effect<HermesAcceptedConnection>;
/**
* Record an incompatible plugin. Clears any live connection for the instance
* and returns it so the caller can close it.
*/
readonly markUpgradeRequired: (input: {
readonly instanceId: ProviderInstanceId;
readonly upgradeRequired: HermesUpgradeRequired;
}) => Effect.Effect<HermesActiveConnection | undefined>;
/**
* Update the active session count. Generation-fenced; returns `false` when
* the registration is stale, in which case nothing was written.
*/
readonly recordSessionCount: (
registration: HermesGatewayConnectionRegistration,
activeSessionCount: number,
) => Effect.Effect<boolean>;
/**
* Retire a connection, demoting it to `lastSeen`. Generation-fenced;
* returns the retired connection, or `undefined` when the registration is
* stale (already replaced) and nothing was changed.
*/
readonly disconnect: (
registration: HermesGatewayConnectionRegistration,
) => Effect.Effect<HermesActiveConnection | undefined>;
/**
* Clear the live connection for an instance regardless of generation, e.g.
* on revoke. Returns it so the caller can close the transport.
*/
readonly clearConnection: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesActiveConnection | undefined>;
/** Drop all liveness for an instance (on remove). */
readonly forget: (instanceId: ProviderInstanceId) => Effect.Effect<void>;
/** Whether a live connection exists. */
readonly isConnected: (instanceId: ProviderInstanceId) => Effect.Effect<boolean>;
/** Live transport for an instance, if connected. */
readonly transport: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesGatewayTransport | undefined>;
}
/**
* Project the status fields owned by liveness. The durable half (nickname,
* connectorUrl, revoked) is layered on by the broker, which reads it from
* settings.
*/
export type HermesLivenessStatusFields = Pick<
HermesGatewayInstanceStatus,
| "lastConnectedAt"
| "pluginVersion"
| "hermesVersion"
| "model"
| "activeSessionCount"
| "protocolVersion"
| "capabilities"
| "connectionGeneration"
> & {
readonly connected: boolean;
readonly upgradeRequired: boolean;
};
@@ -1,68 +0,0 @@
/**
* HermesEnrollmentStore — the mint/consume/expire lifecycle of one-time
* enrollment tokens.
*
* Separated from the broker so the token rules live in one place:
*
* - A token is redeemable exactly once. Consumption is compare-and-swap:
* the entry is deleted only if it is still byte-identical to the one the
* caller authenticated against, and expiry is re-checked afterwards, so
* two concurrent redemptions cannot both win.
* - Minting a token for an instance invalidates that instance's previous
* tokens, so only the newest unconsumed token is ever redeemable.
* - Tokens expire from memory on a sweep, not only lazily at redemption.
* Redemption-time expiry alone let any operator-scoped client grow the
* map without bound by calling createEnrollment in a loop.
*
* @module HermesEnrollmentStore
*/
import type {
HermesGatewayCreateEnrollmentInput,
HermesGatewayEnrollmentToken,
ProviderInstanceId,
} from "@t3tools/contracts";
import type * as Effect from "effect/Effect";
export interface PendingEnrollment {
readonly input: HermesGatewayCreateEnrollmentInput;
readonly expiresAtMillis: number;
}
export interface HermesEnrollmentStore {
/**
* Mint a token for `input`, invalidating any prior unconsumed token for the
* same instance. Returns the token and its absolute expiry.
*/
readonly mint: (
input: HermesGatewayCreateEnrollmentInput,
) => Effect.Effect<
{ readonly token: HermesGatewayEnrollmentToken; readonly expiresAtMillis: number },
never
>;
/**
* Look up a token without consuming it. Returns `undefined` when the token
* is unknown or already expired — the caller authenticates against this
* value and later passes it back to `consume`.
*/
readonly peek: (token: string) => Effect.Effect<PendingEnrollment | undefined>;
/**
* Compare-and-swap consumption. Deletes the entry only if it is still
* identical to `expected`, then re-checks expiry. Returns the consumed
* enrollment, or `undefined` if it was raced away or expired in between.
*/
readonly consume: (
token: string,
expected: PendingEnrollment,
) => Effect.Effect<PendingEnrollment | undefined>;
/** Drop every unconsumed token belonging to `instanceId`. */
readonly forget: (instanceId: ProviderInstanceId) => Effect.Effect<void>;
/** Drop every expired token. Run periodically; bounds memory. */
readonly sweep: Effect.Effect<void>;
/** Number of unconsumed tokens. Exposed for tests and diagnostics. */
readonly size: Effect.Effect<number>;
}
@@ -1,128 +0,0 @@
import type {
HermesGatewayConnectionHello,
HermesGatewayConnectionRole,
HermesGatewayCreateEnrollmentInput,
HermesGatewayEnrollmentResult,
HermesGatewayInstanceStatus,
HermesGatewayPluginToT3Message,
HermesGatewayRemoveInstanceResult,
HermesGatewayRenameInstanceInput,
HermesGatewayRenameInstanceResult,
HermesGatewayRevokeInstanceResult,
HermesGatewayT3ToPluginMessage,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import type { HermesGatewayManagementError } from "@t3tools/contracts";
import type { ProviderAdapterRequestError } from "../Errors.ts";
export interface HermesGatewayTransport {
readonly send: (
message: HermesGatewayT3ToPluginMessage,
) => Effect.Effect<void, ProviderAdapterRequestError>;
readonly close: (code: number, reason: string) => Effect.Effect<void>;
}
export interface HermesGatewayConnectionRegistration {
readonly instanceId: ProviderInstanceId;
/**
* Fencing token for the instance's primary connection, or `null` for a
* delivery connection.
*
* A delivery connection is deliberately outside the generation scheme: it
* was never registered as the primary, so there is nothing for it to be
* stale against, and giving it a generation would let it be compared —
* and therefore mistaken for a replacement — against the live socket.
*/
readonly generation: number | null;
/**
* What this socket registered as. `delivery` sockets may only hand over
* `home.deliver` frames; they carry no session, take no ping loop, and
* their disconnect must not disturb the instance's liveness state.
*/
readonly role: HermesGatewayConnectionRole;
readonly accepted: Extract<
HermesGatewayT3ToPluginMessage,
{ readonly type: "connection.accepted" }
>;
}
export interface HermesGatewayEnvelope {
readonly instanceId: ProviderInstanceId;
readonly message: Exclude<HermesGatewayPluginToT3Message, HermesGatewayConnectionHello>;
}
export interface HermesGatewayBrokerShape {
readonly createEnrollment: (
input: HermesGatewayCreateEnrollmentInput,
) => Effect.Effect<HermesGatewayEnrollmentResult, HermesGatewayManagementError>;
readonly getInstanceStatus: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesGatewayInstanceStatus, HermesGatewayManagementError>;
readonly listInstances: Effect.Effect<
ReadonlyArray<HermesGatewayInstanceStatus>,
HermesGatewayManagementError
>;
readonly renameInstance: (
input: HermesGatewayRenameInstanceInput,
) => Effect.Effect<HermesGatewayRenameInstanceResult, HermesGatewayManagementError>;
readonly revokeInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesGatewayRevokeInstanceResult, HermesGatewayManagementError>;
readonly removeInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesGatewayRemoveInstanceResult, HermesGatewayManagementError>;
readonly registerConnection: (
hello: HermesGatewayConnectionHello,
transport: HermesGatewayTransport,
) => Effect.Effect<
HermesGatewayConnectionRegistration,
Extract<HermesGatewayT3ToPluginMessage, { readonly type: "connection.rejected" }>
>;
readonly receive: (
registration: HermesGatewayConnectionRegistration,
message: Exclude<HermesGatewayPluginToT3Message, HermesGatewayConnectionHello>,
) => Effect.Effect<void>;
readonly disconnect: (registration: HermesGatewayConnectionRegistration) => Effect.Effect<void>;
readonly request: (
instanceId: ProviderInstanceId,
message: HermesGatewayT3ToPluginMessage,
) => Effect.Effect<
Exclude<HermesGatewayPluginToT3Message, HermesGatewayConnectionHello>,
ProviderAdapterRequestError
>;
readonly send: (
instanceId: ProviderInstanceId,
message: HermesGatewayT3ToPluginMessage,
) => Effect.Effect<void, ProviderAdapterRequestError>;
readonly isConnected: (instanceId: ProviderInstanceId) => Effect.Effect<boolean>;
readonly stream: Stream.Stream<HermesGatewayEnvelope>;
readonly streamStatuses: Stream.Stream<HermesGatewayInstanceStatus>;
}
const unavailable = () => Effect.die(new Error("HermesGatewayBroker live layer is not installed"));
export const HermesGatewayBroker = Context.Reference<HermesGatewayBrokerShape>(
"t3/provider/Services/HermesGatewayBroker",
{
defaultValue: () => ({
createEnrollment: unavailable,
getInstanceStatus: unavailable,
listInstances: unavailable(),
renameInstance: unavailable,
revokeInstance: unavailable,
removeInstance: unavailable,
registerConnection: unavailable,
receive: unavailable,
disconnect: unavailable,
request: unavailable,
send: unavailable,
isConnected: () => Effect.succeed(false),
stream: Stream.empty,
streamStatuses: Stream.empty,
}),
},
);
@@ -11,8 +11,6 @@ import type {
ApprovalRequestId,
ProviderApprovalDecision,
ProviderDriverKind,
ProviderInstanceDescription,
ProviderSkillBody,
ProviderUserInputAnswers,
ProviderRuntimeEvent,
ProviderSendTurnInput,
@@ -121,29 +119,6 @@ export interface ProviderAdapterShape<TError> {
*/
readonly stopAll: () => Effect.Effect<void, TError>;
/**
* Driver-specific enrichment for the Agent page.
*
* OPTIONAL by design. The caller always builds a complete description from
* the `ServerProvider` snapshot first (`describeFromServerProvider`), then
* lets an adapter that knows more overwrite parts of it. A driver that
* implements nothing here still gets a working Agent page, and one that
* cannot reach its agent right now should fail rather than return a
* half-filled description — the caller falls back to the snapshot default.
*/
readonly describe?: (
base: ProviderInstanceDescription,
) => Effect.Effect<ProviderInstanceDescription, TError>;
/**
* Fetch one skill's markdown body. Fired on row expand, never eagerly —
* bodies are unbounded in size and most are never opened.
*
* Returning `markdown: null` means "this skill exists but its body is not
* retrievable"; failing means the request itself could not be made.
*/
readonly getSkillBody?: (skillName: string) => Effect.Effect<ProviderSkillBody, TError>;
/**
* Canonical runtime event stream emitted by this adapter.
*/
@@ -7,11 +7,8 @@
* @module ProviderRegistry
*/
import type {
ProviderDescribeError,
ProviderInstanceDescription,
ProviderInstanceId,
ProviderDriverKind,
ProviderSkillBody,
ServerProvider,
ServerProviderUpdateState,
} from "@t3tools/contracts";
@@ -72,28 +69,6 @@ export interface ProviderRegistryShape {
readonly state: ServerProviderUpdateState | null;
}) => Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Provider-generic description of one configured instance, for the Agent
* page. Always answerable from the cached snapshot; drivers that can reach
* their agent enrich it via `ProviderAdapterShape.describe`.
*
* Enrichment failure is not description failure — an unreachable agent
* still yields the snapshot-derived description, so the page renders
* last-known state instead of an error. Only an unknown instance fails.
*/
readonly describeInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderInstanceDescription, ProviderDescribeError>;
/**
* Read one skill's markdown body from the instance's adapter. Fired on row
* expand — never eagerly, since bodies are unbounded and rarely opened.
*/
readonly getSkillBody: (input: {
readonly instanceId: ProviderInstanceId;
readonly skillName: string;
}) => Effect.Effect<ProviderSkillBody, ProviderDescribeError>;
/**
* Stream of provider snapshot updates — one emission per aggregated
* change. The array contains the full current state.
@@ -1,69 +0,0 @@
/**
* RequestCorrelator — generic request/response correlation over a one-way
* message transport.
*
* Nothing in here is Hermes-specific. Any provider that speaks a protocol
* where a request carries an id and the reply echoes it can use this: register
* a pending entry, write the request, await the correlated reply, and have the
* entry torn down on success, failure, timeout, or interrupt.
*
* The correlator owns three guarantees the call sites used to hand-roll:
*
* 1. **No interrupt window.** Registration happens uninterruptibly and the
* await pipeline is wrapped in `ensuring`, so there is no point at which
* an interrupt can leave an entry in the map with nobody to clean it up.
* 2. **Age-based sweeping.** An entry whose awaiting fiber died abnormally
* is reaped by `sweep` instead of leaking for the process lifetime.
* 3. **Owner-scoped failure.** When a connection drops, every request routed
* over it fails immediately rather than waiting out its timeout.
*
* @module RequestCorrelator
*/
import type * as Duration from "effect/Duration";
import type * as Effect from "effect/Effect";
import type { ProviderAdapterRequestError } from "../Errors.ts";
export interface RequestCorrelatorSend<Owner> {
/**
* The logical route the request travels over. Used to fail an entire group
* of in-flight requests at once when that route dies (see `failOwner`).
*/
readonly owner: Owner;
/** Correlation key. Must match the id echoed on the response. */
readonly requestId: string;
/** Protocol method name, surfaced on errors for diagnostics. */
readonly method: string;
/** Writes the request. Registration is already in place when this runs. */
readonly send: Effect.Effect<void, ProviderAdapterRequestError>;
/** Overrides the correlator's default response timeout. */
readonly timeout?: Duration.Duration | undefined;
}
export interface RequestCorrelator<Owner, Response> {
/**
* Register, send, and await the correlated response. Cleans up the pending
* entry on every exit path, including interrupt.
*/
readonly request: (
input: RequestCorrelatorSend<Owner>,
) => Effect.Effect<Response, ProviderAdapterRequestError>;
/**
* Resolve a pending request. Returns `false` when no entry was waiting,
* which lets callers distinguish a correlated reply from an unsolicited one.
*/
readonly complete: (requestId: string, response: Response) => Effect.Effect<boolean>;
/** Fail every pending request registered against `owner`. */
readonly failOwner: (owner: Owner, detail: string) => Effect.Effect<void>;
/**
* Fail pending entries older than the configured max age. Safety net for
* entries whose awaiting fiber died without running its own cleanup.
*/
readonly sweep: Effect.Effect<void>;
/** Number of in-flight requests. Exposed for tests and diagnostics. */
readonly pendingCount: Effect.Effect<number>;
}
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff. Show more