Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8580032a5f |
No files matched your search
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) OpenAI
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,64 +0,0 @@
|
||||
---
|
||||
name: ios-debugger-agent
|
||||
description: Build, launch, inspect, and drive iOS apps with the repository-configured XcodeBuildMCP server. Use on macOS for iOS Simulator builds, focused native test runs, semantic UI automation, screenshots, logs, or debugging, including T3 Code Mobile verification.
|
||||
---
|
||||
|
||||
# iOS Debugger Agent
|
||||
|
||||
Use the repository-configured `xcodebuildmcp` tools instead of requiring a globally installed Codex plugin. Prefer MCP tools over raw `xcodebuild`, `xcrun`, or `simctl` when the client exposes them.
|
||||
|
||||
## Confirm availability
|
||||
|
||||
This workflow requires macOS 14.5 or newer, Xcode 16 or newer, and Node.js 18 or newer. The repository pins XcodeBuildMCP in both `.mcp.json` for Claude Code and `.codex/config.toml` for Codex. Project MCP servers may require one-time trust or approval followed by a new session.
|
||||
|
||||
If the tools are missing:
|
||||
|
||||
1. Confirm the repository is trusted and its project MCP server was approved.
|
||||
2. Restart or recreate the agent session after approving configuration.
|
||||
3. Run `npx --yes [email protected] doctor` when the server starts but simulator or UI-automation tools are unavailable. Follow its actionable Xcode or AXe setup guidance.
|
||||
4. Fall back to the pinned XcodeBuildMCP CLI or native Apple CLIs only when the current agent client cannot expose project MCP tools.
|
||||
|
||||
Do not ask contributors to install the OpenAI `build-ios-apps` plugin globally.
|
||||
|
||||
## Establish one simulator context
|
||||
|
||||
1. Call `session_show_defaults` before discovery, build, launch, or UI work.
|
||||
2. Call `list_sims` and select one explicit simulator UDID. Prefer a simulator that is already booted; boot an installed simulator when verification requires it, but do not create or download runtimes without user authorization.
|
||||
3. Call `session_set_defaults` with the project or workspace, scheme, Debug configuration, simulator ID, and bundle identifier when known.
|
||||
4. Keep every subsequent build, launch, screenshot, log capture, and UI action pinned to that same UDID.
|
||||
|
||||
Avoid generic Mac window automation for switching among Simulator windows. Explicit device identity is more reliable.
|
||||
|
||||
## Choose build or launch
|
||||
|
||||
- Use `build_run_sim` when native source, native dependencies, entitlements, or project configuration changed.
|
||||
- Use `test_sim` for the smallest relevant native test target or test cases; do not run an entire workspace test matrix routinely.
|
||||
- Use `launch_app_sim` when a compatible app is already installed and no native rebuild is needed.
|
||||
- To reuse an existing build artifact, use `get_sim_app_path` or `get_app_bundle_id`, install it with `install_app_sim` when necessary, and then launch it.
|
||||
- Do not run a build-only action immediately before `build_run_sim` unless the task requires both artifacts.
|
||||
|
||||
After launch, call `snapshot_ui` or `screenshot` before interacting. An open Simulator window alone is not evidence that the intended app launched.
|
||||
|
||||
## Drive the UI semantically
|
||||
|
||||
1. Call `snapshot_ui` to obtain the current accessibility hierarchy and element references.
|
||||
2. Use only current `elementRef` values whose snapshot entries list the intended action. XcodeBuildMCP `2.6.2` does not accept coordinates for `tap`; when the app exposes no actionable reference, prefer a registered deep link or another app-supported route and otherwise report the accessibility blocker.
|
||||
3. Refresh with `snapshot_ui` after navigation or layout changes. Element references are snapshot-specific.
|
||||
4. Use `wait_for_ui` for asynchronous transitions when available rather than fixed sleeps.
|
||||
5. Capture a final `screenshot` for the state that proves the affected flow.
|
||||
|
||||
Use `gesture` or scoped swipe actions when needed. If a gesture is unreliable, return to a known route or relaunch rather than switching to generic desktop automation.
|
||||
|
||||
## Capture logs and debug
|
||||
|
||||
- Use `start_sim_log_cap` and `stop_sim_log_cap` with the exact bundle identifier for focused runtime logs.
|
||||
- Use debugger tools only when the task requires runtime diagnosis; attach to the selected simulator and app rather than an ambiguous process.
|
||||
- Summarize relevant errors instead of returning unbounded logs.
|
||||
|
||||
## Clean up
|
||||
|
||||
Stop only log captures, debugger sessions, apps, or simulators started for the current test. Leave pre-existing simulators and unrelated sessions alone.
|
||||
|
||||
## Upstream
|
||||
|
||||
Adapted from OpenAI's [`build-ios-apps`](https://github.com/openai/plugins/tree/main/plugins/build-ios-apps) plugin version `0.1.2` (`ios-debugger-agent`, MIT) and aligned with XcodeBuildMCP `2.6.2` tool names.
|
||||
@@ -1,9 +0,0 @@
|
||||
interface:
|
||||
display_name: "iOS Debugger Agent"
|
||||
short_description: "Build and drive iOS Simulator apps"
|
||||
default_prompt: "Use $ios-debugger-agent to build, launch, and inspect the current iOS app on Simulator."
|
||||
dependencies:
|
||||
tools:
|
||||
- type: "mcp"
|
||||
value: "xcodebuildmcp"
|
||||
description: "Repository-configured Xcode build, simulator, logging, debugging, and semantic UI tools"
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) OpenAI
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,51 +0,0 @@
|
||||
---
|
||||
name: ios-simulator-browser
|
||||
description: Stream an explicit iOS Simulator through pinned serve-sim into the T3 Code in-app browser or another agent browser. Use on Apple Silicon macOS when the user should watch simulator verification live or when browser-visible simulator evidence is needed.
|
||||
---
|
||||
|
||||
# iOS Simulator Browser
|
||||
|
||||
Use serve-sim as the shared visual feed for an iOS Simulator. Use `ios-debugger-agent` and XcodeBuildMCP semantic UI tools to drive the app; do not treat browser-canvas coordinates as a substitute for missing app accessibility.
|
||||
|
||||
## Confirm availability
|
||||
|
||||
serve-sim `0.1.45` requires Apple Silicon macOS, Xcode command-line tools, and Node.js 20 or newer. If the host is unsupported, continue with XcodeBuildMCP screenshots and report that live streaming was unavailable.
|
||||
|
||||
When running inside T3 Code, use its product-native browser MCP to open the stream. Other agent hosts may use their own browser or preview surface.
|
||||
|
||||
Keep serve-sim on its default `127.0.0.1` binding. Do not expose its preview to a LAN or tunnel unless the user explicitly requests that access and the network is trusted; the preview includes a token-gated shell-execution route.
|
||||
|
||||
## Start one owned stream
|
||||
|
||||
1. Obtain the exact simulator UDID from the iOS build or launch workflow.
|
||||
2. Check whether an existing serve-sim stream for that UDID belongs to another task. Reuse it only when explicitly shared; never kill another task's stream.
|
||||
3. Otherwise, clear only a stale stream for that UDID and start the pinned version with scoped cleanup:
|
||||
|
||||
```bash
|
||||
SIMULATOR_ID=<simulator-udid>
|
||||
cleanup_serve_sim() {
|
||||
npx --yes [email protected] --kill "$SIMULATOR_ID" >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup_serve_sim EXIT INT TERM HUP
|
||||
cleanup_serve_sim
|
||||
npx --yes [email protected] "$SIMULATOR_ID"
|
||||
```
|
||||
|
||||
4. Keep the terminal alive and open the exact local URL printed by serve-sim in the agent's browser.
|
||||
5. Verify that a live simulator frame renders. A loaded wrapper page is not sufficient evidence.
|
||||
|
||||
## Observe while driving semantically
|
||||
|
||||
- Let the user watch the serve-sim stream while XcodeBuildMCP performs `snapshot_ui`, semantic taps, typing, gestures, and screenshots.
|
||||
- Keep the browser and Xcode tooling pinned to the same simulator UDID.
|
||||
- Do not switch to generic desktop automation or browser-canvas clicking merely because the stream is visible.
|
||||
|
||||
If the in-app browser explicitly reports that previews are unavailable, do not install unrelated browser automation. Continue through XcodeBuildMCP, capture a simulator screenshot, report the unavailable live stream, and clean up the owned serve-sim process.
|
||||
|
||||
## Finish
|
||||
|
||||
Stop the long-running terminal and wait for its cleanup trap to finish. If it disappeared without cleanup, run `npx --yes serve-sim@0.1.45 --kill <simulator-udid>` for that exact simulator. Never run an unscoped `--kill`.
|
||||
|
||||
## Upstream
|
||||
|
||||
Adapted from OpenAI's [`build-ios-apps`](https://github.com/openai/plugins/tree/main/plugins/build-ios-apps) plugin version `0.1.2` (`ios-simulator-browser`, MIT). It invokes serve-sim `0.1.45` under its Apache-2.0 license without vendoring the package.
|
||||
@@ -1,4 +0,0 @@
|
||||
interface:
|
||||
display_name: "iOS Simulator Browser"
|
||||
short_description: "Stream iOS Simulator in the browser"
|
||||
default_prompt: "Use $ios-simulator-browser to stream the selected iOS Simulator into the T3 Code in-app browser."
|
||||
@@ -1,71 +0,0 @@
|
||||
---
|
||||
name: test-t3-app
|
||||
description: Launch and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
---
|
||||
|
||||
# Test T3 App
|
||||
|
||||
Use this skill for the web client. For iOS Simulator, Android Emulator, or physical-device testing against an isolated T3 backend, use the sibling [`test-t3-mobile`](../test-t3-mobile/SKILL.md) skill.
|
||||
|
||||
## Start an isolated web environment
|
||||
|
||||
1. Run commands from the repository root.
|
||||
2. Choose a base directory that belongs only to the current worktree or test:
|
||||
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
|
||||
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
|
||||
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
|
||||
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
|
||||
|
||||
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
|
||||
|
||||
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
|
||||
|
||||
## Authenticate the browser on the first navigation
|
||||
|
||||
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
|
||||
2. Use the controlled in-app browser or browser-automation surface available to the agent. Do not use a system-browser launch command during automated testing.
|
||||
3. Open that complete URL exactly once as the controlled browser's first navigation. Preserve the fragment and token verbatim.
|
||||
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
|
||||
5. Continue in the same browser context so its stored bearer session remains available.
|
||||
|
||||
Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
|
||||
|
||||
## Recover a consumed or expired pairing token
|
||||
|
||||
Create another token against the same database and web URL as the running dev server:
|
||||
|
||||
```bash
|
||||
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir <base-dir> \
|
||||
--dev-url <web-url> \
|
||||
--base-url <web-url> \
|
||||
--ttl 15m \
|
||||
--label agent-ui-test
|
||||
```
|
||||
|
||||
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
|
||||
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before changing the database.
|
||||
|
||||
- Use `node apps/server/scripts/t3-sqlite-state.ts query` for schema discovery and read-only checks.
|
||||
- Stop the dev server before using `node apps/server/scripts/t3-sqlite-state.ts exec`, then restart it with the same base directory.
|
||||
- Seed projection tables only for disposable UI fixtures. Use application commands and APIs when testing business behavior or projection correctness.
|
||||
- Use the auth CLI, not direct `auth_*` table edits, for pairing and sessions.
|
||||
|
||||
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
|
||||
|
||||
## Finish the test
|
||||
|
||||
Stop the dev process with its terminal interrupt. Preserve the isolated base directory when it contains useful reproduction evidence; otherwise remove only a path that was created for this test after resolving and verifying the exact target. A fresh isolated base directory is the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
|
||||
## Troubleshoot predictably
|
||||
|
||||
- If the browser shows an unauthenticated pairing screen, issue a new token instead of retrying the consumed URL.
|
||||
- If the pairing URL is no longer visible, create a replacement token with both `--dev-url` and `--base-url`.
|
||||
- If the replacement token is rejected, verify that the CLI and server use the identical absolute base directory and web URL.
|
||||
- If the UI shows unexpected data, verify that every command uses the identical explicit base directory before editing anything.
|
||||
- If ports move because another instance is running, trust the current dev-runner output rather than assuming ports `13773` and `5733`.
|
||||
@@ -1,4 +0,0 @@
|
||||
interface:
|
||||
display_name: "T3 App Testing"
|
||||
short_description: "Launch and seed isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
|
||||
@@ -1,58 +0,0 @@
|
||||
# SQLite fixtures
|
||||
|
||||
Load this reference only when inspecting or seeding local T3 state directly.
|
||||
|
||||
## Select the correct database
|
||||
|
||||
When `--base-dir` or `--home-dir` is explicit, runtime state lives under `<base-dir>/userdata` and the database path is `<base-dir>/userdata/state.sqlite`. The `<base-dir>/dev` state directory is only the fallback for an implicit development home, preventing an ordinary `vp run dev` from touching production state.
|
||||
|
||||
Start the target runtime once before seeding so all migrations have run. Use an isolated base directory. Stop the server before writes to avoid racing application state or an active projection.
|
||||
|
||||
## Use the helper
|
||||
|
||||
List tables:
|
||||
|
||||
```bash
|
||||
node apps/server/scripts/t3-sqlite-state.ts query \
|
||||
--base-dir <base-dir> \
|
||||
--sql "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
|
||||
```
|
||||
|
||||
Inspect current columns before writing a fixture:
|
||||
|
||||
```bash
|
||||
node apps/server/scripts/t3-sqlite-state.ts query \
|
||||
--base-dir <base-dir> \
|
||||
--sql "PRAGMA table_info(projection_threads)"
|
||||
```
|
||||
|
||||
Apply a SQL fixture from a file:
|
||||
|
||||
```bash
|
||||
node apps/server/scripts/t3-sqlite-state.ts exec \
|
||||
--base-dir <base-dir> \
|
||||
--file /tmp/t3-seed.sql
|
||||
```
|
||||
|
||||
Use one statement per invocation for both `query` and `exec`; the helper wraps writes in a transaction and prints the backup path after a successful mutation. Use a single insert with multiple value rows when a fixture needs several records.
|
||||
|
||||
## Seed projection data carefully
|
||||
|
||||
The web UI primarily reads these projection tables:
|
||||
|
||||
- `projection_projects`
|
||||
- `projection_threads`
|
||||
- `projection_thread_messages`
|
||||
- `projection_thread_activities`
|
||||
- `projection_thread_sessions`
|
||||
- `projection_turns`
|
||||
- `projection_pending_approvals`
|
||||
- `projection_thread_proposed_plans`
|
||||
|
||||
Inspect `PRAGMA table_info(<table>)` and the current migrations under `apps/server/src/persistence/Migrations/` before constructing inserts. Keep identifiers unique, timestamps as ISO strings, JSON columns valid, and related project/thread/turn IDs consistent.
|
||||
|
||||
For a substantial current example, inspect `seedDatabase` in `scripts/mobile-showcase-environment.ts`. Adapt its column set to the target database instead of assuming copied SQL remains current.
|
||||
|
||||
Direct projection writes are appropriate for ephemeral visual states, edge-case counts, long titles, activity lists, and similar UI fixtures. They do not create a coherent orchestration event history. Do not modify `orchestration_events` unless the test specifically exercises projector internals, and do not use direct projection writes to claim backend business behavior works.
|
||||
|
||||
Use the app's commands or APIs for behavior tests. Use `node apps/server/src/bin.ts auth ...` for auth state rather than editing `auth_pairing_links` or `auth_sessions`.
|
||||
@@ -1,188 +0,0 @@
|
||||
---
|
||||
name: test-t3-mobile
|
||||
description: Launch and test T3 Code Mobile on an iOS Simulator or Android Emulator against disposable local T3 environments, including Metro and dev-client reuse, native rebuild decisions, per-client pairing, seeded projects, semantic UI control, screenshots, and iOS serve-sim streaming. Use after mobile UI or native changes, when reproducing phone or tablet behavior, pairing an emulator to isolated state, or verifying mobile behavior on macOS, Linux, or Windows.
|
||||
---
|
||||
|
||||
# Test T3 Mobile
|
||||
|
||||
Run one focused, end-to-end mobile verification pass against disposable T3 state. Use the sibling [`test-t3-app`](../test-t3-app/SKILL.md) skill as the detailed reference for pairing-token semantics and SQLite fixtures.
|
||||
|
||||
Command examples use POSIX shell syntax. On Windows, use PowerShell equivalents: set variables with `$env:NAME = "value"`, use an explicit temporary directory from `[System.IO.Path]::GetTempPath()`, and run multiline examples on one line or with PowerShell backticks. Use `$env:ANDROID_HOME\platform-tools\adb.exe` when `adb` is not already on `PATH`.
|
||||
|
||||
## Select a viable platform
|
||||
|
||||
Inspect the host and the affected code before launching processes:
|
||||
|
||||
- On macOS with Xcode, prefer one representative iOS Simulator when the change is cross-platform so the user can watch through serve-sim. Load and follow [`ios-debugger-agent`](../ios-debugger-agent/SKILL.md), and load [`ios-simulator-browser`](../ios-simulator-browser/SKILL.md) when live streaming is available.
|
||||
- On macOS, Linux, or Windows with the Android SDK, use one Android Emulator when Android is the affected surface or iOS tooling is unavailable.
|
||||
- When the change is platform-specific, test that platform. When neither platform is viable, report the missing SDK, emulator, or dev-client prerequisite rather than claiming verification.
|
||||
|
||||
Do not treat unavailable iOS tooling as a blocker when Android is a valid representative target.
|
||||
|
||||
## Choose the lightest valid launch path
|
||||
|
||||
- For JavaScript, TypeScript, or asset-only changes, reuse a compatible installed development client and start Metro. Do not rebuild native code merely to load a new bundle.
|
||||
- For native source, native dependencies, entitlements, config plugins, or generated project changes, rebuild the affected platform.
|
||||
- Use `vp run ios:dev` or `vp run android:dev` only when an Expo clean prebuild is actually required; both commands regenerate the native project.
|
||||
- If the user requested no native rebuild and no compatible app is installed, reuse an existing compatible `.app` or `.apk` artifact when available. Otherwise report the missing dev client instead of silently rebuilding.
|
||||
|
||||
The development identity on both platforms is:
|
||||
|
||||
- App: `T3 Code Dev`
|
||||
- Bundle/package identifier: `com.t3tools.t3code.dev`
|
||||
- URL scheme: `t3code-dev`
|
||||
|
||||
Bundle or package presence proves the correct variant, not native compatibility. Reuse it only when the current changes did not alter its Expo SDK, native dependencies, config plugins, entitlements, generated project, or native source.
|
||||
|
||||
## Start one disposable T3 environment
|
||||
|
||||
Run backend commands from the repository root. Use the ignored, worktree-local `.t3` directory or create a fresh directory with the host OS's temporary-directory mechanism. An explicit base directory stores state in `<base-dir>/userdata`; never point testing at shared `~/.t3` state.
|
||||
|
||||
Seed a small number of meaningful Git projects before starting the backend:
|
||||
|
||||
```bash
|
||||
node apps/server/src/bin.ts project add <git-workspace> \
|
||||
--base-dir <base-dir> \
|
||||
--title <project-title>
|
||||
```
|
||||
|
||||
Running `project add` before the backend starts gives it exclusive offline database access. If a backend is already running, wait until it is ready so the CLI dispatches through the live server; never run offline mutations concurrently with the server.
|
||||
|
||||
Use direct SQLite mutation only for disposable projection fixtures. Follow `test-t3-app` and stop the backend before writing.
|
||||
|
||||
Start a headless backend after seeding:
|
||||
|
||||
```bash
|
||||
node apps/server/src/bin.ts serve \
|
||||
--host 127.0.0.1 \
|
||||
--port <server-port> \
|
||||
--base-dir <base-dir> \
|
||||
--no-browser
|
||||
```
|
||||
|
||||
Use these client origins:
|
||||
|
||||
- iOS Simulator: `http://127.0.0.1:<server-port>`
|
||||
- Android Emulator: `http://10.0.2.2:<server-port>`
|
||||
- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
|
||||
|
||||
Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
|
||||
|
||||
## Start or reuse Metro safely
|
||||
|
||||
Run Metro from `apps/mobile`.
|
||||
|
||||
1. Inspect any process on the intended Metro port and its `/status` response. Reuse it only when it is healthy, belongs to this worktree, and matches `APP_VARIANT=development`, `--dev-client`, and scheme `t3code-dev`.
|
||||
2. Never kill another worktree's Metro. Use a free explicit port when necessary.
|
||||
3. Run `vp run dev:client` on the standard port. For another port, retain the complete development identity:
|
||||
|
||||
```bash
|
||||
APP_VARIANT=development vp exec expo start \
|
||||
--dev-client \
|
||||
--scheme t3code-dev \
|
||||
--clear \
|
||||
--lan \
|
||||
--port <metro-port>
|
||||
```
|
||||
|
||||
In PowerShell, set `$env:APP_VARIANT = "development"` first and then run the `vp exec expo start ...` command without the leading assignment.
|
||||
|
||||
4. Open the exact development-client URL for the selected device and confirm the loaded bundle belongs to this worktree and Metro port.
|
||||
|
||||
### iOS launch
|
||||
|
||||
Use `ios-debugger-agent` to select one UDID and set these XcodeBuildMCP session defaults:
|
||||
|
||||
- Workspace: `<repo>/apps/mobile/ios/T3CodeDev.xcworkspace`
|
||||
- Scheme: `T3CodeDev`
|
||||
- Configuration: `Debug`
|
||||
- Simulator ID: the selected UDID
|
||||
- Bundle ID: `com.t3tools.t3code.dev`
|
||||
|
||||
Check the installed client with:
|
||||
|
||||
```bash
|
||||
xcrun simctl get_app_container <simulator-udid> com.t3tools.t3code.dev app
|
||||
xcrun simctl openurl <simulator-udid> <printed-dev-client-url>
|
||||
```
|
||||
|
||||
Accept the iOS confirmation prompt and dismiss the developer menu when it obscures the app.
|
||||
|
||||
### Android launch
|
||||
|
||||
Select one running emulator serial from `adb devices` and check the installed client:
|
||||
|
||||
```bash
|
||||
adb -s <emulator-serial> shell pm path com.t3tools.t3code.dev
|
||||
adb -s <emulator-serial> reverse tcp:<metro-port> tcp:<metro-port>
|
||||
adb -s <emulator-serial> shell am start -W \
|
||||
-a android.intent.action.VIEW \
|
||||
-d '<printed-dev-client-url>' \
|
||||
com.t3tools.t3code.dev
|
||||
```
|
||||
|
||||
Do not start, stop, erase, or reconfigure an emulator owned by another task. Track and later stop only processes owned by this test.
|
||||
|
||||
## Pair each client once
|
||||
|
||||
Issue a fresh credential against the running backend's exact base directory:
|
||||
|
||||
```bash
|
||||
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir <base-dir> \
|
||||
--base-url <mobile-origin> \
|
||||
--ttl 15m \
|
||||
--label agent-mobile-<short-device-id>
|
||||
```
|
||||
|
||||
In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.
|
||||
|
||||
If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:
|
||||
|
||||
```bash
|
||||
xcrun simctl openurl <simulator-udid> 't3code-dev://connections/new'
|
||||
adb -s <emulator-serial> shell am start -W \
|
||||
-a android.intent.action.VIEW \
|
||||
-d 't3code-dev://connections/new' \
|
||||
com.t3tools.t3code.dev
|
||||
```
|
||||
|
||||
Run only the command for the selected platform.
|
||||
|
||||
In T3 Code Dev, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.
|
||||
|
||||
Pairing credentials are secret, short-lived, and single-use. Create a different credential for every simulator, emulator, physical device, or browser. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.
|
||||
|
||||
## Drive and observe the affected flow
|
||||
|
||||
### iOS
|
||||
|
||||
Use `snapshot_ui` and current element references from XcodeBuildMCP for taps and typing. Stream the same UDID through `ios-simulator-browser` so the user can watch in T3 Code when the host supports it. Use the stream as a visual feed rather than a reason to switch to fragile browser coordinates.
|
||||
|
||||
### Android
|
||||
|
||||
Prefer semantic Android automation exposed by the current agent host. Otherwise inspect the current hierarchy with `adb shell uiautomator dump`, target stable resource IDs, content descriptions, text, or bounds, and use scoped `adb shell input` actions. Refresh the hierarchy after navigation. Capture the final state with `adb exec-out screencap -p`.
|
||||
|
||||
Android does not use serve-sim. Use a browser-compatible Android mirror when the host already provides one; otherwise return focused emulator screenshots as evidence rather than installing unrelated streaming infrastructure during verification.
|
||||
|
||||
## Verify and clean up
|
||||
|
||||
Exercise only the affected flow on one representative device unless the change specifically concerns platform, OS version, or screen size. Before finishing:
|
||||
|
||||
1. Confirm the app connected to the intended disposable environment instead of merely rendering an empty disconnected state.
|
||||
2. Capture the relevant final state.
|
||||
3. Remove the disposable environment from T3 Code Dev.
|
||||
4. Remove any `adb reverse` rule created for this test with `adb -s <emulator-serial> reverse --remove tcp:<metro-port>`.
|
||||
5. Stop only the serve-sim, Metro, backend, emulator, and log processes started by this test.
|
||||
6. Remove only base directories and temporary Git repositories deliberately created for this test. Preserve them when they contain useful reproduction evidence.
|
||||
|
||||
Keep local verification focused. Do not turn this workflow into a full repository test run.
|
||||
|
||||
## Troubleshoot predictable failures
|
||||
|
||||
- **Old UI or an old error appears:** verify Metro's worktree, variant, URL, and port before diagnosing the app.
|
||||
- **The environment remains empty:** verify the platform-specific HTTP origin, use a fresh token, and confirm project seeding used the identical base directory.
|
||||
- **A second client cannot pair:** pairing tokens are single-use; issue another token.
|
||||
- **iOS semantic actions fail:** set explicit XcodeBuildMCP defaults and refresh with `snapshot_ui`.
|
||||
- **Android cannot reach Metro:** verify `adb reverse` for the exact Metro port and relaunch the development-client URL.
|
||||
- **Android cannot reach the backend:** use `10.0.2.2`, not `127.0.0.1`, for the Android Emulator.
|
||||
@@ -1,4 +0,0 @@
|
||||
interface:
|
||||
display_name: "Test T3 Mobile"
|
||||
short_description: "Test T3 Code on iOS or Android"
|
||||
default_prompt: "Use $test-t3-mobile to launch T3 Code against an isolated backend and verify the affected flow on an available simulator or emulator."
|
||||
@@ -1 +0,0 @@
|
||||
../.agents/skills
|
||||
@@ -1,9 +0,0 @@
|
||||
[mcp_servers.xcodebuildmcp]
|
||||
enabled = true
|
||||
required = false
|
||||
command = "npx"
|
||||
args = ["--yes", "[email protected]", "mcp"]
|
||||
startup_timeout_sec = 20.0
|
||||
|
||||
[mcp_servers.xcodebuildmcp.env]
|
||||
XCODEBUILDMCP_ENABLED_WORKFLOWS = "simulator,ui-automation,debugging,logging"
|
||||
@@ -18,10 +18,6 @@
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
|
||||
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
|
||||
# Defaults to https://app.t3.codes; override to test against a staging deployment.
|
||||
# T3CODE_HOSTED_APP_URL=https://nightly.app.t3.codes
|
||||
|
||||
# Public, ingest-only mobile OpenTelemetry configuration.
|
||||
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
|
||||
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
|
||||
|
||||
@@ -788,7 +788,6 @@ jobs:
|
||||
env:
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
|
||||
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
|
||||
@@ -872,7 +871,6 @@ jobs:
|
||||
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
|
||||
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
|
||||
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
|
||||
--build-env "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=${T3CODE_CLERK_CLI_OAUTH_CLIENT_ID:-}" \
|
||||
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"xcodebuildmcp": {
|
||||
"command": "npx",
|
||||
"args": ["--yes", "[email protected]", "mcp"],
|
||||
"env": {
|
||||
"XCODEBUILDMCP_ENABLED_WORKFLOWS": "simulator,ui-automation,debugging,logging"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,257 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Plan: seamless `npx t3 connect` for remote boxes</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #000;
|
||||
--fg: #fff;
|
||||
--muted: #a3a3a3;
|
||||
--surface: #121212;
|
||||
--surface2: #1a1a1a;
|
||||
--border: #2a2a2a;
|
||||
--accent: #7c9cff;
|
||||
--green: #4ade80;
|
||||
--amber: #fbbf24;
|
||||
--red: #f87171;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
}
|
||||
main { max-width: 880px; margin: 0 auto; padding: 48px 24px 96px; }
|
||||
h1 { font-size: 30px; line-height: 1.25; margin: 0 0 8px; }
|
||||
h2 { font-size: 21px; margin: 48px 0 12px; padding-top: 24px; border-top: 1px solid var(--border); }
|
||||
h3 { font-size: 16px; margin: 24px 0 8px; }
|
||||
p, li { color: #e5e5e5; }
|
||||
.sub { color: var(--muted); margin: 0 0 24px; }
|
||||
code, pre {
|
||||
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
code { background: var(--surface2); border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px; }
|
||||
pre {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
overflow-x: auto;
|
||||
line-height: 1.5;
|
||||
}
|
||||
pre code { background: none; border: none; padding: 0; }
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 18px 20px;
|
||||
margin: 16px 0;
|
||||
}
|
||||
.card h3 { margin-top: 0; }
|
||||
table { border-collapse: collapse; width: 100%; margin: 16px 0; font-size: 14.5px; }
|
||||
th, td { text-align: left; padding: 8px 12px; border: 1px solid var(--border); vertical-align: top; }
|
||||
th { background: var(--surface2); font-weight: 600; }
|
||||
td code { white-space: nowrap; }
|
||||
.pill {
|
||||
display: inline-block; font-size: 12px; font-weight: 600; border-radius: 999px;
|
||||
padding: 2px 10px; margin-right: 6px; vertical-align: 2px;
|
||||
}
|
||||
.pill.core { background: #1e2a4a; color: var(--accent); }
|
||||
.pill.new { background: #14301e; color: var(--green); }
|
||||
.pill.later { background: #33270e; color: var(--amber); }
|
||||
.ok { color: var(--green); }
|
||||
.warn { color: var(--amber); }
|
||||
.no { color: var(--red); }
|
||||
ul { padding-left: 22px; }
|
||||
li { margin: 4px 0; }
|
||||
.terminal {
|
||||
background: #0a0a0a; border: 1px solid var(--border); border-radius: 8px;
|
||||
padding: 16px; font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
||||
font-size: 13.5px; line-height: 1.65; color: #d4d4d4; overflow-x: auto;
|
||||
}
|
||||
.terminal .dim { color: #737373; }
|
||||
.terminal .g { color: var(--green); }
|
||||
.terminal .b { color: var(--accent); }
|
||||
figure { margin: 24px 0; }
|
||||
figcaption { color: var(--muted); font-size: 13px; margin-top: 8px; text-align: center; }
|
||||
svg text { font-family: -apple-system, "Segoe UI", sans-serif; }
|
||||
a { color: var(--accent); }
|
||||
.kv { color: var(--muted); font-size: 13.5px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
|
||||
<h1>Seamless <code>npx t3 connect</code> for remote boxes</h1>
|
||||
<p class="sub">Design principle: <strong>the smallest diff that ships the UX.</strong> No relay/infra changes, no new backend surface, no new auth primitives — every step reuses code that already exists. One PR, built as four phases with clear commit boundaries — each phase compiles, passes tests, and leaves the product working, so the PR reviews commit-by-commit. (Phase 4, web-triggered update, is an optional follow-up PR.)</p>
|
||||
|
||||
<div class="terminal">
|
||||
$ npx t3 connect<br><br>
|
||||
To set up T3 Connect, open this URL and sign in:<br>
|
||||
<span class="b">https://app.t3.codes/connect#B64URL_STATE_AND_CHALLENGE</span><br><br>
|
||||
Enter your authentication code: <span class="dim">[code]</span><br><br>
|
||||
<span class="g">Connected as [email protected]!</span><br><br>
|
||||
Run T3 Code in the background whenever this machine boots? (y/n): y<br><br>
|
||||
<span class="g">T3 Code is set up and ready to go.</span>
|
||||
</div>
|
||||
|
||||
<h2>Why this is a small change</h2>
|
||||
<p>The entire <code>t3 connect</code> data plane already works: Clerk PKCE token exchange, encrypted secret store, cloudflared relay-client install, relay environment linking, DPoP tokens. The <em>only</em> broken piece on an SSH box is the redirect: <code>CliTokenManager.login()</code> hardcodes a loopback callback (<code>http://127.0.0.1:34338/callback</code>) that requires a browser on the same machine.</p>
|
||||
<p>We swap that one leg for a hosted out-of-band authorization page and keep everything else. Because PKCE's <code>code_verifier</code> never leaves the box, the displayed one-time code is useless to anyone who sees it — no new token-minting or storage is needed anywhere.</p>
|
||||
|
||||
<div class="card">
|
||||
<h3>Reused as-is (zero changes)</h3>
|
||||
<ul>
|
||||
<li><code>exchangeToken()</code> PKCE exchange — <code>apps/server/src/cloud/CliTokenManager.ts:147</code></li>
|
||||
<li>Token persistence in <code>ServerSecretStore</code> (<code>cloud-cli-oauth-token</code>)</li>
|
||||
<li><code>acquireRelayClientForLink()</code> cloudflared install + progress — <code>cli/connect.ts:146</code></li>
|
||||
<li><code>CliState.setCliDesiredCloudLink()</code> + server-side provisioning on start</li>
|
||||
<li>All relay endpoints (<code>infra/relay</code>) and contracts — <strong>untouched</strong></li>
|
||||
<li>Existing subcommands <code>login/link/status/unlink/logout</code> — semantics unchanged</li>
|
||||
<li>Web app Clerk session + hosted-page precedent (<code>routes/pair.tsx</code>, <code>hostedPairing.ts</code>)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>Auth flow (hosted out-of-band OAuth, Clerk PKCE)</h2>
|
||||
|
||||
<figure>
|
||||
<svg viewBox="0 0 820 470" width="100%" role="img" aria-label="Sequence diagram of the out-of-band OAuth flow">
|
||||
<!-- lanes -->
|
||||
<rect x="20" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
|
||||
<rect x="300" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
|
||||
<rect x="580" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
|
||||
<text x="130" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Remote box — t3 CLI</text>
|
||||
<text x="410" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Laptop — app.t3.codes</text>
|
||||
<text x="690" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Clerk</text>
|
||||
<line x1="130" y1="60" x2="130" y2="450" stroke="#2a2a2a"/>
|
||||
<line x1="410" y1="60" x2="410" y2="450" stroke="#2a2a2a"/>
|
||||
<line x1="690" y1="60" x2="690" y2="450" stroke="#2a2a2a"/>
|
||||
|
||||
<!-- 1: generate + print -->
|
||||
<rect x="30" y="80" width="200" height="34" rx="6" fill="#1e2a4a"/>
|
||||
<text x="130" y="101" fill="#7c9cff" font-size="12.5" text-anchor="middle">1. gen verifier + challenge + state</text>
|
||||
|
||||
<!-- 2: user opens URL -->
|
||||
<line x1="130" y1="140" x2="404" y2="140" stroke="#7c9cff" stroke-dasharray="5 4"/>
|
||||
<polygon points="404,140 394,135 394,145" fill="#7c9cff"/>
|
||||
<text x="267" y="132" fill="#a3a3a3" font-size="12.5" text-anchor="middle">2. user opens /connect#{state,challenge}</text>
|
||||
|
||||
<!-- 3: redirect to clerk -->
|
||||
<line x1="410" y1="185" x2="684" y2="185" stroke="#e5e5e5"/>
|
||||
<polygon points="684,185 674,180 674,190" fill="#e5e5e5"/>
|
||||
<text x="547" y="177" fill="#a3a3a3" font-size="12.5" text-anchor="middle">3. sign in → /oauth/authorize (PKCE)</text>
|
||||
|
||||
<!-- 4: redirect back with code -->
|
||||
<line x1="690" y1="230" x2="416" y2="230" stroke="#e5e5e5"/>
|
||||
<polygon points="416,230 426,225 426,235" fill="#e5e5e5"/>
|
||||
<text x="553" y="222" fill="#a3a3a3" font-size="12.5" text-anchor="middle">4. redirect /connect/callback?code&state</text>
|
||||
|
||||
<!-- 5: page shows code -->
|
||||
<rect x="310" y="252" width="200" height="34" rx="6" fill="#14301e"/>
|
||||
<text x="410" y="273" fill="#4ade80" font-size="12.5" text-anchor="middle">5. shows account + authorization code</text>
|
||||
|
||||
<!-- 6: user enters code -->
|
||||
<line x1="410" y1="316" x2="136" y2="316" stroke="#7c9cff" stroke-dasharray="5 4"/>
|
||||
<polygon points="136,316 146,311 146,321" fill="#7c9cff"/>
|
||||
<text x="273" y="308" fill="#a3a3a3" font-size="12.5" text-anchor="middle">6. user enters code in terminal</text>
|
||||
|
||||
<!-- 7: token exchange -->
|
||||
<line x1="130" y1="360" x2="684" y2="360" stroke="#e5e5e5"/>
|
||||
<polygon points="684,360 674,355 674,365" fill="#e5e5e5"/>
|
||||
<text x="407" y="352" fill="#a3a3a3" font-size="12.5" text-anchor="middle">7. POST /oauth/token {code + verifier} → access/refresh tokens</text>
|
||||
|
||||
<!-- 8: done -->
|
||||
<rect x="30" y="392" width="200" height="46" rx="6" fill="#14301e"/>
|
||||
<text x="130" y="411" fill="#4ade80" font-size="12.5" text-anchor="middle">8. store token, set desired link,</text>
|
||||
<text x="130" y="427" fill="#4ade80" font-size="12.5" text-anchor="middle">install relay client → Connected!</text>
|
||||
</svg>
|
||||
<figcaption>The verifier never leaves the box (steps 1→7), so the authorization code is worthless if observed. state/challenge ride the URL fragment — they are not secrets.</figcaption>
|
||||
</figure>
|
||||
|
||||
<div class="card">
|
||||
<h3>Details that keep it simple</h3>
|
||||
<ul>
|
||||
<li><strong>Stateless URL, no short-link service.</strong> The <code>/connect</code> page reads <code>state</code> + <code>code_challenge</code> from the URL fragment and builds the Clerk authorize URL client-side. ~100-char URL — fine to transfer into an SSH session.</li>
|
||||
<li><strong>State check without a backend:</strong> the callback page displays one authorization blob of <code>code.state</code>; the CLI splits it and verifies <code>state</code> matches what it generated. One line on each side, preserves the loopback flow's CSRF check.</li>
|
||||
<li><strong>Phishing is addressed with copy, not code:</strong> the callback page shows <em>which account</em> is being connected ("Connecting as theo@…") and warns: <em>"Only enter this code in a terminal session you started yourself."</em> No mechanism needed.</li>
|
||||
<li><strong>Code expiry is a non-issue:</strong> Clerk auth codes live 10 minutes — the same timeout the existing loopback flow already uses. Wrong/expired code → friendly retry that reprints the URL.</li>
|
||||
<li><strong>One external config step:</strong> register <code>https://app.t3.codes/connect/callback</code> as an allowed redirect URI on the existing Clerk CLI OAuth client. No new client, no new scopes.</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>The phases (one PR, one commit each)</h2>
|
||||
<p class="kv">Ordering is dependency order: each phase is independently revertable and the tree is green at every boundary. Phases 1–3 are the PR; phase 4 ships separately later.</p>
|
||||
|
||||
<table>
|
||||
<tr><th style="width:1%">Phase</th><th>Scope</th><th>Files</th><th style="width:1%">~LOC</th></tr>
|
||||
<tr>
|
||||
<td><span class="pill core">1</span></td>
|
||||
<td><strong>Hosted code page</strong> (web-only, purely additive, zero risk). Two static routes modeled on <code>pair.tsx</code>: <code>/connect</code> (ensure Clerk session, then client-side redirect to authorize — it's a static SPA, no server 302) and <code>/connect/callback</code> (validate params, show account + copyable code + safety warning). Both routes guard against non-hosted deployments — redirect to <code>/</code> unless <code>isHostedStaticApp()</code>, same pattern as <code>pair.tsx</code>, since this bundle also ships in local instances. Plus the Clerk dashboard redirect-URI entry.</td>
|
||||
<td><code>apps/web/src/routes/connect.tsx</code><br><code>apps/web/src/routes/connect.callback.tsx</code></td>
|
||||
<td>~200</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="pill core">2</span></td>
|
||||
<td><strong>CLI out-of-band OAuth flow + single command.</strong> Add an out-of-band OAuth login path to <code>CliTokenManager</code> (print URL, <code>Prompt.text</code> for the code, reuse <code>exchangeToken</code>). Make bare <code>t3 connect</code> a handler = login + link (subcommands untouched). Auto-pick headless mode inside SSH sessions (<code>SSH_CONNECTION</code>/<code>SSH_TTY</code> — nothing else); <code>--headless</code> flag as manual override. Loopback stays the default on desktop — no regression.</td>
|
||||
<td><code>cloud/CliTokenManager.ts</code> (+60)<br><code>cloud/publicConfig.ts</code> (+10)<br><code>cli/connect.ts</code> (+60)</td>
|
||||
<td>~150</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="pill new">3</span></td>
|
||||
<td><strong>Background on boot — Linux first</strong> (the SSH case). One new module: pinned runtime install to <code>~/.t3/runtime/versions/<v></code> + <code>current</code> symlink, systemd <em>user</em> unit with absolute node/t3 paths, <code>enable-linger</code>. y/n prompt at the end of <code>connect</code>; teardown in <code>logout</code>. Install and service-start failures must land in a log file (under <code>~/.t3/userdata/logs/</code>) whose path is printed at connect time — systemd user units fail invisibly otherwise. Unit-file generation is pure string-building → trivially testable. macOS launchd / Windows follow as 3b/3c only if wanted.</td>
|
||||
<td><code>cloud/bootService.ts</code> (new)<br><code>cli/connect.ts</code> (+prompt/teardown)</td>
|
||||
<td>~250</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="pill later">4</span></td>
|
||||
<td><strong>Web-triggered update</strong> (optional follow-up PR; not part of this one, not needed for the core UX). Web detects <code>daemon version < latest-on-channel</code> using the existing version-skew surface + hosted manifest; one authenticated "update" command — client says <em>update</em>, daemon resolves/verifies the version itself (never client-specified — that would be RCE). Stage install → verify → atomic symlink swap → <code>systemctl --user restart</code>. Progress streams reuse the <code>RelayClientInstallProgressEvent</code> pattern.</td>
|
||||
<td>web banner + one control command + daemon update routine</td>
|
||||
<td>later</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Runtime layout (phase 3)</h3>
|
||||
<pre><code>~/.t3/runtime/
|
||||
├── versions/0.0.27/ ← npm install --prefix (gets native deps right: node-pty etc.)
|
||||
└── current -> versions/0.0.27
|
||||
|
||||
~/.config/systemd/user/t3code.service ← ExecStart=/abs/path/node .../current/.../t3 serve
|
||||
loginctl enable-linger $USER ← survives SSH logout / reboot</code></pre>
|
||||
<p class="kv">Why a real <code>npm install</code> and not "reuse the npx binary": the npx cache is ephemeral and <code>t3</code> ships native deps (<code>node-pty</code>, <code>@ff-labs/fff-node</code>) that need per-platform prebuilds. Why pinned and not <code>npx t3@latest</code> in the unit: a boot-time registry fetch means the box may simply not come up (network down, PATH-less systemd env, nvm). Deterministic boot; updates happen out-of-band (phase 4 follow-up) or by re-running <code>npx t3 connect</code>.</p>
|
||||
|
||||
<h2>Explicitly not doing</h2>
|
||||
<ul>
|
||||
<li><span class="no">✗</span> Relay / <code>infra</code> / contracts changes — none, in any phase</li>
|
||||
<li><span class="no">✗</span> Short-link service (<code>app.t3.codes/c/AB7K</code>) — only matters for hand-typing; revisit if ever needed</li>
|
||||
<li><span class="no">✗</span> RFC 8628 device grant — wrong UX direction, unverified Clerk support</li>
|
||||
<li><span class="no">✗</span> Auto-update loop in the daemon — web-triggered only (phase 4 follow-up), user stays in control</li>
|
||||
<li><span class="no">✗</span> Project auto-registration — workspace assumed set up; the web UI handles the rest</li>
|
||||
<li><span class="no">✗</span> Changing existing loopback flow, subcommands, or desktop behavior</li>
|
||||
</ul>
|
||||
|
||||
<h2>Risks & checks</h2>
|
||||
<ul>
|
||||
<li><span class="warn">⚠</span> <strong>Clerk redirect URI:</strong> confirm the CLI OAuth client accepts the hosted redirect and that the token endpoint honors PKCE exchange for codes issued to it. Verify in staging before the phase 2 commit. <em>(Only external dependency in the plan.)</em></li>
|
||||
<li><span class="warn">⚠</span> <strong>systemd user env is minimal:</strong> always write absolute paths for node + t3 into the unit; never rely on PATH. Service failures are invisible by default — hence the phase 3 requirement to log to a printed file path.</li>
|
||||
<li><span class="warn">⚠</span> <strong>Linger prompt honesty:</strong> the y/n prompt should say the machine becomes reachable via T3 Connect whenever powered on — that's the feature, but say it.</li>
|
||||
<li><span class="ok">✓</span> Re-running <code>connect</code> when linked → idempotent: refresh token, re-confirm service, done.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Decision log</h2>
|
||||
<ul class="kv">
|
||||
<li>Auth: hosted out-of-band OAuth redirect on Clerk PKCE (not relay-brokered pairing, not device grant) — chosen for minimal new surface.</li>
|
||||
<li>URL: stateless static page, no backend short-link.</li>
|
||||
<li>Service: real per-user login service (systemd user + linger first); detect + offer install, never silent.</li>
|
||||
<li>Binary: pinned managed runtime under <code>~/.t3</code>; interactive <code>npx</code> usage untouched.</li>
|
||||
<li>Updates: not always-latest; web UI surfaces available updates with one-click trigger (phase 4 follow-up).</li>
|
||||
<li>Delivery: one PR with a commit per phase (green tree at every boundary), not separate PRs.</li>
|
||||
<li>Workspace: assumed already set up; no auto-registration.</li>
|
||||
</ul>
|
||||
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -2,16 +2,27 @@
|
||||
|
||||
## Task Completion Requirements
|
||||
|
||||
- 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.
|
||||
- `vp check` and `vp run typecheck` must pass before considering tasks completed.
|
||||
- If changing native mobile code, `vp run lint:mobile` must also pass.
|
||||
- Use `vp test` for the built-in Vite+ test command and `vp run test` when you specifically need the `test` package script.
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
|
||||
|
||||
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
|
||||
|
||||
## Core Priorities
|
||||
|
||||
1. Performance first.
|
||||
2. Reliability first.
|
||||
3. Keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).
|
||||
|
||||
If a tradeoff is required, choose correctness and robustness over short-term convenience.
|
||||
|
||||
## Maintainability
|
||||
|
||||
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
|
||||
|
||||
## Package Roles
|
||||
|
||||
@@ -24,6 +35,7 @@
|
||||
## Reference Repos
|
||||
|
||||
- Open-source Codex repo: https://github.com/openai/codex
|
||||
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
|
||||
|
||||
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
|
||||
|
||||
@@ -35,7 +47,8 @@ agents.
|
||||
- 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.
|
||||
- Manage vendored subtrees with `bun run sync:repos`; use `bun run 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
|
||||
|
||||
@@ -54,8 +54,6 @@ There's no public docs site yet, checkout the miscellaneous markdown files in [d
|
||||
## Documentation
|
||||
|
||||
- [Getting started](./docs/getting-started/quick-start.md)
|
||||
- [Remote access](./docs/user/remote-access.md)
|
||||
- [Keeping T3 Code in sync](./docs/user/server-updates.md)
|
||||
- [Architecture overview](./docs/architecture/overview.md)
|
||||
- [Provider guides](./docs/providers/codex.md)
|
||||
- [Operations](./docs/operations/ci.md)
|
||||
|
||||
@@ -53,16 +53,13 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.isDevelopment, true);
|
||||
assert.equal(environment.appDataDirectory, "/Users/alice/Library/Application Support");
|
||||
assert.equal(environment.baseDir, "/tmp/t3");
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata");
|
||||
assert.equal(environment.desktopSettingsPath, "/tmp/t3/userdata/desktop-settings.json");
|
||||
assert.equal(environment.clientSettingsPath, "/tmp/t3/userdata/client-settings.json");
|
||||
assert.equal(
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
"/tmp/t3/userdata/saved-environments.json",
|
||||
);
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.stateDir, "/tmp/t3/dev");
|
||||
assert.equal(environment.desktopSettingsPath, "/tmp/t3/dev/desktop-settings.json");
|
||||
assert.equal(environment.clientSettingsPath, "/tmp/t3/dev/client-settings.json");
|
||||
assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");
|
||||
assert.equal(environment.logDir, "/tmp/t3/dev/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/dev/browser-artifacts");
|
||||
assert.equal(environment.rootDir, "/repo");
|
||||
assert.equal(environment.appRoot, "/repo");
|
||||
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
|
||||
@@ -81,7 +78,7 @@ describe("DesktopEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stores production state under userdata in an explicit home", () =>
|
||||
it.effect("derives production state paths under userdata", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment(
|
||||
{},
|
||||
@@ -98,19 +95,6 @@ describe("DesktopEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps implicit development state separate from production state", () =>
|
||||
Effect.gen(function* () {
|
||||
const development = yield* makeEnvironment(
|
||||
{},
|
||||
{ VITE_DEV_SERVER_URL: "http://localhost:5173" },
|
||||
);
|
||||
const production = yield* makeEnvironment();
|
||||
|
||||
assert.equal(development.stateDir, "/Users/alice/.t3/dev");
|
||||
assert.equal(production.stateDir, "/Users/alice/.t3/userdata");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses a configured app user model id override", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment(
|
||||
|
||||
@@ -147,8 +147,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
: input.platform === "darwin"
|
||||
? path.join(homeDirectory, "Library", "Application Support")
|
||||
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
|
||||
const configuredBaseDir = config.t3Home;
|
||||
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
|
||||
const baseDir = Option.getOrElse(config.t3Home, () => path.join(homeDirectory, ".t3"));
|
||||
const rootDir = path.resolve(input.dirname, "../../..");
|
||||
const appRoot = input.isPackaged ? input.appPath : rootDir;
|
||||
const branding = resolveDesktopAppBranding({
|
||||
@@ -156,10 +155,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
appVersion: input.appVersion,
|
||||
});
|
||||
const displayName = branding.displayName;
|
||||
const stateDir = path.join(
|
||||
baseDir,
|
||||
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
|
||||
);
|
||||
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata");
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const resourcesPath = input.resourcesPath;
|
||||
|
||||
@@ -73,14 +73,8 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
|
||||
}
|
||||
|
||||
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
|
||||
function* (): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow
|
||||
> {
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> {
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.flushMainWindowBounds;
|
||||
yield* shutdown.request;
|
||||
yield* shutdown.awaitComplete;
|
||||
},
|
||||
|
||||
@@ -76,7 +76,6 @@ function makePoolLayer(
|
||||
showConnectingSplash: Effect.void,
|
||||
handleBackendReady: () => Effect.void,
|
||||
handleBackendNotReady: Effect.void,
|
||||
flushMainWindowBounds: Effect.void,
|
||||
dispatchMenuAction: () => Effect.die("unexpected menu action"),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]),
|
||||
|
||||
@@ -250,7 +250,6 @@ describe("DesktopServerExposure", () => {
|
||||
const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
|
||||
setServerExposureMode: () => Effect.fail(settingsFailure),
|
||||
setTailscaleServe: () => Effect.fail(settingsFailure),
|
||||
setUpdateChannel: () => Effect.die("unexpected update channel change"),
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
for (const stream of [process.stdout, process.stderr]) {
|
||||
stream.on("error", (err: NodeJS.ErrnoException) => {
|
||||
if (err.code !== "EPIPE") throw err;
|
||||
});
|
||||
}
|
||||
|
||||
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
@@ -15,7 +15,6 @@ const { fromPartition, sessions } = vi.hoisted(() => ({
|
||||
readonly clearStorageData: ReturnType<typeof vi.fn>;
|
||||
readonly getUserAgent: ReturnType<typeof vi.fn>;
|
||||
readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;
|
||||
readonly setPermissionCheckHandler: ReturnType<typeof vi.fn>;
|
||||
readonly setUserAgent: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
>(),
|
||||
@@ -41,7 +40,6 @@ describe("BrowserSession", () => {
|
||||
clearStorageData: vi.fn(() => Promise.resolve()),
|
||||
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
|
||||
setPermissionRequestHandler: vi.fn(),
|
||||
setPermissionCheckHandler: vi.fn(),
|
||||
setUserAgent: vi.fn(),
|
||||
};
|
||||
sessions.set(partition, browserSession);
|
||||
@@ -63,55 +61,6 @@ describe("BrowserSession", () => {
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("grants clipboard-sanitized-write through both the request and check handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const partition = yield* browserSessions.getPartition("scope-a");
|
||||
yield* browserSessions.getSession("scope-a");
|
||||
|
||||
const browserSession = sessions.get(partition);
|
||||
assert.isDefined(browserSession);
|
||||
|
||||
const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0];
|
||||
const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0];
|
||||
assert.isFunction(requestHandler);
|
||||
assert.isFunction(checkHandler);
|
||||
|
||||
const requestAllows = (permission: string): boolean => {
|
||||
let granted: boolean | undefined;
|
||||
requestHandler(null, permission, (value: boolean) => {
|
||||
granted = value;
|
||||
});
|
||||
assert.isDefined(granted);
|
||||
return granted;
|
||||
};
|
||||
|
||||
for (const permission of [
|
||||
"clipboard-read",
|
||||
"clipboard-sanitized-write",
|
||||
"notifications",
|
||||
"geolocation",
|
||||
]) {
|
||||
assert.isTrue(requestAllows(permission), `request handler should allow ${permission}`);
|
||||
assert.isTrue(
|
||||
checkHandler(null, permission) as boolean,
|
||||
`check handler should allow ${permission}`,
|
||||
);
|
||||
}
|
||||
|
||||
// `clipboard-write` is not a real Electron permission — the async write API
|
||||
// uses `clipboard-sanitized-write` — so the stale name must not be granted,
|
||||
// and unrelated permissions stay denied.
|
||||
for (const permission of ["clipboard-write", "midi"]) {
|
||||
assert.isFalse(requestAllows(permission), `request handler should deny ${permission}`);
|
||||
assert.isFalse(
|
||||
checkHandler(null, permission) as boolean,
|
||||
`check handler should deny ${permission}`,
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves partition scope and the platform failure chain", () => {
|
||||
const nativeCause = new Error("native digest failed");
|
||||
const platformCause = PlatformError.systemError({
|
||||
|
||||
@@ -11,20 +11,6 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
|
||||
// Permissions granted to preview web content. `clipboard-sanitized-write` is the
|
||||
// Electron permission behind `navigator.clipboard.writeText()` — note it is NOT
|
||||
// `clipboard-write`, which is not a valid Electron permission name. Async
|
||||
// clipboard writes are gated by the permission *check* handler (not only the
|
||||
// request handler), so both handlers must allow it; otherwise built-in "Copy"
|
||||
// buttons — e.g. the Next.js / Vercel error overlay — fail with
|
||||
// `Failed to execute 'writeText' on 'Clipboard': Write permission denied`.
|
||||
const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
|
||||
"clipboard-read",
|
||||
"clipboard-sanitized-write",
|
||||
"notifications",
|
||||
"geolocation",
|
||||
]);
|
||||
|
||||
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
|
||||
"BrowserSessionPartitionDerivationError",
|
||||
{
|
||||
@@ -134,11 +120,9 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
.replace(/\s*t3code\/[\d.]+/, "");
|
||||
browserSession.setUserAgent(userAgent);
|
||||
browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
|
||||
callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
|
||||
const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
|
||||
callback(allowed.includes(permission));
|
||||
});
|
||||
browserSession.setPermissionCheckHandler((_webContents, permission) =>
|
||||
ALLOWED_PREVIEW_PERMISSIONS.has(permission),
|
||||
);
|
||||
const next = new Map(sessions);
|
||||
next.set(partition, browserSession);
|
||||
return [browserSession, next] as const;
|
||||
|
||||
@@ -11,17 +11,6 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
|
||||
|
||||
const DesktopSettingsPatch = Schema.Struct({
|
||||
mainWindowBounds: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
x: Schema.Number,
|
||||
y: Schema.Number,
|
||||
width: Schema.Number,
|
||||
height: Schema.Number,
|
||||
}),
|
||||
),
|
||||
),
|
||||
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
|
||||
serverExposureMode: Schema.optionalKey(Schema.Literals(["local-only", "network-accessible"])),
|
||||
tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
tailscaleServePort: Schema.optionalKey(Schema.Number),
|
||||
@@ -102,8 +91,6 @@ describe("DesktopSettings", () => {
|
||||
assert.deepEqual(
|
||||
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
|
||||
{
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
@@ -129,8 +116,6 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
@@ -230,13 +215,10 @@ describe("DesktopSettings", () => {
|
||||
"serverExposureMode": "network-accessible",
|
||||
"tailscaleServeEnabled": true,
|
||||
"tailscaleServePort": 8443,
|
||||
"mainWindowBounds": { "x": 120, "y": 80, "width": 1280, "height": 900 },
|
||||
}\n`,
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
@@ -250,24 +232,6 @@ describe("DesktopSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects window bounds that do not satisfy the domain schema", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
mainWindowBounds: { x: 10.5, y: 20, width: 839, height: 620 },
|
||||
mainWindowMaximized: true,
|
||||
serverExposureMode: "network-accessible",
|
||||
});
|
||||
|
||||
const loaded = yield* settings.load;
|
||||
assert.isNull(loaded.mainWindowBounds);
|
||||
assert.isFalse(loaded.mainWindowMaximized);
|
||||
assert.equal(loaded.serverExposureMode, "network-accessible");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists sparse desktop settings documents", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
@@ -275,15 +239,12 @@ describe("DesktopSettings", () => {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
|
||||
yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 1440, height: 960 }, true);
|
||||
yield* settings.setServerExposureMode("network-accessible");
|
||||
|
||||
const persisted = yield* decodeDesktopSettingsPatch(
|
||||
yield* fileSystem.readFileString(environment.desktopSettingsPath),
|
||||
);
|
||||
assert.deepEqual(persisted, {
|
||||
mainWindowBounds: { x: -1200, y: 40, width: 1440, height: 960 },
|
||||
mainWindowMaximized: true,
|
||||
serverExposureMode: "network-accessible",
|
||||
} satisfies typeof DesktopSettingsPatch.Type);
|
||||
}),
|
||||
@@ -300,8 +261,6 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
@@ -327,8 +286,6 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
@@ -353,8 +310,6 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 443,
|
||||
|
||||
@@ -20,8 +20,6 @@ import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts
|
||||
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly mainWindowBounds: DesktopWindowBounds | null;
|
||||
readonly mainWindowMaximized: boolean;
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
readonly tailscaleServeEnabled: boolean;
|
||||
readonly tailscaleServePort: number;
|
||||
@@ -50,25 +48,8 @@ export interface DesktopSettingsChange {
|
||||
}
|
||||
|
||||
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
|
||||
const MIN_MAIN_WINDOW_SIZE = {
|
||||
width: 840,
|
||||
height: 620,
|
||||
} as const;
|
||||
export const DesktopWindowBoundsSchema = Schema.Struct({
|
||||
x: Schema.Int,
|
||||
y: Schema.Int,
|
||||
width: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_MAIN_WINDOW_SIZE.width)),
|
||||
height: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_MAIN_WINDOW_SIZE.height)),
|
||||
});
|
||||
export type DesktopWindowBounds = typeof DesktopWindowBoundsSchema.Type;
|
||||
export const DEFAULT_MAIN_WINDOW_SIZE = {
|
||||
width: 1100,
|
||||
height: 780,
|
||||
} as const;
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
@@ -79,16 +60,7 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
wslOnly: false,
|
||||
};
|
||||
|
||||
const DesktopWindowBoundsDocument = Schema.Struct({
|
||||
x: Schema.Number,
|
||||
y: Schema.Number,
|
||||
width: Schema.Number,
|
||||
height: Schema.Number,
|
||||
});
|
||||
|
||||
const DesktopSettingsDocument = Schema.Struct({
|
||||
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
|
||||
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
|
||||
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
|
||||
tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
tailscaleServePort: Schema.optionalKey(Schema.Number),
|
||||
@@ -109,8 +81,6 @@ type Mutable<T> = { -readonly [K in keyof T]: T[K] };
|
||||
const DesktopSettingsJson = fromLenientJson(DesktopSettingsDocument);
|
||||
const decodeDesktopSettingsJson = Schema.decodeEffect(DesktopSettingsJson);
|
||||
const encodeDesktopSettingsJson = Schema.encodeEffect(DesktopSettingsJson);
|
||||
const decodeDesktopWindowBounds = Schema.decodeUnknownOption(DesktopWindowBoundsSchema);
|
||||
const desktopWindowBoundsEquivalence = Schema.toEquivalence(DesktopWindowBoundsSchema);
|
||||
|
||||
const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({
|
||||
settings,
|
||||
@@ -144,10 +114,6 @@ export class DesktopAppSettings extends Context.Service<
|
||||
{
|
||||
readonly load: Effect.Effect<DesktopSettings>;
|
||||
readonly get: Effect.Effect<DesktopSettings>;
|
||||
readonly setMainWindowBounds: (
|
||||
bounds: DesktopWindowBounds,
|
||||
isMaximized: boolean,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setServerExposureMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
@@ -192,16 +158,11 @@ function normalizeWslDistro(value: unknown): string | null {
|
||||
return typeof value === "string" && isValidDistroName(value) ? value : null;
|
||||
}
|
||||
|
||||
export function normalizeMainWindowBounds(value: unknown): DesktopWindowBounds | null {
|
||||
return Option.getOrNull(decodeDesktopWindowBounds(value));
|
||||
}
|
||||
|
||||
function normalizeDesktopSettingsDocument(
|
||||
parsed: DesktopSettingsDocument,
|
||||
appVersion: string,
|
||||
): DesktopSettings {
|
||||
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
|
||||
const mainWindowBounds = normalizeMainWindowBounds(parsed.mainWindowBounds);
|
||||
const parsedUpdateChannel = Option.fromNullishOr(parsed.updateChannel);
|
||||
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
|
||||
const updateChannelConfiguredByUser =
|
||||
@@ -216,8 +177,6 @@ function normalizeDesktopSettingsDocument(
|
||||
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
|
||||
|
||||
return {
|
||||
mainWindowBounds,
|
||||
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
|
||||
serverExposureMode:
|
||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
|
||||
@@ -238,12 +197,6 @@ function toDesktopSettingsDocument(
|
||||
): DesktopSettingsDocument {
|
||||
const document: Mutable<DesktopSettingsDocument> = {};
|
||||
|
||||
if (settings.mainWindowBounds !== null) {
|
||||
document.mainWindowBounds = settings.mainWindowBounds;
|
||||
}
|
||||
if (settings.mainWindowMaximized) {
|
||||
document.mainWindowMaximized = true;
|
||||
}
|
||||
if (settings.serverExposureMode !== defaults.serverExposureMode) {
|
||||
document.serverExposureMode = settings.serverExposureMode;
|
||||
}
|
||||
@@ -284,22 +237,6 @@ function setServerExposureMode(
|
||||
};
|
||||
}
|
||||
|
||||
function setMainWindowBounds(
|
||||
settings: DesktopSettings,
|
||||
bounds: DesktopWindowBounds,
|
||||
isMaximized: boolean,
|
||||
): DesktopSettings {
|
||||
return settings.mainWindowBounds !== null &&
|
||||
desktopWindowBoundsEquivalence(settings.mainWindowBounds, bounds) &&
|
||||
settings.mainWindowMaximized === isMaximized
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
mainWindowBounds: bounds,
|
||||
mainWindowMaximized: isMaximized,
|
||||
};
|
||||
}
|
||||
|
||||
function setTailscaleServe(
|
||||
settings: DesktopSettings,
|
||||
input: { readonly enabled: boolean; readonly port: Option.Option<number> },
|
||||
@@ -494,18 +431,6 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
return yield* SynchronizedRef.setAndGet(settingsRef, settings);
|
||||
}).pipe(Effect.withSpan("desktop.settings.load")),
|
||||
setMainWindowBounds: (bounds, isMaximized) =>
|
||||
persist((settings) => setMainWindowBounds(settings, bounds, isMaximized)).pipe(
|
||||
Effect.withSpan("desktop.settings.setMainWindowBounds", {
|
||||
attributes: {
|
||||
x: bounds.x,
|
||||
y: bounds.y,
|
||||
width: bounds.width,
|
||||
height: bounds.height,
|
||||
isMaximized,
|
||||
},
|
||||
}),
|
||||
),
|
||||
setServerExposureMode: (mode) =>
|
||||
persist((settings) => setServerExposureMode(settings, mode)).pipe(
|
||||
Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
|
||||
@@ -563,8 +488,6 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET
|
||||
return DesktopAppSettings.of({
|
||||
get: SynchronizedRef.get(settingsRef),
|
||||
load: SynchronizedRef.get(settingsRef),
|
||||
setMainWindowBounds: (bounds, isMaximized) =>
|
||||
update((settings) => setMainWindowBounds(settings, bounds, isMaximized)),
|
||||
setServerExposureMode: (mode) =>
|
||||
update((settings) => setServerExposureMode(settings, mode)),
|
||||
setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
|
||||
|
||||
@@ -19,9 +19,7 @@ const clientSettings: ClientSettings = {
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
favorites: [],
|
||||
glassOpacity: 80,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
@@ -29,7 +27,6 @@ const clientSettings: ClientSettings = {
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
sidebarV2Enabled: false,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
@@ -158,7 +158,6 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
|
||||
@@ -76,7 +76,6 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
|
||||
showConnectingSplash: Effect.void,
|
||||
handleBackendReady: () => Effect.void,
|
||||
handleBackendNotReady: Effect.void,
|
||||
flushMainWindowBounds: Effect.void,
|
||||
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]);
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import type * as Electron from "electron";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
vi.mock("electron", async (importOriginal) => ({
|
||||
@@ -23,20 +18,12 @@ vi.mock("electron", async (importOriginal) => ({
|
||||
setUserAgent: vi.fn(),
|
||||
})),
|
||||
},
|
||||
screen: {
|
||||
getAllDisplays: vi.fn(() => [
|
||||
{
|
||||
bounds: { x: 0, y: 0, width: 1920, height: 1080 },
|
||||
},
|
||||
]),
|
||||
},
|
||||
}));
|
||||
|
||||
import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
@@ -79,21 +66,15 @@ function makeFakeBrowserWindow() {
|
||||
const window = {
|
||||
close: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
getBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })),
|
||||
getNormalBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })),
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isFullScreen: vi.fn(() => false),
|
||||
isMaximized: vi.fn(() => false),
|
||||
isMinimized: vi.fn(() => false),
|
||||
isVisible: vi.fn(() => true),
|
||||
loadURL: vi.fn(() => Promise.resolve()),
|
||||
maximize: vi.fn(),
|
||||
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
windowListeners.set(eventName, listener);
|
||||
}),
|
||||
once: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
windowListeners.set(eventName, listener);
|
||||
}),
|
||||
once: vi.fn(),
|
||||
restore: vi.fn(),
|
||||
setBackgroundColor: vi.fn(),
|
||||
setAutoHideCursor: vi.fn(),
|
||||
@@ -105,14 +86,7 @@ function makeFakeBrowserWindow() {
|
||||
|
||||
return {
|
||||
window: window as unknown as Electron.BrowserWindow,
|
||||
getBounds: window.getBounds,
|
||||
getNormalBounds: window.getNormalBounds,
|
||||
isDestroyed: window.isDestroyed,
|
||||
isFullScreen: window.isFullScreen,
|
||||
isMaximized: window.isMaximized,
|
||||
isMinimized: window.isMinimized,
|
||||
loadURL: window.loadURL,
|
||||
maximize: window.maximize,
|
||||
openDevTools: webContents.openDevTools,
|
||||
reload: webContents.reload,
|
||||
send: webContents.send,
|
||||
@@ -170,57 +144,13 @@ const desktopEnvironmentLayer = DesktopEnvironment.layer(environmentInput).pipe(
|
||||
),
|
||||
);
|
||||
|
||||
const desktopWindowBoundsEquivalence = Schema.toEquivalence(
|
||||
DesktopAppSettings.DesktopWindowBoundsSchema,
|
||||
);
|
||||
|
||||
function makeTestLayer(input: {
|
||||
readonly window: Electron.BrowserWindow;
|
||||
readonly createCount: Ref.Ref<number>;
|
||||
readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly createdWindowOptions?: Electron.BrowserWindowConstructorOptions[];
|
||||
readonly desktopSettings?: DesktopAppSettings.DesktopSettings;
|
||||
readonly mainWindowBoundsUpdates?: DesktopAppSettings.DesktopWindowBounds[];
|
||||
readonly mainWindowMaximizedUpdates?: boolean[];
|
||||
readonly beforeMainWindowBoundsUpdate?: (
|
||||
bounds: DesktopAppSettings.DesktopWindowBounds,
|
||||
) => Effect.Effect<void>;
|
||||
readonly openedExternalUrls?: unknown[];
|
||||
}) {
|
||||
let desktopSettings = input.desktopSettings ?? DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS;
|
||||
const desktopAppSettingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.sync(() => desktopSettings),
|
||||
load: Effect.sync(() => desktopSettings),
|
||||
setMainWindowBounds: (bounds, isMaximized) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.beforeMainWindowBoundsUpdate) {
|
||||
yield* input.beforeMainWindowBoundsUpdate(bounds);
|
||||
}
|
||||
const changed =
|
||||
desktopSettings.mainWindowBounds === null ||
|
||||
!desktopWindowBoundsEquivalence(desktopSettings.mainWindowBounds, bounds) ||
|
||||
desktopSettings.mainWindowMaximized !== isMaximized;
|
||||
if (changed) {
|
||||
desktopSettings = {
|
||||
...desktopSettings,
|
||||
mainWindowBounds: bounds,
|
||||
mainWindowMaximized: isMaximized,
|
||||
};
|
||||
input.mainWindowBoundsUpdates?.push(bounds);
|
||||
input.mainWindowMaximizedUpdates?.push(isMaximized);
|
||||
}
|
||||
return { settings: desktopSettings, changed };
|
||||
}),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.die("unexpected update channel change"),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
|
||||
|
||||
const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: (options) =>
|
||||
Effect.sync(() => {
|
||||
@@ -245,7 +175,6 @@ function makeTestLayer(input: {
|
||||
Layer.mergeAll(
|
||||
desktopAssetsLayer,
|
||||
desktopEnvironmentLayer,
|
||||
desktopAppSettingsLayer,
|
||||
desktopServerExposureLayer,
|
||||
DesktopState.layer,
|
||||
electronMenuLayer,
|
||||
@@ -343,7 +272,6 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
|
||||
Layer.mergeAll(
|
||||
desktopAssetsLayer,
|
||||
desktopEnvironmentLayer,
|
||||
DesktopAppSettings.layerTest(),
|
||||
desktopServerExposureLayer,
|
||||
electronMenuLayer,
|
||||
Layer.succeed(ElectronShell.ElectronShell, {
|
||||
@@ -366,23 +294,6 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
|
||||
});
|
||||
|
||||
describe("DesktopWindow", () => {
|
||||
it("restores bounds only when the window fits within a connected display", () => {
|
||||
const persistedBounds = { x: 2040, y: 80, width: 1320, height: 880 };
|
||||
const displays = [
|
||||
{ x: 0, y: 0, width: 1920, height: 1080 },
|
||||
{ x: 1920, y: 0, width: 2560, height: 1440 },
|
||||
];
|
||||
|
||||
assert.deepEqual(
|
||||
DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, displays),
|
||||
persistedBounds,
|
||||
);
|
||||
assert.deepEqual(
|
||||
DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, [displays[0]!]),
|
||||
DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE,
|
||||
);
|
||||
});
|
||||
|
||||
it("recognizes only same-origin renderer navigations", () => {
|
||||
assert.isTrue(
|
||||
DesktopWindow.isSameOriginRendererNavigation({
|
||||
@@ -424,10 +335,6 @@ describe("DesktopWindow", () => {
|
||||
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
assert.equal(yield* Ref.get(createCount), 1);
|
||||
assert.equal(createdWindowOptions[0]?.width, 1100);
|
||||
assert.equal(createdWindowOptions[0]?.height, 780);
|
||||
assert.isUndefined(createdWindowOptions[0]?.x);
|
||||
assert.isUndefined(createdWindowOptions[0]?.y);
|
||||
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
|
||||
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
|
||||
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
|
||||
@@ -436,427 +343,6 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the persisted main window bounds when opening the window", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
createdWindowOptions,
|
||||
desktopSettings: {
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
assert.equal(createdWindowOptions[0]?.width, 1320);
|
||||
assert.equal(createdWindowOptions[0]?.height, 880);
|
||||
assert.equal(createdWindowOptions[0]?.x, 120);
|
||||
assert.equal(createdWindowOptions[0]?.y, 80);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restores the persisted maximized state", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
desktopSettings: {
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
|
||||
mainWindowMaximized: true,
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
assert.equal(fakeWindow.maximize.mock.calls.length, 0);
|
||||
const readyToShow = fakeWindow.windowListeners.get("ready-to-show");
|
||||
if (!readyToShow) {
|
||||
return yield* Effect.die("window ready-to-show listener was not registered");
|
||||
}
|
||||
readyToShow();
|
||||
assert.equal(fakeWindow.maximize.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("debounces move and resize bounds updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
mainWindowBoundsUpdates,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const move = fakeWindow.windowListeners.get("move");
|
||||
const resize = fakeWindow.windowListeners.get("resize");
|
||||
if (!move || !resize) {
|
||||
return yield* Effect.die("window bounds listeners were not registered");
|
||||
}
|
||||
|
||||
fakeWindow.getBounds.mockReturnValue({ x: 120, y: 80, width: 1280, height: 840 });
|
||||
move();
|
||||
yield* TestClock.adjust(250);
|
||||
|
||||
fakeWindow.getBounds.mockReturnValue({ x: 160, y: 100, width: 1360, height: 900 });
|
||||
resize();
|
||||
yield* TestClock.adjust(499);
|
||||
assert.deepEqual(mainWindowBoundsUpdates, []);
|
||||
|
||||
yield* TestClock.adjust(1);
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 160, y: 100, width: 1360, height: 900 }]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("persists normal bounds and state for a maximized window", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
fakeWindow.isMaximized.mockReturnValue(true);
|
||||
fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
|
||||
fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
|
||||
const mainWindowMaximizedUpdates: boolean[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
mainWindowBoundsUpdates,
|
||||
mainWindowMaximizedUpdates,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const close = fakeWindow.windowListeners.get("close");
|
||||
if (!close) {
|
||||
return yield* Effect.die("window close listener was not registered");
|
||||
}
|
||||
close();
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
|
||||
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
|
||||
assert.deepEqual(mainWindowMaximizedUpdates, [true]);
|
||||
assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
|
||||
assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("persists normal bounds and state from the native maximize event", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
|
||||
const mainWindowMaximizedUpdates: boolean[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
mainWindowBoundsUpdates,
|
||||
mainWindowMaximizedUpdates,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const maximize = fakeWindow.windowListeners.get("maximize");
|
||||
if (!maximize) {
|
||||
return yield* Effect.die("window maximize listener was not registered");
|
||||
}
|
||||
|
||||
fakeWindow.isMaximized.mockReturnValue(true);
|
||||
fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
|
||||
fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
|
||||
maximize();
|
||||
yield* TestClock.adjust(500);
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
|
||||
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
|
||||
assert.deepEqual(mainWindowMaximizedUpdates, [true]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not persist bounds that fail the domain schema", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
fakeWindow.getBounds.mockReturnValue({ x: 100.4, y: 80.2, width: 839.4, height: 619.4 });
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
mainWindowBoundsUpdates,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const resize = fakeWindow.windowListeners.get("resize");
|
||||
if (!resize) {
|
||||
return yield* Effect.die("window resize listener was not registered");
|
||||
}
|
||||
resize();
|
||||
yield* TestClock.adjust(500);
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
|
||||
assert.deepEqual(mainWindowBoundsUpdates, []);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves unrestorable bounds until the user changes the window", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
mainWindowBoundsUpdates,
|
||||
desktopSettings: {
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
mainWindowBounds: { x: 2040, y: 80, width: 1320, height: 880 },
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const close = fakeWindow.windowListeners.get("close");
|
||||
const move = fakeWindow.windowListeners.get("move");
|
||||
if (!close || !move) {
|
||||
return yield* Effect.die("window lifecycle listeners were not registered");
|
||||
}
|
||||
|
||||
close();
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
assert.deepEqual(mainWindowBoundsUpdates, []);
|
||||
|
||||
fakeWindow.getBounds.mockReturnValue({ x: 80, y: 60, width: 1280, height: 840 });
|
||||
move();
|
||||
yield* TestClock.adjust(500);
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 80, y: 60, width: 1280, height: 840 }]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("flushes normal bounds when fullscreen before the debounce completes", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
|
||||
fakeWindow.getNormalBounds.mockReturnValue({ x: 200, y: 130, width: 1400, height: 940 });
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
mainWindowBoundsUpdates,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const resize = fakeWindow.windowListeners.get("resize");
|
||||
if (!resize) {
|
||||
return yield* Effect.die("window resize listener was not registered");
|
||||
}
|
||||
resize();
|
||||
yield* TestClock.adjust(250);
|
||||
fakeWindow.isFullScreen.mockReturnValue(true);
|
||||
|
||||
yield* desktopWindow.flushMainWindowBounds;
|
||||
|
||||
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 200, y: 130, width: 1400, height: 940 }]);
|
||||
assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
|
||||
assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("flushes normal bounds when minimized before the debounce completes", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 });
|
||||
fakeWindow.getNormalBounds.mockReturnValue({ x: 180, y: 120, width: 1440, height: 960 });
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
mainWindowBoundsUpdates,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const resize = fakeWindow.windowListeners.get("resize");
|
||||
if (!resize) {
|
||||
return yield* Effect.die("window resize listener was not registered");
|
||||
}
|
||||
resize();
|
||||
yield* TestClock.adjust(250);
|
||||
fakeWindow.isMinimized.mockReturnValue(true);
|
||||
|
||||
yield* desktopWindow.flushMainWindowBounds;
|
||||
|
||||
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 180, y: 120, width: 1440, height: 960 }]);
|
||||
assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
|
||||
assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs display lookup failures before falling back to the default size", () =>
|
||||
Effect.gen(function* () {
|
||||
const displayLookupFailure = new Error("screen API unavailable");
|
||||
vi.mocked(Electron.screen.getAllDisplays).mockImplementationOnce(() => {
|
||||
throw displayLookupFailure;
|
||||
});
|
||||
const logRecords: Array<{
|
||||
readonly message: unknown;
|
||||
readonly annotations: Readonly<Record<string, unknown>>;
|
||||
}> = [];
|
||||
const logger = Logger.make(({ fiber, message }) => {
|
||||
logRecords.push({
|
||||
message,
|
||||
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
|
||||
});
|
||||
});
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
createdWindowOptions,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(layer, Logger.layer([logger], { mergeWithExisting: false }))),
|
||||
);
|
||||
|
||||
const warning = logRecords.find(
|
||||
(record) =>
|
||||
Array.isArray(record.message) &&
|
||||
record.message[0] === "failed to read connected displays; using defaults",
|
||||
);
|
||||
assert.isDefined(warning);
|
||||
assert.strictEqual(warning.annotations.cause, displayLookupFailure);
|
||||
assert.equal(createdWindowOptions[0]?.width, 1100);
|
||||
assert.equal(createdWindowOptions[0]?.height, 780);
|
||||
assert.isUndefined(createdWindowOptions[0]?.x);
|
||||
assert.isUndefined(createdWindowOptions[0]?.y);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("persists the current main window bounds before the window closes", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
fakeWindow.getBounds.mockReturnValue({ x: 240, y: 160, width: 1410, height: 930 });
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
|
||||
const writeStarted = yield* Deferred.make<void>();
|
||||
const allowWrite = yield* Deferred.make<void>();
|
||||
const flushCompleted = yield* Deferred.make<void>();
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
mainWindowBoundsUpdates,
|
||||
beforeMainWindowBoundsUpdate: () =>
|
||||
Deferred.succeed(writeStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(allowWrite)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const close = fakeWindow.windowListeners.get("close");
|
||||
if (!close) {
|
||||
return yield* Effect.die("window close listener was not registered");
|
||||
}
|
||||
close();
|
||||
yield* Deferred.await(writeStarted);
|
||||
fakeWindow.isDestroyed.mockReturnValue(true);
|
||||
|
||||
const flushFiber = yield* desktopWindow.flushMainWindowBounds.pipe(
|
||||
Effect.andThen(Deferred.succeed(flushCompleted, undefined)),
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
assert.isFalse(yield* Deferred.isDone(flushCompleted));
|
||||
|
||||
yield* Deferred.succeed(allowWrite, undefined);
|
||||
yield* Fiber.join(flushFiber);
|
||||
assert.isTrue(yield* Deferred.isDone(flushCompleted));
|
||||
|
||||
assert.deepEqual(mainWindowBoundsUpdates, [
|
||||
{
|
||||
x: 240,
|
||||
y: 160,
|
||||
width: 1410,
|
||||
height: 930,
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("publishes native macOS fullscreen changes to the renderer", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -5,7 +5,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
@@ -17,13 +17,11 @@ import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
|
||||
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
|
||||
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
|
||||
-2, // ERR_FAILED
|
||||
@@ -43,7 +41,6 @@ type WindowTitleBarOptions = Pick<
|
||||
type DesktopWindowRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopAssets.DesktopAssets
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
| ElectronMenu.ElectronMenu
|
||||
| ElectronShell.ElectronShell
|
||||
| ElectronTheme.ElectronTheme
|
||||
@@ -78,7 +75,6 @@ export class DesktopWindow extends Context.Service<
|
||||
// window so a "macOS dock click" while the backend is down doesn't
|
||||
// produce a stranded window pointing at nothing.
|
||||
readonly handleBackendNotReady: Effect.Effect<void>;
|
||||
readonly flushMainWindowBounds: Effect.Effect<void>;
|
||||
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
|
||||
readonly syncAppearance: Effect.Effect<void>;
|
||||
}
|
||||
@@ -103,45 +99,6 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
|
||||
return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
type DisplayBounds = Pick<Electron.Rectangle, "x" | "y" | "width" | "height">;
|
||||
|
||||
function windowFitsWithinDisplay(
|
||||
windowBounds: DesktopAppSettings.DesktopWindowBounds,
|
||||
displayBounds: DisplayBounds,
|
||||
): boolean {
|
||||
return (
|
||||
windowBounds.x >= displayBounds.x &&
|
||||
windowBounds.y >= displayBounds.y &&
|
||||
windowBounds.x + windowBounds.width <= displayBounds.x + displayBounds.width &&
|
||||
windowBounds.y + windowBounds.height <= displayBounds.y + displayBounds.height
|
||||
);
|
||||
}
|
||||
|
||||
function windowBoundsEqual(
|
||||
left: DesktopAppSettings.DesktopWindowBounds,
|
||||
right: DesktopAppSettings.DesktopWindowBounds,
|
||||
): boolean {
|
||||
return (
|
||||
left.x === right.x &&
|
||||
left.y === right.y &&
|
||||
left.width === right.width &&
|
||||
left.height === right.height
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveInitialMainWindowBounds(
|
||||
persistedBounds: DesktopAppSettings.DesktopWindowBounds | null,
|
||||
displays: readonly DisplayBounds[],
|
||||
): DesktopAppSettings.DesktopWindowBounds | typeof DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE {
|
||||
if (
|
||||
persistedBounds !== null &&
|
||||
displays.some((display) => windowFitsWithinDisplay(persistedBounds, display))
|
||||
) {
|
||||
return persistedBounds;
|
||||
}
|
||||
return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE;
|
||||
}
|
||||
|
||||
// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
|
||||
// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
|
||||
// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
|
||||
@@ -245,7 +202,6 @@ export const make = Effect.gen(function* () {
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
// Window-side latch for the primary backend's readiness. Set by
|
||||
// handleBackendReady (driven by the pool's onReady callback), cleared
|
||||
// by handleBackendNotReady (driven by onShutdown). Only consumed by
|
||||
@@ -258,7 +214,6 @@ export const make = Effect.gen(function* () {
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
|
||||
|
||||
const dismissConnectingSplash = Effect.gen(function* () {
|
||||
const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
|
||||
@@ -295,31 +250,9 @@ export const make = Effect.gen(function* () {
|
||||
const iconPaths = yield* assets.iconPaths;
|
||||
const iconOption = getIconOption(iconPaths, environment.platform);
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
const persistedSettings = yield* desktopSettings.get;
|
||||
const persistedBounds = persistedSettings.mainWindowBounds;
|
||||
const displayBoundsResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
return {
|
||||
_tag: "Success" as const,
|
||||
bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
|
||||
};
|
||||
} catch (cause) {
|
||||
return { _tag: "Failure" as const, cause };
|
||||
}
|
||||
});
|
||||
const displayBounds =
|
||||
displayBoundsResult._tag === "Success"
|
||||
? displayBoundsResult.bounds
|
||||
: yield* logWindowWarning("failed to read connected displays; using defaults", {
|
||||
cause: displayBoundsResult.cause,
|
||||
}).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
|
||||
const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
|
||||
const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
|
||||
if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
|
||||
yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
|
||||
}
|
||||
const window = yield* electronWindow.create({
|
||||
...initialBounds,
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
@@ -341,92 +274,6 @@ export const make = Effect.gen(function* () {
|
||||
if (environment.platform === "darwin") {
|
||||
window.setAutoHideCursor(false);
|
||||
}
|
||||
let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
|
||||
let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
|
||||
let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
|
||||
const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => {
|
||||
if (window.isDestroyed()) {
|
||||
return null;
|
||||
}
|
||||
const bounds =
|
||||
window.isFullScreen() || window.isMaximized() || window.isMinimized()
|
||||
? window.getNormalBounds()
|
||||
: window.getBounds();
|
||||
return DesktopAppSettings.normalizeMainWindowBounds({
|
||||
x: Math.round(bounds.x),
|
||||
y: Math.round(bounds.y),
|
||||
width: Math.round(bounds.width),
|
||||
height: Math.round(bounds.height),
|
||||
});
|
||||
};
|
||||
const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds();
|
||||
const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
|
||||
const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
|
||||
if (!boundsPersistenceEnabled) {
|
||||
return pendingBoundsPersistFiber;
|
||||
}
|
||||
const bounds = readPersistableBounds();
|
||||
if (bounds === null) {
|
||||
return pendingBoundsPersistFiber;
|
||||
}
|
||||
pendingBoundsPersistFiber = runFork(
|
||||
desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.catch((error) =>
|
||||
logWindowWarning("failed to persist main window bounds", {
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return pendingBoundsPersistFiber;
|
||||
};
|
||||
const scheduleBoundsPersist = () => {
|
||||
if (!boundsPersistenceEnabled) {
|
||||
const currentBounds = readPersistableBounds();
|
||||
if (
|
||||
currentBounds === null ||
|
||||
(fallbackWindowBounds !== null &&
|
||||
windowBoundsEqual(currentBounds, fallbackWindowBounds) &&
|
||||
window.isMaximized() === fallbackWindowMaximized)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
boundsPersistenceEnabled = true;
|
||||
if (boundsPersistFiber !== undefined) {
|
||||
const fiber = boundsPersistFiber;
|
||||
boundsPersistFiber = undefined;
|
||||
runFork(Fiber.interrupt(fiber));
|
||||
}
|
||||
boundsPersistFiber = runFork(
|
||||
Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
boundsPersistFiber = undefined;
|
||||
void persistCurrentBounds();
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
const clearBoundsPersist = () => {
|
||||
if (boundsPersistFiber === undefined) {
|
||||
return;
|
||||
}
|
||||
const fiber = boundsPersistFiber;
|
||||
boundsPersistFiber = undefined;
|
||||
runFork(Fiber.interrupt(fiber));
|
||||
};
|
||||
const flushBoundsPersist = Effect.sync(() => {
|
||||
clearBoundsPersist();
|
||||
return persistCurrentBounds();
|
||||
}).pipe(
|
||||
Effect.flatMap((fiber) =>
|
||||
fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
flushMainWindowBounds = flushBoundsPersist;
|
||||
|
||||
yield* previewManager.setMainWindow(window);
|
||||
window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
|
||||
@@ -517,13 +364,6 @@ export const make = Effect.gen(function* () {
|
||||
event.preventDefault();
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
window.on("resize", scheduleBoundsPersist);
|
||||
window.on("move", scheduleBoundsPersist);
|
||||
window.on("maximize", scheduleBoundsPersist);
|
||||
window.on("unmaximize", scheduleBoundsPersist);
|
||||
window.on("close", () => {
|
||||
runFork(flushBoundsPersist);
|
||||
});
|
||||
|
||||
if (environment.platform === "darwin") {
|
||||
window.on("enter-full-screen", () => {
|
||||
@@ -632,9 +472,6 @@ export const make = Effect.gen(function* () {
|
||||
bindFirstRevealTrigger(revealSubscribers, () => {
|
||||
// Reveal the real window, then close the connecting splash (if any) so the
|
||||
// two don't overlap and there's no blank gap between them.
|
||||
if (persistedSettings.mainWindowMaximized) {
|
||||
window.maximize();
|
||||
}
|
||||
void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
|
||||
});
|
||||
|
||||
@@ -645,7 +482,6 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
window.on("closed", () => {
|
||||
clearDevelopmentLoadRetry();
|
||||
clearBoundsPersist();
|
||||
void runPromise(electronWindow.clearMain(Option.some(window)));
|
||||
});
|
||||
|
||||
@@ -762,9 +598,6 @@ export const make = Effect.gen(function* () {
|
||||
handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
|
||||
Effect.withSpan("desktop.window.handleBackendNotReady"),
|
||||
),
|
||||
flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
|
||||
Effect.withSpan("desktop.window.flushMainWindowBounds"),
|
||||
),
|
||||
dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
|
||||
yield* Effect.annotateCurrentSpan({ action });
|
||||
const existingWindow = yield* focusedMainWindow;
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"astro": "^7.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import type { APIRoute } from "astro";
|
||||
|
||||
import { buildT3ProjectFileJsonSchema } from "@t3tools/shared/t3ProjectFile";
|
||||
|
||||
// Rendered at build time; published at https://t3.codes/schema/t3.json so
|
||||
// t3.json files can reference it via "$schema" for editor/LSP support.
|
||||
export const GET: APIRoute = () =>
|
||||
new Response(`${JSON.stringify(buildT3ProjectFileJsonSchema(), null, 2)}\n`, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { VercelConfig } from "@vercel/config/v1";
|
||||
|
||||
export const config: VercelConfig = {
|
||||
installCommand: "npm install -g vite-plus && vp install --filter '@t3tools/marketing...'",
|
||||
installCommand: "npm install -g vite-plus && vp install --filter '@t3tools/marketing'",
|
||||
buildCommand: "vp run --filter @t3tools/marketing build",
|
||||
outputDirectory: "dist",
|
||||
};
|
||||
+5
-19
@@ -13,10 +13,7 @@ import { ConfirmDialogHost } from "./components/ConfirmDialogHost";
|
||||
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
|
||||
import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
|
||||
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
|
||||
import {
|
||||
AppearancePreferencesProvider,
|
||||
useAppearancePreferences,
|
||||
} from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { RootStack } from "./Stack";
|
||||
import { appAtomRegistry } from "./state/atom-registry";
|
||||
import { OverlayPortalHost } from "./components/OverlayPortal";
|
||||
@@ -29,10 +26,6 @@ if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
|
||||
prepareNativeShowcaseCapture();
|
||||
}
|
||||
|
||||
void SplashScreen.preventAutoHideAsync().catch(() => {
|
||||
// The native module can be unavailable in non-native test environments.
|
||||
});
|
||||
|
||||
const appLinking = {
|
||||
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
|
||||
// The Expo dev client launches the app via
|
||||
@@ -47,25 +40,18 @@ const appLinking = {
|
||||
|
||||
const Navigation = createStaticNavigation(RootStack);
|
||||
|
||||
function SplashScreenCoordinator() {
|
||||
const { isReady } = useAppearancePreferences();
|
||||
|
||||
useEffect(() => {
|
||||
if (isReady) void SplashScreen.hide();
|
||||
}, [isReady]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const colorScheme = useColorScheme();
|
||||
const statusBarBg = useThemeColor("--color-status-bar");
|
||||
|
||||
useEffect(() => {
|
||||
SplashScreen.hide();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<RegistryContext.Provider value={appAtomRegistry}>
|
||||
<CloudAuthProvider>
|
||||
<AppearancePreferencesProvider>
|
||||
<SplashScreenCoordinator />
|
||||
<GestureHandlerRootView className="flex-1">
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
|
||||
@@ -15,6 +15,7 @@ import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "re
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { AppText as Text } from "./components/AppText";
|
||||
import { renderCompactBrandTitle } from "./components/CompactBrandTitle";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
@@ -59,7 +60,6 @@ import {
|
||||
EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
|
||||
transitionIncomingSharePresentation,
|
||||
} from "./features/sharing/incoming-share-presentation";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass";
|
||||
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
|
||||
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
|
||||
|
||||
@@ -79,24 +79,19 @@ type AppScreenOptions = NativeStackNavigationOptions & {
|
||||
// Shared header presets. Screens only override genuinely dynamic values (titles,
|
||||
// subtitles, toolbar items, search callbacks) via NativeStackScreenOptions.
|
||||
//
|
||||
// GLASS: transparent header over the screen's primary scroll view on supported
|
||||
// iOS versions. Pre-glass iOS gets the same solid material as internal-scroll
|
||||
// surfaces so content is laid out below the bar instead of underlapping it.
|
||||
// GLASS: transparent header over the screen's primary scroll view, with the iOS 26
|
||||
// scroll-edge blur sampling the content (Home, Thread, Files tree, settings sheet).
|
||||
const GLASS_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerBackTitle: "",
|
||||
headerLargeTitle: false,
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED
|
||||
? { backgroundColor: "transparent" }
|
||||
: SHEET_BACKGROUND_COLOR !== undefined
|
||||
? { backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
|
||||
: undefined,
|
||||
headerStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
|
||||
scrollEdgeEffects: NATIVE_LIQUID_GLASS_SUPPORTED ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
|
||||
unstable_navigationItemStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? "editor" : undefined,
|
||||
headerTransparent: Platform.OS === "ios",
|
||||
scrollEdgeEffects: Platform.OS === "ios" ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
|
||||
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
|
||||
};
|
||||
|
||||
// SOLID: opaque sheet-colored header for surfaces whose content scrolls internally
|
||||
@@ -383,7 +378,8 @@ export const RootStack = createNativeStackNavigator({
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
headerBackVisible: false,
|
||||
title: "Threads",
|
||||
headerTitle: renderCompactBrandTitle,
|
||||
title: "T3 Code",
|
||||
},
|
||||
}),
|
||||
Thread: createNativeStackScreen({
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { T3Wordmark } from "./T3Wordmark";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
/**
|
||||
* Compact brand lockup sized for native navigation bars.
|
||||
*/
|
||||
export function CompactBrandTitle() {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
|
||||
return (
|
||||
<View
|
||||
aria-level={1}
|
||||
accessibilityLabel="T3 Code"
|
||||
accessible
|
||||
role="heading"
|
||||
style={{ alignItems: "center", flexDirection: "row", gap: 6 }}
|
||||
>
|
||||
<T3Wordmark color={iconColor} height={11} />
|
||||
<Text
|
||||
style={{
|
||||
color: mutedColor,
|
||||
fontFamily: "DMSans-Medium",
|
||||
fontSize: 14,
|
||||
letterSpacing: -0.35,
|
||||
}}
|
||||
>
|
||||
Code
|
||||
</Text>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: subtleColor,
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 6,
|
||||
paddingVertical: 2,
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: mutedColor,
|
||||
fontFamily: "DMSans-Bold",
|
||||
fontSize: 9,
|
||||
letterSpacing: 0.9,
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
Alpha
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function renderCompactBrandTitle() {
|
||||
return <CompactBrandTitle />;
|
||||
}
|
||||
@@ -33,7 +33,7 @@ import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
|
||||
import { connectionStorageLayer } from "./storage";
|
||||
|
||||
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
|
||||
if (state.isConnected === false) {
|
||||
if (state.isConnected === false || state.isInternetReachable === false) {
|
||||
return "offline";
|
||||
}
|
||||
if (state.isConnected === true) {
|
||||
|
||||
@@ -41,8 +41,6 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -58,9 +58,6 @@ export function ConnectionSheetButton(props: {
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={props.label}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ disabled: props.disabled ?? false }}
|
||||
className={cn(
|
||||
props.compact
|
||||
? "min-h-[42px] flex-row items-center justify-center gap-1.5 rounded-[14px] px-3.5 py-2.5"
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import type { ProjectEntry } from "@t3tools/contracts";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
FlatList,
|
||||
Platform,
|
||||
Pressable,
|
||||
RefreshControl,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import {
|
||||
buildFileTree,
|
||||
defaultExpandedTreePaths,
|
||||
@@ -123,7 +129,7 @@ export function FileTreeBrowser(props: {
|
||||
const insets = useSafeAreaInsets();
|
||||
// Native transparent-header height ≈ safe-area top + nav bar (~44). Matches the
|
||||
// observed adjustedContentInset bottom (~102) seen in the native trace.
|
||||
const headerInset = NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 44 : 0;
|
||||
const headerInset = Platform.OS === "ios" ? insets.top + 44 : 0;
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
const { onPreviewFile, onSelectFile, selectedPath: controlledSelectedPath } = props;
|
||||
const controlledSelectedPathRef = useRef(controlledSelectedPath);
|
||||
@@ -243,11 +249,9 @@ export function FileTreeBrowser(props: {
|
||||
className="flex-1"
|
||||
data={visibleNodes}
|
||||
keyExtractor={(item) => item.node.path}
|
||||
contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
scrollIndicatorInsets={
|
||||
NATIVE_LIQUID_GLASS_SUPPORTED
|
||||
? { top: headerInset, left: 0, right: 0, bottom: 0 }
|
||||
: undefined
|
||||
Platform.OS === "ios" ? { top: headerInset, left: 0, right: 0, bottom: 0 } : undefined
|
||||
}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
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 +14,6 @@ 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 { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
@@ -20,10 +21,10 @@ import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
buildHomeListFilterMenu,
|
||||
type HomeListFilterMenuEnvironment,
|
||||
type HomeListFilterMenuProject,
|
||||
} from "./home-list-filter-menu";
|
||||
import {
|
||||
hasCustomHomeListOptions,
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
} from "./home-list-options";
|
||||
@@ -32,17 +33,16 @@ export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment;
|
||||
|
||||
export function HomeHeader(props: {
|
||||
readonly environments: ReadonlyArray<HomeHeaderEnvironment>;
|
||||
readonly projects: ReadonlyArray<HomeListFilterMenuProject>;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
}) {
|
||||
@@ -59,24 +59,11 @@ 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();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
const hasCustomListOptions = hasCustomHomeListOptions(props);
|
||||
const menuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{
|
||||
@@ -95,57 +82,40 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
})),
|
||||
],
|
||||
},
|
||||
...(props.projects.length === 0
|
||||
? []
|
||||
: ([
|
||||
{
|
||||
id: "project",
|
||||
title: "Project",
|
||||
subactions: [
|
||||
{
|
||||
id: "project:all",
|
||||
title: "All projects",
|
||||
state: checkedMenuState(props.selectedProjectKey === null),
|
||||
},
|
||||
...props.projects.map((project) => ({
|
||||
id: `project:${project.key}`,
|
||||
title: project.label,
|
||||
state: checkedMenuState(props.selectedProjectKey === project.key),
|
||||
})),
|
||||
],
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
...(threadListV2Enabled
|
||||
? []
|
||||
: ([
|
||||
{
|
||||
id: "project-sort",
|
||||
title: "Sort projects",
|
||||
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
id: `project-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.projectSortOrder === option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "thread-sort",
|
||||
title: "Sort threads",
|
||||
subactions: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
id: `thread-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.threadSortOrder === option.value),
|
||||
})),
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
{
|
||||
id: "project-sort",
|
||||
title: "Sort projects",
|
||||
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
id: `project-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.projectSortOrder === option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "thread-sort",
|
||||
title: "Sort threads",
|
||||
subactions: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
id: `thread-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.threadSortOrder === option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "project-grouping",
|
||||
title: "Group projects",
|
||||
subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
id: `project-grouping:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.projectGroupingMode === option.value),
|
||||
})),
|
||||
},
|
||||
],
|
||||
[
|
||||
props.environments,
|
||||
props.projectGroupingMode,
|
||||
props.projectSortOrder,
|
||||
props.projects,
|
||||
props.selectedEnvironmentId,
|
||||
props.selectedProjectKey,
|
||||
props.threadSortOrder,
|
||||
threadListV2Enabled,
|
||||
],
|
||||
);
|
||||
const handleMenuAction = useCallback(
|
||||
@@ -167,19 +137,6 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (id === "project:all") {
|
||||
props.onProjectChange(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (id.startsWith("project:")) {
|
||||
const projectKey = id.slice("project:".length);
|
||||
if (props.projects.some((project) => project.key === projectKey)) {
|
||||
props.onProjectChange(projectKey);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const projectSort = PROJECT_SORT_OPTIONS.find(
|
||||
(option) => id === `project-sort:${option.value}`,
|
||||
);
|
||||
@@ -193,6 +150,13 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
props.onThreadSortOrderChange(threadSort.value);
|
||||
return;
|
||||
}
|
||||
|
||||
const grouping = PROJECT_GROUPING_OPTIONS.find(
|
||||
(option) => id === `project-grouping:${option.value}`,
|
||||
);
|
||||
if (grouping) {
|
||||
props.onProjectGroupingModeChange(grouping.value);
|
||||
}
|
||||
},
|
||||
[props],
|
||||
);
|
||||
@@ -291,24 +255,17 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
function IosHomeHeader(props: HomeHeaderProps) {
|
||||
const searchBarRef = useRef<SearchBarCommands>(null);
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const threadListV2Enabled = useThreadListV2FilterGate();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
const hasCustomListOptions = hasCustomHomeListOptions(props);
|
||||
const focusSearch = useCallback(() => {
|
||||
searchBarRef.current?.focus();
|
||||
return searchBarRef.current !== null;
|
||||
}, []);
|
||||
useHardwareKeyboardCommand("focusSearch", focusSearch);
|
||||
const filterMenu = buildHomeListFilterMenu({
|
||||
...props,
|
||||
listOrganization: !threadListV2Enabled,
|
||||
});
|
||||
const filterMenu = buildHomeListFilterMenu(props);
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions
|
||||
optionsVersion={filterMenu.items}
|
||||
options={{
|
||||
// Static header config (glass, title, fonts) lives in Stack.tsx
|
||||
// (GLASS_HEADER_OPTIONS). Only dynamic values are set here.
|
||||
@@ -409,28 +366,6 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
{props.projects.length > 0 ? (
|
||||
<NativeHeaderToolbar.Menu title="Project">
|
||||
<NativeHeaderToolbar.Label>Project</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
isOn={props.selectedProjectKey === null}
|
||||
onPress={() => props.onProjectChange(null)}
|
||||
subtitle="Show threads from every project"
|
||||
>
|
||||
<NativeHeaderToolbar.Label>All projects</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
{props.projects.map((project) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={project.key}
|
||||
isOn={props.selectedProjectKey === project.key}
|
||||
onPress={() => props.onProjectChange(project.key)}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{project.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
) : null}
|
||||
|
||||
<NativeHeaderToolbar.Menu title="Sort projects">
|
||||
<NativeHeaderToolbar.Label>Sort projects</NativeHeaderToolbar.Label>
|
||||
{PROJECT_SORT_OPTIONS.map((option) => (
|
||||
@@ -456,6 +391,20 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
<NativeHeaderToolbar.Menu title="Group projects">
|
||||
<NativeHeaderToolbar.Label>Group projects</NativeHeaderToolbar.Label>
|
||||
{PROJECT_GROUPING_OPTIONS.map((option) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.projectGroupingMode === option.value}
|
||||
onPress={() => props.onProjectGroupingModeChange(option.value)}
|
||||
subtitle={option.subtitle}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
|
||||
<NativeHeaderToolbar.SearchBarSlot />
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { renderCompactBrandTitle } from "../../components/CompactBrandTitle";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -29,8 +29,7 @@ export function HomeRouteScreen() {
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -54,32 +53,11 @@ export function HomeRouteScreen() {
|
||||
const {
|
||||
options: listOptions,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
} = useHomeListOptions(availableEnvironmentIds);
|
||||
const selectedEnvironmentId = listOptions.selectedEnvironmentId;
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const projectFilterOptions = useMemo(
|
||||
() =>
|
||||
projects
|
||||
.filter(
|
||||
(project) =>
|
||||
selectedEnvironmentId === null || project.environmentId === selectedEnvironmentId,
|
||||
)
|
||||
.map((project) => ({
|
||||
key: scopedProjectKey(project.environmentId, project.id),
|
||||
label: project.title,
|
||||
})),
|
||||
[projects, selectedEnvironmentId],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
selectedProjectKey !== null &&
|
||||
!projectFilterOptions.some((project) => project.key === selectedProjectKey)
|
||||
) {
|
||||
setSelectedProjectKey(null);
|
||||
}
|
||||
}, [projectFilterOptions, selectedProjectKey]);
|
||||
|
||||
// In split layouts the persistent sidebar IS the thread list — Home becomes
|
||||
// an empty detail pane so selecting a thread never transitions layouts.
|
||||
@@ -109,18 +87,19 @@ export function HomeRouteScreen() {
|
||||
>
|
||||
<>
|
||||
{/* Restore the compact title in case the split branch blanked it. */}
|
||||
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
|
||||
<NativeStackScreenOptions
|
||||
options={{ title: "T3 Code", headerTitle: renderCompactBrandTitle }}
|
||||
/>
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
projects={projectFilterOptions}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
selectedProjectKey={selectedProjectKey}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
@@ -135,19 +114,15 @@ export function HomeRouteScreen() {
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onSettleThread={settleThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
// Settled threads are live shells: opening one is plain
|
||||
// navigation, and sending a message un-settles server-side.
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: thread.environmentId,
|
||||
threadId: thread.id,
|
||||
@@ -174,7 +149,6 @@ export function HomeRouteScreen() {
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
selectedProjectKey={selectedProjectKey}
|
||||
threads={threads}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
/>
|
||||
|
||||
@@ -14,20 +14,17 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Platform, Pressable, View } from "react-native";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Platform, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import {
|
||||
PendingTaskListRow,
|
||||
@@ -35,13 +32,6 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "../threads/thread-list-items";
|
||||
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
|
||||
type ThreadListV2Item,
|
||||
} from "../threads/threadListV2";
|
||||
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
|
||||
import {
|
||||
buildHomeListLayout,
|
||||
@@ -52,12 +42,7 @@ import {
|
||||
type HomeGroupDisplayState,
|
||||
type HomeListItem,
|
||||
} from "./homeListItems";
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
type HomeProjectSortOrder,
|
||||
} from "./homeThreadList";
|
||||
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
|
||||
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
|
||||
@@ -73,15 +58,14 @@ interface HomeScreenProps {
|
||||
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onAddConnection: () => void;
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
@@ -89,9 +73,6 @@ interface HomeScreenProps {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** Resolves true iff the settle was dispatched and succeeded. */
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -181,9 +162,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
>(() => new Map());
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled =
|
||||
AsyncResult.isSuccess(preferencesResult) &&
|
||||
preferencesResult.value.threadListV2Enabled === true;
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
@@ -245,51 +223,12 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onScrollBeginDrag: handleScrollBeginDrag,
|
||||
});
|
||||
|
||||
const scopedProject = useMemo(
|
||||
() =>
|
||||
props.selectedProjectKey === null
|
||||
? null
|
||||
: (props.projects.find(
|
||||
(project) =>
|
||||
scopedProjectKey(project.environmentId, project.id) === props.selectedProjectKey &&
|
||||
(props.selectedEnvironmentId === null ||
|
||||
project.environmentId === props.selectedEnvironmentId),
|
||||
) ?? null),
|
||||
[props.projects, props.selectedEnvironmentId, props.selectedProjectKey],
|
||||
);
|
||||
const scopedProjects = useMemo(
|
||||
() => (scopedProject === null ? props.projects : [scopedProject]),
|
||||
[props.projects, scopedProject],
|
||||
);
|
||||
const scopedThreads = useMemo(
|
||||
() =>
|
||||
scopedProject === null
|
||||
? props.threads
|
||||
: props.threads.filter(
|
||||
(thread) =>
|
||||
thread.environmentId === scopedProject.environmentId &&
|
||||
thread.projectId === scopedProject.id,
|
||||
),
|
||||
[props.threads, scopedProject],
|
||||
);
|
||||
const scopedPendingTasks = useMemo(
|
||||
() =>
|
||||
scopedProject === null
|
||||
? props.pendingTasks
|
||||
: props.pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
pendingTask.message.environmentId === scopedProject.environmentId &&
|
||||
pendingTask.creation.projectId === scopedProject.id,
|
||||
),
|
||||
[props.pendingTasks, scopedProject],
|
||||
);
|
||||
|
||||
const projectGroups = useMemo(
|
||||
() =>
|
||||
buildHomeThreadGroups({
|
||||
projects: scopedProjects,
|
||||
threads: scopedThreads,
|
||||
pendingTasks: scopedPendingTasks,
|
||||
projects: props.projects,
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
@@ -297,14 +236,14 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projectGroupingMode,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threadSortOrder,
|
||||
scopedPendingTasks,
|
||||
scopedProjects,
|
||||
scopedThreads,
|
||||
props.threads,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -327,222 +266,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
const projectByKey = useMemo(() => {
|
||||
const map = new Map<string, EnvironmentProject>();
|
||||
for (const project of props.projects) {
|
||||
map.set(scopedProjectKey(project.environmentId, project.id), project);
|
||||
}
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
const v2ProjectScopeKey = props.selectedProjectKey;
|
||||
const v2ScopeProjects = useMemo(
|
||||
() =>
|
||||
sortHomeProjectScopes({
|
||||
scopes: buildHomeProjectScopes({
|
||||
projects: props.projects,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projectGroupingMode,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
],
|
||||
);
|
||||
const v2ScopedProjectGroup = useMemo(
|
||||
() =>
|
||||
v2ProjectScopeKey === null
|
||||
? null
|
||||
: (v2ScopeProjects.find(
|
||||
(scope) =>
|
||||
scope.key === v2ProjectScopeKey ||
|
||||
scope.projectRefs.some(
|
||||
(projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
|
||||
v2ProjectScopeKey,
|
||||
),
|
||||
) ?? null),
|
||||
[v2ProjectScopeKey, v2ScopeProjects],
|
||||
);
|
||||
const v2ScopedProjectKeys = useMemo(
|
||||
() =>
|
||||
v2ScopedProjectGroup === null
|
||||
? null
|
||||
: new Set(
|
||||
v2ScopedProjectGroup.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[v2ScopedProjectGroup],
|
||||
);
|
||||
// Thread List v2 (beta): one flat list in creation order, no grouping.
|
||||
// Settled threads collapse into a recency tail below the card block.
|
||||
// Settled threads stay in the live shell stream (settled ≠ archived), so
|
||||
// the partition works directly off live shells — no snapshot merging or
|
||||
// optimistic holds.
|
||||
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
|
||||
// closed PR auto-settles its thread on the next partition (mirrors web).
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
const handleChangeRequestState = useCallback(
|
||||
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
|
||||
setChangeRequestStateByKey((current) => {
|
||||
if ((current.get(threadKey) ?? null) === state) return current;
|
||||
const next = new Map(current);
|
||||
if (state === null) {
|
||||
next.delete(threadKey);
|
||||
} else {
|
||||
next.set(threadKey, state);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleSettleThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onSettleThread(thread);
|
||||
},
|
||||
[props.onSettleThread],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
// context changes so environment/search flips never inherit a deep page.
|
||||
const [settledVisibleCount, setSettledVisibleCount] = useState(
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
);
|
||||
const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
|
||||
const lastSettledResetKeyRef = useRef(settledResetKey);
|
||||
if (lastSettledResetKeyRef.current !== settledResetKey) {
|
||||
lastSettledResetKeyRef.current = settledResetKey;
|
||||
setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
|
||||
}
|
||||
const showMoreSettled = useCallback(
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
// now is quantized to the minute and ticks so the inactivity auto-settle
|
||||
// boundary is actually crossed while the app stays open (mirrors web);
|
||||
// without a clock dependency the partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
// by the time the beta is switched on, which would misclassify the
|
||||
// inactivity auto-settle boundary until the first tick.
|
||||
setNowMinute(new Date().toISOString().slice(0, 16));
|
||||
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
|
||||
return () => clearInterval(id);
|
||||
}, [threadListV2Enabled]);
|
||||
// Threads on servers without the settlement capability never classify as
|
||||
// settled (the user could neither un-settle nor pin them).
|
||||
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
|
||||
const settlementEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSettlement === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
threads: props.threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
threadListV2Enabled,
|
||||
v2ScopedProjectGroup,
|
||||
]);
|
||||
const threadListV2Items = threadListV2Layout.items;
|
||||
|
||||
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
|
||||
}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(item.thread.environmentId)
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(item.thread.session?.providerInstanceId ?? item.thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
Object.keys(props.savedConnectionsById).length > 1
|
||||
? (props.savedConnectionsById[item.thread.environmentId]?.environmentLabel ?? null)
|
||||
: null
|
||||
}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(item.thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
/>
|
||||
),
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
handleSettleThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onSelectThread,
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback(
|
||||
(item: ThreadListV2Item) => `${item.thread.environmentId}:${item.thread.id}`,
|
||||
[],
|
||||
);
|
||||
|
||||
const extraData = useMemo(
|
||||
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
|
||||
[props.savedConnectionsById, projectCwdByKey],
|
||||
@@ -636,10 +359,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
|
||||
|
||||
/* Empty states */
|
||||
// The signal must ignore the search/environment filters: an active query
|
||||
// that matches nothing needs the in-list "No results" state, not the
|
||||
// full-page "No threads yet". Settled threads are unarchived live shells,
|
||||
// so the v1 check already covers v2.
|
||||
const hasAnyThreads =
|
||||
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
|
||||
const hasResults = projectGroups.length > 0;
|
||||
@@ -669,7 +388,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
className="flex-1 items-center justify-center bg-screen px-8"
|
||||
style={{
|
||||
paddingBottom: Math.max(insets.bottom, 24),
|
||||
paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
|
||||
paddingTop: Platform.OS === "ios" ? insets.top + 72 : 0,
|
||||
}}
|
||||
>
|
||||
<View className="w-full max-w-[430px]">
|
||||
@@ -680,20 +399,11 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||
variant="plain"
|
||||
/>
|
||||
{emptyState.loading && !shouldShowConnectionStatus ? (
|
||||
{emptyState.loading ? (
|
||||
<View className="mt-4 items-center">
|
||||
<ActivityIndicator color={accentColor} />
|
||||
</View>
|
||||
) : null}
|
||||
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
|
||||
<View className="mt-4">
|
||||
<WorkspaceConnectionStatus
|
||||
state={props.catalogState}
|
||||
onPress={props.onOpenEnvironments}
|
||||
variant="sidebar"
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
@@ -716,50 +426,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 listEmpty = !hasResults ? (
|
||||
hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : scopedProject !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${scopedProject.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : selectedEnvironmentLabel ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedEnvironmentLabel}`}
|
||||
@@ -769,73 +438,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
|
||||
)
|
||||
) : null;
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
// v2 project scope, so it can be null (results elsewhere) while this list
|
||||
// is empty. Search outranks the scope — "No results" names the actionable
|
||||
// fact when a query is active. Pending tasks render in the header, so the
|
||||
// list showing them isn't empty in the user's eyes.
|
||||
const v2ListEmpty =
|
||||
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : (
|
||||
listEmpty
|
||||
);
|
||||
|
||||
if (threadListV2Enabled) {
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<SwipeableScrollGateProvider enabled={swipeEnabled}>
|
||||
<FlatList
|
||||
data={threadListV2Items}
|
||||
renderItem={renderV2Item}
|
||||
keyExtractor={v2KeyExtractor}
|
||||
extraData={{
|
||||
projectByKey,
|
||||
serverConfigs,
|
||||
savedConnectionsById: props.savedConnectionsById,
|
||||
}}
|
||||
ListHeaderComponent={v2ListHeader}
|
||||
ListFooterComponent={
|
||||
threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
|
||||
onPress={showMoreSettled}
|
||||
className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-muted">
|
||||
Show more ({threadListV2Layout.hiddenSettledCount} settled hidden)
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null
|
||||
}
|
||||
ListEmptyComponent={v2ListEmpty}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
{...scrollGateHandlers}
|
||||
scrollEventThrottle={16}
|
||||
contentContainerStyle={{
|
||||
paddingBottom:
|
||||
Platform.OS === "ios"
|
||||
? Math.max(insets.bottom, 24) + 96
|
||||
: Math.max(insets.bottom, 16) + 88,
|
||||
}}
|
||||
/>
|
||||
</SwipeableScrollGateProvider>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
@@ -858,8 +460,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
ListHeaderComponent={listHeader}
|
||||
ListEmptyComponent={listEmpty}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
|
||||
contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"}
|
||||
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
|
||||
@@ -67,21 +67,4 @@ describe("workspace connection status", () => {
|
||||
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
|
||||
expect(workspaceConnectionStatusLabel(state)).toBe("Could not reach Julius’s Mac mini");
|
||||
});
|
||||
|
||||
it("shows shell catch-up while cached threads remain visible", () => {
|
||||
const state = workspaceState({ hasPendingShellSnapshot: true });
|
||||
|
||||
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
|
||||
expect(workspaceConnectionStatusLabel(state)).toBe("Syncing threads...");
|
||||
});
|
||||
|
||||
it("distinguishes initial shell loading from cached catch-up", () => {
|
||||
const state = workspaceState({
|
||||
hasLoadedShellSnapshot: false,
|
||||
hasPendingShellSnapshot: true,
|
||||
});
|
||||
|
||||
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
|
||||
expect(workspaceConnectionStatusLabel(state)).toBe("Loading threads...");
|
||||
});
|
||||
});
|
||||
@@ -12,10 +12,7 @@ export function WorkspaceConnectionStatus(props: {
|
||||
readonly variant?: "floating" | "sidebar";
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon-muted");
|
||||
const isSynchronizing =
|
||||
props.state.networkStatus !== "offline" &&
|
||||
props.state.connectionError === null &&
|
||||
(props.state.connectingEnvironments.length > 0 || props.state.hasPendingShellSnapshot);
|
||||
const isReconnecting = props.state.connectingEnvironments.length > 0;
|
||||
const variant = props.variant ?? "floating";
|
||||
|
||||
return (
|
||||
@@ -40,7 +37,7 @@ export function WorkspaceConnectionStatus(props: {
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{isSynchronizing ? (
|
||||
{isReconnecting ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView name="wifi.slash" size={15} tintColor={iconColor} type="monochrome" />
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { buildHomeListFilterMenu } from "./home-list-filter-menu";
|
||||
|
||||
describe("buildHomeListFilterMenu", () => {
|
||||
it("adds a project scope submenu that selects and clears the same scope as the chips", () => {
|
||||
const onProjectChange = vi.fn();
|
||||
const menu = buildHomeListFilterMenu({
|
||||
environments: [],
|
||||
projects: [
|
||||
{ key: "environment-1:project-1", label: "Codething" },
|
||||
{ key: "environment-1:project-2", label: "Website" },
|
||||
],
|
||||
selectedEnvironmentId: null,
|
||||
selectedProjectKey: "environment-1:project-1",
|
||||
projectSortOrder: "updated_at",
|
||||
threadSortOrder: "updated_at",
|
||||
onEnvironmentChange: vi.fn(),
|
||||
onProjectChange,
|
||||
onProjectSortOrderChange: vi.fn(),
|
||||
onThreadSortOrderChange: vi.fn(),
|
||||
});
|
||||
|
||||
const projectMenu = menu.items.find(
|
||||
(item) => item.type === "submenu" && item.title === "Project",
|
||||
);
|
||||
expect(projectMenu).toMatchObject({
|
||||
type: "submenu",
|
||||
items: [
|
||||
{ title: "All projects", state: "off" },
|
||||
{ title: "Codething", state: "on" },
|
||||
{ title: "Website", state: "off" },
|
||||
],
|
||||
});
|
||||
if (projectMenu?.type !== "submenu") throw new Error("Expected project submenu");
|
||||
|
||||
projectMenu.items[0]?.onPress();
|
||||
projectMenu.items[2]?.onPress();
|
||||
expect(onProjectChange).toHaveBeenNthCalledWith(1, null);
|
||||
expect(onProjectChange).toHaveBeenNthCalledWith(2, "environment-1:project-2");
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,21 @@
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
import { PROJECT_SORT_OPTIONS, THREAD_SORT_OPTIONS } from "./home-list-options";
|
||||
import {
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
} from "./home-list-options";
|
||||
|
||||
export interface HomeListFilterMenuEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
export interface HomeListFilterMenuProject {
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
type HomeListFilterMenuAction = {
|
||||
readonly type: "action";
|
||||
readonly title: string;
|
||||
@@ -34,20 +37,15 @@ export interface HomeListFilterMenu {
|
||||
|
||||
export function buildHomeListFilterMenu(props: {
|
||||
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
|
||||
readonly projects: ReadonlyArray<HomeListFilterMenuProject>;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onOpenSettings?: () => void;
|
||||
/** False hides the sort/group submenus. Thread List v2 uses a fixed
|
||||
creation-order layout, so offering those controls while it silently
|
||||
ignores them would be a lie; the environment filter still applies. */
|
||||
readonly listOrganization?: boolean;
|
||||
}): HomeListFilterMenu {
|
||||
const items: Array<HomeListFilterMenuAction | HomeListFilterMenuSubmenu> = [];
|
||||
|
||||
@@ -59,75 +57,61 @@ export function buildHomeListFilterMenu(props: {
|
||||
});
|
||||
}
|
||||
|
||||
items.push({
|
||||
type: "submenu",
|
||||
title: "Environment",
|
||||
items: [
|
||||
{
|
||||
type: "action",
|
||||
title: "All environments",
|
||||
subtitle: "Show threads from every environment",
|
||||
state: props.selectedEnvironmentId === null ? "on" : "off",
|
||||
onPress: () => props.onEnvironmentChange(null),
|
||||
},
|
||||
...props.environments.map((environment) => ({
|
||||
type: "action" as const,
|
||||
title: environment.label,
|
||||
state:
|
||||
props.selectedEnvironmentId === environment.environmentId
|
||||
? ("on" as const)
|
||||
: ("off" as const),
|
||||
onPress: () => props.onEnvironmentChange(environment.environmentId),
|
||||
})),
|
||||
],
|
||||
});
|
||||
|
||||
if (props.projects.length > 0) {
|
||||
items.push({
|
||||
items.push(
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Project",
|
||||
title: "Environment",
|
||||
items: [
|
||||
{
|
||||
type: "action",
|
||||
title: "All projects",
|
||||
subtitle: "Show threads from every project",
|
||||
state: props.selectedProjectKey === null ? "on" : "off",
|
||||
onPress: () => props.onProjectChange(null),
|
||||
title: "All environments",
|
||||
subtitle: "Show threads from every environment",
|
||||
state: props.selectedEnvironmentId === null ? "on" : "off",
|
||||
onPress: () => props.onEnvironmentChange(null),
|
||||
},
|
||||
...props.projects.map((project) => ({
|
||||
...props.environments.map((environment) => ({
|
||||
type: "action" as const,
|
||||
title: project.label,
|
||||
state: props.selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
|
||||
onPress: () => props.onProjectChange(project.key),
|
||||
title: environment.label,
|
||||
state:
|
||||
props.selectedEnvironmentId === environment.environmentId
|
||||
? ("on" as const)
|
||||
: ("off" as const),
|
||||
onPress: () => props.onEnvironmentChange(environment.environmentId),
|
||||
})),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
if (props.listOrganization !== false) {
|
||||
items.push(
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Sort projects",
|
||||
items: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
state: props.projectSortOrder === option.value ? "on" : "off",
|
||||
onPress: () => props.onProjectSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Sort threads",
|
||||
items: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
state: props.threadSortOrder === option.value ? "on" : "off",
|
||||
onPress: () => props.onThreadSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Sort projects",
|
||||
items: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
state: props.projectSortOrder === option.value ? "on" : "off",
|
||||
onPress: () => props.onProjectSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Sort threads",
|
||||
items: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
state: props.threadSortOrder === option.value ? "on" : "off",
|
||||
onPress: () => props.onThreadSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Group projects",
|
||||
items: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
subtitle: option.subtitle,
|
||||
state: props.projectGroupingMode === option.value ? "on" : "off",
|
||||
onPress: () => props.onProjectGroupingModeChange(option.value),
|
||||
})),
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
title: "Thread list options",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -13,6 +14,7 @@ const defaults: HomeListOptions = {
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
};
|
||||
|
||||
describe("home list options", () => {
|
||||
@@ -20,12 +22,10 @@ describe("home list options", () => {
|
||||
expect(hasCustomHomeListOptions(defaults)).toBe(false);
|
||||
});
|
||||
|
||||
it("marks environment filters as customized", () => {
|
||||
it("marks environment filters and grouping changes as customized", () => {
|
||||
expect(
|
||||
hasCustomHomeListOptions({ ...defaults, selectedEnvironmentId: "environment-1" as never }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
hasCustomHomeListOptions({ ...defaults, selectedProjectKey: "environment-1:project-1" }),
|
||||
).toBe(true);
|
||||
expect(hasCustomHomeListOptions({ ...defaults, projectGroupingMode: "separate" })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -25,18 +26,9 @@ export interface HomeListOptions {
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
}
|
||||
|
||||
export interface ResolvedHomeListOptions extends HomeListOptions {
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
export function resolveProjectGroupingMode(
|
||||
projectGroupingEnabled: boolean | undefined,
|
||||
): SidebarProjectGroupingMode {
|
||||
return projectGroupingEnabled === false ? "separate" : "repository";
|
||||
}
|
||||
|
||||
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
|
||||
readonly value: HomeProjectSortOrder;
|
||||
readonly label: string;
|
||||
@@ -53,6 +45,28 @@ export const THREAD_SORT_OPTIONS: ReadonlyArray<{
|
||||
{ value: "created_at", label: "Created at" },
|
||||
];
|
||||
|
||||
export const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{
|
||||
readonly value: SidebarProjectGroupingMode;
|
||||
readonly label: string;
|
||||
readonly subtitle: string;
|
||||
}> = [
|
||||
{
|
||||
value: "repository",
|
||||
label: "Group by repository",
|
||||
subtitle: "Combine matching repositories across environments",
|
||||
},
|
||||
{
|
||||
value: "repository_path",
|
||||
label: "Group by repository path",
|
||||
subtitle: "Combine only matching paths within a repository",
|
||||
},
|
||||
{
|
||||
value: "separate",
|
||||
label: "Keep separate",
|
||||
subtitle: "Show every project path separately",
|
||||
},
|
||||
];
|
||||
|
||||
function defaultHomeListOptions(): HomeListOptions {
|
||||
return {
|
||||
selectedEnvironmentId: null,
|
||||
@@ -61,44 +75,34 @@ function defaultHomeListOptions(): HomeListOptions {
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
};
|
||||
}
|
||||
|
||||
interface HomeListOptionsContextValue {
|
||||
readonly options: HomeListOptions;
|
||||
readonly setOptions: Dispatch<SetStateAction<HomeListOptions>>;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
const HomeListOptionsContext = createContext<HomeListOptionsContextValue | null>(null);
|
||||
|
||||
/** Keeps list preferences stable while the app moves between compact and split shells. */
|
||||
export function HomeListOptionsProvider({
|
||||
children,
|
||||
projectGroupingMode,
|
||||
}: PropsWithChildren<{ readonly projectGroupingMode: SidebarProjectGroupingMode }>) {
|
||||
export function HomeListOptionsProvider({ children }: PropsWithChildren) {
|
||||
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
|
||||
const value = useMemo(
|
||||
() => ({ options, setOptions, projectGroupingMode }),
|
||||
[options, projectGroupingMode],
|
||||
);
|
||||
const value = useMemo(() => ({ options, setOptions }), [options]);
|
||||
return createElement(HomeListOptionsContext, { value }, children);
|
||||
}
|
||||
|
||||
export function hasCustomHomeListOptions(
|
||||
options: HomeListOptions & {
|
||||
readonly selectedProjectKey?: string | null;
|
||||
},
|
||||
): boolean {
|
||||
export function hasCustomHomeListOptions(options: HomeListOptions): boolean {
|
||||
const defaultProjectSortOrder =
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER;
|
||||
return (
|
||||
options.selectedEnvironmentId !== null ||
|
||||
(options.selectedProjectKey !== null && options.selectedProjectKey !== undefined) ||
|
||||
options.projectSortOrder !== defaultProjectSortOrder ||
|
||||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER
|
||||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
|
||||
options.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE
|
||||
);
|
||||
}
|
||||
|
||||
@@ -112,14 +116,10 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
|
||||
availableEnvironmentIds.has(options.selectedEnvironmentId)
|
||||
? options.selectedEnvironmentId
|
||||
: null;
|
||||
const availableOptions =
|
||||
const resolvedOptions =
|
||||
selectedEnvironmentId === options.selectedEnvironmentId
|
||||
? options
|
||||
: { ...options, selectedEnvironmentId };
|
||||
const resolvedOptions: ResolvedHomeListOptions = {
|
||||
...availableOptions,
|
||||
projectGroupingMode: shared?.projectGroupingMode ?? "repository",
|
||||
};
|
||||
|
||||
const setSelectedEnvironmentId = useCallback((value: EnvironmentId | null) => {
|
||||
setOptions((current) => ({ ...current, selectedEnvironmentId: value }));
|
||||
@@ -130,10 +130,15 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
|
||||
const setThreadSortOrder = useCallback((value: SidebarThreadSortOrder) => {
|
||||
setOptions((current) => ({ ...current, threadSortOrder: value }));
|
||||
}, []);
|
||||
const setProjectGroupingMode = useCallback((value: SidebarProjectGroupingMode) => {
|
||||
setOptions((current) => ({ ...current, projectGroupingMode: value }));
|
||||
}, []);
|
||||
|
||||
return {
|
||||
options: resolvedOptions,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
setProjectGroupingMode,
|
||||
} as const;
|
||||
}
|
||||
@@ -47,8 +47,6 @@ function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -5,11 +5,7 @@ import type {
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
} from "./homeThreadList";
|
||||
import { buildHomeThreadGroups } from "./homeThreadList";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -45,8 +41,6 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -71,308 +65,6 @@ function buildGroups(
|
||||
}
|
||||
|
||||
describe("buildHomeThreadGroups", () => {
|
||||
it("builds one v2 scope for the same repository across environments", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-local"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
];
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.projects).toEqual(projects);
|
||||
expect(scopes[0]?.projectRefs).toEqual(
|
||||
projects.map((project) => ({
|
||||
environmentId: project.environmentId,
|
||||
projectId: project.id,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
it("routes stale duplicate project refs through the canonical repository group", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const local = makeProject({
|
||||
id: ProjectId.make("project-local"),
|
||||
environmentId: localEnvironmentId,
|
||||
title: "t3code",
|
||||
workspaceRoot: "/workspaces/t3code",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const stale = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-stale"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
});
|
||||
const canonicalRemote = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-canonical-remote"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code/",
|
||||
repositoryIdentity,
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const projects = [local, stale, canonicalRemote];
|
||||
const staleThread = makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ThreadId.make("thread-stale-project-ref"),
|
||||
projectId: stale.id,
|
||||
title: "Still visible",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
const groups = buildGroups(projects, [staleThread]);
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.projects.map((project) => project.id)).toEqual([
|
||||
local.id,
|
||||
canonicalRemote.id,
|
||||
]);
|
||||
expect(scopes[0]?.projectRefs.map((projectRef) => projectRef.projectId)).toEqual([
|
||||
local.id,
|
||||
stale.id,
|
||||
canonicalRemote.id,
|
||||
]);
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.threads.map((thread) => thread.id)).toEqual([staleThread.id]);
|
||||
expect(groups[0]?.newThreadTarget?.id).toBe(canonicalRemote.id);
|
||||
});
|
||||
|
||||
it("keeps repository identity from an older duplicate when the freshness winner lacks it", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-local"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote-with-identity"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code",
|
||||
repositoryIdentity,
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote-fresh"),
|
||||
title: "t3code",
|
||||
workspaceRoot: "/remote/t3code/",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(scopes).toHaveLength(1);
|
||||
expect(scopes[0]?.representative.id).toBe(ProjectId.make("project-local"));
|
||||
expect(scopes[0]?.projects.map((project) => project.id)).toContain(
|
||||
ProjectId.make("project-remote-fresh"),
|
||||
);
|
||||
expect(scopes[0]?.projectRefs).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("sorts v2 project scopes by their grouped thread activity", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const olderProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-older"),
|
||||
title: "Older project",
|
||||
});
|
||||
const newerProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-newer"),
|
||||
title: "Newer project",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [newerProject, olderProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "separate",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("thread-older-project"),
|
||||
projectId: olderProject.id,
|
||||
title: "Most recently active",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("thread-newer-project"),
|
||||
projectId: newerProject.id,
|
||||
title: "Less recently active",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "updated_at",
|
||||
}).map((scope) => scope.representative.id),
|
||||
).toEqual([olderProject.id, newerProject.id]);
|
||||
});
|
||||
|
||||
it("sorts invalid project creation timestamps after valid ones", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const invalidProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-invalid"),
|
||||
title: "A invalid timestamp",
|
||||
createdAt: "invalid",
|
||||
});
|
||||
const validProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-valid"),
|
||||
title: "Z valid timestamp",
|
||||
createdAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [invalidProject, validProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "separate",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "created_at",
|
||||
}).map((scope) => scope.representative.id),
|
||||
).toEqual([validProject.id, invalidProject.id]);
|
||||
});
|
||||
|
||||
it("uses the freshest member when a grouped scope has no activity", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const olderMember = makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-older-member"),
|
||||
title: "t3code",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const newerMember = makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-newer-member"),
|
||||
title: "t3code",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const otherProject = makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-other"),
|
||||
title: "other",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
});
|
||||
const scopes = buildHomeProjectScopes({
|
||||
projects: [olderMember, newerMember, otherProject],
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
});
|
||||
|
||||
expect(
|
||||
sortHomeProjectScopes({
|
||||
scopes,
|
||||
threads: [],
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "updated_at",
|
||||
})[0]?.key,
|
||||
).toBe(scopes.find((scope) => scope.projects.length === 2)?.key);
|
||||
});
|
||||
|
||||
it("does not merge unrelated repositories that share a title", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const projects = ["one", "two"].map((name) =>
|
||||
makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make(`project-${name}`),
|
||||
title: "app",
|
||||
repositoryIdentity: {
|
||||
canonicalKey: `github.com/example/${name}`,
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: `[email protected]:example/${name}.git`,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: "repository",
|
||||
}),
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("sorts the newest thread first regardless of snapshot order", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const project = makeProject({
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
import {
|
||||
deriveLogicalProjectKey,
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupLabel,
|
||||
} from "@t3tools/client-runtime/state/project-grouping";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
getThreadSortTimestamp,
|
||||
sortThreads,
|
||||
toSortableTimestamp,
|
||||
} from "@t3tools/client-runtime/state/thread-sort";
|
||||
import { getThreadSortTimestamp, sortThreads } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ScopedProjectRef,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarProjectSortOrder,
|
||||
SidebarThreadSortOrder,
|
||||
@@ -28,164 +22,6 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
|
||||
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
|
||||
|
||||
export interface HomeProjectScope {
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly representative: EnvironmentProject;
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
|
||||
}
|
||||
|
||||
function getProjectFreshnessTimestamp(project: EnvironmentProject): number {
|
||||
return toSortableTimestamp(project.updatedAt) ?? toSortableTimestamp(project.createdAt) ?? 0;
|
||||
}
|
||||
|
||||
function getProjectSortTimestamp(
|
||||
project: EnvironmentProject,
|
||||
sortOrder: HomeProjectSortOrder,
|
||||
): number {
|
||||
return sortOrder === "created_at"
|
||||
? (toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY)
|
||||
: (toSortableTimestamp(project.updatedAt) ??
|
||||
toSortableTimestamp(project.createdAt) ??
|
||||
Number.NEGATIVE_INFINITY);
|
||||
}
|
||||
|
||||
export function buildHomeProjectScopes(input: {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}): ReadonlyArray<HomeProjectScope> {
|
||||
const projects = input.projects.filter(
|
||||
(project) => input.environmentId === null || project.environmentId === input.environmentId,
|
||||
);
|
||||
const projectsByPhysicalKey = new Map<string, EnvironmentProject[]>();
|
||||
for (const project of projects) {
|
||||
const physicalKey = derivePhysicalProjectKey(project);
|
||||
const existing = projectsByPhysicalKey.get(physicalKey);
|
||||
if (existing) existing.push(project);
|
||||
else projectsByPhysicalKey.set(physicalKey, [project]);
|
||||
}
|
||||
|
||||
const winnersByPhysicalKey = new Map<
|
||||
string,
|
||||
{ readonly key: string; readonly project: EnvironmentProject }
|
||||
>();
|
||||
for (const [physicalKey, members] of projectsByPhysicalKey) {
|
||||
const project = members.reduce((winner, candidate) => {
|
||||
const freshnessDelta =
|
||||
getProjectFreshnessTimestamp(candidate) - getProjectFreshnessTimestamp(winner);
|
||||
return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > winner.id)
|
||||
? candidate
|
||||
: winner;
|
||||
});
|
||||
const identitySource = members.find((member) => member.repositoryIdentity !== null) ?? project;
|
||||
winnersByPhysicalKey.set(physicalKey, {
|
||||
key: deriveLogicalProjectKey(identitySource, { groupingMode: input.projectGroupingMode }),
|
||||
project,
|
||||
});
|
||||
}
|
||||
|
||||
const groups = new Map<string, EnvironmentProject[]>();
|
||||
for (const { key, project } of winnersByPhysicalKey.values()) {
|
||||
const existing = groups.get(key);
|
||||
if (existing) existing.push(project);
|
||||
else groups.set(key, [project]);
|
||||
}
|
||||
|
||||
const projectRefsByGroup = new Map<string, ScopedProjectRef[]>();
|
||||
const seenProjectRefs = new Set<string>();
|
||||
for (const project of projects) {
|
||||
const refKey = scopedProjectKey(project.environmentId, project.id);
|
||||
if (seenProjectRefs.has(refKey)) continue;
|
||||
seenProjectRefs.add(refKey);
|
||||
|
||||
const key =
|
||||
winnersByPhysicalKey.get(derivePhysicalProjectKey(project))?.key ??
|
||||
deriveLogicalProjectKey(project, { groupingMode: input.projectGroupingMode });
|
||||
const refs = projectRefsByGroup.get(key);
|
||||
const projectRef = { environmentId: project.environmentId, projectId: project.id };
|
||||
if (refs) refs.push(projectRef);
|
||||
else projectRefsByGroup.set(key, [projectRef]);
|
||||
}
|
||||
|
||||
return Array.from(groups, ([key, projects]) => {
|
||||
const representative = projects[0]!;
|
||||
return {
|
||||
key,
|
||||
title:
|
||||
projects.length > 1
|
||||
? deriveProjectGroupLabel({ representative, members: projects })
|
||||
: representative.title,
|
||||
representative,
|
||||
projects,
|
||||
projectRefs: projectRefsByGroup.get(key) ?? [],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function sortHomeProjectScopes(input: {
|
||||
readonly scopes: ReadonlyArray<HomeProjectScope>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
}): ReadonlyArray<HomeProjectScope> {
|
||||
const scopeKeyByProjectRef = new Map(
|
||||
input.scopes.flatMap((scope) =>
|
||||
scope.projectRefs.map(
|
||||
(projectRef) =>
|
||||
[scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.key] as const,
|
||||
),
|
||||
),
|
||||
);
|
||||
const latestActivityByScope = new Map<string, number>();
|
||||
const recordActivity = (scopeKey: string | undefined, timestamp: number) => {
|
||||
if (!scopeKey || !Number.isFinite(timestamp)) return;
|
||||
latestActivityByScope.set(
|
||||
scopeKey,
|
||||
Math.max(latestActivityByScope.get(scopeKey) ?? Number.NEGATIVE_INFINITY, timestamp),
|
||||
);
|
||||
};
|
||||
|
||||
for (const thread of input.threads) {
|
||||
if (thread.archivedAt !== null) continue;
|
||||
recordActivity(
|
||||
scopeKeyByProjectRef.get(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
getThreadSortTimestamp(thread, input.projectSortOrder),
|
||||
);
|
||||
}
|
||||
for (const pendingTask of input.pendingTasks) {
|
||||
recordActivity(
|
||||
scopeKeyByProjectRef.get(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
Date.parse(pendingTask.message.createdAt),
|
||||
);
|
||||
}
|
||||
|
||||
return Arr.sort(
|
||||
input.scopes,
|
||||
Order.mapInput(
|
||||
Order.Struct({
|
||||
timestamp: Order.flip(Order.Number),
|
||||
title: Order.String,
|
||||
key: Order.String,
|
||||
}),
|
||||
(scope: HomeProjectScope) => ({
|
||||
timestamp:
|
||||
latestActivityByScope.get(scope.key) ??
|
||||
Math.max(
|
||||
...scope.projects.map((project) =>
|
||||
getProjectSortTimestamp(project, input.projectSortOrder),
|
||||
),
|
||||
),
|
||||
title: scope.title,
|
||||
key: scope.key,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Default home view only surfaces threads active within this window, to keep the
|
||||
* screen compact while keeping recent work visible.
|
||||
@@ -267,18 +103,22 @@ export function buildHomeThreadGroups(input: {
|
||||
const groups = new Map<string, MutableHomeThreadGroup>();
|
||||
const groupKeyByProjectKey = new Map<string, string>();
|
||||
|
||||
for (const scope of buildHomeProjectScopes(input)) {
|
||||
groups.set(scope.key, {
|
||||
key: scope.key,
|
||||
projects: [...scope.projects],
|
||||
pendingTasks: [],
|
||||
threads: [],
|
||||
for (const project of input.projects) {
|
||||
if (input.environmentId !== null && project.environmentId !== input.environmentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const groupKey = deriveLogicalProjectKey(project, {
|
||||
groupingMode: input.projectGroupingMode,
|
||||
});
|
||||
for (const projectRef of scope.projectRefs) {
|
||||
groupKeyByProjectKey.set(
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
scope.key,
|
||||
);
|
||||
const physicalKey = scopedProjectKey(project.environmentId, project.id);
|
||||
groupKeyByProjectKey.set(physicalKey, groupKey);
|
||||
|
||||
const existing = groups.get(groupKey);
|
||||
if (existing) {
|
||||
existing.projects.push(project);
|
||||
} else {
|
||||
groups.set(groupKey, { key: groupKey, projects: [project], pendingTasks: [], threads: [] });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,21 +215,19 @@ export function buildHomeThreadGroups(input: {
|
||||
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
|
||||
: sortedThreads;
|
||||
|
||||
// A stale project id still resolves to the canonical member with the same
|
||||
// environment/path, so quick creation follows the machine with the newest activity.
|
||||
const lastActiveProject = Arr.head(sortedThreads).pipe(
|
||||
Option.flatMap((thread) =>
|
||||
Arr.findFirst(
|
||||
input.projects,
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
// Sorted newest-first, so the first thread whose project is a group member
|
||||
// marks the machine the user last worked on.
|
||||
const lastActiveProject = Arr.findFirst(sortedThreads, (thread) =>
|
||||
group.projects.some(
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
Option.flatMap((threadProject) =>
|
||||
).pipe(
|
||||
Option.flatMap((thread) =>
|
||||
Arr.findFirst(
|
||||
group.projects,
|
||||
(project) =>
|
||||
derivePhysicalProjectKey(project) === derivePhysicalProjectKey(threadProject),
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
),
|
||||
Option.getOrNull,
|
||||
|
||||
@@ -36,8 +36,6 @@ import { AppText as Text } from "../../components/AppText";
|
||||
const ACTION_ITEM_WIDTH = 58;
|
||||
const ACTION_CIRCLE_SIZE = 36;
|
||||
const ACTION_ICON_SIZE = 15;
|
||||
const COMPACT_ACTION_CIRCLE_SIZE = 28;
|
||||
const COMPACT_ACTION_ICON_SIZE = 13;
|
||||
|
||||
export const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2;
|
||||
export const THREAD_SWIPE_SPRING = {
|
||||
@@ -165,20 +163,10 @@ export function useSwipeableScrollGate(options?: {
|
||||
export function ThreadSwipeable(props: {
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly children: (close: () => void) => ReactNode;
|
||||
/** Uses action visuals that fit inside compact 44pt rows. The press target
|
||||
* still spans the row's full height and width. */
|
||||
readonly compactActions?: boolean;
|
||||
readonly containerStyle?: StyleProp<ViewStyle>;
|
||||
/** Disables NEW swipe activations (e.g. while the list scrolls). */
|
||||
readonly enabled?: boolean;
|
||||
readonly enableTrackpadSwipe?: boolean;
|
||||
/**
|
||||
* What a full swipe commits: "delete" (default, v1 behavior — the Delete
|
||||
* button stretches) or "primary" — the advertised primary action fires and
|
||||
* its button stretches instead. A full swipe must always match the action
|
||||
* the stretching button advertises.
|
||||
*/
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeWidth: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
|
||||
@@ -251,11 +239,7 @@ export function ThreadSwipeable(props: {
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
if (props.fullSwipeAction === "primary") {
|
||||
props.primaryAction.onPress();
|
||||
} else {
|
||||
props.onDelete();
|
||||
}
|
||||
props.onDelete();
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
@@ -263,8 +247,6 @@ export function ThreadSwipeable(props: {
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={props.backgroundColor}
|
||||
compact={props.compactActions === true}
|
||||
fullSwipeAction={props.fullSwipeAction ?? "delete"}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
@@ -291,7 +273,6 @@ export function ThreadSwipeable(props: {
|
||||
function SwipeActionButton(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly backgroundColor: string;
|
||||
readonly compact: boolean;
|
||||
readonly entryRange: readonly [number, number];
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
@@ -300,8 +281,6 @@ function SwipeActionButton(props: {
|
||||
readonly stretchesOnFullSwipe: boolean;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const circleSize = props.compact ? COMPACT_ACTION_CIRCLE_SIZE : ACTION_CIRCLE_SIZE;
|
||||
const iconSize = props.compact ? COMPACT_ACTION_ICON_SIZE : ACTION_ICON_SIZE;
|
||||
const actionStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
|
||||
@@ -333,7 +312,7 @@ function SwipeActionButton(props: {
|
||||
|
||||
return {
|
||||
transform: [{ translateX: -stretch }],
|
||||
width: circleSize + stretch,
|
||||
width: ACTION_CIRCLE_SIZE + stretch,
|
||||
};
|
||||
});
|
||||
const iconStyle = useAnimatedStyle(() => {
|
||||
@@ -395,13 +374,13 @@ function SwipeActionButton(props: {
|
||||
width: "100%",
|
||||
})}
|
||||
>
|
||||
<View style={{ height: circleSize, width: circleSize }}>
|
||||
<View style={{ height: ACTION_CIRCLE_SIZE, width: ACTION_CIRCLE_SIZE }}>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
backgroundColor: props.backgroundColor,
|
||||
borderRadius: 999,
|
||||
height: circleSize,
|
||||
height: ACTION_CIRCLE_SIZE,
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
@@ -413,25 +392,25 @@ function SwipeActionButton(props: {
|
||||
style={[
|
||||
{
|
||||
alignItems: "center",
|
||||
height: circleSize,
|
||||
height: ACTION_CIRCLE_SIZE,
|
||||
justifyContent: "center",
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
width: circleSize,
|
||||
width: ACTION_CIRCLE_SIZE,
|
||||
},
|
||||
iconStyle,
|
||||
]}
|
||||
>
|
||||
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
|
||||
<SymbolView
|
||||
name={props.icon}
|
||||
size={ACTION_ICON_SIZE}
|
||||
tintColor="#ffffff"
|
||||
type="monochrome"
|
||||
/>
|
||||
</Animated.View>
|
||||
</View>
|
||||
<Animated.View
|
||||
style={[
|
||||
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
|
||||
labelStyle,
|
||||
]}
|
||||
>
|
||||
<Animated.View style={[{ paddingTop: 2 }, labelStyle]}>
|
||||
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
|
||||
{props.label}
|
||||
</Text>
|
||||
@@ -443,8 +422,6 @@ function SwipeActionButton(props: {
|
||||
|
||||
export function ThreadSwipeActions(props: {
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly compact: boolean;
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onFullSwipeArmedChange: (armed: boolean) => void;
|
||||
@@ -453,7 +430,6 @@ export function ThreadSwipeActions(props: {
|
||||
readonly threadTitle: string;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const fullSwipeIsPrimary = props.fullSwipeAction === "primary";
|
||||
useAnimatedReaction(
|
||||
() => -props.translation.value >= props.fullSwipeThreshold,
|
||||
(armed, previous) => {
|
||||
@@ -476,19 +452,17 @@ export function ThreadSwipeActions(props: {
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={props.primaryAction.accessibilityLabel}
|
||||
backgroundColor="#007aff"
|
||||
compact={props.compact}
|
||||
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon={props.primaryAction.icon}
|
||||
label={props.primaryAction.label}
|
||||
onPress={props.primaryAction.onPress}
|
||||
stretchesOnFullSwipe={fullSwipeIsPrimary}
|
||||
stretchesOnFullSwipe={false}
|
||||
translation={props.translation}
|
||||
/>
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={`Delete ${props.threadTitle}`}
|
||||
backgroundColor="#ff2d55"
|
||||
compact={props.compact}
|
||||
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon="trash"
|
||||
@@ -497,7 +471,7 @@ export function ThreadSwipeActions(props: {
|
||||
props.swipeableMethods.close();
|
||||
props.onDelete();
|
||||
}}
|
||||
stretchesOnFullSwipe={!fullSwipeIsPrimary}
|
||||
stretchesOnFullSwipe
|
||||
translation={props.translation}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useCallback, useRef } from "react";
|
||||
@@ -7,37 +6,19 @@ import { Alert } from "react-native";
|
||||
|
||||
import { showConfirmDialog } from "../../components/ConfirmDialogHost";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreadSnapshots";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
|
||||
/** Version skew: never send settle/unsettle to a server that predates them
|
||||
(capability defaults false on decode for older servers). */
|
||||
function environmentSupportsSettlement(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadSettlement === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
archive: "archived",
|
||||
unarchive: "unarchived",
|
||||
delete: "deleted",
|
||||
settle: "settled",
|
||||
unsettle: "un-settled",
|
||||
};
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete";
|
||||
|
||||
function actionFailureMessage(action: ThreadListAction, cause: Cause.Cause<unknown>): string {
|
||||
const error = Cause.squash(cause);
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
return `The thread could not be ${ACTION_VERBS[action]}.`;
|
||||
const verb =
|
||||
action === "archive" ? "archived" : action === "unarchive" ? "unarchived" : "deleted";
|
||||
return `The thread could not be ${verb}.`;
|
||||
}
|
||||
|
||||
function selectionHaptic(): void {
|
||||
@@ -47,115 +28,54 @@ function selectionHaptic(): void {
|
||||
function actionFailureTitle(action: ThreadListAction): string {
|
||||
if (action === "archive") return "Could not archive thread";
|
||||
if (action === "unarchive") return "Could not unarchive thread";
|
||||
if (action === "settle") return "Could not settle thread";
|
||||
if (action === "unsettle") return "Could not un-settle thread";
|
||||
return "Could not delete thread";
|
||||
}
|
||||
|
||||
/** Resolves to true iff the action was dispatched and succeeded. */
|
||||
function useThreadActionExecutor(
|
||||
onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
|
||||
) {
|
||||
const archiveMutation = useAtomCommand(threadEnvironment.archive, { reportFailure: false });
|
||||
const unarchiveMutation = useAtomCommand(threadEnvironment.unarchive, { reportFailure: false });
|
||||
const deleteMutation = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
|
||||
const settleMutation = useAtomCommand(threadEnvironment.settle, { reportFailure: false });
|
||||
const unsettleMutation = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });
|
||||
const inFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const executeAction = useCallback(
|
||||
async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (inFlightThreadKeys.current.has(key)) {
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
|
||||
inFlightThreadKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
if (
|
||||
(action === "settle" || action === "unsettle") &&
|
||||
!environmentSupportsSettlement(thread.environmentId)
|
||||
) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This environment's server does not support settling yet. Update the server to use Settle.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Settle may only target what effectiveSettled could classify as
|
||||
// settled: not starting/running sessions, not threads waiting on
|
||||
// approvals or user input. Anything else would hide live work.
|
||||
if (action === "settle" && !canSettle(thread, { now: new Date().toISOString() })) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread still needs attention. Resolve or interrupt it first, then try again.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Archive keeps its original, narrower guard: never interrupt a
|
||||
// thread mid-turn.
|
||||
if (
|
||||
action === "archive" &&
|
||||
thread.session?.status === "running" &&
|
||||
thread.session.activeTurnId != null
|
||||
) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread is working. Interrupt it first, then try again.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const result =
|
||||
action === "unsettle"
|
||||
? // reason "user" pins the thread active: auto-settle stays
|
||||
// suppressed until real activity clears the pin server-side.
|
||||
await unsettleMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, reason: "user" },
|
||||
})
|
||||
: await (
|
||||
action === "settle"
|
||||
? settleMutation
|
||||
: action === "archive"
|
||||
? archiveMutation
|
||||
: action === "unarchive"
|
||||
? unarchiveMutation
|
||||
: deleteMutation
|
||||
)({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
const mutation =
|
||||
action === "archive"
|
||||
? archiveMutation
|
||||
: action === "unarchive"
|
||||
? unarchiveMutation
|
||||
: deleteMutation;
|
||||
const result = await mutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
Alert.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
|
||||
return false;
|
||||
}
|
||||
// Settled threads stay in the live shell stream; only the archive
|
||||
// lifecycle still feeds the archived-snapshot surface.
|
||||
if (action === "archive" || action === "unarchive" || action === "delete") {
|
||||
refreshArchivedThreadsForEnvironment(thread.environmentId);
|
||||
return;
|
||||
}
|
||||
onCompleted?.(action, thread);
|
||||
return true;
|
||||
} finally {
|
||||
inFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[
|
||||
archiveMutation,
|
||||
deleteMutation,
|
||||
onCompleted,
|
||||
settleMutation,
|
||||
unarchiveMutation,
|
||||
unsettleMutation,
|
||||
],
|
||||
[archiveMutation, deleteMutation, onCompleted, unarchiveMutation],
|
||||
);
|
||||
|
||||
return executeAction;
|
||||
}
|
||||
|
||||
function useConfirmDeleteThread(
|
||||
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<boolean>,
|
||||
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<void>,
|
||||
) {
|
||||
return useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -191,8 +111,6 @@ function useConfirmDeleteThread(
|
||||
export function useThreadListActions(): {
|
||||
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
|
||||
@@ -202,18 +120,10 @@ export function useThreadListActions(): {
|
||||
},
|
||||
[executeAction],
|
||||
);
|
||||
const settleThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
const unsettleThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
return { archiveThread, confirmDeleteThread, settleThread, unsettleThread };
|
||||
return { archiveThread, confirmDeleteThread };
|
||||
}
|
||||
|
||||
export function useArchivedThreadListActions(
|
||||
|
||||
@@ -5,7 +5,6 @@ export function shouldShowWorkspaceConnectionStatus(state: WorkspaceState): bool
|
||||
state.networkStatus === "offline" ||
|
||||
state.connectionError !== null ||
|
||||
state.hasConnectingEnvironment ||
|
||||
state.hasPendingShellSnapshot ||
|
||||
(state.hasLoadedShellSnapshot && !state.hasReadyEnvironment)
|
||||
);
|
||||
}
|
||||
@@ -19,8 +18,5 @@ export function workspaceConnectionStatusLabel(state: WorkspaceState): string {
|
||||
return `Reconnecting ${state.connectingEnvironments.length} environments`;
|
||||
}
|
||||
if (state.connectionError !== null) return state.connectionError;
|
||||
if (state.hasPendingShellSnapshot) {
|
||||
return state.hasLoadedShellSnapshot ? "Syncing threads..." : "Loading threads...";
|
||||
}
|
||||
return "Not connected";
|
||||
}
|
||||
@@ -2,8 +2,7 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useFocusEffect } from "@react-navigation/native";
|
||||
import {
|
||||
NavigationContext,
|
||||
@@ -23,7 +22,6 @@ import {
|
||||
} from "react";
|
||||
import { useWindowDimensions, View } from "react-native";
|
||||
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
deriveFileInspectorPaneLayout,
|
||||
@@ -36,12 +34,11 @@ import {
|
||||
} from "../../lib/layout";
|
||||
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import {
|
||||
parseActiveThreadPath,
|
||||
useHardwareKeyboardCommand,
|
||||
} from "../keyboard/hardwareKeyboardCommands";
|
||||
import { HomeListOptionsProvider, resolveProjectGroupingMode } from "../home/home-list-options";
|
||||
import { HomeListOptionsProvider } from "../home/home-list-options";
|
||||
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
|
||||
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
|
||||
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
|
||||
@@ -187,31 +184,6 @@ export function AdaptiveWorkspaceLayout(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly pathname: string;
|
||||
}) {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
if (!AsyncResult.isSuccess(preferencesResult)) {
|
||||
return AsyncResult.isFailure(preferencesResult) ? (
|
||||
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
|
||||
) : null;
|
||||
}
|
||||
return (
|
||||
<AdaptiveWorkspaceLayoutContent
|
||||
{...props}
|
||||
projectGroupingMode={resolveProjectGroupingMode(
|
||||
preferencesResult.value.projectGroupingEnabled,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AdaptiveWorkspaceLayoutContent(
|
||||
props: {
|
||||
readonly children: ReactNode;
|
||||
readonly pathname: string;
|
||||
} & {
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
},
|
||||
) {
|
||||
const projectGroupingMode = props.projectGroupingMode;
|
||||
const { width, height } = useWindowDimensions();
|
||||
const pathname = props.pathname;
|
||||
const navigation = useNavigation();
|
||||
@@ -502,7 +474,7 @@ function AdaptiveWorkspaceLayoutContent(
|
||||
);
|
||||
|
||||
return (
|
||||
<HomeListOptionsProvider projectGroupingMode={projectGroupingMode}>
|
||||
<HomeListOptionsProvider>
|
||||
<AdaptiveWorkspaceContext.Provider value={contextValue}>
|
||||
<View testID="adaptive-workspace-layout" className="flex-1 flex-row">
|
||||
{shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
|
||||
|
||||
@@ -119,14 +119,10 @@ function LocalSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<GeneralSettingsSection />
|
||||
|
||||
<SettingsSection title="Appearance">
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
@@ -506,14 +502,10 @@ function ConfiguredSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<GeneralSettingsSection />
|
||||
|
||||
<SettingsSection title="Appearance">
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
@@ -522,54 +514,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
function GeneralSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const projectGroupingEnabled = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.projectGroupingEnabled !== false
|
||||
: true;
|
||||
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsSwitchRow
|
||||
icon="folder"
|
||||
label="Project Grouping"
|
||||
value={projectGroupingEnabled}
|
||||
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Device-local beta toggles. Mobile has no client-settings sync, so this is
|
||||
* 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;
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
<SettingsSection title="Beta">
|
||||
<SettingsSwitchRow
|
||||
icon="sidebar.left"
|
||||
label="Thread List v2"
|
||||
value={threadListV2Enabled}
|
||||
onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<Text className="px-2 text-sm text-foreground-muted">
|
||||
One flat thread list in creation order. Active work renders as cards; settled threads
|
||||
collapse to compact rows. Switch back any time.
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function AppSettingsSection() {
|
||||
const icon = useThemeColor("--color-icon");
|
||||
|
||||
|
||||
@@ -582,13 +582,10 @@ export function NewTaskDraftScreen(props: {
|
||||
? "Approve actions"
|
||||
: flow.runtimeMode === "auto-accept-edits"
|
||||
? "Auto-accept edits"
|
||||
: flow.runtimeMode === "auto"
|
||||
? "Auto"
|
||||
: "Full access",
|
||||
: "Full access",
|
||||
subactions: [
|
||||
{ id: "options:runtime:approval-required", title: "Approve actions" },
|
||||
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
|
||||
{ id: "options:runtime:auto", title: "Auto" },
|
||||
{ id: "options:runtime:full-access", title: "Full access" },
|
||||
].map((option) => {
|
||||
const value = option.id.replace("options:runtime:", "");
|
||||
|
||||
@@ -26,13 +26,7 @@ import {
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
FadeInDown,
|
||||
FadeOut,
|
||||
FadeOutDown,
|
||||
LinearTransition,
|
||||
} from "react-native-reanimated";
|
||||
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
@@ -238,12 +232,7 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
|
||||
const isReconnecting = props.status.kind !== "unavailable";
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
className="absolute inset-x-0 bottom-full items-center pb-2"
|
||||
entering={FadeInDown.duration(180)}
|
||||
exiting={FadeOutDown.duration(140)}
|
||||
pointerEvents="box-none"
|
||||
>
|
||||
<View className="items-center pb-2">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
@@ -261,7 +250,7 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
|
||||
{props.status.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</Animated.View>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -638,13 +627,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
? "Approve actions"
|
||||
: currentRuntimeMode === "auto-accept-edits"
|
||||
? "Auto-accept edits"
|
||||
: currentRuntimeMode === "auto"
|
||||
? "Auto"
|
||||
: "Full access",
|
||||
: "Full access",
|
||||
subactions: [
|
||||
{ id: "options:runtime:approval-required", title: "Approve actions" },
|
||||
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
|
||||
{ id: "options:runtime:auto", title: "Auto" },
|
||||
{ id: "options:runtime:full-access", title: "Full access" },
|
||||
].map((option) => {
|
||||
const value = option.id.replace("options:runtime:", "");
|
||||
|
||||
@@ -14,13 +14,15 @@ import type {
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Platform, View, type GestureResponderEvent } from "react-native";
|
||||
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
|
||||
import Animated, { FadeInDown, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
@@ -169,6 +171,48 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
|
||||
}, [threadId, feed]);
|
||||
}
|
||||
|
||||
// Pre-measurement estimate for the working pill's slot (the real height is
|
||||
// measured via onComposerLayout since the pill lives inside the composer
|
||||
// overlay). Matches the rendered pill: pt-2 + pb-2 (16) wrapping a bordered
|
||||
// px-3/py-2 row (~36), so ~52 — keep it in sync with WorkingDurationPill.
|
||||
const WORKING_INDICATOR_HEIGHT = 52;
|
||||
|
||||
const WorkingDurationPill = memo(function WorkingDurationPill(props: {
|
||||
readonly startedAt: string;
|
||||
}) {
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const intervalId = setInterval(() => {
|
||||
setNowMs(Date.now());
|
||||
}, 1_000);
|
||||
return () => clearInterval(intervalId);
|
||||
}, [props.startedAt]);
|
||||
|
||||
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
className="shrink-0 px-4 pb-2 pt-2"
|
||||
entering={FadeInDown.duration(200)}
|
||||
exiting={FadeOut.duration(140)}
|
||||
>
|
||||
<View className="self-start rounded-full border border-neutral-200/80 bg-neutral-50/90 px-3 py-2 dark:border-white/[0.08] dark:bg-white/[0.04]">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View className="flex-row items-center gap-1">
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
Working for {durationLabel}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
});
|
||||
|
||||
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
@@ -202,7 +246,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
const estimatedOverlayHeight = composerOverlapHeight;
|
||||
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
|
||||
// The overlay's measured height includes the home-indicator inset (the
|
||||
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
|
||||
// UIKit add the safe-area bottom to the content inset AGAIN — leaving a
|
||||
@@ -359,7 +404,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
activeWorkStartedAt={props.activeWorkStartedAt}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
@@ -387,7 +431,15 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
list's bottom inset, so any padding above the pill/composer
|
||||
pushes the resting content floor up by the same amount. */}
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
|
||||
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||
<Animated.View
|
||||
className="w-full self-center"
|
||||
layout={LinearTransition.duration(220)}
|
||||
style={{ maxWidth: contentMaxWidth }}
|
||||
>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<Animated.View
|
||||
className="shrink-0 gap-3 px-4 pb-3"
|
||||
@@ -414,7 +466,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</View>
|
||||
</Animated.View>
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
@@ -129,7 +128,6 @@ export interface ThreadFeedProps {
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
@@ -818,10 +816,6 @@ function renderFeedEntry(
|
||||
const entry = info.item;
|
||||
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
|
||||
|
||||
if (entry.type === "working") {
|
||||
return <WorkingTimelineRow startedAt={entry.createdAt} />;
|
||||
}
|
||||
|
||||
if (entry.type === "turn-fold") {
|
||||
return (
|
||||
<Pressable
|
||||
@@ -999,32 +993,6 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
const WorkingTimelineRow = memo(function WorkingTimelineRow(props: { readonly startedAt: string }) {
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const intervalId = setInterval(() => {
|
||||
setNowMs(Date.now());
|
||||
}, 1_000);
|
||||
return () => clearInterval(intervalId);
|
||||
}, [props.startedAt]);
|
||||
|
||||
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
|
||||
|
||||
return (
|
||||
<View className="mb-4 flex-row items-center gap-2 px-1.5 py-1">
|
||||
<View className="flex-row items-center gap-1">
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400 dark:bg-neutral-500" />
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs tabular-nums text-neutral-600 dark:text-neutral-400">
|
||||
Working for {durationLabel}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
function UserMessageContent(props: {
|
||||
readonly text: string;
|
||||
readonly markdownStyles: MarkdownStyleSet;
|
||||
@@ -1447,15 +1415,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
props.latestTurn,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
props.activeWorkStartedAt,
|
||||
),
|
||||
[
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
props.activeWorkStartedAt,
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
],
|
||||
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
|
||||
);
|
||||
|
||||
// The empty↔filled key below remounts the list, which resets its imperative
|
||||
@@ -1800,9 +1761,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
{props.feed.length === 0 &&
|
||||
props.activeWorkStartedAt === null &&
|
||||
props.contentPresentation.kind === "ready" ? (
|
||||
{props.feed.length === 0 && props.contentPresentation.kind === "ready" ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
|
||||
@@ -5,12 +5,9 @@ import type {
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
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 { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
|
||||
import { Platform, Pressable, StyleSheet, TextInput, View, useColorScheme } from "react-native";
|
||||
import { Platform, StyleSheet, TextInput, View, useColorScheme } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -20,19 +17,17 @@ import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
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";
|
||||
import {
|
||||
hasCustomHomeListOptions,
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
useHomeListOptions,
|
||||
@@ -47,7 +42,7 @@ import {
|
||||
type HomeGroupDisplayState,
|
||||
type HomeListItem,
|
||||
} from "../home/homeListItems";
|
||||
import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";
|
||||
import { buildHomeThreadGroups } from "../home/homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
|
||||
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
|
||||
import { useThreadListActions } from "../home/useThreadListActions";
|
||||
@@ -63,27 +58,6 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "./thread-list-items";
|
||||
import { ThreadListV2Row } from "./thread-list-v2-items";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
|
||||
type ThreadListV2Item,
|
||||
} 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
|
||||
"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 }
|
||||
| { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
|
||||
|
||||
/**
|
||||
* Shared capsule behind the sidebar header buttons — a native liquid-glass
|
||||
@@ -194,12 +168,7 @@ function ThreadNavigationSidebarPane(
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const headerIsOverContentRef = useRef(false);
|
||||
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 { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -216,94 +185,26 @@ function ThreadNavigationSidebarPane(
|
||||
() => new Set(environments.map((environment) => environment.environmentId)),
|
||||
[environments],
|
||||
);
|
||||
const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } =
|
||||
useHomeListOptions(availableEnvironmentIds);
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
}),
|
||||
[options.projectGroupingMode, options.selectedEnvironmentId, projects],
|
||||
);
|
||||
const projectFilterOptions = useMemo(
|
||||
() =>
|
||||
projectScopes.map((scope) => ({
|
||||
key: scope.key,
|
||||
label: scope.title,
|
||||
})),
|
||||
[projectScopes],
|
||||
);
|
||||
const selectedProjectScope = useMemo(
|
||||
() =>
|
||||
selectedProjectKey === null
|
||||
? null
|
||||
: (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null),
|
||||
[projectScopes, selectedProjectKey],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
selectedProjectKey !== null &&
|
||||
!projectFilterOptions.some((project) => project.key === selectedProjectKey)
|
||||
) {
|
||||
setSelectedProjectKey(null);
|
||||
}
|
||||
}, [projectFilterOptions, selectedProjectKey]);
|
||||
const selectedProjectRefs = useMemo(
|
||||
() =>
|
||||
selectedProjectScope === null
|
||||
? null
|
||||
: new Set(
|
||||
selectedProjectScope.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[selectedProjectScope],
|
||||
);
|
||||
const scopedProjects = useMemo(
|
||||
() =>
|
||||
selectedProjectRefs === null
|
||||
? projects
|
||||
: projects.filter((project) =>
|
||||
selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)),
|
||||
),
|
||||
[projects, selectedProjectRefs],
|
||||
);
|
||||
const scopedThreads = useMemo(
|
||||
() =>
|
||||
selectedProjectRefs === null
|
||||
? threads
|
||||
: threads.filter((thread) =>
|
||||
selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
),
|
||||
[selectedProjectRefs, threads],
|
||||
);
|
||||
const scopedPendingTasks = useMemo(
|
||||
() =>
|
||||
selectedProjectRefs === null
|
||||
? pendingTasks
|
||||
: pendingTasks.filter((pendingTask) =>
|
||||
selectedProjectRefs.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
),
|
||||
[pendingTasks, selectedProjectRefs],
|
||||
);
|
||||
const {
|
||||
options,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
} = useHomeListOptions(availableEnvironmentIds);
|
||||
const groups = useMemo(
|
||||
() =>
|
||||
buildHomeThreadGroups({
|
||||
projects: scopedProjects,
|
||||
threads: scopedThreads,
|
||||
pendingTasks: scopedPendingTasks,
|
||||
projects,
|
||||
threads,
|
||||
pendingTasks,
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
projectSortOrder: options.projectSortOrder,
|
||||
threadSortOrder: options.threadSortOrder,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
}),
|
||||
[options, props.searchQuery, scopedPendingTasks, scopedProjects, scopedThreads],
|
||||
[options, pendingTasks, projects, props.searchQuery, threads],
|
||||
);
|
||||
const [groupDisplayStates, setGroupDisplayStates] = useState<
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
@@ -335,148 +236,6 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return map;
|
||||
}, [projects]);
|
||||
const projectByKey = useMemo(() => {
|
||||
const map = new Map<string, EnvironmentProject>();
|
||||
for (const project of projects) {
|
||||
map.set(scopedProjectKey(project.environmentId, project.id), project);
|
||||
}
|
||||
return map;
|
||||
}, [projects]);
|
||||
|
||||
// Thread List v2 (beta) support — same model as the compact Home list
|
||||
// (HomeScreen.tsx): flat creation-order card block + settled recency tail.
|
||||
// PR states stream in per-row; merged/closed PRs auto-settle their thread
|
||||
// on the next partition.
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
const handleChangeRequestState = useCallback(
|
||||
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
|
||||
setChangeRequestStateByKey((current) => {
|
||||
if ((current.get(threadKey) ?? null) === state) return current;
|
||||
const next = new Map(current);
|
||||
if (state === null) {
|
||||
next.delete(threadKey);
|
||||
} else {
|
||||
next.set(threadKey, state);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
// context changes so environment/search flips never inherit a deep page.
|
||||
const [settledVisibleCount, setSettledVisibleCount] = useState(
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
);
|
||||
const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`;
|
||||
const lastSettledResetKeyRef = useRef(settledResetKey);
|
||||
if (lastSettledResetKeyRef.current !== settledResetKey) {
|
||||
lastSettledResetKeyRef.current = settledResetKey;
|
||||
setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
|
||||
}
|
||||
const showMoreSettled = useCallback(
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
// now ticks per minute so the inactivity auto-settle boundary is actually
|
||||
// crossed while the pane stays open; without a clock dependency the
|
||||
// partition memoizes a frozen "now".
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
// by the time the beta is switched on, which would misclassify the
|
||||
// inactivity auto-settle boundary until the first tick.
|
||||
setNowMinute(new Date().toISOString().slice(0, 16));
|
||||
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
|
||||
return () => clearInterval(id);
|
||||
}, [threadListV2Enabled]);
|
||||
// Threads on servers without the settlement capability never classify as
|
||||
// settled (the user could neither un-settle nor pin them).
|
||||
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
|
||||
const settlementEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSettlement === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
return buildThreadListV2Items({
|
||||
threads: threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
options.selectedEnvironmentId,
|
||||
props.searchQuery,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
threadListV2Enabled,
|
||||
threads,
|
||||
selectedProjectScope,
|
||||
]);
|
||||
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.
|
||||
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
|
||||
const v2PendingTasks = pendingTasks.filter(
|
||||
(pendingTask) =>
|
||||
(options.selectedEnvironmentId === null ||
|
||||
pendingTask.message.environmentId === options.selectedEnvironmentId) &&
|
||||
(selectedProjectRefs === null ||
|
||||
selectedProjectRefs.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
)) &&
|
||||
(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,
|
||||
});
|
||||
}
|
||||
if (threadListV2Layout.hiddenSettledCount > 0) {
|
||||
items.push({
|
||||
type: "v2-show-more",
|
||||
key: "v2-show-more",
|
||||
hiddenCount: threadListV2Layout.hiddenSettledCount,
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}, [
|
||||
listLayout.items,
|
||||
options.selectedEnvironmentId,
|
||||
pendingTasks,
|
||||
props.searchQuery,
|
||||
selectedProjectRefs,
|
||||
threadListV2Enabled,
|
||||
threadListV2Layout,
|
||||
]);
|
||||
const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
|
||||
const listMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
@@ -500,54 +259,36 @@ function ThreadNavigationSidebarPane(
|
||||
})),
|
||||
],
|
||||
},
|
||||
...(projectFilterOptions.length === 0
|
||||
? []
|
||||
: ([
|
||||
{
|
||||
id: "project",
|
||||
title: "Project",
|
||||
subactions: [
|
||||
{
|
||||
id: "project:all",
|
||||
title: "All projects",
|
||||
subtitle: "Show threads from every project",
|
||||
state: selectedProjectKey === null ? "on" : "off",
|
||||
},
|
||||
...projectFilterOptions.map((project) => ({
|
||||
id: `project:${project.key}`,
|
||||
title: project.label,
|
||||
state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
|
||||
})),
|
||||
],
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
// v2 lays the list out in fixed creation order — offering sort/group
|
||||
// controls it silently ignores would be a lie. Environment still
|
||||
// scopes the v2 partition, so it stays.
|
||||
...(threadListV2Enabled
|
||||
? []
|
||||
: ([
|
||||
{
|
||||
id: "project-sort",
|
||||
title: "Sort projects",
|
||||
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
id: `project-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: options.projectSortOrder === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "thread-sort",
|
||||
title: "Sort threads",
|
||||
subactions: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
id: `thread-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: options.threadSortOrder === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
{
|
||||
id: "project-sort",
|
||||
title: "Sort projects",
|
||||
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
id: `project-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: options.projectSortOrder === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "thread-sort",
|
||||
title: "Sort threads",
|
||||
subactions: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
id: `thread-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: options.threadSortOrder === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "project-grouping",
|
||||
title: "Group projects",
|
||||
subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
id: `project-grouping:${option.value}`,
|
||||
title: option.label,
|
||||
subtitle: option.subtitle,
|
||||
state: options.projectGroupingMode === option.value ? "on" : "off",
|
||||
})),
|
||||
},
|
||||
],
|
||||
[environments, options, projectFilterOptions, selectedProjectKey, threadListV2Enabled],
|
||||
[environments, options],
|
||||
);
|
||||
const handleListMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
@@ -563,17 +304,6 @@ function ThreadNavigationSidebarPane(
|
||||
if (environment) setSelectedEnvironmentId(environment.environmentId);
|
||||
return;
|
||||
}
|
||||
if (event === "project:all") {
|
||||
setSelectedProjectKey(null);
|
||||
return;
|
||||
}
|
||||
if (event.startsWith("project:")) {
|
||||
const projectKey = event.slice("project:".length);
|
||||
if (projectFilterOptions.some((project) => project.key === projectKey)) {
|
||||
setSelectedProjectKey(projectKey);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const projectSort = PROJECT_SORT_OPTIONS.find(
|
||||
(option) => `project-sort:${option.value}` === event,
|
||||
);
|
||||
@@ -588,10 +318,14 @@ function ThreadNavigationSidebarPane(
|
||||
setThreadSortOrder(threadSort.value);
|
||||
return;
|
||||
}
|
||||
const grouping = PROJECT_GROUPING_OPTIONS.find(
|
||||
(option) => `project-grouping:${option.value}` === event,
|
||||
);
|
||||
if (grouping) setProjectGroupingMode(grouping.value);
|
||||
},
|
||||
[
|
||||
environments,
|
||||
projectFilterOptions,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setSelectedEnvironmentId,
|
||||
setThreadSortOrder,
|
||||
@@ -647,44 +381,7 @@ function ThreadNavigationSidebarPane(
|
||||
onScroll: handleScroll,
|
||||
onScrollBeginDrag: handleScrollBeginDrag,
|
||||
});
|
||||
const listExtraData = useMemo(
|
||||
() => ({
|
||||
selectedThreadKey: props.selectedThreadKey ?? "",
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
}),
|
||||
[props.selectedThreadKey, savedConnectionsById, serverConfigs],
|
||||
);
|
||||
const sidebarItemsAreEqual = useCallback(
|
||||
(previous: SidebarListItem, item: SidebarListItem): boolean => {
|
||||
if (previous.type === "v2-thread" && item.type === "v2-thread") {
|
||||
return (
|
||||
previous.key === item.key &&
|
||||
previous.item.thread === item.item.thread &&
|
||||
previous.item.variant === item.item.variant &&
|
||||
previous.item.showSettledDivider === item.item.showSettledDivider
|
||||
);
|
||||
}
|
||||
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-thread" ||
|
||||
previous.type === "v2-show-more" ||
|
||||
previous.type === "v2-pending-task" ||
|
||||
item.type === "v2-thread" ||
|
||||
item.type === "v2-show-more" ||
|
||||
item.type === "v2-pending-task"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return homeListItemsAreEqual(previous, item);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const listExtraData = props.selectedThreadKey ?? "";
|
||||
const focusSearch = useCallback(() => {
|
||||
const focus = () => {
|
||||
if (props.nativeChrome) {
|
||||
@@ -703,78 +400,8 @@ function ThreadNavigationSidebarPane(
|
||||
}, [props.nativeChrome, props.onRequestVisibility, props.visible]);
|
||||
useHardwareKeyboardCommand("focusSearch", focusSearch);
|
||||
const renderListItem = useCallback(
|
||||
({ item }: { readonly item: SidebarListItem }) => {
|
||||
({ item }: { readonly item: HomeListItem }) => {
|
||||
switch (item.type) {
|
||||
case "v2-pending-task":
|
||||
return (
|
||||
<PendingTaskListRow
|
||||
variant="sidebar"
|
||||
pendingTask={item.pendingTask}
|
||||
environmentLabel={
|
||||
savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
|
||||
null
|
||||
}
|
||||
isLast={item.isLast}
|
||||
onSelectPendingTask={openPendingTask}
|
||||
onDeletePendingTask={confirmDeletePendingTask}
|
||||
/>
|
||||
);
|
||||
case "v2-thread": {
|
||||
const thread = item.item.thread;
|
||||
const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
|
||||
return (
|
||||
<ThreadListV2Row
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
showSettledDivider={item.item.showSettledDivider}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(thread.environmentId)
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
Object.keys(savedConnectionsById).length > 1
|
||||
? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
|
||||
: null
|
||||
}
|
||||
pane="sidebar"
|
||||
selected={
|
||||
scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
|
||||
}
|
||||
fullSwipeWidth={props.width - 20}
|
||||
onSelectThread={handleSelectThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onArchiveThread={archiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={settleThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
simultaneousSwipeGesture={sidebarScrollGesture}
|
||||
/>
|
||||
);
|
||||
}
|
||||
case "v2-show-more":
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Show ${Math.min(item.hiddenCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
|
||||
onPress={showMoreSettled}
|
||||
className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-muted">
|
||||
Show more ({item.hiddenCount} settled hidden)
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
case "header":
|
||||
return (
|
||||
<ThreadListGroupHeader
|
||||
@@ -850,58 +477,42 @@ function ThreadNavigationSidebarPane(
|
||||
archiveThread,
|
||||
confirmDeletePendingTask,
|
||||
confirmDeleteThread,
|
||||
handleChangeRequestState,
|
||||
handleSelectThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
openPendingTask,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onNewThreadInProject,
|
||||
props.selectedThreadKey,
|
||||
props.width,
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
settleThread,
|
||||
settlementEnvironmentIds,
|
||||
showMoreSettled,
|
||||
sidebarScrollGesture,
|
||||
unsettleThread,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
// v2 ignores the sort/group options, so only the environment filter can
|
||||
// light the "customized" state while the beta is on.
|
||||
const filterCustomized = threadListV2Enabled
|
||||
? options.selectedEnvironmentId !== null || selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions({ ...options, selectedProjectKey });
|
||||
const filterIcon = filterCustomized
|
||||
const filterIcon = hasCustomHomeListOptions(options)
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle";
|
||||
const filterMenu = useMemo(
|
||||
() =>
|
||||
buildHomeListFilterMenu({
|
||||
environments,
|
||||
projects: projectFilterOptions,
|
||||
selectedEnvironmentId: options.selectedEnvironmentId,
|
||||
selectedProjectKey,
|
||||
projectSortOrder: options.projectSortOrder,
|
||||
threadSortOrder: options.threadSortOrder,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
onEnvironmentChange: setSelectedEnvironmentId,
|
||||
onProjectChange: setSelectedProjectKey,
|
||||
onProjectSortOrderChange: setProjectSortOrder,
|
||||
onThreadSortOrderChange: setThreadSortOrder,
|
||||
listOrganization: !threadListV2Enabled,
|
||||
onProjectGroupingModeChange: setProjectGroupingMode,
|
||||
}),
|
||||
[
|
||||
environments,
|
||||
options,
|
||||
projectFilterOptions,
|
||||
selectedProjectKey,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setSelectedEnvironmentId,
|
||||
setThreadSortOrder,
|
||||
threadListV2Enabled,
|
||||
],
|
||||
);
|
||||
const nativeHeaderItems = useMemo(
|
||||
@@ -919,9 +530,7 @@ function ThreadNavigationSidebarPane(
|
||||
? "Loading threads…"
|
||||
: props.searchQuery.trim().length > 0
|
||||
? "No matching threads"
|
||||
: selectedProjectScope !== null
|
||||
? `No threads in ${selectedProjectScope.title}`
|
||||
: "No threads yet"}
|
||||
: "No threads yet"}
|
||||
</Text>
|
||||
);
|
||||
|
||||
@@ -929,7 +538,6 @@ function ThreadNavigationSidebarPane(
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions
|
||||
optionsVersion={nativeHeaderItems}
|
||||
options={{
|
||||
headerSearchBarOptions: {
|
||||
ref: searchBarRef,
|
||||
@@ -955,18 +563,16 @@ function ThreadNavigationSidebarPane(
|
||||
<SwipeableScrollGateProvider enabled={swipeEnabled}>
|
||||
<GestureDetector gesture={sidebarScrollGesture}>
|
||||
<LegendList
|
||||
data={listItems}
|
||||
data={listLayout.items}
|
||||
drawDistance={500}
|
||||
estimatedItemSize={64}
|
||||
extraData={listExtraData}
|
||||
getItemType={(item) => item.type}
|
||||
itemsAreEqual={sidebarItemsAreEqual}
|
||||
itemsAreEqual={homeListItemsAreEqual}
|
||||
keyExtractor={(item) => item.key}
|
||||
renderItem={renderListItem}
|
||||
automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
|
||||
contentInsetAdjustmentBehavior={
|
||||
NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"
|
||||
}
|
||||
automaticallyAdjustsScrollIndicatorInsets
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
contentContainerStyle={[
|
||||
styles.threadListContent,
|
||||
{
|
||||
@@ -1016,12 +622,12 @@ function ThreadNavigationSidebarPane(
|
||||
<SwipeableScrollGateProvider enabled={swipeEnabled}>
|
||||
<GestureDetector gesture={sidebarScrollGesture}>
|
||||
<LegendList
|
||||
data={listItems}
|
||||
data={listLayout.items}
|
||||
drawDistance={500}
|
||||
estimatedItemSize={64}
|
||||
extraData={listExtraData}
|
||||
getItemType={(item) => item.type}
|
||||
itemsAreEqual={sidebarItemsAreEqual}
|
||||
itemsAreEqual={homeListItemsAreEqual}
|
||||
keyExtractor={(item) => item.key}
|
||||
renderItem={renderListItem}
|
||||
contentContainerStyle={[
|
||||
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
} from "../../components/AndroidScreenHeader";
|
||||
import { LoadingScreen } from "../../components/LoadingScreen";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { connectionTone } from "../connection/connectionTone";
|
||||
|
||||
import {
|
||||
@@ -279,7 +278,7 @@ function ThreadRouteContent(
|
||||
);
|
||||
|
||||
/* ─── Native header theming ──────────────────────────────────────── */
|
||||
const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
|
||||
const usesNativeHeaderGlass = Platform.OS === "ios";
|
||||
const headerSubtitle = [
|
||||
selectedThreadProject?.title ?? null,
|
||||
selectedEnvironmentConnection?.environmentLabel ?? null,
|
||||
|
||||
@@ -58,8 +58,6 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
|
||||
|
||||
type WorkspaceMode = "local" | "worktree";
|
||||
|
||||
const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];
|
||||
|
||||
function pendingTaskDraftKey(messageId: string): string {
|
||||
return `pending-task:${messageId}`;
|
||||
}
|
||||
@@ -350,14 +348,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
// Keep the user's explicit choice separate from the resolved display value:
|
||||
// only the explicit flag is ever written back to the draft, so the resolved
|
||||
// value keeps tracking the server setting when the config loads late.
|
||||
const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
|
||||
const startFromOrigin =
|
||||
draftStartFromOrigin ??
|
||||
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
|
||||
true;
|
||||
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
@@ -377,7 +368,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedModel =
|
||||
selectedProjectDraft.modelSelection ??
|
||||
selectedProject?.defaultModelSelection ??
|
||||
modelOptions.find((option) => option.isDefault)?.selection ??
|
||||
modelOptions[0]?.selection ??
|
||||
null;
|
||||
const selectedModelKey = selectedModel
|
||||
@@ -485,14 +475,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
);
|
||||
const branchState = useBranches(branchTarget);
|
||||
const branchesLoading = branchState.isPending;
|
||||
const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;
|
||||
const availableBranches = useMemo(
|
||||
() =>
|
||||
pipe(
|
||||
allBranchRefs,
|
||||
branchState.data?.refs ?? [],
|
||||
Arr.filter((branch) => !branch.isRemote),
|
||||
),
|
||||
[allBranchRefs],
|
||||
[branchState.data?.refs],
|
||||
);
|
||||
|
||||
const filteredBranches = useMemo(() => {
|
||||
@@ -554,11 +543,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
startFromOrigin,
|
||||
},
|
||||
});
|
||||
},
|
||||
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
@@ -571,11 +560,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
startFromOrigin,
|
||||
},
|
||||
});
|
||||
},
|
||||
[draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
|
||||
[selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
|
||||
);
|
||||
|
||||
const setStartFromOrigin = useCallback(
|
||||
@@ -608,16 +597,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
|
||||
return;
|
||||
}
|
||||
// The default may only exist as origin/<default> (isRemote), which
|
||||
// availableBranches filters out — search the unfiltered refs for it.
|
||||
const preferredBranch =
|
||||
allBranchRefs.find((branch) => branch.isDefault) ??
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
availableBranches.find((branch) => branch.isDefault) ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
}
|
||||
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
@@ -709,12 +696,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
workspaceMode: mode,
|
||||
branch: workspaceSelection?.branch ?? null,
|
||||
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
|
||||
// The draft only carries the flag when the user touched it; fall
|
||||
// back to the resolved default (server settings) so queued tasks
|
||||
// drain with the same origin mode the composer displayed.
|
||||
...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
|
||||
? { startFromOrigin: true }
|
||||
: {}),
|
||||
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
|
||||
},
|
||||
createdAt: metadata.createdAt,
|
||||
};
|
||||
@@ -725,7 +707,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
selectedModel,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
startFromOrigin,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import type { ReactNode } from "react";
|
||||
import { Platform, useColorScheme } from "react-native";
|
||||
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { renderCompactBrandTitle } from "../../components/CompactBrandTitle";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
|
||||
|
||||
const SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
@@ -34,12 +34,13 @@ const SIDEBAR_SCREEN_OPTIONS: SidebarScreenOptions = {
|
||||
headerLargeTitle: false,
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? { backgroundColor: "transparent" } : undefined,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerTitle: renderCompactBrandTitle,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
|
||||
scrollEdgeEffects: NATIVE_LIQUID_GLASS_SUPPORTED ? SCROLL_EDGE_EFFECTS : undefined,
|
||||
title: "Threads",
|
||||
unstable_navigationItemStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? "editor" : undefined,
|
||||
headerTransparent: true,
|
||||
scrollEdgeEffects: SCROLL_EDGE_EFFECTS,
|
||||
title: "T3 Code",
|
||||
unstable_navigationItemStyle: "editor",
|
||||
};
|
||||
|
||||
const SidebarStack = createNativeStackNavigator();
|
||||
|
||||
@@ -1,463 +0,0 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { memo, useCallback, useEffect, useMemo, type ComponentProps } from "react";
|
||||
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
|
||||
|
||||
/**
|
||||
* Thread List v2 renders one flat native list: rich edge-to-edge rows for
|
||||
* active work and a receded settled tail, all with native swipe and
|
||||
* long-press actions. State reads through colored status labels and text
|
||||
* hierarchy rather than card fills.
|
||||
*/
|
||||
|
||||
const MONO_FONT = Platform.select({
|
||||
ios: "Menlo",
|
||||
android: "monospace",
|
||||
default: "monospace",
|
||||
});
|
||||
|
||||
// Status hues follow the system-wide convention set by sidebar v1 and the
|
||||
// Live Activity/widgets (amber approval, indigo input, sky working) so a
|
||||
// thread reads the same color everywhere it surfaces.
|
||||
const STATUS_LABEL_BY_STATUS: Partial<
|
||||
Record<ThreadListV2Status, { label: string; className: string }>
|
||||
> = {
|
||||
approval: { label: "Approval", className: "text-amber-700 dark:text-amber-300" },
|
||||
input: { label: "Input", className: "text-indigo-600 dark:text-indigo-300" },
|
||||
working: { label: "Working", className: "text-sky-600 dark:text-sky-400" },
|
||||
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
|
||||
};
|
||||
|
||||
function threadTimeLabel(thread: EnvironmentThreadShell): string {
|
||||
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
|
||||
}
|
||||
|
||||
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
|
||||
// its own surface (thread screen / settings) rather than crowding the row.
|
||||
const CARD_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
const SLIM_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "unsettle", title: "Un-settle", image: "arrow.uturn.backward" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
// Pre-settlement servers: no lifecycle items, archive fills the gap.
|
||||
const LEGACY_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "archive", title: "Archive", image: "archivebox" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
/** Rounded-row radius shared with the v1 sidebar rows. */
|
||||
const SIDEBAR_V2_ROW_RADIUS = 12;
|
||||
|
||||
export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivider(props: {
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
}) {
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
return (
|
||||
<View
|
||||
className={cn(
|
||||
"mb-1.5 mt-4 flex-row items-center gap-2.5",
|
||||
props.pane === "sidebar" ? "px-3" : "px-5",
|
||||
)}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-tertiary">Settled</Text>
|
||||
<View className="h-px flex-1" style={{ backgroundColor: borderColor }} />
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
readonly showSettledDivider: boolean;
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly providerDriver: string | null;
|
||||
/** Which machine hosts the thread. Null when only one environment is
|
||||
connected — repeating the same label on every row is noise. Mirrors
|
||||
the web sidebar's remote-environment cloud icon, but as text since
|
||||
phones have no hover tooltips. */
|
||||
readonly environmentLabel: string | null;
|
||||
/** Hosting surface. "screen" (default) renders the compact Home idiom:
|
||||
flat edge-to-edge rows on the screen background with inset hairlines.
|
||||
"sidebar" renders the iPad split-view idiom: rounded rows blending
|
||||
into the drawer surface, selection filled with the accent color —
|
||||
matching the v1 sidebar rows. */
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
/** Highlights the thread open in the detail pane (iPad split view). The
|
||||
compact Home list never sets it — phones navigate away on select. */
|
||||
readonly selected?: boolean;
|
||||
/** Override for narrow panes (iPad sidebar); defaults to window width. */
|
||||
readonly fullSwipeWidth?: number;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** False on environments whose server predates thread.settle/unsettle:
|
||||
swipe + menu fall back to Archive instead of failing on use. */
|
||||
readonly settlementSupported: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
/** Reports this row's live PR state up so the partition can auto-settle
|
||||
merged/closed work (mirrors web's onChangeRequestState). */
|
||||
readonly onChangeRequestState?: (
|
||||
threadKey: string,
|
||||
state: "open" | "closed" | "merged" | null,
|
||||
) => void;
|
||||
readonly projectCwd?: string | null;
|
||||
readonly simultaneousSwipeGesture?: ComponentProps<
|
||||
typeof ThreadSwipeable
|
||||
>["simultaneousWithExternalGesture"];
|
||||
}) {
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const {
|
||||
thread,
|
||||
variant,
|
||||
onSelectThread,
|
||||
onDeleteThread,
|
||||
onSettleThread,
|
||||
onUnsettleThread,
|
||||
onArchiveThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
|
||||
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
|
||||
const prState = pr?.state ?? null;
|
||||
const threadKey = `${thread.environmentId}:${thread.id}`;
|
||||
useEffect(() => {
|
||||
onChangeRequestState?.(threadKey, prState);
|
||||
}, [onChangeRequestState, prState, threadKey]);
|
||||
|
||||
const screenColor = useThemeColor("--color-screen");
|
||||
const drawerColor = useThemeColor("--color-drawer");
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
|
||||
const sidebarPane = props.pane === "sidebar";
|
||||
const selected = props.selected === true;
|
||||
|
||||
const status = resolveThreadListV2Status(thread);
|
||||
const statusLabel = STATUS_LABEL_BY_STATUS[status];
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "settle") handleSettle();
|
||||
if (nativeEvent.event === "unsettle") handleUnsettle();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
},
|
||||
[handleArchive, handleDelete, handleSettle, handleUnsettle],
|
||||
);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Every settled
|
||||
// row can un-settle — explicit settles clear the override, auto-settled
|
||||
// rows get pinned active until real activity clears the pin.
|
||||
const canUnsettle = variant === "slim";
|
||||
const primaryAction = useMemo(() => {
|
||||
// Pre-settlement server: archive is the swipe action, as in v1. (Slim
|
||||
// rows cannot occur here — unsupported environments never classify as
|
||||
// settled.)
|
||||
if (!props.settlementSupported) {
|
||||
return {
|
||||
accessibilityLabel: `Archive ${thread.title}`,
|
||||
icon: "archivebox" as const,
|
||||
label: "Archive",
|
||||
onPress: handleArchive,
|
||||
};
|
||||
}
|
||||
return canUnsettle
|
||||
? {
|
||||
accessibilityLabel: `Un-settle ${thread.title}`,
|
||||
icon: "arrow.uturn.backward" as const,
|
||||
label: "Un-settle",
|
||||
onPress: handleUnsettle,
|
||||
}
|
||||
: {
|
||||
accessibilityLabel: `Settle ${thread.title}`,
|
||||
icon: "checkmark" as const,
|
||||
label: "Settle",
|
||||
onPress: handleSettle,
|
||||
};
|
||||
}, [
|
||||
canUnsettle,
|
||||
handleArchive,
|
||||
handleSettle,
|
||||
handleUnsettle,
|
||||
props.settlementSupported,
|
||||
thread.title,
|
||||
]);
|
||||
|
||||
// The sidebar pane fills selected rows with the accent color (matching the
|
||||
// v1 sidebar), so every piece of row text needs a white-on-accent variant.
|
||||
const cardContent = (
|
||||
<>
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
{props.project ? (
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-sm font-t3-medium",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.project?.title ?? ""}
|
||||
</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs tabular-nums",
|
||||
selected ? "text-white" : (statusLabel?.className ?? "text-foreground-tertiary"),
|
||||
)}
|
||||
>
|
||||
{statusLabel?.label ?? timeLabel}
|
||||
</Text>
|
||||
</View>
|
||||
<Text
|
||||
className={cn(
|
||||
"mt-1 text-base font-t3-medium",
|
||||
selected ? "text-user-bubble-foreground" : "text-foreground",
|
||||
)}
|
||||
numberOfLines={2}
|
||||
>
|
||||
{thread.title}
|
||||
</Text>
|
||||
<View className="mt-1 flex-row items-center gap-2">
|
||||
{status === "failed" && thread.session?.lastError ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
selected
|
||||
? "text-user-bubble-foreground-muted"
|
||||
: "text-red-600/80 dark:text-red-400/80",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.session.lastError}
|
||||
</Text>
|
||||
) : thread.branch || props.environmentLabel ? (
|
||||
/* "branch · machine" share one truncating line. The machine sits
|
||||
last so a tight fit cuts the repetitive label, not the branch —
|
||||
and machine-only fills the row for non-git projects. */
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.branch ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{thread.branch}
|
||||
</Text>
|
||||
) : null}
|
||||
{thread.branch && props.environmentLabel ? " · " : null}
|
||||
{props.environmentLabel ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
|
||||
)}
|
||||
>
|
||||
{props.environmentLabel}
|
||||
</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
) : (
|
||||
<View className="flex-1" />
|
||||
)}
|
||||
{pr ? (
|
||||
<Text
|
||||
accessibilityLabel={pr.accessibilityLabel}
|
||||
className={cn("text-xs", selected ? "text-white" : pr.textClassName)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
#{pr.label}
|
||||
</Text>
|
||||
) : null}
|
||||
{props.providerDriver ? (
|
||||
<View className="opacity-60">
|
||||
<ProviderIcon provider={props.providerDriver} size={14} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
|
||||
const rowContent = (close: () => void) =>
|
||||
variant === "card" ? (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
onPress={() => {
|
||||
close();
|
||||
onSelectThread(thread);
|
||||
}}
|
||||
style={
|
||||
sidebarPane
|
||||
? ({ pressed }) => ({
|
||||
backgroundColor: selected
|
||||
? selectedBackgroundColor
|
||||
: pressed
|
||||
? pressedBackgroundColor
|
||||
: drawerColor,
|
||||
borderRadius: SIDEBAR_V2_ROW_RADIUS,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 10,
|
||||
})
|
||||
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
|
||||
}
|
||||
>
|
||||
{sidebarPane ? (
|
||||
cardContent
|
||||
) : (
|
||||
/* Flat native list rows: no tonal containers — colored status
|
||||
labels and text hierarchy carry state, an inset hairline
|
||||
separates rows. The opaque screen background stays so swipe
|
||||
actions reveal behind the row. */
|
||||
<View className="bg-screen">
|
||||
<View className="px-5 py-2.5">{cardContent}</View>
|
||||
<View className="ml-5 h-px bg-border-subtle" />
|
||||
</View>
|
||||
)}
|
||||
</Pressable>
|
||||
) : (
|
||||
<Pressable
|
||||
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
className={sidebarPane ? undefined : "bg-screen"}
|
||||
onPress={() => {
|
||||
close();
|
||||
onSelectThread(thread);
|
||||
}}
|
||||
style={
|
||||
sidebarPane
|
||||
? ({ pressed }) => ({
|
||||
backgroundColor: selected
|
||||
? selectedBackgroundColor
|
||||
: pressed
|
||||
? pressedBackgroundColor
|
||||
: drawerColor,
|
||||
borderRadius: SIDEBAR_V2_ROW_RADIUS,
|
||||
})
|
||||
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
|
||||
}
|
||||
>
|
||||
{/* Settled history recedes: dimmed favicon + muted title. */}
|
||||
<View
|
||||
className={cn(
|
||||
"min-h-[44px] flex-row items-center gap-2.5 py-2",
|
||||
sidebarPane ? "px-3" : "px-5",
|
||||
)}
|
||||
>
|
||||
{props.project ? (
|
||||
<View className="opacity-40">
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
projectTitle={props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-base",
|
||||
selected ? "text-user-bubble-foreground" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-sm tabular-nums",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
|
||||
</Text>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{props.showSettledDivider ? <ThreadListV2SettledDivider pane={props.pane} /> : null}
|
||||
<ThreadSwipeable
|
||||
backgroundColor={sidebarPane ? drawerColor : screenColor}
|
||||
compactActions={variant === "slim"}
|
||||
containerStyle={
|
||||
sidebarPane ? { borderRadius: SIDEBAR_V2_ROW_RADIUS, overflow: "hidden" } : undefined
|
||||
}
|
||||
enableTrackpadSwipe
|
||||
// Full swipe commits the advertised lifecycle action (Settle /
|
||||
// Un-settle), never the destructive delete.
|
||||
fullSwipeAction="primary"
|
||||
fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
|
||||
onDelete={handleDelete}
|
||||
onSwipeableClose={props.onSwipeableClose}
|
||||
onSwipeableWillOpen={props.onSwipeableWillOpen}
|
||||
primaryAction={primaryAction}
|
||||
resetKey={`${thread.environmentId}:${thread.id}`}
|
||||
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
|
||||
threadTitle={thread.title}
|
||||
>
|
||||
{(close) => (
|
||||
<ControlPillMenu
|
||||
actions={
|
||||
!props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
: CARD_MENU_ACTIONS
|
||||
}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
>
|
||||
{rowContent(close)}
|
||||
</ControlPillMenu>
|
||||
)}
|
||||
</ThreadSwipeable>
|
||||
</>
|
||||
);
|
||||
});
|
||||
@@ -1,243 +0,0 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
resolveThreadListV2Status,
|
||||
sortThreadsForListV2,
|
||||
} from "./threadListV2";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
environmentId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
const NOW = "2026-06-02T00:00:00.000Z";
|
||||
|
||||
describe("resolveThreadListV2Status", () => {
|
||||
it("prioritizes approval over a running session", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
hasPendingApprovals: true,
|
||||
session: {
|
||||
threadId: ThreadId.make("t"),
|
||||
status: "running",
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
});
|
||||
expect(resolveThreadListV2Status(thread)).toBe("approval");
|
||||
});
|
||||
|
||||
it("resolves ready for quiescent threads", () => {
|
||||
expect(resolveThreadListV2Status(makeThread({ id: ThreadId.make("t"), title: "t" }))).toBe(
|
||||
"ready",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortThreadsForListV2", () => {
|
||||
it("orders by creation time, newest first, ignoring activity", () => {
|
||||
const sorted = sortThreadsForListV2([
|
||||
{ id: "oldest", createdAt: "2026-06-01T08:00:00.000Z" },
|
||||
{ id: "newest", createdAt: "2026-06-01T12:00:00.000Z" },
|
||||
{ id: "middle", createdAt: "2026-06-01T10:00:00.000Z" },
|
||||
]);
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items", () => {
|
||||
it("partitions settled threads into a slim tail with one divider", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Settled",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled-2"),
|
||||
title: "Settled 2",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
["active", "card"],
|
||||
["settled", "slim"],
|
||||
["settled-2", "slim"],
|
||||
]);
|
||||
expect(items.map((item) => item.showSettledDivider)).toEqual([false, true, false]);
|
||||
expect(items.map((item) => item.isLast)).toEqual([false, false, true]);
|
||||
});
|
||||
|
||||
it("keeps cards in creation order while settled sorts by recency", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("older-created"),
|
||||
title: "Older",
|
||||
createdAt: "2026-06-01T08:00:00.000Z",
|
||||
updatedAt: NOW, // recent activity must NOT promote it
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("newer-created"),
|
||||
title: "Newer",
|
||||
createdAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["newer-created", "older-created"]);
|
||||
});
|
||||
|
||||
it("keeps settled threads in the tail and filters by search query", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("match"), title: "Fix login bug" }),
|
||||
makeThread({ id: ThreadId.make("miss"), title: "Greeting" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Fix login again",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "login",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
["match", "card"],
|
||||
["settled", "slim"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("scopes the flat list to one project", () => {
|
||||
const otherProjectId = ProjectId.make("project-2");
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("included"), title: "Included" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("excluded"),
|
||||
projectId: otherProjectId,
|
||||
title: "Excluded",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["included"]);
|
||||
});
|
||||
|
||||
it("scopes the flat list to every environment member of a logical project", () => {
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("local"), title: "Local" }),
|
||||
makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ThreadId.make("remote"),
|
||||
title: "Remote",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [
|
||||
{ environmentId, projectId: ProjectId.make("project-1") },
|
||||
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
|
||||
],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["local", "remote"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items settled paging", () => {
|
||||
it("caps the settled tail at settledLimit and reports the hidden count", () => {
|
||||
const threads = [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
...Array.from({ length: 4 }, (_, index) =>
|
||||
makeThread({
|
||||
id: ThreadId.make(`settled-${index}`),
|
||||
title: `Settled ${index}`,
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
// A turn adopted the message (same requestedAt): without it the
|
||||
// thread reads as a queued turn start, which never settles.
|
||||
latestTurn: {
|
||||
turnId: TurnId.make(`turn-${index}`),
|
||||
state: "completed",
|
||||
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
startedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
completedAt: `2026-06-01T0${index}:10:00.000Z`,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
];
|
||||
|
||||
const layout = buildThreadListV2Items({
|
||||
threads,
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
settledLimit: 2,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.hiddenSettledCount).toBe(2);
|
||||
expect(layout.items.filter((item) => item.variant === "slim")).toHaveLength(2);
|
||||
// Most recent settled first — the hidden ones are the oldest.
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual([
|
||||
"active",
|
||||
"settled-3",
|
||||
"settled-2",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,172 +0,0 @@
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* Thread List v2 model, ported from the web sidebar v2
|
||||
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
|
||||
*
|
||||
* Four visual states, three colors: color is reserved for "act now"
|
||||
* (approval), "in motion" (working), and "broken" (failed). Ready is the
|
||||
* unlabeled resting state.
|
||||
*/
|
||||
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
|
||||
|
||||
// Settled-tail paging: recent history is the common lookup; the deep tail
|
||||
// stays behind an explicit Show more. Shared by the compact Home list and
|
||||
// the iPad sidebar so both page identically.
|
||||
export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
|
||||
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
|
||||
|
||||
export function resolveThreadListV2Status(
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
|
||||
): ThreadListV2Status {
|
||||
if (thread.hasPendingApprovals) {
|
||||
return "approval";
|
||||
}
|
||||
if (thread.hasPendingUserInput) {
|
||||
return "input";
|
||||
}
|
||||
if (thread.session?.status === "running" || thread.session?.status === "starting") {
|
||||
return "working";
|
||||
}
|
||||
if (thread.session?.status === "error") {
|
||||
return "failed";
|
||||
}
|
||||
return "ready";
|
||||
}
|
||||
|
||||
/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
|
||||
poison the whole ordering, so it sinks to the epoch instead. */
|
||||
function parseTimestampMs(isoDate: string): number {
|
||||
const parsed = Date.parse(isoDate);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
/** First VALID timestamp wins: a present-yet-malformed string falls through
|
||||
to the next candidate rather than sinking the row to the epoch. */
|
||||
function firstValidTimestampMs(...candidates: ReadonlyArray<string | null | undefined>): number {
|
||||
for (const candidate of candidates) {
|
||||
if (candidate == null) continue;
|
||||
const parsed = Date.parse(candidate);
|
||||
if (!Number.isNaN(parsed)) return parsed;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* v2 sort: static creation order, newest thread on top. Activity NEVER
|
||||
* reorders the list — a row holds its position from open until settled, so
|
||||
* the screen only moves at lifecycle transitions. Mirrors web's
|
||||
* sortThreadsForSidebarV2.
|
||||
*/
|
||||
export function sortThreadsForListV2<T extends { readonly id: string; readonly createdAt: string }>(
|
||||
threads: readonly T[],
|
||||
): T[] {
|
||||
// .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023
|
||||
// change-by-copy array methods.
|
||||
return [...threads].sort(
|
||||
(left, right) =>
|
||||
parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) ||
|
||||
left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
|
||||
export interface ThreadListV2Item {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
/** First settled row after the card block draws the SETTLED divider. */
|
||||
readonly showSettledDivider: boolean;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadListV2Layout {
|
||||
readonly items: ThreadListV2Item[];
|
||||
/** Settled threads beyond the render limit (behind "Show more"). */
|
||||
readonly hiddenSettledCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Partitions visible threads into the active card block (creation order) and
|
||||
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
|
||||
* mirrors the web default of 3 — mobile has no client-settings sync yet, so
|
||||
* the default is fixed here rather than user-configurable.
|
||||
*/
|
||||
export function buildThreadListV2Items(input: {
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly projectRefs?: ReadonlyArray<{
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectId: ProjectId;
|
||||
}> | null;
|
||||
readonly searchQuery: string;
|
||||
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
|
||||
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
|
||||
/** Environments whose server supports thread.settle/unsettle. Threads on
|
||||
other environments never classify as settled — the user could neither
|
||||
un-settle nor pin them. Absent = no gating (tests). */
|
||||
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
readonly autoSettleAfterDays?: number;
|
||||
/** Max settled rows to render; the rest are counted, not built. */
|
||||
readonly settledLimit?: number;
|
||||
/** Injectable for tests; defaults to now. */
|
||||
readonly now?: string;
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const projectKeys = input.projectRefs
|
||||
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
|
||||
: null;
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
for (const thread of input.threads) {
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
// and partition into the tail via effectiveSettled.
|
||||
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
|
||||
if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
|
||||
continue;
|
||||
}
|
||||
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
|
||||
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const changeRequestState =
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
) {
|
||||
settled.push(thread);
|
||||
} else {
|
||||
active.push(thread);
|
||||
}
|
||||
}
|
||||
|
||||
const orderedActive = sortThreadsForListV2(active);
|
||||
const orderedSettled = [...settled].sort(
|
||||
(left, right) =>
|
||||
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
|
||||
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
|
||||
);
|
||||
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
|
||||
const visibleSettled =
|
||||
orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
|
||||
|
||||
const items: ThreadListV2Item[] = [];
|
||||
for (const thread of orderedActive) {
|
||||
items.push({ thread, variant: "card", showSettledDivider: false, isLast: false });
|
||||
}
|
||||
for (const [index, thread] of visibleSettled.entries()) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "slim",
|
||||
showSettledDivider: index === 0,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
const last = items.at(-1);
|
||||
if (last) {
|
||||
items[items.length - 1] = { ...last, isLast: true };
|
||||
}
|
||||
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
|
||||
}
|
||||
@@ -15,7 +15,6 @@ export type ModelOption = {
|
||||
readonly providerKey: string;
|
||||
readonly providerLabel: string;
|
||||
readonly providerDriver: string;
|
||||
readonly isDefault: boolean;
|
||||
readonly capabilities: ModelCapabilities | null;
|
||||
readonly selection: ModelSelection;
|
||||
};
|
||||
@@ -79,7 +78,6 @@ export function buildModelOptions(
|
||||
providerKey: provider.instanceId,
|
||||
providerLabel,
|
||||
providerDriver: provider.driver,
|
||||
isDefault: model.isDefault === true,
|
||||
capabilities: model.capabilities,
|
||||
selection: normalizeSelectionOptions(
|
||||
{
|
||||
@@ -109,7 +107,6 @@ export function buildModelOptions(
|
||||
providerKey: fallbackModelSelection.instanceId,
|
||||
providerLabel,
|
||||
providerDriver: fallbackModelSelection.instanceId,
|
||||
isDefault: false,
|
||||
capabilities: null,
|
||||
selection: fallbackModelSelection,
|
||||
});
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { supportsNativeLiquidGlass } from "./native-glass-capability";
|
||||
|
||||
describe("supportsNativeLiquidGlass", () => {
|
||||
it("uses native liquid glass when iOS reports the capability", () => {
|
||||
expect(supportsNativeLiquidGlass("ios", true)).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps pre-glass iOS on the solid fallback", () => {
|
||||
expect(supportsNativeLiquidGlass("ios", false)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not enable iOS liquid-glass layout behavior on other platforms", () => {
|
||||
expect(supportsNativeLiquidGlass("android", true)).toBe(false);
|
||||
expect(supportsNativeLiquidGlass("web", true)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +0,0 @@
|
||||
export function supportsNativeLiquidGlass(
|
||||
platform: string,
|
||||
nativeCapabilityAvailable: boolean,
|
||||
): boolean {
|
||||
return platform === "ios" && nativeCapabilityAvailable;
|
||||
}
|
||||
@@ -38,8 +38,6 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -50,8 +50,6 @@ function makeThread(
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -414,20 +412,6 @@ describe("buildThreadFeed", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("appends active work as a normal timeline row", () => {
|
||||
const startedAt = "2026-04-01T00:00:01.000Z";
|
||||
const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt);
|
||||
|
||||
expect(presented).toEqual([
|
||||
{
|
||||
type: "working",
|
||||
id: "working-indicator-row",
|
||||
createdAt: startedAt,
|
||||
},
|
||||
]);
|
||||
expect(deriveThreadFeedPresentation(presented, null, new Set())).toEqual([]);
|
||||
});
|
||||
|
||||
it("models work-log overflow as list rows", () => {
|
||||
const activity = (
|
||||
id: string,
|
||||
|
||||
@@ -98,11 +98,6 @@ type RawThreadFeedEntry =
|
||||
|
||||
export type ThreadFeedEntry =
|
||||
| Extract<RawThreadFeedEntry, { type: "message" }>
|
||||
| {
|
||||
readonly type: "working";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
| {
|
||||
readonly type: "activity-group";
|
||||
readonly id: string;
|
||||
@@ -1110,11 +1105,9 @@ export function deriveThreadFeedPresentation(
|
||||
latestTurn: ThreadFeedLatestTurn | null,
|
||||
expandedTurnIds: ReadonlySet<TurnId>,
|
||||
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
|
||||
activeWorkStartedAt: string | null = null,
|
||||
): ThreadFeedEntry[] {
|
||||
const sourceFeed = feed.filter(
|
||||
(entry) =>
|
||||
entry.type !== "turn-fold" && entry.type !== "work-toggle" && entry.type !== "working",
|
||||
(entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle",
|
||||
);
|
||||
const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
|
||||
const collapsedEntryIds = new Set<string>();
|
||||
@@ -1143,19 +1136,12 @@ export function deriveThreadFeedPresentation(
|
||||
appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
|
||||
}
|
||||
}
|
||||
if (activeWorkStartedAt !== null) {
|
||||
result.push({
|
||||
type: "working",
|
||||
id: "working-indicator-row",
|
||||
createdAt: activeWorkStartedAt,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function appendPresentedFeedEntry(
|
||||
result: ThreadFeedEntry[],
|
||||
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" | "working" }>,
|
||||
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
|
||||
expandedWorkGroupIds: ReadonlySet<string>,
|
||||
): void {
|
||||
if (entry.type !== "activity-group") {
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
@@ -62,123 +61,20 @@ function normalizeScreenOptions(
|
||||
return normalized as NativeStackNavigationOptions;
|
||||
}
|
||||
|
||||
function optionsSignature(value: unknown, seen = new WeakSet<object>()): string {
|
||||
if (value === null) return "null";
|
||||
switch (typeof value) {
|
||||
case "boolean":
|
||||
case "number":
|
||||
case "string":
|
||||
return JSON.stringify(value);
|
||||
case "undefined":
|
||||
return "undefined";
|
||||
case "function":
|
||||
// Header factories are frequently recreated inline. Their source is
|
||||
// stable across equivalent renders, while a reference comparison would
|
||||
// make navigation.setOptions re-enter the navigator indefinitely.
|
||||
return `function:${Function.prototype.toString.call(value)}`;
|
||||
case "symbol":
|
||||
return `symbol:${String(value)}`;
|
||||
case "bigint":
|
||||
return `bigint:${String(value)}`;
|
||||
case "object": {
|
||||
const object = value as object;
|
||||
if (seen.has(object)) return "[circular]";
|
||||
seen.add(object);
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map((entry) => optionsSignature(entry, seen)).join(",")}]`;
|
||||
}
|
||||
// React refs carry mutable native instances that must not make static
|
||||
// screen options appear different after every render.
|
||||
if ("current" in object) return "[ref]";
|
||||
return `{${Object.keys(value as Record<string, unknown>)
|
||||
.sort()
|
||||
.map(
|
||||
(key) =>
|
||||
`${JSON.stringify(key)}:${optionsSignature((value as Record<string, unknown>)[key], seen)}`,
|
||||
)
|
||||
.join(",")}}`;
|
||||
}
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function stabilizeOptionFunctions(
|
||||
value: unknown,
|
||||
path: string,
|
||||
latestFunctions: Map<string, (...args: unknown[]) => unknown>,
|
||||
wrappers: Map<string, (...args: unknown[]) => unknown>,
|
||||
seen = new WeakSet<object>(),
|
||||
): unknown {
|
||||
if (typeof value === "function") {
|
||||
latestFunctions.set(path, value as (...args: unknown[]) => unknown);
|
||||
let wrapper = wrappers.get(path);
|
||||
if (!wrapper) {
|
||||
wrapper = (...args: unknown[]) => {
|
||||
return latestFunctions.get(path)?.(...args);
|
||||
};
|
||||
wrappers.set(path, wrapper);
|
||||
}
|
||||
return wrapper;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
if (seen.has(value)) return value;
|
||||
seen.add(value);
|
||||
return value.map((entry, index) =>
|
||||
stabilizeOptionFunctions(entry, `${path}[${index}]`, latestFunctions, wrappers, seen),
|
||||
);
|
||||
}
|
||||
if (value !== null && typeof value === "object") {
|
||||
if (seen.has(value) || "current" in value) return value;
|
||||
seen.add(value);
|
||||
return Object.fromEntries(
|
||||
Object.entries(value as Record<string, unknown>).map(([key, entry]) => [
|
||||
key,
|
||||
stabilizeOptionFunctions(entry, `${path}.${key}`, latestFunctions, wrappers, seen),
|
||||
]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function NativeStackScreenOptions(props: {
|
||||
readonly options?: AppNativeStackNavigationOptions;
|
||||
/**
|
||||
* Causes dynamic native header factories to be reapplied when their closed-over
|
||||
* menu content changes. Factory functions are intentionally stabilized, so
|
||||
* their source alone cannot capture a menu that was initially empty while
|
||||
* asynchronous data was loading.
|
||||
*/
|
||||
readonly optionsVersion?: unknown;
|
||||
readonly listeners?: Record<string, (event: never) => void>;
|
||||
readonly name?: string;
|
||||
}) {
|
||||
const navigation = useNativeStackNavigation();
|
||||
const lastAppliedOptionsSignatureRef = useRef<string | undefined>(undefined);
|
||||
const latestOptionFunctionsRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
|
||||
const optionFunctionWrappersRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
|
||||
const normalizedOptions = useMemo(() => normalizeScreenOptions(props.options), [props.options]);
|
||||
const stableOptions = normalizedOptions
|
||||
? (stabilizeOptionFunctions(
|
||||
normalizedOptions,
|
||||
"options",
|
||||
latestOptionFunctionsRef.current,
|
||||
optionFunctionWrappersRef.current,
|
||||
) as NativeStackNavigationOptions)
|
||||
: undefined;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!navigation || !stableOptions) {
|
||||
if (!navigation || !normalizedOptions) {
|
||||
return;
|
||||
}
|
||||
const signature = optionsSignature([stableOptions, props.optionsVersion]);
|
||||
// Avoid re-entering navigation state when semantically equal options are
|
||||
// reapplied every layout (common when callers pass unstable object literals).
|
||||
if (lastAppliedOptionsSignatureRef.current === signature) {
|
||||
return;
|
||||
}
|
||||
lastAppliedOptionsSignatureRef.current = signature;
|
||||
navigation.setOptions(stableOptions);
|
||||
}, [navigation, props.optionsVersion, stableOptions]);
|
||||
navigation.setOptions(normalizedOptions);
|
||||
}, [navigation, normalizedOptions]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!navigation || !props.listeners) {
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import { isLiquidGlassSupported } from "@callstack/liquid-glass";
|
||||
import { Platform } from "react-native";
|
||||
|
||||
import { supportsNativeLiquidGlass } from "../lib/native-glass-capability";
|
||||
|
||||
export const NATIVE_LIQUID_GLASS_SUPPORTED = supportsNativeLiquidGlass(
|
||||
Platform.OS,
|
||||
isLiquidGlassSupported,
|
||||
);
|
||||
@@ -22,13 +22,6 @@ export interface Preferences {
|
||||
readonly codeWordBreak?: boolean;
|
||||
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
readonly collapsedProjectGroups?: readonly string[];
|
||||
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.
|
||||
*/
|
||||
readonly threadListV2Enabled?: boolean;
|
||||
}
|
||||
|
||||
export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
|
||||
@@ -78,8 +71,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
codeWordBreak?: boolean;
|
||||
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
collapsedProjectGroups?: readonly string[];
|
||||
projectGroupingEnabled?: boolean;
|
||||
threadListV2Enabled?: boolean;
|
||||
} = {};
|
||||
|
||||
if (typeof parsed.liveActivitiesEnabled === "boolean") {
|
||||
@@ -106,12 +97,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
(key): key is string => typeof key === "string",
|
||||
);
|
||||
}
|
||||
if (typeof parsed.projectGroupingEnabled === "boolean") {
|
||||
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
|
||||
}
|
||||
if (typeof parsed.threadListV2Enabled === "boolean") {
|
||||
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
|
||||
}
|
||||
return preferences;
|
||||
}
|
||||
|
||||
|
||||
@@ -58,8 +58,6 @@ function threadDetailToShell(
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
settledOverride: thread.settledOverride,
|
||||
settledAt: thread.settledAt,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: latestUserMessageAt(thread),
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";
|
||||
import { runSqliteState } from "./t3-sqlite-state.ts";
|
||||
|
||||
const createFixtureDatabase = Effect.fn("createSqliteStateFixtureDatabase")(function* (
|
||||
baseDir: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const stateDir = path.join(baseDir, "userdata");
|
||||
const databasePath = path.join(stateDir, "state.sqlite");
|
||||
yield* fs.makeDirectory(stateDir, { recursive: true });
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`CREATE TABLE fixtures (id INTEGER PRIMARY KEY, label TEXT NOT NULL)`;
|
||||
yield* sql`INSERT INTO fixtures (id, label) VALUES (1, 'existing')`;
|
||||
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath })));
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("t3-sqlite-state", (it) => {
|
||||
it.effect("reports each invalid SQL source with a specific error", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-state-input-" });
|
||||
|
||||
const multipleSources = yield* runSqliteState({
|
||||
operation: "query",
|
||||
baseDir,
|
||||
sql: "SELECT 1",
|
||||
file: "fixture.sql",
|
||||
}).pipe(Effect.flip);
|
||||
assert.equal(multipleSources._tag, "SqliteStateMultipleSqlSourcesError");
|
||||
assert.equal(multipleSources.message, "Provide only one of --sql or --file.");
|
||||
|
||||
const missingSource = yield* runSqliteState({ operation: "query", baseDir }).pipe(
|
||||
Effect.flip,
|
||||
);
|
||||
assert.equal(missingSource._tag, "SqliteStateMissingSqlSourceError");
|
||||
assert.equal(missingSource.message, "Provide one of --sql or --file.");
|
||||
|
||||
const emptySql = yield* runSqliteState({
|
||||
operation: "query",
|
||||
baseDir,
|
||||
sql: " ",
|
||||
}).pipe(Effect.flip);
|
||||
assert.equal(emptySql._tag, "SqliteStateEmptySqlError");
|
||||
assert.equal(emptySql.message, "SQL input is empty.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("queries an isolated database through Effect SQL", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-state-query-" });
|
||||
yield* createFixtureDatabase(baseDir);
|
||||
|
||||
const result = yield* runSqliteState({
|
||||
operation: "query",
|
||||
baseDir,
|
||||
sql: "SELECT id, label FROM fixtures",
|
||||
});
|
||||
|
||||
assert.equal(result.operation, "query");
|
||||
if (result.operation === "query") {
|
||||
assert.deepStrictEqual(result.rows, [{ id: 1, label: "existing" }]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("backs up isolated state before writes and refuses the shared home", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-state-exec-" });
|
||||
yield* createFixtureDatabase(baseDir);
|
||||
|
||||
const mutation = yield* runSqliteState({
|
||||
operation: "exec",
|
||||
baseDir,
|
||||
sql: "INSERT INTO fixtures (id, label) VALUES (2, 'seeded')",
|
||||
});
|
||||
assert.equal(mutation.operation, "exec");
|
||||
if (mutation.operation === "exec") {
|
||||
assert.equal((yield* fs.stat(mutation.backup)).mode & 0o777, 0o600);
|
||||
}
|
||||
|
||||
const error = yield* runSqliteState(
|
||||
{
|
||||
operation: "exec",
|
||||
baseDir,
|
||||
sql: "DELETE FROM fixtures",
|
||||
},
|
||||
{ sharedHome: baseDir },
|
||||
).pipe(Effect.flip);
|
||||
assert.equal(error._tag, "SqliteStateSharedHomeMutationError");
|
||||
|
||||
const aliasParent = yield* fs.makeTempDirectoryScoped({
|
||||
prefix: "t3-sqlite-state-alias-",
|
||||
});
|
||||
const aliasBaseDir = path.join(aliasParent, "shared-home-alias");
|
||||
yield* fs.symlink(baseDir, aliasBaseDir);
|
||||
const aliasError = yield* runSqliteState(
|
||||
{
|
||||
operation: "exec",
|
||||
baseDir: aliasBaseDir,
|
||||
sql: "DELETE FROM fixtures",
|
||||
},
|
||||
{ sharedHome: baseDir },
|
||||
).pipe(Effect.flip);
|
||||
assert.equal(aliasError._tag, "SqliteStateSharedHomeMutationError");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,285 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// @effect-diagnostics nodeBuiltinImport:off - node:os resolves the shared T3 home guard.
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeOS from "node:os";
|
||||
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
|
||||
import * as Console from "effect/Console";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import { Argument, Command, Flag } from "effect/unstable/cli";
|
||||
|
||||
import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";
|
||||
|
||||
export const SqliteStateOperation = Schema.Literals(["query", "exec"]);
|
||||
export type SqliteStateOperation = typeof SqliteStateOperation.Type;
|
||||
|
||||
export class SqliteStateMultipleSqlSourcesError extends Schema.TaggedErrorClass<SqliteStateMultipleSqlSourcesError>()(
|
||||
"SqliteStateMultipleSqlSourcesError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Provide only one of --sql or --file.";
|
||||
}
|
||||
}
|
||||
|
||||
export class SqliteStateMissingSqlSourceError extends Schema.TaggedErrorClass<SqliteStateMissingSqlSourceError>()(
|
||||
"SqliteStateMissingSqlSourceError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Provide one of --sql or --file.";
|
||||
}
|
||||
}
|
||||
|
||||
export class SqliteStateEmptySqlError extends Schema.TaggedErrorClass<SqliteStateEmptySqlError>()(
|
||||
"SqliteStateEmptySqlError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "SQL input is empty.";
|
||||
}
|
||||
}
|
||||
|
||||
export class SqliteStateDatabaseMissingError extends Schema.TaggedErrorClass<SqliteStateDatabaseMissingError>()(
|
||||
"SqliteStateDatabaseMissingError",
|
||||
{
|
||||
databasePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Database does not exist at '${this.databasePath}'. Start T3 once to run migrations.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SqliteStateSharedHomeMutationError extends Schema.TaggedErrorClass<SqliteStateSharedHomeMutationError>()(
|
||||
"SqliteStateSharedHomeMutationError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Refusing to mutate the shared ~/.t3 database. Use an isolated --base-dir.";
|
||||
}
|
||||
}
|
||||
|
||||
export class SqliteStateSqlFileError extends Schema.TaggedErrorClass<SqliteStateSqlFileError>()(
|
||||
"SqliteStateSqlFileError",
|
||||
{
|
||||
filePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read SQL from '${this.filePath}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SqliteStateDatabaseError extends Schema.TaggedErrorClass<SqliteStateDatabaseError>()(
|
||||
"SqliteStateDatabaseError",
|
||||
{
|
||||
operation: SqliteStateOperation,
|
||||
databasePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to ${this.operation} SQLite database at '${this.databasePath}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
const SqliteStateValue = Schema.Union([
|
||||
Schema.Null,
|
||||
Schema.String,
|
||||
Schema.Number,
|
||||
Schema.Array(Schema.Number),
|
||||
]);
|
||||
const SqliteStateRow = Schema.Record(Schema.String, SqliteStateValue);
|
||||
const SqliteStateQueryResult = Schema.Struct({
|
||||
operation: Schema.Literal("query"),
|
||||
database: Schema.String,
|
||||
rows: Schema.Array(SqliteStateRow),
|
||||
});
|
||||
const SqliteStateExecResult = Schema.Struct({
|
||||
operation: Schema.Literal("exec"),
|
||||
database: Schema.String,
|
||||
backup: Schema.String,
|
||||
});
|
||||
const SqliteStateResult = Schema.Union([SqliteStateQueryResult, SqliteStateExecResult]);
|
||||
const encodeSqliteStateResult = Schema.encodeEffect(fromJsonStringPretty(SqliteStateResult));
|
||||
|
||||
export type SqliteStateResult = typeof SqliteStateResult.Type;
|
||||
|
||||
type RawSqliteValue = null | string | number | bigint | Uint8Array;
|
||||
type RawSqliteRow = Readonly<Record<string, RawSqliteValue>>;
|
||||
|
||||
export interface RunSqliteStateInput {
|
||||
readonly operation: SqliteStateOperation;
|
||||
readonly baseDir: string;
|
||||
readonly sql?: string | undefined;
|
||||
readonly file?: string | undefined;
|
||||
}
|
||||
|
||||
export interface RunSqliteStateOptions {
|
||||
readonly sharedHome?: string | undefined;
|
||||
}
|
||||
|
||||
const resolveSqlSource = Effect.fn("resolveSqliteStateSqlSource")(function* (
|
||||
sql: string | undefined,
|
||||
file: string | undefined,
|
||||
) {
|
||||
if (sql !== undefined && file !== undefined) {
|
||||
return yield* new SqliteStateMultipleSqlSourcesError();
|
||||
}
|
||||
if (sql === undefined && file === undefined) {
|
||||
return yield* new SqliteStateMissingSqlSourceError();
|
||||
}
|
||||
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
let source: string;
|
||||
if (sql !== undefined) {
|
||||
source = sql;
|
||||
} else {
|
||||
const filePath = path.resolve(file as string);
|
||||
source = yield* fs
|
||||
.readFileString(filePath)
|
||||
.pipe(Effect.mapError((cause) => new SqliteStateSqlFileError({ filePath, cause })));
|
||||
}
|
||||
|
||||
const trimmed = source.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return yield* new SqliteStateEmptySqlError();
|
||||
}
|
||||
return trimmed;
|
||||
});
|
||||
|
||||
function normalizeSqliteValue(value: RawSqliteValue): typeof SqliteStateValue.Type {
|
||||
if (typeof value === "bigint") {
|
||||
const numericValue = Number(value);
|
||||
return Number.isSafeInteger(numericValue) ? numericValue : value.toString();
|
||||
}
|
||||
if (value instanceof Uint8Array) {
|
||||
return Array.from(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function normalizeSqliteRow(row: RawSqliteRow): typeof SqliteStateRow.Type {
|
||||
return Object.fromEntries(
|
||||
Object.entries(row).map(([key, value]) => [key, normalizeSqliteValue(value)]),
|
||||
);
|
||||
}
|
||||
|
||||
export const runSqliteState = Effect.fn("runSqliteState")(function* (
|
||||
input: RunSqliteStateInput,
|
||||
options: RunSqliteStateOptions = {},
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = path.resolve(input.baseDir);
|
||||
const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
|
||||
const databasePath = path.join(baseDir, "userdata", "state.sqlite");
|
||||
const source = yield* resolveSqlSource(input.sql, input.file);
|
||||
|
||||
if (!(yield* fs.exists(databasePath))) {
|
||||
return yield* new SqliteStateDatabaseMissingError({ databasePath });
|
||||
}
|
||||
if (input.operation === "exec") {
|
||||
const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([
|
||||
fs.realPath(baseDir),
|
||||
fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
|
||||
]);
|
||||
if (canonicalBaseDir === canonicalSharedHome) {
|
||||
return yield* new SqliteStateSharedHomeMutationError();
|
||||
}
|
||||
}
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql.unsafe("PRAGMA busy_timeout = 5000").unprepared;
|
||||
|
||||
if (input.operation === "query") {
|
||||
const rows = yield* sql.unsafe<RawSqliteRow>(source).unprepared.pipe(
|
||||
Effect.provideService(SqlClient.SafeIntegers, true),
|
||||
Effect.map((rows) => rows.map(normalizeSqliteRow)),
|
||||
);
|
||||
return {
|
||||
operation: "query",
|
||||
database: databasePath,
|
||||
rows,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-");
|
||||
const backupPath = `${databasePath}.backup-${timestamp}`;
|
||||
yield* sql`VACUUM INTO ${backupPath}`;
|
||||
yield* fs.chmod(backupPath, 0o600);
|
||||
yield* sql.withTransaction(sql.unsafe(source).unprepared);
|
||||
|
||||
return {
|
||||
operation: "exec",
|
||||
database: databasePath,
|
||||
backup: backupPath,
|
||||
} as const;
|
||||
});
|
||||
|
||||
return yield* program.pipe(
|
||||
Effect.provide(
|
||||
NodeSqliteClient.layer({
|
||||
filename: databasePath,
|
||||
readonly: input.operation === "query",
|
||||
}),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SqliteStateDatabaseError({
|
||||
operation: input.operation,
|
||||
databasePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
export const t3SqliteStateCommand = Command.make(
|
||||
"t3-sqlite-state",
|
||||
{
|
||||
operation: Argument.choice("operation", SqliteStateOperation.literals).pipe(
|
||||
Argument.withDescription("Run a read-only query or a backed-up fixture mutation."),
|
||||
),
|
||||
baseDir: Flag.string("base-dir").pipe(
|
||||
Flag.withDescription("Explicit T3 base directory containing userdata/state.sqlite."),
|
||||
),
|
||||
sql: Flag.string("sql").pipe(
|
||||
Flag.optional,
|
||||
Flag.withDescription("SQL source supplied directly on the command line."),
|
||||
),
|
||||
file: Flag.string("file").pipe(
|
||||
Flag.optional,
|
||||
Flag.withDescription("Path to a SQL source file."),
|
||||
),
|
||||
},
|
||||
({ operation, baseDir, sql, file }) =>
|
||||
runSqliteState({
|
||||
operation,
|
||||
baseDir,
|
||||
sql: Option.getOrUndefined(sql),
|
||||
file: Option.getOrUndefined(file),
|
||||
}).pipe(Effect.flatMap(encodeSqliteStateResult), Effect.flatMap(Console.log)),
|
||||
).pipe(
|
||||
Command.withDescription(
|
||||
"Inspect or seed an isolated T3 SQLite database with automatic backups for writes.",
|
||||
),
|
||||
);
|
||||
|
||||
if (import.meta.main) {
|
||||
Command.run(t3SqliteStateCommand, { version: "0.0.0" }).pipe(
|
||||
Effect.provide(NodeServices.layer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import * as PlatformError from "effect/PlatformError";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
|
||||
|
||||
@@ -21,10 +20,7 @@ const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
const testLayer = Layer.mergeAll(
|
||||
configLayer,
|
||||
WorkspacePaths.layer,
|
||||
ProjectFaviconResolver.layer.pipe(
|
||||
Layer.provide(WorkspacePaths.layer),
|
||||
Layer.provide(T3ProjectFileLoader.layer),
|
||||
),
|
||||
ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer)),
|
||||
ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
|
||||
@@ -6,16 +6,10 @@ import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentOrchestrationHttpApi,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentOrchestrationHttpApi } from "@t3tools/contracts";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpServer from "effect/unstable/http/HttpServer";
|
||||
@@ -28,7 +22,6 @@ import { Command } from "effect/unstable/cli";
|
||||
import { cli, makeCli } from "./bin.ts";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
|
||||
@@ -202,18 +195,6 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
|
||||
);
|
||||
|
||||
it.effect("exposes service lifecycle commands without T3 Connect configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const { output } = yield* captureStdout(runCli(["service", "--help"], noConnectCli));
|
||||
|
||||
assert.include(output, "Manage the T3 Code background service.");
|
||||
assert.include(output, "install");
|
||||
assert.include(output, "uninstall");
|
||||
assert.include(output, "update");
|
||||
assert.include(output, "status");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports fresh headless connect state without requiring local configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
@@ -255,7 +236,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts the --headless login override without enabling access", () =>
|
||||
it.effect("logs in to headless connect without enabling access", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-login-test-"),
|
||||
@@ -273,7 +254,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
);
|
||||
|
||||
const login = yield* captureStdout(
|
||||
runConnectCli(["connect", "login", "--base-dir", baseDir, "--headless"]),
|
||||
runConnectCli(["connect", "login", "--base-dir", baseDir]),
|
||||
);
|
||||
const status = yield* captureStdout(
|
||||
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
|
||||
@@ -284,7 +265,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
readonly authenticated: boolean;
|
||||
};
|
||||
|
||||
assert.equal(login.output, "✓ Signed in");
|
||||
assert.equal(login.output, "Signed in to T3 Connect.");
|
||||
assert.isFalse(decoded.desired);
|
||||
assert.isTrue(decoded.authenticated);
|
||||
}),
|
||||
@@ -317,10 +298,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
output,
|
||||
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
|
||||
);
|
||||
assert.equal(output, "Signed out of T3 Connect locally.");
|
||||
assert.isFalse(NodeFS.existsSync(tokenPath));
|
||||
}),
|
||||
);
|
||||
@@ -482,63 +460,6 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("force removes projects that still contain threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-force-remove-test-"),
|
||||
);
|
||||
const workspaceRoot = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-force-remove-workspace-"),
|
||||
);
|
||||
|
||||
yield* runCliWithRuntime(["project", "add", workspaceRoot, "--base-dir", baseDir]);
|
||||
const afterAdd = yield* readPersistedSnapshot(baseDir);
|
||||
const project = afterAdd.projects.find(
|
||||
(candidate) => candidate.workspaceRoot === workspaceRoot && candidate.deletedAt === null,
|
||||
);
|
||||
assert.isTrue(project !== undefined);
|
||||
|
||||
const config = yield* makeCliTestServerConfig(baseDir);
|
||||
yield* Effect.gen(function* () {
|
||||
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
|
||||
yield* engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-cli-force-remove-thread"),
|
||||
threadId: ThreadId.make("thread-cli-force-remove"),
|
||||
projectId: project!.id,
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: DateTime.formatIso(yield* DateTime.now),
|
||||
});
|
||||
}).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
|
||||
|
||||
yield* runCliWithRuntime([
|
||||
"project",
|
||||
"remove",
|
||||
project!.id,
|
||||
"--force",
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const afterRemove = yield* readPersistedSnapshot(baseDir);
|
||||
assert.isTrue(
|
||||
(afterRemove.projects.find((candidate) => candidate.id === project!.id)?.deletedAt ??
|
||||
null) !== null,
|
||||
);
|
||||
assert.isTrue(
|
||||
(afterRemove.threads.find((thread) => thread.id === "thread-cli-force-remove")?.deletedAt ??
|
||||
null) !== null,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes project commands through a running server when runtime state is present", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
|
||||
@@ -13,7 +13,6 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import { sharedServerCommandFlags } from "./cli/config.ts";
|
||||
import { projectCommand } from "./cli/project.ts";
|
||||
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
|
||||
import { serviceCommand } from "./cli/service.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
@@ -48,7 +47,6 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
|
||||
serveCommand,
|
||||
authCommand,
|
||||
projectCommand,
|
||||
serviceCommand,
|
||||
cloudEnabled ? connectCommand : connectUnavailableCommand,
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -69,7 +69,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
return "full thread diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -178,7 +177,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -262,7 +260,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -304,102 +301,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("filters git-attributed sections and reports gitFileCount from patch sections", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-attribution");
|
||||
const threadId = ThreadId.make("thread-attribution");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const patch = [
|
||||
"diff --git a/agent.ts b/agent.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/agent.ts",
|
||||
"+++ b/agent.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"diff --git a/pulled.ts b/pulled.ts",
|
||||
"index 3333333..4444444 100644",
|
||||
"--- a/pulled.ts",
|
||||
"+++ b/pulled.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-before",
|
||||
"+after",
|
||||
"",
|
||||
].join("\n");
|
||||
// Attribution also tags a path that has no section in this patch
|
||||
// (e.g. whitespace-only change elided by ignoreWhitespace) — it must
|
||||
// not count toward gitFileCount.
|
||||
const attribution = new Map<string, "agent" | "git">([
|
||||
["agent.ts", "agent"],
|
||||
["pulled.ts", "git"],
|
||||
["whitespace-only.ts", "git"],
|
||||
]);
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed(patch),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(attribution),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getArchivedShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const { filtered, revealed } = yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
const filtered = yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
const revealed = yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
includeGitChanges: true,
|
||||
});
|
||||
return { filtered, revealed };
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(filtered.diff).toContain("agent.ts");
|
||||
expect(filtered.diff).not.toContain("pulled.ts");
|
||||
expect(filtered.gitFileCount).toBe(1);
|
||||
expect(revealed.diff).toBe(patch);
|
||||
expect(revealed.gitFileCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not preflight checkpoint refs before diffing", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-no-preflight");
|
||||
@@ -427,7 +328,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed("diff patch"),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
@@ -481,7 +381,6 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed(""),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
attributeCheckpointDiff: () => Effect.succeed(null),
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
} from "./Errors.ts";
|
||||
import type { CheckpointServiceError } from "./Errors.ts";
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import { filterUnifiedDiffFiles, listUnifiedDiffPaths } from "./Diffs.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
|
||||
/** Service tag for checkpoint diff queries. */
|
||||
@@ -67,14 +66,12 @@ function buildTurnDiffResult(
|
||||
readonly toTurnCount: number;
|
||||
},
|
||||
diff: string,
|
||||
gitFileCount?: number,
|
||||
): OrchestrationGetTurnDiffResultType {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
diff,
|
||||
...(gitFileCount !== undefined ? { gitFileCount } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -82,51 +79,6 @@ export const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
|
||||
// Drop file sections attributed to pre-existing git history from a patch
|
||||
// unless the caller opted in. Attribution failures degrade to the
|
||||
// unfiltered patch — never block the diff on attribution. The returned
|
||||
// gitFileCount comes from the SAME attribution pass that produced the
|
||||
// patch, so UI driven by it always agrees with what is rendered;
|
||||
// undefined means attribution was unavailable and nothing was filtered.
|
||||
const applyAttributionFilter = Effect.fn("applyAttributionFilter")(function* (input: {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly diff: string;
|
||||
readonly includeGitChanges: boolean;
|
||||
}): Effect.fn.Return<{ readonly diff: string; readonly gitFileCount: number | undefined }> {
|
||||
if (input.diff.trim().length === 0) {
|
||||
return { diff: input.diff, gitFileCount: undefined };
|
||||
}
|
||||
const attribution = yield* checkpointStore
|
||||
.attributeCheckpointDiff({
|
||||
cwd: input.cwd,
|
||||
fromCheckpointRef: input.fromCheckpointRef,
|
||||
toCheckpointRef: input.toCheckpointRef,
|
||||
})
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (attribution === null) {
|
||||
return { diff: input.diff, gitFileCount: undefined };
|
||||
}
|
||||
// Count only git-attributed paths with a section in THIS patch. The
|
||||
// attribution map can include paths absent from the patch (e.g.
|
||||
// whitespace-only changes elided by ignoreWhitespace) — counting those
|
||||
// would advertise hidden files the toggle can never reveal.
|
||||
let gitFileCount = 0;
|
||||
for (const path of listUnifiedDiffPaths(input.diff)) {
|
||||
if (attribution.get(path) === "git") {
|
||||
gitFileCount += 1;
|
||||
}
|
||||
}
|
||||
if (input.includeGitChanges || gitFileCount === 0) {
|
||||
return { diff: input.diff, gitFileCount };
|
||||
}
|
||||
return {
|
||||
diff: filterUnifiedDiffFiles(input.diff, (path) => attribution.get(path) !== "git"),
|
||||
gitFileCount,
|
||||
};
|
||||
});
|
||||
|
||||
const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
@@ -212,7 +164,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const rawDiff = yield* checkpointStore
|
||||
const diff = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
@@ -221,15 +173,8 @@ export const make = Effect.gen(function* () {
|
||||
ignoreWhitespace,
|
||||
})
|
||||
.pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
|
||||
const filtered = yield* applyAttributionFilter({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
diff: rawDiff,
|
||||
includeGitChanges: input.includeGitChanges ?? false,
|
||||
});
|
||||
|
||||
const turnDiff = buildTurnDiffResult(input, filtered.diff, filtered.gitFileCount);
|
||||
const turnDiff = buildTurnDiffResult(input, diff);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
operation,
|
||||
@@ -309,24 +254,15 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, 0);
|
||||
const toCheckpointRef = threadContext.value.toCheckpointRef as CheckpointRef;
|
||||
const rawDiff = yield* checkpointStore
|
||||
const diff = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),
|
||||
toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
})
|
||||
.pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
|
||||
const filtered = yield* applyAttributionFilter({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
diff: rawDiff,
|
||||
includeGitChanges: input.includeGitChanges ?? false,
|
||||
});
|
||||
|
||||
const turnDiff = buildTurnDiffResult(
|
||||
{
|
||||
@@ -334,8 +270,7 @@ export const make = Effect.gen(function* () {
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
},
|
||||
filtered.diff,
|
||||
filtered.gitFileCount,
|
||||
diff,
|
||||
);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
|
||||
@@ -55,7 +55,6 @@ function writeTextFile(
|
||||
function git(
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
env?: NodeJS.ProcessEnv,
|
||||
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
|
||||
return Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
@@ -64,19 +63,12 @@ function git(
|
||||
command: "git",
|
||||
cwd,
|
||||
args,
|
||||
...(env ? { env: { ...global.process.env, ...env } } : {}),
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
return result.stdout.trim();
|
||||
});
|
||||
}
|
||||
|
||||
/** Author and committer dates both in the past: a genuinely pre-existing commit. */
|
||||
const PRE_EXISTING_COMMIT_ENV: NodeJS.ProcessEnv = {
|
||||
GIT_AUTHOR_DATE: "2020-01-01T00:00:00Z",
|
||||
GIT_COMMITTER_DATE: "2020-01-01T00:00:00Z",
|
||||
};
|
||||
|
||||
function initRepoWithCommit(
|
||||
cwd: string,
|
||||
): Effect.Effect<
|
||||
@@ -230,237 +222,4 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("attributeCheckpointDiff", () => {
|
||||
it.effect("returns an empty map when HEAD did not move", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-no-head-move");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.size).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("attributes a branch switch to git while keeping tool edits as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = yield* git(tmp, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
||||
// A second branch with a pre-existing commit, created before the turn.
|
||||
yield* git(tmp, ["checkout", "-b", "feature"]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "feature.ts"), "export const feature = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "feature work"], PRE_EXISTING_COMMIT_ENV);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-branch-switch");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": switch branches (history-driven) and also edit a file.
|
||||
yield* git(tmp, ["checkout", "feature"]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("feature.ts")).toBe("git");
|
||||
expect(attribution!.get("edited.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps files committed during the turn as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-own-commit");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": edit and commit — HEAD moves, but by a turn-authored commit.
|
||||
yield* writeTextFile(NodePath.join(tmp, "committed.ts"), "export const done = true;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "agent commit"]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("committed.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("attributes a cherry-pick of a pre-existing commit to git", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = yield* git(tmp, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
||||
// Pre-existing commit on another branch, authored before the turn.
|
||||
yield* git(tmp, ["checkout", "-b", "source"]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "picked.ts"), "export const picked = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(
|
||||
tmp,
|
||||
[
|
||||
"-c",
|
||||
"[email protected]",
|
||||
"-c",
|
||||
"user.name=Other",
|
||||
"commit",
|
||||
"-m",
|
||||
"source work",
|
||||
],
|
||||
PRE_EXISTING_COMMIT_ENV,
|
||||
);
|
||||
const pickedOid = yield* git(tmp, ["rev-parse", "HEAD"]);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-cherry-pick");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
yield* git(tmp, ["cherry-pick", pickedOid]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("picked.ts")).toBe("git");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps an amend of a pre-turn commit as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
// Pre-turn commit with an old author date, as amend preserves it.
|
||||
yield* writeTextFile(NodePath.join(tmp, "amended.ts"), "export const value = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "pre-turn work", "--date", "2020-01-01T00:00:00Z"]);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-amend");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": edit the file and amend it into the pre-turn commit.
|
||||
// The author date stays 2020, but the content is new agent work.
|
||||
yield* writeTextFile(NodePath.join(tmp, "amended.ts"), "export const value = 2;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "--amend", "--no-edit"]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("amended.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a whitespace-only amend of a pre-turn commit as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
// Pre-turn commit; its pre-amend state stays reachable via reflog,
|
||||
// which is exactly the patch-id collision candidate.
|
||||
yield* writeTextFile(NodePath.join(tmp, "style.ts"), "export const x = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "pre-turn work"], PRE_EXISTING_COMMIT_ENV);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-ws-amend");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": whitespace-only reformat amended into the pre-turn
|
||||
// commit. `git patch-id --stable` would hash this identically to the
|
||||
// original (it strips whitespace); --verbatim must not.
|
||||
yield* writeTextFile(NodePath.join(tmp, "style.ts"), "export const x = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "--amend", "--no-edit"]);
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).not.toBe(null);
|
||||
expect(attribution!.get("style.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns null for legacy checkpoints without head metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-legacy");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
// Simulate a pre-attribution checkpoint: commit the tree with the old
|
||||
// single-line message format.
|
||||
const treeOid = yield* git(tmp, ["write-tree"]);
|
||||
const legacyCommit = yield* git(tmp, [
|
||||
"commit-tree",
|
||||
treeOid,
|
||||
"-m",
|
||||
`t3 checkpoint ref=${fromCheckpointRef}`,
|
||||
]);
|
||||
yield* git(tmp, ["update-ref", fromCheckpointRef, legacyCommit]);
|
||||
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
|
||||
|
||||
const attribution = yield* checkpointStore.attributeCheckpointDiff({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(attribution).toBe(null);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -46,18 +46,6 @@ export interface DeleteCheckpointRefsInput {
|
||||
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
|
||||
}
|
||||
|
||||
export interface AttributeCheckpointDiffInput {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-path origin classification of a checkpoint tree delta, or null when
|
||||
* attribution is unavailable (see VcsCheckpointAttribution).
|
||||
*/
|
||||
export type CheckpointAttribution = ReadonlyMap<string, "agent" | "git"> | null;
|
||||
|
||||
/** Service tag for checkpoint persistence and restore operations. */
|
||||
export class CheckpointStore extends Context.Service<
|
||||
CheckpointStore,
|
||||
@@ -105,17 +93,6 @@ export class CheckpointStore extends Context.Service<
|
||||
readonly deleteCheckpointRefs: (
|
||||
input: DeleteCheckpointRefsInput,
|
||||
) => Effect.Effect<void, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Classify each path in a checkpoint-to-checkpoint tree delta as
|
||||
* agent-authored or explained by pre-existing git history.
|
||||
*
|
||||
* Returns null when attribution is unavailable (legacy checkpoints
|
||||
* without HEAD metadata, or truncated git output).
|
||||
*/
|
||||
readonly attributeCheckpointDiff: (
|
||||
input: AttributeCheckpointDiffInput,
|
||||
) => Effect.Effect<CheckpointAttribution, CheckpointStoreError>;
|
||||
}
|
||||
>()("t3/checkpointing/CheckpointStore") {}
|
||||
|
||||
@@ -180,16 +157,6 @@ export const make = Effect.gen(function* () {
|
||||
return yield* checkpoints.deleteCheckpointRefs(input);
|
||||
});
|
||||
|
||||
const attributeCheckpointDiff: CheckpointStore["Service"]["attributeCheckpointDiff"] = Effect.fn(
|
||||
"attributeCheckpointDiff",
|
||||
)(function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints(
|
||||
"CheckpointStore.attributeCheckpointDiff",
|
||||
input.cwd,
|
||||
);
|
||||
return yield* checkpoints.attributeCheckpointDiff(input);
|
||||
});
|
||||
|
||||
return CheckpointStore.of({
|
||||
isGitRepository,
|
||||
captureCheckpoint,
|
||||
@@ -197,7 +164,6 @@ export const make = Effect.gen(function* () {
|
||||
restoreCheckpoint,
|
||||
diffCheckpoints,
|
||||
deleteCheckpointRefs,
|
||||
attributeCheckpointDiff,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { filterUnifiedDiffFiles, parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
|
||||
import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
|
||||
|
||||
describe("parseTurnDiffFilesFromUnifiedDiff", () => {
|
||||
it("returns empty list for empty diff", () => {
|
||||
@@ -66,159 +66,3 @@ describe("parseTurnDiffFilesFromUnifiedDiff", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterUnifiedDiffFiles", () => {
|
||||
const twoFileDiff = [
|
||||
"diff --git a/kept.ts b/kept.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/kept.ts",
|
||||
"+++ b/kept.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"diff --git a/dropped.ts b/dropped.ts",
|
||||
"index 3333333..4444444 100644",
|
||||
"--- a/dropped.ts",
|
||||
"+++ b/dropped.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-before",
|
||||
"+after",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
it("removes sections whose path is rejected", () => {
|
||||
const filtered = filterUnifiedDiffFiles(twoFileDiff, (path) => path !== "dropped.ts");
|
||||
expect(filtered).toContain("kept.ts");
|
||||
expect(filtered).not.toContain("dropped.ts");
|
||||
expect(parseTurnDiffFilesFromUnifiedDiff(filtered)).toEqual([
|
||||
{ path: "kept.ts", additions: 1, deletions: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns the diff unchanged when everything is kept", () => {
|
||||
expect(filterUnifiedDiffFiles(twoFileDiff, () => true)).toBe(twoFileDiff);
|
||||
});
|
||||
|
||||
it("filters deleted files via the --- a/ path", () => {
|
||||
const deletionDiff = [
|
||||
"diff --git a/removed.ts b/removed.ts",
|
||||
"deleted file mode 100644",
|
||||
"index 1111111..0000000",
|
||||
"--- a/removed.ts",
|
||||
"+++ /dev/null",
|
||||
"@@ -1,1 +0,0 @@",
|
||||
"-gone",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(deletionDiff, (path) => path !== "removed.ts").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("filters simple header-only sections via the diff --git header", () => {
|
||||
const oddDiff = ["diff --git a/x b/x", "Binary files differ", ""].join("\n");
|
||||
expect(filterUnifiedDiffFiles(oddDiff, (path) => path !== "x").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("keeps unparseable sections", () => {
|
||||
const oddDiff = ["diff --git malformed-header", "Binary files differ", ""].join("\n");
|
||||
expect(filterUnifiedDiffFiles(oddDiff, () => false)).toBe(oddDiff);
|
||||
});
|
||||
|
||||
it("returns empty diff unchanged", () => {
|
||||
expect(filterUnifiedDiffFiles("", () => false)).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDiffSectionPath via renames", () => {
|
||||
it("filters rename sections by the post-image path", () => {
|
||||
const renameDiff = [
|
||||
"diff --git a/old/name.ts b/new/name.ts",
|
||||
"similarity index 90%",
|
||||
"rename from old/name.ts",
|
||||
"rename to new/name.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/old/name.ts",
|
||||
"+++ b/new/name.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-before",
|
||||
"+after",
|
||||
"",
|
||||
].join("\n");
|
||||
// The attribution map is keyed by post-image paths; a filter that only
|
||||
// knows the new path must still match this section.
|
||||
expect(filterUnifiedDiffFiles(renameDiff, (path) => path !== "new/name.ts").trim()).toBe("");
|
||||
expect(filterUnifiedDiffFiles(renameDiff, (path) => path !== "old/name.ts")).toBe(renameDiff);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterUnifiedDiffFiles fallback paths", () => {
|
||||
it("filters binary sections via the diff --git header", () => {
|
||||
const binaryDiff = [
|
||||
"diff --git a/assets/logo.png b/assets/logo.png",
|
||||
"index 1111111..2222222 100644",
|
||||
"Binary files a/assets/logo.png and b/assets/logo.png differ",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(binaryDiff, (path) => path !== "assets/logo.png").trim()).toBe(
|
||||
"",
|
||||
);
|
||||
expect(filterUnifiedDiffFiles(binaryDiff, () => true)).toBe(binaryDiff);
|
||||
});
|
||||
|
||||
it("filters mode-only sections via the diff --git header", () => {
|
||||
const modeDiff = [
|
||||
"diff --git a/scripts/run.sh b/scripts/run.sh",
|
||||
"old mode 100644",
|
||||
"new mode 100755",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(modeDiff, (path) => path !== "scripts/run.sh").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("filters binary sections with spaces in the path", () => {
|
||||
const binaryDiff = [
|
||||
"diff --git a/my assets/logo file.png b/my assets/logo file.png",
|
||||
"Binary files differ",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(
|
||||
filterUnifiedDiffFiles(binaryDiff, (path) => path !== "my assets/logo file.png").trim(),
|
||||
).toBe("");
|
||||
});
|
||||
|
||||
it("decodes git C-style quoted paths", () => {
|
||||
const quotedDiff = [
|
||||
'diff --git "a/sp\\303\\244ce.ts" "b/sp\\303\\244ce.ts"',
|
||||
"index 1111111..2222222 100644",
|
||||
'--- "a/sp\\303\\244ce.ts"',
|
||||
'+++ "b/sp\\303\\244ce.ts"',
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"",
|
||||
].join("\n");
|
||||
// git octal-escapes the raw UTF-8 bytes (`ä` = \303\244); the decoder
|
||||
// must reassemble them into the real character, not per-byte mojibake.
|
||||
expect(filterUnifiedDiffFiles(quotedDiff, (path) => path !== "späce.ts").trim()).toBe("");
|
||||
});
|
||||
|
||||
it("filters rename-only sections without hunks via rename metadata", () => {
|
||||
const renameOnlyDiff = [
|
||||
"diff --git a/old.ts b/new.ts",
|
||||
"similarity index 100%",
|
||||
"rename from old.ts",
|
||||
"rename to new.ts",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(filterUnifiedDiffFiles(renameOnlyDiff, (path) => path !== "new.ts").trim()).toBe("");
|
||||
expect(filterUnifiedDiffFiles(renameOnlyDiff, (path) => path !== "old.ts")).toBe(
|
||||
renameOnlyDiff,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps ambiguous unquoted rename headers", () => {
|
||||
// Rename of a space-containing path is ambiguous in the header when git
|
||||
// does not quote; with no other metadata the section must be kept.
|
||||
const ambiguous = ["diff --git a/x y b/y z", "Binary files differ", ""].join("\n");
|
||||
expect(filterUnifiedDiffFiles(ambiguous, () => false)).toBe(ambiguous);
|
||||
});
|
||||
});
|
||||
@@ -25,179 +25,3 @@ export function parseTurnDiffFilesFromUnifiedDiff(
|
||||
|
||||
return files.toSorted((left, right) => left.path.localeCompare(right.path));
|
||||
}
|
||||
|
||||
const SIMPLE_ESCAPES: Record<string, number> = {
|
||||
"\\": 0x5c,
|
||||
'"': 0x22,
|
||||
a: 0x07,
|
||||
b: 0x08,
|
||||
f: 0x0c,
|
||||
n: 0x0a,
|
||||
r: 0x0d,
|
||||
t: 0x09,
|
||||
v: 0x0b,
|
||||
};
|
||||
|
||||
function stripGitPathQuoting(value: string): string {
|
||||
if (!(value.startsWith('"') && value.endsWith('"') && value.length >= 2)) {
|
||||
return value;
|
||||
}
|
||||
// Git C-style quoting: octal escapes are raw UTF-8 BYTES (e.g. `ä` is
|
||||
// `\303\244`), so decode into a byte buffer first and UTF-8-decode the
|
||||
// whole path at the end — per-escape String.fromCharCode would yield
|
||||
// mojibake that never matches attribution map keys.
|
||||
const inner = value.slice(1, -1);
|
||||
const bytes: Array<number> = [];
|
||||
const encoder = new TextEncoder();
|
||||
for (let index = 0; index < inner.length; index += 1) {
|
||||
const char = inner[index]!;
|
||||
if (char !== "\\" || index === inner.length - 1) {
|
||||
bytes.push(...encoder.encode(char));
|
||||
continue;
|
||||
}
|
||||
const next = inner[index + 1]!;
|
||||
const simple = SIMPLE_ESCAPES[next];
|
||||
if (simple !== undefined) {
|
||||
bytes.push(simple);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
const octal = /^[0-7]{1,3}/.exec(inner.slice(index + 1))?.[0];
|
||||
if (octal) {
|
||||
bytes.push(parseInt(octal, 8) & 0xff);
|
||||
index += octal.length;
|
||||
continue;
|
||||
}
|
||||
bytes.push(...encoder.encode(char));
|
||||
}
|
||||
return new TextDecoder("utf-8", { fatal: false }).decode(new Uint8Array(bytes));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the post-image path out of a `diff --git a/<path> b/<path>` header.
|
||||
*
|
||||
* Only trustworthy when both paths are quoted or the two paths are equal
|
||||
* (no rename): for unquoted renamed paths containing spaces the split is
|
||||
* ambiguous, so return null and let the caller keep the section.
|
||||
*/
|
||||
function resolveDiffGitHeaderPath(headerLine: string): string | null {
|
||||
const spec = headerLine.slice("diff --git ".length).trim();
|
||||
const quotedMatch = /^("(?:[^"\\]|\\.)*"|\S+) ("(?:[^"\\]|\\.)*"|\S+)$/.exec(spec);
|
||||
if (quotedMatch) {
|
||||
const source = stripGitPathQuoting(quotedMatch[1]!);
|
||||
const target = stripGitPathQuoting(quotedMatch[2]!);
|
||||
if (source.startsWith("a/") && target.startsWith("b/")) {
|
||||
return target.slice(2);
|
||||
}
|
||||
}
|
||||
// Paths with spaces are unquoted in this header; recover the symmetric
|
||||
// a/X b/X form (covers everything but renames of space-containing paths).
|
||||
if (spec.length % 2 === 1) {
|
||||
const midpoint = (spec.length - 1) / 2;
|
||||
const source = spec.slice(0, midpoint);
|
||||
const target = spec.slice(midpoint + 1);
|
||||
if (source.startsWith("a/") && target.startsWith("b/") && source.slice(2) === target.slice(2)) {
|
||||
return target.slice(2);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the post-image path of one `diff --git` section, preferring the
|
||||
* `+++ b/` line and falling back to `--- a/` for deletions. Binary and
|
||||
* mode-only sections have neither, so fall back to rename/copy metadata and
|
||||
* finally the `diff --git` header itself. Returns null when the section is
|
||||
* unparseable; callers should keep such sections.
|
||||
*/
|
||||
function resolveDiffSectionPath(section: string): string | null {
|
||||
// `--- a/` precedes `+++ b/` in a section, so resolve the post-image path
|
||||
// in a full pass before falling back — for renames the two differ, and the
|
||||
// attribution map is keyed by the post-image path.
|
||||
let fallbackSource: string | null = null;
|
||||
let renameTarget: string | null = null;
|
||||
let headerPath: string | null = null;
|
||||
for (const line of section.split("\n")) {
|
||||
if (line.startsWith("+++ ")) {
|
||||
const target = stripGitPathQuoting(line.slice(4).trim());
|
||||
if (target !== "/dev/null") {
|
||||
return target.startsWith("b/") ? target.slice(2) : target;
|
||||
}
|
||||
} else if (line.startsWith("--- ") && fallbackSource === null) {
|
||||
const source = stripGitPathQuoting(line.slice(4).trim());
|
||||
if (source !== "/dev/null" && source.startsWith("a/")) {
|
||||
fallbackSource = source.slice(2);
|
||||
}
|
||||
} else if (
|
||||
(line.startsWith("rename to ") || line.startsWith("copy to ")) &&
|
||||
renameTarget === null
|
||||
) {
|
||||
renameTarget = stripGitPathQuoting(line.slice(line.indexOf(" to ") + 4));
|
||||
} else if (line.startsWith("diff --git ") && headerPath === null) {
|
||||
headerPath = resolveDiffGitHeaderPath(line);
|
||||
}
|
||||
}
|
||||
return fallbackSource ?? renameTarget ?? headerPath;
|
||||
}
|
||||
|
||||
function splitUnifiedDiffSections(diff: string): ReadonlyArray<string> {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
if (normalized.trim().length === 0) {
|
||||
return [];
|
||||
}
|
||||
const sections: Array<string> = [];
|
||||
let currentStart = -1;
|
||||
const lines = normalized.split("\n");
|
||||
const flush = (endExclusive: number) => {
|
||||
if (currentStart >= 0) {
|
||||
sections.push(lines.slice(currentStart, endExclusive).join("\n"));
|
||||
}
|
||||
};
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
if (lines[index]!.startsWith("diff --git ")) {
|
||||
flush(index);
|
||||
currentStart = index;
|
||||
}
|
||||
}
|
||||
flush(lines.length);
|
||||
return sections;
|
||||
}
|
||||
|
||||
/**
|
||||
* List the resolvable post-image paths of a unified diff's file sections.
|
||||
* Unparseable sections are omitted.
|
||||
*/
|
||||
export function listUnifiedDiffPaths(diff: string): ReadonlyArray<string> {
|
||||
const paths: Array<string> = [];
|
||||
for (const section of splitUnifiedDiffSections(diff)) {
|
||||
const path = resolveDiffSectionPath(section);
|
||||
if (path !== null) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove file sections from a unified diff by path.
|
||||
*
|
||||
* Sections whose path cannot be determined are kept (fail toward showing).
|
||||
*/
|
||||
export function filterUnifiedDiffFiles(
|
||||
diff: string,
|
||||
shouldKeepPath: (path: string) => boolean,
|
||||
): string {
|
||||
const sections = splitUnifiedDiffSections(diff);
|
||||
if (sections.length === 0) {
|
||||
return diff;
|
||||
}
|
||||
|
||||
const kept = sections.filter((section) => {
|
||||
const path = resolveDiffSectionPath(section);
|
||||
return path === null || shouldKeepPath(path);
|
||||
});
|
||||
if (kept.length === sections.length) {
|
||||
return diff;
|
||||
}
|
||||
return kept.join("\n");
|
||||
}
|
||||
@@ -18,9 +18,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { deriveServerPaths } from "../config.ts";
|
||||
import { resolveServerConfig } from "./config.ts";
|
||||
|
||||
const deriveExplicitServerPaths = (baseDir: string, devUrl: URL | undefined) =>
|
||||
deriveServerPaths(baseDir, devUrl, { baseDirIsExplicit: true });
|
||||
|
||||
const encodeDesktopBootstrap = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
|
||||
const makeDesktopBootstrap = (
|
||||
@@ -63,10 +60,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-env-base");
|
||||
const derivedPaths = yield* deriveExplicitServerPaths(
|
||||
baseDir,
|
||||
new URL("http://127.0.0.1:5173"),
|
||||
);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.none(),
|
||||
@@ -125,7 +119,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
assert.equal(resolved.stateDir, join(baseDir, "userdata"));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -133,10 +126,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-flags-base");
|
||||
const derivedPaths = yield* deriveExplicitServerPaths(
|
||||
baseDir,
|
||||
new URL("http://127.0.0.1:4173"),
|
||||
);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("web"),
|
||||
@@ -195,7 +185,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
});
|
||||
assert.equal(resolved.dbPath, join(baseDir, "userdata", "state.sqlite"));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -210,10 +199,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
tailscaleServePort: 443,
|
||||
}),
|
||||
);
|
||||
const derivedPaths = yield* deriveExplicitServerPaths(
|
||||
baseDir,
|
||||
new URL("http://127.0.0.1:4173"),
|
||||
);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
@@ -410,10 +396,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
tailscaleServePort: 443,
|
||||
}),
|
||||
);
|
||||
const derivedPaths = yield* deriveExplicitServerPaths(
|
||||
baseDir,
|
||||
new URL("http://127.0.0.1:4173"),
|
||||
);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
@@ -478,7 +461,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" });
|
||||
const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
||||
yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
derivedPaths.settingsPath,
|
||||
@@ -546,7 +529,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-headless-base");
|
||||
const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
|
||||
@@ -31,9 +31,7 @@ export const hostFlag = Flag.string("host").pipe(
|
||||
Flag.optional,
|
||||
);
|
||||
export const baseDirFlag = Flag.string("base-dir").pipe(
|
||||
Flag.withDescription(
|
||||
"Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",
|
||||
),
|
||||
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
@@ -261,21 +259,19 @@ export const resolveServerConfig = (
|
||||
resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
|
||||
() => undefined,
|
||||
);
|
||||
const explicitBaseDir = resolveOptionPrecedence(
|
||||
normalizedFlags.baseDir,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
).pipe(Option.filter((value) => value.trim().length > 0));
|
||||
const baseDir = yield* resolveBaseDir(
|
||||
Option.getOrUndefined(
|
||||
resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.baseDir,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.fromUndefinedOr(bootstrap?.t3Home),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
|
||||
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
|
||||
yield* fs.makeDirectory(cwd, { recursive: true });
|
||||
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
|
||||
baseDirIsExplicit: Option.isSome(explicitBaseDir),
|
||||
});
|
||||
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl);
|
||||
yield* ServerConfig.ensureServerDirectories(derivedPaths);
|
||||
const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
|
||||
derivedPaths.settingsPath,
|
||||
|
||||
@@ -1,44 +1,18 @@
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
|
||||
import {
|
||||
acquireRelayClientForLink,
|
||||
formatHeadlessAuthorizationPrompt,
|
||||
formatRelayClientReady,
|
||||
headlessSessionConfig,
|
||||
isPublishAgentActivityEnabledValue,
|
||||
reportCloudDisconnectResults,
|
||||
} from "./connect.ts";
|
||||
import { recoverServiceOnboardingOffer } from "./service.ts";
|
||||
|
||||
it("explains how to complete headless authorization", () => {
|
||||
assert.equal(
|
||||
formatHeadlessAuthorizationPrompt("https://example.test/connect"),
|
||||
[
|
||||
"Headless authorization",
|
||||
"Open this URL on a device with a browser:",
|
||||
" https://example.test/connect",
|
||||
"",
|
||||
"After signing in, return here and enter the code shown in your browser.",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("formats relay readiness without printing its installation path", () => {
|
||||
assert.equal(formatRelayClientReady("2026.5.2"), "✓ Relay client ready · cloudflared 2026.5.2");
|
||||
});
|
||||
|
||||
const readHeadlessSessionConfig = (env: Record<string, string>) =>
|
||||
headlessSessionConfig.pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))));
|
||||
|
||||
const managedExecutable = {
|
||||
status: "available",
|
||||
@@ -47,22 +21,6 @@ const managedExecutable = {
|
||||
version: RelayClient.CLOUDFLARED_VERSION,
|
||||
} as const;
|
||||
|
||||
it.effect("detects headless operation from individual SSH config values", () =>
|
||||
Effect.gen(function* () {
|
||||
assert.isFalse(yield* readHeadlessSessionConfig({}));
|
||||
assert.isFalse(yield* readHeadlessSessionConfig({ CI: "true" }));
|
||||
assert.isTrue(yield* readHeadlessSessionConfig({ SSH_CONNECTION: "client server" }));
|
||||
assert.isTrue(yield* readHeadlessSessionConfig({ SSH_TTY: "/dev/pts/1" }));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("treats cancelling optional background setup as a successful skip", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* recoverServiceOnboardingOffer(Effect.fail(new Terminal.QuitError({})));
|
||||
assert.isFalse(result);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not install the relay client when the user declines the managed download", () =>
|
||||
Effect.gen(function* () {
|
||||
let installCalls = 0;
|
||||
|
||||
+57
-188
@@ -8,9 +8,7 @@ import { RelayOkResponse } from "@t3tools/contracts/relay";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -18,8 +16,6 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
@@ -31,7 +27,6 @@ import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
|
||||
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
import * as CliState from "../cloud/CliState.ts";
|
||||
import * as CliTokenManager from "../cloud/CliTokenManager.ts";
|
||||
import {
|
||||
@@ -43,95 +38,14 @@ import { relayUrlConfig } from "../cloud/publicConfig.ts";
|
||||
import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as ExternalLauncher from "../process/externalLauncher.ts";
|
||||
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
import {
|
||||
bootServiceLayer,
|
||||
offerServiceDuringOnboarding,
|
||||
recoverServiceOnboardingOffer,
|
||||
} from "./service.ts";
|
||||
|
||||
const jsonFlag = Flag.boolean("json").pipe(
|
||||
Flag.withDescription("Emit JSON instead of human-readable output."),
|
||||
Flag.withDefault(false),
|
||||
);
|
||||
|
||||
const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);
|
||||
|
||||
const headlessFlag = Flag.boolean("headless").pipe(
|
||||
Flag.withDescription("Authorize without a local browser using out-of-band OAuth."),
|
||||
Flag.withDefault(false),
|
||||
);
|
||||
|
||||
/**
|
||||
* Inside an SSH session there is no local browser to complete the loopback
|
||||
* OAuth callback, so out-of-band OAuth is the only flow that can work.
|
||||
*/
|
||||
export const headlessSessionConfig = Config.all({
|
||||
sshConnection: Config.string("SSH_CONNECTION").pipe(Config.option),
|
||||
sshTty: Config.string("SSH_TTY").pipe(Config.option),
|
||||
}).pipe(
|
||||
Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)),
|
||||
);
|
||||
|
||||
const promptForOutOfBandOAuthCode = Effect.fn("cloud.cli.prompt_for_out_of_band_oauth_code")(
|
||||
function* ({ authorizeUrl, validate }: CliTokenManager.OutOfBandOAuthPromptInput) {
|
||||
yield* Console.log(formatHeadlessAuthorizationPrompt(authorizeUrl));
|
||||
return yield* Prompt.run(Prompt.text({ message: "Authorization code", validate }));
|
||||
},
|
||||
);
|
||||
|
||||
export function formatHeadlessAuthorizationPrompt(authorizeUrl: string): string {
|
||||
return [
|
||||
"Headless authorization",
|
||||
"Open this URL on a device with a browser:",
|
||||
` ${authorizeUrl}`,
|
||||
"",
|
||||
"After signing in, return here and enter the code shown in your browser.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/** Returns the connected account identity, if the flow could determine one. */
|
||||
const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
|
||||
readonly headless: boolean;
|
||||
}) {
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig);
|
||||
if (!useOutOfBandOAuth) {
|
||||
const authorization = yield* tokens.get;
|
||||
if (authorization._tag === "Authorized") {
|
||||
return authorization.token.identity ?? null;
|
||||
}
|
||||
yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");
|
||||
}
|
||||
// A stored credential whose refresh fails (revoked, expired grant) must
|
||||
// fall through to a fresh out-of-band authorization, not dead-end the command.
|
||||
const existing = yield* tokens.getExisting.pipe(
|
||||
Effect.catchTag("CloudCliCredentialRefreshError", () =>
|
||||
Console.log(
|
||||
"The stored T3 Connect credential could not be refreshed; signing in again.",
|
||||
).pipe(Effect.as(Option.none())),
|
||||
),
|
||||
);
|
||||
if (Option.isSome(existing)) {
|
||||
return existing.value.identity ?? null;
|
||||
}
|
||||
const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin(
|
||||
promptForOutOfBandOAuthCode,
|
||||
).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
// Ctrl-C / EOF at the prompt is a QuitError; let it propagate so the CLI
|
||||
// cancels quietly instead of dumping an authorization error.
|
||||
Terminal.isQuitError(cause) || isCloudCliTokenManagerError(cause)
|
||||
? cause
|
||||
: new CliTokenManager.CloudCliAuthorizationError({ cause }),
|
||||
),
|
||||
);
|
||||
yield* tokens.store(token);
|
||||
return identity;
|
||||
});
|
||||
|
||||
function bytesToString(value: Uint8Array): string {
|
||||
return new TextDecoder().decode(value);
|
||||
}
|
||||
@@ -408,13 +322,11 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
});
|
||||
|
||||
if (options.clearAuthorization) {
|
||||
yield* Console.log(
|
||||
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
|
||||
);
|
||||
yield* Console.log("Signed out of T3 Connect locally.");
|
||||
}
|
||||
});
|
||||
|
||||
const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(
|
||||
const runCloudCommand = <A, E>(
|
||||
flags: { readonly baseDir: Option.Option<string> },
|
||||
run: Effect.Effect<
|
||||
A,
|
||||
@@ -423,8 +335,6 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
|
||||
| CliTokenManager.CloudCliTokenManager
|
||||
| RelayClient.RelayClient
|
||||
| EnvironmentAuth.EnvironmentAuth
|
||||
| BootService.BootService
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Prompt.Environment
|
||||
@@ -434,75 +344,37 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
|
||||
options?: {
|
||||
readonly quietLogs?: boolean;
|
||||
},
|
||||
) {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
|
||||
const runtimeLayer = Layer.mergeAll(
|
||||
ServerSecretStore.layer,
|
||||
CliTokenManager.layer.pipe(
|
||||
Layer.provide(ServerSecretStore.layer),
|
||||
Layer.provide(ExternalLauncher.layer),
|
||||
),
|
||||
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
|
||||
EnvironmentAuth.runtimeLayer,
|
||||
ServerEnvironment.layer,
|
||||
bootServiceLayer(config),
|
||||
headlessRelayClientTracingLayer,
|
||||
).pipe(
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
Layer.provideMerge(ServerConfig.layer(config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
);
|
||||
return yield* run.pipe(Effect.provide(runtimeLayer));
|
||||
});
|
||||
|
||||
const connectedAs = (identity: string | null): string => (identity ? ` as ${identity}` : "");
|
||||
|
||||
export function formatRelayClientReady(version: string): string {
|
||||
return `✓ Relay client ready · cloudflared ${version}`;
|
||||
}
|
||||
|
||||
const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: {
|
||||
readonly headless: boolean;
|
||||
readonly publishOnly?: boolean;
|
||||
}) {
|
||||
const publishOnly = options.publishOnly ?? false;
|
||||
if (!publishOnly) {
|
||||
const relayClient = yield* RelayClient.RelayClient;
|
||||
const installed = yield* acquireRelayClientForLink(
|
||||
relayClient,
|
||||
confirmRelayClientInstall,
|
||||
reportRelayClientInstallProgress,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
|
||||
const runtimeLayer = Layer.mergeAll(
|
||||
ServerSecretStore.layer,
|
||||
CliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)),
|
||||
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
|
||||
EnvironmentAuth.runtimeLayer,
|
||||
ServerEnvironment.layer,
|
||||
headlessRelayClientTracingLayer,
|
||||
).pipe(
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
Layer.provideMerge(ServerConfig.layer(config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
);
|
||||
if (Option.isNone(installed)) {
|
||||
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
|
||||
return null;
|
||||
}
|
||||
yield* Console.log(formatRelayClientReady(installed.value.version));
|
||||
}
|
||||
|
||||
const identity = yield* authorizeCli(options);
|
||||
yield* CliState.setCliDesiredCloudLink(true, publishOnly ? "publish_only" : "managed");
|
||||
if (publishOnly) {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true"));
|
||||
}
|
||||
return { identity } as const;
|
||||
});
|
||||
return yield* run.pipe(Effect.provide(runtimeLayer));
|
||||
});
|
||||
|
||||
const connectLoginCommand = Command.make("login", {
|
||||
...projectLocationFlags,
|
||||
headless: headlessFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
yield* Console.log("T3 Connect\n");
|
||||
const identity = yield* authorizeCli(flags);
|
||||
yield* Console.log(`✓ Signed in${connectedAs(identity)}`);
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
yield* tokens.get;
|
||||
yield* Console.log("Signed in to T3 Connect.");
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -510,7 +382,6 @@ const connectLoginCommand = Command.make("login", {
|
||||
|
||||
const connectLinkCommand = Command.make("link", {
|
||||
...projectLocationFlags,
|
||||
headless: headlessFlag,
|
||||
publishOnly: Flag.boolean("publish-only").pipe(
|
||||
Flag.withDescription(
|
||||
"Link to publish agent activity only — no managed tunnel. Reach this environment out of band (e.g. Tailscale).",
|
||||
@@ -523,15 +394,41 @@ const connectLinkCommand = Command.make("link", {
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
yield* Console.log("T3 Connect\n");
|
||||
const linked = yield* linkEnvironmentForConnect(flags);
|
||||
if (linked) {
|
||||
// A publish-only link needs no Cloudflare tunnel, so skip installing the
|
||||
// relay client entirely.
|
||||
if (!flags.publishOnly) {
|
||||
const relayClient = yield* RelayClient.RelayClient;
|
||||
const installed = yield* acquireRelayClientForLink(
|
||||
relayClient,
|
||||
confirmRelayClientInstall,
|
||||
reportRelayClientInstallProgress,
|
||||
);
|
||||
if (Option.isNone(installed)) {
|
||||
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
flags.publishOnly
|
||||
? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).`
|
||||
: `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`t3 serve\` to make this machine reachable.`,
|
||||
`Using relay client ${installed.value.version} from ${installed.value.executablePath}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
yield* tokens.get;
|
||||
yield* CliState.setCliDesiredCloudLink(
|
||||
true,
|
||||
flags.publishOnly ? "publish_only" : "managed",
|
||||
);
|
||||
if (flags.publishOnly) {
|
||||
// A publish-only link exists solely to publish; without the publish
|
||||
// flag the link would be inert and the success message a lie.
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true"));
|
||||
}
|
||||
yield* Console.log(
|
||||
flags.publishOnly
|
||||
? "This environment will publish agent activity to your mobile clients the next time T3 starts (no managed tunnel)."
|
||||
: "This T3 environment will be available through T3 Connect the next time T3 starts.",
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -669,36 +566,8 @@ const connectLogoutCommand = Command.make("logout", {
|
||||
),
|
||||
);
|
||||
|
||||
export const connectCommand = Command.make("connect", {
|
||||
...projectLocationFlags,
|
||||
headless: headlessFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Set up T3 Connect for this machine."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
yield* Console.log("T3 Connect\n");
|
||||
const linked = yield* linkEnvironmentForConnect(flags);
|
||||
if (!linked) {
|
||||
return;
|
||||
}
|
||||
// Show which account was linked so an unexpected identity (an
|
||||
// authorization code for a different account) is visible before the
|
||||
// machine is brought online.
|
||||
yield* Console.log(`✓ Connected${connectedAs(linked.identity)}`);
|
||||
|
||||
// Connect itself already succeeded; a boot-service failure must not
|
||||
// fail the command, just tell the user what happened and move on.
|
||||
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
|
||||
yield* Console.log(
|
||||
background
|
||||
? "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out."
|
||||
: "\nNext\n Start the server with `t3 serve` to make this machine reachable.",
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
export const connectCommand = Command.make("connect").pipe(
|
||||
Command.withDescription("Manage headless T3 Connect access."),
|
||||
Command.withSubcommands([
|
||||
connectLoginCommand,
|
||||
connectLinkCommand,
|
||||
|
||||
@@ -493,10 +493,6 @@ const projectRemoveCommand = Command.make("remove", {
|
||||
project: Argument.string("project").pipe(
|
||||
Argument.withDescription("Project id or workspace root to remove."),
|
||||
),
|
||||
force: Flag.boolean("force").pipe(
|
||||
Flag.withDescription("Delete the project and all of its threads."),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Remove a project."),
|
||||
Command.withHandler((flags) =>
|
||||
@@ -519,7 +515,6 @@ const projectRemoveCommand = Command.make("remove", {
|
||||
type: "project.delete",
|
||||
commandId: CommandId.make(yield* projectCommandUuid),
|
||||
projectId: project.id,
|
||||
force: flags.force,
|
||||
});
|
||||
return `Removed project ${project.id} (${project.title}).`;
|
||||
}),
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { formatServiceStatus } from "./service.ts";
|
||||
|
||||
const status = {
|
||||
supported: true,
|
||||
installed: true,
|
||||
current: true,
|
||||
unitPath: "/home/me/.config/systemd/user/t3code.service",
|
||||
logPath: "/home/me/.t3/userdata/logs/boot-service.log",
|
||||
} as const;
|
||||
|
||||
it("reports the installed service version and host paths", () => {
|
||||
assert.equal(
|
||||
formatServiceStatus(status, "0.0.29"),
|
||||
[
|
||||
"T3 Code service",
|
||||
" Status: installed · [email protected]",
|
||||
" Unit: /home/me/.config/systemd/user/t3code.service",
|
||||
" Logs: /home/me/.t3/userdata/logs/boot-service.log",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("gives a direct repair command for a stale service", () => {
|
||||
assert.include(
|
||||
formatServiceStatus({ ...status, current: false }, "0.0.29"),
|
||||
"Next: Run `npx t3@latest service update`.",
|
||||
);
|
||||
});
|
||||
|
||||
it("explains service availability without systemd", () => {
|
||||
assert.include(
|
||||
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
|
||||
"Supported on: Linux with systemd",
|
||||
);
|
||||
});
|
||||
@@ -1,199 +0,0 @@
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { Command, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
import type * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
|
||||
export const bootServiceLayer = (config: ServerConfig.ServerConfig["Service"]) =>
|
||||
BootService.layer({
|
||||
baseDir: config.baseDir,
|
||||
logsDir: config.logsDir,
|
||||
cliVersion: packageJson.version,
|
||||
}).pipe(Layer.provide(ProcessRunner.layer));
|
||||
|
||||
export type ServiceReconcileResult =
|
||||
| {
|
||||
readonly changed: false;
|
||||
readonly status: BootService.BootServiceStatus;
|
||||
}
|
||||
| {
|
||||
readonly changed: true;
|
||||
readonly previouslyInstalled: boolean;
|
||||
readonly plan: BootService.BootServicePlan;
|
||||
};
|
||||
|
||||
/** Install, update, or repair the service using the CLI version running this command. */
|
||||
export const reconcileService = Effect.fn("cli.service.reconcile")(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const status = yield* service.status;
|
||||
if (status.installed && status.current) {
|
||||
return { changed: false, status } satisfies ServiceReconcileResult;
|
||||
}
|
||||
const plan = yield* service.install;
|
||||
return {
|
||||
changed: true,
|
||||
previouslyInstalled: status.installed,
|
||||
plan,
|
||||
} satisfies ServiceReconcileResult;
|
||||
});
|
||||
|
||||
export function formatServiceStatus(
|
||||
status: BootService.BootServiceStatus,
|
||||
cliVersion: string,
|
||||
): string {
|
||||
if (!status.supported) {
|
||||
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd";
|
||||
}
|
||||
if (!status.installed) {
|
||||
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
|
||||
}
|
||||
return [
|
||||
"T3 Code service",
|
||||
` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,
|
||||
` Unit: ${status.unitPath}`,
|
||||
` Logs: ${status.logPath}`,
|
||||
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(
|
||||
flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
|
||||
run: Effect.Effect<A, E, BootService.BootService>,
|
||||
) {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
return yield* run.pipe(Effect.provide(bootServiceLayer(config)));
|
||||
});
|
||||
|
||||
const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe(
|
||||
Command.withDescription("Install T3 Code as a background service for this user."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const result = yield* reconcileService();
|
||||
if (!result.changed) {
|
||||
yield* Console.log(
|
||||
`T3 Code service is already installed with t3@${packageJson.version}.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
`${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
|
||||
Command.withDescription(
|
||||
"Update or repair the background service using this CLI version. Use `npx t3@latest service update` for the latest release.",
|
||||
),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const result = yield* reconcileService();
|
||||
if (!result.changed) {
|
||||
yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
`${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
|
||||
Command.withDescription("Stop and remove the T3 Code background service."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const removed = yield* service.uninstall;
|
||||
yield* Console.log(
|
||||
removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
|
||||
Command.withDescription("Show whether the T3 Code background service is installed."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
yield* Console.log(formatServiceStatus(yield* service.status, packageJson.version));
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const { supported, installed, current } = yield* service.status;
|
||||
if (!supported) {
|
||||
return false;
|
||||
}
|
||||
if (installed && current) {
|
||||
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
|
||||
return true;
|
||||
}
|
||||
const wanted = yield* Prompt.run(
|
||||
Prompt.confirm({
|
||||
message: installed
|
||||
? "The installed T3 Code service needs an update or repair. Update it now?"
|
||||
: "Run T3 Code in the background whenever this machine boots? " +
|
||||
"It stays reachable through T3 Connect even after you log out.",
|
||||
initial: true,
|
||||
}),
|
||||
);
|
||||
if (!wanted) {
|
||||
return false;
|
||||
}
|
||||
const result = yield* reconcileService();
|
||||
if (result.changed) {
|
||||
yield* Console.log(
|
||||
`Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
export const recoverServiceOnboardingOffer = <R>(
|
||||
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
|
||||
) =>
|
||||
offer.pipe(
|
||||
Effect.catchTags({
|
||||
QuitError: () => Effect.succeed(false),
|
||||
BootServiceUnsupportedError: (error) =>
|
||||
Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceCommandError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceInstallError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
}),
|
||||
);
|
||||
|
||||
export const serviceCommand = Command.make("service").pipe(
|
||||
Command.withDescription("Manage the T3 Code background service."),
|
||||
Command.withSubcommands([
|
||||
serviceInstallCommand,
|
||||
serviceUninstallCommand,
|
||||
serviceUpdateCommand,
|
||||
serviceStatusCommand,
|
||||
]),
|
||||
);
|
||||
Loaded 100 of 418 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user