Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7adbc1161 | ||
|
|
95f6b12918 | ||
|
|
926ff9baaa | ||
|
|
843adadac2 | ||
|
|
c010fc3f3f | ||
|
|
1b61ce1112 | ||
|
|
60af905e70 | ||
|
|
8650f05f95 | ||
|
|
8fe8f9a9c1 | ||
|
|
936593c258 | ||
|
|
2919147c80 | ||
|
|
1ba3d01bc6 | ||
|
|
5fcdefd057 | ||
|
|
38a6e3ce65 | ||
|
|
f2d2fb2f24 | ||
|
|
8829e2f9b9 | ||
|
|
2deea7abb0 | ||
|
|
b64ae880e0 | ||
|
|
887dd6e455 | ||
|
|
f1a68ac9b0 | ||
|
|
55dd01612e | ||
|
|
3c50a64885 | ||
|
|
9ccfd9dfef | ||
|
|
4f584da0f8 | ||
|
|
362f127922 | ||
|
|
9cf9fc9c5c | ||
|
|
e00781a661 | ||
|
|
d25b15737a | ||
|
|
b0c4992c79 | ||
|
|
dd5ea32488 | ||
|
|
c13a021e43 | ||
|
|
476d69cd1d | ||
|
|
a148e08197 | ||
|
|
831eb66fee |
No files matched your search
@@ -1,52 +1,139 @@
|
||||
# AGENTS.md
|
||||
# T3 Code
|
||||
|
||||
## Task Completion Requirements
|
||||
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.
|
||||
|
||||
- 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.
|
||||
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.
|
||||
|
||||
## Dev Servers
|
||||
## What makes T3 Code special?
|
||||
|
||||
- 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.
|
||||
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.
|
||||
|
||||
## Package Roles
|
||||
### 1. Open at the core
|
||||
|
||||
- `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.
|
||||
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.
|
||||
|
||||
## Reference Repos
|
||||
### 2. Performance without compromise
|
||||
|
||||
- Open-source Codex repo: https://github.com/openai/codex
|
||||
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.
|
||||
|
||||
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
|
||||
### 3. Remote ready
|
||||
|
||||
## Vendored Repositories
|
||||
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.
|
||||
|
||||
This project vendors external repositories under `.repos/` as read-only reference material for coding
|
||||
agents.
|
||||
### 4. Multi-surface
|
||||
|
||||
- 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.
|
||||
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.
|
||||
@@ -1,24 +1,36 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
|
||||
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.
|
||||
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
|
||||
> Install and authenticate at least one provider before use:
|
||||
> T3 Code currently supports Codex, Claude, Cursor, Grok Build 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`
|
||||
|
||||
### Run without installing
|
||||
### Try it out (install-free)
|
||||
|
||||
The easiest way to test T3 Code is to run the server in your terminal:
|
||||
|
||||
```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
|
||||
@@ -47,7 +59,7 @@ yay -S t3code-bin
|
||||
|
||||
We are very very early in this project. Expect bugs.
|
||||
|
||||
We are not accepting contributions yet.
|
||||
We are (mostly) not accepting contributions yet. Small fixes may be considered. Big features will not be.
|
||||
|
||||
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.29",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -63,6 +63,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
calls.setDockIcon.push(iconPath);
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
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,16 +176,28 @@ 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,
|
||||
() => quitAllowed || updaterQuitAllowed,
|
||||
() => {
|
||||
quitAllowed = true;
|
||||
},
|
||||
|
||||
@@ -4,6 +4,8 @@ import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const {
|
||||
appendSwitchMock,
|
||||
autoUpdaterOnMock,
|
||||
autoUpdaterRemoveListenerMock,
|
||||
exitMock,
|
||||
getAppPathMock,
|
||||
getVersionMock,
|
||||
@@ -23,6 +25,8 @@ 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"),
|
||||
@@ -43,6 +47,10 @@ const {
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
autoUpdater: {
|
||||
on: autoUpdaterOnMock,
|
||||
removeListener: autoUpdaterRemoveListenerMock,
|
||||
},
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
@@ -77,6 +85,8 @@ import * as ElectronApp from "./ElectronApp.ts";
|
||||
describe("ElectronApp", () => {
|
||||
beforeEach(() => {
|
||||
appendSwitchMock.mockClear();
|
||||
autoUpdaterOnMock.mockClear();
|
||||
autoUpdaterRemoveListenerMock.mockClear();
|
||||
exitMock.mockClear();
|
||||
onMock.mockClear();
|
||||
quitMock.mockClear();
|
||||
@@ -153,4 +163,22 @@ 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,6 +66,9 @@ 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,
|
||||
@@ -178,6 +181,16 @@ 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,6 +18,7 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
environmentIdentificationMode: "artwork",
|
||||
favorites: [],
|
||||
glassOpacity: 80,
|
||||
providerModelPreferences: {},
|
||||
@@ -30,6 +31,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
sidebarV2Enabled: false,
|
||||
sidebarV2ConfiguredByUser: false,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
@@ -45,6 +45,7 @@ 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"]);
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["T3WebSocketModule"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'T3WebSocket'
|
||||
s.version = '1.0.0'
|
||||
s.summary = 'URLSession-backed WebSocket for T3 Code mobile.'
|
||||
s.description = 'WebSocket client backed by URLSessionWebSocketTask so iOS negotiates permessage-deflate, which SocketRocket (React Native default) cannot.'
|
||||
s.author = 'T3 Tools'
|
||||
s.homepage = 'https://t3tools.com'
|
||||
s.platforms = {
|
||||
:ios => '18.0',
|
||||
}
|
||||
s.source = { :path => '.' }
|
||||
s.static_framework = true
|
||||
|
||||
s.dependency 'ExpoModulesCore'
|
||||
s.pod_target_xcconfig = {
|
||||
'DEFINES_MODULE' => 'YES',
|
||||
}
|
||||
s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'
|
||||
end
|
||||
@@ -0,0 +1,210 @@
|
||||
import ExpoModulesCore
|
||||
import Foundation
|
||||
|
||||
// WebSocket client backed by URLSessionWebSocketTask. React Native's built-in
|
||||
// iOS WebSocket (SocketRocket) never offers permessage-deflate, so frames from
|
||||
// the T3 server arrive uncompressed. URLSessionWebSocketTask offers the
|
||||
// extension in its handshake by default, letting the server (which negotiates
|
||||
// permessage-deflate since #4705) compress the JSON RPC stream.
|
||||
//
|
||||
// Only the surface Effect's `Socket.fromWebSocket` needs is exposed: connect,
|
||||
// send text/binary, close, and open/message/close/error events routed by a
|
||||
// JS-assigned connection id.
|
||||
public final class T3WebSocketModule: Module {
|
||||
private let connections = T3WebSocketConnections()
|
||||
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3WebSocket")
|
||||
|
||||
Events("onOpen", "onMessage", "onClose", "onError")
|
||||
|
||||
Function("connect") { (id: Int, url: String, protocols: [String]) throws in
|
||||
guard let parsedUrl = URL(string: url) else {
|
||||
throw Exception(name: "InvalidUrl", description: "Invalid WebSocket URL: \(url)")
|
||||
}
|
||||
self.connections.open(id: id, url: parsedUrl, protocols: protocols) { [weak self] event, payload in
|
||||
self?.sendEvent(event, payload)
|
||||
}
|
||||
}
|
||||
|
||||
Function("sendText") { (id: Int, text: String) in
|
||||
self.connections.send(id: id, message: .string(text))
|
||||
}
|
||||
|
||||
Function("sendBinary") { (id: Int, base64: String) in
|
||||
guard let data = Data(base64Encoded: base64) else { return }
|
||||
self.connections.send(id: id, message: .data(data))
|
||||
}
|
||||
|
||||
Function("close") { (id: Int, code: Int, reason: String) in
|
||||
self.connections.close(id: id, code: code, reason: reason)
|
||||
}
|
||||
|
||||
OnDestroy {
|
||||
self.connections.cancelAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private typealias T3WebSocketEmitter = (_ event: String, _ payload: [String: Any]) -> Void
|
||||
|
||||
private final class T3WebSocketConnections: NSObject, URLSessionWebSocketDelegate {
|
||||
// Snapshot frames on the socket-fallback path can reach tens of MB; the
|
||||
// URLSession default receive cap is 1 MB, which would abort the connection.
|
||||
private static let maximumMessageSize = 128 * 1024 * 1024
|
||||
|
||||
private let queue = DispatchQueue(label: "com.t3tools.t3code.websocket")
|
||||
private var tasksById: [Int: URLSessionWebSocketTask] = [:]
|
||||
private var idsByTaskIdentifier: [Int: Int] = [:]
|
||||
private var emittersById: [Int: T3WebSocketEmitter] = [:]
|
||||
|
||||
// Held so teardown can invalidate it: URLSession retains its delegate (self)
|
||||
// until invalidated, so skipping that leaks this object and the session on
|
||||
// every module destroy/recreate cycle. Only touched from `queue`.
|
||||
private var activeSession: URLSession?
|
||||
|
||||
private var session: URLSession {
|
||||
if let activeSession { return activeSession }
|
||||
let configuration = URLSessionConfiguration.default
|
||||
// Dev clients (and network debuggers) register custom URLProtocol classes
|
||||
// that intercept URLSession traffic. They do not understand the WebSocket
|
||||
// upgrade and drop the connection right after the 101 (NSURLErrorDomain
|
||||
// -1005). WebSocket traffic has no reason to go through them.
|
||||
configuration.protocolClasses = []
|
||||
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
|
||||
activeSession = session
|
||||
return session
|
||||
}
|
||||
|
||||
func open(id: Int, url: URL, protocols: [String], emitter: @escaping T3WebSocketEmitter) {
|
||||
queue.async {
|
||||
let task = protocols.isEmpty
|
||||
? self.session.webSocketTask(with: url)
|
||||
: self.session.webSocketTask(with: url, protocols: protocols)
|
||||
task.maximumMessageSize = Self.maximumMessageSize
|
||||
self.tasksById[id] = task
|
||||
self.idsByTaskIdentifier[task.taskIdentifier] = id
|
||||
self.emittersById[id] = emitter
|
||||
task.resume()
|
||||
self.receiveLoop(id: id, task: task)
|
||||
}
|
||||
}
|
||||
|
||||
func send(id: Int, message: URLSessionWebSocketTask.Message) {
|
||||
queue.async {
|
||||
guard let task = self.tasksById[id] else { return }
|
||||
task.send(message) { [weak self] error in
|
||||
guard let self, let error else { return }
|
||||
self.queue.async {
|
||||
self.emitLocked(id: id, event: "onError", payload: ["message": error.localizedDescription])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func close(id: Int, code: Int, reason: String) {
|
||||
queue.async {
|
||||
guard let task = self.tasksById[id] else { return }
|
||||
let closeCode = URLSessionWebSocketTask.CloseCode(rawValue: code) ?? .normalClosure
|
||||
task.cancel(with: closeCode, reason: reason.data(using: .utf8))
|
||||
}
|
||||
}
|
||||
|
||||
func cancelAll() {
|
||||
queue.async {
|
||||
for task in self.tasksById.values {
|
||||
task.cancel(with: .goingAway, reason: nil)
|
||||
}
|
||||
self.tasksById.removeAll()
|
||||
self.idsByTaskIdentifier.removeAll()
|
||||
self.emittersById.removeAll()
|
||||
// Releases the session's reference to this delegate. A later `open` call
|
||||
// builds a fresh session rather than using an invalidated one.
|
||||
self.activeSession?.invalidateAndCancel()
|
||||
self.activeSession = nil
|
||||
}
|
||||
}
|
||||
|
||||
private func receiveLoop(id: Int, task: URLSessionWebSocketTask) {
|
||||
task.receive { [weak self] result in
|
||||
guard let self else { return }
|
||||
self.queue.async {
|
||||
switch result {
|
||||
case .success(let message):
|
||||
switch message {
|
||||
case .string(let text):
|
||||
self.emitLocked(id: id, event: "onMessage", payload: ["data": text, "binary": false])
|
||||
case .data(let data):
|
||||
self.emitLocked(id: id, event: "onMessage", payload: ["data": data.base64EncodedString(), "binary": true])
|
||||
@unknown default:
|
||||
break
|
||||
}
|
||||
guard self.tasksById[id] != nil else { return }
|
||||
self.receiveLoop(id: id, task: task)
|
||||
case .failure:
|
||||
// The delegate close/error callbacks own failure reporting; the loop
|
||||
// just stops so it does not spin on a dead task.
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Must be called on `queue`.
|
||||
private func emitLocked(id: Int, event: String, payload: [String: Any]) {
|
||||
guard let emitter = emittersById[id] else { return }
|
||||
var enriched = payload
|
||||
enriched["id"] = id
|
||||
emitter(event, enriched)
|
||||
}
|
||||
|
||||
private func remove(id: Int, taskIdentifier: Int) {
|
||||
tasksById.removeValue(forKey: id)
|
||||
idsByTaskIdentifier.removeValue(forKey: taskIdentifier)
|
||||
emittersById.removeValue(forKey: id)
|
||||
}
|
||||
|
||||
// MARK: - URLSessionWebSocketDelegate
|
||||
|
||||
func urlSession(
|
||||
_ session: URLSession,
|
||||
webSocketTask: URLSessionWebSocketTask,
|
||||
didOpenWithProtocol protocol: String?
|
||||
) {
|
||||
queue.async {
|
||||
guard let id = self.idsByTaskIdentifier[webSocketTask.taskIdentifier] else { return }
|
||||
self.emitLocked(id: id, event: "onOpen", payload: ["protocol": `protocol` ?? ""])
|
||||
}
|
||||
}
|
||||
|
||||
func urlSession(
|
||||
_ session: URLSession,
|
||||
webSocketTask: URLSessionWebSocketTask,
|
||||
didCloseWith closeCode: URLSessionWebSocketTask.CloseCode,
|
||||
reason: Data?
|
||||
) {
|
||||
queue.async {
|
||||
guard let id = self.idsByTaskIdentifier[webSocketTask.taskIdentifier] else { return }
|
||||
let reasonText = reason.flatMap { String(data: $0, encoding: .utf8) } ?? ""
|
||||
self.emitLocked(id: id, event: "onClose", payload: ["code": closeCode.rawValue, "reason": reasonText])
|
||||
self.remove(id: id, taskIdentifier: webSocketTask.taskIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
func urlSession(
|
||||
_ session: URLSession,
|
||||
task: URLSessionTask,
|
||||
didCompleteWithError error: Error?
|
||||
) {
|
||||
queue.async {
|
||||
guard let id = self.idsByTaskIdentifier[task.taskIdentifier] else { return }
|
||||
if let error {
|
||||
self.emitLocked(id: id, event: "onError", payload: ["message": error.localizedDescription])
|
||||
// Abnormal termination: no close frame arrived, mirror the browser's
|
||||
// 1006 so Effect's close-code classification treats it as an error.
|
||||
self.emitLocked(id: id, event: "onClose", payload: ["code": 1006, "reason": error.localizedDescription])
|
||||
}
|
||||
self.remove(id: id, taskIdentifier: task.taskIdentifier)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,6 @@ import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteSc
|
||||
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
|
||||
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
|
||||
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
|
||||
import {
|
||||
SettingsLegalDocumentCloseHeaderButton,
|
||||
@@ -190,10 +189,11 @@ const SettingsSheetStack = createNativeStackNavigator({
|
||||
},
|
||||
}),
|
||||
SettingsWaitlist: createNativeStackScreen({
|
||||
screen: SettingsWaitlistRouteScreen,
|
||||
// Keep the old deep link working after the Connect GA launch.
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "waitlist",
|
||||
options: {
|
||||
title: "Join the waitlist",
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -42,6 +42,12 @@ 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()) {
|
||||
@@ -80,6 +86,36 @@ 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,6 +223,16 @@ 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)
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
import { useWaitlist } from "@clerk/expo";
|
||||
import { ActivityIndicator, Pressable, Text, TextInput, View } from "react-native";
|
||||
import { useState } from "react";
|
||||
|
||||
import { cn } from "../../lib/cn";
|
||||
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
|
||||
|
||||
export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) {
|
||||
const { errors, fetchStatus, waitlist } = useWaitlist();
|
||||
const [emailAddress, setEmailAddress] = useState("");
|
||||
const [requestError, setRequestError] = useState<string | null>(null);
|
||||
const isSubmitting = fetchStatus === "fetching";
|
||||
const fieldError = errors.fields.emailAddress?.longMessage;
|
||||
|
||||
const joinWaitlist = async () => {
|
||||
const normalizedEmailAddress = emailAddress.trim();
|
||||
if (!normalizedEmailAddress || isSubmitting) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRequestError(null);
|
||||
try {
|
||||
await joinCloudWaitlist(waitlist, normalizedEmailAddress);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
setRequestError(
|
||||
error instanceof CloudWaitlistJoinRejectedError
|
||||
? "Could not join the waitlist. Check your email address and try again."
|
||||
: "Could not join the waitlist. Check your connection and try again.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if (waitlist.id) {
|
||||
return (
|
||||
<View className="gap-[18px]">
|
||||
<Text className="text-center font-t3-bold text-xl text-foreground">
|
||||
You are on the waitlist
|
||||
</Text>
|
||||
<Text className="text-center font-sans text-base text-foreground-secondary">
|
||||
We will email you when your T3 Connect access is ready.
|
||||
</Text>
|
||||
<SignInAction onPress={props.onSignIn} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="gap-[18px]">
|
||||
<Text className="font-sans text-base text-foreground-secondary">
|
||||
Enter your email and we will let you know when access is ready.
|
||||
</Text>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="font-t3-bold text-sm text-foreground-secondary">Email address</Text>
|
||||
<TextInput
|
||||
accessibilityLabel="Email address"
|
||||
autoCapitalize="none"
|
||||
autoComplete="email"
|
||||
autoCorrect={false}
|
||||
className={cn(
|
||||
"min-h-[54px] rounded-2xl border border-input-border bg-input px-4 py-3.5 font-sans text-lg text-foreground border-continuous",
|
||||
(fieldError || requestError) && "border-danger-foreground",
|
||||
)}
|
||||
keyboardType="email-address"
|
||||
onChangeText={(value) => {
|
||||
setEmailAddress(value);
|
||||
setRequestError(null);
|
||||
}}
|
||||
onSubmitEditing={() => void joinWaitlist()}
|
||||
placeholder="Enter your email address"
|
||||
placeholderTextColorClassName="accent-placeholder"
|
||||
returnKeyType="join"
|
||||
textContentType="emailAddress"
|
||||
value={emailAddress}
|
||||
/>
|
||||
{fieldError || requestError ? (
|
||||
<Text
|
||||
accessibilityLiveRegion="polite"
|
||||
className="font-sans text-sm text-danger-foreground"
|
||||
selectable
|
||||
>
|
||||
{fieldError ?? requestError}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{
|
||||
busy: isSubmitting,
|
||||
disabled: isSubmitting || emailAddress.trim().length === 0,
|
||||
}}
|
||||
disabled={isSubmitting || emailAddress.trim().length === 0}
|
||||
onPress={() => void joinWaitlist()}
|
||||
className="min-h-[54px] flex-row items-center justify-center gap-2 rounded-full bg-primary px-5 py-3 disabled:opacity-[0.45]"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<ActivityIndicator colorClassName="accent-primary-foreground" size="small" />
|
||||
) : null}
|
||||
<Text className="font-t3-bold text-base text-primary-foreground">
|
||||
{isSubmitting ? "Joining" : "Join the waitlist"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
|
||||
<SignInAction onPress={props.onSignIn} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function SignInAction(props: { readonly onPress: () => void }) {
|
||||
return (
|
||||
<View className="flex-row items-center justify-center gap-1 pt-1">
|
||||
<Text className="font-sans text-base text-foreground-secondary">Already have access?</Text>
|
||||
<Pressable accessibilityRole="button" hitSlop={8} onPress={props.onPress}>
|
||||
<Text className="font-t3-bold text-base text-foreground">Sign in</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
CloudWaitlistJoinRejectedError,
|
||||
CloudWaitlistJoinRequestError,
|
||||
joinCloudWaitlist,
|
||||
} from "./cloudWaitlistJoin";
|
||||
|
||||
describe("joinCloudWaitlist", () => {
|
||||
it("submits the provided email address", async () => {
|
||||
const join = vi.fn().mockResolvedValue({ error: null });
|
||||
|
||||
await joinCloudWaitlist({ join }, "[email protected]");
|
||||
|
||||
expect(join).toHaveBeenCalledExactlyOnceWith({ emailAddress: "[email protected]" });
|
||||
});
|
||||
|
||||
it("preserves Clerk rejection details without exposing the email address", async () => {
|
||||
const cause = Object.assign(new Error("The enrollment was rejected."), {
|
||||
code: "form_identifier_invalid",
|
||||
});
|
||||
const join = vi.fn().mockResolvedValue({ error: cause });
|
||||
|
||||
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
|
||||
(error: unknown) => error,
|
||||
);
|
||||
|
||||
expect(failure).toBeInstanceOf(CloudWaitlistJoinRejectedError);
|
||||
expect(failure).toMatchObject({
|
||||
code: "form_identifier_invalid",
|
||||
cause,
|
||||
});
|
||||
expect(String(failure)).not.toContain("[email protected]");
|
||||
});
|
||||
|
||||
it("distinguishes request failures from rejected enrollments", async () => {
|
||||
const cause = new Error("network unavailable");
|
||||
const join = vi.fn().mockRejectedValue(cause);
|
||||
|
||||
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
|
||||
(error: unknown) => error,
|
||||
);
|
||||
|
||||
expect(failure).toBeInstanceOf(CloudWaitlistJoinRequestError);
|
||||
expect(failure).toMatchObject({ cause });
|
||||
expect(failure).not.toBeInstanceOf(CloudWaitlistJoinRejectedError);
|
||||
});
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
interface CloudWaitlistJoiner {
|
||||
readonly join: (input: { emailAddress: string }) => Promise<{
|
||||
readonly error: { readonly code: string } | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
export class CloudWaitlistJoinRejectedError extends Schema.TaggedErrorClass<CloudWaitlistJoinRejectedError>()(
|
||||
"CloudWaitlistJoinRejectedError",
|
||||
{
|
||||
code: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Cloud waitlist enrollment was rejected with code "${this.code}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudWaitlistJoinRequestError extends Schema.TaggedErrorClass<CloudWaitlistJoinRequestError>()(
|
||||
"CloudWaitlistJoinRequestError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Cloud waitlist enrollment request failed.";
|
||||
}
|
||||
}
|
||||
|
||||
export async function joinCloudWaitlist(
|
||||
waitlist: CloudWaitlistJoiner,
|
||||
emailAddress: string,
|
||||
): Promise<void> {
|
||||
const result = await waitlist.join({ emailAddress }).catch((cause) => {
|
||||
throw new CloudWaitlistJoinRequestError({ cause });
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
throw new CloudWaitlistJoinRejectedError({
|
||||
code: result.error.code,
|
||||
cause: result.error,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -24,13 +24,7 @@ import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironment
|
||||
import { ConnectionStatusDot } from "./ConnectionStatusDot";
|
||||
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
|
||||
|
||||
/**
|
||||
* "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: {
|
||||
interface CloudEnvironmentRowsProps {
|
||||
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
|
||||
readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
|
||||
@@ -41,8 +35,31 @@ export function CloudEnvironmentRows(props: {
|
||||
* 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 =
|
||||
@@ -67,8 +84,6 @@ export function CloudEnvironmentRows(props: {
|
||||
|
||||
const showHeader = props.showHeader ?? true;
|
||||
|
||||
if (!(props.showcaseSignedIn ?? isSignedIn)) return null;
|
||||
|
||||
return (
|
||||
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
|
||||
{showHeader ? (
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
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";
|
||||
@@ -12,7 +10,7 @@ import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { T3Wordmark } from "../../components/T3Wordmark";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
@@ -59,21 +57,14 @@ 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");
|
||||
const threadListV2Enabled = useThreadListV2FilterGate();
|
||||
// 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 hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
@@ -291,7 +282,10 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
function IosHomeHeader(props: HomeHeaderProps) {
|
||||
const searchBarRef = useRef<SearchBarCommands>(null);
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const threadListV2Enabled = useThreadListV2FilterGate();
|
||||
// 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 hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
|
||||
@@ -27,6 +27,7 @@ import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
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 {
|
||||
@@ -35,12 +36,13 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "../threads/thread-list-items";
|
||||
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
|
||||
import { ThreadListV2PendingRow, ThreadListV2Row } from "../threads/thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
|
||||
type ThreadListV2Item,
|
||||
type ThreadListV2ListItem,
|
||||
} from "../threads/threadListV2";
|
||||
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
|
||||
import {
|
||||
@@ -181,9 +183,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
>(() => new Map());
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled =
|
||||
AsyncResult.isSuccess(preferencesResult) &&
|
||||
preferencesResult.value.threadListV2Enabled === true;
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
@@ -550,50 +550,100 @@ 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]);
|
||||
const threadListV2Items = threadListV2Layout.items;
|
||||
// Queued tasks are not thread shells, so the v2 partition never sees them;
|
||||
// they are spliced in below the active block and stay visible and deletable
|
||||
// while their environment is offline. Same environment scope and search
|
||||
// filter as the list itself.
|
||||
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
|
||||
const v2PendingTasks = useMemo(
|
||||
() =>
|
||||
props.pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
(props.selectedEnvironmentId === null ||
|
||||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
|
||||
(v2ScopedProjectKeys === null ||
|
||||
v2ScopedProjectKeys.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
)) &&
|
||||
(v2SearchQuery.length === 0 ||
|
||||
pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
|
||||
),
|
||||
[props.pendingTasks, props.selectedEnvironmentId, v2ScopedProjectKeys, v2SearchQuery],
|
||||
);
|
||||
const threadListV2Items = useMemo(
|
||||
() =>
|
||||
buildThreadListV2ListItems({
|
||||
items: threadListV2Layout.items,
|
||||
pendingTasks: v2PendingTasks,
|
||||
}),
|
||||
[threadListV2Layout.items, v2PendingTasks],
|
||||
);
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
({ item }: { readonly item: ThreadListV2Item }) => (
|
||||
<ThreadListV2Row
|
||||
thread={item.thread}
|
||||
variant={item.variant}
|
||||
showSettledDivider={item.showSettledDivider}
|
||||
project={
|
||||
projectByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
projectTitle={v2ProjectTitleByProjectKey.get(
|
||||
scopedProjectKey(item.thread.environmentId, item.thread.projectId),
|
||||
)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(item.thread.environmentId)
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(item.thread.session?.providerInstanceId ?? item.thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
Object.keys(props.savedConnectionsById).length > 1
|
||||
? (props.savedConnectionsById[item.thread.environmentId]?.environmentLabel ?? null)
|
||||
: null
|
||||
}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(item.thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
/>
|
||||
),
|
||||
({ item }: { readonly item: ThreadListV2ListItem }) => {
|
||||
if (item.type === "v2-pending") {
|
||||
const pendingScopeKey = scopedProjectKey(
|
||||
item.pendingTask.message.environmentId,
|
||||
item.pendingTask.creation.projectId,
|
||||
);
|
||||
return (
|
||||
<ThreadListV2PendingRow
|
||||
pendingTask={item.pendingTask}
|
||||
project={projectByKey.get(pendingScopeKey) ?? null}
|
||||
projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
|
||||
environmentLabel={
|
||||
Object.keys(props.savedConnectionsById).length > 1
|
||||
? (props.savedConnectionsById[item.pendingTask.message.environmentId]
|
||||
?.environmentLabel ?? null)
|
||||
: null
|
||||
}
|
||||
showPendingDivider={item.showPendingDivider}
|
||||
onSelectPendingTask={props.onSelectPendingTask}
|
||||
onDeletePendingTask={props.onDeletePendingTask}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const thread = item.item.thread;
|
||||
return (
|
||||
<ThreadListV2Row
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
project={
|
||||
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
}
|
||||
projectTitle={v2ProjectTitleByProjectKey.get(
|
||||
scopedProjectKey(thread.environmentId, thread.projectId),
|
||||
)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(thread.environmentId)
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
Object.keys(props.savedConnectionsById).length > 1
|
||||
? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
|
||||
: null
|
||||
}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
@@ -604,6 +654,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onDeletePendingTask,
|
||||
props.onSelectPendingTask,
|
||||
props.onSelectThread,
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
@@ -611,10 +663,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
v2ProjectTitleByProjectKey,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback(
|
||||
(item: ThreadListV2Item) => `${item.thread.environmentId}:${item.thread.id}`,
|
||||
[],
|
||||
);
|
||||
const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
|
||||
|
||||
const extraData = useMemo(
|
||||
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
|
||||
@@ -789,41 +838,9 @@ 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}
|
||||
{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 v2ListHeader = listHeader;
|
||||
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery ? (
|
||||
@@ -847,37 +864,33 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// is empty. Search outranks the scope — "No results" names the actionable
|
||||
// fact when a query is active. Snoozed threads outrank the rest: "No
|
||||
// threads yet" over an inbox that is merely all-snoozed reads as data
|
||||
// loss. Pending tasks render in the header, so the list showing them
|
||||
// isn't empty in the user's eyes.
|
||||
// loss.
|
||||
const v2SnoozedCount = threadListV2Layout.snoozedCount;
|
||||
const v2ListEmpty =
|
||||
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
|
||||
v2SnoozedCount > 0 ? (
|
||||
// The snoozed threads already passed this search filter: "No
|
||||
// results" would claim nothing matched when matches are merely
|
||||
// parked.
|
||||
<EmptyState
|
||||
title={
|
||||
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
|
||||
}
|
||||
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
)
|
||||
) : v2SnoozedCount > 0 ? (
|
||||
const v2ListEmpty = hasSearchQuery ? (
|
||||
v2SnoozedCount > 0 ? (
|
||||
// The snoozed threads already passed this search filter: "No
|
||||
// results" would claim nothing matched when matches are merely
|
||||
// parked.
|
||||
<EmptyState
|
||||
title={v2SnoozedCount === 1 ? "1 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."
|
||||
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.`}
|
||||
/>
|
||||
) : (
|
||||
listEmpty
|
||||
);
|
||||
<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
|
||||
);
|
||||
|
||||
if (threadListV2Enabled) {
|
||||
return (
|
||||
@@ -889,6 +902,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
keyExtractor={v2KeyExtractor}
|
||||
extraData={{
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
|
||||
serverConfigs,
|
||||
savedConnectionsById: props.savedConnectionsById,
|
||||
}}
|
||||
|
||||
@@ -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";
|
||||
@@ -45,7 +45,10 @@ 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 { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import {
|
||||
useRemoteEnvironmentRuntime,
|
||||
useSavedRemoteConnections,
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
|
||||
interface EnvironmentOption {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -61,11 +64,6 @@ 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";
|
||||
@@ -228,6 +226,63 @@ 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();
|
||||
@@ -592,22 +647,16 @@ 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 browseDirectoryPath = useMemo(
|
||||
() =>
|
||||
isFilesystemBrowseQuery(props.pathInput, props.environment.platform)
|
||||
? getBrowseDirectoryPath(props.pathInput)
|
||||
: "",
|
||||
const browsePath = useMemo(
|
||||
() => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
|
||||
[props.environment.platform, props.pathInput],
|
||||
);
|
||||
const browseFilterQuery =
|
||||
browseDirectoryPath.length > 0 && !hasTrailingPathSeparator(props.pathInput)
|
||||
? getBrowseLeafPathSegment(props.pathInput).toLowerCase()
|
||||
: "";
|
||||
const browseInput = useMemo(
|
||||
() => (browseDirectoryPath.length > 0 ? { partialPath: browseDirectoryPath } : null),
|
||||
[browseDirectoryPath],
|
||||
() => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
|
||||
[browsePath.directoryPath],
|
||||
);
|
||||
const browseState = useEnvironmentQuery(
|
||||
browseInput === null
|
||||
@@ -617,20 +666,10 @@ function FolderBrowser(props: {
|
||||
input: browseInput,
|
||||
}),
|
||||
);
|
||||
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 { visibleEntries: visibleBrowseEntries } = useMemo(
|
||||
() => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browsePath.filterQuery),
|
||||
[browsePath.filterQuery, browseState.data?.entries],
|
||||
);
|
||||
const parentBrowsePath = getBrowseParentPath(browseDirectoryPath);
|
||||
const canBrowseUpPath = canNavigateUp(browseDirectoryPath);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -642,7 +681,7 @@ function FolderBrowser(props: {
|
||||
<ActivityIndicator color={accentColor} />
|
||||
</View>
|
||||
) : null}
|
||||
{canBrowseUpPath ? (
|
||||
{browsePath.canBrowseUp ? (
|
||||
<ListRow
|
||||
title=".."
|
||||
icon={
|
||||
@@ -656,7 +695,9 @@ function FolderBrowser(props: {
|
||||
isFirst
|
||||
right={null}
|
||||
onPress={() => {
|
||||
if (parentBrowsePath) props.setPathInput(parentBrowsePath);
|
||||
if (browsePath.parentPath) {
|
||||
void props.navigateToBrowsePath(browsePath.parentPath);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
@@ -665,15 +706,15 @@ function FolderBrowser(props: {
|
||||
key={entry.fullPath}
|
||||
title={entry.name}
|
||||
icon={<SymbolView name="folder" size={17} tintColor={accentColor} type="monochrome" />}
|
||||
isFirst={index === 0 && !canBrowseUpPath}
|
||||
isFirst={index === 0 && !browsePath.canBrowseUp}
|
||||
right={null}
|
||||
onPress={() =>
|
||||
props.setPathInput(
|
||||
browseDirectoryPath.length > 0
|
||||
? appendBrowsePathSegment(browseDirectoryPath, entry.name)
|
||||
: ensureBrowseDirectoryPath(entry.fullPath),
|
||||
)
|
||||
}
|
||||
onPress={() => {
|
||||
const nextPath =
|
||||
browsePath.directoryPath.length > 0
|
||||
? appendBrowsePathSegment(browsePath.directoryPath, entry.name)
|
||||
: ensureBrowseDirectoryPath(entry.fullPath);
|
||||
void props.navigateToBrowsePath(nextPath);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</ListSection>
|
||||
@@ -684,19 +725,13 @@ function FolderBrowser(props: {
|
||||
export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
|
||||
const environment = useEnvironmentFromParam(props.environmentId);
|
||||
const createProject = useCreateProject(environment);
|
||||
const [pathInput, setPathInput] = useState(() =>
|
||||
getAddProjectInitialQuery(environment?.baseDirectory),
|
||||
);
|
||||
const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
|
||||
useBrowsePathInput(environment);
|
||||
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 || isSubmitting) return;
|
||||
if (!environment || isBrowseNavigating || isSubmitting) return;
|
||||
setError(null);
|
||||
const resolved = resolveAddProjectPath({
|
||||
rawPath: pathInput,
|
||||
@@ -714,7 +749,7 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st
|
||||
setError(errorMessage(Cause.squash(result.cause)));
|
||||
}
|
||||
setIsSubmitting(false);
|
||||
}, [createProject, environment, isSubmitting, pathInput]);
|
||||
}, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
|
||||
|
||||
return (
|
||||
<AddProjectShell>
|
||||
@@ -728,12 +763,13 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st
|
||||
/>
|
||||
<PrimaryActionButton
|
||||
label="Add project"
|
||||
disabled={isSubmitting}
|
||||
disabled={isBrowseNavigating || isSubmitting}
|
||||
onPress={() => void submitPath()}
|
||||
loading={isSubmitting}
|
||||
/>
|
||||
<FolderBrowser
|
||||
environment={environment}
|
||||
navigateToBrowsePath={navigateToBrowsePath}
|
||||
pathInput={pathInput}
|
||||
setPathInput={setPathInput}
|
||||
/>
|
||||
@@ -757,19 +793,13 @@ export function AddProjectDestinationScreen(props: {
|
||||
const createProject = useCreateProject(environment);
|
||||
const remoteUrl = stringParam(props.remoteUrl);
|
||||
const repositoryTitle = stringParam(props.repositoryTitle);
|
||||
const [pathInput, setPathInput] = useState(() =>
|
||||
getAddProjectInitialQuery(environment?.baseDirectory),
|
||||
);
|
||||
const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
|
||||
useBrowsePathInput(environment);
|
||||
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 || isSubmitting) return;
|
||||
if (!environment || !remoteUrl || isBrowseNavigating || isSubmitting) return;
|
||||
setError(null);
|
||||
const resolved = resolveAddProjectPath({
|
||||
rawPath: pathInput,
|
||||
@@ -798,7 +828,15 @@ export function AddProjectDestinationScreen(props: {
|
||||
}
|
||||
}
|
||||
setIsSubmitting(false);
|
||||
}, [cloneRepository, createProject, environment, isSubmitting, pathInput, remoteUrl]);
|
||||
}, [
|
||||
cloneRepository,
|
||||
createProject,
|
||||
environment,
|
||||
isBrowseNavigating,
|
||||
isSubmitting,
|
||||
pathInput,
|
||||
remoteUrl,
|
||||
]);
|
||||
|
||||
return (
|
||||
<AddProjectShell>
|
||||
@@ -820,12 +858,13 @@ export function AddProjectDestinationScreen(props: {
|
||||
/>
|
||||
<PrimaryActionButton
|
||||
label="Clone project"
|
||||
disabled={isSubmitting || !remoteUrl}
|
||||
disabled={isBrowseNavigating || isSubmitting || !remoteUrl}
|
||||
onPress={() => void submitPath()}
|
||||
loading={isSubmitting}
|
||||
/>
|
||||
<FolderBrowser
|
||||
environment={environment}
|
||||
navigateToBrowsePath={navigateToBrowsePath}
|
||||
pathInput={pathInput}
|
||||
setPathInput={setPathInput}
|
||||
/>
|
||||
|
||||
@@ -8,11 +8,20 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { Alert, Linking, Platform, ScrollView, View } from "react-native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Linking,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import {
|
||||
type AtomCommandResult,
|
||||
isAtomCommandInterrupted,
|
||||
reportAtomCommandResult,
|
||||
settleAsyncResult,
|
||||
@@ -37,6 +46,7 @@ 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";
|
||||
@@ -156,7 +166,7 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const environmentCount = connections.length;
|
||||
const accountLabel = useMemo(() => {
|
||||
if (!isLoaded) return "Checking";
|
||||
if (!isSignedIn) return "Request access";
|
||||
if (!isSignedIn) return "Sign in";
|
||||
return user?.primaryEmailAddress?.emailAddress ?? "Signed in";
|
||||
}, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]);
|
||||
|
||||
@@ -263,13 +273,13 @@ function ConfiguredSettingsRouteScreen() {
|
||||
|
||||
const promptSignIn = useCallback(() => {
|
||||
Alert.alert(
|
||||
"Request T3 Connect access",
|
||||
"Live Activity updates require approved T3 Connect access so relay can deliver updates to this device.",
|
||||
"Sign in to T3 Connect",
|
||||
"Live Activity updates require T3 Connect so relay can deliver updates to this device.",
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{
|
||||
text: "Continue",
|
||||
onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsWaitlist" }),
|
||||
onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),
|
||||
},
|
||||
],
|
||||
);
|
||||
@@ -431,7 +441,8 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const openAccount = useCallback(() => {
|
||||
if (!isLoaded) return;
|
||||
if (!isSignedIn) {
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsWaitlist" });
|
||||
expandClerkSheet();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
return;
|
||||
}
|
||||
expandClerkSheet();
|
||||
@@ -546,11 +557,8 @@ 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 = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.threadListV2Enabled === true
|
||||
: false;
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
@@ -570,8 +578,12 @@ function BetaSettingsSection() {
|
||||
);
|
||||
}
|
||||
|
||||
type UpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
|
||||
|
||||
function AppSettingsSection() {
|
||||
const icon = useThemeColor("--color-icon");
|
||||
const [updateState, setUpdateState] = useState<UpdateCheckState>("idle");
|
||||
const updateInFlight = useRef(false);
|
||||
|
||||
const version = Constants.expoConfig?.version ?? "0.0.0";
|
||||
// Fall back to "production" to match resolveAppVariant in app.config.ts, so a
|
||||
@@ -590,30 +602,140 @@ function AppSettingsSection() {
|
||||
: null
|
||||
: null;
|
||||
|
||||
const busy =
|
||||
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
|
||||
|
||||
// "Up to date" is a transient acknowledgement, not a state worth persisting —
|
||||
// drop back to the bundle label so the row keeps answering "what am I running?".
|
||||
useEffect(() => {
|
||||
if (updateState !== "current") return;
|
||||
const timer = setTimeout(() => setUpdateState("idle"), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [updateState]);
|
||||
|
||||
const checkForUpdate = useCallback(async () => {
|
||||
// `disabled={busy}` only takes effect on the next render, so two taps in the
|
||||
// same frame would both get through. The ref closes that window.
|
||||
if (updateInFlight.current) return;
|
||||
updateInFlight.current = true;
|
||||
try {
|
||||
await runUpdateCheck(setUpdateState);
|
||||
} finally {
|
||||
updateInFlight.current = false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const statusLabel =
|
||||
updateState === "checking"
|
||||
? "Checking…"
|
||||
: updateState === "downloading"
|
||||
? "Downloading…"
|
||||
: updateState === "restarting"
|
||||
? "Restarting…"
|
||||
: updateState === "current"
|
||||
? "Up to date"
|
||||
: bundleLabel;
|
||||
|
||||
const versionRow = (
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
<SymbolView
|
||||
name="info.circle"
|
||||
size={22}
|
||||
tintColor={icon}
|
||||
type="monochrome"
|
||||
weight="regular"
|
||||
/>
|
||||
<Text className="flex-1 text-lg text-foreground">Version</Text>
|
||||
<View className="items-end">
|
||||
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
|
||||
{statusLabel ? (
|
||||
<Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{Updates.isEnabled ? (
|
||||
<View className="w-[22px] items-center">
|
||||
{busy ? (
|
||||
<ActivityIndicator color={icon} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="arrow.clockwise"
|
||||
size={18}
|
||||
tintColor={icon}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsSection title="App">
|
||||
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
|
||||
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
<SymbolView
|
||||
name="info.circle"
|
||||
size={22}
|
||||
tintColor={icon}
|
||||
type="monochrome"
|
||||
weight="regular"
|
||||
/>
|
||||
<Text className="flex-1 text-lg text-foreground">Version</Text>
|
||||
<View className="items-end">
|
||||
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
|
||||
{bundleLabel ? (
|
||||
<Text className="text-xs text-foreground-muted/70">{bundleLabel}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
{Updates.isEnabled ? (
|
||||
<Pressable
|
||||
accessibilityLabel="Check for updates"
|
||||
accessibilityRole="button"
|
||||
disabled={busy}
|
||||
onPress={() => void checkForUpdate()}
|
||||
>
|
||||
{versionRow}
|
||||
</Pressable>
|
||||
) : (
|
||||
versionRow
|
||||
)}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
async function runUpdateCheck(setUpdateState: (state: UpdateCheckState) => void): Promise<void> {
|
||||
setUpdateState("checking");
|
||||
const check = await settlePromise(() => Updates.checkForUpdateAsync());
|
||||
if (check._tag === "Failure") {
|
||||
reportUpdateFailure(check, "Could not check for updates.");
|
||||
setUpdateState("idle");
|
||||
return;
|
||||
}
|
||||
// A rollback directive (`eas update:rollback`) arrives as isAvailable: false
|
||||
// with isRollBackToEmbedded: true — there is nothing newer to install, but the
|
||||
// running OTA still has to be dropped for the embedded bundle.
|
||||
if (!check.value.isAvailable && !check.value.isRollBackToEmbedded) {
|
||||
setUpdateState("current");
|
||||
return;
|
||||
}
|
||||
|
||||
setUpdateState("downloading");
|
||||
const fetched = await settlePromise(() => Updates.fetchUpdateAsync());
|
||||
if (fetched._tag === "Failure") {
|
||||
reportUpdateFailure(fetched, "Could not download the update.");
|
||||
setUpdateState("idle");
|
||||
return;
|
||||
}
|
||||
// isNew is always false for a rollback, so it can't be the sole gate here either.
|
||||
if (!fetched.value.isNew && !fetched.value.isRollBackToEmbedded) {
|
||||
setUpdateState("current");
|
||||
return;
|
||||
}
|
||||
|
||||
setUpdateState("restarting");
|
||||
// reloadAsync never resolves on success — the JS context is torn down — so
|
||||
// reaching the failure branch below is the only way this returns.
|
||||
const reloaded = await settlePromise(() => Updates.reloadAsync());
|
||||
if (reloaded._tag === "Failure") {
|
||||
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.");
|
||||
setUpdateState("idle");
|
||||
}
|
||||
}
|
||||
|
||||
function reportUpdateFailure(result: AtomCommandResult<unknown, unknown>, fallback: string): void {
|
||||
reportAtomCommandResult(result, { label: "app update check" });
|
||||
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
|
||||
const error = squashAtomCommandFailure(result);
|
||||
Alert.alert("Update failed", error instanceof Error ? error.message : fallback);
|
||||
}
|
||||
|
||||
function capitalize(value: string): string {
|
||||
return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback } from "react";
|
||||
import { ScrollView } from "react-native";
|
||||
|
||||
import { CloudWaitlistEnrollment } from "../cloud/CloudWaitlistEnrollment";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
|
||||
export function SettingsWaitlistRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (!hasCloudPublicConfig()) {
|
||||
navigation.dispatch(StackActions.replace("Settings"));
|
||||
}
|
||||
}, [navigation]),
|
||||
);
|
||||
|
||||
return hasCloudPublicConfig() ? <ConfiguredSettingsWaitlistRouteScreen /> : null;
|
||||
}
|
||||
|
||||
function ConfiguredSettingsWaitlistRouteScreen() {
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { expand } = useClerkSettingsSheetDetent();
|
||||
const navigation = useNavigation();
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (isLoaded && isSignedIn) {
|
||||
navigation.dispatch(StackActions.replace("Settings"));
|
||||
}
|
||||
}, [isLoaded, isSignedIn, navigation]),
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ScrollView
|
||||
automaticallyAdjustKeyboardInsets
|
||||
contentContainerStyle={{
|
||||
paddingBottom: 32,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 12,
|
||||
}}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="interactive"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
<CloudWaitlistEnrollment
|
||||
onSignIn={() => {
|
||||
expand();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
}}
|
||||
/>
|
||||
</ScrollView>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,6 @@ 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";
|
||||
@@ -25,9 +24,9 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { usePendingNewTasks } 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,26 +62,21 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "./thread-list-items";
|
||||
import { ThreadListV2Row } from "./thread-list-v2-items";
|
||||
import { ThreadListV2PendingRow, ThreadListV2Row } from "./thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
|
||||
type ThreadListV2Item,
|
||||
type ThreadListV2ListItem,
|
||||
} from "./threadListV2";
|
||||
|
||||
/** The sidebar list serves both lists: v1 grouped items or, when the Thread
|
||||
List v2 beta is on, queued offline tasks, flat v2 rows, and a settled
|
||||
List v2 beta is on, flat v2 rows with queued tasks spliced in, and a settled
|
||||
"Show more" pager. */
|
||||
type SidebarListItem =
|
||||
| HomeListItem
|
||||
| {
|
||||
readonly type: "v2-pending-task";
|
||||
readonly key: string;
|
||||
readonly pendingTask: PendingNewTask;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
| { readonly type: "v2-thread"; readonly key: string; readonly item: ThreadListV2Item }
|
||||
| ThreadListV2ListItem
|
||||
| { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
|
||||
|
||||
/**
|
||||
@@ -196,10 +190,7 @@ function ThreadNavigationSidebarPane(
|
||||
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled =
|
||||
AsyncResult.isSuccess(preferencesResult) &&
|
||||
preferencesResult.value.threadListV2Enabled === true;
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -477,11 +468,11 @@ function ThreadNavigationSidebarPane(
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const listItems = useMemo<readonly SidebarListItem[]>(() => {
|
||||
if (!threadListV2Enabled) return listLayout.items;
|
||||
// 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.
|
||||
// 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.
|
||||
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
|
||||
const v2PendingTasks = pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
@@ -494,19 +485,10 @@ function ThreadNavigationSidebarPane(
|
||||
(v2SearchQuery.length === 0 ||
|
||||
pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
|
||||
);
|
||||
const items: SidebarListItem[] = v2PendingTasks.map((pendingTask, index) => ({
|
||||
type: "v2-pending-task" as const,
|
||||
key: `v2-pending:${pendingTask.message.messageId}`,
|
||||
pendingTask,
|
||||
isLast: index === v2PendingTasks.length - 1,
|
||||
}));
|
||||
for (const item of threadListV2Layout.items) {
|
||||
items.push({
|
||||
type: "v2-thread" as const,
|
||||
key: scopedThreadKey(item.thread.environmentId, item.thread.id),
|
||||
item,
|
||||
});
|
||||
}
|
||||
const items: SidebarListItem[] = buildThreadListV2ListItems({
|
||||
items: threadListV2Layout.items,
|
||||
pendingTasks: v2PendingTasks,
|
||||
});
|
||||
if (threadListV2Layout.hiddenSettledCount > 0) {
|
||||
items.push({
|
||||
type: "v2-show-more",
|
||||
@@ -694,13 +676,26 @@ 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, savedConnectionsById, serverConfigs],
|
||||
[
|
||||
props.selectedThreadKey,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
],
|
||||
);
|
||||
const sidebarItemsAreEqual = useCallback(
|
||||
(previous: SidebarListItem, item: SidebarListItem): boolean => {
|
||||
@@ -715,16 +710,19 @@ function ThreadNavigationSidebarPane(
|
||||
if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
|
||||
return previous.hiddenCount === item.hiddenCount;
|
||||
}
|
||||
if (previous.type === "v2-pending-task" && item.type === "v2-pending-task") {
|
||||
return previous.pendingTask === item.pendingTask && previous.isLast === item.isLast;
|
||||
if (previous.type === "v2-pending" && item.type === "v2-pending") {
|
||||
return (
|
||||
previous.pendingTask === item.pendingTask &&
|
||||
previous.showPendingDivider === item.showPendingDivider
|
||||
);
|
||||
}
|
||||
if (
|
||||
previous.type === "v2-thread" ||
|
||||
previous.type === "v2-show-more" ||
|
||||
previous.type === "v2-pending-task" ||
|
||||
previous.type === "v2-pending" ||
|
||||
item.type === "v2-thread" ||
|
||||
item.type === "v2-show-more" ||
|
||||
item.type === "v2-pending-task"
|
||||
item.type === "v2-pending"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -752,20 +750,29 @@ function ThreadNavigationSidebarPane(
|
||||
const renderListItem = useCallback(
|
||||
({ item }: { readonly item: SidebarListItem }) => {
|
||||
switch (item.type) {
|
||||
case "v2-pending-task":
|
||||
case "v2-pending": {
|
||||
const pendingScopeKey = scopedProjectKey(
|
||||
item.pendingTask.message.environmentId,
|
||||
item.pendingTask.creation.projectId,
|
||||
);
|
||||
return (
|
||||
<PendingTaskListRow
|
||||
variant="sidebar"
|
||||
<ThreadListV2PendingRow
|
||||
pendingTask={item.pendingTask}
|
||||
project={projectByKey.get(pendingScopeKey) ?? null}
|
||||
projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
|
||||
environmentLabel={
|
||||
savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
|
||||
null
|
||||
Object.keys(savedConnectionsById).length > 1
|
||||
? (savedConnectionsById[item.pendingTask.message.environmentId]
|
||||
?.environmentLabel ?? null)
|
||||
: null
|
||||
}
|
||||
isLast={item.isLast}
|
||||
pane="sidebar"
|
||||
showPendingDivider={item.showPendingDivider}
|
||||
onSelectPendingTask={openPendingTask}
|
||||
onDeletePendingTask={confirmDeletePendingTask}
|
||||
/>
|
||||
);
|
||||
}
|
||||
case "v2-thread": {
|
||||
const thread = item.item.thread;
|
||||
const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
|
||||
|
||||
@@ -14,6 +14,7 @@ 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";
|
||||
@@ -68,7 +69,9 @@ const LEGACY_MENU_ACTIONS: MenuAction[] = [
|
||||
/** Rounded-row radius shared with the v1 sidebar rows. */
|
||||
const SIDEBAR_V2_ROW_RADIUS = 12;
|
||||
|
||||
export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivider(props: {
|
||||
/** Section label + rule: the only structure in an otherwise flat list. */
|
||||
export const ThreadListV2SectionDivider = memo(function ThreadListV2SectionDivider(props: {
|
||||
readonly label: string;
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
}) {
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
@@ -79,12 +82,127 @@ export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivid
|
||||
props.pane === "sidebar" ? "px-3" : "px-5",
|
||||
)}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-tertiary">Settled</Text>
|
||||
<Text className="text-xs font-t3-medium text-foreground-tertiary">{props.label}</Text>
|
||||
<View className="h-px flex-1" style={{ backgroundColor: borderColor }} />
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
/**
|
||||
* A queued new task, in the same idiom as an active v2 row: it is work the
|
||||
* user wrote, so it reads like the threads it will become. "Queued" takes
|
||||
* the status slot — the state is the one thing that differs — and stays
|
||||
* uncolored because nothing is asked of the user; the environment is simply
|
||||
* not reachable yet.
|
||||
*/
|
||||
export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props: {
|
||||
readonly pendingTask: PendingNewTask;
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly projectTitle?: string;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
/** Draws the "Pending" divider above the first queued row. */
|
||||
readonly showPendingDivider: boolean;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
}) {
|
||||
const { pendingTask, onSelectPendingTask, onDeletePendingTask } = props;
|
||||
const drawerColor = useThemeColor("--color-drawer");
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const sidebarPane = props.pane === "sidebar";
|
||||
const projectTitle =
|
||||
props.projectTitle ?? props.project?.title ?? pendingTask.creation.projectTitle ?? "";
|
||||
const branch = pendingTask.creation.branch;
|
||||
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "delete") onDeletePendingTask(pendingTask);
|
||||
},
|
||||
[onDeletePendingTask, pendingTask],
|
||||
);
|
||||
|
||||
const rowContent = (
|
||||
<>
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
{props.project ? (
|
||||
<ProjectFavicon
|
||||
environmentId={pendingTask.message.environmentId}
|
||||
size={15}
|
||||
projectTitle={projectTitle}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
<Text className="flex-1 text-sm font-t3-medium text-foreground-muted" numberOfLines={1}>
|
||||
{projectTitle}
|
||||
</Text>
|
||||
<Text className="text-xs text-foreground-tertiary">Queued</Text>
|
||||
</View>
|
||||
{/* One line, unlike the two an active row allows: a queued title is
|
||||
derived from the whole prompt rather than written as a title, so the
|
||||
second line is usually a stray word or emoji rather than meaning. */}
|
||||
<Text className="mt-1 text-base font-t3-medium text-foreground" numberOfLines={1}>
|
||||
{pendingTask.title}
|
||||
</Text>
|
||||
{branch || props.environmentLabel ? (
|
||||
<Text className="mt-1 text-xs text-foreground-muted" numberOfLines={1}>
|
||||
{branch ? (
|
||||
<Text className="text-xs text-foreground-muted" style={{ fontFamily: MONO_FONT }}>
|
||||
{branch}
|
||||
</Text>
|
||||
) : null}
|
||||
{branch && props.environmentLabel ? " · " : null}
|
||||
{props.environmentLabel ? (
|
||||
<Text className="text-xs text-foreground-tertiary">{props.environmentLabel}</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{props.showPendingDivider ? (
|
||||
<ThreadListV2SectionDivider label="Pending" pane={props.pane} />
|
||||
) : null}
|
||||
<ControlPillMenu
|
||||
actions={PENDING_TASK_MENU_ACTIONS}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
>
|
||||
<Pressable
|
||||
accessibilityHint="Opens the queued task for editing"
|
||||
accessibilityLabel={pendingTask.title}
|
||||
accessibilityRole="button"
|
||||
onPress={() => onSelectPendingTask(pendingTask)}
|
||||
style={
|
||||
sidebarPane
|
||||
? ({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackgroundColor : drawerColor,
|
||||
borderRadius: SIDEBAR_V2_ROW_RADIUS,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 10,
|
||||
})
|
||||
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
|
||||
}
|
||||
>
|
||||
{sidebarPane ? (
|
||||
rowContent
|
||||
) : (
|
||||
<View className="bg-screen">
|
||||
<View className="px-5 py-2.5">{rowContent}</View>
|
||||
<View className="ml-5 h-px bg-border-subtle" />
|
||||
</View>
|
||||
)}
|
||||
</Pressable>
|
||||
</ControlPillMenu>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
@@ -423,7 +541,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
|
||||
return (
|
||||
<>
|
||||
{props.showSettledDivider ? <ThreadListV2SettledDivider pane={props.pane} /> : null}
|
||||
{props.showSettledDivider ? (
|
||||
<ThreadListV2SectionDivider label="Settled" pane={props.pane} />
|
||||
) : null}
|
||||
<ThreadSwipeable
|
||||
backgroundColor={sidebarPane ? drawerColor : screenColor}
|
||||
compactActions={variant === "slim"}
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
resolveThreadListV2Enabled,
|
||||
resolveThreadListV2Status,
|
||||
sortThreadsForListV2,
|
||||
} from "./threadListV2";
|
||||
@@ -38,6 +49,25 @@ 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({
|
||||
@@ -320,3 +350,88 @@ describe("buildThreadListV2Items settled paging", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
function makePendingTask(id: string): PendingNewTask {
|
||||
return {
|
||||
message: {
|
||||
environmentId,
|
||||
threadId: ThreadId.make(`thread-${id}`),
|
||||
messageId: MessageId.make(id),
|
||||
commandId: CommandId.make(`command-${id}`),
|
||||
text: id,
|
||||
attachments: [],
|
||||
createdAt: NOW,
|
||||
creation: {
|
||||
projectId: ProjectId.make("project-1"),
|
||||
workspaceMode: "worktree",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
creation: {
|
||||
projectId: ProjectId.make("project-1"),
|
||||
workspaceMode: "worktree",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
title: id,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildThreadListV2ListItems", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "settled",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
it("splices queued tasks between the active block and the settled tail", () => {
|
||||
const items = buildThreadListV2ListItems({
|
||||
items: layout.items,
|
||||
pendingTasks: [makePendingTask("queued-1"), makePendingTask("queued-2")],
|
||||
});
|
||||
|
||||
expect(
|
||||
items.map((item) =>
|
||||
item.type === "v2-pending" ? item.pendingTask.title : item.item.thread.id,
|
||||
),
|
||||
).toEqual(["active", "queued-1", "queued-2", "settled"]);
|
||||
// Only the leading queued row labels the section, exactly like Settled.
|
||||
expect(
|
||||
items.filter((item) => item.type === "v2-pending" && item.showPendingDivider),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("ends the list with queued tasks when nothing has settled yet", () => {
|
||||
const activeOnly = buildThreadListV2Items({
|
||||
threads: [makeThread({ id: ThreadId.make("active"), title: "active" })],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
const items = buildThreadListV2ListItems({
|
||||
items: activeOnly.items,
|
||||
pendingTasks: [makePendingTask("queued-1")],
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.type)).toEqual(["v2-thread", "v2-pending"]);
|
||||
});
|
||||
|
||||
it("leaves the thread order untouched when nothing is queued", () => {
|
||||
const items = buildThreadListV2ListItems({ items: layout.items, pendingTasks: [] });
|
||||
|
||||
expect(items.map((item) => item.key)).toEqual([
|
||||
`v2-thread:${environmentId}:active`,
|
||||
`v2-thread:${environmentId}:settled`,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/stat
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
|
||||
/**
|
||||
* Thread List v2 model, ported from the web sidebar v2
|
||||
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
|
||||
@@ -18,6 +20,26 @@ 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 {
|
||||
@@ -93,6 +115,60 @@ export interface ThreadListV2Layout {
|
||||
readonly nextSnoozeWakeAt: string | null;
|
||||
}
|
||||
|
||||
export interface ThreadListV2ThreadListItem {
|
||||
readonly type: "v2-thread";
|
||||
readonly key: string;
|
||||
readonly item: ThreadListV2Item;
|
||||
}
|
||||
|
||||
export interface ThreadListV2PendingListItem {
|
||||
readonly type: "v2-pending";
|
||||
readonly key: string;
|
||||
readonly pendingTask: PendingNewTask;
|
||||
/** First queued row after the active block draws the PENDING divider. */
|
||||
readonly showPendingDivider: boolean;
|
||||
}
|
||||
|
||||
export type ThreadListV2ListItem = ThreadListV2ThreadListItem | ThreadListV2PendingListItem;
|
||||
|
||||
/**
|
||||
* Splices queued tasks between the active block and the settled tail, so the
|
||||
* list reads active → pending → settled. Queued work sits below the live
|
||||
* threads because nothing can happen to it until its environment returns:
|
||||
* it is waiting, not asking. Shared by the compact Home list and the iPad
|
||||
* sidebar so both order and label the sections identically.
|
||||
*/
|
||||
export function buildThreadListV2ListItems(input: {
|
||||
readonly items: ReadonlyArray<ThreadListV2Item>;
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
}): ThreadListV2ListItem[] {
|
||||
const threadItems = input.items.map(
|
||||
(item): ThreadListV2ListItem => ({
|
||||
type: "v2-thread",
|
||||
key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
|
||||
item,
|
||||
}),
|
||||
);
|
||||
if (input.pendingTasks.length === 0) return threadItems;
|
||||
|
||||
const pendingItems = input.pendingTasks.map(
|
||||
(pendingTask, index): ThreadListV2ListItem => ({
|
||||
type: "v2-pending",
|
||||
key: `v2-pending:${pendingTask.message.messageId}`,
|
||||
pendingTask,
|
||||
showPendingDivider: index === 0,
|
||||
}),
|
||||
);
|
||||
// The settled tail begins at the row that draws the SETTLED divider; with
|
||||
// no settled rows the queued block simply ends the list.
|
||||
const settledStart = threadItems.findIndex(
|
||||
(entry) => entry.type === "v2-thread" && entry.item.showSettledDivider,
|
||||
);
|
||||
return settledStart === -1
|
||||
? [...threadItems, ...pendingItems]
|
||||
: [...threadItems.slice(0, settledStart), ...pendingItems, ...threadItems.slice(settledStart)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Partitions visible threads into the active card block (creation order) and
|
||||
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
type Listener = (payload: Record<string, unknown>) => void;
|
||||
const nativeListeners = new Map<string, Listener>();
|
||||
const calls: Array<{ method: string; args: unknown[] }> = [];
|
||||
let platformOS = "ios";
|
||||
let moduleAvailable = true;
|
||||
|
||||
const nativeModule = {
|
||||
connect: (...args: unknown[]) => calls.push({ method: "connect", args }),
|
||||
sendText: (...args: unknown[]) => calls.push({ method: "sendText", args }),
|
||||
sendBinary: (...args: unknown[]) => calls.push({ method: "sendBinary", args }),
|
||||
close: (...args: unknown[]) => calls.push({ method: "close", args }),
|
||||
addListener: (eventName: string, listener: Listener) => {
|
||||
nativeListeners.set(eventName, listener);
|
||||
return { remove: () => nativeListeners.delete(eventName) };
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
calls,
|
||||
nativeListeners,
|
||||
emit: (eventName: string, payload: Record<string, unknown>) => {
|
||||
nativeListeners.get(eventName)?.(payload);
|
||||
},
|
||||
setPlatform: (os: string) => {
|
||||
platformOS = os;
|
||||
},
|
||||
setModuleAvailable: (available: boolean) => {
|
||||
moduleAvailable = available;
|
||||
},
|
||||
getPlatform: () => platformOS,
|
||||
getModule: () => (moduleAvailable ? nativeModule : null),
|
||||
// Native listeners intentionally survive reset: the wrapper attaches them
|
||||
// once per app lifetime, so clearing them here would not match production.
|
||||
reset: () => {
|
||||
calls.length = 0;
|
||||
platformOS = "ios";
|
||||
moduleAvailable = true;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-native", () => ({
|
||||
Platform: {
|
||||
get OS() {
|
||||
return mocks.getPlatform();
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("expo", () => ({
|
||||
requireOptionalNativeModule: () => mocks.getModule(),
|
||||
}));
|
||||
|
||||
import { loadNativeWebSocketConstructor } from "./nativeWebSocket";
|
||||
|
||||
async function openSocket() {
|
||||
const construct = await loadNativeWebSocketConstructor();
|
||||
expect(construct).not.toBeNull();
|
||||
return construct!("wss://example.test/ws");
|
||||
}
|
||||
|
||||
function lastCall(method: string) {
|
||||
const entries = mocks.calls.filter((call) => call.method === method);
|
||||
return entries[entries.length - 1];
|
||||
}
|
||||
|
||||
function connectionIdOf(socket: WebSocket): number {
|
||||
void socket;
|
||||
return lastCall("connect")!.args[0] as number;
|
||||
}
|
||||
|
||||
describe("nativeWebSocketConstructor", () => {
|
||||
beforeEach(() => {
|
||||
mocks.reset();
|
||||
});
|
||||
|
||||
it("resolves null on Android and when the native module is missing", async () => {
|
||||
mocks.setPlatform("android");
|
||||
expect(await loadNativeWebSocketConstructor()).toBeNull();
|
||||
|
||||
mocks.setPlatform("ios");
|
||||
mocks.setModuleAvailable(false);
|
||||
expect(await loadNativeWebSocketConstructor()).toBeNull();
|
||||
});
|
||||
|
||||
it("connects and transitions readyState on open", async () => {
|
||||
const socket = await openSocket();
|
||||
const id = connectionIdOf(socket);
|
||||
expect(lastCall("connect")!.args).toEqual([id, "wss://example.test/ws", []]);
|
||||
expect(socket.readyState).toBe(0);
|
||||
|
||||
const opened = vi.fn();
|
||||
socket.addEventListener("open", opened, { once: true });
|
||||
mocks.emit("onOpen", { id });
|
||||
expect(socket.readyState).toBe(1);
|
||||
expect(opened).toHaveBeenCalledTimes(1);
|
||||
|
||||
// `once` listeners must not fire again.
|
||||
mocks.emit("onOpen", { id });
|
||||
expect(opened).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("delivers text messages as strings and binary messages as bytes", async () => {
|
||||
const socket = await openSocket();
|
||||
const id = connectionIdOf(socket);
|
||||
const received: unknown[] = [];
|
||||
socket.addEventListener("message", (event) => {
|
||||
received.push((event as { data: unknown }).data);
|
||||
});
|
||||
|
||||
mocks.emit("onMessage", { id, data: "hello", binary: false });
|
||||
mocks.emit("onMessage", { id, data: btoa("\x01\x02\x03"), binary: true });
|
||||
|
||||
expect(received[0]).toBe("hello");
|
||||
expect(received[1]).toBeInstanceOf(Uint8Array);
|
||||
expect([...(received[1] as Uint8Array)]).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("sends binary data base64-encoded and strings as text", async () => {
|
||||
const socket = await openSocket();
|
||||
const id = connectionIdOf(socket);
|
||||
|
||||
socket.send("ping");
|
||||
expect(lastCall("sendText")!.args).toEqual([id, "ping"]);
|
||||
|
||||
socket.send(new Uint8Array([1, 2, 3]));
|
||||
expect(lastCall("sendBinary")!.args).toEqual([id, btoa("\x01\x02\x03")]);
|
||||
});
|
||||
|
||||
it("dispatches close once and routes messages by connection id", async () => {
|
||||
const first = await openSocket();
|
||||
const firstId = connectionIdOf(first);
|
||||
const second = await openSocket();
|
||||
const secondId = connectionIdOf(second);
|
||||
expect(firstId).not.toBe(secondId);
|
||||
|
||||
const firstClosed = vi.fn();
|
||||
const secondClosed = vi.fn();
|
||||
first.addEventListener("close", firstClosed);
|
||||
second.addEventListener("close", secondClosed);
|
||||
|
||||
mocks.emit("onClose", { id: firstId, code: 1000, reason: "done" });
|
||||
mocks.emit("onClose", { id: firstId, code: 1000, reason: "done" });
|
||||
|
||||
expect(firstClosed).toHaveBeenCalledTimes(1);
|
||||
expect(first.readyState).toBe(3);
|
||||
expect(secondClosed).not.toHaveBeenCalled();
|
||||
expect(second.readyState).toBe(0);
|
||||
});
|
||||
|
||||
it("close() is idempotent and forwards code and reason", async () => {
|
||||
const socket = await openSocket();
|
||||
const id = connectionIdOf(socket);
|
||||
|
||||
socket.close(4000, "bye");
|
||||
socket.close(4000, "bye");
|
||||
|
||||
const closeCalls = mocks.calls.filter((call) => call.method === "close");
|
||||
expect(closeCalls).toHaveLength(1);
|
||||
expect(closeCalls[0]!.args).toEqual([id, 4000, "bye"]);
|
||||
expect(socket.readyState).toBe(2);
|
||||
});
|
||||
|
||||
it("ignores a native open that lands after close", async () => {
|
||||
const socket = await openSocket();
|
||||
const id = connectionIdOf(socket);
|
||||
const opened = vi.fn();
|
||||
socket.addEventListener("open", opened);
|
||||
|
||||
// Effect closes while still CONNECTING (open timeout or scope teardown);
|
||||
// the in-flight native connect can still report success afterwards.
|
||||
socket.close(1000, "");
|
||||
mocks.emit("onOpen", { id });
|
||||
|
||||
expect(opened).not.toHaveBeenCalled();
|
||||
expect(socket.readyState).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,226 @@
|
||||
import { Platform } from "react-native";
|
||||
|
||||
// URLSession-backed WebSocket for iOS. React Native's built-in WebSocket uses
|
||||
// SocketRocket on iOS, which never offers permessage-deflate, so server frames
|
||||
// arrive uncompressed. URLSessionWebSocketTask offers the extension by default.
|
||||
// Android needs none of this: React Native's OkHttp-backed WebSocket already
|
||||
// negotiates permessage-deflate on its own.
|
||||
//
|
||||
// Only the surface Effect's `Socket.fromWebSocket` drives is implemented:
|
||||
// addEventListener/removeEventListener for open/message/close/error (with
|
||||
// `once` support), `readyState`, `send`, and `close`.
|
||||
|
||||
interface NativeEventSubscription {
|
||||
remove(): void;
|
||||
}
|
||||
|
||||
interface T3WebSocketNativeModule {
|
||||
connect(id: number, url: string, protocols: string[]): void;
|
||||
sendText(id: number, text: string): void;
|
||||
sendBinary(id: number, base64: string): void;
|
||||
close(id: number, code: number, reason: string): void;
|
||||
addListener(
|
||||
eventName: "onOpen" | "onMessage" | "onClose" | "onError",
|
||||
listener: (payload: {
|
||||
id: number;
|
||||
data?: string;
|
||||
binary?: boolean;
|
||||
code?: number;
|
||||
reason?: string;
|
||||
message?: string;
|
||||
}) => void,
|
||||
): NativeEventSubscription;
|
||||
}
|
||||
|
||||
type NativeWebSocketEventType = "open" | "message" | "close" | "error";
|
||||
|
||||
interface ListenerEntry {
|
||||
readonly listener: (event: unknown) => void;
|
||||
readonly once: boolean;
|
||||
}
|
||||
|
||||
const activeSockets = new Map<number, NativeWebSocket>();
|
||||
let nextSocketId = 1;
|
||||
let nativeListenersAttached = false;
|
||||
|
||||
function attachNativeListeners(module: T3WebSocketNativeModule) {
|
||||
if (nativeListenersAttached) {
|
||||
return;
|
||||
}
|
||||
nativeListenersAttached = true;
|
||||
module.addListener("onOpen", (payload) => {
|
||||
activeSockets.get(payload.id)?.handleOpen();
|
||||
});
|
||||
module.addListener("onMessage", (payload) => {
|
||||
activeSockets.get(payload.id)?.handleMessage(payload.data ?? "", payload.binary === true);
|
||||
});
|
||||
module.addListener("onClose", (payload) => {
|
||||
activeSockets.get(payload.id)?.handleClose(payload.code ?? 1006, payload.reason ?? "");
|
||||
});
|
||||
module.addListener("onError", (payload) => {
|
||||
activeSockets.get(payload.id)?.handleError(payload.message ?? "WebSocket error");
|
||||
});
|
||||
}
|
||||
|
||||
function base64ToUint8Array(base64: string): Uint8Array {
|
||||
const binary = atob(base64);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes: Uint8Array): string {
|
||||
let binary = "";
|
||||
const chunkSize = 8192;
|
||||
for (let index = 0; index < bytes.length; index += chunkSize) {
|
||||
binary += String.fromCharCode(...bytes.subarray(index, index + chunkSize));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
class NativeWebSocket {
|
||||
static readonly CONNECTING = 0;
|
||||
static readonly OPEN = 1;
|
||||
static readonly CLOSING = 2;
|
||||
static readonly CLOSED = 3;
|
||||
|
||||
readyState: number = NativeWebSocket.CONNECTING;
|
||||
|
||||
private readonly id: number;
|
||||
private readonly module: T3WebSocketNativeModule;
|
||||
private readonly listeners = new Map<NativeWebSocketEventType, Set<ListenerEntry>>();
|
||||
|
||||
constructor(module: T3WebSocketNativeModule, url: string, protocols?: string | Array<string>) {
|
||||
this.module = module;
|
||||
this.id = nextSocketId++;
|
||||
activeSockets.set(this.id, this);
|
||||
attachNativeListeners(module);
|
||||
const protocolList =
|
||||
typeof protocols === "string" ? [protocols] : protocols ? [...protocols] : [];
|
||||
try {
|
||||
module.connect(this.id, url, protocolList);
|
||||
} catch (error) {
|
||||
activeSockets.delete(this.id);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
addEventListener(
|
||||
type: NativeWebSocketEventType,
|
||||
listener: (event: unknown) => void,
|
||||
options?: { once?: boolean },
|
||||
): void {
|
||||
let entries = this.listeners.get(type);
|
||||
if (!entries) {
|
||||
entries = new Set();
|
||||
this.listeners.set(type, entries);
|
||||
}
|
||||
entries.add({ listener, once: options?.once === true });
|
||||
}
|
||||
|
||||
removeEventListener(type: NativeWebSocketEventType, listener: (event: unknown) => void): void {
|
||||
const entries = this.listeners.get(type);
|
||||
if (!entries) {
|
||||
return;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.listener === listener) {
|
||||
entries.delete(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
send(data: string | Uint8Array | ArrayBuffer): void {
|
||||
if (typeof data === "string") {
|
||||
this.module.sendText(this.id, data);
|
||||
return;
|
||||
}
|
||||
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
|
||||
this.module.sendBinary(this.id, bytesToBase64(bytes));
|
||||
}
|
||||
|
||||
close(code?: number, reason?: string): void {
|
||||
if (this.readyState === NativeWebSocket.CLOSING || this.readyState === NativeWebSocket.CLOSED) {
|
||||
return;
|
||||
}
|
||||
this.readyState = NativeWebSocket.CLOSING;
|
||||
this.module.close(this.id, code ?? 1000, reason ?? "");
|
||||
}
|
||||
|
||||
handleOpen(): void {
|
||||
// `close()` during CONNECTING (an Effect open-timeout or scope teardown)
|
||||
// leaves a native connect in flight, so its `didOpen` can still land. Only
|
||||
// a socket that is still connecting may transition to OPEN; otherwise the
|
||||
// close would be silently undone and open handlers would fire on a socket
|
||||
// the caller already gave up on.
|
||||
if (this.readyState !== NativeWebSocket.CONNECTING) {
|
||||
return;
|
||||
}
|
||||
this.readyState = NativeWebSocket.OPEN;
|
||||
this.dispatch("open", { type: "open" });
|
||||
}
|
||||
|
||||
handleMessage(data: string, binary: boolean): void {
|
||||
this.dispatch("message", {
|
||||
type: "message",
|
||||
data: binary ? base64ToUint8Array(data) : data,
|
||||
});
|
||||
}
|
||||
|
||||
handleClose(code: number, reason: string): void {
|
||||
if (this.readyState === NativeWebSocket.CLOSED) {
|
||||
return;
|
||||
}
|
||||
this.readyState = NativeWebSocket.CLOSED;
|
||||
activeSockets.delete(this.id);
|
||||
this.dispatch("close", { type: "close", code, reason });
|
||||
}
|
||||
|
||||
handleError(message: string): void {
|
||||
this.dispatch("error", new Error(message));
|
||||
}
|
||||
|
||||
private dispatch(type: NativeWebSocketEventType, event: unknown): void {
|
||||
const entries = this.listeners.get(type);
|
||||
if (!entries) {
|
||||
return;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.once) {
|
||||
entries.delete(entry);
|
||||
}
|
||||
entry.listener(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the WebSocket constructor backed by URLSessionWebSocketTask, resolving
|
||||
* `null` when unavailable (Android, or an iOS binary predating the native
|
||||
* module). Callers fall back to the global WebSocket.
|
||||
*
|
||||
* Async because "expo" is imported lazily: its module-scope setup code assumes
|
||||
* a React Native environment, and this file's importer (runtime.ts) sits in
|
||||
* many test import chains.
|
||||
*/
|
||||
export async function loadNativeWebSocketConstructor(): Promise<
|
||||
((url: string, protocols?: string | Array<string>) => globalThis.WebSocket) | null
|
||||
> {
|
||||
if (Platform.OS !== "ios") {
|
||||
return null;
|
||||
}
|
||||
let module: T3WebSocketNativeModule | null;
|
||||
try {
|
||||
const expo = await import("expo");
|
||||
module = expo.requireOptionalNativeModule<T3WebSocketNativeModule>("T3WebSocket");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!module) {
|
||||
return null;
|
||||
}
|
||||
return (url, protocols) =>
|
||||
new NativeWebSocket(module, url, protocols) as unknown as globalThis.WebSocket;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as Socket from "effect/unstable/socket/Socket";
|
||||
@@ -9,6 +10,7 @@ import { managedRelayClientLayer } from "../features/cloud/managedRelayLayer";
|
||||
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
|
||||
import { tracingLayer } from "../features/observability/tracing";
|
||||
import * as Persistence from "../persistence/layer";
|
||||
import { loadNativeWebSocketConstructor } from "./nativeWebSocket";
|
||||
|
||||
function configuredRelayUrl(): string {
|
||||
return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";
|
||||
@@ -16,6 +18,19 @@ function configuredRelayUrl(): string {
|
||||
|
||||
const httpClientLayer = remoteHttpClientLayer(fetch);
|
||||
|
||||
// iOS swaps in a URLSessionWebSocketTask-backed constructor so the socket
|
||||
// negotiates permessage-deflate (SocketRocket, behind the global WebSocket,
|
||||
// cannot). Android's global WebSocket (OkHttp) already negotiates it.
|
||||
const webSocketConstructorLayer: Layer.Layer<Socket.WebSocketConstructor> = Layer.unwrap(
|
||||
Effect.promise(loadNativeWebSocketConstructor).pipe(
|
||||
Effect.map((nativeConstructor) =>
|
||||
nativeConstructor === null
|
||||
? Socket.layerWebSocketConstructorGlobal
|
||||
: Layer.succeed(Socket.WebSocketConstructor, nativeConstructor),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
type RuntimeLayerSource =
|
||||
| ReturnType<typeof managedRelayClientLayer>
|
||||
| typeof Socket.layerWebSocketConstructorGlobal
|
||||
@@ -26,7 +41,7 @@ type RuntimeLayerSource =
|
||||
|
||||
const runtimeLayer = Layer.merge(
|
||||
managedRelayClientLayer(configuredRelayUrl()),
|
||||
Socket.layerWebSocketConstructorGlobal,
|
||||
webSocketConstructorLayer,
|
||||
).pipe(
|
||||
Layer.provideMerge(cryptoLayer),
|
||||
Layer.provideMerge(httpClientLayer),
|
||||
|
||||
@@ -46,6 +46,7 @@ const MobileDatabaseOperation = Schema.Literals([
|
||||
"load-cache",
|
||||
"save-cache",
|
||||
"remove-cache",
|
||||
"clear-cache-kind",
|
||||
"clear-environment-cache",
|
||||
"clear-all-caches",
|
||||
"inspect-caches",
|
||||
@@ -203,6 +204,10 @@ 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>;
|
||||
@@ -322,6 +327,17 @@ 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: () =>
|
||||
@@ -392,6 +408,7 @@ function makeUnavailable(error: MobileDatabaseError): MobileDatabase["Service"]
|
||||
loadCache: () => fail,
|
||||
saveCache: () => fail,
|
||||
removeCache: () => fail,
|
||||
clearCacheKind: () => fail,
|
||||
clearEnvironmentCache: () => fail,
|
||||
clearAllCaches: fail,
|
||||
inspectCaches: fail,
|
||||
|
||||
@@ -25,8 +25,9 @@ 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 into per
|
||||
* device.
|
||||
* 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`.
|
||||
*/
|
||||
readonly threadListV2Enabled?: boolean;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.29",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -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 });
|
||||
const result = yield* gitCore.listRefs({ cwd, refresh: true });
|
||||
const localBranch = result.refs.find(
|
||||
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { describe } from "vite-plus/test";
|
||||
|
||||
import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import { cast } from "effect/Function";
|
||||
import {
|
||||
Headers,
|
||||
HttpBody,
|
||||
HttpClient,
|
||||
HttpClientResponse,
|
||||
@@ -29,6 +30,7 @@ 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,
|
||||
@@ -42,6 +44,73 @@ 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* () {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
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)),
|
||||
);
|
||||
@@ -0,0 +1,36 @@
|
||||
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,6 +201,52 @@ 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 {
|
||||
@@ -208,7 +254,9 @@ export function projectThreadDetailSnapshot(
|
||||
...snapshot,
|
||||
thread: {
|
||||
...snapshot.thread,
|
||||
activities: snapshot.thread.activities.map(projectActivityPayload),
|
||||
activities: dropStaleContextWindowActivities(snapshot.thread.activities).map(
|
||||
projectActivityPayload,
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -72,6 +72,7 @@ import { vi } from "vite-plus/test";
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts";
|
||||
import { makeRoutesLayer } from "./server.ts";
|
||||
import { resolveAvailableEditorsForConfig } from "./ws.ts";
|
||||
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
|
||||
@@ -815,6 +816,7 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provideMerge(ServerSecretStore.layer),
|
||||
Layer.provide(workspaceAndProjectServicesLayer),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
Layer.provide(HttpResponseCompression.layerNode),
|
||||
Layer.provide(layerConfig),
|
||||
);
|
||||
|
||||
@@ -1287,6 +1289,35 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("compresses large JSON responses through the composed routes", () =>
|
||||
Effect.gen(function* () {
|
||||
const descriptor = {
|
||||
...testEnvironmentDescriptor,
|
||||
label: "Test environment".repeat(100),
|
||||
};
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
serverEnvironment: {
|
||||
getDescriptor: Effect.succeed(descriptor),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const url = yield* getHttpServerUrl("/.well-known/t3/environment");
|
||||
const response = yield* fetchEffect(url, {
|
||||
headers: {
|
||||
"accept-encoding": "gzip",
|
||||
},
|
||||
});
|
||||
const body = yield* responseJsonEffect<typeof descriptor>(response);
|
||||
|
||||
assert.equal(response.status, 200);
|
||||
assert.equal(response.headers["content-encoding"], "gzip");
|
||||
assert.equal(response.headers.vary, "Accept-Encoding");
|
||||
assert.deepEqual(body, descriptor);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("includes CORS headers on public environment descriptor responses", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
@@ -3081,6 +3112,34 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("negotiates permessage-deflate with clients that offer it", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const { cookie, url } = parseSessionCookieFromWsUrl(yield* getWsServerUrl("/ws"));
|
||||
const openSocket = (perMessageDeflate: boolean) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.callback<NodeSocket.NodeWS.WebSocket, Error>((resume) => {
|
||||
const socket = new NodeSocket.NodeWS.WebSocket(url, {
|
||||
perMessageDeflate,
|
||||
...(cookie ? { headers: { cookie } } : {}),
|
||||
});
|
||||
socket.on("open", () => resume(Effect.succeed(socket)));
|
||||
socket.on("error", (error) => resume(Effect.fail(error)));
|
||||
}),
|
||||
(socket) => Effect.sync(() => socket.close()),
|
||||
);
|
||||
|
||||
const compressed = yield* openSocket(true);
|
||||
// The ws client records the negotiated extension only when the server's
|
||||
// 101 response accepted the offer.
|
||||
assert.include(compressed.extensions, "permessage-deflate");
|
||||
|
||||
const plain = yield* openSocket(false);
|
||||
assert.notInclude(plain.extensions, "permessage-deflate");
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("issues short-lived websocket tickets for authenticated bearer sessions", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
@@ -5633,15 +5692,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
),
|
||||
);
|
||||
assert.equal(fullDiffResult.diff, "full-diff");
|
||||
|
||||
const replayResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.replayEvents]({
|
||||
fromSequenceExclusive: 0,
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(replayResult, []);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
@@ -6304,73 +6354,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("enriches replayed project events with repository identity metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/t3tools/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:T3Tools/t3code.git",
|
||||
},
|
||||
displayName: "T3Tools/t3code",
|
||||
provider: "github",
|
||||
owner: "T3Tools",
|
||||
name: "t3code",
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
readEvents: (_fromSequenceExclusive) =>
|
||||
Stream.make({
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: defaultProjectId,
|
||||
occurredAt: "2026-04-05T00:00:00.000Z",
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "project.created",
|
||||
payload: {
|
||||
projectId: defaultProjectId,
|
||||
title: "Default Project",
|
||||
workspaceRoot: "/tmp/default-project",
|
||||
defaultModelSelection,
|
||||
scripts: [],
|
||||
createdAt: "2026-04-05T00:00:00.000Z",
|
||||
updatedAt: "2026-04-05T00:00:00.000Z",
|
||||
},
|
||||
} satisfies Extract<OrchestrationEvent, { type: "project.created" }>),
|
||||
},
|
||||
repositoryIdentityResolver: {
|
||||
resolve: () => Effect.succeed(repositoryIdentity),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const replayResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.replayEvents]({
|
||||
fromSequenceExclusive: 0,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const replayedEvent = replayResult[0];
|
||||
assert.equal(replayedEvent?.type, "project.created");
|
||||
assert.deepEqual(
|
||||
replayedEvent && replayedEvent.type === "project.created"
|
||||
? replayedEvent.payload.repositoryIdentity
|
||||
: null,
|
||||
repositoryIdentity,
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("stops the provider session and closes thread terminals after archive", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive");
|
||||
|
||||
@@ -5,12 +5,14 @@ import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts";
|
||||
import {
|
||||
otlpTracesProxyRouteLayer,
|
||||
assetRouteLayer,
|
||||
serverEnvironmentHttpApiLayer,
|
||||
staticAndDevRouteLayer,
|
||||
browserApiCorsLayer,
|
||||
httpCompressionLayer,
|
||||
} from "./http.ts";
|
||||
import { fixPath } from "./os-jank.ts";
|
||||
import { websocketRpcRouteLayer } from "./ws.ts";
|
||||
@@ -150,6 +152,9 @@ const HttpServerLive = Layer.unwrap(
|
||||
}),
|
||||
);
|
||||
|
||||
const HttpResponseCompressionLive =
|
||||
typeof Bun !== "undefined" ? HttpResponseCompression.layerBun : HttpResponseCompression.layerNode;
|
||||
|
||||
const PlatformServicesLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
if (typeof Bun !== "undefined") {
|
||||
@@ -372,6 +377,7 @@ export const makeRoutesLayer = Layer.mergeAll(
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
Layer.provide(ServerSelfUpdate.layer),
|
||||
Layer.provide(browserApiCorsLayer),
|
||||
Layer.provide(httpCompressionLayer),
|
||||
);
|
||||
|
||||
export const makeServerLayer = Layer.unwrap(
|
||||
@@ -514,6 +520,7 @@ export const makeServerLayer = Layer.unwrap(
|
||||
return serverApplicationLayer.pipe(
|
||||
Layer.provideMerge(RuntimeServicesLive),
|
||||
Layer.provideMerge(serverRelayBrokerTracingLayer),
|
||||
Layer.provideMerge(HttpResponseCompressionLive),
|
||||
Layer.provideMerge(HttpServerLive),
|
||||
Layer.provide(ObservabilityLive),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it, describe } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts";
|
||||
import { makeGitVcsDriverCore, splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts";
|
||||
import * as GitVcsDriver from "./GitVcsDriver.ts";
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
@@ -38,6 +42,21 @@ const makeNonRepositoryHandle = () =>
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
|
||||
const makeSuccessfulHandle = (stdout: string) =>
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.encodeText(Stream.make(stdout)),
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
|
||||
const makeTmpDir = (
|
||||
prefix = "git-vcs-driver-test-",
|
||||
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> =>
|
||||
@@ -129,11 +148,434 @@ it.effect("uses stable diagnostics for every parsed non-repository command", ()
|
||||
assert.deepStrictEqual(commands, [
|
||||
{ args: ["status", "--porcelain=2", "--branch"], lcAll: "C" },
|
||||
{ args: ["rev-parse", "--abbrev-ref", "HEAD"], lcAll: "C" },
|
||||
{ args: ["branch", "--no-color", "--no-column"], lcAll: "C" },
|
||||
{ args: ["rev-parse", "--git-common-dir"], lcAll: "C" },
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("coalesces concurrent ref pages into one repository snapshot", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const spawnedArgs = yield* Ref.make<ReadonlyArray<ReadonlyArray<string>>>([]);
|
||||
const firstWorktreeScanStarted = yield* Deferred.make<void>();
|
||||
const remoteNamesScanCompleted = yield* Deferred.make<void>();
|
||||
const delayFirstWorktreeScan = yield* Ref.make(true);
|
||||
const countingSpawner = ChildProcessSpawner.make((command) =>
|
||||
Effect.gen(function* () {
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
return yield* Effect.die("expected a standard Git command");
|
||||
}
|
||||
yield* Ref.update(spawnedArgs, (current) => [...current, command.args]);
|
||||
const isWorktreeScan =
|
||||
command.args.includes("worktree") && command.args.includes("--porcelain");
|
||||
const shouldDelay =
|
||||
isWorktreeScan && (yield* Ref.getAndSet(delayFirstWorktreeScan, false));
|
||||
if (shouldDelay) {
|
||||
yield* Deferred.succeed(firstWorktreeScanStarted, undefined);
|
||||
yield* Effect.sleep("8 seconds");
|
||||
}
|
||||
const handle = yield* delegate.spawn(command);
|
||||
const isRemoteNamesScan =
|
||||
command.args.length === 3 &&
|
||||
command.args[0] === "--git-dir" &&
|
||||
command.args[2] === "remote";
|
||||
return isRemoteNamesScan
|
||||
? ChildProcessSpawner.makeHandle({
|
||||
...handle,
|
||||
exitCode: handle.exitCode.pipe(
|
||||
Effect.tap(() => Deferred.succeed(remoteNamesScanCompleted, undefined)),
|
||||
),
|
||||
})
|
||||
: handle;
|
||||
}),
|
||||
);
|
||||
const driver = yield* makeGitVcsDriverCore().pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, countingSpawner),
|
||||
);
|
||||
const cwd = yield* makeTmpDir();
|
||||
const runGit = (args: ReadonlyArray<string>) =>
|
||||
driver.execute({
|
||||
operation: "GitVcsDriver.test.coalescedListRefs",
|
||||
cwd,
|
||||
args,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
|
||||
yield* driver.initRepo({ cwd });
|
||||
yield* runGit(["config", "user.email", "[email protected]"]);
|
||||
yield* runGit(["config", "user.name", "Test"]);
|
||||
yield* writeTextFile(cwd, "README.md", "# test\n");
|
||||
yield* runGit(["add", "."]);
|
||||
yield* runGit(["commit", "-m", "initial commit"]);
|
||||
yield* Ref.set(spawnedArgs, []);
|
||||
|
||||
const initialRequest = yield* driver
|
||||
.listRefs({ cwd, refresh: true, limit: 100 })
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* Deferred.await(firstWorktreeScanStarted);
|
||||
yield* Deferred.await(remoteNamesScanCompleted);
|
||||
yield* TestClock.adjust("6 seconds");
|
||||
const laterRequests = yield* Effect.all(
|
||||
Array.from({ length: 30 }, (_, index) =>
|
||||
driver.listRefs({
|
||||
cwd,
|
||||
refresh: true,
|
||||
query: `missing-${index}`,
|
||||
limit: 100,
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* TestClock.adjust("2 seconds");
|
||||
yield* Fiber.join(initialRequest);
|
||||
yield* Fiber.join(laterRequests);
|
||||
yield* driver.listRefs({ cwd, cursor: 1, limit: 100 });
|
||||
|
||||
const firstSnapshotCommands = yield* Ref.get(spawnedArgs);
|
||||
const snapshotRefScans = firstSnapshotCommands.filter(
|
||||
(args) =>
|
||||
args.includes("for-each-ref") &&
|
||||
args.includes("refs/heads") &&
|
||||
args.includes("refs/remotes"),
|
||||
);
|
||||
const worktreeScans = firstSnapshotCommands.filter(
|
||||
(args) => args.includes("worktree") && args.includes("--porcelain"),
|
||||
);
|
||||
assert.equal(snapshotRefScans.length, 1);
|
||||
assert.equal(worktreeScans.length, 1);
|
||||
|
||||
yield* driver.createRef({ cwd, refName: "feature/cache-invalidation" });
|
||||
const refreshed = yield* driver.listRefs({ cwd, limit: 100 });
|
||||
assert.equal(
|
||||
refreshed.refs.some((ref) => ref.name === "feature/cache-invalidation"),
|
||||
true,
|
||||
);
|
||||
const allCommands = yield* Ref.get(spawnedArgs);
|
||||
assert.equal(
|
||||
allCommands.filter(
|
||||
(args) =>
|
||||
args.includes("for-each-ref") &&
|
||||
args.includes("refs/heads") &&
|
||||
args.includes("refs/remotes"),
|
||||
).length,
|
||||
2,
|
||||
);
|
||||
}),
|
||||
).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
|
||||
);
|
||||
|
||||
it.effect("retries an in-flight ref snapshot invalidated by a mutation", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const firstWorktreeScanStarted = yield* Deferred.make<void>();
|
||||
const firstRefScanCompleted = yield* Deferred.make<void>();
|
||||
const releaseFirstWorktreeScan = yield* Deferred.make<void>();
|
||||
const delayFirstWorktreeScan = yield* Ref.make(true);
|
||||
const refScans = yield* Ref.make(0);
|
||||
const coordinatingSpawner = ChildProcessSpawner.make((command) =>
|
||||
Effect.gen(function* () {
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
return yield* Effect.die("expected a standard Git command");
|
||||
}
|
||||
const isWorktreeScan =
|
||||
command.args.includes("worktree") && command.args.includes("--porcelain");
|
||||
if (isWorktreeScan && (yield* Ref.getAndSet(delayFirstWorktreeScan, false))) {
|
||||
yield* Deferred.succeed(firstWorktreeScanStarted, undefined);
|
||||
yield* Deferred.await(releaseFirstWorktreeScan);
|
||||
}
|
||||
const handle = yield* delegate.spawn(command);
|
||||
const isRefScan =
|
||||
command.args.includes("for-each-ref") &&
|
||||
command.args.includes("refs/heads") &&
|
||||
command.args.includes("refs/remotes");
|
||||
if (!isRefScan) return handle;
|
||||
const scan = yield* Ref.updateAndGet(refScans, (count) => count + 1);
|
||||
return scan === 1
|
||||
? ChildProcessSpawner.makeHandle({
|
||||
...handle,
|
||||
exitCode: handle.exitCode.pipe(
|
||||
Effect.tap(() => Deferred.succeed(firstRefScanCompleted, undefined)),
|
||||
),
|
||||
})
|
||||
: handle;
|
||||
}),
|
||||
);
|
||||
const driver = yield* makeGitVcsDriverCore().pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, coordinatingSpawner),
|
||||
);
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver));
|
||||
|
||||
const inFlight = yield* driver
|
||||
.listRefs({ cwd, refresh: true, limit: 100 })
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* Deferred.await(firstWorktreeScanStarted);
|
||||
yield* Deferred.await(firstRefScanCompleted);
|
||||
|
||||
yield* driver.createRef({ cwd, refName: "feature/during-refresh" });
|
||||
yield* Deferred.succeed(releaseFirstWorktreeScan, undefined);
|
||||
|
||||
const refs = yield* Fiber.join(inFlight);
|
||||
assert.isTrue(refs.refs.some((ref) => ref.name === "feature/during-refresh"));
|
||||
assert.equal(yield* Ref.get(refScans), 2);
|
||||
}),
|
||||
).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
|
||||
);
|
||||
|
||||
it.effect("invalidates a ref snapshot when a mutation fails after changing Git", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const partiallyFailingSpawner = ChildProcessSpawner.make((command) =>
|
||||
Effect.gen(function* () {
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
return yield* Effect.die("expected a standard Git command");
|
||||
}
|
||||
if (command.args[0] === "branch" && command.args[1] === "feature/partial-failure") {
|
||||
const handle = yield* delegate.spawn(command);
|
||||
yield* handle.exitCode;
|
||||
return makeNonRepositoryHandle();
|
||||
}
|
||||
return yield* delegate.spawn(command);
|
||||
}),
|
||||
);
|
||||
const driver = yield* makeGitVcsDriverCore().pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, partiallyFailingSpawner),
|
||||
);
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver));
|
||||
yield* driver.listRefs({ cwd, refresh: true });
|
||||
|
||||
yield* driver.createRef({ cwd, refName: "feature/partial-failure" }).pipe(Effect.flip);
|
||||
|
||||
const refs = yield* driver.listRefs({ cwd });
|
||||
assert.isTrue(refs.refs.some((ref) => ref.name === "feature/partial-failure"));
|
||||
}),
|
||||
).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
|
||||
);
|
||||
|
||||
it.effect("fails a ref snapshot when for-each-ref exits unsuccessfully", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const snapshotAttempts = yield* Ref.make(0);
|
||||
const failingSnapshotSpawner = ChildProcessSpawner.make((command) =>
|
||||
Effect.gen(function* () {
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
return yield* Effect.die("expected a standard Git command");
|
||||
}
|
||||
if (command.args.includes("for-each-ref")) {
|
||||
yield* Ref.update(snapshotAttempts, (count) => count + 1);
|
||||
return makeNonRepositoryHandle();
|
||||
}
|
||||
return yield* delegate.spawn(command);
|
||||
}),
|
||||
);
|
||||
const driver = yield* makeGitVcsDriverCore().pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, failingSnapshotSpawner),
|
||||
);
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver));
|
||||
|
||||
const error = yield* driver.listRefs({ cwd, refresh: true }).pipe(Effect.flip);
|
||||
|
||||
assert.deepInclude(error, {
|
||||
_tag: "GitCommandError",
|
||||
operation: "GitVcsDriver.listRefs.snapshotRefs",
|
||||
detail: "Git ref snapshot enumeration failed.",
|
||||
exitCode: 128,
|
||||
});
|
||||
assert.equal(yield* Ref.get(snapshotAttempts), 1);
|
||||
}),
|
||||
).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
|
||||
);
|
||||
|
||||
it.effect("marks the current branch when worktree metadata is unavailable", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const incompleteMetadataSpawner = ChildProcessSpawner.make((command) =>
|
||||
Effect.gen(function* () {
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
return yield* Effect.die("expected a standard Git command");
|
||||
}
|
||||
const isWorktreeRoot =
|
||||
command.args.includes("rev-parse") && command.args.includes("--show-toplevel");
|
||||
const isWorktreeList =
|
||||
command.args.includes("worktree") && command.args.includes("--porcelain");
|
||||
if (isWorktreeRoot || isWorktreeList) {
|
||||
return makeNonRepositoryHandle();
|
||||
}
|
||||
return yield* delegate.spawn(command);
|
||||
}),
|
||||
);
|
||||
const driver = yield* makeGitVcsDriverCore().pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, incompleteMetadataSpawner),
|
||||
);
|
||||
const cwd = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd).pipe(
|
||||
Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
|
||||
);
|
||||
|
||||
const refs = yield* driver.listRefs({ cwd, refresh: true });
|
||||
|
||||
assert.isTrue(refs.isRepo);
|
||||
assert.isTrue(refs.refs.find((ref) => ref.name === initialBranch)?.current);
|
||||
}),
|
||||
).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
|
||||
);
|
||||
|
||||
it.effect("ignores worktree metadata for directories that no longer exist", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const missingWorktreePath = "/missing/deleted-worktree";
|
||||
const staleWorktreeSpawner = ChildProcessSpawner.make((command) =>
|
||||
Effect.gen(function* () {
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
return yield* Effect.die("expected a standard Git command");
|
||||
}
|
||||
const isWorktreeList =
|
||||
command.args.includes("worktree") && command.args.includes("--porcelain");
|
||||
if (isWorktreeList) {
|
||||
return makeSuccessfulHandle(
|
||||
`worktree ${missingWorktreePath}\0HEAD deadbeef\0branch refs/heads/stale-worktree\0\0`,
|
||||
);
|
||||
}
|
||||
return yield* delegate.spawn(command);
|
||||
}),
|
||||
);
|
||||
const driver = yield* makeGitVcsDriverCore().pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, staleWorktreeSpawner),
|
||||
);
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver));
|
||||
yield* git(cwd, ["branch", "stale-worktree"]).pipe(
|
||||
Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
|
||||
);
|
||||
|
||||
const refs = yield* driver.listRefs({ cwd, refresh: true });
|
||||
|
||||
assert.equal(refs.refs.find((ref) => ref.name === "stale-worktree")?.worktreePath, null);
|
||||
}),
|
||||
).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
|
||||
);
|
||||
|
||||
it.effect("refreshes the current branch after an external checkout", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
const cwd = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
yield* git(cwd, ["branch", "external-checkout"]);
|
||||
|
||||
const initialRefs = yield* driver.listRefs({ cwd, refresh: true });
|
||||
assert.isTrue(initialRefs.refs.find((ref) => ref.name === initialBranch)?.current);
|
||||
|
||||
// Raw execute intentionally bypasses the driver's mutation invalidation,
|
||||
// matching a checkout performed by another process.
|
||||
yield* driver.execute({
|
||||
operation: "GitVcsDriver.test.externalCheckout",
|
||||
cwd,
|
||||
args: ["checkout", "external-checkout"],
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
yield* TestClock.adjust("6 seconds");
|
||||
|
||||
const refreshedRefs = yield* driver.listRefs({ cwd, refresh: true });
|
||||
assert.isTrue(refreshedRefs.refs.find((ref) => ref.name === "external-checkout")?.current);
|
||||
assert.isFalse(refreshedRefs.refs.find((ref) => ref.name === initialBranch)?.current);
|
||||
}),
|
||||
).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("backs off failed upstream refreshes across linked worktrees", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fetchAttempts = yield* Ref.make(0);
|
||||
const failingFetchSpawner = ChildProcessSpawner.make((command) =>
|
||||
Effect.gen(function* () {
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
return yield* Effect.die("expected a standard Git command");
|
||||
}
|
||||
if (command.args.includes("fetch") && command.args.includes("--quiet")) {
|
||||
yield* Ref.update(fetchAttempts, (count) => count + 1);
|
||||
return makeNonRepositoryHandle();
|
||||
}
|
||||
return yield* delegate.spawn(command);
|
||||
}),
|
||||
);
|
||||
const driver = yield* makeGitVcsDriverCore().pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, failingFetchSpawner),
|
||||
);
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
|
||||
const worktreesRoot = yield* makeTmpDir("git-vcs-driver-worktrees-");
|
||||
const pathService = yield* Path.Path;
|
||||
const worktreePath = pathService.join(worktreesRoot, "linked");
|
||||
const runGit = (workingDirectory: string, args: ReadonlyArray<string>) =>
|
||||
driver.execute({
|
||||
operation: "GitVcsDriver.test.upstreamRefreshBackoff",
|
||||
cwd: workingDirectory,
|
||||
args,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
|
||||
yield* driver.initRepo({ cwd });
|
||||
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
yield* runGit(cwd, ["config", "user.name", "Test"]);
|
||||
yield* writeTextFile(cwd, "README.md", "# test\n");
|
||||
yield* runGit(cwd, ["add", "."]);
|
||||
yield* runGit(cwd, ["commit", "-m", "initial commit"]);
|
||||
const initialBranch = (yield* runGit(cwd, ["branch", "--show-current"])).stdout.trim();
|
||||
yield* runGit(remote, ["init", "--bare"]);
|
||||
yield* runGit(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* runGit(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* runGit(cwd, ["worktree", "add", "-b", "feature/linked", worktreePath]);
|
||||
yield* runGit(worktreePath, [
|
||||
"branch",
|
||||
"--set-upstream-to",
|
||||
`origin/${initialBranch}`,
|
||||
"feature/linked",
|
||||
]);
|
||||
const rootCommonDir = (yield* runGit(cwd, ["rev-parse", "--git-common-dir"])).stdout.trim();
|
||||
const linkedCommonDir = (yield* runGit(worktreePath, [
|
||||
"rev-parse",
|
||||
"--git-common-dir",
|
||||
])).stdout.trim();
|
||||
assert.equal(
|
||||
yield* fileSystem.realPath(pathService.resolve(cwd, rootCommonDir)),
|
||||
yield* fileSystem.realPath(pathService.resolve(worktreePath, linkedCommonDir)),
|
||||
);
|
||||
yield* Ref.set(fetchAttempts, 0);
|
||||
|
||||
yield* driver.statusDetailsRemote(cwd);
|
||||
yield* driver.statusDetailsRemote(worktreePath);
|
||||
assert.equal(yield* Ref.get(fetchAttempts), 1);
|
||||
|
||||
yield* TestClock.adjust("29 seconds");
|
||||
yield* driver.statusDetailsRemote(worktreePath);
|
||||
assert.equal(yield* Ref.get(fetchAttempts), 1);
|
||||
|
||||
yield* TestClock.adjust("1 second");
|
||||
yield* driver.statusDetailsRemote(cwd);
|
||||
assert.equal(yield* Ref.get(fetchAttempts), 2);
|
||||
|
||||
yield* TestClock.adjust("59 seconds");
|
||||
yield* driver.statusDetailsRemote(worktreePath);
|
||||
assert.equal(yield* Ref.get(fetchAttempts), 2);
|
||||
|
||||
yield* TestClock.adjust("1 second");
|
||||
yield* driver.statusDetailsRemote(cwd);
|
||||
assert.equal(yield* Ref.get(fetchAttempts), 3);
|
||||
}),
|
||||
).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
|
||||
);
|
||||
|
||||
it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
describe("process environment", () => {
|
||||
it.effect("preserves the caller locale for general Git subprocesses", () =>
|
||||
@@ -661,6 +1103,33 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
});
|
||||
|
||||
describe("worktree operations", () => {
|
||||
it.effect("preserves newline characters in worktree paths when listing refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const worktreesRoot = yield* makeTmpDir("git-vcs-driver-worktrees-");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const worktreePath = pathService.join(worktreesRoot, "linked\nworktree");
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
yield* git(cwd, ["worktree", "add", "-b", "feature/newline-path", worktreePath]);
|
||||
|
||||
const refs = yield* driver.listRefs({ cwd, refresh: true });
|
||||
const listedPath = refs.refs.find(
|
||||
(ref) => ref.name === "feature/newline-path",
|
||||
)?.worktreePath;
|
||||
|
||||
if (typeof listedPath !== "string") {
|
||||
return assert.fail("expected the linked branch to include its worktree path");
|
||||
}
|
||||
assert.equal(
|
||||
yield* fileSystem.realPath(listedPath),
|
||||
yield* fileSystem.realPath(worktreePath),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates and removes a worktree for a new refName", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
|
||||
@@ -50,8 +50,17 @@ const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 120_000;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
|
||||
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_FAILURE_BASE_COOLDOWN = Duration.seconds(30);
|
||||
const STATUS_UPSTREAM_REFRESH_FAILURE_MAX_COOLDOWN = Duration.minutes(15);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
const REPOSITORY_PATHS_CACHE_CAPACITY = 2_048;
|
||||
const REPOSITORY_PATHS_CACHE_TTL = Duration.minutes(10);
|
||||
const REPOSITORY_PATHS_REFRESH_COALESCE_TTL = Duration.seconds(5);
|
||||
const NON_REPOSITORY_PATHS_CACHE_TTL = Duration.seconds(1);
|
||||
const LIST_REFS_SNAPSHOT_CACHE_CAPACITY = 64;
|
||||
const LIST_REFS_SNAPSHOT_CACHE_TTL = Duration.minutes(2);
|
||||
const LIST_REFS_REFRESH_COALESCE_TTL = Duration.seconds(5);
|
||||
const LIST_REFS_REFRESH_FAILURE_COOLDOWN = Duration.seconds(30);
|
||||
const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({
|
||||
GCM_INTERACTIVE: "never",
|
||||
GIT_ASKPASS: "",
|
||||
@@ -95,6 +104,35 @@ class StatusRemoteRefreshCacheKey extends Data.Class<{
|
||||
remoteName: string;
|
||||
}> {}
|
||||
|
||||
function statusUpstreamRefreshFailureCooldown(consecutiveFailures: number): Duration.Duration {
|
||||
const exponent = Math.max(0, consecutiveFailures - 1);
|
||||
const cooldownMs =
|
||||
Duration.toMillis(STATUS_UPSTREAM_REFRESH_FAILURE_BASE_COOLDOWN) * Math.pow(2, exponent);
|
||||
return Duration.min(Duration.millis(cooldownMs), STATUS_UPSTREAM_REFRESH_FAILURE_MAX_COOLDOWN);
|
||||
}
|
||||
|
||||
class GitRefsSnapshotCacheKey extends Data.Class<{
|
||||
gitCommonDir: string;
|
||||
epoch: number;
|
||||
}> {}
|
||||
|
||||
class GitRefsRefreshCacheKey extends Data.Class<{
|
||||
gitCommonDir: string;
|
||||
generation: number;
|
||||
}> {}
|
||||
|
||||
interface GitRepositoryPaths {
|
||||
readonly gitCommonDir: string;
|
||||
readonly worktreeRoot: string | null;
|
||||
readonly currentBranch: string | null;
|
||||
}
|
||||
|
||||
interface GitRefsSnapshot {
|
||||
readonly localBranches: ReadonlyArray<VcsRef>;
|
||||
readonly remoteBranches: ReadonlyArray<VcsRef>;
|
||||
readonly hasPrimaryRemote: boolean;
|
||||
}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
stdin?: string | undefined;
|
||||
timeoutMs?: number | undefined;
|
||||
@@ -161,21 +199,6 @@ function parsePorcelainPath(line: string): string | null {
|
||||
return filePath.length > 0 ? filePath : null;
|
||||
}
|
||||
|
||||
function parseBranchLine(line: string): { name: string; current: boolean } | null {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
const name = trimmed.replace(/^[*+]\s+/, "");
|
||||
// Exclude symbolic refs like: "origin/HEAD -> origin/main".
|
||||
// Exclude detached HEAD pseudo-refs like: "(HEAD detached at origin/main)".
|
||||
if (name.includes(" -> ") || name.startsWith("(")) return null;
|
||||
|
||||
return {
|
||||
name,
|
||||
current: trimmed.startsWith("* "),
|
||||
};
|
||||
}
|
||||
|
||||
function filterBranchesForListQuery(
|
||||
refs: ReadonlyArray<VcsRef>,
|
||||
query?: string,
|
||||
@@ -210,6 +233,37 @@ function paginateBranches(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function parseWorktreeBranchPaths(stdout: string): ReadonlyMap<string, string> {
|
||||
const worktreePaths = new Map<string, string>();
|
||||
let currentPath: string | null = null;
|
||||
let currentBranch: string | null = null;
|
||||
let currentPrunable = false;
|
||||
|
||||
const flush = () => {
|
||||
if (currentPath !== null && currentBranch !== null && !currentPrunable) {
|
||||
worktreePaths.set(currentBranch, currentPath);
|
||||
}
|
||||
currentPath = null;
|
||||
currentBranch = null;
|
||||
currentPrunable = false;
|
||||
};
|
||||
|
||||
for (const field of stdout.split("\0")) {
|
||||
if (field === "") {
|
||||
flush();
|
||||
} else if (field.startsWith("worktree ")) {
|
||||
currentPath = field.slice("worktree ".length);
|
||||
} else if (field.startsWith("branch refs/heads/")) {
|
||||
currentBranch = field.slice("branch refs/heads/".length);
|
||||
} else if (field === "prunable" || field.startsWith("prunable ")) {
|
||||
currentPrunable = true;
|
||||
}
|
||||
}
|
||||
flush();
|
||||
|
||||
return worktreePaths;
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
@@ -937,35 +991,183 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
fetchCwd,
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
env: STATUS_UPSTREAM_REFRESH_ENV,
|
||||
fallbackErrorDetail: "Background Git fetch exited with a non-zero status.",
|
||||
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
|
||||
},
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {
|
||||
const gitCommonDir = yield* runGitStdout("GitVcsDriver.resolveGitCommonDir", cwd, [
|
||||
"rev-parse",
|
||||
"--git-common-dir",
|
||||
]).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
|
||||
const resolveRepositoryPathsUncached = Effect.fn("resolveRepositoryPathsUncached")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
const commonDirResult = yield* executeGitWithStableDiagnostics(
|
||||
"GitVcsDriver.resolveRepositoryPaths.commonDir",
|
||||
cwd,
|
||||
["rev-parse", "--git-common-dir"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
if (commonDirResult.exitCode !== 0) {
|
||||
const stderr = commonDirResult.stderr.trim();
|
||||
if (isNonRepositoryGitStderr(stderr)) {
|
||||
return null;
|
||||
}
|
||||
return yield* new GitCommandError({
|
||||
...gitCommandContext({
|
||||
operation: "GitVcsDriver.resolveRepositoryPaths.commonDir",
|
||||
cwd,
|
||||
args: ["rev-parse", "--git-common-dir"],
|
||||
}),
|
||||
detail: "Failed to resolve the Git common directory.",
|
||||
exitCode: commonDirResult.exitCode,
|
||||
stdoutLength: commonDirResult.stdout.length,
|
||||
stderrLength: commonDirResult.stderr.length,
|
||||
});
|
||||
}
|
||||
|
||||
const commonDirOutput = commonDirResult.stdout.trim();
|
||||
const resolvedGitCommonDir = path.isAbsolute(commonDirOutput)
|
||||
? path.normalize(commonDirOutput)
|
||||
: path.resolve(cwd, commonDirOutput);
|
||||
const gitCommonDir = yield* fileSystem
|
||||
.realPath(resolvedGitCommonDir)
|
||||
.pipe(Effect.orElseSucceed(() => resolvedGitCommonDir));
|
||||
const [worktreeRootResult, currentBranchResult] = yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitVcsDriver.resolveRepositoryPaths.worktreeRoot",
|
||||
cwd,
|
||||
["rev-parse", "--show-toplevel"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitVcsDriver.resolveRepositoryPaths.currentBranch",
|
||||
cwd,
|
||||
["symbolic-ref", "--quiet", "--short", "HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
],
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
const worktreeRootOutput = worktreeRootResult.stdout.trim();
|
||||
const worktreeRoot =
|
||||
worktreeRootResult.exitCode === 0 && worktreeRootOutput.length > 0
|
||||
? path.normalize(
|
||||
path.isAbsolute(worktreeRootOutput)
|
||||
? worktreeRootOutput
|
||||
: path.resolve(cwd, worktreeRootOutput),
|
||||
)
|
||||
: null;
|
||||
const currentBranchOutput = currentBranchResult.stdout.trim();
|
||||
const currentBranch =
|
||||
currentBranchResult.exitCode === 0 && currentBranchOutput.length > 0
|
||||
? currentBranchOutput
|
||||
: null;
|
||||
|
||||
return {
|
||||
gitCommonDir,
|
||||
worktreeRoot,
|
||||
currentBranch,
|
||||
} satisfies GitRepositoryPaths;
|
||||
});
|
||||
|
||||
const repositoryPathsCache = yield* Cache.makeWith(
|
||||
(cwd: string) => resolveRepositoryPathsUncached(cwd),
|
||||
{
|
||||
capacity: REPOSITORY_PATHS_CACHE_CAPACITY,
|
||||
timeToLive: Exit.match({
|
||||
onSuccess: (repositoryPaths) =>
|
||||
repositoryPaths === null ? NON_REPOSITORY_PATHS_CACHE_TTL : REPOSITORY_PATHS_CACHE_TTL,
|
||||
onFailure: () => Duration.zero,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const repositoryPathsRefreshCache = yield* Cache.makeWith(
|
||||
(cwd: string) =>
|
||||
Cache.invalidate(repositoryPathsCache, cwd).pipe(
|
||||
Effect.andThen(Cache.get(repositoryPathsCache, cwd)),
|
||||
),
|
||||
{
|
||||
capacity: REPOSITORY_PATHS_CACHE_CAPACITY,
|
||||
timeToLive: Exit.match({
|
||||
onSuccess: (repositoryPaths) =>
|
||||
repositoryPaths === null
|
||||
? NON_REPOSITORY_PATHS_CACHE_TTL
|
||||
: REPOSITORY_PATHS_REFRESH_COALESCE_TTL,
|
||||
onFailure: () => Duration.zero,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const normalizeRepositoryPathsCacheKey = (cwd: string) => path.normalize(path.resolve(cwd));
|
||||
const resolveRepositoryPaths = (cwd: string, refresh = false) => {
|
||||
const cacheKey = normalizeRepositoryPathsCacheKey(cwd);
|
||||
return Cache.get(refresh ? repositoryPathsRefreshCache : repositoryPathsCache, cacheKey);
|
||||
};
|
||||
|
||||
const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {
|
||||
const repositoryPaths = yield* resolveRepositoryPaths(cwd);
|
||||
if (repositoryPaths !== null) {
|
||||
return repositoryPaths.gitCommonDir;
|
||||
}
|
||||
return yield* new GitCommandError({
|
||||
...gitCommandContext({
|
||||
operation: "GitVcsDriver.resolveGitCommonDir",
|
||||
cwd,
|
||||
args: ["rev-parse", "--git-common-dir"],
|
||||
}),
|
||||
detail: "Cannot resolve a Git common directory outside a repository.",
|
||||
});
|
||||
});
|
||||
|
||||
const statusRemoteRefreshFailureCounts = new Map<string, number>();
|
||||
const statusRemoteRefreshFailureKey = (cacheKey: StatusRemoteRefreshCacheKey) =>
|
||||
`${cacheKey.gitCommonDir}\0${cacheKey.remoteName}`;
|
||||
const recordStatusRemoteRefreshFailure = (cacheKey: StatusRemoteRefreshCacheKey) => {
|
||||
const key = statusRemoteRefreshFailureKey(cacheKey);
|
||||
const nextCount = (statusRemoteRefreshFailureCounts.get(key) ?? 0) + 1;
|
||||
statusRemoteRefreshFailureCounts.delete(key);
|
||||
statusRemoteRefreshFailureCounts.set(key, nextCount);
|
||||
if (statusRemoteRefreshFailureCounts.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) {
|
||||
const oldestKey = statusRemoteRefreshFailureCounts.keys().next().value;
|
||||
if (oldestKey !== undefined) {
|
||||
statusRemoteRefreshFailureCounts.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
};
|
||||
const clearStatusRemoteRefreshFailures = (cacheKey: StatusRemoteRefreshCacheKey) => {
|
||||
statusRemoteRefreshFailureCounts.delete(statusRemoteRefreshFailureKey(cacheKey));
|
||||
};
|
||||
const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
|
||||
cacheKey: StatusRemoteRefreshCacheKey,
|
||||
) {
|
||||
yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
|
||||
return true as const;
|
||||
return yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName).pipe(
|
||||
Effect.tap(() => Effect.sync(() => clearStatusRemoteRefreshFailures(cacheKey))),
|
||||
Effect.tapError(() => Effect.sync(() => recordStatusRemoteRefreshFailure(cacheKey))),
|
||||
Effect.as(true as const),
|
||||
);
|
||||
});
|
||||
|
||||
const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
|
||||
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
|
||||
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
|
||||
timeToLive: (exit) =>
|
||||
// A failed background fetch is intentionally cached and exponentially
|
||||
// backed off. Status reads swallow this failure and use the last fetched
|
||||
// refs, so repeated thread mounts cannot turn a slow or unavailable remote
|
||||
// into a repository-wide Git subprocess storm.
|
||||
timeToLive: (exit, cacheKey) =>
|
||||
Exit.isSuccess(exit)
|
||||
? STATUS_UPSTREAM_REFRESH_INTERVAL
|
||||
: STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN,
|
||||
: statusUpstreamRefreshFailureCooldown(
|
||||
statusRemoteRefreshFailureCounts.get(statusRemoteRefreshFailureKey(cacheKey)) ?? 1,
|
||||
),
|
||||
});
|
||||
|
||||
const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* (
|
||||
@@ -1273,42 +1475,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
};
|
||||
});
|
||||
|
||||
const readBranchRecency = Effect.fn("readBranchRecency")(function* (cwd: string) {
|
||||
const branchRecency = yield* executeGit(
|
||||
"GitVcsDriver.readBranchRecency",
|
||||
cwd,
|
||||
[
|
||||
"for-each-ref",
|
||||
"--format=%(refname:short)%09%(committerdate:unix)",
|
||||
"refs/heads",
|
||||
"refs/remotes",
|
||||
],
|
||||
{
|
||||
timeoutMs: 15_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
|
||||
const branchLastCommit = new Map<string, number>();
|
||||
if (branchRecency.exitCode !== 0) {
|
||||
return branchLastCommit;
|
||||
}
|
||||
|
||||
for (const line of branchRecency.stdout.split("\n")) {
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const [name, lastCommitRaw] = line.split("\t");
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
|
||||
branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
|
||||
}
|
||||
|
||||
return branchLastCommit;
|
||||
});
|
||||
|
||||
const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) {
|
||||
const statusResult = yield* executeGitWithStableDiagnostics(
|
||||
"GitVcsDriver.statusDetails.status",
|
||||
@@ -1987,257 +2153,283 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
|
||||
);
|
||||
|
||||
const listRefs: GitVcsDriver.GitVcsDriver["Service"]["listRefs"] = Effect.fn("listRefs")(
|
||||
function* (input) {
|
||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||
Effect.orElseSucceed(() => new Map<string, number>()),
|
||||
);
|
||||
const localBranchResult = yield* executeGitWithStableDiagnostics(
|
||||
"GitVcsDriver.listRefs.branchNoColor",
|
||||
input.cwd,
|
||||
["branch", "--no-color", "--no-column"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
GitCommandError: (error) =>
|
||||
isMissingGitCwdError(error)
|
||||
? Effect.succeed({
|
||||
exitCode: ChildProcessSpawner.ExitCode(128),
|
||||
stdout: "",
|
||||
stderr: "fatal: not a git repository",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
})
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
|
||||
if (localBranchResult.exitCode !== 0) {
|
||||
const stderr = localBranchResult.stderr.trim();
|
||||
if (isNonRepositoryGitStderr(stderr)) {
|
||||
return {
|
||||
refs: [],
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
};
|
||||
}
|
||||
return yield* new GitCommandError({
|
||||
...gitCommandContext({
|
||||
operation: "GitVcsDriver.listRefs",
|
||||
cwd: input.cwd,
|
||||
args: ["branch", "--no-color", "--no-column"],
|
||||
}),
|
||||
detail: "Git branch listing failed.",
|
||||
exitCode: localBranchResult.exitCode,
|
||||
stdoutLength: localBranchResult.stdout.length,
|
||||
stderrLength: localBranchResult.stderr.length,
|
||||
});
|
||||
}
|
||||
|
||||
const remoteBranchResultEffect = executeGit(
|
||||
"GitVcsDriver.listRefs.remoteBranches",
|
||||
input.cwd,
|
||||
["branch", "--no-color", "--no-column", "--remotes"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
GitCommandError: (error) =>
|
||||
Effect.logWarning(
|
||||
"Git remote ref lookup failed; falling back to an empty remote ref list.",
|
||||
{
|
||||
operation: error.operation,
|
||||
command: error.command,
|
||||
cwd: error.cwd,
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
},
|
||||
).pipe(
|
||||
Effect.as({
|
||||
exitCode: ChildProcessSpawner.ExitCode(1),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
} satisfies GitVcsDriver.ExecuteGitResult),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const remoteNamesResultEffect = executeGit(
|
||||
"GitVcsDriver.listRefs.remoteNames",
|
||||
input.cwd,
|
||||
["remote"],
|
||||
{
|
||||
const readGitRefsSnapshot = Effect.fn("readGitRefsSnapshot")(function* (gitCommonDir: string) {
|
||||
const fetchCwd =
|
||||
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
|
||||
const gitDirArgs = ["--git-dir", gitCommonDir] as const;
|
||||
const [refsResult, defaultRefResult, worktreeListResult, remoteNamesResult] = yield* Effect.all(
|
||||
[
|
||||
executeGitWithStableDiagnostics(
|
||||
"GitVcsDriver.listRefs.snapshotRefs",
|
||||
fetchCwd,
|
||||
[
|
||||
...gitDirArgs,
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%09%(committerdate:unix)%09%(symref)",
|
||||
"refs/heads",
|
||||
"refs/remotes",
|
||||
],
|
||||
{
|
||||
timeoutMs: 30_000,
|
||||
maxOutputBytes: 16 * 1024 * 1024,
|
||||
fallbackErrorDetail: "Git ref snapshot enumeration failed.",
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitVcsDriver.listRefs.defaultRef",
|
||||
fetchCwd,
|
||||
[...gitDirArgs, "symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitVcsDriver.listRefs.worktreeList",
|
||||
fetchCwd,
|
||||
[...gitDirArgs, "worktree", "list", "--porcelain", "-z"],
|
||||
{
|
||||
timeoutMs: 30_000,
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: 16 * 1024 * 1024,
|
||||
},
|
||||
),
|
||||
executeGit("GitVcsDriver.listRefs.remoteNames", fetchCwd, [...gitDirArgs, "remote"], {
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
}),
|
||||
],
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
|
||||
const remoteNames =
|
||||
remoteNamesResult.exitCode === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||
if (remoteNamesResult.exitCode !== 0 && remoteNamesResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitVcsDriver.listRefs: remote name lookup returned code ${remoteNamesResult.exitCode} for ${gitCommonDir}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
|
||||
);
|
||||
}
|
||||
const defaultBranch =
|
||||
defaultRefResult.exitCode === 0
|
||||
? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
: null;
|
||||
const parsedWorktreeEntries =
|
||||
worktreeListResult.exitCode === 0
|
||||
? [...parseWorktreeBranchPaths(worktreeListResult.stdout)].map(
|
||||
([branchName, worktreePath]) =>
|
||||
[branchName, path.normalize(path.resolve(worktreePath))] as const,
|
||||
)
|
||||
: [];
|
||||
const existingWorktreeEntries = yield* Effect.filter(
|
||||
parsedWorktreeEntries,
|
||||
([, worktreePath]) =>
|
||||
fileSystem.stat(worktreePath).pipe(
|
||||
Effect.as(true),
|
||||
Effect.orElseSucceed(() => false),
|
||||
),
|
||||
{ concurrency: 16 },
|
||||
);
|
||||
const worktreeMap = new Map(existingWorktreeEntries);
|
||||
const localBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = [];
|
||||
const remoteBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = [];
|
||||
|
||||
for (const line of refsResult.stdout.split("\n")) {
|
||||
if (line.length === 0) continue;
|
||||
const [fullRefName, lastCommitRaw, symbolicTarget] = line.split("\t");
|
||||
if (!fullRefName || symbolicTarget) continue;
|
||||
const parsedLastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
|
||||
const lastCommit = Number.isFinite(parsedLastCommit) ? parsedLastCommit : 0;
|
||||
|
||||
if (fullRefName.startsWith("refs/heads/")) {
|
||||
const name = fullRefName.slice("refs/heads/".length);
|
||||
localBranches.push({
|
||||
ref: {
|
||||
name,
|
||||
current: false,
|
||||
isRemote: false,
|
||||
isDefault: name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(name) ?? null,
|
||||
},
|
||||
lastCommit,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (!fullRefName.startsWith("refs/remotes/")) continue;
|
||||
|
||||
const name = fullRefName.slice("refs/remotes/".length);
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(name, remoteNames);
|
||||
const remoteBranch: VcsRef = {
|
||||
name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault:
|
||||
defaultBranch !== null &&
|
||||
parsedRemoteRef?.remoteName === "origin" &&
|
||||
parsedRemoteRef.branchName === defaultBranch,
|
||||
worktreePath: null,
|
||||
...(parsedRemoteRef ? { remoteName: parsedRemoteRef.remoteName } : {}),
|
||||
};
|
||||
remoteBranches.push({ ref: remoteBranch, lastCommit });
|
||||
}
|
||||
|
||||
const byRecencyThenName = (
|
||||
left: { readonly ref: VcsRef; readonly lastCommit: number },
|
||||
right: { readonly ref: VcsRef; readonly lastCommit: number },
|
||||
) =>
|
||||
left.lastCommit !== right.lastCommit
|
||||
? right.lastCommit - left.lastCommit
|
||||
: left.ref.name.localeCompare(right.ref.name);
|
||||
|
||||
return {
|
||||
localBranches: localBranches.toSorted(byRecencyThenName).map(({ ref }) => ref),
|
||||
remoteBranches: remoteBranches.toSorted(byRecencyThenName).map(({ ref }) => ref),
|
||||
hasPrimaryRemote: remoteNames.includes("origin"),
|
||||
} satisfies GitRefsSnapshot;
|
||||
});
|
||||
|
||||
const listRefsEpochByCommonDir = new Map<string, number>();
|
||||
let listRefsEpochSequence = 0;
|
||||
const bumpListRefsEpoch = (gitCommonDir: string): number => {
|
||||
const nextEpoch = ++listRefsEpochSequence;
|
||||
listRefsEpochByCommonDir.delete(gitCommonDir);
|
||||
listRefsEpochByCommonDir.set(gitCommonDir, nextEpoch);
|
||||
if (listRefsEpochByCommonDir.size > LIST_REFS_SNAPSHOT_CACHE_CAPACITY) {
|
||||
const oldestKey = listRefsEpochByCommonDir.keys().next().value;
|
||||
if (oldestKey !== undefined) {
|
||||
listRefsEpochByCommonDir.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
return nextEpoch;
|
||||
};
|
||||
const listRefsGenerationByCommonDir = new Map<string, number>();
|
||||
let listRefsGenerationSequence = 0;
|
||||
const setListRefsGeneration = (gitCommonDir: string, generation: number): number => {
|
||||
listRefsGenerationByCommonDir.delete(gitCommonDir);
|
||||
listRefsGenerationByCommonDir.set(gitCommonDir, generation);
|
||||
if (listRefsGenerationByCommonDir.size > LIST_REFS_SNAPSHOT_CACHE_CAPACITY) {
|
||||
const oldestKey = listRefsGenerationByCommonDir.keys().next().value;
|
||||
if (oldestKey !== undefined) {
|
||||
listRefsGenerationByCommonDir.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
return generation;
|
||||
};
|
||||
const currentListRefsGeneration = (gitCommonDir: string): number => {
|
||||
const current = listRefsGenerationByCommonDir.get(gitCommonDir);
|
||||
return current === undefined
|
||||
? setListRefsGeneration(gitCommonDir, ++listRefsGenerationSequence)
|
||||
: setListRefsGeneration(gitCommonDir, current);
|
||||
};
|
||||
const bumpListRefsGeneration = (gitCommonDir: string): number =>
|
||||
setListRefsGeneration(gitCommonDir, ++listRefsGenerationSequence);
|
||||
const listRefsSnapshotCache = yield* Cache.makeWith(
|
||||
(cacheKey: GitRefsSnapshotCacheKey) => readGitRefsSnapshot(cacheKey.gitCommonDir),
|
||||
{
|
||||
capacity: LIST_REFS_SNAPSHOT_CACHE_CAPACITY,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? LIST_REFS_SNAPSHOT_CACHE_TTL : Duration.zero),
|
||||
},
|
||||
);
|
||||
const listRefsRefreshSnapshotCache = yield* Cache.makeWith(
|
||||
(cacheKey: GitRefsRefreshCacheKey) =>
|
||||
Effect.suspend(() => {
|
||||
const epoch = bumpListRefsEpoch(cacheKey.gitCommonDir);
|
||||
return Cache.get(
|
||||
listRefsSnapshotCache,
|
||||
new GitRefsSnapshotCacheKey({ gitCommonDir: cacheKey.gitCommonDir, epoch }),
|
||||
);
|
||||
}),
|
||||
{
|
||||
capacity: LIST_REFS_SNAPSHOT_CACHE_CAPACITY,
|
||||
timeToLive: (exit) =>
|
||||
Exit.isSuccess(exit) ? LIST_REFS_REFRESH_COALESCE_TTL : LIST_REFS_REFRESH_FAILURE_COOLDOWN,
|
||||
},
|
||||
);
|
||||
const resolveListRefsSnapshot = Effect.fn("resolveListRefsSnapshot")(function* (
|
||||
gitCommonDir: string,
|
||||
refresh: boolean,
|
||||
) {
|
||||
while (true) {
|
||||
const generation = currentListRefsGeneration(gitCommonDir);
|
||||
const currentEpoch = listRefsEpochByCommonDir.get(gitCommonDir);
|
||||
const snapshot =
|
||||
refresh || currentEpoch === undefined
|
||||
? // The refresh cache owns the complete snapshot read, rather than only the
|
||||
// epoch bump. Slow repositories therefore remain singleflight for the
|
||||
// entire Git scan even when more refresh requests arrive after the
|
||||
// coalescing TTL would otherwise have elapsed.
|
||||
yield* Cache.get(
|
||||
listRefsRefreshSnapshotCache,
|
||||
new GitRefsRefreshCacheKey({ gitCommonDir, generation }),
|
||||
)
|
||||
: yield* Cache.get(
|
||||
listRefsSnapshotCache,
|
||||
new GitRefsSnapshotCacheKey({ gitCommonDir, epoch: currentEpoch }),
|
||||
);
|
||||
if (currentListRefsGeneration(gitCommonDir) === generation) {
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
});
|
||||
const invalidateListRefsSnapshot = Effect.fn("invalidateListRefsSnapshot")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
const repositoryPathsCacheKey = normalizeRepositoryPathsCacheKey(cwd);
|
||||
const repositoryPaths = yield* Cache.get(repositoryPathsCache, repositoryPathsCacheKey);
|
||||
if (repositoryPaths === null) return;
|
||||
const previousGeneration = currentListRefsGeneration(repositoryPaths.gitCommonDir);
|
||||
bumpListRefsGeneration(repositoryPaths.gitCommonDir);
|
||||
bumpListRefsEpoch(repositoryPaths.gitCommonDir);
|
||||
yield* Cache.invalidate(
|
||||
listRefsRefreshSnapshotCache,
|
||||
new GitRefsRefreshCacheKey({
|
||||
gitCommonDir: repositoryPaths.gitCommonDir,
|
||||
generation: previousGeneration,
|
||||
}),
|
||||
);
|
||||
yield* Cache.invalidate(repositoryPathsRefreshCache, repositoryPathsCacheKey);
|
||||
yield* Cache.invalidate(repositoryPathsCache, repositoryPathsCacheKey);
|
||||
});
|
||||
|
||||
const listRefs: GitVcsDriver.GitVcsDriver["Service"]["listRefs"] = Effect.fn("listRefs")(
|
||||
function* (input) {
|
||||
const repositoryPaths = yield* resolveRepositoryPaths(input.cwd, input.refresh === true).pipe(
|
||||
Effect.catchTags({
|
||||
GitCommandError: (error) =>
|
||||
Effect.logWarning(
|
||||
"Git remote name lookup failed; falling back to an empty remote name list.",
|
||||
{
|
||||
operation: error.operation,
|
||||
command: error.command,
|
||||
cwd: error.cwd,
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
},
|
||||
).pipe(
|
||||
Effect.as({
|
||||
exitCode: ChildProcessSpawner.ExitCode(1),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
} satisfies GitVcsDriver.ExecuteGitResult),
|
||||
),
|
||||
isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
|
||||
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitVcsDriver.listRefs.defaultRef",
|
||||
input.cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitVcsDriver.listRefs.worktreeList",
|
||||
input.cwd,
|
||||
["worktree", "list", "--porcelain"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
remoteBranchResultEffect,
|
||||
remoteNamesResultEffect,
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const remoteNames =
|
||||
remoteNamesResult.exitCode === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||
if (remoteBranchResult.exitCode !== 0 && remoteBranchResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitVcsDriver.listRefs: remote refName lookup returned code ${remoteBranchResult.exitCode} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote refName list.`,
|
||||
);
|
||||
}
|
||||
if (remoteNamesResult.exitCode !== 0 && remoteNamesResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitVcsDriver.listRefs: remote name lookup returned code ${remoteNamesResult.exitCode} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
|
||||
);
|
||||
if (repositoryPaths === null) {
|
||||
return {
|
||||
refs: [],
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const defaultBranch =
|
||||
defaultRef.exitCode === 0
|
||||
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
: null;
|
||||
|
||||
const worktreeMap = new Map<string, string>();
|
||||
if (worktreeList.exitCode === 0) {
|
||||
let currentPath: string | null = null;
|
||||
for (const line of worktreeList.stdout.split("\n")) {
|
||||
if (line.startsWith("worktree ")) {
|
||||
const candidatePath = line.slice("worktree ".length);
|
||||
const exists = yield* fileSystem.stat(candidatePath).pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
currentPath = exists ? candidatePath : null;
|
||||
} else if (line.startsWith("branch refs/heads/") && currentPath) {
|
||||
worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
|
||||
} else if (line === "") {
|
||||
currentPath = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const localBranches = Arr.filterMap(localBranchResult.stdout.split("\n"), (line) => {
|
||||
const refName = parseBranchLine(line);
|
||||
return refName === null
|
||||
? Result.failVoid
|
||||
: Result.succeed({
|
||||
name: refName.name,
|
||||
current: refName.current,
|
||||
isRemote: false,
|
||||
isDefault: refName.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(refName.name) ?? null,
|
||||
});
|
||||
}).toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
const remoteBranches =
|
||||
remoteBranchResult.exitCode === 0
|
||||
? Arr.filterMap(remoteBranchResult.stdout.split("\n"), (line) => {
|
||||
const refName = parseBranchLine(line);
|
||||
if (refName === null) {
|
||||
return Result.failVoid;
|
||||
}
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(refName.name, remoteNames);
|
||||
const remoteBranch: {
|
||||
name: string;
|
||||
current: boolean;
|
||||
isRemote: boolean;
|
||||
remoteName?: string;
|
||||
isDefault: boolean;
|
||||
worktreePath: string | null;
|
||||
} = {
|
||||
name: refName.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
// origin/HEAD's target is the repo default even when no local
|
||||
// copy of the default branch exists.
|
||||
isDefault:
|
||||
defaultBranch !== null &&
|
||||
parsedRemoteRef?.remoteName === "origin" &&
|
||||
parsedRemoteRef.branchName === defaultBranch,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
remoteBranch.remoteName = parsedRemoteRef.remoteName;
|
||||
}
|
||||
return Result.succeed(remoteBranch);
|
||||
}).toSorted((a, b) => {
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
})
|
||||
: [];
|
||||
|
||||
const snapshot = yield* resolveListRefsSnapshot(
|
||||
repositoryPaths.gitCommonDir,
|
||||
input.refresh === true,
|
||||
);
|
||||
const hasCurrentWorktreeBranch =
|
||||
repositoryPaths.worktreeRoot !== null &&
|
||||
snapshot.localBranches.some((ref) => ref.worktreePath === repositoryPaths.worktreeRoot);
|
||||
const localBranches = snapshot.localBranches.map((ref) => ({
|
||||
...ref,
|
||||
current: hasCurrentWorktreeBranch
|
||||
? ref.worktreePath === repositoryPaths.worktreeRoot
|
||||
: ref.name === repositoryPaths.currentBranch,
|
||||
}));
|
||||
const combinedBranches = input.includeMatchingRemoteRefs
|
||||
? [...localBranches, ...remoteBranches]
|
||||
: dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]);
|
||||
? [...localBranches, ...snapshot.remoteBranches]
|
||||
: dedupeRemoteBranchesWithLocalMatches([...localBranches, ...snapshot.remoteBranches]);
|
||||
// Keep current/default refs on the first page even when the default
|
||||
// only exists as origin/<default> (remote refs sort after all locals).
|
||||
const allBranches = combinedBranches.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
return aPriority - bPriority;
|
||||
const allBranches = combinedBranches.toSorted((left, right) => {
|
||||
const leftPriority = left.current ? 0 : left.isDefault ? 1 : 2;
|
||||
const rightPriority = right.current ? 0 : right.isDefault ? 1 : 2;
|
||||
return leftPriority - rightPriority;
|
||||
});
|
||||
const branchesForKind =
|
||||
input.refKind === "local"
|
||||
@@ -2254,7 +2446,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
return {
|
||||
refs: [...refs.refs],
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: remoteNames.includes("origin"),
|
||||
hasPrimaryRemote: snapshot.hasPrimaryRemote,
|
||||
nextCursor: refs.nextCursor,
|
||||
totalCount: refs.totalCount,
|
||||
};
|
||||
@@ -2548,6 +2740,25 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
}),
|
||||
);
|
||||
|
||||
const withListRefsInvalidation = <A, E>(
|
||||
cwd: string,
|
||||
effect: Effect.Effect<A, E>,
|
||||
): Effect.Effect<A, E> =>
|
||||
effect.pipe(Effect.ensuring(invalidateListRefsSnapshot(cwd).pipe(Effect.ignore)));
|
||||
const initRepoWithListRefsInvalidation: GitVcsDriver.GitVcsDriver["Service"]["initRepo"] = (
|
||||
input,
|
||||
) =>
|
||||
initRepo(input).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.gen(function* () {
|
||||
const cacheKey = normalizeRepositoryPathsCacheKey(input.cwd);
|
||||
yield* Cache.invalidate(repositoryPathsRefreshCache, cacheKey);
|
||||
yield* Cache.invalidate(repositoryPathsCache, cacheKey);
|
||||
yield* invalidateListRefsSnapshot(input.cwd).pipe(Effect.ignore);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return GitVcsDriver.GitVcsDriver.of({
|
||||
execute,
|
||||
status,
|
||||
@@ -2555,27 +2766,31 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
statusDetailsLocal,
|
||||
statusDetailsRemote,
|
||||
prepareCommitContext,
|
||||
commit,
|
||||
pushCurrentBranch,
|
||||
pullCurrentBranch,
|
||||
commit: (cwd, subject, body, options) =>
|
||||
withListRefsInvalidation(cwd, commit(cwd, subject, body, options)),
|
||||
pushCurrentBranch: (cwd, fallbackBranch, options) =>
|
||||
withListRefsInvalidation(cwd, pushCurrentBranch(cwd, fallbackBranch, options)),
|
||||
pullCurrentBranch: (cwd) => withListRefsInvalidation(cwd, pullCurrentBranch(cwd)),
|
||||
readRangeContext,
|
||||
getReviewDiffPreview,
|
||||
readConfigValue,
|
||||
listRefs,
|
||||
createWorktree,
|
||||
fetchPullRequestBranch,
|
||||
ensureRemote,
|
||||
createWorktree: (input) => withListRefsInvalidation(input.cwd, createWorktree(input)),
|
||||
fetchPullRequestBranch: (input) =>
|
||||
withListRefsInvalidation(input.cwd, fetchPullRequestBranch(input)),
|
||||
ensureRemote: (input) => withListRefsInvalidation(input.cwd, ensureRemote(input)),
|
||||
resolvePrimaryRemoteName,
|
||||
fetchRemote,
|
||||
fetchRemote: (input) => withListRefsInvalidation(input.cwd, fetchRemote(input)),
|
||||
resolveRemoteTrackingCommit,
|
||||
fetchRemoteBranch,
|
||||
fetchRemoteTrackingBranch,
|
||||
setBranchUpstream,
|
||||
removeWorktree,
|
||||
renameBranch,
|
||||
createRef,
|
||||
switchRef,
|
||||
initRepo,
|
||||
fetchRemoteBranch: (input) => withListRefsInvalidation(input.cwd, fetchRemoteBranch(input)),
|
||||
fetchRemoteTrackingBranch: (input) =>
|
||||
withListRefsInvalidation(input.cwd, fetchRemoteTrackingBranch(input)),
|
||||
setBranchUpstream: (input) => withListRefsInvalidation(input.cwd, setBranchUpstream(input)),
|
||||
removeWorktree: (input) => withListRefsInvalidation(input.cwd, removeWorktree(input)),
|
||||
renameBranch: (input) => withListRefsInvalidation(input.cwd, renameBranch(input)),
|
||||
createRef: (input) => withListRefsInvalidation(input.cwd, createRef(input)),
|
||||
switchRef: (input) => withListRefsInvalidation(input.cwd, switchRef(input)),
|
||||
initRepo: initRepoWithListRefsInvalidation,
|
||||
listLocalBranchNames,
|
||||
});
|
||||
});
|
||||
@@ -46,7 +46,6 @@ import {
|
||||
ProjectWriteFileError,
|
||||
RelayClientInstallFailedError,
|
||||
type RelayClientInstallProgressEvent,
|
||||
OrchestrationReplayEventsError,
|
||||
type FilesystemBrowseFailure,
|
||||
FilesystemBrowseError,
|
||||
AssetWorkspaceContextNotFoundError,
|
||||
@@ -60,7 +59,6 @@ import {
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
import { clamp } from "effect/Number";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http";
|
||||
import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
|
||||
|
||||
@@ -99,7 +97,6 @@ import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
|
||||
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
|
||||
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
@@ -302,7 +299,6 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope],
|
||||
[ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope],
|
||||
[ORCHESTRATION_WS_METHODS.getFullThreadDiff, AuthOrchestrationReadScope],
|
||||
[ORCHESTRATION_WS_METHODS.replayEvents, AuthOrchestrationReadScope],
|
||||
[ORCHESTRATION_WS_METHODS.subscribeShell, AuthOrchestrationReadScope],
|
||||
[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot, AuthOrchestrationReadScope],
|
||||
[ORCHESTRATION_WS_METHODS.subscribeThread, AuthOrchestrationReadScope],
|
||||
@@ -441,8 +437,6 @@ const makeWsRpcLayer = (
|
||||
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
|
||||
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const repositoryIdentityResolver =
|
||||
yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery;
|
||||
@@ -592,53 +586,6 @@ const makeWsRpcLayer = (
|
||||
});
|
||||
};
|
||||
|
||||
const enrichProjectEvent = (
|
||||
event: OrchestrationEvent,
|
||||
): Effect.Effect<OrchestrationEvent, never, never> => {
|
||||
switch (event.type) {
|
||||
case "project.created":
|
||||
return repositoryIdentityResolver.resolve(event.payload.workspaceRoot).pipe(
|
||||
Effect.map((repositoryIdentity) => ({
|
||||
...event,
|
||||
payload: {
|
||||
...event.payload,
|
||||
repositoryIdentity,
|
||||
},
|
||||
})),
|
||||
);
|
||||
case "project.meta-updated":
|
||||
return Effect.gen(function* () {
|
||||
const workspaceRoot =
|
||||
event.payload.workspaceRoot ??
|
||||
Option.match(
|
||||
yield* projectionSnapshotQuery.getProjectShellById(event.payload.projectId),
|
||||
{
|
||||
onNone: () => null,
|
||||
onSome: (project) => project.workspaceRoot,
|
||||
},
|
||||
) ??
|
||||
null;
|
||||
if (workspaceRoot === null) {
|
||||
return event;
|
||||
}
|
||||
|
||||
const repositoryIdentity = yield* repositoryIdentityResolver.resolve(workspaceRoot);
|
||||
return {
|
||||
...event,
|
||||
payload: {
|
||||
...event.payload,
|
||||
repositoryIdentity,
|
||||
},
|
||||
} satisfies OrchestrationEvent;
|
||||
}).pipe(Effect.orElseSucceed(() => event));
|
||||
default:
|
||||
return Effect.succeed(event);
|
||||
}
|
||||
};
|
||||
|
||||
const enrichOrchestrationEvents = (events: ReadonlyArray<OrchestrationEvent>) =>
|
||||
Effect.forEach(events, enrichProjectEvent, { concurrency: 4 });
|
||||
|
||||
const toShellStreamEvent = (
|
||||
event: OrchestrationEvent,
|
||||
): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> => {
|
||||
@@ -1215,30 +1162,6 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.replayEvents]: (input) =>
|
||||
observeRpcEffect(
|
||||
ORCHESTRATION_WS_METHODS.replayEvents,
|
||||
Stream.runCollect(
|
||||
orchestrationEngine.readEvents(
|
||||
clamp(input.fromSequenceExclusive, {
|
||||
maximum: Number.MAX_SAFE_INTEGER,
|
||||
minimum: 0,
|
||||
}),
|
||||
),
|
||||
).pipe(
|
||||
Effect.map((events) => Array.from(events)),
|
||||
Effect.flatMap(enrichOrchestrationEvents),
|
||||
Effect.map((events) => events.map(projectActivityEvent)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationReplayEventsError({
|
||||
message: "Failed to replay orchestration events",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.subscribeShell]: (input) =>
|
||||
observeRpcStreamEffect(
|
||||
ORCHESTRATION_WS_METHODS.subscribeShell,
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildThreadFeed, type ThreadFeedActivity } from "../../mobile/src/lib/threadActivity.ts";
|
||||
import { deriveLatestContextWindowSnapshot } from "../../web/src/lib/contextWindow.ts";
|
||||
import { deriveWorkLogEntries } from "../../web/src/session-logic.ts";
|
||||
import {
|
||||
projectActivityEvent,
|
||||
@@ -231,3 +232,132 @@ describe("projectActivityPayload", () => {
|
||||
expect(event.payload.activity).toBe(activity);
|
||||
});
|
||||
});
|
||||
|
||||
describe("context-window snapshot dedup", () => {
|
||||
function makeContextWindowActivity(
|
||||
id: string,
|
||||
usedTokens: number,
|
||||
turn = `turn-${id}`,
|
||||
): OrchestrationThreadActivity {
|
||||
return {
|
||||
id: EventId.make(id),
|
||||
tone: "info",
|
||||
kind: "context-window.updated",
|
||||
summary: "Context window updated",
|
||||
payload: { usedTokens, maxTokens: 200_000 },
|
||||
turnId: TurnId.make(turn),
|
||||
createdAt: "2026-07-27T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
it("keeps only the latest context-window activity per turn in snapshots", () => {
|
||||
const stale1 = makeContextWindowActivity("ctx-1", 1_000, "turn-a");
|
||||
const latestA = makeContextWindowActivity("ctx-2", 2_000, "turn-a");
|
||||
const latestB = makeContextWindowActivity("ctx-3", 3_000, "turn-b");
|
||||
const tool = fixtures[0]!;
|
||||
|
||||
const projected = projectThreadDetailSnapshot({
|
||||
snapshotSequence: 7,
|
||||
thread: makeThread([stale1, tool, latestA, latestB]),
|
||||
});
|
||||
|
||||
expect(projected.thread.activities.map((activity) => activity.id)).toEqual([
|
||||
tool.id,
|
||||
latestA.id,
|
||||
latestB.id,
|
||||
]);
|
||||
// The retained rows keep their payloads untouched — the tool-data
|
||||
// projection only rewrites payloads with a `data` record.
|
||||
expect(projected.thread.activities[2]?.payload).toEqual(latestB.payload);
|
||||
});
|
||||
|
||||
it("still resolves a meter value after the client reverts the newest turn", () => {
|
||||
// A live thread.reverted makes the client drop all activities from
|
||||
// discarded turns; each surviving turn must keep a usable row.
|
||||
const olderTurn = makeContextWindowActivity("ctx-old", 1_500, "turn-kept");
|
||||
const revertedTurn = makeContextWindowActivity("ctx-new", 9_000, "turn-reverted");
|
||||
|
||||
const projected = projectThreadDetailSnapshot({
|
||||
snapshotSequence: 7,
|
||||
thread: makeThread([olderTurn, revertedTurn]),
|
||||
});
|
||||
const afterRevert = projected.thread.activities.filter(
|
||||
(activity) => activity.turnId === TurnId.make("turn-kept"),
|
||||
);
|
||||
|
||||
expect(deriveLatestContextWindowSnapshot(afterRevert)).toEqual(
|
||||
deriveLatestContextWindowSnapshot([olderTurn]),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches what the web client derives from the full history", () => {
|
||||
const activities = [
|
||||
makeContextWindowActivity("ctx-1", 1_000),
|
||||
makeContextWindowActivity("ctx-2", 2_000),
|
||||
];
|
||||
const projected = projectThreadDetailSnapshot({
|
||||
snapshotSequence: 7,
|
||||
thread: makeThread(activities),
|
||||
});
|
||||
|
||||
expect(deriveLatestContextWindowSnapshot(projected.thread.activities)).toEqual(
|
||||
deriveLatestContextWindowSnapshot(activities),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not let a malformed row shadow an earlier valid row in the same turn", () => {
|
||||
const valid = makeContextWindowActivity("ctx-valid", 5_000, "turn-a");
|
||||
const malformed: OrchestrationThreadActivity = {
|
||||
...makeContextWindowActivity("ctx-broken", 0, "turn-a"),
|
||||
payload: { usedTokens: null },
|
||||
};
|
||||
|
||||
const projected = projectThreadDetailSnapshot({
|
||||
snapshotSequence: 7,
|
||||
thread: makeThread([valid, malformed]),
|
||||
});
|
||||
|
||||
// The malformed row passes through, the valid row survives, and the
|
||||
// client's backward walk resolves the same value as with full history.
|
||||
expect(projected.thread.activities.map((activity) => activity.id)).toEqual([
|
||||
valid.id,
|
||||
malformed.id,
|
||||
]);
|
||||
expect(deriveLatestContextWindowSnapshot(projected.thread.activities)).toEqual(
|
||||
deriveLatestContextWindowSnapshot([valid, malformed]),
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves snapshots without context-window activities untouched", () => {
|
||||
const projected = projectThreadDetailSnapshot({
|
||||
snapshotSequence: 7,
|
||||
thread: makeThread([fixtures[4]!]),
|
||||
});
|
||||
expect(projected.thread.activities).toEqual([fixtures[4]]);
|
||||
});
|
||||
|
||||
it("does not filter live activity-appended events", () => {
|
||||
const activity = makeContextWindowActivity("ctx-live", 4_000);
|
||||
const event = {
|
||||
sequence: 9,
|
||||
eventId: EventId.make("event-ctx"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-projection"),
|
||||
occurredAt: "2026-07-27T00:00:02.000Z",
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "thread.activity-appended",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-projection"),
|
||||
activity,
|
||||
},
|
||||
} satisfies Extract<OrchestrationEvent, { type: "thread.activity-appended" }>;
|
||||
|
||||
const projected = projectActivityEvent(event);
|
||||
expect(
|
||||
projected.type === "thread.activity-appended" ? projected.payload.activity : undefined,
|
||||
).toEqual(activity);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.29",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -11,6 +11,51 @@ export function formatAppDisplayName(input: {
|
||||
return `${input.baseName} (${input.stageLabel})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the sidebar v2 beta is on by default for a build stage.
|
||||
*
|
||||
* Nightly and local dev opt in; Alpha and Latest stay on v1. This is resolved
|
||||
* from the client's own stage label rather than the connected server's version:
|
||||
* v2 only exists in the client, so a stable client on a nightly server has
|
||||
* nothing to turn on.
|
||||
*/
|
||||
export function resolveSidebarV2Default(stageLabel: string): boolean {
|
||||
const stage = stageLabel.trim().toLowerCase();
|
||||
return stage === "nightly" || stage === "dev";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolved sidebar v2 state: an explicit choice if the user has made one,
|
||||
* otherwise the default for this build stage.
|
||||
*
|
||||
* A stored `enabled: true` counts as an explicit choice even without the
|
||||
* companion flag. `true` was never the schema default, so it can only have come
|
||||
* from the Settings → Beta toggle — settings written before that flag existed
|
||||
* would otherwise lose the opt-in and drop such users back to v1 on production.
|
||||
* Mirrors how `normalizeDesktopSettingsDocument` treats a legacy stored
|
||||
* `updateChannel: "nightly"` as user-configured.
|
||||
*
|
||||
* `settingsHydrated` guards the startup window: client settings load
|
||||
* asynchronously and the pre-hydration snapshot is just the schema defaults, so
|
||||
* resolving against it would mount one sidebar and swap it out a tick later,
|
||||
* remounting the tree. While hydrating, hold v1 — where both paths already
|
||||
* start.
|
||||
*/
|
||||
export function resolveSidebarV2Enabled(input: {
|
||||
readonly enabled: boolean;
|
||||
readonly configuredByUser: boolean;
|
||||
readonly settingsHydrated: boolean;
|
||||
readonly stageLabel: string;
|
||||
}): boolean {
|
||||
if (!input.settingsHydrated) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return input.configuredByUser || input.enabled
|
||||
? input.enabled
|
||||
: resolveSidebarV2Default(input.stageLabel);
|
||||
}
|
||||
|
||||
export function resolveServerBackedAppStageLabel(input: {
|
||||
readonly primaryServerVersion: string | null | undefined;
|
||||
readonly fallbackStageLabel: string;
|
||||
|
||||
@@ -2,6 +2,8 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
resolveServerBackedAppDisplayName,
|
||||
resolveServerBackedAppStageLabel,
|
||||
resolveSidebarV2Default,
|
||||
resolveSidebarV2Enabled,
|
||||
} from "./branding.logic";
|
||||
|
||||
const originalWindow = globalThis.window;
|
||||
@@ -114,3 +116,74 @@ describe("branding logic", () => {
|
||||
).toBe("T3 Code (Alpha)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarV2Default", () => {
|
||||
it.each(["Nightly", "Dev", "nightly", " dev "])("enables the beta for %s builds", (stage) => {
|
||||
expect(resolveSidebarV2Default(stage)).toBe(true);
|
||||
});
|
||||
|
||||
it.each(["Alpha", "Latest", ""])("leaves the beta off for %s builds", (stage) => {
|
||||
expect(resolveSidebarV2Default(stage)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarV2Enabled", () => {
|
||||
const hydrated = { settingsHydrated: true } as const;
|
||||
|
||||
it.each(["Alpha", "Latest"])(
|
||||
"keeps a legacy opt-in on %s builds even without the companion flag",
|
||||
(stageLabel) => {
|
||||
// `true` was never the schema default, so it can only be an explicit
|
||||
// opt-in from settings written before `sidebarV2ConfiguredByUser` existed.
|
||||
expect(
|
||||
resolveSidebarV2Enabled({
|
||||
...hydrated,
|
||||
enabled: true,
|
||||
configuredByUser: false,
|
||||
stageLabel,
|
||||
}),
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it("applies the stage default when the beta was never enabled or configured", () => {
|
||||
expect(
|
||||
resolveSidebarV2Enabled({
|
||||
...hydrated,
|
||||
enabled: false,
|
||||
configuredByUser: false,
|
||||
stageLabel: "Nightly",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
resolveSidebarV2Enabled({
|
||||
...hydrated,
|
||||
enabled: false,
|
||||
configuredByUser: false,
|
||||
stageLabel: "Latest",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("honors an explicit opt-out over the stage default", () => {
|
||||
expect(
|
||||
resolveSidebarV2Enabled({
|
||||
...hydrated,
|
||||
enabled: false,
|
||||
configuredByUser: true,
|
||||
stageLabel: "Nightly",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("holds v1 until settings hydrate so the sidebar does not remount", () => {
|
||||
expect(
|
||||
resolveSidebarV2Enabled({
|
||||
enabled: true,
|
||||
configuredByUser: true,
|
||||
settingsHydrated: false,
|
||||
stageLabel: "Nightly",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@ import { getLocalStorageItem } from "../hooks/useLocalStorage";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import { cn, isMacPlatform } from "../lib/utils";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { useEnvironmentIdentificationMode, useSidebarV2Enabled } from "../hooks/useSettings";
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import ThreadSidebarV2 from "./SidebarV2";
|
||||
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
|
||||
@@ -62,7 +62,10 @@ function SidebarControl() {
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const { toggleSidebar } = useSidebar();
|
||||
const isSidebarVisible = useSidebarVisibility();
|
||||
const stageBackdropVariant = useSidebarStageBackdropVariant();
|
||||
const environmentIdentificationMode = useEnvironmentIdentificationMode();
|
||||
const stageBackdropVariant = useSidebarStageBackdropVariant(
|
||||
environmentIdentificationMode === "artwork",
|
||||
);
|
||||
const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle");
|
||||
|
||||
useEffect(() => {
|
||||
@@ -115,7 +118,7 @@ function SidebarControl() {
|
||||
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
const sidebarV2Enabled = useSidebarV2Enabled();
|
||||
// Settings routes render the settings nav, which lives in the v1 component
|
||||
// and is identical for both sidebars — so v1 stays mounted there.
|
||||
const pathname = useLocation({ select: (location) => location.pathname });
|
||||
|
||||
@@ -24,6 +24,7 @@ import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
|
||||
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { useOpenPrLink } from "../lib/openPullRequestLink";
|
||||
import { shouldLoadNextBranchPageAfterScroll } from "../state/paginatedBranches";
|
||||
import { usePaginatedBranches } from "../state/queries";
|
||||
import { useProject, useThread } from "../state/entities";
|
||||
import { useEnvironmentQuery } from "../state/query";
|
||||
@@ -230,7 +231,7 @@ export function BranchToolbarBranchSelector({
|
||||
const refs = branchRefState.refs;
|
||||
const hasNextPage =
|
||||
branchRefState.data?.nextCursor !== null && branchRefState.data?.nextCursor !== undefined;
|
||||
const isFetchingNextPage = branchRefState.isPending && branchRefState.data !== null;
|
||||
const isFetchingNextPage = branchRefState.isFetchingNextPage;
|
||||
const isInitialBranchesLoadPending = branchRefState.isPending && branchRefState.data === null;
|
||||
const currentGitBranch =
|
||||
branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
|
||||
@@ -505,19 +506,16 @@ export function BranchToolbarBranchSelector({
|
||||
// ---------------------------------------------------------------------------
|
||||
// Combobox / list plumbing
|
||||
// ---------------------------------------------------------------------------
|
||||
const handleOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
setIsBranchMenuOpen(open);
|
||||
if (!open) {
|
||||
setBranchQuery("");
|
||||
return;
|
||||
}
|
||||
branchRefState.refresh();
|
||||
},
|
||||
[branchRefState.refresh],
|
||||
);
|
||||
|
||||
const branchListScrollElementRef = useRef<HTMLElement | null>(null);
|
||||
const previousBranchListScrollTopRef = useRef<number | null>(null);
|
||||
const handleOpenChange = useCallback((open: boolean) => {
|
||||
previousBranchListScrollTopRef.current = null;
|
||||
setIsBranchMenuOpen(open);
|
||||
if (!open) {
|
||||
setBranchQuery("");
|
||||
}
|
||||
}, []);
|
||||
|
||||
const [showTopBranchScrollFade, setShowTopBranchScrollFade] = useState(false);
|
||||
const [showBottomBranchScrollFade, setShowBottomBranchScrollFade] = useState(false);
|
||||
const fetchNextBranchPage = useCallback(() => {
|
||||
@@ -528,18 +526,24 @@ export function BranchToolbarBranchSelector({
|
||||
branchRefState.loadNext();
|
||||
}, [branchRefState.loadNext, hasNextPage, isFetchingNextPage]);
|
||||
const maybeFetchNextBranchPage = useCallback(() => {
|
||||
if (!isBranchMenuOpen || !hasNextPage || isFetchingNextPage) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scrollElement = branchListScrollElementRef.current;
|
||||
if (!scrollElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
const distanceFromBottom =
|
||||
scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight;
|
||||
if (distanceFromBottom > 96) {
|
||||
const previousScrollTop = previousBranchListScrollTopRef.current;
|
||||
previousBranchListScrollTopRef.current = scrollElement.scrollTop;
|
||||
if (
|
||||
!isBranchMenuOpen ||
|
||||
!hasNextPage ||
|
||||
isFetchingNextPage ||
|
||||
!shouldLoadNextBranchPageAfterScroll({
|
||||
previousScrollTop,
|
||||
scrollTop: scrollElement.scrollTop,
|
||||
scrollHeight: scrollElement.scrollHeight,
|
||||
clientHeight: scrollElement.clientHeight,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -589,10 +593,6 @@ export function BranchToolbarBranchSelector({
|
||||
void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
|
||||
}, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
maybeFetchNextBranchPage();
|
||||
}, [refs.length, maybeFetchNextBranchPage]);
|
||||
|
||||
const triggerLabel = resolveBranchTriggerLabel({
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
@@ -791,14 +791,10 @@ export function BranchToolbarBranchSelector({
|
||||
renderItem={({ item, index }) => renderPickerItem(item, index)}
|
||||
estimatedItemSize={28}
|
||||
drawDistance={336}
|
||||
onEndReached={() => {
|
||||
if (hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextBranchPage();
|
||||
}
|
||||
}}
|
||||
onLayout={() => {
|
||||
updateBranchListScrollFades();
|
||||
maybeFetchNextBranchPage();
|
||||
previousBranchListScrollTopRef.current =
|
||||
branchListScrollElementRef.current?.scrollTop ?? null;
|
||||
}}
|
||||
onScroll={() => {
|
||||
updateBranchListScrollFades();
|
||||
|
||||
@@ -67,8 +67,10 @@ import {
|
||||
import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation";
|
||||
import {
|
||||
normalizeMarkdownLinkDestination,
|
||||
resolveInlineCodeFileLinkMeta,
|
||||
resolveMarkdownFileLinkMeta,
|
||||
rewriteMarkdownFileUriHref,
|
||||
type MarkdownFileLinkMeta,
|
||||
} from "../markdown-links";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { cn } from "../lib/utils";
|
||||
@@ -162,7 +164,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
|
||||
attributes: {
|
||||
...defaultSchema.attributes,
|
||||
"*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
|
||||
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta"],
|
||||
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
|
||||
},
|
||||
protocols: {
|
||||
...defaultSchema.protocols,
|
||||
@@ -174,6 +176,7 @@ const CHAT_MARKDOWN_REMARK_PLUGINS = [
|
||||
remarkGfm,
|
||||
remarkNormalizeListItemIndentation,
|
||||
remarkPreserveCodeMeta,
|
||||
remarkTagInlineCode,
|
||||
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
|
||||
|
||||
const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
|
||||
@@ -181,6 +184,7 @@ const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
|
||||
remarkNormalizeListItemIndentation,
|
||||
remarkBreaks,
|
||||
remarkPreserveCodeMeta,
|
||||
remarkTagInlineCode,
|
||||
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
|
||||
|
||||
const CHAT_MARKDOWN_REHYPE_PLUGINS = [
|
||||
@@ -253,6 +257,33 @@ function remarkPreserveCodeMeta() {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fenced code also lands on the `code` component, and inline vs block is no
|
||||
* longer distinguishable there once both render `<code>` — so inline spans are
|
||||
* tagged on the mdast, where the distinction still exists. Code inside a link
|
||||
* label stays untagged: linkifying it would nest an anchor inside the link's
|
||||
* anchor and steal its clicks.
|
||||
*/
|
||||
function remarkTagInlineCode() {
|
||||
return (tree: MarkdownAstNode) => {
|
||||
const visit = (node: MarkdownAstNode, insideLink: boolean) => {
|
||||
if (node.type === "inlineCode" && !insideLink) {
|
||||
node.data = {
|
||||
...node.data,
|
||||
hProperties: {
|
||||
...node.data?.hProperties,
|
||||
dataInlineCode: "",
|
||||
},
|
||||
};
|
||||
}
|
||||
const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
|
||||
node.children?.forEach((child) => visit(child, childInsideLink));
|
||||
};
|
||||
|
||||
visit(tree, false);
|
||||
};
|
||||
}
|
||||
|
||||
function nodeToPlainText(node: ReactNode): string {
|
||||
if (typeof node === "string" || typeof node === "number") {
|
||||
return String(node);
|
||||
@@ -276,11 +307,17 @@ function extractCodeBlock(
|
||||
|
||||
const onlyChild = childNodes[0];
|
||||
if (
|
||||
!isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
|
||||
onlyChild.type !== "code"
|
||||
!isValidElement<{ className?: string; children?: ReactNode; node?: { tagName?: string } }>(
|
||||
onlyChild,
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
// With a custom `code` component the child's type is that component, not
|
||||
// the "code" tag — the hast node react-markdown attaches still names it.
|
||||
if (onlyChild.type !== "code" && onlyChild.props.node?.tagName !== "code") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
className: onlyChild.props.className,
|
||||
@@ -816,6 +853,21 @@ function buildFileLinkParentSuffixByPath(filePaths: ReadonlyArray<string>): Map<
|
||||
return suffixByPath;
|
||||
}
|
||||
|
||||
const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;
|
||||
const INLINE_CODE_SPAN_PATTERN = /`([^`\n]+)`/g;
|
||||
|
||||
function extractInlineCodeSpans(text: string): string[] {
|
||||
const spans: string[] = [];
|
||||
const segments = text.split(FENCED_CODE_SEGMENT_PATTERN);
|
||||
for (let index = 0; index < segments.length; index += 2) {
|
||||
for (const match of (segments[index] ?? "").matchAll(INLINE_CODE_SPAN_PATTERN)) {
|
||||
const span = match[1]?.trim();
|
||||
if (span) spans.push(span);
|
||||
}
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
function extractMarkdownLinkHrefs(text: string): string[] {
|
||||
const hrefs: string[] = [];
|
||||
for (const match of text.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
|
||||
@@ -1281,10 +1333,24 @@ function ChatMarkdown({
|
||||
}
|
||||
return metaByHref;
|
||||
}, [cwd, text]);
|
||||
const inlineCodeFileLinkMetaByText = useMemo(() => {
|
||||
const metaByText = new Map<string, MarkdownFileLinkMeta>();
|
||||
for (const span of extractInlineCodeSpans(text)) {
|
||||
if (metaByText.has(span)) continue;
|
||||
const meta = resolveInlineCodeFileLinkMeta(span, cwd);
|
||||
if (meta) {
|
||||
metaByText.set(span, meta);
|
||||
}
|
||||
}
|
||||
return metaByText;
|
||||
}, [cwd, text]);
|
||||
const fileLinkParentSuffixByPath = useMemo(() => {
|
||||
const filePaths = [...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath);
|
||||
const filePaths = [
|
||||
...[...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath),
|
||||
...[...inlineCodeFileLinkMetaByText.values()].map((meta) => meta.filePath),
|
||||
];
|
||||
return buildFileLinkParentSuffixByPath(filePaths);
|
||||
}, [markdownFileLinkMetaByHref]);
|
||||
}, [inlineCodeFileLinkMetaByText, markdownFileLinkMetaByHref]);
|
||||
const markdownUrlTransform = useCallback((href: string) => {
|
||||
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
|
||||
}, []);
|
||||
@@ -1339,8 +1405,49 @@ function ChatMarkdown({
|
||||
},
|
||||
[createAssetUrl, openPreview, preparedConnection, threadRef],
|
||||
);
|
||||
const markdownComponents = useMemo<Components>(
|
||||
() => ({
|
||||
const markdownComponents = useMemo<Components>(() => {
|
||||
const fileLinkChip = (
|
||||
fileLinkMeta: MarkdownFileLinkMeta,
|
||||
copyMarkdown: string,
|
||||
className?: string,
|
||||
) => {
|
||||
const parentSuffix = fileLinkParentSuffixByPath.get(fileLinkMeta.filePath);
|
||||
const labelParts = [fileLinkMeta.basename];
|
||||
if (typeof parentSuffix === "string" && parentSuffix.length > 0) {
|
||||
labelParts.push(parentSuffix);
|
||||
}
|
||||
if (fileLinkMeta.line) {
|
||||
labelParts.push(
|
||||
`L${fileLinkMeta.line}${fileLinkMeta.column ? `:C${fileLinkMeta.column}` : ""}`,
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<MarkdownFileLink
|
||||
href={fileLinkMeta.targetPath}
|
||||
targetPath={fileLinkMeta.targetPath}
|
||||
iconPath={fileLinkMeta.filePath}
|
||||
displayPath={fileLinkMeta.displayPath}
|
||||
workspaceRelativePath={fileLinkMeta.workspaceRelativePath}
|
||||
line={fileLinkMeta.line}
|
||||
label={labelParts.join(" · ")}
|
||||
copyMarkdown={copyMarkdown}
|
||||
theme={resolvedTheme}
|
||||
threadRef={threadRef}
|
||||
onOpen={openInPreferredEditor}
|
||||
onOpenInBrowser={
|
||||
threadRef &&
|
||||
isPreviewSupportedInRuntime() &&
|
||||
isBrowserPreviewFile(fileLinkMeta.filePath)
|
||||
? () => openMarkdownFileInPreview(fileLinkMeta.filePath)
|
||||
: undefined
|
||||
}
|
||||
className={className}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
p({ node: _node, children, ...props }) {
|
||||
return <p {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</p>;
|
||||
},
|
||||
@@ -1455,39 +1562,26 @@ function ChatMarkdown({
|
||||
);
|
||||
}
|
||||
|
||||
const parentSuffix = fileLinkParentSuffixByPath.get(fileLinkMeta.filePath);
|
||||
const labelParts = [fileLinkMeta.basename];
|
||||
if (typeof parentSuffix === "string" && parentSuffix.length > 0) {
|
||||
labelParts.push(parentSuffix);
|
||||
return fileLinkChip(
|
||||
fileLinkMeta,
|
||||
`[${fileLinkMeta.basename}](${normalizedHref})`,
|
||||
props.className,
|
||||
);
|
||||
},
|
||||
code({ node, children, className, ...props }) {
|
||||
if (node?.properties?.dataInlineCode != null) {
|
||||
const codeText = nodeToPlainText(children);
|
||||
const fileLinkMeta =
|
||||
inlineCodeFileLinkMetaByText.get(codeText.trim()) ??
|
||||
resolveInlineCodeFileLinkMeta(codeText, cwd);
|
||||
if (fileLinkMeta) {
|
||||
return fileLinkChip(fileLinkMeta, `\`${codeText}\``);
|
||||
}
|
||||
}
|
||||
if (fileLinkMeta.line) {
|
||||
labelParts.push(
|
||||
`L${fileLinkMeta.line}${fileLinkMeta.column ? `:C${fileLinkMeta.column}` : ""}`,
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<MarkdownFileLink
|
||||
href={fileLinkMeta.targetPath}
|
||||
targetPath={fileLinkMeta.targetPath}
|
||||
iconPath={fileLinkMeta.filePath}
|
||||
displayPath={fileLinkMeta.displayPath}
|
||||
workspaceRelativePath={fileLinkMeta.workspaceRelativePath}
|
||||
line={fileLinkMeta.line}
|
||||
label={labelParts.join(" · ")}
|
||||
copyMarkdown={`[${fileLinkMeta.basename}](${normalizedHref})`}
|
||||
theme={resolvedTheme}
|
||||
threadRef={threadRef}
|
||||
onOpen={openInPreferredEditor}
|
||||
onOpenInBrowser={
|
||||
threadRef &&
|
||||
isPreviewSupportedInRuntime() &&
|
||||
isBrowserPreviewFile(fileLinkMeta.filePath)
|
||||
? () => openMarkdownFileInPreview(fileLinkMeta.filePath)
|
||||
: undefined
|
||||
}
|
||||
className={props.className}
|
||||
/>
|
||||
<code {...props} className={className}>
|
||||
{children}
|
||||
</code>
|
||||
);
|
||||
},
|
||||
table({ node: _node, ...props }) {
|
||||
@@ -1524,22 +1618,23 @@ function ChatMarkdown({
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
}),
|
||||
[
|
||||
diffThemeName,
|
||||
fileLinkParentSuffixByPath,
|
||||
isStreaming,
|
||||
markdownFileLinkMetaByHref,
|
||||
onTaskListChange,
|
||||
openInPreferredEditor,
|
||||
openExternalLinkInPreview,
|
||||
openMarkdownFileInPreview,
|
||||
resolvedTheme,
|
||||
skills,
|
||||
text,
|
||||
threadRef,
|
||||
],
|
||||
);
|
||||
};
|
||||
}, [
|
||||
cwd,
|
||||
diffThemeName,
|
||||
fileLinkParentSuffixByPath,
|
||||
inlineCodeFileLinkMetaByText,
|
||||
isStreaming,
|
||||
markdownFileLinkMetaByHref,
|
||||
onTaskListChange,
|
||||
openInPreferredEditor,
|
||||
openExternalLinkInPreview,
|
||||
openMarkdownFileInPreview,
|
||||
resolvedTheme,
|
||||
skills,
|
||||
text,
|
||||
threadRef,
|
||||
]);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import type { Thread } from "../types";
|
||||
import {
|
||||
buildBrowseGroups,
|
||||
buildThreadActionItems,
|
||||
enumerateCommandPaletteItems,
|
||||
filterCommandPaletteGroups,
|
||||
@@ -193,3 +194,41 @@ describe("buildThreadActionItems", () => {
|
||||
expect(items.map((item) => item.value)).toEqual(["thread:thread-active"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildBrowseGroups", () => {
|
||||
it("waits for asynchronous browse navigation actions", async () => {
|
||||
let finishNavigation: (() => void) | undefined;
|
||||
const browseTo = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
finishNavigation = resolve;
|
||||
}),
|
||||
);
|
||||
const groups = buildBrowseGroups({
|
||||
browseEntries: [{ name: "Downloads", fullPath: "/Users/test/Downloads" }],
|
||||
browseQuery: "~/",
|
||||
canBrowseUp: false,
|
||||
upIcon: null,
|
||||
directoryIcon: null,
|
||||
browseUp: vi.fn(),
|
||||
browseTo,
|
||||
});
|
||||
const item = groups[0]?.items[0];
|
||||
if (!item || item.kind !== "action") {
|
||||
throw new Error("Expected a browse action");
|
||||
}
|
||||
|
||||
let actionSettled = false;
|
||||
const action = item.run().then(() => {
|
||||
actionSettled = true;
|
||||
});
|
||||
await Promise.resolve();
|
||||
|
||||
expect(browseTo).toHaveBeenCalledWith("Downloads");
|
||||
expect(actionSettled).toBe(false);
|
||||
|
||||
finishNavigation?.();
|
||||
await action;
|
||||
expect(actionSettled).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
type KeybindingCommand,
|
||||
type FilesystemBrowseEntry,
|
||||
type KeybindingCommand,
|
||||
THREAD_JUMP_KEYBINDING_COMMANDS,
|
||||
} from "@t3tools/contracts";
|
||||
import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
@@ -70,38 +70,6 @@ export function enumerateCommandPaletteItems(
|
||||
|
||||
export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
|
||||
|
||||
export function filterBrowseEntries(input: {
|
||||
browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
|
||||
browseFilterQuery: string;
|
||||
highlightedItemValue: string | null;
|
||||
}): {
|
||||
filteredEntries: FilesystemBrowseEntry[];
|
||||
highlightedEntry: FilesystemBrowseEntry | null;
|
||||
exactEntry: FilesystemBrowseEntry | null;
|
||||
} {
|
||||
const lowerFilter = input.browseFilterQuery.toLowerCase();
|
||||
const showHidden = input.browseFilterQuery.startsWith(".");
|
||||
|
||||
const filteredEntries = input.browseEntries.filter(
|
||||
(entry) =>
|
||||
entry.name.toLowerCase().startsWith(lowerFilter) &&
|
||||
(showHidden || !entry.name.startsWith(".")),
|
||||
);
|
||||
|
||||
let highlightedEntry: FilesystemBrowseEntry | null = null;
|
||||
if (input.highlightedItemValue?.startsWith("browse:")) {
|
||||
const highlightedPath = input.highlightedItemValue.slice("browse:".length);
|
||||
highlightedEntry = filteredEntries.find((entry) => entry.fullPath === highlightedPath) ?? null;
|
||||
}
|
||||
|
||||
const exactEntry =
|
||||
input.browseFilterQuery.length > 0
|
||||
? (filteredEntries.find((entry) => entry.name === input.browseFilterQuery) ?? null)
|
||||
: null;
|
||||
|
||||
return { filteredEntries, highlightedEntry, exactEntry };
|
||||
}
|
||||
|
||||
export function normalizeSearchText(value: string): string {
|
||||
return value.trim().toLowerCase().replace(/\s+/g, " ");
|
||||
}
|
||||
@@ -302,8 +270,8 @@ export function buildBrowseGroups(input: {
|
||||
canBrowseUp: boolean;
|
||||
upIcon: ReactNode;
|
||||
directoryIcon: ReactNode;
|
||||
browseUp: () => void;
|
||||
browseTo: (name: string) => void;
|
||||
browseUp: () => void | Promise<void>;
|
||||
browseTo: (name: string) => void | Promise<void>;
|
||||
}): CommandPaletteGroup[] {
|
||||
const items: CommandPaletteActionItem[] = [];
|
||||
|
||||
@@ -316,7 +284,7 @@ export function buildBrowseGroups(input: {
|
||||
icon: input.upIcon,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
input.browseUp();
|
||||
await input.browseUp();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -330,7 +298,7 @@ export function buildBrowseGroups(input: {
|
||||
icon: input.directoryIcon,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
input.browseTo(entry.name);
|
||||
await input.browseTo(entry.name);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import {
|
||||
canPreloadBrowsePath,
|
||||
createBrowseNavigationCoordinator,
|
||||
filterFilesystemBrowseEntries,
|
||||
getFilesystemBrowsePath,
|
||||
} from "@t3tools/client-runtime/state/filesystem";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
settlePromise,
|
||||
@@ -61,16 +67,12 @@ import { useProjects, useThreadShells } from "../state/entities";
|
||||
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
|
||||
import {
|
||||
appendBrowsePathSegment,
|
||||
canNavigateUp,
|
||||
ensureBrowseDirectoryPath,
|
||||
findProjectByPath,
|
||||
getBrowseDirectoryPath,
|
||||
getBrowseLeafPathSegment,
|
||||
getBrowseParentPath,
|
||||
hasTrailingPathSeparator,
|
||||
inferProjectTitleFromPath,
|
||||
isExplicitRelativeProjectPath,
|
||||
isFilesystemBrowseQuery,
|
||||
isUnsupportedWindowsProjectPath,
|
||||
resolveProjectPathForDispatch,
|
||||
} from "../lib/projectPaths";
|
||||
@@ -96,7 +98,6 @@ import {
|
||||
type CommandPaletteActionItem,
|
||||
type CommandPaletteSubmenuItem,
|
||||
type CommandPaletteView,
|
||||
filterBrowseEntries,
|
||||
filterCommandPaletteGroups,
|
||||
getCommandPaletteInputPlaceholder,
|
||||
getCommandPaletteMode,
|
||||
@@ -486,6 +487,10 @@ function OpenCommandPaletteDialog(props: {
|
||||
const lookupRepository = useAtomQueryRunner(sourceControlEnvironment.repository, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
|
||||
reportFailure: false,
|
||||
reportDefect: false,
|
||||
});
|
||||
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -502,6 +507,13 @@ function OpenCommandPaletteDialog(props: {
|
||||
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
|
||||
const currentView = viewStack.at(-1) ?? null;
|
||||
const [browseGeneration, setBrowseGeneration] = useState(0);
|
||||
const browseNavigationRef = useRef<ReturnType<typeof createBrowseNavigationCoordinator> | null>(
|
||||
null,
|
||||
);
|
||||
if (browseNavigationRef.current === null) {
|
||||
browseNavigationRef.current = createBrowseNavigationCoordinator();
|
||||
}
|
||||
const browseNavigation = browseNavigationRef.current;
|
||||
const [addProjectEnvironmentId, setAddProjectEnvironmentId] = useState<EnvironmentId | null>(
|
||||
null,
|
||||
);
|
||||
@@ -671,8 +683,12 @@ function OpenCommandPaletteDialog(props: {
|
||||
);
|
||||
const isRemoteProjectCloneFlow = addProjectCloneFlow !== null;
|
||||
const isRemoteProjectRepositoryStep = addProjectCloneFlow?.step === "repository";
|
||||
const isBrowsing =
|
||||
!isRemoteProjectRepositoryStep && isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
|
||||
const browsePath = useMemo(
|
||||
() => getFilesystemBrowsePath(query, browseEnvironmentPlatform, !isRemoteProjectRepositoryStep),
|
||||
[browseEnvironmentPlatform, isRemoteProjectRepositoryStep, query],
|
||||
);
|
||||
const isBrowsing = browsePath.isBrowsing;
|
||||
const browseDirectoryPath = browsePath.directoryPath;
|
||||
const paletteMode = getCommandPaletteMode({ currentView, isBrowsing });
|
||||
const getAddProjectInitialQueryForEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId | null): string => {
|
||||
@@ -710,20 +726,22 @@ function OpenCommandPaletteDialog(props: {
|
||||
browseEnvironmentId && currentProjectEnvironmentId === browseEnvironmentId
|
||||
? currentProjectCwd
|
||||
: null;
|
||||
const getBrowseCwdForEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId | null): string | null =>
|
||||
environmentId && currentProjectEnvironmentId === environmentId ? currentProjectCwd : null,
|
||||
[currentProjectCwd, currentProjectEnvironmentId],
|
||||
);
|
||||
const relativePathNeedsActiveProject =
|
||||
isExplicitRelativeProjectPath(query.trim()) && currentProjectCwdForBrowse === null;
|
||||
const browseDirectoryPath = isBrowsing ? getBrowseDirectoryPath(query) : "";
|
||||
const browseFilterQuery =
|
||||
isBrowsing && !hasTrailingPathSeparator(query) ? getBrowseLeafPathSegment(query) : "";
|
||||
const browseQuery = useEnvironmentQuery(
|
||||
isBrowsing &&
|
||||
browseDirectoryPath.length > 0 &&
|
||||
browsePath.directoryPath.length > 0 &&
|
||||
browseEnvironmentId !== null &&
|
||||
!relativePathNeedsActiveProject
|
||||
? filesystemEnvironment.browse({
|
||||
environmentId: browseEnvironmentId,
|
||||
input: {
|
||||
partialPath: browseDirectoryPath,
|
||||
partialPath: browsePath.directoryPath,
|
||||
...(currentProjectCwdForBrowse ? { cwd: currentProjectCwdForBrowse } : {}),
|
||||
},
|
||||
})
|
||||
@@ -732,9 +750,43 @@ function OpenCommandPaletteDialog(props: {
|
||||
const browseResult = browseQuery.data;
|
||||
const isBrowsePending = browseQuery.isPending;
|
||||
const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES;
|
||||
const { filteredEntries: filteredBrowseEntries, exactEntry: exactBrowseEntry } = useMemo(
|
||||
() => filterBrowseEntries({ browseEntries, browseFilterQuery, highlightedItemValue }),
|
||||
[browseEntries, browseFilterQuery, highlightedItemValue],
|
||||
const { visibleEntries: visibleBrowseEntries, exactEntry: exactBrowseEntry } = useMemo(
|
||||
() => filterFilesystemBrowseEntries(browseEntries, browsePath.filterQuery),
|
||||
[browseEntries, browsePath.filterQuery],
|
||||
);
|
||||
|
||||
const prefetchBrowsePath = useCallback(
|
||||
async (
|
||||
partialPath: string,
|
||||
environmentId: EnvironmentId | null = browseEnvironmentId,
|
||||
cwd: string | null = currentProjectCwdForBrowse,
|
||||
): Promise<void> => {
|
||||
if (!environmentId) {
|
||||
return;
|
||||
}
|
||||
const environment = environments.find(
|
||||
(candidate) => candidate.environmentId === environmentId,
|
||||
);
|
||||
if (!canPreloadBrowsePath(environment?.connection.phase)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await loadBrowsePath({
|
||||
environmentId,
|
||||
input: {
|
||||
partialPath,
|
||||
...(cwd ? { cwd } : {}),
|
||||
},
|
||||
});
|
||||
},
|
||||
[browseEnvironmentId, currentProjectCwdForBrowse, environments, loadBrowsePath],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
browseNavigation.invalidate();
|
||||
},
|
||||
[browseNavigation],
|
||||
);
|
||||
|
||||
const openProjectFromSearch = useMemo(
|
||||
@@ -865,18 +917,22 @@ function OpenCommandPaletteDialog(props: {
|
||||
);
|
||||
const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
|
||||
|
||||
function pushPaletteView(view: CommandPaletteView): void {
|
||||
setViewStack((previousViews) => [
|
||||
...previousViews,
|
||||
{
|
||||
addonIcon: view.addonIcon,
|
||||
groups: view.groups,
|
||||
...(view.initialQuery ? { initialQuery: view.initialQuery } : {}),
|
||||
},
|
||||
]);
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(view.initialQuery ?? "");
|
||||
}
|
||||
const pushPaletteView = useCallback(
|
||||
(view: CommandPaletteView): void => {
|
||||
browseNavigation.invalidate();
|
||||
setViewStack((previousViews) => [
|
||||
...previousViews,
|
||||
{
|
||||
addonIcon: view.addonIcon,
|
||||
groups: view.groups,
|
||||
...(view.initialQuery ? { initialQuery: view.initialQuery } : {}),
|
||||
},
|
||||
]);
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(view.initialQuery ?? "");
|
||||
},
|
||||
[browseNavigation],
|
||||
);
|
||||
|
||||
function pushView(item: CommandPaletteSubmenuItem): void {
|
||||
pushPaletteView({
|
||||
@@ -887,6 +943,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
}
|
||||
|
||||
function popView(): void {
|
||||
browseNavigation.invalidate();
|
||||
setAddProjectCloneFlow(null);
|
||||
if (viewStack.length <= 1) {
|
||||
setAddProjectEnvironmentId(null);
|
||||
@@ -897,6 +954,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
}
|
||||
|
||||
function handleQueryChange(nextQuery: string): void {
|
||||
browseNavigation.invalidate();
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(nextQuery);
|
||||
if (nextQuery === "" && currentView?.initialQuery) {
|
||||
@@ -905,16 +963,35 @@ function OpenCommandPaletteDialog(props: {
|
||||
}
|
||||
|
||||
const startAddProjectBrowse = useCallback(
|
||||
(environmentId: EnvironmentId): void => {
|
||||
setAddProjectEnvironmentId(environmentId);
|
||||
setAddProjectCloneFlow(null);
|
||||
pushPaletteView({
|
||||
async (environmentId: EnvironmentId): Promise<void> => {
|
||||
const initialQuery = getAddProjectInitialQueryForEnvironment(environmentId);
|
||||
const initialBrowsePath = getBrowseDirectoryPath(initialQuery);
|
||||
const browseCwd = getBrowseCwdForEnvironment(environmentId);
|
||||
const view: CommandPaletteView = {
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: [],
|
||||
initialQuery: getAddProjectInitialQueryForEnvironment(environmentId),
|
||||
});
|
||||
initialQuery,
|
||||
};
|
||||
|
||||
await browseNavigation.run(
|
||||
() =>
|
||||
initialBrowsePath.length > 0
|
||||
? prefetchBrowsePath(initialBrowsePath, environmentId, browseCwd)
|
||||
: Promise.resolve(),
|
||||
() => {
|
||||
setAddProjectEnvironmentId(environmentId);
|
||||
setAddProjectCloneFlow(null);
|
||||
pushPaletteView(view);
|
||||
},
|
||||
);
|
||||
},
|
||||
[getAddProjectInitialQueryForEnvironment],
|
||||
[
|
||||
browseNavigation,
|
||||
getAddProjectInitialQueryForEnvironment,
|
||||
getBrowseCwdForEnvironment,
|
||||
prefetchBrowsePath,
|
||||
pushPaletteView,
|
||||
],
|
||||
);
|
||||
|
||||
const startAddProjectClone = useCallback(
|
||||
@@ -927,7 +1004,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
initialQuery: "",
|
||||
});
|
||||
},
|
||||
[],
|
||||
[pushPaletteView],
|
||||
);
|
||||
|
||||
const openSourceControlSettings = useCallback(() => {
|
||||
@@ -950,7 +1027,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
startAddProjectBrowse(environmentId);
|
||||
await startAddProjectBrowse(environmentId);
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -1043,7 +1120,12 @@ function OpenCommandPaletteDialog(props: {
|
||||
),
|
||||
});
|
||||
},
|
||||
[browseEnvironmentId, buildAddProjectSourceGroups, sourceControlDiscovery.data],
|
||||
[
|
||||
browseEnvironmentId,
|
||||
buildAddProjectSourceGroups,
|
||||
pushPaletteView,
|
||||
sourceControlDiscovery.data,
|
||||
],
|
||||
);
|
||||
|
||||
const addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map(
|
||||
@@ -1098,6 +1180,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
addProjectEnvironmentGroups,
|
||||
addProjectEnvironmentOptions.length,
|
||||
defaultAddProjectEnvironmentId,
|
||||
pushPaletteView,
|
||||
startAddProjectSourceSelection,
|
||||
]);
|
||||
|
||||
@@ -1114,6 +1197,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
return;
|
||||
}
|
||||
clearOpenIntent();
|
||||
browseNavigation.invalidate();
|
||||
setAddProjectCloneFlow(null);
|
||||
setViewStack([]);
|
||||
setQuery("");
|
||||
@@ -1139,10 +1223,12 @@ function OpenCommandPaletteDialog(props: {
|
||||
});
|
||||
}, [
|
||||
clearOpenIntent,
|
||||
browseNavigation,
|
||||
currentProjectEnvironmentId,
|
||||
currentProjectId,
|
||||
openIntent,
|
||||
projectThreadItems,
|
||||
pushPaletteView,
|
||||
]);
|
||||
|
||||
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
@@ -1225,7 +1311,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
startAddProjectBrowse(wslAddProjectEnvironmentOption.environmentId);
|
||||
await startAddProjectBrowse(wslAddProjectEnvironmentOption.environmentId);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1541,23 +1627,36 @@ function OpenCommandPaletteDialog(props: {
|
||||
await handleAddProject(cloneResult.value.cwd);
|
||||
}
|
||||
|
||||
function browseTo(name: string): void {
|
||||
const nextQuery = appendBrowsePathSegment(query, name);
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(nextQuery);
|
||||
setBrowseGeneration((generation) => generation + 1);
|
||||
}
|
||||
const browseTo = useCallback(
|
||||
async (name: string): Promise<void> => {
|
||||
const nextQuery = appendBrowsePathSegment(query, name);
|
||||
await browseNavigation.run(
|
||||
() => prefetchBrowsePath(getBrowseDirectoryPath(nextQuery)),
|
||||
() => {
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(nextQuery);
|
||||
setBrowseGeneration((generation) => generation + 1);
|
||||
},
|
||||
);
|
||||
},
|
||||
[browseNavigation, prefetchBrowsePath, query],
|
||||
);
|
||||
|
||||
function browseUp(): void {
|
||||
const parentPath = getBrowseParentPath(query);
|
||||
const browseUp = useCallback(async (): Promise<void> => {
|
||||
const parentPath = browsePath.parentPath;
|
||||
if (parentPath === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(parentPath);
|
||||
setBrowseGeneration((generation) => generation + 1);
|
||||
}
|
||||
await browseNavigation.run(
|
||||
() => prefetchBrowsePath(parentPath),
|
||||
() => {
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(parentPath);
|
||||
setBrowseGeneration((generation) => generation + 1);
|
||||
},
|
||||
);
|
||||
}, [browseNavigation, browsePath.parentPath, prefetchBrowsePath]);
|
||||
|
||||
// Resolve the add-project path from browse data when available. When the
|
||||
// query has a trailing separator (e.g. "~/projects/foo/"), parentPath is the
|
||||
@@ -1567,11 +1666,10 @@ function OpenCommandPaletteDialog(props: {
|
||||
? (browseResult?.parentPath ?? query.trim())
|
||||
: (exactBrowseEntry?.fullPath ?? query.trim());
|
||||
|
||||
const canBrowseUp =
|
||||
isBrowsing && !relativePathNeedsActiveProject && canNavigateUp(browseDirectoryPath);
|
||||
const canBrowseUp = !relativePathNeedsActiveProject && browsePath.canBrowseUp;
|
||||
|
||||
const browseGroups = buildBrowseGroups({
|
||||
browseEntries: filteredBrowseEntries,
|
||||
browseEntries: visibleBrowseEntries,
|
||||
browseQuery: query,
|
||||
canBrowseUp,
|
||||
upIcon: <CornerLeftUpIcon className={ITEM_ICON_CLASS} />,
|
||||
|
||||
@@ -41,7 +41,7 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) {
|
||||
<CommandList>
|
||||
{props.groups.map((group) => (
|
||||
<CommandGroup items={group.items} key={group.value}>
|
||||
<CommandGroupLabel>{group.label}</CommandGroupLabel>
|
||||
<CommandGroupLabel className="ps-[9px]">{group.label}</CommandGroupLabel>
|
||||
<CommandCollection>
|
||||
{(item) =>
|
||||
item.disabled ? (
|
||||
@@ -133,13 +133,13 @@ function CommandPaletteResultRow(props: {
|
||||
)}
|
||||
{props.item.titleTrailingContent}
|
||||
{props.item.timestamp ? (
|
||||
<span className="min-w-12 shrink-0 text-right text-[10px] tabular-nums text-muted-foreground/70">
|
||||
<span className="min-w-12 shrink-0 text-right text-xs tabular-nums text-muted-foreground/70">
|
||||
{props.item.timestamp}
|
||||
</span>
|
||||
) : null}
|
||||
{shortcutLabel ? <CommandShortcut>{shortcutLabel}</CommandShortcut> : null}
|
||||
{props.item.kind === "submenu" ? (
|
||||
<ChevronRightIcon className="ml-auto size-4 shrink-0 text-muted-foreground/50" />
|
||||
<ChevronRightIcon className="-me-0.5 ms-auto size-4 shrink-0 text-muted-foreground/70" />
|
||||
) : null}
|
||||
</CommandItem>
|
||||
);
|
||||
|
||||
@@ -877,7 +877,7 @@ export default function DiffPanel({
|
||||
<AnnotatableCodeView
|
||||
viewerRef={codeViewRef}
|
||||
key={collapseScopeKey ?? reviewSectionId}
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto [&>div>div:last-child]:top-0! [&>div>div:last-child]:bottom-auto!"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto"
|
||||
files={codeViewFiles}
|
||||
sectionId={reviewSectionId}
|
||||
sectionTitle={reviewSectionTitle}
|
||||
@@ -923,7 +923,8 @@ export default function DiffPanel({
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
stickyHeaders: true,
|
||||
layout: { paddingTop: 8, paddingBottom: 8, gap: 8 },
|
||||
itemMetrics: { diffHeaderHeight: 33 },
|
||||
layout: { paddingTop: 0, paddingBottom: 8, gap: 8 },
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { FolderIcon } from "lucide-react";
|
||||
import type { ComponentType } from "react";
|
||||
import { useState } from "react";
|
||||
import { useAssetUrl } from "../assets/assetUrls";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const loadedProjectFaviconSrcs = new Set<string>();
|
||||
|
||||
@@ -40,7 +41,7 @@ function ProjectFaviconFallback({
|
||||
readonly className?: string | undefined;
|
||||
readonly icon: ComponentType<{ className?: string }>;
|
||||
}) {
|
||||
return <Icon className={`size-3.5 shrink-0 text-muted-foreground/50 ${className ?? ""}`} />;
|
||||
return <Icon className={cn("size-3.5 shrink-0 text-muted-foreground/50", className)} />;
|
||||
}
|
||||
|
||||
function ProjectFaviconImage({
|
||||
@@ -64,7 +65,11 @@ function ProjectFaviconImage({
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loaded" ? "" : "hidden"} ${className ?? ""}`}
|
||||
className={cn(
|
||||
"size-3.5 shrink-0 rounded-sm object-contain",
|
||||
status !== "loaded" && "hidden",
|
||||
className,
|
||||
)}
|
||||
onLoad={() => {
|
||||
loadedProjectFaviconSrcs.add(src);
|
||||
setStatus("loaded");
|
||||
|
||||
@@ -2218,9 +2218,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
<div className="group/project-header relative">
|
||||
<SidebarMenuButton
|
||||
ref={isManualProjectSorting ? dragHandleProps?.setActivatorNodeRef : undefined}
|
||||
size="sm"
|
||||
className={`h-8 gap-2 rounded-md px-2 py-1.5 pr-8 text-left hover:bg-sidebar-row-hover group-hover/project-header:bg-sidebar-row-hover group-hover/project-header:text-sidebar-foreground max-sm:pr-14 ${
|
||||
isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"
|
||||
className={`pr-8 group-hover/project-header:bg-sidebar-row-hover group-hover/project-header:text-sidebar-foreground max-sm:pr-14 ${
|
||||
isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : ""
|
||||
}`}
|
||||
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.attributes : {})}
|
||||
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.listeners : {})}
|
||||
@@ -2822,30 +2821,33 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarContent className="gap-0">
|
||||
<SidebarGroup className="px-2 pt-2 pb-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<CommandDialogTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="h-8 gap-2 rounded-md px-2 py-1.5 text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-0"
|
||||
data-testid="command-palette-trigger"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
<span className="flex-1 truncate text-left text-sm font-medium">Search</span>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
<SidebarContent
|
||||
className="gap-0"
|
||||
fixedHeader={
|
||||
<SidebarGroup className="px-2 pt-2 pb-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<CommandDialogTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
className="focus-visible:ring-0"
|
||||
data-testid="command-palette-trigger"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<SearchIcon />
|
||||
<span className="flex-1 truncate">Search</span>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
}
|
||||
>
|
||||
{showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? (
|
||||
<SidebarGroup className="px-2 pt-2 pb-0">
|
||||
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8">
|
||||
|
||||
@@ -1,9 +1,28 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { StageBackdropArt, StageBackdropButtonArt } from "./SidebarStageBackdrop";
|
||||
import {
|
||||
resolveEnvironmentIdentificationPillLabel,
|
||||
resolveSidebarStageBackdropVariant,
|
||||
StageBackdropArt,
|
||||
StageBackdropButtonArt,
|
||||
} from "./SidebarStageBackdrop";
|
||||
|
||||
describe("SidebarStageBackdrop", () => {
|
||||
it("resolves stage artwork only when enabled", () => {
|
||||
expect(resolveSidebarStageBackdropVariant("Dev")).toBe("dev");
|
||||
expect(resolveSidebarStageBackdropVariant("Nightly")).toBe("nightly");
|
||||
expect(resolveSidebarStageBackdropVariant("Dev", false)).toBeNull();
|
||||
expect(resolveSidebarStageBackdropVariant("Alpha")).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves supported environment pill labels", () => {
|
||||
expect(resolveEnvironmentIdentificationPillLabel("Dev")).toBe("Dev");
|
||||
expect(resolveEnvironmentIdentificationPillLabel("nightly")).toBe("Nightly");
|
||||
expect(resolveEnvironmentIdentificationPillLabel("Latest")).toBeNull();
|
||||
expect(resolveEnvironmentIdentificationPillLabel("Alpha")).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["nightly", "dev"] as const)(
|
||||
"uses unique SVG definition ids when %s artwork is rendered more than once",
|
||||
(variant) => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { resolveServerBackedAppStageLabel } from "../branding.logic";
|
||||
import { primaryServerConfigAtom } from "../state/server";
|
||||
|
||||
export type SidebarStageBackdropVariant = "nightly" | "dev";
|
||||
export type EnvironmentIdentificationPillLabel = "Dev" | "Nightly";
|
||||
|
||||
// A wide viewBox keeps the 96-unit art height at a fixed scale while sidebar resizing reveals
|
||||
// more horizontal canvas instead of zooming the scene.
|
||||
@@ -13,23 +14,36 @@ const STAGE_BACKDROP_VIEW_BOX = "0 0 8192 96";
|
||||
|
||||
export function resolveSidebarStageBackdropVariant(
|
||||
stageLabel: string,
|
||||
enabled = true,
|
||||
): SidebarStageBackdropVariant | null {
|
||||
if (!enabled) return null;
|
||||
const normalized = stageLabel.trim().toLowerCase();
|
||||
if (normalized === "nightly") return "nightly";
|
||||
if (normalized === "dev") return "dev";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function useSidebarStageBackdropVariant(): SidebarStageBackdropVariant | null {
|
||||
export function resolveEnvironmentIdentificationPillLabel(
|
||||
stageLabel: string,
|
||||
): EnvironmentIdentificationPillLabel | null {
|
||||
const normalized = stageLabel.trim().toLowerCase();
|
||||
if (normalized === "dev") return "Dev";
|
||||
if (normalized === "nightly") return "Nightly";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function useEnvironmentStageLabel(): string {
|
||||
const primaryServerVersion =
|
||||
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
|
||||
|
||||
return resolveSidebarStageBackdropVariant(
|
||||
resolveServerBackedAppStageLabel({
|
||||
primaryServerVersion,
|
||||
fallbackStageLabel: APP_STAGE_LABEL,
|
||||
}),
|
||||
);
|
||||
return resolveServerBackedAppStageLabel({
|
||||
primaryServerVersion,
|
||||
fallbackStageLabel: APP_STAGE_LABEL,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSidebarStageBackdropVariant(enabled = true): SidebarStageBackdropVariant | null {
|
||||
return resolveSidebarStageBackdropVariant(useEnvironmentStageLabel(), enabled);
|
||||
}
|
||||
|
||||
/** Stage-channel header art; palettes mirror the per-channel app icons in `assets/`. */
|
||||
|
||||
@@ -213,7 +213,11 @@ function WorkingDuration(props: { startedAt: string | null }) {
|
||||
return () => window.clearInterval(id);
|
||||
}, [startedMs]);
|
||||
if (Number.isNaN(startedMs)) return null;
|
||||
return <span className="tabular-nums">{formatWorkingDurationLabel(Date.now() - startedMs)}</span>;
|
||||
return (
|
||||
<span className="font-mono tabular-nums">
|
||||
{formatWorkingDurationLabel(Date.now() - startedMs)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarV2ThreadTooltip({
|
||||
@@ -242,38 +246,40 @@ function SidebarV2ThreadTooltip({
|
||||
<TooltipPopup
|
||||
side="right"
|
||||
align="start"
|
||||
sideOffset={8}
|
||||
sideOffset={4}
|
||||
variant="glass"
|
||||
className="max-w-80 text-left whitespace-normal"
|
||||
>
|
||||
<div className="flex max-w-80 flex-col gap-2 p-2">
|
||||
<div className="whitespace-nowrap text-sm font-medium text-foreground">{thread.title}</div>
|
||||
<div className="grid gap-1.5 text-xs text-muted-foreground">
|
||||
<div className="flex min-w-0 max-w-80 flex-col gap-2 px-0.5 py-1.5">
|
||||
<div className="min-w-0 truncate text-xs leading-none font-medium text-foreground">
|
||||
{thread.title}
|
||||
</div>
|
||||
<div className="grid gap-1.5 pl-0.5 text-xs text-muted-foreground">
|
||||
{projectTitle ? (
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
cwd={projectCwd ?? ""}
|
||||
className="size-4 shrink-0 stroke-muted-foreground"
|
||||
className="size-3 shrink-0 stroke-muted-foreground"
|
||||
/>
|
||||
<div className="min-w-0 wrap-break-word text-foreground/90">{projectTitle}</div>
|
||||
<div className="min-w-0 truncate text-foreground/75">{projectTitle}</div>
|
||||
</div>
|
||||
) : null}
|
||||
{environmentLabel ? (
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<ServerIcon className="size-4 shrink-0 stroke-muted-foreground" />
|
||||
<div className="min-w-0 wrap-break-word text-foreground/90">{environmentLabel}</div>
|
||||
<ServerIcon className="size-3 shrink-0 stroke-muted-foreground" />
|
||||
<div className="min-w-0 truncate text-foreground/75">{environmentLabel}</div>
|
||||
</div>
|
||||
) : null}
|
||||
{thread.branch ? (
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<GitBranchIcon className="size-4 shrink-0 stroke-muted-foreground" />
|
||||
<div className="min-w-0 wrap-break-word text-foreground/90">{thread.branch}</div>
|
||||
<GitBranchIcon className="size-3 shrink-0 stroke-muted-foreground" />
|
||||
<div className="min-w-0 truncate text-foreground/75">{thread.branch}</div>
|
||||
</div>
|
||||
) : null}
|
||||
{branchMismatch ? (
|
||||
<div className="flex min-w-0 items-start gap-2 text-warning">
|
||||
<CircleAlertIcon aria-hidden className="mt-0.5 size-4 shrink-0 stroke-current" />
|
||||
<CircleAlertIcon aria-hidden className="mt-0.5 size-3 shrink-0 stroke-current" />
|
||||
<div className="min-w-0 flex-1 wrap-break-word leading-5">
|
||||
You're currently checked out on another branch.
|
||||
</div>
|
||||
@@ -284,15 +290,15 @@ function SidebarV2ThreadTooltip({
|
||||
<ProviderInstanceIcon
|
||||
driverKind={driverKind}
|
||||
displayName={thread.session?.providerName ?? modelInstanceId}
|
||||
iconClassName="size-4 shrink-0"
|
||||
iconClassName="size-3 shrink-0 grayscale opacity-60"
|
||||
/>
|
||||
<div className="min-w-0 wrap-break-word text-foreground/90">{modelLabel}</div>
|
||||
<div className="min-w-0 truncate text-foreground/75">{modelLabel}</div>
|
||||
</div>
|
||||
) : null}
|
||||
{thread.session?.lastError ? (
|
||||
<div className="flex min-w-0 items-center gap-2 text-red-600 dark:text-red-400">
|
||||
<CircleAlertIcon className="size-4 shrink-0 stroke-current" />
|
||||
<div className="min-w-0 wrap-break-word">{thread.session.lastError}</div>
|
||||
<CircleAlertIcon className="size-3 shrink-0 stroke-current" />
|
||||
<div className="min-w-0 truncate">Error occurred</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
@@ -815,9 +821,9 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
type="button"
|
||||
aria-label="Un-settle thread"
|
||||
onClick={handleUnsettleClick}
|
||||
className="absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover/v2-row:opacity-100"
|
||||
className="absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover/v2-row:opacity-100"
|
||||
>
|
||||
<Undo2Icon className="size-3" />
|
||||
<Undo2Icon className="mb-px size-3.5" />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
@@ -879,11 +885,15 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
) : (
|
||||
<span className="flex-1" />
|
||||
)}
|
||||
<span className="relative ml-auto flex h-5 min-w-8 shrink-0 items-center justify-end pl-1 text-xs">
|
||||
{/* The visible state owns this slot's width: status at rest,
|
||||
actions on hover/focus or while the popover is open. Keeping
|
||||
the hidden state out of flow lets the project label reclaim
|
||||
space without either state overlapping it. */}
|
||||
<span className="group/v2-status-slot relative ml-auto flex h-5 min-w-8 shrink-0 items-stretch justify-end text-xs">
|
||||
<span
|
||||
className={cn(
|
||||
"tabular-nums text-muted-foreground/65 transition-opacity group-hover/v2-row:opacity-0",
|
||||
snoozeMenuOpen && "opacity-0",
|
||||
"self-center justify-self-end tabular-nums text-muted-foreground/65 transition-opacity group-focus-within/v2-status-slot:absolute group-focus-within/v2-status-slot:right-0 group-hover/v2-row:absolute group-hover/v2-row:right-0 group-hover/v2-row:opacity-0",
|
||||
snoozeMenuOpen && "absolute right-0 opacity-0",
|
||||
)}
|
||||
>
|
||||
{topStatus ? (
|
||||
@@ -917,8 +927,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
{props.settlementSupported || showSnoozeButton ? (
|
||||
<span
|
||||
className={cn(
|
||||
"absolute inset-y-0 right-0 flex items-stretch gap-0.5 opacity-0 transition-opacity focus-within:opacity-100 group-hover/v2-row:opacity-100",
|
||||
snoozeMenuOpen && "opacity-100",
|
||||
"absolute inset-y-0 right-0 flex items-stretch opacity-0 transition-opacity focus-within:static focus-within:opacity-100 group-hover/v2-row:static group-hover/v2-row:opacity-100",
|
||||
snoozeMenuOpen && "static opacity-100",
|
||||
)}
|
||||
>
|
||||
{showSnoozeButton ? (
|
||||
@@ -933,9 +943,9 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
type="button"
|
||||
aria-label="Settle thread"
|
||||
onClick={handleSettleClick}
|
||||
className="inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
className="-mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<CheckIcon className="size-3" />
|
||||
<CheckIcon className="size-3.5" />
|
||||
Settle
|
||||
</button>
|
||||
) : null}
|
||||
@@ -2220,151 +2230,158 @@ export default function SidebarV2() {
|
||||
return (
|
||||
<>
|
||||
<SidebarChromeHeader isElectron={isElectron} />
|
||||
<SidebarContent className="gap-0">
|
||||
<SidebarGroup className="px-2 pb-2 pt-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="min-w-0 flex-1">
|
||||
<CommandDialogTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
type="button"
|
||||
aria-label="Search threads and commands"
|
||||
className="h-8 gap-2 rounded-md border-0 bg-transparent px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
data-testid="command-palette-trigger"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
<div className="flex-1 truncate text-left">Search</div>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="h-4 min-w-0 rounded-sm bg-sidebar-control-surface px-1.5 text-[10px] text-sidebar-muted-foreground ring-1 ring-sidebar-border">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
</div>
|
||||
<div className="shrink-0">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
<SidebarContent
|
||||
className="gap-0"
|
||||
fixedHeader={
|
||||
<SidebarGroup className="gap-1 p-2">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="min-w-0 flex-1">
|
||||
<CommandDialogTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
type="button"
|
||||
className="relative size-8 justify-center rounded-md border-0 bg-transparent p-0 text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
onClick={handleNewThreadClick}
|
||||
disabled={projects.length === 0}
|
||||
aria-label="New thread"
|
||||
aria-label="Search threads and commands"
|
||||
className="focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
data-testid="command-palette-trigger"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<SquarePenIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
<span
|
||||
className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">
|
||||
{newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</SidebarGroup>
|
||||
{projectGroups.length > 0 ? (
|
||||
<SidebarGroup className="px-2 pb-2 pt-0">
|
||||
<div className="flex items-center gap-1">
|
||||
<Menu open={projectScopeMenuOpen} onOpenChange={setProjectScopeMenuOpen}>
|
||||
<MenuTrigger
|
||||
aria-label="Filter threads by project"
|
||||
className="flex h-8 min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md px-2 text-left text-sm font-medium text-sidebar-muted-foreground outline-none hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
>
|
||||
{scopedProjectGroup ? (
|
||||
<ProjectFavicon
|
||||
environmentId={scopedProjectGroup.environmentId}
|
||||
cwd={scopedProjectGroup.workspaceRoot}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<FolderIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{scopedProjectGroup?.displayName ?? "All projects"}
|
||||
</span>
|
||||
<ChevronDownIcon className="size-4 shrink-0 text-sidebar-muted-foreground/70" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start" className="w-(--anchor-width)">
|
||||
<MenuRadioGroup
|
||||
value={projectScopeKey ?? "all"}
|
||||
onValueChange={(value) =>
|
||||
setProjectScopeKey(value === "all" ? null : (value as string))
|
||||
<SearchIcon />
|
||||
<div className="flex-1 truncate text-left">Search</div>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="mr-px h-4 min-w-0 rounded-sm bg-sidebar-control-surface px-1.5 text-[10px] text-sidebar-muted-foreground ring-1 ring-sidebar-border">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
</div>
|
||||
<div className="shrink-0">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="icon"
|
||||
type="button"
|
||||
className="relative focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
onClick={handleNewThreadClick}
|
||||
disabled={projects.length === 0}
|
||||
aria-label="New thread"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<MenuRadioItem
|
||||
value="all"
|
||||
closeOnClick
|
||||
className="h-8 min-h-8 px-1 py-0 text-sm font-medium [&>span:last-child]:flex [&>span:last-child]:min-w-0 [&>span:last-child]:items-center [&>span:last-child]:gap-2"
|
||||
>
|
||||
<FolderIcon className="size-4 shrink-0" />
|
||||
<span className="min-w-0 truncate text-sm">All projects</span>
|
||||
</MenuRadioItem>
|
||||
{projectGroups.map((project) => {
|
||||
const scopeKey = project.projectKey;
|
||||
return (
|
||||
<MenuRadioItem
|
||||
key={scopeKey}
|
||||
value={scopeKey}
|
||||
closeOnClick
|
||||
className="h-8 min-h-8 px-1 py-0 text-sm font-medium [&>span:last-child]:flex [&>span:last-child]:min-w-0 [&>span:last-child]:items-center [&>span:last-child]:gap-2"
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
<span className="min-w-0 truncate text-sm">{project.displayName}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Project actions for ${project.displayName}`}
|
||||
title={`Project actions for ${project.displayName}`}
|
||||
className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground/55 outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
void handleProjectActions(event, project);
|
||||
}}
|
||||
>
|
||||
<EllipsisIcon className="size-3.5" />
|
||||
</button>
|
||||
</MenuRadioItem>
|
||||
);
|
||||
})}
|
||||
</MenuRadioGroup>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="relative size-8 shrink-0 justify-center rounded-md bg-transparent p-0 text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
onClick={openAddProjectCommandPalette}
|
||||
type="button"
|
||||
aria-label="New project"
|
||||
<SquarePenIcon />
|
||||
<span
|
||||
className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FolderPlusIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
<span
|
||||
className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">New project</TooltipPopup>
|
||||
</Tooltip>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">
|
||||
{newThreadShortcutLabel
|
||||
? `New thread (${newThreadShortcutLabel})`
|
||||
: "New thread"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
{projectGroups.length > 0 ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<Menu open={projectScopeMenuOpen} onOpenChange={setProjectScopeMenuOpen}>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
aria-label="Filter threads by project"
|
||||
className="min-w-0 flex-1 focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{scopedProjectGroup ? (
|
||||
<ProjectFavicon
|
||||
environmentId={scopedProjectGroup.environmentId}
|
||||
cwd={scopedProjectGroup.workspaceRoot}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<FolderIcon className="size-4 shrink-0" />
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{scopedProjectGroup?.displayName ?? "All projects"}
|
||||
</span>
|
||||
<ChevronDownIcon className="-mr-px size-4 shrink-0" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start" className="w-(--anchor-width)">
|
||||
<MenuRadioGroup
|
||||
value={projectScopeKey ?? "all"}
|
||||
onValueChange={(value) =>
|
||||
setProjectScopeKey(value === "all" ? null : (value as string))
|
||||
}
|
||||
>
|
||||
<MenuRadioItem
|
||||
value="all"
|
||||
closeOnClick
|
||||
className="h-8 min-h-8 px-1 py-0 text-sm font-medium [&>span:last-child]:flex [&>span:last-child]:min-w-0 [&>span:last-child]:items-center [&>span:last-child]:gap-2"
|
||||
>
|
||||
<FolderIcon className="size-4 shrink-0" />
|
||||
<span className="min-w-0 truncate text-sm">All projects</span>
|
||||
</MenuRadioItem>
|
||||
{projectGroups.map((project) => {
|
||||
const scopeKey = project.projectKey;
|
||||
return (
|
||||
<MenuRadioItem
|
||||
key={scopeKey}
|
||||
value={scopeKey}
|
||||
closeOnClick
|
||||
className="h-8 min-h-8 px-1 py-0 text-sm font-medium [&>span:last-child]:flex [&>span:last-child]:min-w-0 [&>span:last-child]:items-center [&>span:last-child]:gap-2"
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
<span className="min-w-0 truncate text-sm">{project.displayName}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Project actions for ${project.displayName}`}
|
||||
title={`Project actions for ${project.displayName}`}
|
||||
className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground/55 outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
void handleProjectActions(event, project);
|
||||
}}
|
||||
>
|
||||
<EllipsisIcon className="size-3.5" />
|
||||
</button>
|
||||
</MenuRadioItem>
|
||||
);
|
||||
})}
|
||||
</MenuRadioGroup>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="icon"
|
||||
className="relative shrink-0 focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
onClick={openAddProjectCommandPalette}
|
||||
type="button"
|
||||
aria-label="New project"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FolderPlusIcon />
|
||||
<span
|
||||
className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">New project</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : null}
|
||||
</SidebarGroup>
|
||||
) : null}
|
||||
<SidebarGroup className="min-h-0 flex-1 overflow-y-auto px-2 py-1 [scrollbar-gutter:stable]">
|
||||
}
|
||||
>
|
||||
<SidebarGroup className="px-2 pb-1 pt-0">
|
||||
<TooltipProvider
|
||||
key="sidebar-thread-tooltips-150"
|
||||
delay={150}
|
||||
@@ -2526,12 +2543,10 @@ export default function SidebarV2() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={showMoreSettled}
|
||||
className="mt-1 flex h-[30px] w-full items-center justify-center gap-1.5 rounded-md border border-dashed border-border font-mono text-[11px] text-muted-foreground transition-colors hover:border-solid hover:border-input hover:bg-background/45 hover:text-foreground dark:border-white/15 dark:hover:border-white/30 dark:hover:bg-transparent"
|
||||
className="flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-left text-sm text-sidebar-muted-foreground/55 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
>
|
||||
<PlusIcon aria-hidden className="size-4 shrink-0" />
|
||||
Show {Math.min(hiddenSettledCount, SETTLED_TAIL_PAGE_COUNT)} more
|
||||
<span className="text-muted-foreground/50">
|
||||
({hiddenSettledCount} settled hidden)
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
) : null}
|
||||
@@ -2547,7 +2562,7 @@ export default function SidebarV2() {
|
||||
onClick={openAddProjectCommandPalette}
|
||||
className="inline-flex items-center gap-1.5 rounded-md border border-sidebar-border px-2.5 py-1 text-[11px] font-medium text-sidebar-muted-foreground transition-colors hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
>
|
||||
<PlusIcon className="size-3" />
|
||||
<PlusIcon className="-mx-0.5 size-3" />
|
||||
Add project
|
||||
</button>
|
||||
</>
|
||||
@@ -2567,48 +2582,52 @@ export default function SidebarV2() {
|
||||
}}
|
||||
>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader className="gap-1.5">
|
||||
<DialogHeader className="gap-3 pb-1!">
|
||||
<DialogTitle className="text-balance">Project settings</DialogTitle>
|
||||
<DialogDescription>
|
||||
{projectActionsTarget && projectActionsTarget.memberProjects.length > 1
|
||||
? `${projectActionsTarget.displayName} has an entry in each environment. Changes apply only to the entry you choose.`
|
||||
: `Manage ${projectActionsTarget?.displayName ?? "this project"} in this environment.`}
|
||||
<DialogDescription className="sr-only">
|
||||
Manage project names, grouping rules, and environments.
|
||||
</DialogDescription>
|
||||
<div className="grid gap-1.5 text-base text-muted-foreground">
|
||||
{projectActionsTarget?.memberProjects.map((member) => (
|
||||
<div key={member.physicalProjectKey} className="flex min-w-0 items-center gap-3">
|
||||
<span className="flex min-w-0 items-center gap-1">
|
||||
<FolderIcon className="size-3.5 shrink-0 opacity-60" />
|
||||
<span className="min-w-0 truncate font-mono">{member.workspaceRoot}</span>
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-4 shrink-0 rounded-sm"
|
||||
aria-label="Copy project path"
|
||||
title="Copy project path"
|
||||
onClick={() =>
|
||||
copyProjectPath(member.workspaceRoot, { path: member.workspaceRoot })
|
||||
}
|
||||
>
|
||||
<CopyIcon className="size-3.5" />
|
||||
</Button>
|
||||
</span>
|
||||
<span className="flex min-w-0 shrink-0 items-center gap-1">
|
||||
<ServerIcon className="size-3.5 shrink-0 opacity-60" />
|
||||
<span className="min-w-0 truncate">
|
||||
{member.environmentLabel ?? "Current environment"}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="p-0">
|
||||
<div className="divide-y divide-border/60">
|
||||
{projectActionsTarget?.memberProjects.map((member) => (
|
||||
<section
|
||||
key={member.physicalProjectKey}
|
||||
className="flex min-w-0 flex-col gap-4 px-6 py-5 sm:gap-3 sm:py-4"
|
||||
className="grid min-w-0 gap-5 px-6 pb-5 pt-2 sm:gap-4 sm:pb-4 sm:pt-2"
|
||||
>
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
<ProjectFavicon
|
||||
environmentId={member.environmentId}
|
||||
cwd={member.workspaceRoot}
|
||||
className="size-5 shrink-0 sm:size-4"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-center gap-1.5 text-base text-muted-foreground sm:text-sm">
|
||||
<ServerIcon className="size-4 shrink-0 stroke-muted-foreground" />
|
||||
<p className="min-w-0 truncate">
|
||||
{member.environmentLabel ?? "Current environment"}
|
||||
</p>
|
||||
</div>
|
||||
<p
|
||||
className="truncate font-mono text-base text-muted-foreground/72 sm:text-sm"
|
||||
title={member.workspaceRoot}
|
||||
>
|
||||
{member.workspaceRoot}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2 sm:gap-3 sm:pl-7">
|
||||
<div className="grid gap-4 sm:grid-cols-2 sm:gap-3">
|
||||
<label className="grid min-w-0 gap-1.5">
|
||||
<span className="font-medium text-foreground">Project name</span>
|
||||
<Input
|
||||
key={`${member.physicalProjectKey}:${member.title}`}
|
||||
size="sm"
|
||||
aria-label={`Project name in ${member.environmentLabel ?? "current environment"}`}
|
||||
defaultValue={member.title}
|
||||
onBlur={(event) => {
|
||||
@@ -2639,8 +2658,7 @@ export default function SidebarV2() {
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
size="sm"
|
||||
className="w-full"
|
||||
className="w-full sm:min-h-7.5"
|
||||
aria-label={`Grouping rule for ${member.environmentLabel ?? "current environment"}`}
|
||||
>
|
||||
<SelectValue>
|
||||
@@ -2672,32 +2690,23 @@ export default function SidebarV2() {
|
||||
</Select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2 sm:pl-7">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
copyProjectPath(member.workspaceRoot, { path: member.workspaceRoot })
|
||||
}
|
||||
>
|
||||
<CopyIcon />
|
||||
Copy path
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-destructive-foreground hover:bg-destructive/8 hover:text-destructive-foreground sm:ml-auto"
|
||||
onClick={() => {
|
||||
const projectGroup = projectActionsTarget;
|
||||
if (!projectGroup) return;
|
||||
setProjectActionsTarget(null);
|
||||
void handleRemoveProjectMembers(projectGroup, [member]);
|
||||
}}
|
||||
>
|
||||
<Trash2Icon />
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
{projectActionsTarget.memberProjects.length > 1 ? (
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-destructive-foreground hover:bg-destructive/8 hover:text-destructive-foreground"
|
||||
onClick={() => {
|
||||
const projectGroup = projectActionsTarget;
|
||||
setProjectActionsTarget(null);
|
||||
void handleRemoveProjectMembers(projectGroup, [member]);
|
||||
}}
|
||||
>
|
||||
<Trash2Icon />
|
||||
Remove project
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
@@ -2727,8 +2736,26 @@ export default function SidebarV2() {
|
||||
</div>
|
||||
) : null}
|
||||
</DialogPanel>
|
||||
<DialogFooter variant="bare">
|
||||
<Button onClick={() => setProjectActionsTarget(null)}>Done</Button>
|
||||
<DialogFooter
|
||||
variant="bare"
|
||||
className={cn(
|
||||
projectActionsTarget?.memberProjects.length === 1 && "sm:justify-between",
|
||||
)}
|
||||
>
|
||||
{projectActionsTarget?.memberProjects.length === 1 ? (
|
||||
<Button
|
||||
variant="destructive-outline"
|
||||
onClick={() => {
|
||||
const projectGroup = projectActionsTarget;
|
||||
setProjectActionsTarget(null);
|
||||
void handleRemoveProjectMembers(projectGroup, projectGroup.memberProjects);
|
||||
}}
|
||||
>
|
||||
<Trash2Icon />
|
||||
Remove project
|
||||
</Button>
|
||||
) : null}
|
||||
<Button onClick={() => setProjectActionsTarget(null)}>Close</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
|
||||
@@ -57,10 +57,8 @@ import {
|
||||
useEffectiveComposerModelState,
|
||||
} from "../../composerDraftStore";
|
||||
import {
|
||||
EMPTY_PROMPT_STASH_QUEUE,
|
||||
MAX_STASH_ENTRIES_PER_QUEUE,
|
||||
MAX_STASH_ENTRIES,
|
||||
partitionStashAttachments,
|
||||
promptStashScopeKey,
|
||||
usePromptStashStore,
|
||||
type PromptStashEntry,
|
||||
} from "../../promptStashStore";
|
||||
@@ -95,6 +93,7 @@ import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
|
||||
import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
|
||||
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
|
||||
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
|
||||
import { ComposerControl, ComposerControlIcon, ComposerSelectControl } from "./ComposerControl";
|
||||
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
|
||||
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
|
||||
import {
|
||||
@@ -167,7 +166,7 @@ function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children:
|
||||
);
|
||||
}
|
||||
import { Button } from "../ui/button";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Select, SelectItem, SelectPopup, SelectValue } from "../ui/select";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { toastManager } from "../ui/toast";
|
||||
import {
|
||||
@@ -303,15 +302,13 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
<ComposerControl
|
||||
className={cn(
|
||||
"shrink-0 whitespace-nowrap px-2 sm:px-3",
|
||||
"shrink-0 whitespace-nowrap",
|
||||
props.interactionMode === "plan"
|
||||
? "bg-blue-500/10 text-blue-400 hover:bg-blue-500/15 hover:text-blue-300"
|
||||
: "text-muted-foreground/70 hover:text-foreground/80",
|
||||
)}
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={props.onToggleInteractionMode}
|
||||
aria-label={interactionModeTooltip}
|
||||
@@ -319,9 +316,9 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
}
|
||||
>
|
||||
{props.interactionMode === "plan" ? (
|
||||
<PencilRulerIcon className="text-current opacity-100" />
|
||||
<ComposerControlIcon icon={PencilRulerIcon} className="text-current opacity-100" />
|
||||
) : (
|
||||
<BotIcon />
|
||||
<ComposerControlIcon icon={BotIcon} opticalSize="large" />
|
||||
)}
|
||||
<span className="sr-only sm:not-sr-only">
|
||||
{props.interactionMode === "plan" ? "Plan" : "Build"}
|
||||
@@ -342,16 +339,9 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
onValueChange={(value) => props.onRuntimeModeChange(value!)}
|
||||
>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SelectTrigger
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="font-medium"
|
||||
aria-label="Runtime mode"
|
||||
/>
|
||||
}
|
||||
render={<ComposerSelectControl className="font-medium" aria-label="Runtime mode" />}
|
||||
>
|
||||
<RuntimeModeIcon className="size-4" />
|
||||
<ComposerControlIcon icon={RuntimeModeIcon} />
|
||||
<SelectValue>{runtimeModeOption.label}</SelectValue>
|
||||
</TooltipTrigger>
|
||||
<SelectPopup alignItemWithTrigger={false}>
|
||||
@@ -387,22 +377,21 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
<ComposerControl
|
||||
className={cn(
|
||||
"shrink-0 whitespace-nowrap px-2 sm:px-3",
|
||||
"shrink-0 whitespace-nowrap",
|
||||
props.planSidebarOpen
|
||||
? "bg-blue-500/10 text-blue-400 hover:bg-blue-500/15 hover:text-blue-300"
|
||||
: "text-muted-foreground/70 hover:text-foreground/80",
|
||||
)}
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={props.onTogglePlanSidebar}
|
||||
aria-label={planSidebarTooltip}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ListTodoIcon
|
||||
<ComposerControlIcon
|
||||
icon={ListTodoIcon}
|
||||
className={props.planSidebarOpen ? "text-current opacity-100" : undefined}
|
||||
/>
|
||||
<span className="sr-only sm:not-sr-only">{props.planSidebarLabel}</span>
|
||||
@@ -742,7 +731,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const clearComposerDraftPromptAndImages = useComposerDraftStore(
|
||||
(store) => store.clearComposerPromptAndImages,
|
||||
);
|
||||
const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection);
|
||||
const syncComposerDraftPersistedAttachments = useComposerDraftStore(
|
||||
(store) => store.syncPersistedAttachments,
|
||||
);
|
||||
@@ -1897,23 +1885,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// ------------------------------------------------------------------
|
||||
// Prompt stash (⌘S)
|
||||
// ------------------------------------------------------------------
|
||||
const stashScopeInstanceId = noProviderAvailable ? null : selectedInstanceId;
|
||||
const stashScope = promptStashScopeKey(stashScopeInstanceId);
|
||||
const stashQueue = usePromptStashStore(
|
||||
(state) => state.queuesByScopeKey[stashScope] ?? EMPTY_PROMPT_STASH_QUEUE,
|
||||
);
|
||||
const stashOtherScopesCount = usePromptStashStore((state) =>
|
||||
Object.entries(state.queuesByScopeKey).reduce(
|
||||
(total, [key, queue]) => (key === stashScope ? total : total + queue.length),
|
||||
0,
|
||||
),
|
||||
);
|
||||
// One global queue. Stashed prompts carry only text + images so they can be
|
||||
// restored into any thread or provider — stash, switch, restore is the
|
||||
// whole point.
|
||||
const stashQueue = usePromptStashStore((state) => state.entries);
|
||||
const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry);
|
||||
const takeStashEntry = usePromptStashStore((state) => state.takeEntry);
|
||||
const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages);
|
||||
const stashProviderLabel = noProviderAvailable
|
||||
? "No provider"
|
||||
: getProviderDisplayName(providerStatuses, selectedProvider);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -1939,10 +1917,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const restoreStashEntry = useCallback(
|
||||
(entry: PromptStashEntry) => {
|
||||
// Remove first so a double activation (click + Enter) can't restore twice.
|
||||
const { entry: taken, durable } = takeStashEntry(
|
||||
promptStashScopeKey(entry.providerInstanceId),
|
||||
entry.id,
|
||||
);
|
||||
const { entry: taken, durable } = takeStashEntry(entry.id);
|
||||
if (!taken) return;
|
||||
if (!durable) {
|
||||
toastManager.add({
|
||||
@@ -2005,21 +1980,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
}
|
||||
}
|
||||
|
||||
const restorableSelection =
|
||||
entry.modelSelection &&
|
||||
providerInstanceEntries.some(
|
||||
(candidate) =>
|
||||
candidate.instanceId === entry.modelSelection?.instanceId &&
|
||||
candidate.enabled &&
|
||||
candidate.isAvailable,
|
||||
)
|
||||
? entry.modelSelection
|
||||
: null;
|
||||
if (restorableSelection) {
|
||||
setComposerDraftModelSelection(composerDraftTarget, restorableSelection, {
|
||||
replaceOptions: true,
|
||||
});
|
||||
}
|
||||
// Deliberately no model/provider restore: the stash exists to carry a
|
||||
// prompt across threads and providers, so whatever the composer has
|
||||
// selected right now stays selected.
|
||||
|
||||
// Each cause gets its own sentence so "too large" is never blamed for a
|
||||
// file that actually failed to decode, or for one the composer simply
|
||||
@@ -2061,8 +2024,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
composerDraftTarget,
|
||||
composerImagesRef,
|
||||
promptRef,
|
||||
providerInstanceEntries,
|
||||
setComposerDraftModelSelection,
|
||||
setComposerDraftPrompt,
|
||||
takeStashEntry,
|
||||
],
|
||||
@@ -2070,7 +2031,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
|
||||
const deleteStashEntry = useCallback(
|
||||
(entry: PromptStashEntry) => {
|
||||
const { durable } = takeStashEntry(promptStashScopeKey(entry.providerInstanceId), entry.id);
|
||||
const { durable } = takeStashEntry(entry.id);
|
||||
if (!durable) {
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
@@ -2106,30 +2067,27 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
|
||||
const stashTarget = composerDraftTarget;
|
||||
const entryId = randomUUID();
|
||||
const scopeKey = promptStashScopeKey(stashScopeInstanceId);
|
||||
try {
|
||||
// Persist the text-only entry *first*, then clear. Ordering matters in
|
||||
// both directions: writing before clearing means a crash or closed tab
|
||||
// mid-encode still leaves the prompt recoverable, while clearing before
|
||||
// the async image work means edits typed during encoding are not wiped.
|
||||
// Images are appended to the stored entry as they finish encoding.
|
||||
const { evicted, durable } = stashEntryToQueue({
|
||||
const { evicted, written, durable } = stashEntryToQueue({
|
||||
id: entryId,
|
||||
createdAt: new Date().toISOString(),
|
||||
prompt,
|
||||
attachments: [],
|
||||
providerInstanceId: stashScopeInstanceId,
|
||||
modelSelection: noProviderAvailable ? null : selectedModelSelection,
|
||||
droppedImageNames: [],
|
||||
unreadableImageNames: [],
|
||||
pendingImageCount: images.length,
|
||||
});
|
||||
|
||||
// Clearing the composer is only safe once the entry is durable. If the
|
||||
// write was rejected (quota, blocked storage) the store has already
|
||||
// rolled itself back, so leave the composer untouched rather than
|
||||
// making it the second casualty of a reload.
|
||||
if (!durable) {
|
||||
// Clearing the composer is only safe once the write actually landed.
|
||||
// If it was rejected (quota) the store has already rolled itself back,
|
||||
// so leave the composer untouched rather than making it the second
|
||||
// casualty of a reload.
|
||||
if (!written) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not stash this prompt",
|
||||
@@ -2139,6 +2097,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Written but only into the in-memory fallback (localStorage blocked):
|
||||
// the entry is visible and restorable this session, so proceed with the
|
||||
// clear, but say it won't survive a reload.
|
||||
if (!durable) {
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Stashed prompt will not survive a reload",
|
||||
description:
|
||||
"Browser storage is unavailable, so this stash is kept in memory only for this session.",
|
||||
data: { hideCopyButton: true },
|
||||
});
|
||||
}
|
||||
|
||||
// Only the prompt and images are cleared — terminal/element contexts,
|
||||
// preview annotations, and review comments are not stashable, so
|
||||
@@ -2153,7 +2123,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Oldest stashed prompt discarded",
|
||||
description: `The ${stashProviderLabel} stash holds ${MAX_STASH_ENTRIES_PER_QUEUE} prompts; the oldest was removed to make room.`,
|
||||
description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`,
|
||||
data: { hideCopyButton: true },
|
||||
});
|
||||
}
|
||||
@@ -2185,7 +2155,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
}
|
||||
const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);
|
||||
|
||||
const { attached, durable: imagesDurable } = finalizeStashEntryImages(scopeKey, entryId, {
|
||||
const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, {
|
||||
attachments: kept,
|
||||
droppedImageNames: [...oversizedImageNames, ...droppedNames],
|
||||
unreadableImageNames,
|
||||
@@ -2194,8 +2164,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// The second phase can be rejected on its own: the text-only entry
|
||||
// fit, but adding image payloads pushed past the quota. Disk would
|
||||
// then still hold the phase-one entry with pendingImageCount set,
|
||||
// which reads as an orphan after reload — so say so now.
|
||||
if (!imagesDurable && images.length > 0) {
|
||||
// which reads as an orphan after reload — so say so now. Gated on the
|
||||
// entry write having been durable: on the in-memory fallback nothing
|
||||
// is ever durable, and the session-only warning already covered it.
|
||||
if (!imagesDurable && durable && images.length > 0) {
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Stashed images were not saved",
|
||||
@@ -2225,13 +2197,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
composerDraftTarget,
|
||||
composerImagesRef,
|
||||
finalizeStashEntryImages,
|
||||
noProviderAvailable,
|
||||
promptRef,
|
||||
pulseStashBadge,
|
||||
selectedModelSelection,
|
||||
stashEntryToQueue,
|
||||
stashProviderLabel,
|
||||
stashScopeInstanceId,
|
||||
]);
|
||||
|
||||
const toggleStashMenu = useCallback(() => {
|
||||
@@ -2841,8 +2809,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
<ComposerCommandMenuLayer anchor={composerMenuAnchor}>
|
||||
<ComposerStashMenu
|
||||
entries={stashQueue}
|
||||
providerLabel={stashProviderLabel}
|
||||
otherScopesCount={stashOtherScopesCount}
|
||||
onRestore={restoreStashEntry}
|
||||
onDelete={deleteStashEntry}
|
||||
onClose={() => setIsStashMenuOpen(false)}
|
||||
|
||||
@@ -93,7 +93,7 @@ export function ComposerBannerStack({ className, items }: ComposerBannerStackPro
|
||||
{showCollapsedStackCap ? (
|
||||
<div
|
||||
className={cn(
|
||||
"pointer-events-none absolute inset-x-0 -top-3 z-0 mx-auto h-3 rounded-t-xl",
|
||||
"pointer-events-none absolute inset-x-0 -top-3 z-0 mx-auto h-3 rounded-t-[22px]",
|
||||
"border border-b-0 border-warning/24 bg-background/96 shadow-[0_6px_18px_rgba(0,0,0,0.06)]",
|
||||
"transition-opacity duration-150 ease-out",
|
||||
"group-hover/banner-stack:opacity-0 group-focus-within/banner-stack:opacity-0",
|
||||
@@ -174,7 +174,7 @@ function ComposerBannerStackAlert({
|
||||
return (
|
||||
<Alert
|
||||
variant={item.variant}
|
||||
className={cn("alert-glass", item.className)}
|
||||
className={cn("alert-glass rounded-[22px]", item.className)}
|
||||
data-variant={item.variant}
|
||||
>
|
||||
{item.icon}
|
||||
|
||||
@@ -139,7 +139,10 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
);
|
||||
}}
|
||||
>
|
||||
<div ref={listRef} className="dropdown-glass relative w-full overflow-hidden rounded-[20px]">
|
||||
<div
|
||||
ref={listRef}
|
||||
className="dropdown-glass relative w-full overflow-hidden rounded-[20px] **:data-[slot=scroll-area-scrollbar]:data-[orientation=vertical]:my-4"
|
||||
>
|
||||
{props.items.length > 0 ? (
|
||||
<CommandList className="max-h-72">
|
||||
{groups.map((group, groupIndex) => (
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { ComponentProps } from "react";
|
||||
import { ChevronDownIcon, type LucideIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Button } from "../ui/button";
|
||||
import { SelectTrigger } from "../ui/select";
|
||||
|
||||
const composerControlClassName =
|
||||
"h-7 min-h-7 gap-1.5 px-2.5 text-muted-foreground/70 transition-none hover:text-foreground/80 [&_svg[data-composer-control-icon]]:mx-0 [&_svg[data-composer-control-chevron]]:-mx-0.5";
|
||||
|
||||
export function ComposerControl({
|
||||
className,
|
||||
size = "sm",
|
||||
variant = "ghost",
|
||||
...props
|
||||
}: ComponentProps<typeof Button>) {
|
||||
return (
|
||||
<Button
|
||||
className={cn(composerControlClassName, className)}
|
||||
size={size}
|
||||
variant={variant}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComposerControlIcon({
|
||||
icon: Icon,
|
||||
className,
|
||||
opticalSize = "default",
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
className?: string | undefined;
|
||||
opticalSize?: "default" | "large";
|
||||
}) {
|
||||
return (
|
||||
<Icon
|
||||
aria-hidden="true"
|
||||
className={cn("shrink-0", opticalSize === "large" ? "size-4.5" : "size-4", className)}
|
||||
data-composer-control-icon
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComposerControlChevron() {
|
||||
return (
|
||||
<ChevronDownIcon
|
||||
aria-hidden="true"
|
||||
className="-mx-0.5 size-3.5 shrink-0 text-muted-foreground opacity-70"
|
||||
data-composer-control-chevron
|
||||
strokeWidth={2.25}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComposerSelectControl({
|
||||
className,
|
||||
size = "sm",
|
||||
variant = "ghost",
|
||||
...props
|
||||
}: ComponentProps<typeof SelectTrigger>) {
|
||||
return (
|
||||
<SelectTrigger
|
||||
className={cn(composerControlClassName, className)}
|
||||
icon={<ComposerControlChevron />}
|
||||
size={size}
|
||||
variant={variant}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { memo, type PointerEventHandler } from "react";
|
||||
import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react";
|
||||
import { useEnvironmentIdentificationMode } from "~/hooks/useSettings";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { StageBackdropButtonArt, useSidebarStageBackdropVariant } from "../SidebarStageBackdrop";
|
||||
import { Button } from "../ui/button";
|
||||
@@ -72,7 +73,10 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
const pointerFocusProps = preserveComposerFocusOnPointerDown
|
||||
? { onPointerDown: preventPointerFocus }
|
||||
: undefined;
|
||||
const stageBackdropVariant = useSidebarStageBackdropVariant();
|
||||
const environmentIdentificationMode = useEnvironmentIdentificationMode();
|
||||
const stageBackdropVariant = useSidebarStageBackdropVariant(
|
||||
environmentIdentificationMode === "artwork",
|
||||
);
|
||||
|
||||
if (pendingAction) {
|
||||
return (
|
||||
|
||||
@@ -5,8 +5,7 @@ import { cn } from "~/lib/utils";
|
||||
|
||||
/**
|
||||
* Bookmark pill perched on the composer's top-right shoulder. Shows the
|
||||
* current method's stash count and doubles as the click target for opening
|
||||
* the stash menu.
|
||||
* stash count and doubles as the click target for opening the stash menu.
|
||||
*
|
||||
* On save the badge gives one quiet acknowledgement: it lifts to full
|
||||
* opacity and the count ticks over. `pulseKey` changes per stash, remounting
|
||||
|
||||
@@ -24,16 +24,13 @@ function stashEntrySnippet(entry: PromptStashEntry): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Popover listing the current connection method's stashed prompts.
|
||||
* Keyboard-first: opened by ⌘S on an empty composer, navigated with
|
||||
* arrows, restored with Enter, dismissed with Escape. The listener runs
|
||||
* capture-phase on window so it wins over the Lexical editor's handlers
|
||||
* while the menu is open.
|
||||
* Popover listing the stashed prompts. Keyboard-first: opened by ⌘S on an
|
||||
* empty composer, navigated with arrows, restored with Enter, dismissed
|
||||
* with Escape. The listener runs capture-phase on window so it wins over
|
||||
* the Lexical editor's handlers while the menu is open.
|
||||
*/
|
||||
export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
|
||||
entries: ReadonlyArray<PromptStashEntry>;
|
||||
providerLabel: string;
|
||||
otherScopesCount: number;
|
||||
onRestore: (entry: PromptStashEntry) => void;
|
||||
onDelete: (entry: PromptStashEntry) => void;
|
||||
onClose: () => void;
|
||||
@@ -99,12 +96,11 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
|
||||
<CommandGroup>
|
||||
<CommandGroupLabel className="flex items-center gap-1.5 px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
|
||||
<BookmarkIcon className="size-3" aria-hidden="true" />
|
||||
Stashed prompts — {props.providerLabel}
|
||||
Stashed prompts
|
||||
</CommandGroupLabel>
|
||||
{entries.length === 0 ? (
|
||||
<p className="px-3 pb-3 pt-1 text-muted-foreground/70 text-xs">
|
||||
Nothing stashed for this method yet. Press ⌘S with a prompt in the composer to stash
|
||||
it.
|
||||
Nothing stashed yet. Press ⌘S with a prompt in the composer to stash it.
|
||||
</p>
|
||||
) : (
|
||||
entries.map((entry) => (
|
||||
@@ -173,12 +169,6 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
|
||||
))
|
||||
)}
|
||||
</CommandGroup>
|
||||
{props.otherScopesCount > 0 ? (
|
||||
<p className="border-t border-border/50 px-3 py-2 text-[11px] text-muted-foreground/60">
|
||||
{props.otherScopesCount} more stashed under other connection methods — switch provider
|
||||
to see them.
|
||||
</p>
|
||||
) : null}
|
||||
</CommandList>
|
||||
</div>
|
||||
</Command>
|
||||
|
||||
@@ -101,11 +101,11 @@ export function DraftHeroHeadline({
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
|
||||
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-foreground underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="pointer-events-auto inline cursor-pointer border-foreground/60 border-b border-dotted text-foreground transition-colors hover:border-foreground/80 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{activeProjectDisplayName ?? "Choose a project"}
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="center" className="max-h-80 w-64 overflow-y-auto">
|
||||
<MenuPopup align="center" className="max-h-80 min-w-40! w-max max-w-64 overflow-y-auto">
|
||||
<MenuRadioGroup
|
||||
value={activeProjectKey}
|
||||
onValueChange={(value) => {
|
||||
@@ -138,7 +138,7 @@ export function DraftHeroHeadline({
|
||||
<button
|
||||
type="button"
|
||||
onClick={openAddProject}
|
||||
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-muted-foreground/60 underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="pointer-events-auto inline cursor-pointer border-muted-foreground/35 border-b border-dotted text-muted-foreground/60 transition-colors hover:border-muted-foreground/60 hover:text-muted-foreground/80 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{activeProjectTitle ?? "Add a project"}
|
||||
</button>
|
||||
|
||||
@@ -50,7 +50,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
|
||||
disabled={Boolean(props.disabledReason)}
|
||||
contentClassName="flex w-full items-center gap-3"
|
||||
className={cn(
|
||||
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2.5 transition-[background-color,box-shadow,color]",
|
||||
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2 transition-[background-color,box-shadow,color]",
|
||||
"hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-highlighted:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0 [&[data-highlighted][data-selected]]:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))]",
|
||||
props.disabledReason &&
|
||||
"data-disabled:pointer-events-auto data-disabled:cursor-not-allowed data-disabled:hover:bg-transparent",
|
||||
|
||||
@@ -43,6 +43,10 @@ type ModelPickerItem = {
|
||||
|
||||
const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
|
||||
|
||||
function ModelListSeparator() {
|
||||
return <div className="h-0.5" />;
|
||||
}
|
||||
|
||||
// Split a `${instanceId}:${slug}` combobox key back into its pieces. Slugs
|
||||
// can contain colons (e.g. some vendor model ids), so we only split on the
|
||||
// first colon — anything after that is the slug.
|
||||
@@ -521,7 +525,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
return (
|
||||
<TooltipProvider delay={0}>
|
||||
<div
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-lg text-popover-foreground [clip-path:inset(0_round_var(--radius-lg))]"
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-86.5 w-screen max-w-90 flex-row overflow-hidden rounded-lg text-popover-foreground [clip-path:inset(0_round_var(--radius-lg))]"
|
||||
data-model-picker-content="true"
|
||||
>
|
||||
{/* Sidebar */}
|
||||
@@ -571,12 +575,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
|
||||
showSidebar && "border-l",
|
||||
showSidebar && "border-l border-border/70",
|
||||
)}
|
||||
>
|
||||
{/* Search bar */}
|
||||
<div className="px-4 pt-2.5">
|
||||
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<div className="px-2 pt-2">
|
||||
<div className="border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<ComboboxInput
|
||||
ref={searchInputRef}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
@@ -584,7 +588,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground opacity-70" />
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
@@ -618,8 +622,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
</div>
|
||||
|
||||
{/* Model list */}
|
||||
<div className="relative min-h-0 flex-1 overflow-hidden">
|
||||
<ComboboxListVirtualized className="model-picker-list size-full min-w-0 p-0">
|
||||
<div className="relative min-h-0 flex-1 overflow-hidden pr-px">
|
||||
<ComboboxListVirtualized className="size-full min-w-0 p-0 not-empty:p-0">
|
||||
<LegendList<string>
|
||||
ref={modelListRef}
|
||||
data={filteredModelKeys}
|
||||
@@ -656,12 +660,14 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
estimatedItemSize={60}
|
||||
drawDistance={480}
|
||||
recycleItems
|
||||
contentContainerClassName="pl-2 pr-px"
|
||||
ItemSeparatorComponent={ModelListSeparator}
|
||||
onLayout={updateModelListScrollFades}
|
||||
onScroll={updateModelListScrollFades}
|
||||
className={cn(
|
||||
"scrollbar-gutter-both h-full overflow-x-hidden overscroll-y-contain py-1.5 [--fade-size:1.5rem]",
|
||||
showTopScrollFade && "mask-t-from-[calc(100%-var(--fade-size))]",
|
||||
showBottomScrollFade && "mask-b-from-[calc(100%-var(--fade-size))]",
|
||||
"model-picker-list h-full overflow-x-hidden overscroll-y-contain py-1.5 [--fade-size:1.5rem]",
|
||||
showTopScrollFade && "model-picker-list-scroll-fade-top",
|
||||
showBottomScrollFade && "model-picker-list-scroll-fade-bottom",
|
||||
)}
|
||||
/>
|
||||
</ComboboxListVirtualized>
|
||||
|
||||
@@ -78,34 +78,20 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
if (!content) {
|
||||
return;
|
||||
}
|
||||
const selectedButton = Array.from(
|
||||
const selectedItem = Array.from(
|
||||
content.querySelectorAll<HTMLElement>("[data-model-picker-provider]"),
|
||||
).find((button) => button.dataset.modelPickerProvider === props.selectedInstanceId);
|
||||
if (!selectedButton) {
|
||||
).find((item) => item.dataset.modelPickerProvider === props.selectedInstanceId);
|
||||
if (!selectedItem) {
|
||||
setSelectedIndicatorTop(null);
|
||||
return;
|
||||
}
|
||||
const contentRect = content.getBoundingClientRect();
|
||||
const selectedButtonRect = selectedButton.getBoundingClientRect();
|
||||
setSelectedIndicatorTop(
|
||||
selectedButtonRect.top -
|
||||
contentRect.top +
|
||||
content.scrollTop +
|
||||
selectedButtonRect.height / 2 -
|
||||
10,
|
||||
);
|
||||
setSelectedIndicatorTop(selectedItem.offsetTop + selectedItem.offsetHeight / 2 - 10);
|
||||
}, [props.instanceEntries, props.selectedInstanceId, showFavorites]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-12 shrink-0 overflow-hidden border-r bg-muted/30"
|
||||
data-model-picker-sidebar="true"
|
||||
>
|
||||
<div className="w-11 shrink-0 overflow-hidden bg-muted/30" data-model-picker-sidebar="true">
|
||||
<div className="h-full overflow-y-auto overscroll-contain [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<div
|
||||
ref={sidebarContentRef}
|
||||
className="relative flex min-h-full flex-col gap-1 px-1 pb-1 pt-0.5"
|
||||
>
|
||||
<div ref={sidebarContentRef} className="relative flex min-h-full flex-col gap-1 p-1">
|
||||
{selectedIndicatorTop !== null ? (
|
||||
<div
|
||||
data-model-picker-selected-indicator="true"
|
||||
@@ -118,8 +104,8 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
) : null}
|
||||
{/* Favorites section */}
|
||||
{showFavorites ? (
|
||||
<div className="mb-1 border-b pb-1">
|
||||
<div className="relative w-full">
|
||||
<>
|
||||
<div className="relative w-full" data-model-picker-provider="favorites">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
@@ -129,7 +115,6 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
)}
|
||||
onClick={() => handleSelect("favorites")}
|
||||
type="button"
|
||||
data-model-picker-provider="favorites"
|
||||
aria-label="Favorites"
|
||||
>
|
||||
<StarIcon className="size-5 fill-current shrink-0" aria-hidden />
|
||||
@@ -146,7 +131,8 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-b border-border/70" aria-hidden="true" />
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{/* Instance buttons (one per configured instance — built-in + custom) */}
|
||||
@@ -170,7 +156,6 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
|
||||
const button = (
|
||||
<button
|
||||
data-model-picker-provider={entry.instanceId}
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",
|
||||
@@ -228,7 +213,11 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
);
|
||||
|
||||
return (
|
||||
<div key={entry.instanceId} className="relative w-full">
|
||||
<div
|
||||
key={entry.instanceId}
|
||||
className="relative w-full"
|
||||
data-model-picker-provider={entry.instanceId}
|
||||
>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={trigger} />
|
||||
<TooltipPopup
|
||||
|
||||
@@ -5,8 +5,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { memo, useEffect, useMemo, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import { buttonVariants } from "../ui/button";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { cn } from "~/lib/utils";
|
||||
@@ -18,6 +17,7 @@ import {
|
||||
getTriggerDisplayModelName,
|
||||
} from "./providerIconUtils";
|
||||
import type { ProviderInstanceEntry } from "../../providerInstances";
|
||||
import { ComposerControl, ComposerControlChevron } from "./ComposerControl";
|
||||
|
||||
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
/**
|
||||
@@ -146,28 +146,27 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
<ComposerControl
|
||||
aria-label={props.triggerAriaLabel}
|
||||
size="sm"
|
||||
variant={props.triggerVariant ?? "ghost"}
|
||||
data-chat-provider-model-picker="true"
|
||||
className={cn(
|
||||
"min-w-0 justify-between whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80",
|
||||
props.compact ? "max-w-42 shrink-0" : "max-w-48 shrink sm:max-w-56 sm:px-3",
|
||||
"min-w-0 justify-between whitespace-nowrap",
|
||||
props.compact ? "max-w-42 shrink-0" : "max-w-48 shrink sm:max-w-56",
|
||||
props.triggerClassName,
|
||||
)}
|
||||
disabled={props.disabled}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<span className="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
{activeEntry ? (
|
||||
<ProviderInstanceIcon
|
||||
driverKind={activeEntry.driverKind}
|
||||
displayName={activeEntry.displayName}
|
||||
accentColor={activeEntry.accentColor}
|
||||
showBadge={showInstanceBadge}
|
||||
className={showInstanceBadge ? "size-5" : "size-4"}
|
||||
className="size-4"
|
||||
iconClassName={cn("size-4", props.activeProviderIconClassName)}
|
||||
indicatorBackground="var(--input)"
|
||||
badgeClassName={cn(
|
||||
@@ -184,7 +183,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
</Tooltip>
|
||||
</span>
|
||||
<span aria-hidden="true" className="flex items-center">
|
||||
<ChevronDownIcon aria-hidden="true" className="!ms-0 !-me-1 size-3 shrink-0 opacity-60" />
|
||||
<ComposerControlChevron />
|
||||
</span>
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup
|
||||
|
||||
@@ -52,10 +52,13 @@ export function renderSkillInlineMarkdownChildren(
|
||||
if (typeof child === "string") {
|
||||
return <SkillInlineText text={child} skills={skills} />;
|
||||
}
|
||||
if (!isValidElement<{ children?: ReactNode }>(child)) {
|
||||
if (!isValidElement<{ children?: ReactNode; node?: { tagName?: string } }>(child)) {
|
||||
return child;
|
||||
}
|
||||
if (child.type === "code" || child.type === "a") {
|
||||
// Custom react-markdown components replace the intrinsic type, so also
|
||||
// check the hast node they carry.
|
||||
const markdownTagName = typeof child.type === "string" ? child.type : child.props.node?.tagName;
|
||||
if (markdownTagName === "code" || markdownTagName === "a") {
|
||||
return child;
|
||||
}
|
||||
if (!("children" in child.props)) {
|
||||
|
||||
@@ -16,8 +16,8 @@ import {
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { ChevronDownIcon, ZapIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import { ZapIcon } from "lucide-react";
|
||||
import { buttonVariants } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
@@ -31,6 +31,7 @@ import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
|
||||
import { getProviderModelCapabilities } from "../../providerModels";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { ComposerControl, ComposerControlChevron, ComposerControlIcon } from "./ComposerControl";
|
||||
|
||||
type ProviderOptions = ReadonlyArray<ProviderOptionSelection>;
|
||||
|
||||
@@ -463,7 +464,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
});
|
||||
const fastModeIcon = showFastModeIcon ? (
|
||||
<>
|
||||
<ZapIcon aria-hidden="true" className="size-3 shrink-0 text-foreground/80 opacity-100" />
|
||||
<ComposerControlIcon icon={ZapIcon} className="text-foreground/80 opacity-100" />
|
||||
<span className="sr-only">Fast mode on</span>
|
||||
</>
|
||||
) : null;
|
||||
@@ -479,13 +480,12 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
<ComposerControl
|
||||
variant={triggerVariant ?? "ghost"}
|
||||
className={cn(
|
||||
isCodexStyle
|
||||
? "min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:max-w-48 sm:px-3 [&_svg]:mx-0"
|
||||
: "shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3",
|
||||
? "min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap sm:max-w-48"
|
||||
: "shrink-0 whitespace-nowrap",
|
||||
triggerClassName,
|
||||
)}
|
||||
/>
|
||||
@@ -495,13 +495,13 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
<span className="flex min-w-0 w-full items-center gap-1.5 overflow-hidden">
|
||||
{fastModeIcon}
|
||||
<span className="min-w-0 truncate">{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
<ComposerControlChevron />
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{fastModeIcon}
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
<ComposerControlChevron />
|
||||
</>
|
||||
)}
|
||||
</MenuTrigger>
|
||||
|
||||
@@ -53,12 +53,8 @@ function ConfiguredT3ConnectSidebarSignIn() {
|
||||
<>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="h-8 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
onClick={openAuthPrompt}
|
||||
>
|
||||
<LogInIcon className="size-4 shrink-0" />
|
||||
<SidebarMenuButton onClick={openAuthPrompt}>
|
||||
<LogInIcon />
|
||||
<span>Sign in to T3 Connect</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useClerk } from "@clerk/react";
|
||||
export function useT3ConnectAuthPrompt() {
|
||||
const clerk = useClerk();
|
||||
const openAuthPrompt = () => {
|
||||
clerk.openWaitlist();
|
||||
clerk.openSignIn({ forceRedirectUrl: window.location.href });
|
||||
};
|
||||
return { authPrompt: null, openAuthPrompt };
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { useClientSettings, useUpdateClientSettings } from "../../hooks/useSettings";
|
||||
import {
|
||||
useClientSettings,
|
||||
useSidebarV2Enabled,
|
||||
useUpdateClientSettings,
|
||||
} from "../../hooks/useSettings";
|
||||
import { Input } from "../ui/input";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
|
||||
@@ -51,7 +55,7 @@ function AutoSettleDaysInput({
|
||||
}
|
||||
|
||||
export function BetaSettingsPanel() {
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
const sidebarV2Enabled = useSidebarV2Enabled();
|
||||
const sidebarAutoSettleAfterDays = useClientSettings(
|
||||
(settings) => settings.sidebarAutoSettleAfterDays,
|
||||
);
|
||||
@@ -66,7 +70,14 @@ export function BetaSettingsPanel() {
|
||||
control={
|
||||
<Switch
|
||||
checked={sidebarV2Enabled}
|
||||
onCheckedChange={(checked) => updateSettings({ sidebarV2Enabled: Boolean(checked) })}
|
||||
// Touching the switch pins the choice, so a nightly build that
|
||||
// defaults v2 on does not flip it back after the user opts out.
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({
|
||||
sidebarV2Enabled: Boolean(checked),
|
||||
sidebarV2ConfiguredByUser: true,
|
||||
})
|
||||
}
|
||||
aria-label="Enable the sidebar v2 beta"
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -21,7 +21,9 @@ import {
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE,
|
||||
DEFAULT_UNIFIED_SETTINGS,
|
||||
type EnvironmentIdentificationMode,
|
||||
MAX_GLASS_OPACITY,
|
||||
MIN_GLASS_OPACITY,
|
||||
} from "@t3tools/contracts/settings";
|
||||
@@ -40,6 +42,10 @@ import {
|
||||
} from "../../components/desktopUpdate.logic";
|
||||
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
|
||||
import { TraitsPicker } from "../chat/TraitsPicker";
|
||||
import {
|
||||
resolveEnvironmentIdentificationPillLabel,
|
||||
useEnvironmentStageLabel,
|
||||
} from "../SidebarStageBackdrop";
|
||||
import { isElectron } from "../../env";
|
||||
import { buildHostedChannelSelectionUrl, type HostedAppChannel } from "../../hostedPairing";
|
||||
import { useTheme } from "../../hooks/useTheme";
|
||||
@@ -114,6 +120,12 @@ const THEME_OPTIONS = [
|
||||
},
|
||||
] as const;
|
||||
|
||||
const ENVIRONMENT_IDENTIFICATION_LABELS: Record<EnvironmentIdentificationMode, string> = {
|
||||
artwork: "Artwork",
|
||||
pill: "Version pill",
|
||||
none: "None",
|
||||
};
|
||||
|
||||
const TIMESTAMP_FORMAT_LABELS = {
|
||||
locale: "System default",
|
||||
"12-hour": "12-hour",
|
||||
@@ -401,6 +413,10 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
() => [
|
||||
...(theme !== "system" ? ["Theme"] : []),
|
||||
...(settings.glassOpacity !== DEFAULT_UNIFIED_SETTINGS.glassOpacity ? ["Glass opacity"] : []),
|
||||
...(settings.environmentIdentificationMode !==
|
||||
DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode
|
||||
? ["Environment identification"]
|
||||
: []),
|
||||
...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat
|
||||
? ["Time format"]
|
||||
: []),
|
||||
@@ -456,6 +472,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.newWorktreesStartFromOrigin,
|
||||
settings.diffIgnoreWhitespace,
|
||||
settings.environmentIdentificationMode,
|
||||
settings.glassOpacity,
|
||||
settings.automaticGitFetchInterval,
|
||||
settings.enableAssistantStreaming,
|
||||
@@ -483,6 +500,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
|
||||
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
|
||||
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
|
||||
environmentIdentificationMode: DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode,
|
||||
glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity,
|
||||
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
|
||||
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
|
||||
@@ -506,55 +524,23 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
};
|
||||
}
|
||||
|
||||
export function GeneralSettingsPanel() {
|
||||
export function AppearanceSettingsPanel() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const lastEnabledProjectGroupingMode = useRef<SidebarProjectGroupingMode>(
|
||||
readLastEnabledProjectGroupingMode(),
|
||||
);
|
||||
const observability = useAtomValue(primaryServerObservabilityAtom);
|
||||
const serverProviders = useAtomValue(primaryServerProvidersAtom);
|
||||
const environmentStageLabel = useEnvironmentStageLabel();
|
||||
const showEnvironmentIdentification =
|
||||
resolveEnvironmentIdentificationPillLabel(environmentStageLabel) !== null;
|
||||
const glassOpacityRatio =
|
||||
(settings.glassOpacity - MIN_GLASS_OPACITY) / (MAX_GLASS_OPACITY - MIN_GLASS_OPACITY);
|
||||
const glassOpacitySliderStyle = {
|
||||
"--glass-slider-progress": `${glassOpacityRatio * 100}%`,
|
||||
"--glass-slider-fill-offset": `${0.5 - glassOpacityRatio}rem`,
|
||||
} as CSSProperties;
|
||||
const diagnosticsDescription = formatDiagnosticsDescription({
|
||||
localTracingEnabled: observability?.localTracingEnabled ?? false,
|
||||
otlpTracesEnabled: observability?.otlpTracesEnabled ?? false,
|
||||
otlpTracesUrl: observability?.otlpTracesUrl,
|
||||
otlpMetricsEnabled: observability?.otlpMetricsEnabled ?? false,
|
||||
otlpMetricsUrl: observability?.otlpMetricsUrl,
|
||||
});
|
||||
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
const textGenModel = textGenerationModelSelection.model;
|
||||
const textGenModelOptions = textGenerationModelSelection.options;
|
||||
const textGenerationModelInstanceEntries = sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
);
|
||||
const textGenInstanceEntry = textGenerationModelInstanceEntries.find(
|
||||
(entry) => entry.instanceId === textGenInstanceId,
|
||||
);
|
||||
const textGenProvider: ProviderDriverKind =
|
||||
textGenInstanceEntry?.driverKind ?? DEFAULT_DRIVER_KIND;
|
||||
const textGenerationModelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
settings,
|
||||
serverProviders,
|
||||
textGenInstanceId,
|
||||
textGenModel,
|
||||
);
|
||||
const isTextGenerationModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection title="General">
|
||||
<SettingsSection title="Appearance">
|
||||
<SettingsRow
|
||||
title="Theme"
|
||||
description="Choose how T3 Code looks across the app."
|
||||
@@ -634,6 +620,118 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
{showEnvironmentIdentification ? (
|
||||
<SettingsRow
|
||||
title="Environment identification"
|
||||
description="Choose how Dev and Nightly environments are identified."
|
||||
resetAction={
|
||||
settings.environmentIdentificationMode !== DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE ? (
|
||||
<SettingResetButton
|
||||
label="environment identification"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
environmentIdentificationMode: DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={settings.environmentIdentificationMode}
|
||||
onValueChange={(value) => {
|
||||
if (value === "artwork" || value === "pill" || value === "none") {
|
||||
updateSettings({ environmentIdentificationMode: value });
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-40" aria-label="Environment identification">
|
||||
<SelectValue>
|
||||
{ENVIRONMENT_IDENTIFICATION_LABELS[settings.environmentIdentificationMode]}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{Object.entries(ENVIRONMENT_IDENTIFICATION_LABELS).map(([value, label]) => (
|
||||
<SelectItem hideIndicator key={value} value={value}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<SettingsRow
|
||||
title="Word wrap"
|
||||
description="Wrap long lines in code blocks, tables, diffs, and file previews by default."
|
||||
resetAction={
|
||||
settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? (
|
||||
<SettingResetButton
|
||||
label="word wrapping"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.wordWrap}
|
||||
onCheckedChange={(checked) => updateSettings({ wordWrap: Boolean(checked) })}
|
||||
aria-label="Wrap code, tables, diffs, and file previews by default"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
export function GeneralSettingsPanel() {
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const lastEnabledProjectGroupingMode = useRef<SidebarProjectGroupingMode>(
|
||||
readLastEnabledProjectGroupingMode(),
|
||||
);
|
||||
const observability = useAtomValue(primaryServerObservabilityAtom);
|
||||
const serverProviders = useAtomValue(primaryServerProvidersAtom);
|
||||
const diagnosticsDescription = formatDiagnosticsDescription({
|
||||
localTracingEnabled: observability?.localTracingEnabled ?? false,
|
||||
otlpTracesEnabled: observability?.otlpTracesEnabled ?? false,
|
||||
otlpTracesUrl: observability?.otlpTracesUrl,
|
||||
otlpMetricsEnabled: observability?.otlpMetricsEnabled ?? false,
|
||||
otlpMetricsUrl: observability?.otlpMetricsUrl,
|
||||
});
|
||||
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
const textGenModel = textGenerationModelSelection.model;
|
||||
const textGenModelOptions = textGenerationModelSelection.options;
|
||||
const textGenerationModelInstanceEntries = sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
);
|
||||
const textGenInstanceEntry = textGenerationModelInstanceEntries.find(
|
||||
(entry) => entry.instanceId === textGenInstanceId,
|
||||
);
|
||||
const textGenProvider: ProviderDriverKind =
|
||||
textGenInstanceEntry?.driverKind ?? DEFAULT_DRIVER_KIND;
|
||||
const textGenerationModelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
settings,
|
||||
serverProviders,
|
||||
textGenInstanceId,
|
||||
textGenModel,
|
||||
);
|
||||
const isTextGenerationModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection title="General">
|
||||
<SettingsRow
|
||||
title="Project Grouping"
|
||||
description="Combine matching repositories across environments."
|
||||
@@ -712,30 +810,6 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Word wrap"
|
||||
description="Wrap long lines in code blocks, tables, diffs, and file previews by default."
|
||||
resetAction={
|
||||
settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? (
|
||||
<SettingResetButton
|
||||
label="word wrapping"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.wordWrap}
|
||||
onCheckedChange={(checked) => updateSettings({ wordWrap: Boolean(checked) })}
|
||||
aria-label="Wrap code, tables, diffs, and file previews by default"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Hide whitespace changes"
|
||||
description="Set whether the diff panel ignores whitespace-only edits by default."
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
GitBranchIcon,
|
||||
KeyboardIcon,
|
||||
Link2Icon,
|
||||
PaletteIcon,
|
||||
Settings2Icon,
|
||||
} from "lucide-react";
|
||||
import { useCanGoBack, useNavigate } from "@tanstack/react-router";
|
||||
@@ -24,6 +25,7 @@ import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3Conne
|
||||
|
||||
export type SettingsSectionPath =
|
||||
| "/settings/general"
|
||||
| "/settings/appearance"
|
||||
| "/settings/keybindings"
|
||||
| "/settings/providers"
|
||||
| "/settings/source-control"
|
||||
@@ -37,6 +39,7 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
|
||||
icon: ComponentType<{ className?: string }>;
|
||||
}> = [
|
||||
{ label: "General", to: "/settings/general", icon: Settings2Icon },
|
||||
{ label: "Appearance", to: "/settings/appearance", icon: PaletteIcon },
|
||||
{ label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon },
|
||||
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
|
||||
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
|
||||
@@ -72,7 +75,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
|
||||
return (
|
||||
<>
|
||||
<SidebarContent className="overflow-x-hidden">
|
||||
<SidebarGroup className="px-2 py-3">
|
||||
<SidebarGroup className="p-2">
|
||||
<SidebarMenu>
|
||||
{SETTINGS_NAV_ITEMS.map((item) => {
|
||||
const Icon = item.icon;
|
||||
@@ -80,22 +83,10 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
|
||||
return (
|
||||
<SidebarMenuItem key={item.to}>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
isActive={isActive}
|
||||
className={
|
||||
isActive
|
||||
? "h-8 items-center gap-2 rounded-md bg-sidebar-row-active px-2 py-1.5 text-left text-sm font-medium text-sidebar-foreground"
|
||||
: "h-8 items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm font-medium text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
}
|
||||
onClick={() => handleSectionClick(item.to)}
|
||||
>
|
||||
<Icon
|
||||
className={
|
||||
isActive
|
||||
? "size-4 shrink-0 text-sidebar-foreground"
|
||||
: "size-4 shrink-0 text-sidebar-muted-foreground/60"
|
||||
}
|
||||
/>
|
||||
<Icon />
|
||||
<span className="truncate">{item.label}</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
@@ -106,15 +97,11 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
|
||||
</SidebarContent>
|
||||
<SidebarFooter className="p-2">
|
||||
<T3ConnectSidebarSignIn />
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
|
||||
<SidebarMenu className="min-w-0">
|
||||
<div className="flex items-center gap-1">
|
||||
<SidebarMenu className="min-w-0 flex-1">
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="h-8 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
onClick={handleBackClick}
|
||||
>
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
<SidebarMenuButton onClick={handleBackClick}>
|
||||
<ArrowLeftIcon />
|
||||
<span>Back</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { SettingsIcon } from "lucide-react";
|
||||
import { memo, useCallback } from "react";
|
||||
import { Link, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { APP_STAGE_LABEL } from "../../branding";
|
||||
import { useEnvironmentIdentificationMode } from "../../hooks/useSettings";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { primaryServerConfigAtom } from "../../state/server";
|
||||
import { resolveSidebarStageBadgeLabel } from "../Sidebar.logic";
|
||||
import { SidebarStageBackdrop, resolveSidebarStageBackdropVariant } from "../SidebarStageBackdrop";
|
||||
import {
|
||||
resolveEnvironmentIdentificationPillLabel,
|
||||
resolveSidebarStageBackdropVariant,
|
||||
SidebarStageBackdrop,
|
||||
useEnvironmentStageLabel,
|
||||
} from "../SidebarStageBackdrop";
|
||||
import { Badge } from "../ui/badge";
|
||||
import {
|
||||
SidebarFooter,
|
||||
SidebarHeader,
|
||||
@@ -25,8 +28,16 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
}: {
|
||||
isElectron: boolean;
|
||||
}) {
|
||||
const stageLabel = useSidebarStageLabel();
|
||||
const backdropVariant = resolveSidebarStageBackdropVariant(stageLabel);
|
||||
const stageLabel = useEnvironmentStageLabel();
|
||||
const environmentIdentificationMode = useEnvironmentIdentificationMode();
|
||||
const backdropVariant = resolveSidebarStageBackdropVariant(
|
||||
stageLabel,
|
||||
environmentIdentificationMode === "artwork",
|
||||
);
|
||||
const pillLabel =
|
||||
environmentIdentificationMode === "pill"
|
||||
? resolveEnvironmentIdentificationPillLabel(stageLabel)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<SidebarHeader
|
||||
@@ -44,6 +55,16 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
)}
|
||||
/>
|
||||
<SidebarBrand onBackdrop={backdropVariant !== null} />
|
||||
{pillLabel ? (
|
||||
<Badge
|
||||
className="relative z-10 ml-1 rounded-full px-1.5 text-muted-foreground"
|
||||
data-environment-identification="pill"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
>
|
||||
{pillLabel}
|
||||
</Badge>
|
||||
) : null}
|
||||
</SidebarHeader>
|
||||
);
|
||||
});
|
||||
@@ -71,16 +92,6 @@ function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
function useSidebarStageLabel() {
|
||||
const primaryServerVersion =
|
||||
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
|
||||
|
||||
return resolveSidebarStageBadgeLabel({
|
||||
primaryServerVersion,
|
||||
fallbackStageLabel: APP_STAGE_LABEL,
|
||||
});
|
||||
}
|
||||
|
||||
function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
@@ -113,12 +124,8 @@ export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
|
||||
<SidebarUpdatePill />
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="h-8 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
onClick={handleSettingsClick}
|
||||
>
|
||||
<SettingsIcon className="size-4.5 shrink-0" />
|
||||
<SidebarMenuButton onClick={handleSettingsClick}>
|
||||
<SettingsIcon />
|
||||
<span>Settings</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
|
||||
@@ -65,7 +65,7 @@ function CommandDialogPopup({
|
||||
<CommandDialogPrimitive.Popup
|
||||
className={cn(
|
||||
DIALOG_POPUP_CLASS,
|
||||
"pointer-events-auto max-h-105 max-w-xl text-foreground **:data-[slot=scroll-area-viewport]:data-has-overflow-y:pe-1",
|
||||
"pointer-events-auto max-h-105 max-w-xl text-foreground",
|
||||
className,
|
||||
)}
|
||||
data-slot="command-dialog-popup"
|
||||
@@ -103,16 +103,16 @@ function CommandInput({
|
||||
wrapperClassName?: string | undefined;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn("px-2.5 py-1.5", wrapperClassName)}>
|
||||
<div className={cn("px-1.25 py-1.5", wrapperClassName)}>
|
||||
<AutocompleteInput
|
||||
autoFocus
|
||||
className={cn(
|
||||
"border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0 placeholder:text-muted-foreground/80",
|
||||
"border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0 placeholder:text-muted-foreground/80 *:data-[slot=autocomplete-input]:ps-9! sm:*:data-[slot=autocomplete-input]:ps-8.5!",
|
||||
className,
|
||||
)}
|
||||
placeholder={placeholder}
|
||||
size="lg"
|
||||
startAddon={<SearchIcon />}
|
||||
startAddon={<SearchIcon className="translate-x-0.5 text-muted-foreground" />}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
@@ -198,7 +198,7 @@ function CommandShortcut({ className, ...props }: React.ComponentProps<"kbd">) {
|
||||
return (
|
||||
<kbd
|
||||
className={cn(
|
||||
"ms-auto font-medium font-sans text-muted-foreground text-xs tracking-widest",
|
||||
"ms-auto font-medium font-sans text-muted-foreground/70 text-xs tracking-widest",
|
||||
className,
|
||||
)}
|
||||
data-slot="command-shortcut"
|
||||
@@ -211,7 +211,7 @@ function CommandFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"relative flex items-center justify-between gap-2 rounded-b-[calc(var(--radius-2xl)-1px)] bg-foreground/[0.025] px-5 py-3 font-medium text-sm text-muted-foreground [&_[data-slot=kbd-group]]:font-sans [&_[data-slot=kbd]]:bg-foreground/[0.08] [&_[data-slot=kbd]]:text-foreground [&_[data-slot=kbd]]:ring-0",
|
||||
"relative flex items-center justify-between gap-2 rounded-b-[calc(var(--radius-2xl)-1px)] bg-foreground/[0.025] px-4 py-2.5 font-medium text-sm text-muted-foreground [&_[data-slot=kbd-group]]:font-sans [&_[data-slot=kbd]]:bg-foreground/[0.08] [&_[data-slot=kbd]]:text-foreground [&_[data-slot=kbd]]:ring-0",
|
||||
className,
|
||||
)}
|
||||
data-slot="command-footer"
|
||||
|
||||
@@ -56,7 +56,7 @@ function ScrollBar({
|
||||
return (
|
||||
<ScrollAreaPrimitive.Scrollbar
|
||||
className={cn(
|
||||
"m-1 flex opacity-0 transition-opacity delay-300 data-[orientation=horizontal]:h-1.5 data-[orientation=vertical]:w-1.5 data-[orientation=horizontal]:flex-col data-hovering:opacity-100 data-scrolling:opacity-100 data-hovering:delay-0 data-scrolling:delay-0 data-hovering:duration-100 data-scrolling:duration-100",
|
||||
"flex opacity-0 transition-opacity delay-300 data-[orientation=horizontal]:mx-1 data-[orientation=horizontal]:mb-px data-[orientation=horizontal]:h-1.5 data-[orientation=vertical]:my-1 data-[orientation=vertical]:mr-px data-[orientation=vertical]:w-1.5 data-[orientation=horizontal]:flex-col data-hovering:opacity-100 data-scrolling:opacity-100 data-hovering:delay-0 data-scrolling:delay-0 data-hovering:duration-100 data-scrolling:duration-100",
|
||||
className,
|
||||
)}
|
||||
data-slot="scroll-area-scrollbar"
|
||||
@@ -64,7 +64,7 @@ function ScrollBar({
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Thumb
|
||||
className="relative flex-1 rounded-full bg-foreground/20"
|
||||
className="relative flex-1 rounded-full bg-[var(--app-scrollbar-thumb)] transition-colors hover:bg-[var(--app-scrollbar-thumb-hover)]"
|
||||
data-slot="scroll-area-thumb"
|
||||
/>
|
||||
</ScrollAreaPrimitive.Scrollbar>
|
||||
|
||||
@@ -77,8 +77,10 @@ function SelectTrigger({
|
||||
size = "default",
|
||||
variant = "default",
|
||||
children,
|
||||
icon,
|
||||
...props
|
||||
}: SelectPrimitive.Trigger.Props & VariantProps<typeof selectTriggerVariants>) {
|
||||
}: SelectPrimitive.Trigger.Props &
|
||||
VariantProps<typeof selectTriggerVariants> & { icon?: React.ReactNode }) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
className={cn(selectTriggerVariants({ size, variant }), className)}
|
||||
@@ -87,7 +89,7 @@ function SelectTrigger({
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon data-slot="select-icon">
|
||||
<ChevronDownIcon className="-me-1 size-3 opacity-50" />
|
||||
{icon ?? <ChevronDownIcon className="-me-1 size-3 opacity-50" />}
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
|
||||
@@ -50,13 +50,35 @@ describe("sidebar interactive cursors", () => {
|
||||
expect(html).toContain("size-[var(--workspace-titlebar-control-size)]!");
|
||||
});
|
||||
|
||||
it("uses a pointer cursor for menu buttons by default", () => {
|
||||
it("uses shared geometry and icon constraints for menu buttons by default", () => {
|
||||
const html = renderSidebarButton();
|
||||
|
||||
expect(html).toContain('data-slot="sidebar-menu-button"');
|
||||
expect(html).toContain("h-8");
|
||||
expect(html).toContain("rounded-md");
|
||||
expect(html).toContain("px-2");
|
||||
expect(html).toContain("py-1.5");
|
||||
expect(html).toContain("]:size-4");
|
||||
expect(html).toContain("]:shrink-0");
|
||||
expect(html).toContain("cursor-pointer");
|
||||
});
|
||||
|
||||
it("applies the shared default treatment to icon-only menu buttons", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SidebarProvider>
|
||||
<SidebarMenuButton size="icon">
|
||||
<span>+</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarProvider>,
|
||||
);
|
||||
|
||||
expect(html).toContain("size-8");
|
||||
expect(html).toContain("justify-center");
|
||||
expect(html).toContain("p-0");
|
||||
expect(html).toContain("font-medium");
|
||||
expect(html).toContain("text-sidebar-muted-foreground/80");
|
||||
});
|
||||
|
||||
it("lets project drag handles override the default pointer cursor", () => {
|
||||
const html = renderSidebarButton("cursor-grab");
|
||||
|
||||
|
||||
@@ -684,19 +684,28 @@ function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof S
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
function SidebarContent({
|
||||
className,
|
||||
fixedHeader,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
fixedHeader?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<ScrollArea hideScrollbars scrollFade className="h-auto min-h-0 flex-1">
|
||||
<div
|
||||
className={cn(
|
||||
"flex w-full min-w-0 flex-col gap-2 group-data-[collapsible=icon]:overflow-hidden",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="content"
|
||||
data-slot="sidebar-content"
|
||||
{...props}
|
||||
/>
|
||||
</ScrollArea>
|
||||
<>
|
||||
{fixedHeader ? <div className="w-full shrink-0">{fixedHeader}</div> : null}
|
||||
<ScrollArea hideScrollbars scrollFade className="h-auto min-h-0 flex-1">
|
||||
<div
|
||||
className={cn(
|
||||
"flex w-full min-w-0 flex-col gap-2 group-data-[collapsible=icon]:overflow-hidden",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="content"
|
||||
data-slot="sidebar-content"
|
||||
{...props}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -783,7 +792,7 @@ function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full cursor-pointer items-center gap-2 overflow-hidden rounded-lg p-2 text-left text-sm outline-hidden ring-ring transition-[width,height,padding] hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 active:bg-sidebar-row-active active:text-sidebar-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-row-selected data-[active=true]:font-medium data-[active=true]:text-sidebar-foreground data-[state=open]:hover:bg-sidebar-row-hover data-[state=open]:hover:text-sidebar-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
"peer/menu-button flex w-full cursor-pointer items-center gap-2 overflow-hidden text-left outline-hidden ring-ring transition-[width,height,padding] hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 active:bg-sidebar-row-active active:text-sidebar-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-row-selected data-[active=true]:font-medium data-[active=true]:text-sidebar-foreground data-[state=open]:hover:bg-sidebar-row-hover data-[state=open]:hover:text-sidebar-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-muted-foreground [&>svg]:opacity-60 hover:[&>svg]:text-sidebar-foreground hover:[&>svg]:opacity-100 active:[&>svg]:text-sidebar-foreground active:[&>svg]:opacity-100 data-[active=true]:[&>svg]:text-sidebar-foreground data-[active=true]:[&>svg]:opacity-100",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
@@ -791,14 +800,14 @@ const sidebarMenuButtonVariants = cva(
|
||||
},
|
||||
variants: {
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
sm: "h-7 text-xs",
|
||||
default: "h-8 rounded-md px-2.5 py-1.5 text-sm",
|
||||
icon: "size-8 justify-center rounded-md p-0",
|
||||
lg: "h-12 rounded-lg p-2 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
sm: "h-7 rounded-lg p-2 text-xs",
|
||||
},
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
|
||||
outline:
|
||||
"bg-sidebar-control-surface ring-1 ring-sidebar-border hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
|
||||
default: "font-medium text-sidebar-muted-foreground/80",
|
||||
outline: "bg-sidebar-control-surface ring-1 ring-sidebar-border",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -105,6 +105,8 @@ function persistenceError(
|
||||
| "save-server-config"
|
||||
| "load-vcs-refs"
|
||||
| "save-vcs-refs"
|
||||
| "remove-vcs-refs"
|
||||
| "clear-vcs-refs"
|
||||
| "clear-environment",
|
||||
cause: unknown,
|
||||
) {
|
||||
@@ -619,6 +621,18 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
: persistenceError("save-vcs-refs", cause),
|
||||
),
|
||||
),
|
||||
removeVcsRefs: (environmentId, cwd) =>
|
||||
removeDatabaseValue(
|
||||
database,
|
||||
VCS_REFS_STORE_NAME,
|
||||
vcsRefsCacheKey(environmentId, cwd),
|
||||
).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause))),
|
||||
clearVcsRefs: (environmentId) =>
|
||||
removeDatabaseValuesInRange(
|
||||
database,
|
||||
VCS_REFS_STORE_NAME,
|
||||
IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
|
||||
).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause))),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
removeDatabaseValue(
|
||||
database,
|
||||
|
||||
@@ -166,9 +166,9 @@ export function showContextMenuFallback<T extends string>(
|
||||
|
||||
const menu = document.createElement("div");
|
||||
menu.className =
|
||||
"fixed z-[10000] min-w-32 max-w-sm overflow-hidden rounded-lg border border-border bg-popover bg-clip-padding text-popover-foreground shadow-lg/5 outline-none";
|
||||
"dropdown-glass fixed z-[10000] min-w-32 max-w-sm overflow-hidden rounded-lg bg-clip-padding text-popover-foreground outline-none";
|
||||
menu.style.cssText =
|
||||
"position:fixed;z-index:10000;min-width:8rem;max-width:24rem;overflow:hidden;border-radius:var(--radius-lg);border:1px solid var(--border);background:var(--popover);background-clip:padding-box;color:var(--popover-foreground);box-shadow:0 10px 15px -3px rgb(0 0 0 / 0.05),0 4px 6px -4px rgb(0 0 0 / 0.05);outline:none;pointer-events:auto;";
|
||||
"position:fixed;z-index:10000;min-width:8rem;max-width:24rem;overflow:hidden;border-radius:var(--radius-lg);background-clip:padding-box;color:var(--popover-foreground);outline:none;pointer-events:auto;";
|
||||
menu.style.left = `${preferredLeft}px`;
|
||||
menu.style.top = `${preferredTop}px`;
|
||||
menu.dataset.level = String(level);
|
||||
|
||||
@@ -6,7 +6,18 @@ import {
|
||||
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { mergeEnvironmentSettings } from "./useSettings";
|
||||
import { mergeEnvironmentSettings, resolveEnvironmentIdentificationMode } from "./useSettings";
|
||||
|
||||
describe("resolveEnvironmentIdentificationMode", () => {
|
||||
it("keeps identification hidden until client settings hydrate", () => {
|
||||
expect(resolveEnvironmentIdentificationMode({ mode: "artwork", settingsHydrated: false })).toBe(
|
||||
"none",
|
||||
);
|
||||
expect(resolveEnvironmentIdentificationMode({ mode: "pill", settingsHydrated: true })).toBe(
|
||||
"pill",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeEnvironmentSettings", () => {
|
||||
it("combines the selected environment's server settings with client preferences", () => {
|
||||
|
||||
@@ -21,9 +21,12 @@ import {
|
||||
type ClientSettingsPatch,
|
||||
type ClientSettings,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
type EnvironmentIdentificationMode,
|
||||
type UnifiedSettings,
|
||||
} from "@t3tools/contracts/settings";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import { APP_STAGE_LABEL } from "~/branding";
|
||||
import { resolveSidebarV2Enabled } from "~/branding.logic";
|
||||
import { ensureLocalApi } from "~/localApi";
|
||||
import * as Struct from "effect/Struct";
|
||||
import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
|
||||
@@ -220,6 +223,46 @@ export function useClientSettings<T = ClientSettings>(
|
||||
return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
|
||||
}
|
||||
|
||||
export function resolveEnvironmentIdentificationMode(input: {
|
||||
mode: EnvironmentIdentificationMode;
|
||||
settingsHydrated: boolean;
|
||||
}): EnvironmentIdentificationMode {
|
||||
// Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
|
||||
return input.settingsHydrated ? input.mode : "none";
|
||||
}
|
||||
|
||||
export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
|
||||
const settingsHydrated = useClientSettingsHydrated();
|
||||
const mode = useClientSettingsValue().environmentIdentificationMode;
|
||||
return resolveEnvironmentIdentificationMode({ mode, settingsHydrated });
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolved sidebar v2 state: an explicit choice in Settings → Beta if the user
|
||||
* has made one, otherwise the default for this build stage (on for nightly and
|
||||
* dev, off for production). Every consumer must read through this rather than
|
||||
* `settings.sidebarV2Enabled`, which is only meaningful alongside
|
||||
* `sidebarV2ConfiguredByUser`.
|
||||
*
|
||||
* Held at v1 until client settings hydrate. The pre-hydration snapshot is just
|
||||
* the schema defaults, so resolving against it would mount one sidebar and then
|
||||
* swap it out once persisted settings land — remounting the whole tree.
|
||||
*/
|
||||
export function useSidebarV2Enabled(): boolean {
|
||||
const settingsHydrated = useClientSettingsHydrated();
|
||||
const settings = useClientSettingsValue();
|
||||
return useMemo(
|
||||
() =>
|
||||
resolveSidebarV2Enabled({
|
||||
enabled: settings.sidebarV2Enabled,
|
||||
configuredByUser: settings.sidebarV2ConfiguredByUser,
|
||||
settingsHydrated,
|
||||
stageLabel: APP_STAGE_LABEL,
|
||||
}),
|
||||
[settings.sidebarV2Enabled, settings.sidebarV2ConfiguredByUser, settingsHydrated],
|
||||
);
|
||||
}
|
||||
|
||||
/** Read current settings for one environment, merged with client-local preferences. */
|
||||
export function useEnvironmentSettings<T = UnifiedSettings>(
|
||||
environmentId: EnvironmentId,
|
||||
|
||||
+52
-34
@@ -77,6 +77,8 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
|
||||
:root {
|
||||
--app-scrollbar-width: 6px;
|
||||
--app-scrollbar-thumb: rgb(217 217 217);
|
||||
--app-scrollbar-thumb-hover: rgb(191 191 191);
|
||||
--glass-blur: 12px;
|
||||
--glass-opacity: 80%;
|
||||
--glass-saturation: 1.14;
|
||||
@@ -91,6 +93,8 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
|
||||
.dark {
|
||||
--app-scrollbar-thumb: rgb(255 255 255 / 8%);
|
||||
--app-scrollbar-thumb-hover: rgb(255 255 255 / 12%);
|
||||
--glass-blur: 16px;
|
||||
--glass-saturation: 1.08;
|
||||
}
|
||||
@@ -327,12 +331,13 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
rgb(0 0 0 / 96%) 82%,
|
||||
black 100%
|
||||
),
|
||||
linear-gradient(black, black);
|
||||
-webkit-mask-position: top, bottom;
|
||||
linear-gradient(black, black), linear-gradient(black, black);
|
||||
-webkit-mask-position: top, bottom, right;
|
||||
-webkit-mask-repeat: no-repeat;
|
||||
-webkit-mask-size:
|
||||
100% var(--topbar-scroll-fade-height),
|
||||
100% calc(100% - var(--topbar-scroll-fade-height));
|
||||
100% calc(100% - var(--topbar-scroll-fade-height)),
|
||||
var(--app-scrollbar-width) 100%;
|
||||
mask-image:
|
||||
linear-gradient(
|
||||
to bottom,
|
||||
@@ -344,12 +349,13 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
rgb(0 0 0 / 96%) 82%,
|
||||
black 100%
|
||||
),
|
||||
linear-gradient(black, black);
|
||||
mask-position: top, bottom;
|
||||
linear-gradient(black, black), linear-gradient(black, black);
|
||||
mask-position: top, bottom, right;
|
||||
mask-repeat: no-repeat;
|
||||
mask-size:
|
||||
100% var(--topbar-scroll-fade-height),
|
||||
100% calc(100% - var(--topbar-scroll-fade-height));
|
||||
100% calc(100% - var(--topbar-scroll-fade-height)),
|
||||
var(--app-scrollbar-width) 100%;
|
||||
}
|
||||
|
||||
.workspace-titlebar-controls {
|
||||
@@ -1035,20 +1041,54 @@ code {
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 0, 0, 0.15);
|
||||
background: var(--app-scrollbar-thumb);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(0, 0, 0, 0.25);
|
||||
background: var(--app-scrollbar-thumb-hover);
|
||||
}
|
||||
|
||||
.dark ::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
.model-picker-list::-webkit-scrollbar-track {
|
||||
margin-block: 0.5rem;
|
||||
}
|
||||
|
||||
.dark ::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
.model-picker-list-scroll-fade-top,
|
||||
.model-picker-list-scroll-fade-bottom {
|
||||
-webkit-mask-image: var(--model-picker-list-scroll-mask), linear-gradient(black, black);
|
||||
-webkit-mask-position: left, right;
|
||||
-webkit-mask-repeat: no-repeat;
|
||||
-webkit-mask-size:
|
||||
calc(100% - var(--app-scrollbar-width)) 100%,
|
||||
var(--app-scrollbar-width) 100%;
|
||||
mask-image: var(--model-picker-list-scroll-mask), linear-gradient(black, black);
|
||||
mask-position: left, right;
|
||||
mask-repeat: no-repeat;
|
||||
mask-size:
|
||||
calc(100% - var(--app-scrollbar-width)) 100%,
|
||||
var(--app-scrollbar-width) 100%;
|
||||
}
|
||||
|
||||
.model-picker-list-scroll-fade-top {
|
||||
--model-picker-list-scroll-mask: linear-gradient(to bottom, transparent, black var(--fade-size));
|
||||
}
|
||||
|
||||
.model-picker-list-scroll-fade-bottom {
|
||||
--model-picker-list-scroll-mask: linear-gradient(
|
||||
to bottom,
|
||||
black calc(100% - var(--fade-size)),
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
.model-picker-list-scroll-fade-top.model-picker-list-scroll-fade-bottom {
|
||||
--model-picker-list-scroll-mask: linear-gradient(
|
||||
to bottom,
|
||||
transparent,
|
||||
black var(--fade-size),
|
||||
black calc(100% - var(--fade-size)),
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
.turn-chip-strip {
|
||||
@@ -1569,28 +1609,6 @@ label:has(> select#reasoning-effort) select {
|
||||
animation: ultrathink-rainbow 10s linear infinite;
|
||||
}
|
||||
|
||||
/* Thin scrollbar for model picker */
|
||||
.model-picker-list::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
.model-picker-list::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.model-picker-list::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.dark .model-picker-list::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.dark .model-picker-list::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
}
|
||||
|
||||
/* Composer chips are non-editable decorators, so the browser skips them when
|
||||
painting text selection; this overlay stands in for the native highlight. */
|
||||
.composer-inline-chip[data-composer-chip-selected]::after {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
resolveInlineCodeFileLinkMeta,
|
||||
resolveMarkdownFileLinkMeta,
|
||||
resolveMarkdownFileLinkTarget,
|
||||
rewriteMarkdownFileUriHref,
|
||||
@@ -127,3 +128,148 @@ describe("resolveMarkdownFileLinkTarget", () => {
|
||||
expect(resolveMarkdownFileLinkTarget("/chat/settings")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveInlineCodeFileLinkMeta", () => {
|
||||
it("links relative paths with file extensions", () => {
|
||||
expect(
|
||||
resolveInlineCodeFileLinkMeta(".plans/worktree-management-v1.md", "/Users/julius/project"),
|
||||
).toMatchObject({
|
||||
targetPath: "/Users/julius/project/.plans/worktree-management-v1.md",
|
||||
basename: "worktree-management-v1.md",
|
||||
});
|
||||
});
|
||||
|
||||
it("links absolute posix paths", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("/Users/julius/project/AGENTS.md")).toMatchObject({
|
||||
targetPath: "/Users/julius/project/AGENTS.md",
|
||||
});
|
||||
expect(resolveInlineCodeFileLinkMeta("/usr/local/bin/tool")).toMatchObject({
|
||||
targetPath: "/usr/local/bin/tool",
|
||||
});
|
||||
expect(resolveInlineCodeFileLinkMeta("/workspace/Makefile")).toMatchObject({
|
||||
basename: "Makefile",
|
||||
});
|
||||
expect(resolveInlineCodeFileLinkMeta("/chat/settings")).toBeNull();
|
||||
});
|
||||
|
||||
it("links windows drive paths", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("C:\\Users\\mike\\project\\src\\main.ts")).toMatchObject({
|
||||
basename: "main.ts",
|
||||
});
|
||||
});
|
||||
|
||||
it("links relative paths with line positions", () => {
|
||||
expect(
|
||||
resolveInlineCodeFileLinkMeta("src/processRunner.ts:71", "/Users/julius/project"),
|
||||
).toMatchObject({
|
||||
targetPath: "/Users/julius/project/src/processRunner.ts:71",
|
||||
line: 71,
|
||||
});
|
||||
});
|
||||
|
||||
it("links bare filenames only when a line suffix marks them as file references", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("script.ts:10", "/Users/julius/project")).toMatchObject({
|
||||
targetPath: "/Users/julius/project/script.ts:10",
|
||||
line: 10,
|
||||
});
|
||||
expect(resolveInlineCodeFileLinkMeta("AGENTS.md", "/Users/julius/project")).toBeNull();
|
||||
});
|
||||
|
||||
it("links extensionless bare filenames with a line suffix", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("Makefile:12", "/Users/julius/project")).toMatchObject({
|
||||
targetPath: "/Users/julius/project/Makefile:12",
|
||||
basename: "Makefile",
|
||||
line: 12,
|
||||
});
|
||||
expect(resolveInlineCodeFileLinkMeta("Dockerfile:8:2", "/Users/julius/project")).toMatchObject({
|
||||
line: 8,
|
||||
column: 2,
|
||||
});
|
||||
expect(resolveInlineCodeFileLinkMeta("Makefile:12")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not treat arbitrary name:digits shapes as files", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("error:1", "/Users/julius/project")).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("TODO:12", "/Users/julius/project")).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("exit:0", "/Users/julius/project")).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("port:3000", "/Users/julius/project")).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("http:80", "/Users/julius/project")).toBeNull();
|
||||
});
|
||||
|
||||
it("links dot-prefixed relative paths without extensions", () => {
|
||||
expect(
|
||||
resolveInlineCodeFileLinkMeta("./scripts/deploy", "/Users/julius/project"),
|
||||
).toMatchObject({
|
||||
basename: "deploy",
|
||||
});
|
||||
});
|
||||
|
||||
it("links relative windows-style paths by normalizing backslashes", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("src\\main.ts", "/Users/julius/project")).toMatchObject({
|
||||
targetPath: "/Users/julius/project/src/main.ts",
|
||||
basename: "main.ts",
|
||||
});
|
||||
expect(
|
||||
resolveInlineCodeFileLinkMeta(".\\scripts\\deploy", "/Users/julius/project"),
|
||||
).toMatchObject({
|
||||
basename: "deploy",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores hosts, ports, and versions", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("127.0.0.1:3000", "/Users/julius/project")).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("localhost:3000", "/Users/julius/project")).toBeNull();
|
||||
expect(
|
||||
resolveInlineCodeFileLinkMeta("example.com/index.html", "/Users/julius/project"),
|
||||
).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("example.com:8080", "/Users/julius/project")).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("10.0.0.1:80:1", "/Users/julius/project")).toBeNull();
|
||||
expect(
|
||||
resolveInlineCodeFileLinkMeta("localhost/index.html", "/Users/julius/project"),
|
||||
).toBeNull();
|
||||
expect(
|
||||
resolveInlineCodeFileLinkMeta("example.uk/index.html", "/Users/julius/project"),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("still links files whose extension merely resembles a tld", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("script.ts:10", "/Users/julius/project")).not.toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("src/setup.sh:3", "/Users/julius/project")).not.toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("Makefile.in:12", "/Users/julius/project")).not.toBeNull();
|
||||
expect(
|
||||
resolveInlineCodeFileLinkMeta("conf.d/nginx.conf", "/Users/julius/project"),
|
||||
).not.toBeNull();
|
||||
});
|
||||
|
||||
it("prefers file over country-code host when a line suffix is present", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("script.pl:10", "/Users/julius/project")).toMatchObject({
|
||||
targetPath: "/Users/julius/project/script.pl:10",
|
||||
line: 10,
|
||||
});
|
||||
expect(resolveInlineCodeFileLinkMeta("model.pt:3", "/Users/julius/project")).not.toBeNull();
|
||||
expect(
|
||||
resolveInlineCodeFileLinkMeta("example.pl/index.html", "/Users/julius/project"),
|
||||
).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("example.com:8080", "/Users/julius/project")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores commands, flags, and expressions", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("git worktree list --porcelain")).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("node.meta", "/Users/julius/project")).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("pnpm install", "/Users/julius/project")).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("src/**/*.ts", "/Users/julius/project")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores extension-less relative segments like git refs and directories", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("origin/main", "/Users/julius/project")).toBeNull();
|
||||
expect(resolveInlineCodeFileLinkMeta("apps/web", "/Users/julius/project")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores external urls", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta("https://example.com/docs.html")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores relative paths without a cwd to resolve against", () => {
|
||||
expect(resolveInlineCodeFileLinkMeta(".plans/worktree-management-v1.md")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,8 @@ const RELATIVE_FILE_PATH_PATTERN = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d
|
||||
const RELATIVE_FILE_NAME_PATTERN = /^[A-Za-z0-9._-]+\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
|
||||
const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
|
||||
// Standard OS and dev-container roots; deliberately excludes app-route-ish
|
||||
// prefixes like /app/ or /chat/ so SPA routes never read as files.
|
||||
const POSIX_FILE_ROOT_PREFIXES = [
|
||||
"/Users/",
|
||||
"/home/",
|
||||
@@ -20,6 +22,20 @@ const POSIX_FILE_ROOT_PREFIXES = [
|
||||
"/Volumes/",
|
||||
"/private/",
|
||||
"/root/",
|
||||
"/usr/",
|
||||
"/bin/",
|
||||
"/sbin/",
|
||||
"/lib/",
|
||||
"/lib64/",
|
||||
"/srv/",
|
||||
"/dev/",
|
||||
"/proc/",
|
||||
"/sys/",
|
||||
"/run/",
|
||||
"/boot/",
|
||||
"/media/",
|
||||
"/workspace/",
|
||||
"/workspaces/",
|
||||
] as const;
|
||||
|
||||
export interface MarkdownFileLinkMeta {
|
||||
@@ -170,6 +186,178 @@ export function resolveMarkdownFileLinkTarget(
|
||||
return resolvePathLinkTarget(pathWithPosition, cwd);
|
||||
}
|
||||
|
||||
const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;
|
||||
const PATH_SEPARATOR_PATTERN = /[\\/]/;
|
||||
const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
|
||||
const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
|
||||
const BARE_EXTENSIONLESS_POSITION_PATTERN = /^[A-Za-z0-9_-]+(?::\d+){1,2}$/;
|
||||
// Any `Name:digits` shape also matches `error:1`, `port:3000`, `TODO:12`, so
|
||||
// extensionless linking is limited to conventional filenames.
|
||||
const EXTENSIONLESS_FILE_NAMES = new Set([
|
||||
"Makefile",
|
||||
"makefile",
|
||||
"GNUmakefile",
|
||||
"Dockerfile",
|
||||
"Containerfile",
|
||||
"Justfile",
|
||||
"justfile",
|
||||
"Rakefile",
|
||||
"Gemfile",
|
||||
"Procfile",
|
||||
"Brewfile",
|
||||
"Caddyfile",
|
||||
"Vagrantfile",
|
||||
"Jenkinsfile",
|
||||
"Podfile",
|
||||
"Fastfile",
|
||||
"BUILD",
|
||||
"WORKSPACE",
|
||||
"LICENSE",
|
||||
"LICENCE",
|
||||
"COPYING",
|
||||
"NOTICE",
|
||||
"AUTHORS",
|
||||
"CONTRIBUTORS",
|
||||
"CHANGELOG",
|
||||
"README",
|
||||
"CODEOWNERS",
|
||||
]);
|
||||
const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
|
||||
// Allowlists, not full public-suffix detection: treating every dotted first
|
||||
// segment as a host would swallow real paths like `conf.d/x.conf` or
|
||||
// `Makefile.in:12`. Extensions that double as filename suffixes (`sh`, `md`,
|
||||
// `ts`, `rs`, `in`, ...) are deliberately absent from both sets.
|
||||
const GENERIC_HOSTNAME_TLDS = new Set([
|
||||
"com",
|
||||
"net",
|
||||
"org",
|
||||
"io",
|
||||
"dev",
|
||||
"app",
|
||||
"ai",
|
||||
"co",
|
||||
"edu",
|
||||
"gov",
|
||||
"mil",
|
||||
"info",
|
||||
"biz",
|
||||
"xyz",
|
||||
"me",
|
||||
"tv",
|
||||
"cc",
|
||||
"gg",
|
||||
"chat",
|
||||
"cloud",
|
||||
"site",
|
||||
"online",
|
||||
"tech",
|
||||
"store",
|
||||
"link",
|
||||
]);
|
||||
// Country codes collide with file extensions (`.pl` Perl, `.pt` PyTorch,
|
||||
// `.es` ES modules), so they only count as host evidence when the candidate
|
||||
// lacks a :line suffix — an explicit line reference marks a file and wins.
|
||||
const COUNTRY_HOSTNAME_TLDS = new Set([
|
||||
"uk",
|
||||
"de",
|
||||
"fr",
|
||||
"nl",
|
||||
"se",
|
||||
"no",
|
||||
"fi",
|
||||
"dk",
|
||||
"pl",
|
||||
"ch",
|
||||
"at",
|
||||
"be",
|
||||
"es",
|
||||
"it",
|
||||
"pt",
|
||||
"eu",
|
||||
"us",
|
||||
"ca",
|
||||
"au",
|
||||
"nz",
|
||||
"jp",
|
||||
"kr",
|
||||
"cn",
|
||||
"br",
|
||||
"ru",
|
||||
"mx",
|
||||
"ie",
|
||||
"cz",
|
||||
"tr",
|
||||
"sg",
|
||||
"hk",
|
||||
]);
|
||||
|
||||
/** `127.0.0.1`, `localhost`, `example.com`, `1.2.3` — hosts and versions, not files. */
|
||||
function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
|
||||
if (segment.startsWith(".")) return false;
|
||||
const lowered = segment.toLowerCase();
|
||||
if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
|
||||
if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
|
||||
const labels = lowered.split(".");
|
||||
const lastLabel = labels[labels.length - 1];
|
||||
if (labels.length < 2 || lastLabel === undefined) return false;
|
||||
if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
|
||||
return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline code spans mostly hold identifiers, commands, and refs (`node.meta`,
|
||||
* `origin/main`) rather than deliberate link destinations, so auto-linking
|
||||
* them demands stronger path evidence than an explicit markdown link does:
|
||||
* an unambiguous path prefix, a file extension, or a :line suffix.
|
||||
*/
|
||||
export function resolveInlineCodeFileLinkMeta(
|
||||
codeText: string,
|
||||
cwd?: string,
|
||||
): MarkdownFileLinkMeta | null {
|
||||
const trimmed = codeText.trim();
|
||||
if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
|
||||
|
||||
// Windows drive/UNC paths keep their backslashes; any other backslashes are
|
||||
// relative Windows-style paths, which neither the shape checks nor the
|
||||
// downstream resolver understand — normalize them to forward slashes.
|
||||
const candidate =
|
||||
WINDOWS_DRIVE_PATH_PATTERN.test(trimmed) || WINDOWS_UNC_PATH_PATTERN.test(trimmed)
|
||||
? trimmed
|
||||
: trimmed.replaceAll("\\", "/");
|
||||
|
||||
const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
|
||||
if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
|
||||
|
||||
const hasExplicitPathShape =
|
||||
RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
|
||||
candidate.startsWith("/") ||
|
||||
WINDOWS_DRIVE_PATH_PATTERN.test(candidate) ||
|
||||
WINDOWS_UNC_PATH_PATTERN.test(candidate);
|
||||
if (!hasExplicitPathShape) {
|
||||
const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
|
||||
const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
|
||||
if (looksLikeHostname(firstSegment, hasPosition)) return null;
|
||||
if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basenameOfPath(withoutPosition))) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const resolved = resolveMarkdownFileLinkMeta(candidate, cwd);
|
||||
if (resolved) return resolved;
|
||||
|
||||
// `Makefile:12` — conventional extensionless names fail the generic
|
||||
// markdown-link candidate patterns, but here the :line suffix already
|
||||
// marked the span as a file reference.
|
||||
if (
|
||||
cwd &&
|
||||
BARE_EXTENSIONLESS_POSITION_PATTERN.test(candidate) &&
|
||||
EXTENSIONLESS_FILE_NAMES.has(candidate.replace(POSITION_SUFFIX_PATTERN, ""))
|
||||
) {
|
||||
return buildFileLinkMetaFromTarget(resolvePathLinkTarget(candidate, cwd), cwd);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function basenameOfPath(path: string): string {
|
||||
const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
|
||||
return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
|
||||
@@ -194,7 +382,10 @@ export function resolveMarkdownFileLinkMeta(
|
||||
): MarkdownFileLinkMeta | null {
|
||||
const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
|
||||
if (!targetPath) return null;
|
||||
return buildFileLinkMetaFromTarget(targetPath, cwd);
|
||||
}
|
||||
|
||||
function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string): MarkdownFileLinkMeta {
|
||||
const { path, line, column } = splitPathAndPosition(targetPath);
|
||||
const parsedLine = line ? Number.parseInt(line, 10) : Number.NaN;
|
||||
const parsedColumn = column ? Number.parseInt(column, 10) : Number.NaN;
|
||||
|
||||
@@ -1,26 +1,19 @@
|
||||
import { ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { removeLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
|
||||
import {
|
||||
MAX_STASH_ENTRIES_PER_QUEUE,
|
||||
MAX_STASH_ENTRIES,
|
||||
PROMPT_STASH_STORAGE_KEY,
|
||||
MAX_STASH_ENTRY_ATTACHMENT_CHARS,
|
||||
PROMPT_STASH_UNSCOPED_KEY,
|
||||
partitionStashAttachments,
|
||||
promptStashScopeKey,
|
||||
usePromptStashStore,
|
||||
writePromptStashStorageForTest,
|
||||
type PromptStashEntry,
|
||||
} from "./promptStashStore";
|
||||
|
||||
const CLAUDE_AGENT_INSTANCE = ProviderInstanceId.make("claudeAgent");
|
||||
const CODEX_INSTANCE = ProviderInstanceId.make("codex");
|
||||
|
||||
function makeEntry(input: {
|
||||
id: string;
|
||||
providerInstanceId?: ProviderInstanceId | null;
|
||||
prompt?: string;
|
||||
attachmentChars?: number;
|
||||
}): PromptStashEntry {
|
||||
@@ -40,35 +33,16 @@ function makeEntry(input: {
|
||||
},
|
||||
]
|
||||
: [],
|
||||
providerInstanceId:
|
||||
input.providerInstanceId === undefined ? CLAUDE_AGENT_INSTANCE : input.providerInstanceId,
|
||||
modelSelection: null,
|
||||
droppedImageNames: [],
|
||||
};
|
||||
}
|
||||
|
||||
function resetPromptStashStore() {
|
||||
usePromptStashStore.setState({ queuesByScopeKey: {} });
|
||||
usePromptStashStore.setState({ entries: [] });
|
||||
writePromptStashStorageForTest("");
|
||||
removeLocalStorageItem(PROMPT_STASH_STORAGE_KEY);
|
||||
}
|
||||
|
||||
describe("promptStashScopeKey", () => {
|
||||
it("maps a provider instance to its own bucket and null to the unscoped bucket", () => {
|
||||
expect(promptStashScopeKey(CLAUDE_AGENT_INSTANCE)).toBe("provider:claudeAgent");
|
||||
expect(promptStashScopeKey(null)).toBe(PROMPT_STASH_UNSCOPED_KEY);
|
||||
expect(promptStashScopeKey(undefined)).toBe(PROMPT_STASH_UNSCOPED_KEY);
|
||||
});
|
||||
|
||||
// Provider slugs must match /^[a-zA-Z][a-zA-Z0-9_-]*$/, so no real instance
|
||||
// id can equal the unscoped sentinel. The namespace prefix makes that
|
||||
// structural rather than incidental.
|
||||
it("namespaces provider keys so they can never equal the unscoped sentinel", () => {
|
||||
expect(promptStashScopeKey(CLAUDE_AGENT_INSTANCE)).not.toBe(PROMPT_STASH_UNSCOPED_KEY);
|
||||
expect(promptStashScopeKey(CODEX_INSTANCE).startsWith("provider:")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("partitionStashAttachments", () => {
|
||||
it("keeps attachments within the budget and reports dropped names in order", () => {
|
||||
const small = {
|
||||
@@ -124,74 +98,50 @@ describe("promptStashStore", () => {
|
||||
const store = usePromptStashStore.getState();
|
||||
store.stashEntry(makeEntry({ id: "first" }));
|
||||
store.stashEntry(makeEntry({ id: "second" }));
|
||||
const queue =
|
||||
usePromptStashStore.getState().queuesByScopeKey[promptStashScopeKey(CLAUDE_AGENT_INSTANCE)] ??
|
||||
[];
|
||||
expect(queue.map((entry) => entry.id)).toEqual(["second", "first"]);
|
||||
const entries = usePromptStashStore.getState().entries;
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["second", "first"]);
|
||||
});
|
||||
|
||||
it("scopes queues by provider instance, including the unscoped bucket", () => {
|
||||
it("evicts the oldest entry past the cap and returns it", () => {
|
||||
const store = usePromptStashStore.getState();
|
||||
store.stashEntry(makeEntry({ id: "claude" }));
|
||||
store.stashEntry(makeEntry({ id: "codex", providerInstanceId: CODEX_INSTANCE }));
|
||||
store.stashEntry(makeEntry({ id: "none", providerInstanceId: null }));
|
||||
const queues = usePromptStashStore.getState().queuesByScopeKey;
|
||||
expect(queues[promptStashScopeKey(CLAUDE_AGENT_INSTANCE)]?.map((entry) => entry.id)).toEqual([
|
||||
"claude",
|
||||
]);
|
||||
expect(queues[promptStashScopeKey(CODEX_INSTANCE)]?.map((entry) => entry.id)).toEqual([
|
||||
"codex",
|
||||
]);
|
||||
expect(queues[PROMPT_STASH_UNSCOPED_KEY]?.map((entry) => entry.id)).toEqual(["none"]);
|
||||
});
|
||||
|
||||
it("evicts the oldest entry past the per-queue cap and returns it", () => {
|
||||
const store = usePromptStashStore.getState();
|
||||
for (let index = 0; index < MAX_STASH_ENTRIES_PER_QUEUE; index += 1) {
|
||||
for (let index = 0; index < MAX_STASH_ENTRIES; index += 1) {
|
||||
expect(store.stashEntry(makeEntry({ id: `entry-${index}` })).evicted).toBeNull();
|
||||
}
|
||||
const { evicted } = store.stashEntry(makeEntry({ id: "overflow" }));
|
||||
expect(evicted?.id).toBe("entry-0");
|
||||
const queue =
|
||||
usePromptStashStore.getState().queuesByScopeKey[promptStashScopeKey(CLAUDE_AGENT_INSTANCE)] ??
|
||||
[];
|
||||
expect(queue).toHaveLength(MAX_STASH_ENTRIES_PER_QUEUE);
|
||||
expect(queue[0]?.id).toBe("overflow");
|
||||
const entries = usePromptStashStore.getState().entries;
|
||||
expect(entries).toHaveLength(MAX_STASH_ENTRIES);
|
||||
expect(entries[0]?.id).toBe("overflow");
|
||||
});
|
||||
|
||||
// This test environment has no `localStorage`, so the store runs on its
|
||||
// in-memory fallback — the exact "kept for this session, gone on reload"
|
||||
// case the composer must distinguish from an outright write failure.
|
||||
it("distinguishes a memory-only write (written, not durable) from a failed one", () => {
|
||||
const store = usePromptStashStore.getState();
|
||||
const result = store.stashEntry(makeEntry({ id: "memory-only" }));
|
||||
expect(result.written).toBe(true);
|
||||
expect(result.durable).toBe(false);
|
||||
expect(usePromptStashStore.getState().entries.map((entry) => entry.id)).toEqual([
|
||||
"memory-only",
|
||||
]);
|
||||
});
|
||||
|
||||
it("takeEntry removes and returns the entry; second take returns null", () => {
|
||||
const store = usePromptStashStore.getState();
|
||||
store.stashEntry(makeEntry({ id: "keep" }));
|
||||
store.stashEntry(makeEntry({ id: "take" }));
|
||||
expect(store.takeEntry(promptStashScopeKey(CLAUDE_AGENT_INSTANCE), "take").entry?.id).toBe(
|
||||
"take",
|
||||
);
|
||||
expect(store.takeEntry(promptStashScopeKey(CLAUDE_AGENT_INSTANCE), "take").entry).toBeNull();
|
||||
const queue =
|
||||
usePromptStashStore.getState().queuesByScopeKey[promptStashScopeKey(CLAUDE_AGENT_INSTANCE)] ??
|
||||
[];
|
||||
expect(queue.map((entry) => entry.id)).toEqual(["keep"]);
|
||||
});
|
||||
|
||||
// Queue keys are persisted as plain strings, so a hand-edited or corrupted
|
||||
// localStorage payload can carry a literal `__proto__` key that survives
|
||||
// JSON.parse as an own property. An unguarded lookup would resolve to
|
||||
// Object.prototype and throw "not iterable" on spread.
|
||||
it("tolerates a __proto__ scope key rehydrated from storage", () => {
|
||||
usePromptStashStore.setState({
|
||||
queuesByScopeKey: JSON.parse('{"__proto__":[]}') as Record<string, PromptStashEntry[]>,
|
||||
});
|
||||
const store = usePromptStashStore.getState();
|
||||
expect(() => store.takeEntry("__proto__", "missing")).not.toThrow();
|
||||
expect(store.takeEntry("__proto__", "missing").entry).toBeNull();
|
||||
expect(store.takeEntry("take").entry?.id).toBe("take");
|
||||
expect(store.takeEntry("take").entry).toBeNull();
|
||||
const entries = usePromptStashStore.getState().entries;
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["keep"]);
|
||||
});
|
||||
|
||||
it("finalizeEntryImages attaches images and clears the pending count", () => {
|
||||
const store = usePromptStashStore.getState();
|
||||
const scopeKey = promptStashScopeKey(CLAUDE_AGENT_INSTANCE);
|
||||
store.stashEntry({ ...makeEntry({ id: "pending" }), pendingImageCount: 2 });
|
||||
|
||||
const { attached } = store.finalizeEntryImages(scopeKey, "pending", {
|
||||
const { attached } = store.finalizeEntryImages("pending", {
|
||||
attachments: [
|
||||
{
|
||||
id: "img-1",
|
||||
@@ -206,7 +156,7 @@ describe("promptStashStore", () => {
|
||||
});
|
||||
|
||||
expect(attached).toBe(true);
|
||||
const entry = usePromptStashStore.getState().queuesByScopeKey[scopeKey]?.[0];
|
||||
const entry = usePromptStashStore.getState().entries[0];
|
||||
expect(entry?.attachments).toHaveLength(1);
|
||||
expect(entry?.droppedImageNames).toEqual(["big.png"]);
|
||||
expect(entry?.pendingImageCount).toBe(0);
|
||||
@@ -214,12 +164,11 @@ describe("promptStashStore", () => {
|
||||
|
||||
it("finalizeEntryImages reports false when the entry was already taken", () => {
|
||||
const store = usePromptStashStore.getState();
|
||||
const scopeKey = promptStashScopeKey(CLAUDE_AGENT_INSTANCE);
|
||||
store.stashEntry({ ...makeEntry({ id: "racing" }), pendingImageCount: 1 });
|
||||
// Restored (or deleted) while its images were still encoding.
|
||||
store.takeEntry(scopeKey, "racing");
|
||||
store.takeEntry("racing");
|
||||
|
||||
const { attached } = store.finalizeEntryImages(scopeKey, "racing", {
|
||||
const { attached } = store.finalizeEntryImages("racing", {
|
||||
attachments: [],
|
||||
droppedImageNames: [],
|
||||
unreadableImageNames: [],
|
||||
@@ -229,31 +178,31 @@ describe("promptStashStore", () => {
|
||||
});
|
||||
|
||||
it("settles a pending count left behind by a crashed or closed session", () => {
|
||||
const scopeKey = promptStashScopeKey(CLAUDE_AGENT_INSTANCE);
|
||||
writePromptStashStorageForTest(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
version: 2,
|
||||
state: {
|
||||
queuesByScopeKey: {
|
||||
[scopeKey]: [{ ...makeEntry({ id: "orphan" }), pendingImageCount: 2 }],
|
||||
},
|
||||
entries: [{ ...makeEntry({ id: "orphan" }), pendingImageCount: 2 }],
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Hydration must settle the stale count, or the entry would stay stuck
|
||||
// showing "saving…" with images that no longer exist anywhere.
|
||||
const entry = usePromptStashStore.getState().queuesByScopeKey[scopeKey]?.[0];
|
||||
const entry = usePromptStashStore.getState().entries[0];
|
||||
expect(entry?.pendingImageCount).toBe(0);
|
||||
expect(entry?.unreadableImageNames).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("drops the scope key entirely when its queue empties", () => {
|
||||
const store = usePromptStashStore.getState();
|
||||
store.stashEntry(makeEntry({ id: "only" }));
|
||||
store.takeEntry(promptStashScopeKey(CLAUDE_AGENT_INSTANCE), "only");
|
||||
expect(
|
||||
usePromptStashStore.getState().queuesByScopeKey[promptStashScopeKey(CLAUDE_AGENT_INSTANCE)],
|
||||
).toBeUndefined();
|
||||
it("ignores an unreadable v1 payload seeded under the current key", () => {
|
||||
// The v1 shape (per-provider queues) does not decode as v2; hydration
|
||||
// must fall back to an empty stash rather than throw.
|
||||
writePromptStashStorageForTest(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
state: { queuesByScopeKey: { "provider:claudeAgent": [] } },
|
||||
}),
|
||||
);
|
||||
expect(usePromptStashStore.getState().entries).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,24 +1,20 @@
|
||||
import { ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { create } from "zustand";
|
||||
|
||||
import { PersistedComposerImageAttachment } from "./composerDraftStore";
|
||||
import { createMemoryStorage, type StateStorage } from "./lib/storage";
|
||||
|
||||
export const PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v1";
|
||||
const PROMPT_STASH_STORAGE_VERSION = 1;
|
||||
|
||||
export const PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v2";
|
||||
/**
|
||||
* Queue bucket for prompts stashed while no provider instance is selected.
|
||||
*
|
||||
* Provider-scoped keys are prefixed (see `promptStashScopeKey`), so this
|
||||
* sentinel can never collide with a provider literally named `__none__`.
|
||||
* v1 bucketed entries into per-provider-instance queues and stored a model
|
||||
* selection with each prompt. The stash is provider-agnostic now, so the old
|
||||
* payload is deleted at startup rather than migrated — left behind it would
|
||||
* silently hold megabytes of the origin's ~5MB localStorage quota forever.
|
||||
*/
|
||||
export const PROMPT_STASH_UNSCOPED_KEY = "__none__";
|
||||
/** Namespace applied to provider-derived keys to keep them collision-proof. */
|
||||
const PROVIDER_SCOPE_PREFIX = "provider:";
|
||||
const LEGACY_PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v1";
|
||||
const PROMPT_STASH_STORAGE_VERSION = 2;
|
||||
|
||||
export const MAX_STASH_ENTRIES_PER_QUEUE = 20;
|
||||
export const MAX_STASH_ENTRIES = 20;
|
||||
/**
|
||||
* Budget for an entry's serialized attachment payload. localStorage is a
|
||||
* ~5MB origin-wide quota shared with the composer draft store, so oversized
|
||||
@@ -30,13 +26,17 @@ export const MAX_STASH_ENTRIES_PER_QUEUE = 20;
|
||||
*/
|
||||
export const MAX_STASH_ENTRY_ATTACHMENT_CHARS = 2_700_000;
|
||||
|
||||
/**
|
||||
* A stashed prompt carries only what every provider can accept: text and
|
||||
* image attachments. Deliberately no provider instance or model selection —
|
||||
* the point of stashing is to move a prompt into a different thread or
|
||||
* provider, so restoring must never drag the old model choice along.
|
||||
*/
|
||||
const StashEntrySchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
prompt: Schema.String,
|
||||
attachments: Schema.Array(PersistedComposerImageAttachment),
|
||||
providerInstanceId: Schema.NullOr(ProviderInstanceId),
|
||||
modelSelection: Schema.NullOr(ModelSelection),
|
||||
/** Names of images that exceeded the attachment budget and were not saved. */
|
||||
droppedImageNames: Schema.Array(Schema.String),
|
||||
/**
|
||||
@@ -57,7 +57,7 @@ const StashEntrySchema = Schema.Struct({
|
||||
export type PromptStashEntry = typeof StashEntrySchema.Type;
|
||||
|
||||
const PersistedPromptStashState = Schema.Struct({
|
||||
queuesByScopeKey: Schema.Record(Schema.String, Schema.Array(StashEntrySchema)),
|
||||
entries: Schema.Array(StashEntrySchema),
|
||||
});
|
||||
type PersistedPromptStashState = typeof PersistedPromptStashState.Type;
|
||||
|
||||
@@ -74,44 +74,23 @@ const decodePersistedPromptStashState = Schema.decodeUnknownSync(PersistedPrompt
|
||||
* recorded as unreadable to keep the prompt itself restorable.
|
||||
*/
|
||||
function clearOrphanedPendingImages(
|
||||
queues: Record<string, ReadonlyArray<PromptStashEntry>>,
|
||||
): Record<string, ReadonlyArray<PromptStashEntry>> {
|
||||
const next: Record<string, ReadonlyArray<PromptStashEntry>> = {};
|
||||
for (const [scopeKey, queue] of Object.entries(queues)) {
|
||||
next[scopeKey] = queue.map((entry) => {
|
||||
if (!entry.pendingImageCount) return entry;
|
||||
const lostCount = entry.pendingImageCount;
|
||||
return {
|
||||
...entry,
|
||||
pendingImageCount: 0,
|
||||
unreadableImageNames: [
|
||||
...(entry.unreadableImageNames ?? []),
|
||||
...Array.from(
|
||||
{ length: lostCount },
|
||||
(_, index) => `image ${index + 1} (not saved before reload)`,
|
||||
),
|
||||
],
|
||||
};
|
||||
});
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Maps the composer's active provider instance to a stash queue bucket. */
|
||||
export function promptStashScopeKey(instanceId: ProviderInstanceId | null | undefined): string {
|
||||
return instanceId ? `${PROVIDER_SCOPE_PREFIX}${instanceId}` : PROMPT_STASH_UNSCOPED_KEY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a queue without inheriting from `Object.prototype`. Scope keys derive
|
||||
* from user-authored provider slugs, so a key like `__proto__` must not
|
||||
* resolve to the prototype chain.
|
||||
*/
|
||||
function readQueue(
|
||||
queues: Record<string, ReadonlyArray<PromptStashEntry>>,
|
||||
scopeKey: string,
|
||||
entries: ReadonlyArray<PromptStashEntry>,
|
||||
): ReadonlyArray<PromptStashEntry> {
|
||||
return Object.hasOwn(queues, scopeKey) ? (queues[scopeKey] ?? []) : [];
|
||||
return entries.map((entry) => {
|
||||
if (!entry.pendingImageCount) return entry;
|
||||
const lostCount = entry.pendingImageCount;
|
||||
return {
|
||||
...entry,
|
||||
pendingImageCount: 0,
|
||||
unreadableImageNames: [
|
||||
...(entry.unreadableImageNames ?? []),
|
||||
...Array.from(
|
||||
{ length: lostCount },
|
||||
(_, index) => `image ${index + 1} (not saved before reload)`,
|
||||
),
|
||||
],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -163,7 +142,7 @@ function resolveBaseStorage(): { storage: StateStorage; durable: boolean } {
|
||||
const { storage: baseStashStorage, durable: storageIsDurable } = resolveBaseStorage();
|
||||
|
||||
/**
|
||||
* Persists the queues, immediately rather than debounced. Stashing is a
|
||||
* Persists the queue, immediately rather than debounced. Stashing is a
|
||||
* deliberate, infrequent keystroke — not a per-character autosave — so there
|
||||
* is nothing to coalesce, and the caller clears the composer on the strength
|
||||
* of this write landing, which a debounce timer cannot honestly report.
|
||||
@@ -171,7 +150,7 @@ const { storage: baseStashStorage, durable: storageIsDurable } = resolveBaseStor
|
||||
* Returns whether the write will survive a reload: false on a quota rejection
|
||||
* or when only the in-memory fallback is available.
|
||||
*/
|
||||
function persistQueues(queues: Record<string, ReadonlyArray<PromptStashEntry>>): {
|
||||
function persistEntries(entries: ReadonlyArray<PromptStashEntry>): {
|
||||
/** The write succeeded (possibly only into the in-memory fallback). */
|
||||
written: boolean;
|
||||
/** The write will survive a reload. */
|
||||
@@ -182,7 +161,7 @@ function persistQueues(queues: Record<string, ReadonlyArray<PromptStashEntry>>):
|
||||
PROMPT_STASH_STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
version: PROMPT_STASH_STORAGE_VERSION,
|
||||
state: { queuesByScopeKey: queues },
|
||||
state: { entries },
|
||||
}),
|
||||
);
|
||||
return { written: true, durable: storageIsDurable };
|
||||
@@ -192,40 +171,42 @@ function persistQueues(queues: Record<string, ReadonlyArray<PromptStashEntry>>):
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads the persisted queues, settling stale pending counts. */
|
||||
function readPersistedQueues(): Record<string, ReadonlyArray<PromptStashEntry>> | null {
|
||||
/** Reads the persisted queue, settling stale pending counts. */
|
||||
function readPersistedEntries(): ReadonlyArray<PromptStashEntry> | null {
|
||||
try {
|
||||
const raw = baseStashStorage.getItem(PROMPT_STASH_STORAGE_KEY);
|
||||
if (typeof raw !== "string" || raw.length === 0) return null;
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
const state = (parsed as { state?: unknown } | null)?.state;
|
||||
if (!state) return null;
|
||||
return clearOrphanedPendingImages(decodePersistedPromptStashState(state).queuesByScopeKey);
|
||||
return clearOrphanedPendingImages(decodePersistedPromptStashState(state).entries);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface PromptStashStoreState {
|
||||
queuesByScopeKey: Record<string, ReadonlyArray<PromptStashEntry>>;
|
||||
entries: ReadonlyArray<PromptStashEntry>;
|
||||
/**
|
||||
* Prepends an entry to its scope's queue, evicting the oldest entry past
|
||||
* the per-queue cap. Returns the evicted entry (for messaging) if any.
|
||||
* Prepends an entry to the queue, evicting the oldest entry past the cap.
|
||||
* Returns the evicted entry (for messaging) if any.
|
||||
*/
|
||||
stashEntry: (entry: PromptStashEntry) => {
|
||||
evicted: PromptStashEntry | null;
|
||||
/** False when the write did not reach durable storage; nothing was kept. */
|
||||
/** False when the write failed outright (e.g. quota); nothing was kept. */
|
||||
written: boolean;
|
||||
/**
|
||||
* False when the write will not survive a reload: either it failed, or it
|
||||
* landed only in the in-memory fallback because localStorage is blocked.
|
||||
*/
|
||||
durable: boolean;
|
||||
};
|
||||
/**
|
||||
* Removes and returns an entry from a scope's queue (restore + delete).
|
||||
* Removes and returns an entry from the queue (restore + delete).
|
||||
* `durable` is false when the removal could not be persisted, meaning a
|
||||
* reload would resurrect the entry.
|
||||
*/
|
||||
takeEntry: (
|
||||
scopeKey: string,
|
||||
entryId: string,
|
||||
) => { entry: PromptStashEntry | null; durable: boolean };
|
||||
takeEntry: (entryId: string) => { entry: PromptStashEntry | null; durable: boolean };
|
||||
/**
|
||||
* Attaches the encoded images to an entry written earlier by `stashEntry`,
|
||||
* clearing its pending count. Returns attached=false when the entry is gone
|
||||
@@ -233,7 +214,6 @@ interface PromptStashStoreState {
|
||||
* tell the user their images did not make it.
|
||||
*/
|
||||
finalizeEntryImages: (
|
||||
scopeKey: string,
|
||||
entryId: string,
|
||||
images: {
|
||||
attachments: ReadonlyArray<PersistedComposerImageAttachment>;
|
||||
@@ -244,58 +224,45 @@ interface PromptStashStoreState {
|
||||
}
|
||||
|
||||
export const usePromptStashStore = create<PromptStashStoreState>()((set, get) => ({
|
||||
queuesByScopeKey: {},
|
||||
entries: [],
|
||||
stashEntry: (entry) => {
|
||||
const scopeKey = promptStashScopeKey(entry.providerInstanceId);
|
||||
const queues = get().queuesByScopeKey;
|
||||
const nextQueue = [entry, ...readQueue(queues, scopeKey)];
|
||||
const evicted =
|
||||
nextQueue.length > MAX_STASH_ENTRIES_PER_QUEUE ? (nextQueue.pop() ?? null) : null;
|
||||
const next = { ...queues, [scopeKey]: nextQueue };
|
||||
const { written, durable } = persistQueues(next);
|
||||
const nextEntries = [entry, ...get().entries];
|
||||
const evicted = nextEntries.length > MAX_STASH_ENTRIES ? (nextEntries.pop() ?? null) : null;
|
||||
const { written, durable } = persistEntries(nextEntries);
|
||||
// A rejected write must not leave the entry visible either: the caller
|
||||
// keeps the composer intact on failure, so a stashed copy would
|
||||
// duplicate the prompt. Eviction likewise only sticks on success.
|
||||
if (!written) {
|
||||
return { evicted: null, durable: false };
|
||||
return { evicted: null, written: false, durable: false };
|
||||
}
|
||||
set(() => ({ queuesByScopeKey: next }));
|
||||
return { evicted, durable };
|
||||
set(() => ({ entries: nextEntries }));
|
||||
return { evicted, written: true, durable };
|
||||
},
|
||||
takeEntry: (scopeKey, entryId) => {
|
||||
const queues = get().queuesByScopeKey;
|
||||
const queue = readQueue(queues, scopeKey);
|
||||
const entry = queue.find((candidate) => candidate.id === entryId) ?? null;
|
||||
takeEntry: (entryId) => {
|
||||
const entries = get().entries;
|
||||
const entry = entries.find((candidate) => candidate.id === entryId) ?? null;
|
||||
if (!entry) return { entry: null, durable: true };
|
||||
const nextQueue = queue.filter((candidate) => candidate.id !== entryId);
|
||||
const next = { ...queues };
|
||||
if (nextQueue.length === 0) {
|
||||
delete next[scopeKey];
|
||||
} else {
|
||||
next[scopeKey] = nextQueue;
|
||||
}
|
||||
const { durable } = persistQueues(next);
|
||||
set(() => ({ queuesByScopeKey: next }));
|
||||
const nextEntries = entries.filter((candidate) => candidate.id !== entryId);
|
||||
const { durable } = persistEntries(nextEntries);
|
||||
set(() => ({ entries: nextEntries }));
|
||||
return { entry, durable };
|
||||
},
|
||||
finalizeEntryImages: (scopeKey, entryId, images) => {
|
||||
const queues = get().queuesByScopeKey;
|
||||
const queue = readQueue(queues, scopeKey);
|
||||
const index = queue.findIndex((candidate) => candidate.id === entryId);
|
||||
const existing = index === -1 ? undefined : queue[index];
|
||||
finalizeEntryImages: (entryId, images) => {
|
||||
const entries = get().entries;
|
||||
const index = entries.findIndex((candidate) => candidate.id === entryId);
|
||||
const existing = index === -1 ? undefined : entries[index];
|
||||
// Restored or deleted mid-encode: nothing to attach to.
|
||||
if (!existing) return { attached: false, durable: true };
|
||||
const nextQueue = [...queue];
|
||||
nextQueue[index] = {
|
||||
const nextEntries = [...entries];
|
||||
nextEntries[index] = {
|
||||
...existing,
|
||||
attachments: images.attachments,
|
||||
droppedImageNames: images.droppedImageNames,
|
||||
unreadableImageNames: images.unreadableImageNames,
|
||||
pendingImageCount: 0,
|
||||
};
|
||||
const next = { ...queues, [scopeKey]: nextQueue };
|
||||
const { durable } = persistQueues(next);
|
||||
set(() => ({ queuesByScopeKey: next }));
|
||||
const { durable } = persistEntries(nextEntries);
|
||||
set(() => ({ entries: nextEntries }));
|
||||
return { attached: true, durable };
|
||||
},
|
||||
}));
|
||||
@@ -303,14 +270,18 @@ export const usePromptStashStore = create<PromptStashStoreState>()((set, get) =>
|
||||
// Hydrate once at startup. Like the app's other persisted stores, tabs are
|
||||
// last-write-wins: no cross-tab merging or storage-event syncing.
|
||||
{
|
||||
const persisted = readPersistedQueues();
|
||||
try {
|
||||
baseStashStorage.removeItem(LEGACY_PROMPT_STASH_STORAGE_KEY);
|
||||
} catch {
|
||||
// Purging the v1 payload is best-effort; a storage policy that rejects
|
||||
// the delete must not take down module init.
|
||||
}
|
||||
const persisted = readPersistedEntries();
|
||||
if (persisted) {
|
||||
usePromptStashStore.setState({ queuesByScopeKey: persisted });
|
||||
usePromptStashStore.setState({ entries: persisted });
|
||||
}
|
||||
}
|
||||
|
||||
export const EMPTY_PROMPT_STASH_QUEUE: ReadonlyArray<PromptStashEntry> = [];
|
||||
|
||||
/**
|
||||
* Test seam: seeds the persisted payload through the same storage the store
|
||||
* reads and rehydrates, without needing a real `localStorage` global.
|
||||
@@ -318,5 +289,5 @@ export const EMPTY_PROMPT_STASH_QUEUE: ReadonlyArray<PromptStashEntry> = [];
|
||||
*/
|
||||
export function writePromptStashStorageForTest(raw: string): void {
|
||||
baseStashStorage.setItem(PROMPT_STASH_STORAGE_KEY, raw);
|
||||
usePromptStashStore.setState({ queuesByScopeKey: readPersistedQueues() ?? {} });
|
||||
usePromptStashStore.setState({ entries: readPersistedEntries() ?? [] });
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagn
|
||||
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
|
||||
import { Route as SettingsBetaRouteImport } from './routes/settings.beta'
|
||||
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
|
||||
import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
|
||||
import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
|
||||
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
|
||||
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
|
||||
@@ -90,6 +91,11 @@ const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
|
||||
path: '/archived',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsAppearanceRoute = SettingsAppearanceRouteImport.update({
|
||||
id: '/appearance',
|
||||
path: '/appearance',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const ConnectCallbackRoute = ConnectCallbackRouteImport.update({
|
||||
id: '/connect_/callback',
|
||||
path: '/connect/callback',
|
||||
@@ -113,6 +119,7 @@ export interface FileRoutesByFullPath {
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/beta': typeof SettingsBetaRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
@@ -129,6 +136,7 @@ export interface FileRoutesByTo {
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/beta': typeof SettingsBetaRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
@@ -148,6 +156,7 @@ export interface FileRoutesById {
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/connect_/callback': typeof ConnectCallbackRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/beta': typeof SettingsBetaRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
@@ -168,6 +177,7 @@ export interface FileRouteTypes {
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/connect/callback'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
| '/settings/beta'
|
||||
| '/settings/connections'
|
||||
@@ -184,6 +194,7 @@ export interface FileRouteTypes {
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/connect/callback'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
| '/settings/beta'
|
||||
| '/settings/connections'
|
||||
@@ -202,6 +213,7 @@ export interface FileRouteTypes {
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/connect_/callback'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
| '/settings/beta'
|
||||
| '/settings/connections'
|
||||
@@ -316,6 +328,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsArchivedRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/appearance': {
|
||||
id: '/settings/appearance'
|
||||
path: '/appearance'
|
||||
fullPath: '/settings/appearance'
|
||||
preLoaderRoute: typeof SettingsAppearanceRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/connect_/callback': {
|
||||
id: '/connect_/callback'
|
||||
path: '/connect/callback'
|
||||
@@ -355,6 +374,7 @@ const ChatRouteChildren: ChatRouteChildren = {
|
||||
const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
|
||||
|
||||
interface SettingsRouteChildren {
|
||||
SettingsAppearanceRoute: typeof SettingsAppearanceRoute
|
||||
SettingsArchivedRoute: typeof SettingsArchivedRoute
|
||||
SettingsBetaRoute: typeof SettingsBetaRoute
|
||||
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
|
||||
@@ -366,6 +386,7 @@ interface SettingsRouteChildren {
|
||||
}
|
||||
|
||||
const SettingsRouteChildren: SettingsRouteChildren = {
|
||||
SettingsAppearanceRoute: SettingsAppearanceRoute,
|
||||
SettingsArchivedRoute: SettingsArchivedRoute,
|
||||
SettingsBetaRoute: SettingsBetaRoute,
|
||||
SettingsConnectionsRoute: SettingsConnectionsRoute,
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useAtomValue } from "@effect/atom-react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import { isCommandPaletteOpen } from "../commandPaletteBus";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { useClientSettings, useSidebarV2Enabled } from "../hooks/useSettings";
|
||||
import { openCommandPalette } from "../commandPaletteBus";
|
||||
import { useProjects } from "../state/entities";
|
||||
import { usePrimaryEnvironmentId } from "../state/environments";
|
||||
@@ -28,7 +28,7 @@ function ChatRouteGlobalShortcuts() {
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
|
||||
useHandleNewThread();
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
const sidebarV2Enabled = useSidebarV2Enabled();
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const projects = useProjects();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
|
||||
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user