Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71bf16596d | ||
|
|
cf2b02f8e9 | ||
|
|
fb1a59e963 | ||
|
|
a74bb10a11 | ||
|
|
120d684da9 | ||
|
|
3e77096713 | ||
|
|
a0b75c6b58 |
No files matched your search
@@ -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
|
||||
@@ -35,5 +35,3 @@ node_modules/
|
||||
*.log
|
||||
.env*
|
||||
!.env.example
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
@@ -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.
|
||||
@@ -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).
|
||||
|
||||
|
||||
@@ -63,7 +63,6 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
calls.setDockIcon.push(iconPath);
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
describe("DesktopLifecycle", () => {
|
||||
for (const platform of ["darwin", "win32", "linux"] satisfies ReadonlyArray<NodeJS.Platform>) {
|
||||
it.effect(`lets the updater's quit event proceed on ${platform}`, () => {
|
||||
const appListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
|
||||
const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
appListeners.set("before-quit-for-update", listener);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
appListeners.delete("before-quit-for-update");
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
on: (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
appListeners.set(
|
||||
eventName,
|
||||
listener as unknown as (...args: readonly unknown[]) => void,
|
||||
);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
appListeners.delete(eventName);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
const electronThemeLayer = Layer.succeed(ElectronTheme.ElectronTheme, {
|
||||
shouldUseDarkColors: Effect.succeed(false),
|
||||
setSource: () => Effect.void,
|
||||
onUpdated: () => Effect.void,
|
||||
});
|
||||
|
||||
const desktopWindowLayer = Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
createMain: Effect.die("unexpected window creation"),
|
||||
ensureMain: Effect.die("unexpected window creation"),
|
||||
revealOrCreateMain: Effect.die("unexpected window creation"),
|
||||
activate: Effect.void,
|
||||
createMainIfBackendReady: Effect.void,
|
||||
showConnectingSplash: Effect.void,
|
||||
handleBackendReady: () => Effect.void,
|
||||
handleBackendNotReady: Effect.void,
|
||||
flushMainWindowBounds: Effect.void,
|
||||
dispatchMenuAction: () => Effect.void,
|
||||
syncAppearance: Effect.void,
|
||||
});
|
||||
|
||||
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, {
|
||||
platform,
|
||||
isDevelopment: false,
|
||||
} as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
const layer = DesktopLifecycle.layer.pipe(
|
||||
Layer.provideMerge(electronAppLayer),
|
||||
Layer.provideMerge(electronThemeLayer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(DesktopShutdown.layer),
|
||||
Layer.provideMerge(DesktopState.layer),
|
||||
);
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
yield* lifecycle.register;
|
||||
|
||||
appListeners.get("before-quit-for-update")?.();
|
||||
|
||||
let prevented = false;
|
||||
const event = {
|
||||
preventDefault: () => {
|
||||
prevented = true;
|
||||
},
|
||||
} as Electron.Event;
|
||||
appListeners.get("before-quit")?.(event);
|
||||
|
||||
assert.isFalse(
|
||||
prevented,
|
||||
"cancelling this event prevents the updater from completing its relaunch",
|
||||
);
|
||||
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
assert.isTrue(yield* Ref.get(state.quitting));
|
||||
}),
|
||||
).pipe(Effect.provide(layer));
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -176,28 +176,16 @@ export const make = DesktopLifecycle.of({
|
||||
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
|
||||
const runEffect = Effect.runPromiseWith(context);
|
||||
let quitAllowed = false;
|
||||
let updaterQuitAllowed = false;
|
||||
yield* electronTheme.onUpdated(() => {
|
||||
void runEffect(
|
||||
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
|
||||
);
|
||||
});
|
||||
yield* electronApp.onBeforeQuitForUpdate(() => {
|
||||
// Electron's updater owns the remaining quit/install/relaunch sequence.
|
||||
// Cancelling the following app "before-quit" event breaks that sequence,
|
||||
// most visibly on macOS where the native updater performs the relaunch.
|
||||
updaterQuitAllowed = true;
|
||||
void runEffect(
|
||||
logLifecycleInfo("allowing updater-controlled quit").pipe(
|
||||
Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),
|
||||
),
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("before-quit", (event: Electron.Event) => {
|
||||
handleBeforeQuit(
|
||||
event,
|
||||
runEffect,
|
||||
() => quitAllowed || updaterQuitAllowed,
|
||||
() => quitAllowed,
|
||||
() => {
|
||||
quitAllowed = true;
|
||||
},
|
||||
|
||||
@@ -4,8 +4,6 @@ import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const {
|
||||
appendSwitchMock,
|
||||
autoUpdaterOnMock,
|
||||
autoUpdaterRemoveListenerMock,
|
||||
exitMock,
|
||||
getAppPathMock,
|
||||
getVersionMock,
|
||||
@@ -25,8 +23,6 @@ const {
|
||||
whenReadyMock,
|
||||
} = vi.hoisted(() => ({
|
||||
appendSwitchMock: vi.fn(),
|
||||
autoUpdaterOnMock: vi.fn(),
|
||||
autoUpdaterRemoveListenerMock: vi.fn(),
|
||||
exitMock: vi.fn(),
|
||||
getAppPathMock: vi.fn(() => "/app"),
|
||||
getVersionMock: vi.fn(() => "1.2.3"),
|
||||
@@ -47,10 +43,6 @@ const {
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
autoUpdater: {
|
||||
on: autoUpdaterOnMock,
|
||||
removeListener: autoUpdaterRemoveListenerMock,
|
||||
},
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
@@ -85,8 +77,6 @@ import * as ElectronApp from "./ElectronApp.ts";
|
||||
describe("ElectronApp", () => {
|
||||
beforeEach(() => {
|
||||
appendSwitchMock.mockClear();
|
||||
autoUpdaterOnMock.mockClear();
|
||||
autoUpdaterRemoveListenerMock.mockClear();
|
||||
exitMock.mockClear();
|
||||
onMock.mockClear();
|
||||
quitMock.mockClear();
|
||||
@@ -163,22 +153,4 @@ describe("ElectronApp", () => {
|
||||
assert.deepEqual(removeListenerMock.mock.calls, [["activate", listener]]);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("scopes native updater quit listeners", () =>
|
||||
Effect.gen(function* () {
|
||||
const listener = vi.fn();
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
yield* electronApp.onBeforeQuitForUpdate(listener);
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(autoUpdaterOnMock.mock.calls, [["before-quit-for-update", listener]]);
|
||||
assert.deepEqual(autoUpdaterRemoveListenerMock.mock.calls, [
|
||||
["before-quit-for-update", listener],
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
});
|
||||
@@ -66,9 +66,6 @@ export class ElectronApp extends Context.Service<
|
||||
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
|
||||
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
|
||||
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
|
||||
readonly onBeforeQuitForUpdate: (
|
||||
listener: () => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
@@ -181,16 +178,6 @@ export const make = ElectronApp.of({
|
||||
}
|
||||
Electron.app.commandLine.appendSwitch(switchName, value);
|
||||
}),
|
||||
onBeforeQuitForUpdate: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.autoUpdater.on("before-quit-for-update", listener);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.autoUpdater.removeListener("before-quit-for-update", listener);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
on: addScopedAppListener,
|
||||
});
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
environmentIdentificationMode: "artwork",
|
||||
favorites: [],
|
||||
glassOpacity: 80,
|
||||
providerModelPreferences: {},
|
||||
@@ -31,7 +30,6 @@ const clientSettings: ClientSettings = {
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
sidebarV2Enabled: false,
|
||||
sidebarV2ConfiguredByUser: false,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
@@ -45,7 +45,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
IconChevronUp,
|
||||
IconCircleCheck,
|
||||
IconCircleXFilled,
|
||||
IconClock,
|
||||
IconCopy,
|
||||
IconDeviceDesktop,
|
||||
IconDots,
|
||||
@@ -96,6 +97,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
camera: IconCamera,
|
||||
checkmark: IconCheck,
|
||||
"checkmark.circle": IconCircleCheck,
|
||||
clock: IconClock,
|
||||
"chevron.down": IconChevronDown,
|
||||
"chevron.left": IconChevronLeft,
|
||||
"chevron.left.forwardslash.chevron.right": IconCode,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -24,7 +24,13 @@ import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironment
|
||||
import { ConnectionStatusDot } from "./ConnectionStatusDot";
|
||||
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
|
||||
|
||||
interface CloudEnvironmentRowsProps {
|
||||
/**
|
||||
* "T3 Connect" section: every environment published to the signed-in account,
|
||||
* with connect switches, availability status, refresh, and loading/error
|
||||
* states. Shared between the Settings environments screen and the T3 Connect
|
||||
* onboarding sheet.
|
||||
*/
|
||||
export function CloudEnvironmentRows(props: {
|
||||
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
|
||||
readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
|
||||
@@ -35,31 +41,8 @@ interface CloudEnvironmentRowsProps {
|
||||
* pull-to-refresh).
|
||||
*/
|
||||
readonly showHeader?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* "T3 Connect" section: every environment published to the signed-in account,
|
||||
* with connect switches, availability status, refresh, and loading/error
|
||||
* states. Shared between the Settings environments screen and the T3 Connect
|
||||
* onboarding sheet.
|
||||
*/
|
||||
export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
// Showcase captures run without a Clerk publishable key, so `ClerkProvider`
|
||||
// is never mounted and any `useAuth` call throws — the fixture states whether
|
||||
// the rows are signed in instead of asking Clerk.
|
||||
if (props.showcaseSignedIn !== undefined) {
|
||||
return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;
|
||||
}
|
||||
return <SignedInCloudEnvironmentRows {...props} />;
|
||||
}
|
||||
|
||||
function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
}) {
|
||||
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
if (!isSignedIn) return null;
|
||||
return <CloudEnvironmentRowsContent {...props} />;
|
||||
}
|
||||
|
||||
function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
|
||||
const controller = useConnectionController();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const availableCloudEnvironments =
|
||||
@@ -84,6 +67,8 @@ function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
|
||||
|
||||
const showHeader = props.showHeader ?? true;
|
||||
|
||||
if (!(props.showcaseSignedIn ?? isSignedIn)) return null;
|
||||
|
||||
return (
|
||||
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
|
||||
{showHeader ? (
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
|
||||
@@ -10,7 +12,7 @@ import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { T3Wordmark } from "../../components/T3Wordmark";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
@@ -57,14 +59,21 @@ function checkedMenuState(checked: boolean) {
|
||||
return checked ? ("on" as const) : undefined;
|
||||
}
|
||||
|
||||
/** Thread List v2 lays the list out in fixed creation order, so the
|
||||
sort/group filter controls would be silently ignored — hide them and
|
||||
key the "customized" icon state off the environment filter alone. */
|
||||
function useThreadListV2FilterGate() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
return (
|
||||
AsyncResult.isSuccess(preferencesResult) && preferencesResult.value.threadListV2Enabled === true
|
||||
);
|
||||
}
|
||||
|
||||
function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
// Thread List v2 lays the list out in fixed creation order, so the
|
||||
// sort/group filter controls would be silently ignored — hide them and
|
||||
// key the "customized" icon state off the environment filter alone.
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const threadListV2Enabled = useThreadListV2FilterGate();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
@@ -282,10 +291,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
function IosHomeHeader(props: HomeHeaderProps) {
|
||||
const searchBarRef = useRef<SearchBarCommands>(null);
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
// Thread List v2 lays the list out in fixed creation order, so the
|
||||
// sort/group filter controls would be silently ignored — hide them and
|
||||
// key the "customized" icon state off the environment filter alone.
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const threadListV2Enabled = useThreadListV2FilterGate();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
|
||||
@@ -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";
|
||||
@@ -30,8 +29,14 @@ export function HomeRouteScreen() {
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const {
|
||||
archiveThread,
|
||||
confirmDeleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -60,12 +65,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) => ({
|
||||
@@ -138,6 +141,8 @@ export function HomeRouteScreen() {
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onSettleThread={settleThread}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
|
||||
@@ -24,11 +24,9 @@ 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";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import {
|
||||
@@ -37,14 +35,15 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "../threads/thread-list-items";
|
||||
import { ThreadListV2PendingRow, ThreadListV2Row } from "../threads/thread-list-v2-items";
|
||||
import { ThreadListV2Row, ThreadListV2SnoozedShelfHeader } from "../threads/thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
snoozeWakeLabel,
|
||||
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 {
|
||||
buildHomeListLayout,
|
||||
@@ -67,6 +66,11 @@ import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-stat
|
||||
|
||||
/* ─── Types ──────────────────────────────────────────────────────────── */
|
||||
|
||||
/** v2 list rows: thread rows plus the standalone snoozed-shelf header. */
|
||||
type ThreadListV2DisplayItem =
|
||||
| { readonly type: "thread"; readonly item: ThreadListV2Item }
|
||||
| { readonly type: "snoozed-shelf-header"; readonly count: number };
|
||||
|
||||
interface HomeScreenProps {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
@@ -94,6 +98,10 @@ interface HomeScreenProps {
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** Resolves true iff the settle was dispatched and succeeded. */
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
/** Snoozes for the swipe action's one-hour default. */
|
||||
readonly onSnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
/** Wakes a snoozed thread from the snoozed shelf. */
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
@@ -184,7 +192,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
>(() => new Map());
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const threadListV2Enabled =
|
||||
AsyncResult.isSuccess(preferencesResult) &&
|
||||
preferencesResult.value.threadListV2Enabled === true;
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
@@ -452,6 +462,18 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onSettleThread],
|
||||
);
|
||||
const handleSnoozeThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onSnoozeThread(thread);
|
||||
},
|
||||
[props.onSnoozeThread],
|
||||
);
|
||||
const handleUnsnoozeThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onUnsnoozeThread(thread);
|
||||
},
|
||||
[props.onUnsnoozeThread],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
@@ -469,6 +491,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
// Collapsed by default, like web: the shelf is a shelf, not a second inbox.
|
||||
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
|
||||
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
|
||||
// now is quantized to the minute and ticks so the inactivity auto-settle
|
||||
// boundary is actually crossed while the app stays open (mirrors web);
|
||||
// without a clock dependency the partition memoizes a frozen "now".
|
||||
@@ -509,7 +534,13 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
return {
|
||||
items: [],
|
||||
hiddenSettledCount: 0,
|
||||
snoozedCount: 0,
|
||||
snoozedShelfHeaderIndex: null,
|
||||
nextSnoozeWakeAt: null,
|
||||
};
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
@@ -523,11 +554,16 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
snoozedShelfExpanded,
|
||||
// Phones navigate away on select, so no row is ever "open" here — the
|
||||
// collapsed-shelf exception is an iPad split-view concern.
|
||||
selectedThreadKey: null,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
@@ -551,94 +587,86 @@ 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],
|
||||
);
|
||||
// The shelf header is a list row of its own: it must render even when the
|
||||
// shelf is collapsed and has no rows to hang it on.
|
||||
const threadListV2Items = useMemo((): ThreadListV2DisplayItem[] => {
|
||||
const rows: ThreadListV2DisplayItem[] = threadListV2Layout.items.map((item) => ({
|
||||
type: "thread" as const,
|
||||
item,
|
||||
}));
|
||||
const headerIndex = threadListV2Layout.snoozedShelfHeaderIndex;
|
||||
if (headerIndex !== null) {
|
||||
rows.splice(headerIndex, 0, {
|
||||
type: "snoozed-shelf-header",
|
||||
count: threadListV2Layout.snoozedCount,
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}, [
|
||||
threadListV2Layout.items,
|
||||
threadListV2Layout.snoozedCount,
|
||||
threadListV2Layout.snoozedShelfHeaderIndex,
|
||||
]);
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
({ item }: { readonly item: ThreadListV2ListItem }) => {
|
||||
if (item.type === "v2-pending") {
|
||||
const pendingScopeKey = scopedProjectKey(
|
||||
item.pendingTask.message.environmentId,
|
||||
item.pendingTask.creation.projectId,
|
||||
);
|
||||
({ item: displayItem }: { readonly item: ThreadListV2DisplayItem }) => {
|
||||
if (displayItem.type === "snoozed-shelf-header") {
|
||||
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}
|
||||
<ThreadListV2SnoozedShelfHeader
|
||||
count={displayItem.count}
|
||||
expanded={snoozedShelfExpanded}
|
||||
onToggle={toggleSnoozedShelf}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const thread = item.item.thread;
|
||||
const item = displayItem.item;
|
||||
return (
|
||||
<ThreadListV2Row
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
thread={item.thread}
|
||||
variant={item.variant}
|
||||
showSettledDivider={item.showSettledDivider}
|
||||
snoozed={item.snoozed}
|
||||
snoozeWakeLabelText={
|
||||
item.snoozed && item.thread.snoozedUntil != null
|
||||
? snoozeWakeLabel(item.thread.snoozedUntil, { now: `${nowMinute}:00.000Z` })
|
||||
: undefined
|
||||
}
|
||||
project={
|
||||
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
projectByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
projectTitle={v2ProjectTitleByProjectKey.get(
|
||||
scopedProjectKey(thread.environmentId, thread.projectId),
|
||||
scopedProjectKey(item.thread.environmentId, item.thread.projectId),
|
||||
)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(thread.environmentId)
|
||||
.get(item.thread.environmentId)
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
(item.thread.session?.providerInstanceId ??
|
||||
item.thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
Object.keys(props.savedConnectionsById).length > 1
|
||||
? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
|
||||
? (props.savedConnectionsById[item.thread.environmentId]?.environmentLabel ?? null)
|
||||
: null
|
||||
}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
settlementSupported={settlementEnvironmentIds.has(item.thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(item.thread.environmentId)}
|
||||
onSnoozeThread={handleSnoozeThread}
|
||||
onUnsnoozeThread={handleUnsnoozeThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
projectCwdByKey.get(
|
||||
scopedProjectKey(item.thread.environmentId, item.thread.projectId),
|
||||
) ?? null
|
||||
}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
@@ -649,22 +677,32 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnsnoozeThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onDeletePendingTask,
|
||||
props.onSelectPendingTask,
|
||||
props.onSelectThread,
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
nowMinute,
|
||||
snoozeEnvironmentIds,
|
||||
snoozedShelfExpanded,
|
||||
toggleSnoozedShelf,
|
||||
v2ProjectTitleByProjectKey,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
|
||||
const v2KeyExtractor = useCallback(
|
||||
(item: ThreadListV2DisplayItem) =>
|
||||
item.type === "snoozed-shelf-header"
|
||||
? "snoozed-shelf-header"
|
||||
: `${item.item.thread.environmentId}:${item.item.thread.id}`,
|
||||
[],
|
||||
);
|
||||
|
||||
const extraData = useMemo(
|
||||
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
|
||||
@@ -774,9 +812,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 +877,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 ? (
|
||||
@@ -865,35 +933,21 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
// v2 project scope, so it can be null (results elsewhere) while this list
|
||||
// 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.
|
||||
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.
|
||||
// fact when a query is active. Pending tasks render in the header, so the
|
||||
// list showing them isn't empty in the user's eyes. Snoozed threads need
|
||||
// no empty-state case: the shelf header renders as a list row whenever
|
||||
// anything is snoozed, so an all-snoozed list is never actually empty.
|
||||
const v2ListEmpty =
|
||||
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<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={`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 +959,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,
|
||||
|
||||
@@ -47,13 +47,57 @@ export const THREAD_SWIPE_SPRING = {
|
||||
stiffness: 330,
|
||||
};
|
||||
|
||||
interface ThreadSwipePrimaryAction {
|
||||
interface ThreadSwipeAction {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly label: string;
|
||||
readonly onPress: () => void;
|
||||
}
|
||||
|
||||
interface ThreadSwipeSecondaryAction extends ThreadSwipeAction {
|
||||
readonly backgroundColor: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rows that opt out of a secondary action reveal a single-action tray, so the
|
||||
* open width (and every animation range derived from it) shrinks to one item
|
||||
* instead of leaving an empty slot where Delete used to sit.
|
||||
*/
|
||||
function swipeActionsWidth(hasSecondaryAction: boolean) {
|
||||
return hasSecondaryAction ? THREAD_SWIPE_ACTIONS_WIDTH : ACTION_ITEM_WIDTH;
|
||||
}
|
||||
|
||||
/** `undefined` = v1 default (Delete), `null` = no secondary action at all. */
|
||||
function resolveSecondaryAction(input: {
|
||||
readonly close: () => void;
|
||||
readonly onDelete: () => void;
|
||||
readonly secondaryAction: ThreadSwipeAction | null | undefined;
|
||||
readonly threadTitle: string;
|
||||
}): ThreadSwipeSecondaryAction | null {
|
||||
if (input.secondaryAction === null) return null;
|
||||
if (input.secondaryAction === undefined) {
|
||||
return {
|
||||
accessibilityLabel: `Delete ${input.threadTitle}`,
|
||||
backgroundColor: "#ff2d55",
|
||||
icon: "trash",
|
||||
label: "Delete",
|
||||
onPress: () => {
|
||||
input.close();
|
||||
input.onDelete();
|
||||
},
|
||||
};
|
||||
}
|
||||
const action = input.secondaryAction;
|
||||
return {
|
||||
...action,
|
||||
backgroundColor: "#5856d6",
|
||||
onPress: () => {
|
||||
input.close();
|
||||
action.onPress();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivers the scroll gate to swipeables via context so that flipping it does
|
||||
* NOT re-render whole rows: putting the flag in list extraData/renderItem deps
|
||||
@@ -183,7 +227,15 @@ export function ThreadSwipeable(props: {
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void;
|
||||
readonly primaryAction: ThreadSwipePrimaryAction;
|
||||
readonly primaryAction: ThreadSwipeAction;
|
||||
/**
|
||||
* Second action revealed nearest the row edge. Omitted (`undefined`) keeps
|
||||
* the v1 default of a destructive Delete; explicit `null` opts out of a
|
||||
* secondary action entirely and reveals a single-action tray — the two must
|
||||
* stay distinguishable so gating an optional action can never fall back to
|
||||
* an unadvertised Delete.
|
||||
*/
|
||||
readonly secondaryAction?: ThreadSwipeAction | null;
|
||||
/**
|
||||
* Identity of the content being wrapped. When a recycled list reuses this
|
||||
* component for a different item, the swipeable snaps back to closed so an
|
||||
@@ -197,7 +249,12 @@ export function ThreadSwipeable(props: {
|
||||
}) {
|
||||
const swipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const fullSwipeArmedRef = useRef(false);
|
||||
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, props.fullSwipeWidth * 0.58);
|
||||
const hasSecondaryAction = props.secondaryAction !== null;
|
||||
const actionsWidth = swipeActionsWidth(hasSecondaryAction);
|
||||
const fullSwipeThreshold = Math.max(actionsWidth + 44, props.fullSwipeWidth * 0.58);
|
||||
// With no secondary action there is no Delete button to stretch or commit,
|
||||
// so a full swipe can only mean the primary action.
|
||||
const fullSwipeAction = hasSecondaryAction ? (props.fullSwipeAction ?? "delete") : "primary";
|
||||
const close = useCallback(() => swipeableRef.current?.close(), []);
|
||||
const gateEnabled = use(SwipeableScrollGateContext);
|
||||
const resetKey = props.resetKey;
|
||||
@@ -251,7 +308,7 @@ export function ThreadSwipeable(props: {
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
if (props.fullSwipeAction === "primary") {
|
||||
if (fullSwipeAction === "primary") {
|
||||
props.primaryAction.onPress();
|
||||
} else {
|
||||
props.onDelete();
|
||||
@@ -264,9 +321,8 @@ export function ThreadSwipeable(props: {
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={props.backgroundColor}
|
||||
compact={props.compactActions === true}
|
||||
fullSwipeAction={props.fullSwipeAction ?? "delete"}
|
||||
fullSwipeAction={fullSwipeAction}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
primaryAction={{
|
||||
...props.primaryAction,
|
||||
@@ -275,12 +331,16 @@ export function ThreadSwipeable(props: {
|
||||
props.primaryAction.onPress();
|
||||
},
|
||||
}}
|
||||
swipeableMethods={methods}
|
||||
threadTitle={props.threadTitle}
|
||||
secondaryAction={resolveSecondaryAction({
|
||||
close: () => methods.close(),
|
||||
onDelete: props.onDelete,
|
||||
secondaryAction: props.secondaryAction,
|
||||
threadTitle: props.threadTitle,
|
||||
})}
|
||||
translation={translation}
|
||||
/>
|
||||
)}
|
||||
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
|
||||
rightThreshold={actionsWidth * 0.42}
|
||||
simultaneousWithExternalGesture={props.simultaneousWithExternalGesture}
|
||||
>
|
||||
{props.children(close)}
|
||||
@@ -290,6 +350,9 @@ export function ThreadSwipeable(props: {
|
||||
|
||||
function SwipeActionButton(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
/** Width of the whole action tray — the point past which a swipe stretches
|
||||
* the committing button instead of revealing more of it. */
|
||||
readonly actionsWidth: number;
|
||||
readonly backgroundColor: string;
|
||||
readonly compact: boolean;
|
||||
readonly entryRange: readonly [number, number];
|
||||
@@ -305,10 +368,10 @@ function SwipeActionButton(props: {
|
||||
const actionStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
|
||||
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
|
||||
const stretch = Math.max(reveal - props.actionsWidth, 0);
|
||||
const fullSwipeProgress = interpolate(
|
||||
reveal,
|
||||
[THREAD_SWIPE_ACTIONS_WIDTH, props.fullSwipeThreshold + 20],
|
||||
[props.actionsWidth, props.fullSwipeThreshold + 20],
|
||||
[0, 1],
|
||||
Extrapolation.CLAMP,
|
||||
);
|
||||
@@ -327,9 +390,7 @@ function SwipeActionButton(props: {
|
||||
});
|
||||
const circleStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = props.stretchesOnFullSwipe
|
||||
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
|
||||
: 0;
|
||||
const stretch = props.stretchesOnFullSwipe ? Math.max(reveal - props.actionsWidth, 0) : 0;
|
||||
|
||||
return {
|
||||
transform: [{ translateX: -stretch }],
|
||||
@@ -338,9 +399,7 @@ function SwipeActionButton(props: {
|
||||
});
|
||||
const iconStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = props.stretchesOnFullSwipe
|
||||
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
|
||||
: 0;
|
||||
const stretch = props.stretchesOnFullSwipe ? Math.max(reveal - props.actionsWidth, 0) : 0;
|
||||
const armedProgress = interpolate(
|
||||
reveal,
|
||||
[props.fullSwipeThreshold, props.fullSwipeThreshold + 20],
|
||||
@@ -358,7 +417,7 @@ function SwipeActionButton(props: {
|
||||
}
|
||||
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
|
||||
const stretch = Math.max(reveal - props.actionsWidth, 0);
|
||||
return {
|
||||
opacity: interpolate(
|
||||
reveal,
|
||||
@@ -446,14 +505,17 @@ export function ThreadSwipeActions(props: {
|
||||
readonly compact: boolean;
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onFullSwipeArmedChange: (armed: boolean) => void;
|
||||
readonly primaryAction: ThreadSwipePrimaryAction;
|
||||
readonly swipeableMethods: SwipeableMethods;
|
||||
readonly threadTitle: string;
|
||||
readonly primaryAction: ThreadSwipeAction;
|
||||
/** Null renders a single-action tray — no second button, no Delete. */
|
||||
readonly secondaryAction: ThreadSwipeSecondaryAction | null;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const fullSwipeIsPrimary = props.fullSwipeAction === "primary";
|
||||
const secondaryAction = props.secondaryAction;
|
||||
// Without a secondary action the primary is the only thing that can stretch
|
||||
// and commit on full swipe, whatever the caller asked for.
|
||||
const fullSwipeIsPrimary = props.fullSwipeAction === "primary" || secondaryAction === null;
|
||||
const actionsWidth = swipeActionsWidth(secondaryAction !== null);
|
||||
useAnimatedReaction(
|
||||
() => -props.translation.value >= props.fullSwipeThreshold,
|
||||
(armed, previous) => {
|
||||
@@ -470,14 +532,21 @@ export function ThreadSwipeActions(props: {
|
||||
backgroundColor: props.backgroundColor,
|
||||
flexDirection: "row",
|
||||
height: "100%",
|
||||
width: THREAD_SWIPE_ACTIONS_WIDTH,
|
||||
width: actionsWidth,
|
||||
}}
|
||||
>
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={props.primaryAction.accessibilityLabel}
|
||||
actionsWidth={actionsWidth}
|
||||
backgroundColor="#007aff"
|
||||
compact={props.compact}
|
||||
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
|
||||
// The lone button sits at the row edge, so it enters on the same
|
||||
// ramp the secondary would have used.
|
||||
entryRange={
|
||||
secondaryAction === null
|
||||
? [8, ACTION_ITEM_WIDTH * 0.72]
|
||||
: [ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]
|
||||
}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon={props.primaryAction.icon}
|
||||
label={props.primaryAction.label}
|
||||
@@ -485,21 +554,21 @@ export function ThreadSwipeActions(props: {
|
||||
stretchesOnFullSwipe={fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={`Delete ${props.threadTitle}`}
|
||||
backgroundColor="#ff2d55"
|
||||
compact={props.compact}
|
||||
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon="trash"
|
||||
label="Delete"
|
||||
onPress={() => {
|
||||
props.swipeableMethods.close();
|
||||
props.onDelete();
|
||||
}}
|
||||
stretchesOnFullSwipe={!fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
{secondaryAction === null ? null : (
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={secondaryAction.accessibilityLabel}
|
||||
actionsWidth={actionsWidth}
|
||||
backgroundColor={secondaryAction.backgroundColor}
|
||||
compact={props.compact}
|
||||
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon={secondaryAction.icon}
|
||||
label={secondaryAction.label}
|
||||
onPress={secondaryAction.onPress}
|
||||
stretchesOnFullSwipe={!fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useCallback, useRef } from "react";
|
||||
@@ -13,6 +13,8 @@ import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
|
||||
const SWIPE_SNOOZE_DURATION_MS = 60 * 60 * 1_000;
|
||||
|
||||
/** Version skew: never send settle/unsettle to a server that predates them
|
||||
(capability defaults false on decode for older servers). */
|
||||
function environmentSupportsSettlement(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
@@ -22,6 +24,13 @@ function environmentSupportsSettlement(environmentId: EnvironmentThreadShell["en
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadSnooze === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -192,9 +201,17 @@ export function useThreadListActions(): {
|
||||
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly snoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
|
||||
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
|
||||
// Same double-tap guard executeAction gives the other lifecycle actions:
|
||||
// without it a rapid second Wake/Snooze tap queues a duplicate command and,
|
||||
// on failure, stacks one alert per tap.
|
||||
const snoozeInFlightKeys = useRef(new Set<string>());
|
||||
|
||||
const archiveThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -206,6 +223,94 @@ export function useThreadListActions(): {
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
const snoozeThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (snoozeInFlightKeys.current.has(key)) return false;
|
||||
if (!environmentSupportsSnooze(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not snooze thread",
|
||||
"This environment's server does not support snoozing yet. Update the server to use Snooze.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
if (!canSnooze(thread, { now: new Date().toISOString() })) {
|
||||
// canSnooze refuses for two unrelated reasons; naming the wrong one
|
||||
// sends the user looking for a request that isn't there.
|
||||
Alert.alert(
|
||||
"Could not snooze thread",
|
||||
thread.hasPendingApprovals || thread.hasPendingUserInput
|
||||
? "This thread is waiting on you. Respond to the pending request before snoozing it."
|
||||
: "This thread is still starting a turn. Try again once it's running.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
snoozeInFlightKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
const result = await snoozeMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: {
|
||||
threadId: thread.id,
|
||||
snoozedUntil: new Date(Date.now() + SWIPE_SNOOZE_DURATION_MS).toISOString(),
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not snooze thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be snoozed.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
snoozeInFlightKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[snoozeMutation],
|
||||
);
|
||||
// Waking has no client-side precondition (canSnooze guards the way IN, not
|
||||
// the way OUT) — a thread the user can see on the shelf can always wake.
|
||||
const unsnoozeThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (snoozeInFlightKeys.current.has(key)) return false;
|
||||
if (!environmentSupportsSnooze(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not wake thread",
|
||||
"This environment's server does not support snoozing yet. Update the server to wake this thread.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
snoozeInFlightKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
const result = await unsnoozeMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, reason: "user" },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not wake thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be woken.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
snoozeInFlightKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[unsnoozeMutation],
|
||||
);
|
||||
const unsettleThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
|
||||
[executeAction],
|
||||
@@ -213,7 +318,14 @@ export function useThreadListActions(): {
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
return { archiveThread, confirmDeleteThread, settleThread, unsettleThread };
|
||||
return {
|
||||
archiveThread,
|
||||
confirmDeleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
};
|
||||
}
|
||||
|
||||
export function useArchivedThreadListActions(
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
|
||||
@@ -46,7 +46,6 @@ import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { runtime } from "../../lib/runtime";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { SettingsRow } from "./components/SettingsRow";
|
||||
import { SettingsSection } from "./components/SettingsSection";
|
||||
@@ -556,8 +555,11 @@ function GeneralSettingsSection() {
|
||||
* the counterpart of web's Settings → Beta backed by mobile preferences.
|
||||
*/
|
||||
function BetaSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const threadListV2Enabled = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.threadListV2Enabled === true
|
||||
: false;
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
import { LegendList } from "@legendapp/list/react-native";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
|
||||
@@ -21,13 +22,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 { mobilePreferencesAtom } from "../../state/preferences";
|
||||
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 +63,40 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "./thread-list-items";
|
||||
import { ThreadListV2PendingRow, ThreadListV2Row } from "./thread-list-v2-items";
|
||||
import { ThreadListV2Row, ThreadListV2SnoozedShelfHeader } from "./thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
snoozeWakeLabel,
|
||||
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;
|
||||
/** Precomputed against the minute tick so the row comparator can see
|
||||
the countdown change; undefined for non-snoozed rows. */
|
||||
readonly snoozeWakeLabelText: string | undefined;
|
||||
}
|
||||
| {
|
||||
readonly type: "v2-snoozed-shelf-header";
|
||||
readonly key: string;
|
||||
readonly count: number;
|
||||
readonly expanded: boolean;
|
||||
}
|
||||
| { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
|
||||
|
||||
/**
|
||||
@@ -189,9 +208,18 @@ function ThreadNavigationSidebarPane(
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const headerIsOverContentRef = useRef(false);
|
||||
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const {
|
||||
archiveThread,
|
||||
confirmDeleteThread,
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled =
|
||||
AsyncResult.isSuccess(preferencesResult) &&
|
||||
preferencesResult.value.threadListV2Enabled === true;
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -220,19 +248,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(
|
||||
() =>
|
||||
@@ -393,6 +415,9 @@ function ThreadNavigationSidebarPane(
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
// Collapsed by default, like web: the shelf is a shelf, not a second inbox.
|
||||
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
|
||||
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
|
||||
// now ticks per minute so the inactivity auto-settle boundary is actually
|
||||
// crossed while the pane stays open; without a clock dependency the
|
||||
// partition memoizes a frozen "now".
|
||||
@@ -433,7 +458,13 @@ function ThreadNavigationSidebarPane(
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
return {
|
||||
items: [],
|
||||
hiddenSettledCount: 0,
|
||||
snoozedCount: 0,
|
||||
snoozedShelfHeaderIndex: null,
|
||||
nextSnoozeWakeAt: null,
|
||||
};
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
@@ -445,11 +476,17 @@ function ThreadNavigationSidebarPane(
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
snoozedShelfExpanded,
|
||||
// Split view keeps a thread open beside the list: a snoozed one must
|
||||
// keep its row (and its Wake action) even while the shelf is closed.
|
||||
selectedThreadKey: props.selectedThreadKey ?? null,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
props.selectedThreadKey,
|
||||
options.selectedEnvironmentId,
|
||||
props.searchQuery,
|
||||
settledVisibleCount,
|
||||
@@ -475,11 +512,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 +529,34 @@ 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,
|
||||
}));
|
||||
const snoozeLabelNow = `${nowMinute}:00.000Z`;
|
||||
const threadRows: SidebarListItem[] = threadListV2Layout.items.map((item) => ({
|
||||
type: "v2-thread" as const,
|
||||
key: scopedThreadKey(item.thread.environmentId, item.thread.id),
|
||||
item,
|
||||
snoozeWakeLabelText:
|
||||
item.snoozed && item.thread.snoozedUntil != null
|
||||
? snoozeWakeLabel(item.thread.snoozedUntil, { now: snoozeLabelNow })
|
||||
: undefined,
|
||||
}));
|
||||
// The shelf header is a row of its own: collapsed, it IS the shelf, so
|
||||
// it has no thread row to hang off. splice() handles the all-snoozed
|
||||
// case (index lands at the end) without a separate branch.
|
||||
if (threadListV2Layout.snoozedShelfHeaderIndex !== null) {
|
||||
threadRows.splice(threadListV2Layout.snoozedShelfHeaderIndex, 0, {
|
||||
type: "v2-snoozed-shelf-header",
|
||||
key: "v2-snoozed-shelf-header",
|
||||
count: threadListV2Layout.snoozedCount,
|
||||
expanded: snoozedShelfExpanded,
|
||||
});
|
||||
}
|
||||
items.push(...threadRows);
|
||||
if (threadListV2Layout.hiddenSettledCount > 0) {
|
||||
items.push({
|
||||
type: "v2-show-more",
|
||||
@@ -506,10 +567,12 @@ function ThreadNavigationSidebarPane(
|
||||
return items;
|
||||
}, [
|
||||
listLayout.items,
|
||||
nowMinute,
|
||||
options.selectedEnvironmentId,
|
||||
pendingTasks,
|
||||
props.searchQuery,
|
||||
selectedProjectRefs,
|
||||
snoozedShelfExpanded,
|
||||
threadListV2Enabled,
|
||||
threadListV2Layout,
|
||||
]);
|
||||
@@ -683,26 +746,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 => {
|
||||
@@ -711,25 +761,35 @@ function ThreadNavigationSidebarPane(
|
||||
previous.key === item.key &&
|
||||
previous.item.thread === item.item.thread &&
|
||||
previous.item.variant === item.item.variant &&
|
||||
previous.item.showSettledDivider === item.item.showSettledDivider
|
||||
previous.item.showSettledDivider === item.item.showSettledDivider &&
|
||||
// A timer wake is derived from the clock, not from new data: the
|
||||
// shell reference and variant can both be unchanged while the row
|
||||
// stops being snoozed. Without this the woken row keeps its blue
|
||||
// countdown and Wake action.
|
||||
previous.item.snoozed === item.item.snoozed &&
|
||||
// Same reason for the countdown text: it changes on the minute
|
||||
// tick while every other field holds still.
|
||||
previous.snoozeWakeLabelText === item.snoozeWakeLabelText
|
||||
);
|
||||
}
|
||||
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-snoozed-shelf-header" && item.type === "v2-snoozed-shelf-header") {
|
||||
return previous.count === item.count && previous.expanded === item.expanded;
|
||||
}
|
||||
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" ||
|
||||
previous.type === "v2-snoozed-shelf-header" ||
|
||||
item.type === "v2-thread" ||
|
||||
item.type === "v2-show-more" ||
|
||||
item.type === "v2-pending"
|
||||
item.type === "v2-pending-task" ||
|
||||
item.type === "v2-snoozed-shelf-header"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -757,29 +817,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);
|
||||
@@ -788,6 +839,8 @@ function ThreadNavigationSidebarPane(
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
snoozed={item.item.snoozed}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
projectTitle={projectTitleByProjectKey.get(scopeKey)}
|
||||
providerDriver={
|
||||
@@ -814,6 +867,9 @@ function ThreadNavigationSidebarPane(
|
||||
onArchiveThread={archiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={settleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
|
||||
@@ -823,6 +879,15 @@ function ThreadNavigationSidebarPane(
|
||||
/>
|
||||
);
|
||||
}
|
||||
case "v2-snoozed-shelf-header":
|
||||
return (
|
||||
<ThreadListV2SnoozedShelfHeader
|
||||
count={item.count}
|
||||
expanded={item.expanded}
|
||||
onToggle={toggleSnoozedShelf}
|
||||
pane="sidebar"
|
||||
/>
|
||||
);
|
||||
case "v2-show-more":
|
||||
return (
|
||||
<Pressable
|
||||
@@ -929,7 +994,11 @@ function ThreadNavigationSidebarPane(
|
||||
settlementEnvironmentIds,
|
||||
showMoreSettled,
|
||||
sidebarScrollGesture,
|
||||
snoozeEnvironmentIds,
|
||||
snoozeThread,
|
||||
toggleSnoozedShelf,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
@@ -976,28 +1045,17 @@ function ThreadNavigationSidebarPane(
|
||||
}),
|
||||
[filterIcon, filterMenu, props.onOpenSettings],
|
||||
);
|
||||
// "No threads yet" over an inbox that is merely all-snoozed reads as
|
||||
// data loss; name the snoozed threads instead.
|
||||
const snoozedCount = threadListV2Layout.snoozedCount;
|
||||
// Snoozed threads need no case here: the shelf header renders as a list
|
||||
// row whenever anything is snoozed, so an all-snoozed pane is never empty.
|
||||
const listEmpty = (
|
||||
<Text className="px-2 py-4 text-sm text-foreground-muted">
|
||||
{catalogState.isLoadingConnections
|
||||
? "Loading threads…"
|
||||
: props.searchQuery.trim().length > 0
|
||||
? snoozedCount > 0
|
||||
? // Snoozed matches passed this same search filter — "No
|
||||
// matching threads" would misreport them as nonexistent.
|
||||
snoozedCount === 1
|
||||
? "1 matching thread snoozed"
|
||||
: "All matching threads snoozed"
|
||||
: "No matching threads"
|
||||
: snoozedCount > 0
|
||||
? snoozedCount === 1
|
||||
? "1 thread snoozed"
|
||||
: `${snoozedCount} threads snoozed`
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
? "No matching threads"
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
</Text>
|
||||
);
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -2,11 +2,13 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { canSnooze } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { memo, useCallback, useEffect, useMemo, type ComponentProps } from "react";
|
||||
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
|
||||
import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react";
|
||||
import { Platform, Pressable, useColorScheme, useWindowDimensions, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
@@ -14,10 +16,14 @@ 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";
|
||||
import {
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
resolveThreadListV2Status,
|
||||
resolveThreadListV2SwipeActions,
|
||||
type ThreadListV2Status,
|
||||
} from "./threadListV2";
|
||||
|
||||
/**
|
||||
* Thread List v2 renders one flat native list: rich edge-to-edge rows for
|
||||
@@ -60,6 +66,12 @@ const SLIM_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
// Snoozed rows wake instead of settling — the thread is parked, not done.
|
||||
const SNOOZED_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "unsnooze", title: "Wake thread", image: "clock" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
// Pre-settlement servers: no lifecycle items, archive fills the gap.
|
||||
const LEGACY_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "archive", title: "Archive", image: "archivebox" },
|
||||
@@ -69,9 +81,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,124 +92,55 @@ 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 } },
|
||||
];
|
||||
// SymbolView takes a literal tint, so the shelf chevron can't ride the
|
||||
// blue-600/blue-400 Tailwind pair the label uses. Same values, resolved here.
|
||||
const SNOOZE_ACCENT_LIGHT = "#2563eb";
|
||||
const SNOOZE_ACCENT_DARK = "#60a5fa";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Snoozed shelf header: tappable, showing the count while collapsed so the
|
||||
* shelf's whole footprint is one line. Mirrors web's snoozed shelf toggle —
|
||||
* parked work stays reachable without competing with the inbox.
|
||||
*/
|
||||
export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props: {
|
||||
readonly pendingTask: PendingNewTask;
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly projectTitle?: string;
|
||||
readonly environmentLabel: string | null;
|
||||
export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedShelfHeader(props: {
|
||||
readonly count: number;
|
||||
readonly expanded: boolean;
|
||||
readonly onToggle: () => void;
|
||||
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}
|
||||
</>
|
||||
);
|
||||
|
||||
const colorScheme = useColorScheme();
|
||||
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>
|
||||
</>
|
||||
<Pressable
|
||||
accessibilityHint={
|
||||
props.expanded ? "Collapses the snoozed threads." : "Expands the snoozed threads."
|
||||
}
|
||||
accessibilityLabel={props.count === 1 ? "1 snoozed thread" : `${props.count} snoozed threads`}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
className={cn(
|
||||
"mb-1.5 mt-4 flex-row items-center gap-2.5",
|
||||
props.pane === "sidebar" ? "px-3" : "px-5",
|
||||
)}
|
||||
onPress={props.onToggle}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-blue-600 dark:text-blue-400">
|
||||
{props.expanded ? "Snoozed" : `Snoozed (${props.count})`}
|
||||
</Text>
|
||||
<View className="h-px flex-1 bg-blue-500/20 dark:bg-blue-400/15" />
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={10}
|
||||
tintColor={colorScheme === "dark" ? SNOOZE_ACCENT_DARK : SNOOZE_ACCENT_LIGHT}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -207,6 +148,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
readonly showSettledDivider: boolean;
|
||||
/** Snoozed-shelf row: shows its wake time and offers Wake, not Settle. */
|
||||
readonly snoozed?: boolean;
|
||||
/** Pre-formatted "wakes in" text for snoozed rows. Computed by the parent
|
||||
against its minute tick rather than here: this row is memoized, so a
|
||||
clock read inside it would freeze at first render and the countdown
|
||||
would never move. Mirrors web's snoozeWakeLabelText prop. */
|
||||
readonly snoozeWakeLabelText?: string;
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly projectTitle?: string;
|
||||
readonly providerDriver: string | null;
|
||||
@@ -229,11 +177,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSnoozeThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** False on environments whose server predates thread.settle/unsettle:
|
||||
swipe + menu fall back to Archive instead of failing on use. */
|
||||
readonly settlementSupported: boolean;
|
||||
/** False on servers that predate thread.snooze/unsnooze. */
|
||||
readonly snoozeSupported: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
/** Reports this row's live PR state up so the partition can auto-settle
|
||||
@@ -254,10 +206,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onSelectThread,
|
||||
onDeleteThread,
|
||||
onSettleThread,
|
||||
onSnoozeThread,
|
||||
onUnsnoozeThread,
|
||||
onUnsettleThread,
|
||||
onArchiveThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
const snoozedRow = props.snoozed === true;
|
||||
|
||||
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
|
||||
const prState = pr?.state ?? null;
|
||||
@@ -279,27 +234,53 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
const handleSnooze = useCallback(() => onSnoozeThread(thread), [onSnoozeThread, thread]);
|
||||
const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
|
||||
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "settle") handleSettle();
|
||||
if (nativeEvent.event === "unsettle") handleUnsettle();
|
||||
if (nativeEvent.event === "unsnooze") handleUnsnooze();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
},
|
||||
[handleArchive, handleDelete, handleSettle, handleUnsettle],
|
||||
[handleArchive, handleDelete, handleSettle, handleUnsettle, handleUnsnooze],
|
||||
);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Every settled
|
||||
// row can un-settle — explicit settles clear the override, auto-settled
|
||||
// rows get pinned active until real activity clears the pin.
|
||||
const canUnsettle = variant === "slim";
|
||||
// Snooze eligibility is time-gated (a user message no turn has adopted yet
|
||||
// blocks it for the grace window), so the row re-renders itself the moment
|
||||
// that window lapses — otherwise Snooze would stay hidden until unrelated
|
||||
// props changed.
|
||||
const [snoozeGateTick, bumpSnoozeGateTick] = useState(0);
|
||||
const snoozeGateExpiryMs = props.snoozeSupported
|
||||
? resolveThreadListV2SnoozeGateExpiryMs(thread, { now: new Date().toISOString() })
|
||||
: null;
|
||||
useEffect(() => {
|
||||
if (snoozeGateExpiryMs === null) return;
|
||||
const delayMs = Math.min(Math.max(0, snoozeGateExpiryMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeGateTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeGateTick re-arms after a clamped fire: for a far-future expiry the
|
||||
// boundary is unchanged, so without it the timer chain would stop.
|
||||
}, [snoozeGateExpiryMs, snoozeGateTick]);
|
||||
const swipeActions = resolveThreadListV2SwipeActions({
|
||||
variant,
|
||||
settlementSupported: props.settlementSupported,
|
||||
snoozeSupported: props.snoozeSupported,
|
||||
snoozable: canSnooze(thread, { now: new Date().toISOString() }),
|
||||
snoozed: snoozedRow,
|
||||
});
|
||||
const primaryAction = useMemo(() => {
|
||||
// Pre-settlement server: archive is the swipe action, as in v1. (Slim
|
||||
// rows cannot occur here — unsupported environments never classify as
|
||||
// settled.)
|
||||
if (!props.settlementSupported) {
|
||||
if (swipeActions.primary === "archive") {
|
||||
return {
|
||||
accessibilityLabel: `Archive ${thread.title}`,
|
||||
icon: "archivebox" as const,
|
||||
@@ -307,7 +288,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onPress: handleArchive,
|
||||
};
|
||||
}
|
||||
return canUnsettle
|
||||
if (swipeActions.primary === "unsnooze") {
|
||||
return {
|
||||
accessibilityLabel: `Wake ${thread.title} now`,
|
||||
icon: "clock" as const,
|
||||
label: "Wake",
|
||||
onPress: handleUnsnooze,
|
||||
};
|
||||
}
|
||||
return swipeActions.primary === "unsettle"
|
||||
? {
|
||||
accessibilityLabel: `Un-settle ${thread.title}`,
|
||||
icon: "arrow.uturn.backward" as const,
|
||||
@@ -321,13 +310,29 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onPress: handleSettle,
|
||||
};
|
||||
}, [
|
||||
canUnsettle,
|
||||
handleArchive,
|
||||
handleSettle,
|
||||
handleUnsettle,
|
||||
props.settlementSupported,
|
||||
handleUnsnooze,
|
||||
swipeActions.primary,
|
||||
thread.title,
|
||||
]);
|
||||
const secondaryAction = useMemo(
|
||||
() =>
|
||||
swipeActions.secondary === "snooze"
|
||||
? {
|
||||
accessibilityLabel: `Snooze ${thread.title} for 1 hour`,
|
||||
icon: "clock" as const,
|
||||
label: "Snooze 1h",
|
||||
onPress: handleSnooze,
|
||||
}
|
||||
: null,
|
||||
[handleSnooze, swipeActions.secondary, thread.title],
|
||||
);
|
||||
const swipeAccessibilityHint =
|
||||
secondaryAction === null
|
||||
? `Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`
|
||||
: `Opens the thread. Swipe left for ${primaryAction.label.toLowerCase()} and snooze actions.`;
|
||||
|
||||
// The sidebar pane fills selected rows with the accent color (matching the
|
||||
// v1 sidebar), so every piece of row text needs a white-on-accent variant.
|
||||
@@ -440,7 +445,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const rowContent = (close: () => void) =>
|
||||
variant === "card" ? (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityHint={swipeAccessibilityHint}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
@@ -478,8 +483,18 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
</Pressable>
|
||||
) : (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityHint={swipeAccessibilityHint}
|
||||
// The wake countdown is the row's whole story visually; a screen
|
||||
// reader must hear it too, not just the Wake hint.
|
||||
accessibilityLabel={
|
||||
snoozedRow && props.snoozeWakeLabelText !== undefined
|
||||
? // The label can read "now" for the sliver between the wake
|
||||
// passing and the next re-partition removing the row.
|
||||
props.snoozeWakeLabelText === "now"
|
||||
? `${thread.title}, snoozed, wakes now`
|
||||
: `${thread.title}, snoozed, wakes in ${props.snoozeWakeLabelText}`
|
||||
: thread.title
|
||||
}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
className={sidebarPane ? undefined : "bg-screen"}
|
||||
@@ -526,14 +541,22 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
>
|
||||
{thread.title}
|
||||
</Text>
|
||||
{/* Snoozed rows show when they come BACK, not when they were last
|
||||
touched — the return ticket is the row's whole story. */}
|
||||
<Text
|
||||
className={cn(
|
||||
"text-sm tabular-nums",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
|
||||
selected
|
||||
? "text-user-bubble-foreground-muted"
|
||||
: snoozedRow
|
||||
? "text-blue-600 dark:text-blue-400"
|
||||
: "text-foreground-tertiary",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
|
||||
{snoozedRow && props.snoozeWakeLabelText !== undefined
|
||||
? props.snoozeWakeLabelText
|
||||
: relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
|
||||
</Text>
|
||||
</View>
|
||||
</Pressable>
|
||||
@@ -541,9 +564,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"}
|
||||
@@ -552,13 +573,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
}
|
||||
enableTrackpadSwipe
|
||||
// Full swipe commits the advertised lifecycle action (Settle /
|
||||
// Un-settle), never the destructive delete.
|
||||
// Un-settle), never the secondary Snooze action.
|
||||
fullSwipeAction="primary"
|
||||
fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
|
||||
onDelete={handleDelete}
|
||||
onSwipeableClose={props.onSwipeableClose}
|
||||
onSwipeableWillOpen={props.onSwipeableWillOpen}
|
||||
primaryAction={primaryAction}
|
||||
secondaryAction={secondaryAction}
|
||||
resetKey={`${thread.environmentId}:${thread.id}`}
|
||||
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
|
||||
threadTitle={thread.title}
|
||||
@@ -566,11 +588,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
{(close) => (
|
||||
<ControlPillMenu
|
||||
actions={
|
||||
!props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
: CARD_MENU_ACTIONS
|
||||
snoozedRow
|
||||
? SNOOZED_MENU_ACTIONS
|
||||
: !props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
: CARD_MENU_ACTIONS
|
||||
}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
|
||||
@@ -1,20 +1,11 @@
|
||||
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,
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
resolveThreadListV2SwipeActions,
|
||||
resolveThreadListV2Status,
|
||||
sortThreadsForListV2,
|
||||
} from "./threadListV2";
|
||||
@@ -49,25 +40,6 @@ function makeThread(
|
||||
|
||||
const NOW = "2026-06-02T00:00:00.000Z";
|
||||
|
||||
describe("resolveThreadListV2Enabled", () => {
|
||||
it("defaults on when the device has never chosen", () => {
|
||||
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("honors an explicit device opt-out", () => {
|
||||
expect(resolveThreadListV2Enabled({ preference: false, preferencesLoaded: true })).toBe(false);
|
||||
expect(resolveThreadListV2Enabled({ preference: true, preferencesLoaded: true })).toBe(true);
|
||||
});
|
||||
|
||||
it("holds the default while preferences are still loading so the list does not remount", () => {
|
||||
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: false })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2Status", () => {
|
||||
it("prioritizes approval over a running session", () => {
|
||||
const thread = makeThread({
|
||||
@@ -95,6 +67,102 @@ describe("resolveThreadListV2Status", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2SwipeActions", () => {
|
||||
it("offers settle and snooze for an active snoozable thread", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "settle", secondary: "snooze" });
|
||||
});
|
||||
|
||||
it("offers un-settle and snooze for settled history", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "slim",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "unsettle", secondary: "snooze" });
|
||||
});
|
||||
|
||||
it("omits snooze when the server or thread does not allow it", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: false,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "settle", secondary: null });
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: false,
|
||||
}),
|
||||
).toEqual({ primary: "settle", secondary: null });
|
||||
});
|
||||
|
||||
it("falls back to archive only for a pre-lifecycle server", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "card",
|
||||
settlementSupported: false,
|
||||
snoozeSupported: false,
|
||||
snoozable: true,
|
||||
}),
|
||||
).toEqual({ primary: "archive", secondary: null });
|
||||
});
|
||||
|
||||
it("offers wake and no snooze on a snoozed row", () => {
|
||||
expect(
|
||||
resolveThreadListV2SwipeActions({
|
||||
variant: "slim",
|
||||
settlementSupported: true,
|
||||
snoozeSupported: true,
|
||||
snoozable: true,
|
||||
snoozed: true,
|
||||
}),
|
||||
).toEqual({ primary: "unsnooze", secondary: null });
|
||||
});
|
||||
});
|
||||
|
||||
// snoozeWakeLabel itself is covered in client-runtime, where it lives.
|
||||
|
||||
describe("resolveThreadListV2SnoozeGateExpiryMs", () => {
|
||||
it("reports when an unadopted turn's grace window lapses", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
latestUserMessageAt: "2026-06-02T00:00:30.000Z",
|
||||
});
|
||||
expect(resolveThreadListV2SnoozeGateExpiryMs(thread, { now: "2026-06-02T00:01:00.000Z" })).toBe(
|
||||
Date.parse("2026-06-02T00:02:30.000Z"),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null once the thread is already snoozable", () => {
|
||||
const thread = makeThread({ id: ThreadId.make("t"), title: "t" });
|
||||
expect(resolveThreadListV2SnoozeGateExpiryMs(thread, { now: NOW })).toBe(null);
|
||||
});
|
||||
|
||||
it("returns null for threads blocked on the user — only new data clears those", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
hasPendingApprovals: true,
|
||||
latestUserMessageAt: NOW,
|
||||
});
|
||||
expect(resolveThreadListV2SnoozeGateExpiryMs(thread, { now: NOW })).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortThreadsForListV2", () => {
|
||||
it("orders by creation time, newest first, ignoring activity", () => {
|
||||
const sorted = sortThreadsForListV2([
|
||||
@@ -166,6 +234,95 @@ describe("buildThreadListV2Items", () => {
|
||||
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
|
||||
});
|
||||
|
||||
it("builds snoozed rows between active and settled when the shelf is expanded", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Settled",
|
||||
settledOverride: "settled",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("later"),
|
||||
title: "Wakes later",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("sooner"),
|
||||
title: "Wakes sooner",
|
||||
snoozedUntil: "2026-06-02T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
snoozedShelfExpanded: true,
|
||||
});
|
||||
|
||||
// Soonest wake first, and the shelf sits between inbox and settled.
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual([
|
||||
"active",
|
||||
"sooner",
|
||||
"later",
|
||||
"settled",
|
||||
]);
|
||||
expect(layout.items.map((item) => item.snoozed)).toEqual([false, true, true, false]);
|
||||
expect(layout.snoozedShelfHeaderIndex).toBe(1);
|
||||
expect(layout.snoozedCount).toBe(2);
|
||||
});
|
||||
|
||||
it("collapses to a header-only shelf, reporting the index past the last row", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("snoozed"),
|
||||
title: "Snoozed",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.items).toEqual([]);
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
// Header still renders — the count IS the shelf while collapsed.
|
||||
expect(layout.snoozedShelfHeaderIndex).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps the open thread on a collapsed shelf so it never vanishes", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("open"),
|
||||
title: "Open",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("other"),
|
||||
title: "Other",
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
selectedThreadKey: `${environmentId}:open`,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual(["open"]);
|
||||
expect(layout.items[0]?.snoozed).toBe(true);
|
||||
// Both still count: the shelf header reports everything parked.
|
||||
expect(layout.snoozedCount).toBe(2);
|
||||
});
|
||||
|
||||
it("keeps snoozed threads visible on environments without the snooze capability", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
@@ -350,88 +507,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`,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,16 @@
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
effectiveSettled,
|
||||
effectiveSnoozed,
|
||||
hasQueuedTurnStart,
|
||||
QUEUED_TURN_START_GRACE_MS,
|
||||
} from "@t3tools/client-runtime/state/thread-settled";
|
||||
|
||||
// Wake labels live with the rest of the snooze model so web and mobile can
|
||||
// never drift; re-exported here because this module is the list's one stop.
|
||||
export { snoozeWakeLabel } from "@t3tools/client-runtime/state/thread-settled";
|
||||
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).
|
||||
@@ -13,6 +20,59 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
* unlabeled resting state.
|
||||
*/
|
||||
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
|
||||
export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
|
||||
|
||||
export function resolveThreadListV2SwipeActions(input: {
|
||||
readonly variant: "card" | "slim";
|
||||
readonly settlementSupported: boolean;
|
||||
readonly snoozeSupported: boolean;
|
||||
readonly snoozable: boolean;
|
||||
/** Row is on the snoozed shelf. */
|
||||
readonly snoozed?: boolean;
|
||||
}): {
|
||||
readonly primary: Exclude<ThreadListV2SwipeAction, "snooze">;
|
||||
readonly secondary: "snooze" | null;
|
||||
} {
|
||||
// A snoozed row's one lifecycle move is waking: settling parked work is
|
||||
// meaningless, and re-snoozing an already-snoozed thread is a no-op.
|
||||
if (input.snoozed === true) {
|
||||
return { primary: "unsnooze", secondary: null };
|
||||
}
|
||||
const primary = input.settlementSupported
|
||||
? input.variant === "slim"
|
||||
? "unsettle"
|
||||
: "settle"
|
||||
: "archive";
|
||||
return {
|
||||
primary,
|
||||
secondary: input.snoozeSupported && input.snoozable ? "snooze" : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* When a thread's snooze eligibility can flip on its own, as epoch ms — the
|
||||
* moment the queued-turn-start grace window expires and `canSnooze` starts
|
||||
* returning true. Null when nothing time-based gates it: either the thread is
|
||||
* already snoozable, or it is blocked on the user and only fresh server data
|
||||
* can clear that. Rows arm a one-shot timer on this so an unadopted turn's
|
||||
* Snooze action appears when the grace period lapses instead of waiting for
|
||||
* an unrelated re-render.
|
||||
*/
|
||||
export function resolveThreadListV2SnoozeGateExpiryMs(
|
||||
thread: Pick<
|
||||
EnvironmentThreadShell,
|
||||
"hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
|
||||
>,
|
||||
options: { readonly now: string },
|
||||
): number | null {
|
||||
// Blocked-on-user threads are not on a clock — leave them to data updates.
|
||||
if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null;
|
||||
if (!hasQueuedTurnStart(thread, options)) return null;
|
||||
// hasQueuedTurnStart already rejected a null/unparseable message time.
|
||||
const messageAtMs = Date.parse(thread.latestUserMessageAt ?? "");
|
||||
if (Number.isNaN(messageAtMs)) return null;
|
||||
return messageAtMs + QUEUED_TURN_START_GRACE_MS;
|
||||
}
|
||||
|
||||
// Settled-tail paging: recent history is the common lookup; the deep tail
|
||||
// stays behind an explicit Show more. Shared by the compact Home list and
|
||||
@@ -20,26 +80,6 @@ export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "
|
||||
export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
|
||||
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
|
||||
|
||||
/**
|
||||
* Thread List v2 is on by default on every app variant; the Settings → Beta
|
||||
* toggle is an opt-out. Preferences persist as sparse patches, so `undefined`
|
||||
* genuinely means "never chosen".
|
||||
*
|
||||
* `preferencesLoaded` guards the startup window: preferences load
|
||||
* asynchronously, and rendering one list before the stored choice arrives would
|
||||
* remount the whole thing a tick later. While loading, hold the default — that
|
||||
* is where every device without an explicit opt-out lands anyway.
|
||||
*/
|
||||
export function resolveThreadListV2Enabled(input: {
|
||||
readonly preference: boolean | undefined;
|
||||
readonly preferencesLoaded: boolean;
|
||||
}): boolean {
|
||||
if (!input.preferencesLoaded) {
|
||||
return true;
|
||||
}
|
||||
return input.preference ?? true;
|
||||
}
|
||||
|
||||
export function resolveThreadListV2Status(
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
|
||||
): ThreadListV2Status {
|
||||
@@ -99,6 +139,9 @@ export interface ThreadListV2Item {
|
||||
readonly variant: "card" | "slim";
|
||||
/** First settled row after the card block draws the SETTLED divider. */
|
||||
readonly showSettledDivider: boolean;
|
||||
/** Snoozed-shelf row: renders its wake time instead of its last-activity
|
||||
time, and offers Wake instead of Settle. */
|
||||
readonly snoozed: boolean;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
@@ -106,69 +149,21 @@ export interface ThreadListV2Layout {
|
||||
readonly items: ThreadListV2Item[];
|
||||
/** Settled threads beyond the render limit (behind "Show more"). */
|
||||
readonly hiddenSettledCount: number;
|
||||
/** Snoozed threads hidden from the list (visibility parity with web's
|
||||
collapsed Snoozed shelf; mobile has no shelf UI yet). */
|
||||
/** Snoozed threads matching the current filters. Drives the shelf header,
|
||||
which shows the count while collapsed; rows only build when the shelf
|
||||
is expanded (or for the open thread). */
|
||||
readonly snoozedCount: number;
|
||||
/** Soonest wake time among hidden snoozed threads, or null. Callers arm
|
||||
a timeout at this boundary so the list re-partitions the moment a
|
||||
/** Index in `items` where the snoozed shelf header belongs, or null when
|
||||
nothing is snoozed. Callers splice their own header element in here:
|
||||
the header must render even while the shelf is collapsed (its count is
|
||||
the whole shelf then), so it can't hang off a row flag. */
|
||||
readonly snoozedShelfHeaderIndex: number | null;
|
||||
/** Soonest wake time among snoozed threads, or null. Callers arm a
|
||||
timeout at this boundary so the list re-partitions the moment a
|
||||
snooze expires instead of on the next minute tick. */
|
||||
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`
|
||||
@@ -202,6 +197,13 @@ export function buildThreadListV2Items(input: {
|
||||
second-precise, so classifying with the floored minute would hold a
|
||||
woken thread hidden for up to a minute. Defaults to `now`. */
|
||||
readonly snoozeNow?: string;
|
||||
/** Expands the snoozed shelf into rows. Collapsed (the default, matching
|
||||
web) the shelf is just its header + count. */
|
||||
readonly snoozedShelfExpanded?: boolean;
|
||||
/** Scoped key ("environmentId:threadId") of the open thread. A snoozed
|
||||
thread reached by route keeps its row even while the shelf is
|
||||
collapsed — the open thread must never vanish behind a shelf. */
|
||||
readonly selectedThreadKey?: string | null;
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const snoozeNow = input.snoozeNow ?? now;
|
||||
@@ -213,7 +215,7 @@ export function buildThreadListV2Items(input: {
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
let snoozedCount = 0;
|
||||
const snoozed: EnvironmentThreadShell[] = [];
|
||||
let nextSnoozeWakeAt: string | null = null;
|
||||
for (const thread of input.threads) {
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
@@ -231,7 +233,7 @@ export function buildThreadListV2Items(input: {
|
||||
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
|
||||
// work). Snooze outranks settled classification, same as web.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozedCount += 1;
|
||||
snoozed.push(thread);
|
||||
if (
|
||||
thread.snoozedUntil != null &&
|
||||
(nextSnoozeWakeAt === null ||
|
||||
@@ -252,6 +254,21 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
|
||||
const orderedActive = sortThreadsForListV2(active);
|
||||
// Soonest wake first: the shelf reads as a queue of what comes back next.
|
||||
const orderedSnoozed = [...snoozed].sort(
|
||||
(left, right) =>
|
||||
parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
|
||||
);
|
||||
const selectedThreadKey = input.selectedThreadKey ?? null;
|
||||
const visibleSnoozed =
|
||||
input.snoozedShelfExpanded === true
|
||||
? orderedSnoozed
|
||||
: // Collapsed: only the open thread survives, so a snoozed thread
|
||||
// opened by deep link (or snoozed from another device while open)
|
||||
// keeps its row and its Wake affordance.
|
||||
orderedSnoozed.filter(
|
||||
(thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
|
||||
);
|
||||
const orderedSettled = [...settled].sort(
|
||||
(left, right) =>
|
||||
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
|
||||
@@ -263,13 +280,32 @@ export function buildThreadListV2Items(input: {
|
||||
|
||||
const items: ThreadListV2Item[] = [];
|
||||
for (const thread of orderedActive) {
|
||||
items.push({ thread, variant: "card", showSettledDivider: false, isLast: false });
|
||||
items.push({
|
||||
thread,
|
||||
variant: "card",
|
||||
showSettledDivider: false,
|
||||
snoozed: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
// Snoozed shelf sits between the inbox and Settled — out of the way,
|
||||
// never gone. Slim like settled rows: parked work, not inbox work.
|
||||
const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
|
||||
for (const thread of visibleSnoozed) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "slim",
|
||||
showSettledDivider: false,
|
||||
snoozed: true,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
for (const [index, thread] of visibleSettled.entries()) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "slim",
|
||||
showSettledDivider: index === 0,
|
||||
snoozed: false,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
@@ -280,7 +316,8 @@ export function buildThreadListV2Items(input: {
|
||||
return {
|
||||
items,
|
||||
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
|
||||
snoozedCount,
|
||||
snoozedCount: orderedSnoozed.length,
|
||||
snoozedShelfHeaderIndex,
|
||||
nextSnoozeWakeAt,
|
||||
};
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { resolveThreadListV2Enabled } from "./threadListV2";
|
||||
|
||||
/**
|
||||
* Resolved Thread List v2 state: the device-local preference if the user has
|
||||
* set one, otherwise the default (on). Every consumer must read through this
|
||||
* rather than the raw preference, which is undefined until explicitly chosen.
|
||||
*/
|
||||
export function useThreadListV2Enabled(): boolean {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const loaded = AsyncResult.isSuccess(preferencesResult);
|
||||
return resolveThreadListV2Enabled({
|
||||
preference: loaded ? preferencesResult.value.threadListV2Enabled : undefined,
|
||||
preferencesLoaded: loaded,
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -25,9 +25,8 @@ export interface Preferences {
|
||||
readonly projectGroupingEnabled?: boolean;
|
||||
/**
|
||||
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
|
||||
* client-settings sync, so the flat v2 thread list is opted out of per
|
||||
* device. Undefined means the user has never chosen, which resolves to on —
|
||||
* see `resolveThreadListV2Enabled`.
|
||||
* client-settings sync, so the flat v2 thread list is opted into per
|
||||
* device.
|
||||
*/
|
||||
readonly threadListV2Enabled?: boolean;
|
||||
}
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -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()),
|
||||
}),
|
||||
|
||||
@@ -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,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";
|
||||
|
||||
|
||||
@@ -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} | ||||