Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c696e04e81 | ||
|
|
f684971262 | ||
|
|
18f7243fd3 | ||
|
|
9fb0ba2990 | ||
|
|
6d341a14be | ||
|
|
422cf087ee | ||
|
|
e78baddda1 | ||
|
|
e33c0d8e82 | ||
|
|
3261623f90 | ||
|
|
758f999f9b | ||
|
|
e8be967295 | ||
|
|
5b519775f5 | ||
|
|
965a76b531 | ||
|
|
35ddbc4ab1 | ||
|
|
1fa4219b48 | ||
|
|
5faee6114b | ||
|
|
0b837b8ef1 | ||
|
|
19d1329ac5 | ||
|
|
5b8cfdbf05 | ||
|
|
202e5609ff | ||
|
|
bb38c3320d | ||
|
|
6b9a5987f6 | ||
|
|
fc3f78f5d9 | ||
|
|
2f41c073a2 | ||
|
|
51672b6ecb | ||
|
|
67a7b1a1d3 | ||
|
|
ce467da9cf | ||
|
|
6ef7aa8399 | ||
|
|
193e3c62e6 | ||
|
|
91dfe60a99 | ||
|
|
edb12401e5 | ||
|
|
79fe11bc1c | ||
|
|
b3e51317e4 | ||
|
|
ddd5a46f39 | ||
|
|
88c69ffff6 | ||
|
|
979854895c | ||
|
|
9cbe50d10d | ||
|
|
9d9208cec5 | ||
|
|
57100fba85 | ||
|
|
3afb4a9ef9 | ||
|
|
315b27385d | ||
|
|
719c905eac | ||
|
|
0542abc75e | ||
|
|
7609495bf7 | ||
|
|
b41e89eba9 | ||
|
|
4d83436415 | ||
|
|
e51538b812 | ||
|
|
1c9a6de26e | ||
|
|
fbd77420f2 | ||
|
|
16491a84b9 | ||
|
|
b44ed835c6 | ||
|
|
9c9916aefe | ||
|
|
936394b6f2 | ||
|
|
c38225ef1c | ||
|
|
39cd15b954 | ||
|
|
160d97f403 | ||
|
|
d330759f58 | ||
|
|
5961d36769 | ||
|
|
0b1ce58824 | ||
|
|
10da67b9da | ||
|
|
6e5df67f15 | ||
|
|
29b1abc45e | ||
|
|
14b6bfdf15 | ||
|
|
b6a2563db7 | ||
|
|
c5ff51ec1f | ||
|
|
2d31cb022d | ||
|
|
bc9428a06a | ||
|
|
593289c3c7 | ||
|
|
ab4a88386d | ||
|
|
78a0ea55c1 | ||
|
|
9a0a07167f | ||
|
|
9fe4832a3f | ||
|
|
376c149eac | ||
|
|
7e2bb47504 | ||
|
|
18fa89c4ad | ||
|
|
f74eb62661 | ||
|
|
e5fba263e6 | ||
|
|
18b468871e | ||
|
|
020179c19a | ||
|
|
571a8b44bd | ||
|
|
b6e1b39335 | ||
|
|
c7b21ff172 | ||
|
|
4e09cddb40 | ||
|
|
783692afc1 | ||
|
|
aa5ec80364 | ||
|
|
282ecb3178 | ||
|
|
32c6012dab | ||
|
|
6f34ad3e87 | ||
|
|
62cf461759 | ||
|
|
23c18fda7a | ||
|
|
c0bb237345 | ||
|
|
5d34f9ff23 | ||
|
|
c8a04bd59b | ||
|
|
db4b2d8a0f | ||
|
|
2c199aacac | ||
|
|
8ca4eec9ca | ||
|
|
0936fd271f | ||
|
|
fa69f05b69 | ||
|
|
c710167bde | ||
|
|
a135f2c2d3 | ||
|
|
946b867666 | ||
|
|
0ca3240691 | ||
|
|
f4da4f3b40 | ||
|
|
b6d9ce325c | ||
|
|
8e3467fe60 | ||
|
|
2fae0d0ac3 | ||
|
|
08993a5ec8 | ||
|
|
501ce27b81 | ||
|
|
40c0ab0883 | ||
|
|
33f1cb4224 | ||
|
|
d266c068d0 | ||
|
|
5fcfe242c1 | ||
|
|
df65a6c3ad | ||
|
|
3235658c08 | ||
|
|
749baec353 | ||
|
|
d7baa37e5c | ||
|
|
68ea280388 | ||
|
|
dfbda84362 | ||
|
|
78485e6d50 | ||
|
|
63b6b44627 | ||
|
|
3795dbb017 | ||
|
|
2640e6dcfc | ||
|
|
e34250df46 | ||
|
|
7e1a0d551c | ||
|
|
b511227b7a | ||
|
|
69c8be2ee5 | ||
|
|
271454cbd2 | ||
|
|
e8ff6bc7f8 | ||
|
|
398140a9bd | ||
|
|
2b180a2b2d | ||
|
|
7a820abfdd | ||
|
|
53e3c98a55 | ||
|
|
4f11740510 | ||
|
|
1735e27d9e | ||
|
|
ebe8afb1df | ||
|
|
bf76535fe4 | ||
|
|
5c66110e26 | ||
|
|
da3c2030f7 | ||
|
|
0506508e9b | ||
|
|
b859a575d1 | ||
|
|
e63403fe92 | ||
|
|
c0e161af06 | ||
|
|
d0b9f8d40d | ||
|
|
d8b12ae801 | ||
|
|
31caa5652b | ||
|
|
e350c0a07b | ||
|
|
38e0bb07bb | ||
|
|
765e1b5fc0 | ||
|
|
03e20c875c | ||
|
|
2318e00270 | ||
|
|
4cfec8c128 | ||
|
|
1bd2fa25e2 | ||
|
|
5ca32661b7 | ||
|
|
8b33799523 | ||
|
|
24f9c2a08e | ||
|
|
31ca9e5531 | ||
|
|
73bf127d71 | ||
|
|
43e2aeab38 | ||
|
|
b655a9f183 | ||
|
|
4e3f2f04d5 | ||
|
|
1047dac0c5 | ||
|
|
143b9c9280 | ||
|
|
cf58cadd02 | ||
|
|
6a17629670 | ||
|
|
7b8d12618b | ||
|
|
bcd640bf4d | ||
|
|
b49a2e677c | ||
|
|
ed81c156da | ||
|
|
7dc75127c2 | ||
|
|
e057e2e985 | ||
|
|
a7f6d97b94 | ||
|
|
f9a4f59930 | ||
|
|
7f1cb61031 | ||
|
|
c49d424e3a | ||
|
|
4804a9824f | ||
|
|
0748134cec | ||
|
|
6e9987cf17 | ||
|
|
8b5469863a | ||
|
|
58302b2010 | ||
|
|
1f2797325b | ||
|
|
c14a5ca492 | ||
|
|
eb733c10f2 | ||
|
|
8a02c71861 | ||
|
|
fdca15471d | ||
|
|
5d68fca8f2 | ||
|
|
2a33a18716 | ||
|
|
bde0a4c0dd | ||
|
|
54f167e2e0 | ||
|
|
d114e2772d | ||
|
|
0418301de7 | ||
|
|
5e8b2c800e | ||
|
|
b98233702c |
No files matched your search
@@ -0,0 +1,21 @@
|
||||
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.
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,9 @@
|
||||
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"
|
||||
@@ -0,0 +1,21 @@
|
||||
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.
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,4 @@
|
||||
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."
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
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`.
|
||||
@@ -0,0 +1,4 @@
|
||||
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."
|
||||
@@ -0,0 +1,58 @@
|
||||
# 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`.
|
||||
@@ -0,0 +1,188 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,4 @@
|
||||
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."
|
||||
@@ -0,0 +1 @@
|
||||
../.agents/skills
|
||||
@@ -0,0 +1,9 @@
|
||||
[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,6 +18,10 @@
|
||||
# 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
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
name: Mobile Showcase Screenshots
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
platform:
|
||||
description: Device platforms to capture
|
||||
required: true
|
||||
default: all
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- ios
|
||||
- android
|
||||
appearance:
|
||||
description: System appearances to capture
|
||||
required: true
|
||||
default: both
|
||||
type: choice
|
||||
options:
|
||||
- both
|
||||
- dark
|
||||
- light
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
|
||||
jobs:
|
||||
ios:
|
||||
name: iPhone 6.9, iPhone 6.5, and iPad 13
|
||||
if: inputs.platform == 'all' || inputs.platform == 'ios'
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Capture iOS showcase
|
||||
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}"
|
||||
|
||||
- name: Validate App Store Connect assets
|
||||
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --validate-only
|
||||
|
||||
- name: Upload iOS screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: app-store-connect-screenshots
|
||||
path: artifacts/app-store/screenshots/apple/
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
android:
|
||||
name: Android phone, 7-inch tablet, and 10-inch tablet
|
||||
if: inputs.platform == 'all' || inputs.platform == 'android'
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
T3_SHOWCASE_ANDROID_ABI: x86_64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle cache
|
||||
uses: gradle/actions/setup-gradle@v5
|
||||
|
||||
- name: Enable KVM
|
||||
run: |
|
||||
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS="static_node=kvm"' \
|
||||
| sudo tee /etc/udev/rules.d/99-kvm4all.rules
|
||||
sudo udevadm control --reload-rules
|
||||
sudo udevadm trigger --name-match=kvm
|
||||
|
||||
- name: Capture Android showcase
|
||||
uses: reactivecircus/android-emulator-runner@v2
|
||||
with:
|
||||
api-level: 36
|
||||
target: google_apis
|
||||
arch: x86_64
|
||||
profile: pixel_7_pro
|
||||
avd-name: Pixel_10_Pro
|
||||
cores: 8
|
||||
ram-size: 4096M
|
||||
disable-animations: false
|
||||
script: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}"
|
||||
|
||||
- name: Validate Google Play assets
|
||||
run: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}" --validate-only
|
||||
|
||||
- name: Upload Android screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: google-play-screenshots
|
||||
path: artifacts/app-store/screenshots/google-play/
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -788,6 +788,7 @@ 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 }}
|
||||
@@ -871,6 +872,7 @@ 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:-}" \
|
||||
|
||||
@@ -27,8 +27,13 @@ squashfs-root/
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
.showcase/
|
||||
apps/mobile/.showcase/
|
||||
artifacts/app-store/screenshots/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
.env*
|
||||
!.env.example
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"xcodebuildmcp": {
|
||||
"command": "npx",
|
||||
"args": ["--yes", "[email protected]", "mcp"],
|
||||
"env": {
|
||||
"XCODEBUILDMCP_ENABLED_WORKFLOWS": "simulator,ui-automation,debugging,logging"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,510 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>T3 Code — Sidebar v2 Beta Plan</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #000;
|
||||
--fg: #fff;
|
||||
--muted: #9ca3af;
|
||||
--dim: #6b7280;
|
||||
--surface: #0d0d0f;
|
||||
--surface2: #16161a;
|
||||
--border: #26262c;
|
||||
--amber: #f59e0b;
|
||||
--sky: #38bdf8;
|
||||
--indigo: #818cf8;
|
||||
--violet: #a78bfa;
|
||||
--emerald: #34d399;
|
||||
--red: #f87171;
|
||||
--teal: #2dd4bf;
|
||||
--mono: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font: 15px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.wrap { max-width: 960px; margin: 0 auto; padding: 56px 24px 120px; }
|
||||
h1 { font-size: 32px; line-height: 1.2; letter-spacing: -0.02em; }
|
||||
h2 { font-size: 21px; letter-spacing: -0.01em; margin: 72px 0 8px; }
|
||||
h2 .num { color: var(--dim); font-weight: 500; margin-right: 10px; }
|
||||
h3 { font-size: 15px; margin: 28px 0 8px; }
|
||||
p { color: var(--muted); margin: 10px 0; max-width: 72ch; }
|
||||
p strong, li strong { color: var(--fg); font-weight: 600; }
|
||||
a { color: var(--sky); text-decoration: none; }
|
||||
a:hover { text-decoration: underline; }
|
||||
code {
|
||||
font-family: var(--mono); font-size: 12.5px;
|
||||
background: var(--surface2); border: 1px solid var(--border);
|
||||
padding: 1px 5px; border-radius: 4px; color: #d4d4d8;
|
||||
}
|
||||
pre {
|
||||
font-family: var(--mono); font-size: 12.5px; line-height: 1.7;
|
||||
background: var(--surface); border: 1px solid var(--border);
|
||||
border-radius: 10px; padding: 16px 18px; overflow-x: auto;
|
||||
color: #d4d4d8; margin: 14px 0;
|
||||
}
|
||||
pre .c { color: var(--dim); }
|
||||
pre .k { color: var(--violet); }
|
||||
pre .s { color: var(--emerald); }
|
||||
ul, ol { margin: 10px 0 10px 22px; color: var(--muted); max-width: 72ch; }
|
||||
li { margin: 6px 0; }
|
||||
li::marker { color: var(--dim); }
|
||||
.lede { font-size: 17px; color: var(--muted); margin-top: 14px; }
|
||||
.meta { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 20px; }
|
||||
.chip {
|
||||
font-size: 12px; padding: 3px 10px; border-radius: 999px;
|
||||
border: 1px solid var(--border); color: var(--muted); background: var(--surface);
|
||||
}
|
||||
.chip.hot { border-color: rgba(52,211,153,.4); color: var(--emerald); }
|
||||
.cols { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 18px 0; }
|
||||
@media (max-width: 760px) { .cols { grid-template-columns: 1fr; } }
|
||||
.panel {
|
||||
background: var(--surface); border: 1px solid var(--border);
|
||||
border-radius: 12px; padding: 18px 20px;
|
||||
}
|
||||
.panel h4 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--dim); margin-bottom: 10px; }
|
||||
.panel ul { margin-left: 18px; font-size: 13.5px; }
|
||||
.kv { font-size: 13.5px; color: var(--muted); }
|
||||
.kv b { color: var(--fg); font-weight: 600; }
|
||||
.note {
|
||||
border-left: 3px solid var(--violet); background: rgba(167,139,250,.06);
|
||||
padding: 12px 16px; border-radius: 0 10px 10px 0; margin: 18px 0; color: var(--muted);
|
||||
font-size: 14px; max-width: 78ch;
|
||||
}
|
||||
.warn { border-left-color: var(--amber); background: rgba(245,158,11,.06); }
|
||||
|
||||
/* ————— sidebar mock ————— */
|
||||
.mockwrap { display: grid; grid-template-columns: 320px 1fr; gap: 28px; margin: 24px 0; align-items: start; }
|
||||
@media (max-width: 820px) { .mockwrap { grid-template-columns: 1fr; } }
|
||||
.sidebar {
|
||||
background: #0a0a0c; border: 1px solid var(--border); border-radius: 14px;
|
||||
overflow: hidden; box-shadow: 0 20px 60px rgba(0,0,0,.6);
|
||||
font-size: 12px;
|
||||
}
|
||||
.sb-top {
|
||||
display: flex; gap: 8px; padding: 10px; border-bottom: 1px solid var(--border);
|
||||
align-items: center;
|
||||
}
|
||||
.sb-search {
|
||||
flex: 1; display: flex; align-items: center; gap: 6px;
|
||||
background: var(--surface2); border: 1px solid var(--border); border-radius: 7px;
|
||||
padding: 5px 9px; color: var(--dim); font-size: 11.5px;
|
||||
}
|
||||
.sb-search kbd {
|
||||
margin-left: auto; font-family: var(--mono); font-size: 10px;
|
||||
border: 1px solid var(--border); border-radius: 4px; padding: 0 4px; color: var(--dim);
|
||||
}
|
||||
.sb-new {
|
||||
width: 26px; height: 26px; border-radius: 7px; border: 1px solid var(--border);
|
||||
background: var(--surface2); color: var(--muted); display: grid; place-items: center;
|
||||
font-size: 15px; cursor: default;
|
||||
}
|
||||
.rows { padding: 6px; display: flex; flex-direction: column; gap: 3px; }
|
||||
|
||||
.row {
|
||||
position: relative; border-radius: 8px; cursor: default;
|
||||
transition: background .12s;
|
||||
overflow: hidden;
|
||||
}
|
||||
.row:hover { background: rgba(255,255,255,.045); }
|
||||
.row .rail {
|
||||
position: absolute; left: 0; top: 6px; bottom: 6px; width: 3px; border-radius: 2px;
|
||||
}
|
||||
.rail.amber { background: var(--amber); }
|
||||
.rail.sky { background: var(--sky); animation: pulse 1.6s ease-in-out infinite; }
|
||||
.rail.red { background: var(--red); }
|
||||
@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: .35; } }
|
||||
|
||||
.card { padding: 8px 10px 8px 14px; }
|
||||
.card .l1 { display: flex; align-items: center; gap: 8px; }
|
||||
.card .title { color: #d4d4d8; font-weight: 500; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.row.unread .card .title { color: var(--fg); font-weight: 650; }
|
||||
.fav {
|
||||
width: 15px; height: 15px; border-radius: 4px; flex: none;
|
||||
display: grid; place-items: center; font-size: 8px; font-weight: 700; letter-spacing: .02em;
|
||||
}
|
||||
.fav.t3 { background: rgba(167,139,250,.14); color: var(--violet); border: 1px solid rgba(167,139,250,.3); }
|
||||
.fav.fh { background: rgba(56,189,248,.12); color: #7dd3fc; border: 1px solid rgba(56,189,248,.3); }
|
||||
.slim .fav { width: 13px; height: 13px; font-size: 7px; }
|
||||
.card .diff { font-family: var(--mono); font-size: 10px; white-space: nowrap; }
|
||||
.diff .add { color: var(--emerald); } .diff .del { color: var(--red); }
|
||||
.card .time { margin-left: auto; color: var(--dim); font-size: 10px; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.card .time.wait { color: var(--amber); }
|
||||
.card .meta {
|
||||
margin-top: 3px; display: flex; align-items: center; gap: 8px;
|
||||
color: var(--dim); font-size: 10px; padding-left: 23px;
|
||||
white-space: nowrap; overflow: hidden;
|
||||
}
|
||||
.meta .st { font-weight: 650; font-size: 9.5px; letter-spacing: .02em; }
|
||||
.st.amber { color: var(--amber); } .st.sky { color: var(--sky); } .st.red { color: var(--red); }
|
||||
.branch { font-family: var(--mono); font-size: 9.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.model { font-family: var(--mono); font-size: 9.5px; display: inline-flex; align-items: center; gap: 3px; }
|
||||
.hx.cl { color: rgba(217,119,87,.75); font-size: 9px; }
|
||||
.hx.cx { color: rgba(255,255,255,.45); font-size: 9px; }
|
||||
.mach { font-size: 9.5px; color: var(--dim); display: inline-flex; align-items: center; gap: 3px; }
|
||||
|
||||
.slim { display: flex; align-items: center; gap: 7px; padding: 5px 10px; height: 27px; }
|
||||
.slim .dot { width: 5px; height: 5px; border-radius: 50%; background: var(--dim); flex: none; }
|
||||
.slim .title { color: var(--muted); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.slim .pr { font-family: var(--mono); font-size: 9.5px; color: var(--violet); white-space: nowrap; }
|
||||
.slim .pr.open { color: var(--emerald); }
|
||||
.slim .time { margin-left: auto; color: var(--dim); font-size: 10px; flex: none; }
|
||||
|
||||
.settle-btn {
|
||||
position: absolute; right: 8px; top: 8px; opacity: 0;
|
||||
border: 1px solid var(--border); background: var(--surface2); color: var(--muted);
|
||||
border-radius: 6px; font-size: 10px; padding: 2px 8px; cursor: pointer;
|
||||
transition: opacity .12s; font-family: inherit;
|
||||
}
|
||||
.row:hover .settle-btn { opacity: 1; }
|
||||
.settle-btn:hover { color: var(--fg); border-color: var(--dim); }
|
||||
.row.settling { transition: opacity .35s, max-height .35s ease; max-height: 0 !important; opacity: 0; }
|
||||
|
||||
.mock-legend h4 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--dim); margin: 18px 0 8px; }
|
||||
.mock-legend .kv { display: block; margin: 7px 0; }
|
||||
.lg-dot { display: inline-block; width: 8px; height: 8px; border-radius: 2px; margin-right: 8px; vertical-align: baseline; }
|
||||
.toast {
|
||||
margin: 10px 6px 8px; border: 1px solid rgba(45,212,191,.35); background: rgba(45,212,191,.07);
|
||||
border-radius: 8px; padding: 8px 10px; font-size: 11px; color: var(--muted);
|
||||
display: none; align-items: center; gap: 8px;
|
||||
}
|
||||
.toast.show { display: flex; }
|
||||
.toast b { color: var(--teal); font-weight: 600; }
|
||||
.toast button {
|
||||
margin-left: auto; border: 1px solid rgba(45,212,191,.4); background: transparent;
|
||||
color: var(--teal); border-radius: 5px; font-size: 10px; padding: 2px 8px; cursor: pointer;
|
||||
}
|
||||
.reset { font-size: 12px; color: var(--dim); cursor: pointer; background: none; border: none; font-family: inherit; }
|
||||
.reset:hover { color: var(--muted); }
|
||||
|
||||
table { border-collapse: collapse; width: 100%; margin: 14px 0; font-size: 13.5px; }
|
||||
th { text-align: left; color: var(--dim); font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: .05em; padding: 8px 12px; border-bottom: 1px solid var(--border); }
|
||||
td { padding: 9px 12px; border-bottom: 1px solid var(--border); color: var(--muted); vertical-align: top; }
|
||||
td:first-child { color: var(--fg); white-space: nowrap; }
|
||||
.phase { border: 1px solid var(--border); border-radius: 12px; margin: 16px 0; overflow: hidden; }
|
||||
.phase-h {
|
||||
display: flex; align-items: baseline; gap: 12px; padding: 14px 20px;
|
||||
background: var(--surface); border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.phase-h .n {
|
||||
font-family: var(--mono); font-size: 12px; color: var(--bg); background: var(--fg);
|
||||
border-radius: 6px; padding: 1px 8px; font-weight: 700;
|
||||
}
|
||||
.phase-h .t { font-weight: 600; font-size: 15px; }
|
||||
.phase-h .d { margin-left: auto; font-size: 12px; color: var(--dim); }
|
||||
.phase-b { padding: 6px 20px 16px; }
|
||||
.phase-b ul { font-size: 13.5px; }
|
||||
svg text { font-family: -apple-system, BlinkMacSystemFont, sans-serif; }
|
||||
svg .mono { font-family: var(--mono); }
|
||||
.foot { margin-top: 80px; padding-top: 20px; border-top: 1px solid var(--border); color: var(--dim); font-size: 12.5px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
|
||||
<h1>Sidebar v2 — beta plan</h1>
|
||||
<p class="lede">One flat, recency-sorted thread list where row size is earned by state — and “settled” becomes a real lifecycle stage users control. Familiar mechanics only: nothing here requires learning a new gesture.</p>
|
||||
<div class="meta">
|
||||
<span class="chip hot">beta · toggle in settings</span>
|
||||
<span class="chip">plan: <code style="border:none;background:none;padding:0">.plans/21-sidebar-v2-beta.md</code></span>
|
||||
<span class="chip"><a href="https://hsyscdqldmk5.postplan.dev/" target="_blank" rel="noopener noreferrer">original 5 concepts ↗</a></span>
|
||||
</div>
|
||||
|
||||
<h2><span class="num">01</span>What we're building</h2>
|
||||
<p>The hybrid the concepts page predicted, filtered through “meet users where they are”: <strong>concept 4's adaptive density</strong> as the skeleton, <strong>concept 1's card layout</strong> (trimmed to two structured lines — no generated text) for active rows, and <strong>concept 3 reduced to a sort rule</strong> (approval-blocked threads pin above the recency flow — no tiers, no inline approve).</p>
|
||||
<div class="cols">
|
||||
<div class="panel">
|
||||
<h4>Changes</h4>
|
||||
<ul>
|
||||
<li><strong>Flat recency list</strong> — project group headers gone; project becomes a chip. This is how Claude Code, Codex, and Cursor already present sessions.</li>
|
||||
<li><strong>Settled lifecycle state</strong> — explicit, user- or rule-triggered. Settled rows collapse to slim one-liners (≈ today's density).</li>
|
||||
<li><strong>Four states, three colors</strong> — Needs approval (amber, pinned with wait time), Working (sky, pulsing), <strong>Ready</strong> (no color, no label — the normal resting state; bold title until visited), Failed (red).</li>
|
||||
<li><strong>Structured metadata only</strong> — the card's second line is status word · branch · harness + model · machine. No summaries or free text to generate; every field is data the shell already carries.</li>
|
||||
<li><strong>Project identity = favicon</strong> — the existing <code>ProjectFavicon</code> per-row, not a text chip. Harness (Claude Code / Codex / other) is a tinted glyph on the model; machine shows only when the thread lives on another computer.</li>
|
||||
<li><strong>Failed sessions visible</strong> — <code>session.lastError</code> finally gets a red state; today a dead session shows nothing.</li>
|
||||
<li><strong>Settle → worktree cleanup</strong> — settling an orphaned-worktree thread offers a one-click remove.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h4>Deliberately not</h4>
|
||||
<ul>
|
||||
<li>Inline approve/reject in the sidebar — needs a safety story first.</li>
|
||||
<li>Message snippets (concept 2) — streaming churn unsolved.</li>
|
||||
<li>Ops-grid density mode (concept 5).</li>
|
||||
<li>Auto-archive of long-settled threads (future: settled ≥ 30d).</li>
|
||||
<li>Removing v1 — it stays the default; v2 is opt-in.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2><span class="num">02</span>The mock</h2>
|
||||
<p><strong>Hover any card and hit “Settle”</strong> — it collapses into the slim tail. That height change is the whole design: it happens only at lifecycle transitions, never from streaming updates, which is what keeps the list calm.</p>
|
||||
|
||||
<div class="mockwrap">
|
||||
<div class="sidebar" id="mock">
|
||||
<div class="sb-top">
|
||||
<div class="sb-search">⌕ Search <kbd>⌘K</kbd></div>
|
||||
<div class="sb-new">+</div>
|
||||
</div>
|
||||
<div class="toast" id="toast"><span>Settled · worktree <b>fix-pr-titles</b> is orphaned</span><button id="toast-remove">Remove</button></div>
|
||||
<div class="rows" id="rows">
|
||||
|
||||
<div class="row unread" data-card style="max-height:64px">
|
||||
<div class="rail amber"></div>
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav t3">T3</span><span class="title">Normalize open PR titles</span><span class="time wait">waiting 2m</span></div>
|
||||
<div class="meta"><span class="st amber">APPROVAL</span><span class="branch">fix-pr-titles</span><span class="model"><span class="hx cl">✳</span>opus-4.8</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle data-toast>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row" data-card style="max-height:64px">
|
||||
<div class="rail sky"></div>
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav t3">T3</span><span class="title">Sidebar v2 UX Redesign</span><span class="time">14m 22s</span></div>
|
||||
<div class="meta"><span class="st sky">WORKING</span><span class="branch">sidebar-v2-beta</span><span class="model"><span class="hx cl">✳</span>fable-5</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row unread" data-card style="max-height:64px">
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav fh">FH</span><span class="title">Fix image upload stalls</span><span class="time">18m</span></div>
|
||||
<div class="meta"><span class="branch">main</span><span class="model"><span class="hx cl">✳</span>sonnet-5</span><span class="mach">⏻ mac-studio</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row unread" data-card style="max-height:64px">
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav t3">T3</span><span class="title">Review default experience plan</span><span class="time">9m</span></div>
|
||||
<div class="meta"><span class="branch">plan-ux-review</span><span class="model"><span class="hx cl">✳</span>opus-4.8</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row unread" data-card style="max-height:64px">
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav t3">T3</span><span class="title">Disable pairing codes by default</span><span class="diff"><span class="add">+214</span> <span class="del">−38</span></span><span class="time">12m</span></div>
|
||||
<div class="meta"><span class="branch">disable-pairing-codes</span><span class="model"><span class="hx cx">◈</span>gpt-5.6-sol</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row unread" data-card style="max-height:64px">
|
||||
<div class="rail red"></div>
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav t3">T3</span><span class="title">iOS Simulator Remote Setup</span><span class="time">34m</span></div>
|
||||
<div class="meta"><span class="st red">FAILED</span><span class="branch">main</span><span class="model"><span class="hx cx">◈</span>gpt-5.6-sol</span><span class="mach">⏻ mbp-16</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row"><div class="slim"><span class="fav t3">T3</span><span class="title">Default new worktrees from origin main</span><span class="time">41m</span></div></div>
|
||||
<div class="row"><div class="slim"><span class="fav t3">T3</span><span class="title">Fix performance bottlenecks</span><span class="pr">#3825 merged</span><span class="time">1d</span></div></div>
|
||||
<div class="row"><div class="slim"><span class="fav t3">T3</span><span class="title">Stress test long thread rendering</span><span class="pr open">#3822 open</span><span class="time">2d</span></div></div>
|
||||
<div class="row"><div class="slim"><span class="fav fh">FH</span><span class="title">CLI File Hosting Options</span><span class="time">2d</span></div></div>
|
||||
</div>
|
||||
<div style="padding:4px 10px 10px; text-align:right"><button class="reset" id="reset-mock">↺ reset mock</button></div>
|
||||
</div>
|
||||
|
||||
<div class="mock-legend">
|
||||
<h4>Card anatomy (active threads, ~52px)</h4>
|
||||
<span class="kv"><b>Line 1</b> — project favicon · title (bold = unread) · diff stats when present · time</span>
|
||||
<span class="kv"><b>Line 2</b> — structured metadata only: status word (only when colored) · branch · harness glyph + model · machine (only when not this one). No generated text — everything on the card is data we already have.</span>
|
||||
<h4>Four states, three colors</h4>
|
||||
<span class="kv"><span class="lg-dot" style="background:var(--amber)"></span><b>APPROVAL</b> — blocked mid-run, pinned to top with “waiting Xm”</span>
|
||||
<span class="kv"><span class="lg-dot" style="background:var(--sky)"></span><b>WORKING</b> — pulsing rail, live elapsed timer</span>
|
||||
<span class="kv"><span class="lg-dot" style="background:var(--fg)"></span><b>Ready</b> — the default; needs no label. Stopped, waiting on you. Bold title until visited.</span>
|
||||
<span class="kv"><span class="lg-dot" style="background:var(--red)"></span><b>FAILED</b> — session error, invisible today</span>
|
||||
<h4>Harness · model · machine</h4>
|
||||
<span class="kv"><b>✳</b> Claude Code · <b>◈</b> Codex · a neutral glyph for “other” — one tinted glyph before the model name, deliberately quiet.</span>
|
||||
<span class="kv"><b>⏻ machine</b> appears only on threads running somewhere other than the current computer; local threads show nothing.</span>
|
||||
<h4>Slim row (settled, ~28px)</h4>
|
||||
<span class="kv">favicon · title · PR when notable · time. Visually ≈ today's v1 row, so density for history is preserved.</span>
|
||||
<h4>Sort</h4>
|
||||
<span class="kv">Approval first (by wait time) → then pure recency. No sections, no headers, no “show more” — the tail just scrolls, virtualized.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2><span class="num">03</span>The settled model</h2>
|
||||
<p>Concept 4 derived “settled” passively. This version makes it an <strong>acknowledgment with an act attached</strong> — Gmail's archive, GitHub notifications' “Done” — which is what makes row heights stable and the list trustworthy.</p>
|
||||
|
||||
<svg viewBox="0 0 900 210" style="width:100%; max-width:900px; margin:18px 0" role="img" aria-label="Settled state machine">
|
||||
<defs>
|
||||
<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
|
||||
<path d="M0 0 L10 5 L0 10 z" fill="#6b7280"/>
|
||||
</marker>
|
||||
</defs>
|
||||
<rect x="30" y="65" width="180" height="80" rx="14" fill="rgba(56,189,248,.08)" stroke="#38bdf8" stroke-width="1.5"/>
|
||||
<text x="120" y="100" text-anchor="middle" fill="#fff" font-size="17" font-weight="600">Active</text>
|
||||
<text x="120" y="122" text-anchor="middle" fill="#9ca3af" font-size="11">rich card · in rollups</text>
|
||||
<rect x="370" y="65" width="180" height="80" rx="14" fill="rgba(107,114,128,.1)" stroke="#6b7280" stroke-width="1.5"/>
|
||||
<text x="460" y="100" text-anchor="middle" fill="#fff" font-size="17" font-weight="600">Settled</text>
|
||||
<text x="460" y="122" text-anchor="middle" fill="#9ca3af" font-size="11">slim row · out of rollups</text>
|
||||
<rect x="700" y="65" width="170" height="80" rx="14" fill="rgba(248,113,113,.06)" stroke="#3f3f46" stroke-width="1.5" stroke-dasharray="5 4"/>
|
||||
<text x="785" y="100" text-anchor="middle" fill="#fff" font-size="17" font-weight="600">Archived</text>
|
||||
<text x="785" y="122" text-anchor="middle" fill="#9ca3af" font-size="11">existing flow, unchanged</text>
|
||||
<path d="M212 85 C 270 60, 310 60, 368 85" fill="none" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr)"/>
|
||||
<text x="290" y="52" text-anchor="middle" fill="#9ca3af" font-size="11.5">user settles · PR merged/closed · inactive ≥ 3d</text>
|
||||
<path d="M368 128 C 310 153, 270 153, 212 128" fill="none" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr)"/>
|
||||
<text x="290" y="172" text-anchor="middle" fill="#9ca3af" font-size="11.5">any real activity · user un-settles</text>
|
||||
<path d="M552 105 L 698 105" fill="none" stroke="#4b5563" stroke-width="1.5" stroke-dasharray="5 4" marker-end="url(#arr)"/>
|
||||
<text x="625" y="94" text-anchor="middle" fill="#6b7280" font-size="11.5">manual (future: 30d auto)</text>
|
||||
</svg>
|
||||
|
||||
<p><strong>Storage is one override, everything else is computed.</strong> No background jobs, no sweeper:</p>
|
||||
<pre><span class="k">effectiveSettled</span>(thread) =
|
||||
override === <span class="s">"settled"</span> → <span class="k">true</span> <span class="c">// manual settle</span>
|
||||
override === <span class="s">"active"</span> → <span class="k">false</span> <span class="c">// manual keep-active (beats auto rules)</span>
|
||||
pr.state ∈ {<span class="s">merged</span>, <span class="s">closed</span>} → <span class="k">true</span> <span class="c">// auto — strongest signal</span>
|
||||
lastActivityAt < now − inactivityThreshold → <span class="k">true</span> <span class="c">// auto — backstop, default 3d, configurable</span>
|
||||
otherwise → <span class="k">false</span></pre>
|
||||
<ul>
|
||||
<li>Stored: <code>settledOverride: "settled" | "active" | null</code> + <code>settledAt</code>, server-side next to <code>archivedAt</code> — it must sync across desktop/remote, and worktree cleanup needs the server to know. Mirrors the <code>thread.archived</code> event pattern exactly.</li>
|
||||
<li><strong>Activity clears the override</strong> (new user message, session start, approval request) — a settled thread that wakes up expands and floats back up. Settled is never a hole a thread disappears into.</li>
|
||||
<li><strong>Viewing ≠ settling.</strong> Visiting clears unread (existing <code>lastVisitedAt</code>); settling asserts “this work is concluded.” Conflating them would make auto-unsettle fight the user.</li>
|
||||
</ul>
|
||||
<div class="note warn"><strong>Inbox-zero hedge:</strong> manual settling must feel like optional satisfaction, not homework. The auto rules guarantee a user who never touches the affordance still gets a tidy list. Beta telemetry decides how prominent the affordance stays.</div>
|
||||
|
||||
<h2><span class="num">04</span>Swap boundary</h2>
|
||||
<p><strong>Whole-component swap, one seam.</strong> Today's <code>Sidebar.tsx</code> (~3,750 lines) takes zero props and mounts at exactly one place. Everything that must behave identically in both sidebars already lives <em>outside</em> the component in shared hooks and stores — and what lives inside (project grouping, drag-and-drop, show-more) is precisely what v2 deletes.</p>
|
||||
|
||||
<svg viewBox="0 0 900 330" style="width:100%; max-width:900px; margin:18px 0" role="img" aria-label="Component swap architecture">
|
||||
<defs>
|
||||
<marker id="arr2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
|
||||
<path d="M0 0 L10 5 L0 10 z" fill="#6b7280"/>
|
||||
</marker>
|
||||
</defs>
|
||||
<rect x="280" y="14" width="340" height="52" rx="10" fill="#0d0d0f" stroke="#26262c"/>
|
||||
<text x="450" y="36" text-anchor="middle" fill="#fff" font-size="13" font-weight="600" class="mono">AppSidebarLayout.tsx:93</text>
|
||||
<text x="450" y="54" text-anchor="middle" fill="#9ca3af" font-size="11" class="mono">{sidebarV2Enabled ? <ThreadSidebarV2/> : <ThreadSidebar/>}</text>
|
||||
<path d="M380 66 L 235 108" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr2)"/>
|
||||
<path d="M520 66 L 665 108" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr2)"/>
|
||||
<rect x="70" y="112" width="330" height="78" rx="10" fill="#0d0d0f" stroke="#26262c"/>
|
||||
<text x="235" y="136" text-anchor="middle" fill="#fff" font-size="13" font-weight="600" class="mono">Sidebar.tsx (v1 — untouched, default)</text>
|
||||
<text x="235" y="156" text-anchor="middle" fill="#9ca3af" font-size="11">project groups · dnd · show-more · collapse</text>
|
||||
<text x="235" y="174" text-anchor="middle" fill="#6b7280" font-size="11">ignores new settled fields entirely</text>
|
||||
<rect x="500" y="112" width="330" height="78" rx="10" fill="rgba(52,211,153,.05)" stroke="#34d399"/>
|
||||
<text x="665" y="136" text-anchor="middle" fill="#fff" font-size="13" font-weight="600" class="mono">SidebarV2.tsx (new, beta)</text>
|
||||
<text x="665" y="156" text-anchor="middle" fill="#9ca3af" font-size="11">flat virtualized list · card/slim rows · settle</text>
|
||||
<text x="665" y="174" text-anchor="middle" fill="#6b7280" font-size="11">no imports from Sidebar.tsx, ever</text>
|
||||
<path d="M235 190 L 235 232" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr2)"/>
|
||||
<path d="M665 190 L 665 232" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr2)"/>
|
||||
<rect x="70" y="236" width="760" height="72" rx="10" fill="#0d0d0f" stroke="#26262c"/>
|
||||
<text x="450" y="260" text-anchor="middle" fill="#fff" font-size="13" font-weight="600">Shared — both components call the same modules</text>
|
||||
<text x="450" y="282" text-anchor="middle" fill="#9ca3af" font-size="11" class="mono">Sidebar.logic.ts · ThreadStatusIndicators · useThreadActions · threadSelectionStore · uiStateStore · threadSort.ts · keybindings</text>
|
||||
<text x="450" y="300" text-anchor="middle" fill="#6b7280" font-size="11">anything both need moves here first — never cross-imported</text>
|
||||
</svg>
|
||||
|
||||
<ul>
|
||||
<li>The settled <strong>data model ships dark and is flag-independent</strong> — v1 simply ignores the new fields. The toggle is a pure view swap: flipping it never migrates data, so switching back and forth is always safe.</li>
|
||||
<li>Toggle lives in a new <strong>“Beta features”</strong> settings panel: <code>sidebarV2Enabled</code> (default false) + <code>sidebarAutoSettleAfterDays</code> (default 3, nullable = never) in <code>ClientSettingsSchema</code>.</li>
|
||||
<li>Inherited for free via shared hooks: click-to-open, multi-select, context menu, inline rename, thread-jump ⌘1–9, archive, PR link, port/terminal/remote indicators.</li>
|
||||
</ul>
|
||||
|
||||
<h2><span class="num">05</span>Phases</h2>
|
||||
|
||||
<div class="phase">
|
||||
<div class="phase-h"><span class="n">P1</span><span class="t">Settled data model</span><span class="d">ships dark · no UI change</span></div>
|
||||
<div class="phase-b">
|
||||
<ul>
|
||||
<li><code>contracts/settings.ts</code> — add <code>sidebarV2Enabled</code>, <code>sidebarAutoSettleAfterDays</code>.</li>
|
||||
<li><code>contracts/orchestration.ts</code> — <code>settledOverride</code> + <code>settledAt</code> on the thread (decoding defaults → old data decodes unchanged); <code>thread.settled</code> / <code>thread.unsettled</code> events; <code>thread.settle</code> / <code>thread.unsettle</code> commands.</li>
|
||||
<li><code>server/orchestration/decider.ts</code> — handle both commands (settle is idempotent for bulk); activity paths (user message, session start, approval request) emit <code>thread.unsettled</code> when an override is set.</li>
|
||||
<li><code>client-runtime/threadReducer.ts</code> — reduce both events (archive cases at :87–101 are the template).</li>
|
||||
<li>Pure <code>effectiveSettled(shell, {now, autoSettleAfterDays})</code> in client-runtime; unit-test the full truth table (override × PR state × inactivity).</li>
|
||||
</ul>
|
||||
<p class="kv"><b>Verify:</b> typecheck · reducer + predicate tests · zero visible change.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="phase">
|
||||
<div class="phase-h"><span class="n">P2</span><span class="t">SidebarV2 component + beta toggle</span><span class="d">the visible feature</span></div>
|
||||
<div class="phase-b">
|
||||
<ul>
|
||||
<li>“Beta features” settings panel + route; swap seam in <code>AppSidebarLayout.tsx</code>.</li>
|
||||
<li><code>SidebarV2.tsx</code>: flat virtualized list, sort = needs-approval (by wait) → recency; single <code>SidebarV2Row</code> with <code>card</code> / <code>slim</code> variants from the same shell data. Rows lead with the existing <code>ProjectFavicon</code> component (environmentId + cwd are already on the shell).</li>
|
||||
<li>Consolidate status derivation in <code>Sidebar.logic.ts</code> to four visual states: <strong>Needs approval</strong>, <strong>Working</strong> (incl. connecting), <strong>Ready</strong> (merges today's Awaiting Input / Plan Ready / Completed-unseen — same user action, so one unlabeled state), and new <strong>Failed</strong> (<code>session.lastError</code>, non-running) — kept shared so v1 can adopt Failed later.</li>
|
||||
<li>Meta line: harness glyph + model from the shell's provider/model selection; machine label from the thread's environment vs. the current one (render only when they differ). Both are display-only lookups, no new data plumbing.</li>
|
||||
<li>Unread = bold-until-visited from existing <code>uiStateStore.threadLastVisitedAtById</code>.</li>
|
||||
<li>Height changes <strong>only</strong> on settle/unsettle transitions (auto-animate); streaming never resizes rows.</li>
|
||||
<li><code>useThreadActions</code>: <code>settleThread</code> / <code>unsettleThread</code> mirroring <code>archiveThread</code>, minus navigation — settling never navigates away. Affordances: row hover button, context menu, bulk multi-select. No keyboard shortcut yet.</li>
|
||||
</ul>
|
||||
<p class="kv"><b>Verify:</b> toggle on → v2; toggle off → v1 pixel-identical to before · settle round-trips across a desktop+remote pair · killed session → Failed card.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="phase">
|
||||
<div class="phase-h"><span class="n">P3</span><span class="t">Worktree cleanup hook</span><span class="d">settle = reclaim disk</span></div>
|
||||
<div class="phase-b">
|
||||
<ul>
|
||||
<li>On <strong>manual settle</strong> where the worktree is orphaned (<code>getOrphanedWorktreePathForThread</code>): non-blocking “Worktree kept · Remove?” prompt → <code>vcsEnvironment.removeWorktree</code>. Never automatic, never blocks the settle.</li>
|
||||
<li>Skip the prompt when the worktree has uncommitted changes or unpushed commits (from vcs status the sidebar already has).</li>
|
||||
<li>Auto-settle never touches worktrees. Follow-up (tracked, out of scope): settings “Storage” view listing orphaned worktrees of settled threads with sizes + bulk remove.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="phase">
|
||||
<div class="phase-h"><span class="n">P4</span><span class="t">Telemetry & beta exit</span><span class="d">find the balance</span></div>
|
||||
<div class="phase-b">
|
||||
<ul>
|
||||
<li>Count settles by source: manual / auto-PR / auto-inactivity / bulk. Count un-settles: manual vs. activity-driven.</li>
|
||||
<li><strong>Activity-driven un-settles of manual settles</strong> = the model fighting users → retune threshold or triggers.</li>
|
||||
<li>Manual settling ≈ 0% → shrink the affordance, lean on auto rules. High → a habit worth building on (keyboard shortcut, etc.).</li>
|
||||
<li>Track toggle-off rate after trying v2.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2><span class="num">06</span>Open questions</h2>
|
||||
<table>
|
||||
<tr><th>Question</th><th>Current thinking</th></tr>
|
||||
<tr><td>Server-side activity observation</td><td>If decider activity paths are too scattered for unsettle-on-activity, fall back to client-side: compute with activity timestamps, override only stores manual state (activity newer than <code>settledAt</code> wins). Decide in P1.</td></tr>
|
||||
<tr><td>Shell projection</td><td><code>settledOverride</code>/<code>settledAt</code> <strong>must</strong> be in the thread shell stream — the sidebar never loads details. Verify first thing in P1.</td></tr>
|
||||
<tr><td>Diff stats on cards</td><td>Requires checkpoint data in the shell; if absent, defer diff stats rather than loading details per row.</td></tr>
|
||||
<tr><td>Project grouping in v2</td><td>Not planned; v1 stays available for users who want groups. Revisit only if beta feedback demands it.</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="foot">T3 Code · Sidebar v2 beta · plan doc pair: <code>.plans/21-sidebar-v2-beta.md</code> (implementation detail) + this page (design + rationale). Mock data mirrors the original concepts page (from live state.sqlite, Jul 13).</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function settle(btn, showToast) {
|
||||
const row = btn.closest('.row');
|
||||
if (!row) return;
|
||||
row.classList.add('settling');
|
||||
setTimeout(() => {
|
||||
row.classList.remove('settling');
|
||||
row.removeAttribute('data-card');
|
||||
row.style.maxHeight = '';
|
||||
const title = row.querySelector('.title').textContent;
|
||||
const time = row.querySelector('.time').textContent.replace('waiting ', '');
|
||||
const fav = row.querySelector('.fav').outerHTML;
|
||||
row.classList.remove('unread');
|
||||
row.innerHTML = '<div class="slim">' + fav + '<span class="title">' + title +
|
||||
'</span><span class="time">' + time + '</span></div>';
|
||||
const rows = document.getElementById('rows');
|
||||
const firstSlim = Array.from(rows.children).find(r => !r.hasAttribute('data-card'));
|
||||
rows.insertBefore(row, firstSlim ?? null);
|
||||
row.style.opacity = '0';
|
||||
requestAnimationFrame(() => { row.style.transition = 'opacity .3s'; row.style.opacity = '1'; });
|
||||
if (showToast) document.getElementById('toast').classList.add('show');
|
||||
}, 360);
|
||||
}
|
||||
function hideToast() { document.getElementById('toast').classList.remove('show'); }
|
||||
document.querySelectorAll('[data-settle]').forEach((btn) => {
|
||||
btn.addEventListener('click', () => settle(btn, btn.hasAttribute('data-toast')));
|
||||
});
|
||||
document.getElementById('toast-remove').addEventListener('click', hideToast);
|
||||
document.getElementById('reset-mock').addEventListener('click', () => location.reload());
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,285 +0,0 @@
|
||||
# Sidebar v2 (beta): flat adaptive-density list with settled threads
|
||||
|
||||
Status: planned
|
||||
Mocks: https://hsyscdqldmk5.postplan.dev/ (concept 4 base + concept 1 card layout + concept 3 needs-you pinning)
|
||||
|
||||
## Summary
|
||||
|
||||
A new thread sidebar behind a client-settings beta toggle. Core changes vs. the
|
||||
current sidebar:
|
||||
|
||||
- **Flat recency list.** Project group headers are gone; project identity moves
|
||||
onto the row as the existing `ProjectFavicon` (environmentId + cwd). This
|
||||
matches the session lists users know from Claude Code, Codex, and Cursor.
|
||||
- **Adaptive density via a "settled" lifecycle state.** Active threads render
|
||||
as two-line cards: favicon + title + time, then a structured meta line
|
||||
(status word · branch · harness glyph + model · machine). Settled threads
|
||||
collapse to slim one-liners, roughly today's row height. No generated or
|
||||
free-text summaries anywhere — every field on a card is data the shell
|
||||
already carries.
|
||||
- **Settled is an explicit state**, not a derived one: users settle threads
|
||||
manually, or threads auto-settle (PR merged/closed, inactivity). Any real
|
||||
activity auto-unsettles. Settled is a lifecycle stage between active and
|
||||
archived — it stays in the list, just quiet.
|
||||
- **Four visual states, three colors.** Needs approval (amber, pinned above
|
||||
the recency flow with "waiting Xm"), Working (sky, pulsing, elapsed timer),
|
||||
**Ready** (uncolored and unlabeled — the normal resting state: the agent
|
||||
stopped and is waiting on you, whether it finished, asked a question, or
|
||||
proposed a plan; bold title until visited is the only signal), Failed (red,
|
||||
`session.lastError` — a dead session shows nothing today). Today's Awaiting
|
||||
Input / Plan Ready / Completed-unseen pills all collapse into Ready: they
|
||||
differ in detail, not in what the user should do (look at the thread).
|
||||
Color is reserved for "act now" (amber), "in motion" (sky), "broken" (red).
|
||||
- **Harness / model / machine as quiet metadata.** A tinted glyph before the
|
||||
model name distinguishes Claude Code / Codex / other; a machine label
|
||||
renders only when the thread lives on a different computer than the one
|
||||
you're looking at. Display-only lookups from shell data, no new plumbing.
|
||||
- **Settled feeds cleanup.** Settling a thread offers/permits worktree cleanup;
|
||||
long-settled threads are candidates for future auto-archive.
|
||||
|
||||
The v2 component is a sibling of the current sidebar, swapped at a single mount
|
||||
point. The current sidebar is untouched except for the swap seam.
|
||||
|
||||
## Rationale
|
||||
|
||||
Full design discussion lives in the session that produced the mocks; the short
|
||||
version:
|
||||
|
||||
- We aren't in a position to teach users a new interaction model. Every v2
|
||||
mechanic maps to an existing habit: flat recency list (Claude Code / Codex /
|
||||
Cursor), settle (Gmail archive / GitHub notifications "Done"), unread-bold
|
||||
(email). Zero new gestures.
|
||||
- "Settled" makes the adaptive-density row-height rule *stable*: height changes
|
||||
only at real lifecycle transitions, never from ambient re-rendering. This
|
||||
kills concept 4's "jumpy list" risk.
|
||||
- Viewing a thread does **not** settle it. Visiting clears unseen (existing
|
||||
`lastVisitedAt` mechanics); settling asserts "this work is concluded." If
|
||||
viewing settled, auto-unsettle would fight the user and the state would stop
|
||||
meaning anything.
|
||||
- Settling is optional by design. The auto rules are the hedge against
|
||||
inbox-zero fatigue: a user who never touches the affordance still gets a
|
||||
naturally tidy list. Beta telemetry question: what fraction of settles are
|
||||
manual vs. auto?
|
||||
|
||||
## The settled model
|
||||
|
||||
```
|
||||
Active ──(user settles | PR merged/closed | inactivity ≥ threshold)──▶ Settled
|
||||
Settled ──(new user message | session starts | approval requested |
|
||||
PR reopened | user un-settles)──▶ Active
|
||||
Settled ──(existing archive flow, or future auto-archive)──▶ Archived
|
||||
```
|
||||
|
||||
Settled is a **computed property with one stored override**:
|
||||
|
||||
```
|
||||
effectiveSettled(thread) =
|
||||
override === "settled" → true (manual settle)
|
||||
override === "active" → false (manual keep-active)
|
||||
pr.state ∈ {merged, closed} → true (auto)
|
||||
lastActivityAt < now − inactivityThreshold → true (auto)
|
||||
otherwise → false
|
||||
```
|
||||
|
||||
- The stored field is a tri-state: `settledOverride: "settled" | "active" | null`
|
||||
plus `settledAt: IsoDateTime | null` (set when override becomes "settled",
|
||||
used for display and future auto-archive aging).
|
||||
- The auto cases need no background job and no events — they fall out of data
|
||||
the sidebar already streams (`vcs.status` change request state,
|
||||
`latestUserMessageAt` / turn timestamps). Auto-unsettle for the time-based
|
||||
case is free: activity moves the timestamp, the predicate flips.
|
||||
- **Activity clears the override.** Any thread activity event (new user
|
||||
message, session start, approval request) resets `settledOverride` to null
|
||||
server-side, so a manually settled thread that wakes up becomes active again
|
||||
and later auto-rules apply fresh. Likewise, manually un-settling a merged-PR
|
||||
thread sets `settledOverride: "active"`, which beats the PR auto-rule.
|
||||
- Inactivity threshold: default 3 days, client setting, `null` = never
|
||||
auto-settle by time.
|
||||
|
||||
Server-side storage (next to `archivedAt` on the thread) rather than
|
||||
client-local: settled must sync across desktop/remote environments, and the
|
||||
worktree-cleanup hook needs the server to know. This mirrors the
|
||||
`archivedAt` / `thread.archived` / `thread.unarchived` pattern exactly.
|
||||
|
||||
Consequences of being settled:
|
||||
|
||||
- Row collapses to the slim one-liner.
|
||||
- Excluded from status rollups (any badge counts, aggregate status dots).
|
||||
- Eligible for worktree cleanup prompting (see below).
|
||||
- Future: settled ≥ 30 days → auto-archive candidate (not in this phase).
|
||||
|
||||
## Swap strategy: component swap at the mount point
|
||||
|
||||
Decision: **swap the whole sidebar component**, not internals.
|
||||
|
||||
The current `Sidebar.tsx` (~3750 lines) takes no props — it reads everything
|
||||
from hooks/atoms/stores — and `AppSidebarLayout.tsx:93` is its single mount
|
||||
point. The truly shared behavior (thread-jump keybindings, selection store,
|
||||
uiStateStore, `useThreadActions`, context-menu via `readLocalApi()`) already
|
||||
lives *outside* the component in hooks and stores, so a sibling component
|
||||
inherits all of it by calling the same hooks. What lives inside Sidebar.tsx
|
||||
(project grouping, drag-and-drop, show-more, per-project collapse) is exactly
|
||||
the stuff v2 deletes — threading a variant flag through it would mean touching
|
||||
hundreds of conditional branches for no benefit.
|
||||
|
||||
```tsx
|
||||
// AppSidebarLayout.tsx — the entire seam
|
||||
const sidebarV2 = useClientSettings((s) => s.sidebarV2Enabled);
|
||||
...
|
||||
{sidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />}
|
||||
```
|
||||
|
||||
Rules for the seam:
|
||||
|
||||
- `SidebarV2.tsx` imports freely from `Sidebar.logic.ts`,
|
||||
`ThreadStatusIndicators.tsx`, `useThreadActions`, `threadSelectionStore`,
|
||||
`uiStateStore` — shared logic stays shared.
|
||||
- `SidebarV2.tsx` must not import from `Sidebar.tsx`, and vice versa. Anything
|
||||
both need moves into `Sidebar.logic.ts` (or a new shared module) first.
|
||||
- The settled *data model* (contracts, server, reducer) is flag-independent —
|
||||
it ships dark and is simply unused by the v1 component. Only the *UI* is
|
||||
gated. This keeps the toggle a pure view swap: flipping it never migrates
|
||||
data, so switching back and forth is always safe.
|
||||
- v1 remains the default. Deleting v1 is a separate future decision once beta
|
||||
feedback lands.
|
||||
|
||||
## Implementation phases
|
||||
|
||||
### Phase 1 — Settled data model (ships dark, no UI)
|
||||
|
||||
Mirror the archived pattern end-to-end:
|
||||
|
||||
1. `packages/contracts/src/settings.ts`: add to `ClientSettingsSchema`:
|
||||
- `sidebarV2Enabled: boolean` (default false)
|
||||
- `sidebarAutoSettleAfterDays: number | null` (default 3)
|
||||
2. `packages/contracts/src/orchestration.ts`:
|
||||
- Thread shell: `settledOverride: "settled" | "active" | null`,
|
||||
`settledAt: IsoDateTime | null` (both with decoding defaults of null —
|
||||
old persisted threads decode unchanged).
|
||||
- Events: `thread.settled` (threadId, settledAt, updatedAt),
|
||||
`thread.unsettled` (threadId, updatedAt). Payload schemas alongside
|
||||
`ThreadArchivedPayload` / `ThreadUnarchivedPayload`.
|
||||
- Commands: `thread.settle`, `thread.unsettle`.
|
||||
3. `apps/server/src/orchestration/decider.ts`: handle both commands, mirroring
|
||||
archive/unarchive. Invariants in `commandInvariants.ts`
|
||||
(`requireThreadNotArchived` applies; settle of an already-settled thread is
|
||||
a no-op rather than an error — idempotent for bulk operations).
|
||||
In the decider paths that record thread activity (user message appended,
|
||||
session started, approval requested): if `settledOverride !== null`, also
|
||||
emit `thread.unsettled` to clear it.
|
||||
4. `packages/client-runtime/src/state/threadReducer.ts`: reduce both events
|
||||
(`threadReducer.ts:87-101` is the archive template). Tests alongside the
|
||||
archive reducer tests.
|
||||
5. `packages/client-runtime` (new `threadSettled.ts` or in `threadSort.ts`):
|
||||
pure `effectiveSettled(shell, { now, autoSettleAfterDays })` implementing
|
||||
the predicate above, plus `lastActivityAt(shell)` (max of
|
||||
latestUserMessageAt, latest turn completion, session start). Unit-test the
|
||||
truth table: each override state × PR state × inactivity.
|
||||
|
||||
Verification: `bun run typecheck`, reducer + predicate unit tests. No visible
|
||||
change anywhere.
|
||||
|
||||
### Phase 2 — SidebarV2 component + beta toggle
|
||||
|
||||
1. Settings UI: "Beta features" section (new panel in
|
||||
`apps/web/src/components/settings/SettingsPanels.tsx` + route, matching the
|
||||
existing settings-page pattern) with the v2 toggle and, indented under it,
|
||||
the auto-settle threshold control.
|
||||
2. Swap seam in `AppSidebarLayout.tsx` as above.
|
||||
3. `apps/web/src/components/SidebarV2.tsx`, reusing shared modules. Structure:
|
||||
- **One flat virtualized list** of all non-archived threads across
|
||||
projects. Sort key: (needs-approval first, by wait time) → then recency
|
||||
(`latestUserMessageAt`, reusing `threadSort.ts`). No show-more, no
|
||||
project collapse, no dnd.
|
||||
- **Row variants** (single `SidebarV2Row` with a `variant` prop, both
|
||||
variants rendered from the same shell data):
|
||||
- `card` (~52px, threads where `effectiveSettled` is false): line 1
|
||||
`ProjectFavicon` + title (+ diff stats when present) + time ("waiting
|
||||
Xm" in amber when approval-blocked, live elapsed for working); line 2
|
||||
structured meta — status word (only for the colored states) · branch ·
|
||||
harness glyph + model · machine (only when the thread's environment is
|
||||
not the current machine). Left rail color only for approval (amber),
|
||||
working (sky, pulsing), failed (red) — Ready rows carry no color or
|
||||
label, just a bold title while unread. No free-text/generated content.
|
||||
- `slim` (~28px, settled): `ProjectFavicon` · title · PR badge when
|
||||
notable · time. Visually close to today's v1 row.
|
||||
- **Status derivation** consolidates `Sidebar.logic.ts`'s pill logic into
|
||||
four visual states: Needs Approval, Working (incl. connecting), Ready
|
||||
(today's Awaiting Input + Plan Ready + Completed-unseen — same user
|
||||
action, different payload), and new Failed (`session.lastError` on a
|
||||
non-running session). Keep it in `Sidebar.logic.ts` so v1 can adopt
|
||||
Failed later too.
|
||||
- **Unread**: bold title until visited, from existing
|
||||
`uiStateStore.threadLastVisitedAtById` — same mechanics as today's
|
||||
Completed-unseen pill.
|
||||
- **Row height changes only on lifecycle transitions** (settle/unsettle),
|
||||
animated with the existing auto-animate pattern. Streaming/status
|
||||
updates within a variant never change height.
|
||||
- Preserved v1 behaviors, via the shared hooks: click-to-open, multi-select
|
||||
(threadSelectionStore), context menu (add Settle/Un-settle entries),
|
||||
inline rename, thread-jump shortcut labels, archive affordance, PR icon
|
||||
link, port/terminal/remote indicators (moved into line 3 / slim row
|
||||
trailing icons).
|
||||
4. Settle affordances:
|
||||
- Hover action on the row (next to today's archive hover button) +
|
||||
context-menu entry + bulk via multi-select.
|
||||
- `useThreadActions`: add `settleThread` / `unsettleThread` mirroring
|
||||
`archiveThread` (`useThreadActions.ts:91-134`), minus the navigation
|
||||
dance — settling never navigates away.
|
||||
- No keyboard shortcut in the first cut; add via keybindings once the
|
||||
affordance proves out.
|
||||
|
||||
Verification: typecheck/lint; toggle on → v2 renders, toggle off → v1
|
||||
identical to before; settle/unsettle round-trips including across a
|
||||
desktop+remote pair; kill a session mid-run → Failed card appears.
|
||||
|
||||
### Phase 3 — Worktree cleanup hook
|
||||
|
||||
Settling is the natural moment to reclaim disk:
|
||||
|
||||
1. On **manual settle** of a thread whose worktree is orphaned
|
||||
(`getOrphanedWorktreePathForThread`, `worktreeCleanup.ts:11-33`): show a
|
||||
non-blocking inline prompt/toast — "Worktree kept · Remove?" — that calls
|
||||
`vcsEnvironment.removeWorktree`. Never remove without an explicit click;
|
||||
never block the settle on the answer. Skip the prompt entirely when the
|
||||
worktree has uncommitted changes or unpushed commits (check via the
|
||||
existing vcs status the sidebar already has).
|
||||
2. **Auto-settle does not touch worktrees** in this phase. A settings-page
|
||||
"Storage" affordance listing orphaned worktrees of settled threads (with
|
||||
sizes, bulk-remove) is the follow-up; tracked but not in scope.
|
||||
|
||||
### Phase 4 — Beta telemetry & exit criteria
|
||||
|
||||
Instrument (whatever the existing analytics path is — if none, a lightweight
|
||||
local counter surfaced in diagnostics is enough for the beta):
|
||||
|
||||
- settle events by source: manual / auto-PR / auto-inactivity / bulk
|
||||
- un-settle events: manual vs. activity-driven (activity-driven un-settles of
|
||||
*manual* settles = the model fighting users)
|
||||
- toggle-off rate after trying v2
|
||||
|
||||
Decision inputs for exiting beta: if manual settling is ~0%, shrink the
|
||||
affordance and lean on auto rules; if activity-unsettle-of-manual-settle is
|
||||
high, the inactivity threshold or unsettle triggers need retuning.
|
||||
|
||||
## Explicitly out of scope
|
||||
|
||||
- Inline approve/reject in the sidebar (concept 3) — needs a safety story.
|
||||
- Message snippets in rows (concept 2) — streaming churn unsolved.
|
||||
- Ops-grid density mode (concept 5).
|
||||
- Auto-archive of long-settled threads.
|
||||
- Removing v1 / making v2 the default.
|
||||
- Project grouping inside v2 (v1 remains available for users who want groups).
|
||||
|
||||
## Open questions
|
||||
|
||||
- Where thread "activity" is centrally observable server-side for the
|
||||
unsettle-on-activity rule — if the decider paths are too scattered, an
|
||||
acceptable fallback is client-side: compute `effectiveSettled` with the
|
||||
activity timestamps and only use the override for manual state (activity
|
||||
newer than `settledAt` wins). Decide during Phase 1 once in the decider.
|
||||
- Whether `settledAt` belongs in the thread *shell* stream (sidebar reads
|
||||
shells only) — it must, or v2 can't sort/collapse without detail loads.
|
||||
Verify shell projection includes it.
|
||||
- Diff stats on cards require checkpoint data in the shell; if absent, defer
|
||||
diff stats rather than loading details for every row.
|
||||
@@ -0,0 +1,257 @@
|
||||
<!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,27 +2,16 @@
|
||||
|
||||
## Task Completion Requirements
|
||||
|
||||
- `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.
|
||||
- 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.
|
||||
|
||||
## Package Roles
|
||||
|
||||
@@ -35,7 +24,6 @@ Long term maintainability is a core priority. If you add new functionality, firs
|
||||
## 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.
|
||||
|
||||
@@ -47,8 +35,7 @@ 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 `bun run sync:repos`; use `bun run sync:repos --repo <id>` to sync one
|
||||
configured repository.
|
||||
- Manage vendored subtrees with `vpr sync:repos`; use `vpr sync:repos --repo <id>` to sync one configured repository.
|
||||
- When updating a dependency with a configured vendored subtree, sync that subtree in the same change so
|
||||
`.repos/` matches the installed dependency version.
|
||||
- When writing Effect code, read `.repos/effect-smol/LLMS.md` first and inspect `.repos/effect-smol/` for
|
||||
|
||||
@@ -54,6 +54,8 @@ 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)
|
||||
|
||||
@@ -20,7 +20,7 @@ export const APP_BUNDLE_ID = isDevelopment
|
||||
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 12;
|
||||
const LAUNCHER_VERSION = 14;
|
||||
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = NodePath.join(
|
||||
repoRoot,
|
||||
@@ -220,11 +220,12 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
}
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
|
||||
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
|
||||
setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
|
||||
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
|
||||
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
|
||||
{
|
||||
@@ -277,11 +278,25 @@ function readJson(path) {
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
|
||||
const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
|
||||
const launcherExecutableName = `${displayName} Launcher`;
|
||||
return {
|
||||
launcherExecutableName,
|
||||
launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
|
||||
runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
|
||||
};
|
||||
}
|
||||
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
|
||||
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
|
||||
const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
|
||||
const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
|
||||
const launcherBinaryPath = isDevelopment
|
||||
? developmentPaths.launcherBinaryPath
|
||||
: runtimeElectronBinaryPath;
|
||||
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
|
||||
|
||||
@@ -298,7 +313,8 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
|
||||
const currentMetadata = readJson(metadataPath);
|
||||
if (
|
||||
NodeFS.existsSync(targetBinaryPath) &&
|
||||
NodeFS.existsSync(launcherBinaryPath) &&
|
||||
(!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
@@ -306,10 +322,10 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
// The launcher also handles protocol activations outside the dev runner,
|
||||
// so refresh its fallback environment on every launch. Never let a value
|
||||
// captured by an older parent app override the live dev-runner environment.
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
|
||||
}
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
return targetBinaryPath;
|
||||
return launcherBinaryPath;
|
||||
}
|
||||
|
||||
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
@@ -321,15 +337,24 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
recursive: true,
|
||||
verbatimSymlinks: true,
|
||||
});
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchMainBundleInfoPlist(
|
||||
targetAppBundlePath,
|
||||
iconPath,
|
||||
isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
|
||||
);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
if (isDevelopment) {
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
// Keep Electron's native executable inside the branded bundle. Launching the
|
||||
// node_modules copy makes macOS associate the process (and Dock label) with
|
||||
// Electron.app even though this bundle's Info.plist has the T3 Code name.
|
||||
// Its conventional executable name also keeps Electron's default-app runtime
|
||||
// in development mode instead of making app.isPackaged report true.
|
||||
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
|
||||
}
|
||||
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
|
||||
return targetBinaryPath;
|
||||
return launcherBinaryPath;
|
||||
}
|
||||
|
||||
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
|
||||
import {
|
||||
makeDevelopmentLauncherScript,
|
||||
resolveElectronBinaryPath,
|
||||
resolveMacLauncherPaths,
|
||||
} from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
@@ -45,4 +49,33 @@ describe("electron development launcher", () => {
|
||||
);
|
||||
assert.deepEqual(calls, ["ensure", "require:electron"]);
|
||||
});
|
||||
|
||||
it("keeps the native Electron executable name inside the branded macOS bundle", () => {
|
||||
const paths = resolveMacLauncherPaths(
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app",
|
||||
"T3 Code (Dev)",
|
||||
);
|
||||
|
||||
assert.equal(paths.launcherExecutableName, "T3 Code (Dev) Launcher");
|
||||
assert.equal(
|
||||
paths.launcherBinaryPath,
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/T3 Code (Dev) Launcher",
|
||||
);
|
||||
assert.equal(
|
||||
paths.runtimeElectronBinaryPath,
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron",
|
||||
);
|
||||
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: paths.runtimeElectronBinaryPath,
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {},
|
||||
});
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron'",
|
||||
);
|
||||
assert.notInclude(script, "node_modules/electron");
|
||||
});
|
||||
});
|
||||
@@ -53,13 +53,16 @@ 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/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.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.rootDir, "/repo");
|
||||
assert.equal(environment.appRoot, "/repo");
|
||||
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
|
||||
@@ -78,7 +81,7 @@ describe("DesktopEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("derives production state paths under userdata", () =>
|
||||
it.effect("stores production state under userdata in an explicit home", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment(
|
||||
{},
|
||||
@@ -95,6 +98,19 @@ 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,7 +147,8 @@ 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 baseDir = Option.getOrElse(config.t3Home, () => path.join(homeDirectory, ".t3"));
|
||||
const configuredBaseDir = config.t3Home;
|
||||
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
|
||||
const rootDir = path.resolve(input.dirname, "../../..");
|
||||
const appRoot = input.isPackaged ? input.appPath : rootDir;
|
||||
const branding = resolveDesktopAppBranding({
|
||||
@@ -155,7 +156,10 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
appVersion: input.appVersion,
|
||||
});
|
||||
const displayName = branding.displayName;
|
||||
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata");
|
||||
const stateDir = path.join(
|
||||
baseDir,
|
||||
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
|
||||
);
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const resourcesPath = input.resourcesPath;
|
||||
|
||||
@@ -73,8 +73,14 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
|
||||
}
|
||||
|
||||
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> {
|
||||
function* (): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow
|
||||
> {
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.flushMainWindowBounds;
|
||||
yield* shutdown.request;
|
||||
yield* shutdown.awaitComplete;
|
||||
},
|
||||
|
||||
@@ -76,6 +76,7 @@ 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,6 +250,7 @@ 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"),
|
||||
|
||||
@@ -31,6 +31,12 @@ const TestLayer = ElectronMenu.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
const makeWindow = (zoomFactor = 1): Electron.BrowserWindow =>
|
||||
({
|
||||
id: 7,
|
||||
webContents: { getZoomFactor: () => zoomFactor },
|
||||
}) as unknown as Electron.BrowserWindow;
|
||||
|
||||
describe("ElectronMenu", () => {
|
||||
beforeEach(() => {
|
||||
buildFromTemplateMock.mockReset();
|
||||
@@ -70,7 +76,7 @@ describe("ElectronMenu", () => {
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const selectedItemId = yield* electronMenu.showContextMenu({
|
||||
window: {} as Electron.BrowserWindow,
|
||||
window: makeWindow(),
|
||||
items: [{ id: "copy", label: "Copy" }],
|
||||
position: Option.none(),
|
||||
});
|
||||
@@ -81,20 +87,24 @@ describe("ElectronMenu", () => {
|
||||
|
||||
it.effect("resolves with none when the menu closes without a click", () =>
|
||||
Effect.gen(function* () {
|
||||
let popupOptions: Electron.PopupOptions | undefined;
|
||||
buildFromTemplateMock.mockImplementation(() => ({
|
||||
popup: (options: Electron.PopupOptions) => {
|
||||
popupOptions = options;
|
||||
options.callback?.();
|
||||
},
|
||||
}));
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const selectedItemId = yield* electronMenu.showContextMenu({
|
||||
window: {} as Electron.BrowserWindow,
|
||||
window: makeWindow(2),
|
||||
items: [{ id: "copy", label: "Copy" }],
|
||||
position: Option.some({ x: 10.8, y: 20.2 }),
|
||||
});
|
||||
|
||||
assert.isTrue(Option.isNone(selectedItemId));
|
||||
assert.equal(popupOptions?.x, 21);
|
||||
assert.equal(popupOptions?.y, 40);
|
||||
assert.deepEqual(buildFromTemplateMock.mock.calls[0]?.[0][0], {
|
||||
label: "Copy",
|
||||
enabled: true,
|
||||
|
||||
@@ -94,13 +94,20 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
|
||||
return normalizedItems;
|
||||
}
|
||||
|
||||
// Renderer positions arrive in CSS pixels; popup() expects window points, so
|
||||
// page zoom must be factored in or menus drift proportionally to their
|
||||
// distance from the window origin.
|
||||
const normalizePosition = (
|
||||
position: Option.Option<ElectronMenuPosition>,
|
||||
zoomFactor: number,
|
||||
): Option.Option<ElectronMenuPosition> =>
|
||||
Option.filter(
|
||||
position,
|
||||
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
|
||||
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
|
||||
({ x, y }) =>
|
||||
Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
|
||||
).pipe(
|
||||
Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
@@ -214,7 +221,10 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
try {
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupPosition = normalizePosition(
|
||||
input.position,
|
||||
input.window.webContents.getZoomFactor(),
|
||||
);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
|
||||
@@ -10,6 +10,7 @@ const { autoUpdaterMock } = vi.hoisted(() => ({
|
||||
autoInstallOnAppQuit: true,
|
||||
channel: "latest",
|
||||
disableDifferentialDownload: false,
|
||||
fullChangelog: false,
|
||||
checkForUpdates: vi.fn(() => Promise.resolve(null)),
|
||||
downloadUpdate: vi.fn(() => Promise.resolve([])),
|
||||
on: vi.fn(),
|
||||
@@ -33,6 +34,7 @@ describe("ElectronUpdater", () => {
|
||||
autoUpdaterMock.autoInstallOnAppQuit = true;
|
||||
autoUpdaterMock.channel = "latest";
|
||||
autoUpdaterMock.disableDifferentialDownload = false;
|
||||
autoUpdaterMock.fullChangelog = false;
|
||||
autoUpdaterMock.checkForUpdates.mockClear();
|
||||
autoUpdaterMock.checkForUpdates.mockImplementation(() => Promise.resolve(null));
|
||||
autoUpdaterMock.downloadUpdate.mockClear();
|
||||
@@ -98,6 +100,18 @@ describe("ElectronUpdater", () => {
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("sets full changelog mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
|
||||
yield* updater.setFullChangelog(true);
|
||||
assert.equal(autoUpdaterMock.fullChangelog, true);
|
||||
|
||||
yield* updater.setFullChangelog(false);
|
||||
assert.equal(autoUpdaterMock.fullChangelog, false);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("quit and install failed");
|
||||
|
||||
@@ -66,6 +66,7 @@ export class ElectronUpdater extends Context.Service<
|
||||
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
|
||||
readonly allowDowngrade: Effect.Effect<boolean>;
|
||||
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
|
||||
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
|
||||
@@ -112,6 +113,11 @@ export const make = ElectronUpdater.of({
|
||||
autoUpdater.allowDowngrade = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.fullChangelog = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
setDisableDifferentialDownload: (value) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.disableDifferentialDownload = value;
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getWindowFullscreenState,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
setTheme,
|
||||
@@ -48,6 +49,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getWindowFullscreenState);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
|
||||
yield* ipc.handle(getLocalEnvironmentBearerToken);
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
|
||||
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
|
||||
@@ -48,6 +50,7 @@ export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in";
|
||||
export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out";
|
||||
export const PREVIEW_RESET_ZOOM_CHANNEL = "desktop:preview-reset-zoom";
|
||||
export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
|
||||
export const PREVIEW_SET_COLOR_SCHEME_CHANNEL = "desktop:preview-set-color-scheme";
|
||||
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
|
||||
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
|
||||
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
DesktopPreviewRecordingSaveInputSchema,
|
||||
DesktopPreviewRegisterWebviewInputSchema,
|
||||
DesktopPreviewScreenshotArtifactSchema,
|
||||
DesktopPreviewSetColorSchemeInputSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
@@ -138,6 +139,15 @@ export const hardReload = tabMethod(
|
||||
"desktop.ipc.preview.hardReload",
|
||||
(manager, tabId) => manager.hardReload(tabId),
|
||||
);
|
||||
export const setColorScheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL,
|
||||
payload: DesktopPreviewSetColorSchemeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.setColorScheme")(function* ({ tabId, colorScheme }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.setColorScheme(tabId, colorScheme);
|
||||
}),
|
||||
});
|
||||
export const openDevTools = tabMethod(
|
||||
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
|
||||
"desktop.ipc.preview.openDevTools",
|
||||
@@ -346,6 +356,7 @@ export const methods = [
|
||||
zoomOut,
|
||||
resetZoom,
|
||||
hardReload,
|
||||
setColorScheme,
|
||||
openDevTools,
|
||||
clearCookies,
|
||||
clearCache,
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
|
||||
import { getLocalEnvironmentBootstraps } from "./window.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import { getLocalEnvironmentBootstraps, getWindowFullscreenState } from "./window.ts";
|
||||
|
||||
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "wsl.exe",
|
||||
@@ -126,3 +130,19 @@ describe("getLocalEnvironmentBootstraps", () => {
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
|
||||
});
|
||||
});
|
||||
|
||||
describe("getWindowFullscreenState", () => {
|
||||
it.effect("reads the current native window state", () => {
|
||||
const window = { isFullScreen: () => true } as Electron.BrowserWindow;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
assert.isTrue(yield* getWindowFullscreenState.handler());
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mock(ElectronWindow.ElectronWindow)({
|
||||
currentMainOrFirst: Effect.succeed(Option.some(window)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -55,6 +55,16 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const window = yield* electronWindow.currentMainOrFirst;
|
||||
return Option.isSome(window) && window.value.isFullScreen();
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
|
||||
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
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";
|
||||
|
||||
@@ -116,6 +116,19 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getWindowFullscreenState: () =>
|
||||
ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
|
||||
onWindowFullscreenStateChange: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, fullscreen: unknown) => {
|
||||
if (typeof fullscreen !== "boolean") return;
|
||||
listener(fullscreen);
|
||||
};
|
||||
|
||||
ipcRenderer.on(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
|
||||
setUpdateChannel: (channel) =>
|
||||
ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
|
||||
@@ -147,6 +160,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }),
|
||||
resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }),
|
||||
hardReload: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, { tabId }),
|
||||
setColorScheme: (tabId, colorScheme) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL, { tabId, colorScheme }),
|
||||
openDevTools: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
|
||||
clearCookies: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL),
|
||||
|
||||
@@ -15,6 +15,7 @@ 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>;
|
||||
}
|
||||
>(),
|
||||
@@ -40,6 +41,7 @@ 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);
|
||||
@@ -61,6 +63,55 @@ 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,6 +11,20 @@ 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",
|
||||
{
|
||||
@@ -120,9 +134,11 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
.replace(/\s*t3code\/[\d.]+/, "");
|
||||
browserSession.setUserAgent(userAgent);
|
||||
browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
|
||||
const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
|
||||
callback(allowed.includes(permission));
|
||||
callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
|
||||
});
|
||||
browserSession.setPermissionCheckHandler((_webContents, permission) =>
|
||||
ALLOWED_PREVIEW_PERMISSIONS.has(permission),
|
||||
);
|
||||
const next = new Map(sessions);
|
||||
next.set(partition, browserSession);
|
||||
return [browserSession, next] as const;
|
||||
|
||||
@@ -365,6 +365,79 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("emulates prefers-color-scheme and re-applies it across webview swaps", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const makeWebContents = (id: number) => {
|
||||
const sendCommand = vi.fn(async () => undefined);
|
||||
return {
|
||||
sendCommand,
|
||||
wc: {
|
||||
id,
|
||||
isDestroyed: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never,
|
||||
};
|
||||
};
|
||||
const first = makeWebContents(42);
|
||||
fromId.mockReturnValue(first.wc);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_scheme");
|
||||
yield* manager.registerWebview("tab_scheme", 42);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* manager.setColorScheme("tab_scheme", "dark");
|
||||
|
||||
expect(first.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "dark" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("dark");
|
||||
|
||||
const replacement = makeWebContents(43);
|
||||
fromId.mockReturnValue(replacement.wc);
|
||||
yield* manager.registerWebview("tab_scheme", 43);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(replacement.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "dark" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("dark");
|
||||
|
||||
yield* manager.setColorScheme("tab_scheme", "system");
|
||||
|
||||
expect(replacement.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", {
|
||||
features: [{ name: "prefers-color-scheme", value: "" }],
|
||||
});
|
||||
expect(states.at(-1)?.colorScheme).toBe("system");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
import type {
|
||||
DesktopPreviewAnnotationTheme,
|
||||
DesktopPreviewColorScheme,
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
@@ -84,6 +85,7 @@ export interface PreviewTabState {
|
||||
canGoBack: boolean;
|
||||
canGoForward: boolean;
|
||||
zoomFactor: number;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -1288,6 +1290,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1320,6 +1323,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1386,7 +1390,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc.getZoomFactor(),
|
||||
);
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
runFork(restoreControlSession(tabId, wc));
|
||||
const registeredAt = yield* currentIso;
|
||||
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
@@ -1457,6 +1461,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
canGoBack: current?.canGoBack ?? false,
|
||||
canGoForward: current?.canGoForward ?? false,
|
||||
zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR,
|
||||
colorScheme: current?.colorScheme ?? "system",
|
||||
controller: current?.controller ?? "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1525,7 +1530,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* detachControlSession(wc.id);
|
||||
yield* attempt({ operation: "openDevTools", tabId, webContentsId: wc.id }, () => {
|
||||
wc.once("devtools-closed", () => {
|
||||
if (!wc.isDestroyed()) runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
if (!wc.isDestroyed()) runFork(restoreControlSession(tabId, wc));
|
||||
});
|
||||
wc.openDevTools({ mode: "detach" });
|
||||
});
|
||||
@@ -1684,6 +1689,65 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* update(tabId, { zoomFactor: next });
|
||||
});
|
||||
|
||||
// Emulated media lives on the CDP debugger session, not the WebContents, so
|
||||
// it is lost whenever the session detaches (webview swap, DevTools
|
||||
// open/close) and must be re-applied after every (re)attach.
|
||||
const applyColorScheme = Effect.fn("PreviewManager.applyColorScheme")(function* (
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) {
|
||||
yield* ensureControlSession(wc);
|
||||
yield* attemptPromise({ operation: "applyColorScheme", tabId, webContentsId: wc.id }, () =>
|
||||
wc.debugger.sendCommand("Emulation.setEmulatedMedia", {
|
||||
features: [
|
||||
{
|
||||
name: "prefers-color-scheme",
|
||||
// An empty value clears the override so the page follows the OS.
|
||||
value: colorScheme === "system" ? "" : colorScheme,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// Re-establish the control session after a detach, restoring any
|
||||
// color-scheme override the tab carries. The scheme is read after the
|
||||
// session attaches so a concurrent setColorScheme is not overwritten with
|
||||
// a stale snapshot.
|
||||
const restoreControlSession = (tabId: string, wc: Electron.WebContents) =>
|
||||
ensureControlSession(wc).pipe(
|
||||
Effect.andThen(SynchronizedRef.get(tabsRef)),
|
||||
Effect.flatMap((tabs) => {
|
||||
const colorScheme = tabs.get(tabId)?.colorScheme ?? "system";
|
||||
return colorScheme === "system" ? Effect.void : applyColorScheme(tabId, wc, colorScheme);
|
||||
}),
|
||||
Effect.ignore,
|
||||
);
|
||||
|
||||
const setColorScheme = Effect.fn("PreviewManager.setColorScheme")(function* (
|
||||
tabId: string,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) {
|
||||
const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
if (!tab) {
|
||||
return yield* new PreviewTabNotFoundError({ tabId });
|
||||
}
|
||||
if (tab.colorScheme !== colorScheme) {
|
||||
// Record the choice even when the CDP call below can't run yet (no
|
||||
// webview, DevTools holding the debugger) — it is re-applied on the
|
||||
// next control-session (re)attach.
|
||||
yield* update(tabId, { colorScheme });
|
||||
}
|
||||
// Re-read after the update: registerWebview may have swapped the guest
|
||||
// in the meantime and the override must land on the current one.
|
||||
const webContentsId = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.webContentsId;
|
||||
if (webContentsId == null) return;
|
||||
const wc = webContents.fromId(webContentsId);
|
||||
if (!wc || wc.isDestroyed()) return;
|
||||
yield* applyColorScheme(tabId, wc, colorScheme);
|
||||
});
|
||||
|
||||
const captureScreenshot = Effect.fn("PreviewManager.captureScreenshot")(function* (
|
||||
tabId: string,
|
||||
) {
|
||||
@@ -2526,6 +2590,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
revealArtifact,
|
||||
saveRecording,
|
||||
setAnnotationTheme,
|
||||
setColorScheme,
|
||||
setMainWindow,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
@@ -2830,6 +2895,10 @@ export class PreviewManager extends Context.Service<
|
||||
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly setColorScheme: (
|
||||
tabId: string,
|
||||
colorScheme: DesktopPreviewColorScheme,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
|
||||
@@ -2921,6 +2990,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
zoomOut: operations.zoomOut,
|
||||
resetZoom: operations.resetZoom,
|
||||
hardReload: operations.hardReload,
|
||||
setColorScheme: operations.setColorScheme,
|
||||
openDevTools: operations.openDevTools,
|
||||
clearCookies: Effect.fn("PreviewManager.clearCookies")(function* () {
|
||||
yield* browserSession
|
||||
|
||||
@@ -11,6 +11,17 @@ 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),
|
||||
@@ -91,6 +102,8 @@ describe("DesktopSettings", () => {
|
||||
assert.deepEqual(
|
||||
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
|
||||
{
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
@@ -116,6 +129,8 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
@@ -215,10 +230,13 @@ 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,
|
||||
@@ -232,6 +250,24 @@ 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* () {
|
||||
@@ -239,12 +275,15 @@ 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);
|
||||
}),
|
||||
@@ -261,6 +300,8 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
@@ -286,6 +327,8 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
@@ -310,6 +353,8 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 443,
|
||||
|
||||
@@ -20,6 +20,8 @@ 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;
|
||||
@@ -48,8 +50,25 @@ 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,
|
||||
@@ -60,7 +79,16 @@ 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),
|
||||
@@ -81,6 +109,8 @@ 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,
|
||||
@@ -114,6 +144,10 @@ 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>;
|
||||
@@ -158,11 +192,16 @@ 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 =
|
||||
@@ -177,6 +216,8 @@ 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,
|
||||
@@ -197,6 +238,12 @@ 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;
|
||||
}
|
||||
@@ -237,6 +284,22 @@ 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> },
|
||||
@@ -431,6 +494,18 @@ 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 } }),
|
||||
@@ -488,6 +563,8 @@ 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,6 +19,7 @@ const clientSettings: ClientSettings = {
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
favorites: [],
|
||||
glassOpacity: 80,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
|
||||
@@ -38,6 +38,7 @@ const flushCallbacks = Effect.yieldNow;
|
||||
function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
let checkCount = 0;
|
||||
let allowDowngrade = false;
|
||||
let fullChangelog = false;
|
||||
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
|
||||
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
|
||||
const sentStates: DesktopUpdateState[] = [];
|
||||
@@ -73,6 +74,10 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.sync(() => {
|
||||
fullChangelog = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
@@ -153,6 +158,7 @@ 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),
|
||||
@@ -186,6 +192,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
layer,
|
||||
checkCount: () => checkCount,
|
||||
feedUrls: () => feedUrls,
|
||||
fullChangelog: () => fullChangelog,
|
||||
listenerCount: () =>
|
||||
Array.from(listeners.values()).reduce(
|
||||
(total, eventListeners) => total + eventListeners.size,
|
||||
@@ -287,6 +294,49 @@ describe("DesktopUpdates", () => {
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("enables nightly full changelog release notes and broadcasts summaries", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
yield* updates.setChannel("nightly");
|
||||
assert.equal(harness.fullChangelog(), true);
|
||||
|
||||
harness.emit("update-available", {
|
||||
version: "1.2.4-nightly.20260709.766",
|
||||
releaseNotes: [
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.766",
|
||||
note: `<h2>What's Changed</h2><ul><li>feat(client): persist offline environment data by <a>@juliusmarminge</a> in <a>#3795</a></li></ul><h2>Full Changelog</h2>`,
|
||||
},
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.765",
|
||||
note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821",
|
||||
},
|
||||
],
|
||||
});
|
||||
yield* flushCallbacks;
|
||||
|
||||
const state = yield* updates.getState;
|
||||
assert.equal(state.status, "available");
|
||||
assert.deepEqual(state.releaseNotes, [
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.766",
|
||||
items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"],
|
||||
},
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.765",
|
||||
items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"],
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("keeps raw updater event failures out of update state", () => {
|
||||
const harness = makeHarness();
|
||||
const cause = new Error(
|
||||
|
||||
@@ -27,6 +27,7 @@ import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
@@ -49,6 +50,10 @@ type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
|
||||
|
||||
const UpdateInfo = Schema.Struct({
|
||||
version: Schema.String,
|
||||
// Left unvalidated on purpose: a malformed release-notes payload must never
|
||||
// fail the decode and block the update state transition. The shape is
|
||||
// validated defensively in normalizeDesktopUpdateReleaseNotes.
|
||||
releaseNotes: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const DownloadProgressInfo = Schema.Struct({
|
||||
@@ -330,10 +335,12 @@ export const make = Effect.gen(function* () {
|
||||
yield* electronUpdater.setChannel(channel);
|
||||
yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
|
||||
yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
|
||||
yield* electronUpdater.setFullChangelog(allowsPrerelease);
|
||||
yield* logUpdaterInfo("using update channel", {
|
||||
channel,
|
||||
allowPrerelease: allowsPrerelease,
|
||||
allowDowngrade: allowsPrerelease,
|
||||
fullChangelog: allowsPrerelease,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -567,11 +574,15 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const checkedAt = yield* currentIsoTimestamp;
|
||||
const releaseNotes = normalizeDesktopUpdateReleaseNotes(info.releaseNotes, info.version);
|
||||
yield* setState(
|
||||
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt),
|
||||
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt, releaseNotes),
|
||||
);
|
||||
yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
|
||||
yield* logUpdaterInfo("update available", { version: info.version });
|
||||
yield* logUpdaterInfo("update available", {
|
||||
version: info.version,
|
||||
releaseNoteGroups: releaseNotes.length,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
|
||||
|
||||
describe("normalizeDesktopUpdateReleaseNotes", () => {
|
||||
it("splits a plain string note into items under the fallback version", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
"## What's changed\n- First fix\n- Second fix",
|
||||
"1.2.3",
|
||||
);
|
||||
expect(notes).toEqual([{ version: "1.2.3", items: ["First fix", "Second fix"] }]);
|
||||
});
|
||||
|
||||
it("keeps per-version groups and drops empty ones", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
[
|
||||
{ version: "1.2.3", note: "- Newer change" },
|
||||
{ version: "1.2.2", note: "Full changelog: https://example.com/compare/x...y" },
|
||||
{ version: "1.2.1", note: "- Older change" },
|
||||
],
|
||||
"1.2.3",
|
||||
);
|
||||
expect(notes).toEqual([
|
||||
{ version: "1.2.3", items: ["Newer change"] },
|
||||
{ version: "1.2.1", items: ["Older change"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("decodes valid HTML entities", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes("- Fix & polish 😀", "1.0.0");
|
||||
expect(notes).toEqual([{ version: "1.0.0", items: ["Fix & polish 😀"] }]);
|
||||
});
|
||||
|
||||
it("ignores malformed entries instead of throwing", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
[
|
||||
{ version: "1.2.3", note: "- Valid change" },
|
||||
{ version: 42, note: "- Bad version type" },
|
||||
{ version: "1.2.1", note: { html: "<p>object note</p>" } },
|
||||
"not an object",
|
||||
null,
|
||||
],
|
||||
"1.2.3",
|
||||
);
|
||||
expect(notes).toEqual([{ version: "1.2.3", items: ["Valid change"] }]);
|
||||
});
|
||||
|
||||
it("returns non-empty groups even when preceded by many boilerplate-only groups", () => {
|
||||
const boilerplate = Array.from({ length: 7 }, (_, index) => ({
|
||||
version: `1.3.${9 - index}`,
|
||||
note: "Full changelog: https://example.com/compare/x...y",
|
||||
}));
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
[...boilerplate, { version: "1.3.2", note: "- Older but real change" }],
|
||||
"1.3.9",
|
||||
);
|
||||
expect(notes).toEqual([{ version: "1.3.2", items: ["Older but real change"] }]);
|
||||
});
|
||||
|
||||
it("does not throw on out-of-range numeric entities and keeps the literal", () => {
|
||||
expect(() =>
|
||||
normalizeDesktopUpdateReleaseNotes("- Broken entity �", "1.0.0"),
|
||||
).not.toThrow();
|
||||
const notes = normalizeDesktopUpdateReleaseNotes("- Broken entity �", "1.0.0");
|
||||
expect(notes).toEqual([{ version: "1.0.0", items: ["Broken entity �"] }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import type { DesktopUpdateReleaseNote } from "@t3tools/contracts";
|
||||
|
||||
interface ElectronReleaseNoteInfo {
|
||||
readonly version: string;
|
||||
readonly note: string | null | undefined;
|
||||
}
|
||||
|
||||
function isElectronReleaseNoteInfo(value: unknown): value is ElectronReleaseNoteInfo {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const candidate = value as { readonly version?: unknown; readonly note?: unknown };
|
||||
return (
|
||||
typeof candidate.version === "string" &&
|
||||
(typeof candidate.note === "string" || candidate.note === null || candidate.note === undefined)
|
||||
);
|
||||
}
|
||||
|
||||
const MAX_RELEASE_NOTE_GROUPS = 6;
|
||||
const MAX_RELEASE_NOTE_ITEMS_PER_GROUP = 8;
|
||||
const MAX_RELEASE_NOTE_ITEM_LENGTH = 220;
|
||||
|
||||
const HTML_ENTITY_REPLACEMENTS: Readonly<Record<string, string>> = {
|
||||
amp: "&",
|
||||
apos: "'",
|
||||
gt: ">",
|
||||
lt: "<",
|
||||
nbsp: " ",
|
||||
quot: '"',
|
||||
};
|
||||
|
||||
function decodeCodePoint(codePoint: number, entity: string): string {
|
||||
// String.fromCodePoint throws RangeError outside the valid Unicode range, and
|
||||
// Number.isFinite alone lets oversized values (e.g. �) through.
|
||||
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
|
||||
return `&${entity};`;
|
||||
}
|
||||
return String.fromCodePoint(codePoint);
|
||||
}
|
||||
|
||||
function decodeHtmlEntity(entity: string): string {
|
||||
const named = HTML_ENTITY_REPLACEMENTS[entity];
|
||||
if (named) return named;
|
||||
if (entity.startsWith("#x")) {
|
||||
return decodeCodePoint(Number.parseInt(entity.slice(2), 16), entity);
|
||||
}
|
||||
if (entity.startsWith("#")) {
|
||||
return decodeCodePoint(Number.parseInt(entity.slice(1), 10), entity);
|
||||
}
|
||||
return `&${entity};`;
|
||||
}
|
||||
|
||||
function decodeHtmlEntities(input: string): string {
|
||||
return input.replace(/&([a-zA-Z]+|#\d+|#x[0-9a-fA-F]+);/g, (_, entity: string) =>
|
||||
decodeHtmlEntity(entity),
|
||||
);
|
||||
}
|
||||
|
||||
function stripMarkup(input: string): string {
|
||||
return decodeHtmlEntities(
|
||||
input
|
||||
.replace(/<br\s*\/?>/gi, "\n")
|
||||
.replace(/<li\b[^>]*>/gi, "\n- ")
|
||||
.replace(/<\/(?:p|div|li|h[1-6]|ul|ol|blockquote)>/gi, "\n")
|
||||
.replace(/<[^>]*>/g, "")
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
|
||||
.replace(/\*\*([^*]+)\*\*/g, "$1"),
|
||||
);
|
||||
}
|
||||
|
||||
function truncateReleaseNoteItem(item: string): string {
|
||||
if (item.length <= MAX_RELEASE_NOTE_ITEM_LENGTH) return item;
|
||||
return `${item.slice(0, MAX_RELEASE_NOTE_ITEM_LENGTH - 3).trimEnd()}...`;
|
||||
}
|
||||
|
||||
function isIgnoredReleaseNoteLine(line: string): boolean {
|
||||
const normalized = line
|
||||
.toLowerCase()
|
||||
.replace(/[*_`#]/g, "")
|
||||
.trim();
|
||||
return (
|
||||
normalized === "" ||
|
||||
normalized === "what's changed" ||
|
||||
normalized === "whats changed" ||
|
||||
normalized === "full changelog" ||
|
||||
normalized === "new contributors" ||
|
||||
normalized.startsWith("compare: ") ||
|
||||
normalized.includes("/compare/")
|
||||
);
|
||||
}
|
||||
|
||||
function extractReleaseNoteItems(note: string | null | undefined): ReadonlyArray<string> {
|
||||
if (!note) return [];
|
||||
|
||||
const items: string[] = [];
|
||||
for (const rawLine of stripMarkup(note).split("\n")) {
|
||||
const item = rawLine
|
||||
.trim()
|
||||
.replace(/^[-*]\s+/, "")
|
||||
.replace(/^\d+[.)]\s+/, "")
|
||||
.replace(/\s+/g, " ");
|
||||
if (isIgnoredReleaseNoteLine(item)) continue;
|
||||
items.push(truncateReleaseNoteItem(item));
|
||||
if (items.length >= MAX_RELEASE_NOTE_ITEMS_PER_GROUP) break;
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
export function normalizeDesktopUpdateReleaseNotes(
|
||||
releaseNotes: unknown,
|
||||
fallbackVersion: string,
|
||||
): ReadonlyArray<DesktopUpdateReleaseNote> {
|
||||
const rawNotes =
|
||||
typeof releaseNotes === "string"
|
||||
? [{ version: fallbackVersion, note: releaseNotes }]
|
||||
: Array.isArray(releaseNotes)
|
||||
? releaseNotes.filter(isElectronReleaseNoteInfo)
|
||||
: [];
|
||||
|
||||
return rawNotes
|
||||
.map((entry) => ({
|
||||
version: entry.version,
|
||||
items: extractReleaseNoteItems(entry.note),
|
||||
}))
|
||||
.filter((entry) => entry.items.length > 0)
|
||||
.slice(0, MAX_RELEASE_NOTE_GROUPS);
|
||||
}
|
||||
@@ -118,6 +118,12 @@ describe("updateMachine", () => {
|
||||
});
|
||||
|
||||
it("tracks available, download start, and progress cleanly", () => {
|
||||
const releaseNotes = [
|
||||
{
|
||||
version: "1.1.0",
|
||||
items: ["feat: add update release notes"],
|
||||
},
|
||||
];
|
||||
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
@@ -126,15 +132,33 @@ describe("updateMachine", () => {
|
||||
},
|
||||
"1.1.0",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
releaseNotes,
|
||||
);
|
||||
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
|
||||
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||
|
||||
expect(available.status).toBe("available");
|
||||
expect(available.channel).toBe("latest");
|
||||
expect(available.releaseNotes).toBe(releaseNotes);
|
||||
expect(downloading.releaseNotes).toBe(releaseNotes);
|
||||
expect(downloading.status).toBe("downloading");
|
||||
expect(downloading.downloadPercent).toBe(0);
|
||||
expect(progress.downloadPercent).toBe(55.5);
|
||||
expect(progress.errorContext).toBeNull();
|
||||
});
|
||||
|
||||
it("clears release notes when checking again", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "nightly"),
|
||||
enabled: true,
|
||||
status: "available",
|
||||
availableVersion: "1.1.0-nightly.1",
|
||||
releaseNotes: [{ version: "1.1.0-nightly.1", items: ["feat: old note"] }],
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.releaseNotes).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
DesktopRuntimeInfo,
|
||||
DesktopUpdateChannel,
|
||||
DesktopUpdateReleaseNote,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
@@ -29,6 +30,7 @@ export function createInitialDesktopUpdateState(
|
||||
runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
@@ -45,6 +47,7 @@ export function reduceDesktopUpdateStateOnCheckStart(
|
||||
...state,
|
||||
status: "checking",
|
||||
checkedAt,
|
||||
releaseNotes: [],
|
||||
message: null,
|
||||
downloadPercent: null,
|
||||
errorContext: null,
|
||||
@@ -72,12 +75,14 @@ export function reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
checkedAt: string,
|
||||
releaseNotes: ReadonlyArray<DesktopUpdateReleaseNote> = [],
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "available",
|
||||
availableVersion: version,
|
||||
downloadedVersion: null,
|
||||
releaseNotes,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
@@ -95,6 +100,7 @@ export function reduceDesktopUpdateStateOnNoUpdate(
|
||||
status: "up-to-date",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
|
||||
@@ -76,6 +76,7 @@ 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,12 +1,17 @@
|
||||
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 type * as Electron from "electron";
|
||||
import * as Electron from "electron";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
vi.mock("electron", async (importOriginal) => ({
|
||||
@@ -18,17 +23,25 @@ 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";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
|
||||
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
@@ -46,6 +59,7 @@ const environmentInput = {
|
||||
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
|
||||
|
||||
function makeFakeBrowserWindow() {
|
||||
const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContents = {
|
||||
copyImageAt: vi.fn(),
|
||||
@@ -65,12 +79,21 @@ 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()),
|
||||
on: vi.fn(),
|
||||
once: vi.fn(),
|
||||
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);
|
||||
}),
|
||||
restore: vi.fn(),
|
||||
setBackgroundColor: vi.fn(),
|
||||
setAutoHideCursor: vi.fn(),
|
||||
@@ -82,12 +105,20 @@ 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,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
windowListeners,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -139,13 +170,57 @@ 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(() => {
|
||||
@@ -170,6 +245,7 @@ function makeTestLayer(input: {
|
||||
Layer.mergeAll(
|
||||
desktopAssetsLayer,
|
||||
desktopEnvironmentLayer,
|
||||
desktopAppSettingsLayer,
|
||||
desktopServerExposureLayer,
|
||||
DesktopState.layer,
|
||||
electronMenuLayer,
|
||||
@@ -267,6 +343,7 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
|
||||
Layer.mergeAll(
|
||||
desktopAssetsLayer,
|
||||
desktopEnvironmentLayer,
|
||||
DesktopAppSettings.layerTest(),
|
||||
desktopServerExposureLayer,
|
||||
electronMenuLayer,
|
||||
Layer.succeed(ElectronShell.ElectronShell, {
|
||||
@@ -289,6 +366,23 @@ 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({
|
||||
@@ -330,6 +424,10 @@ 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/"]);
|
||||
@@ -338,6 +436,458 @@ 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();
|
||||
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,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const enterFullscreen = fakeWindow.windowListeners.get("enter-full-screen");
|
||||
const leaveFullscreen = fakeWindow.windowListeners.get("leave-full-screen");
|
||||
if (!enterFullscreen || !leaveFullscreen) {
|
||||
return yield* Effect.die("fullscreen listeners were not registered");
|
||||
}
|
||||
|
||||
enterFullscreen();
|
||||
leaveFullscreen();
|
||||
assert.deepEqual(fakeWindow.send.mock.calls, [
|
||||
[WINDOW_FULLSCREEN_STATE_CHANNEL, true],
|
||||
[WINDOW_FULLSCREEN_STATE_CHANNEL, false],
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers when the development renderer is temporarily unreachable", () =>
|
||||
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 type * as Electron from "electron";
|
||||
import * as Electron from "electron";
|
||||
|
||||
import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
@@ -15,13 +15,15 @@ import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL } from "../ipc/channels.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
|
||||
@@ -41,6 +43,7 @@ type WindowTitleBarOptions = Pick<
|
||||
type DesktopWindowRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopAssets.DesktopAssets
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
| ElectronMenu.ElectronMenu
|
||||
| ElectronShell.ElectronShell
|
||||
| ElectronTheme.ElectronTheme
|
||||
@@ -75,6 +78,7 @@ 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>;
|
||||
}
|
||||
@@ -99,6 +103,45 @@ 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.
|
||||
@@ -202,6 +245,7 @@ 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
|
||||
@@ -214,6 +258,7 @@ 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());
|
||||
@@ -250,9 +295,31 @@ 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({
|
||||
width: 1100,
|
||||
height: 780,
|
||||
...initialBounds,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
@@ -274,6 +341,92 @@ 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) => {
|
||||
@@ -364,6 +517,22 @@ 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", () => {
|
||||
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
|
||||
});
|
||||
window.on("leave-full-screen", () => {
|
||||
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
|
||||
});
|
||||
}
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
@@ -463,6 +632,9 @@ 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));
|
||||
});
|
||||
|
||||
@@ -473,6 +645,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
window.on("closed", () => {
|
||||
clearDevelopmentLoadRetry();
|
||||
clearBoundsPersist();
|
||||
void runPromise(electronWindow.clearMain(Option.some(window)));
|
||||
});
|
||||
|
||||
@@ -589,6 +762,9 @@ 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;
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
formatNodePtyProbeFailureReason,
|
||||
formatWslShellTransportFailureReason,
|
||||
parseNodePath,
|
||||
parseNodeVersion,
|
||||
parseResolvedPath,
|
||||
parseToolchainReport,
|
||||
probeWslDistros,
|
||||
@@ -173,6 +174,29 @@ describe("parseNodePath", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseNodeVersion", () => {
|
||||
it("extracts the node version from a nodeVersion: line", () => {
|
||||
expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0");
|
||||
});
|
||||
|
||||
it("returns null when the version value is empty", () => {
|
||||
expect(parseNodeVersion("nodeVersion:")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when there is no nodeVersion line at all", () => {
|
||||
expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores surrounding noise and trims whitespace", () => {
|
||||
const stdout = [
|
||||
"some preamble noise",
|
||||
" nodeVersion:22.16.0 ",
|
||||
"nodePath:/usr/bin/node",
|
||||
].join("\n");
|
||||
expect(parseNodeVersion(stdout)).toBe("22.16.0");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseResolvedPath", () => {
|
||||
it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
|
||||
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
|
||||
|
||||
@@ -32,7 +32,11 @@ export interface EnsureWslNodePtyOptions {
|
||||
}
|
||||
|
||||
export type EnsureWslNodePtyResult =
|
||||
| { readonly ok: true; readonly nodePath: string; readonly resolvedPath: string }
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly nodePath: string;
|
||||
readonly resolvedPath: string;
|
||||
}
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly reason: string;
|
||||
@@ -222,6 +226,7 @@ export const formatNodePtyProbeFailureReason = (exitCode: number): string | null
|
||||
const NODE_PTY_PROBE_SCRIPT = (
|
||||
linuxServerDir: string,
|
||||
) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
|
||||
printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
|
||||
printf 'resolvedPath:%s\\n' "$PATH"
|
||||
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
|
||||
// The server bundle externalizes its deps to node_modules, and the WSL Node
|
||||
@@ -318,6 +323,16 @@ export const parseNodePath = (stdout: string): string | null => {
|
||||
return path ?? null;
|
||||
};
|
||||
|
||||
export const parseNodeVersion = (stdout: string): string | null => {
|
||||
const version = stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.startsWith("nodeVersion:"))
|
||||
.map((line) => line.slice("nodeVersion:".length).trim())
|
||||
.find((value) => value.length > 0);
|
||||
return version ?? null;
|
||||
};
|
||||
|
||||
// Captures the login-shell PATH after the shared resolver has loaded version
|
||||
// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
|
||||
// paths containing spaces or apostrophes can be forwarded as one env argv.
|
||||
@@ -404,7 +419,11 @@ const ensureNodePtyImpl = (
|
||||
|
||||
const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
|
||||
if (transportFailureReason !== null) {
|
||||
return { ok: false, reason: transportFailureReason, fatal: false } as const;
|
||||
return {
|
||||
ok: false,
|
||||
reason: transportFailureReason,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
// No node at all, even after the shared resolver repaired PATH. Surface
|
||||
@@ -457,12 +476,31 @@ const ensureNodePtyImpl = (
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (probe.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
|
||||
if (probe.exitCode === 0) {
|
||||
const rawVersion = parseNodeVersion(probe.stdout);
|
||||
if (
|
||||
rawVersion !== null &&
|
||||
options.nodeEngineRange &&
|
||||
!satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
|
||||
) {
|
||||
const range = options.nodeEngineRange.trim();
|
||||
return {
|
||||
ok: false,
|
||||
reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
return { ok: true, nodePath, resolvedPath } as const;
|
||||
}
|
||||
|
||||
if (options.allowBuild !== true) {
|
||||
const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
|
||||
if (packagedProbeFailure !== null) {
|
||||
return { ok: false, reason: packagedProbeFailure, fatal: true } as const;
|
||||
return {
|
||||
ok: false,
|
||||
reason: packagedProbeFailure,
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"astro": "^7.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1 +1 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>
|
||||
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" fill="#EDECEC" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 649 B After Width: | Height: | Size: 665 B |
@@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path fill="#F5F5F5" d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861" />
|
||||
<path fill="#F5F5F5" d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 948 B |
@@ -1,6 +1,6 @@
|
||||
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
|
||||
|
||||
export const MARKETING_STATS = {
|
||||
githubStars: "12k+",
|
||||
githubStars: "14k+",
|
||||
users: "100,000",
|
||||
} as const;
|
||||
@@ -33,6 +33,9 @@ const mobileEndorsementRows = [
|
||||
<span class="hero-float-mark hf-cursor" title="Cursor">
|
||||
<img src="/harnesses/cursor_light.svg" alt="" />
|
||||
</span>
|
||||
<span class="hero-float-mark hf-grok" title="Grok">
|
||||
<img src="/harnesses/grok-dark.svg" alt="" />
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="container hero-inner">
|
||||
@@ -41,7 +44,7 @@ const mobileEndorsementRows = [
|
||||
</h1>
|
||||
|
||||
<p class="hero-sub">
|
||||
Orchestrate Claude Code, Codex, OpenCode and Cursor from one surface.
|
||||
Orchestrate Claude Code, Codex, OpenCode, Cursor, and Grok from one surface.
|
||||
Bring your own subscription. Fork the whole thing.
|
||||
</p>
|
||||
|
||||
@@ -173,7 +176,7 @@ const mobileEndorsementRows = [
|
||||
<h2>Bring your own sub</h2>
|
||||
<p>
|
||||
T3 Code doesn't resell tokens. Plug in Claude Code, Codex, OpenCode,
|
||||
or Cursor with the credentials you already have — we orchestrate
|
||||
Cursor, or Grok with the credentials you already have — we orchestrate
|
||||
them, you keep your plan.
|
||||
</p>
|
||||
</div>
|
||||
@@ -207,6 +210,13 @@ const mobileEndorsementRows = [
|
||||
<div class="harness-tag">cursor-agent</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="harness">
|
||||
<div class="harness-mark"><img src="/harnesses/grok-dark.svg" alt="" /></div>
|
||||
<div class="harness-meta">
|
||||
<div class="harness-name">Grok CLI</div>
|
||||
<div class="harness-tag">grok login</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="harness-footer">
|
||||
@@ -615,8 +625,9 @@ const mobileEndorsementRows = [
|
||||
|
||||
.hero-float-mark.hf-claude { background: radial-gradient(circle at 30% 25%, rgba(217, 119, 87, 0.22), rgba(20, 20, 24, 0.92) 65%); top: 8%; left: 7%; animation-delay: 0s; transform: rotate(-8deg); }
|
||||
.hero-float-mark.hf-codex { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 6%; right: 7%; animation-delay: -2.5s; transform: rotate(6deg); }
|
||||
.hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 32%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }
|
||||
.hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 30%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }
|
||||
.hero-float-mark.hf-cursor { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 30%; right: 5%; animation-delay: -7s; transform: rotate(-5deg); }
|
||||
.hero-float-mark.hf-grok { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 52%; left: 6%; animation-delay: -1.2s; transform: rotate(3deg); }
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
.hero-float-mark { width: 76px; height: 76px; border-radius: 20px; }
|
||||
@@ -625,6 +636,7 @@ const mobileEndorsementRows = [
|
||||
.hero-float-mark.hf-codex { top: 2%; right: 3%; }
|
||||
.hero-float-mark.hf-opencode { top: 26%; left: 2%; }
|
||||
.hero-float-mark.hf-cursor { top: 24%; right: 2%; }
|
||||
.hero-float-mark.hf-grok { top: 48%; left: 2%; transform: rotate(3deg); }
|
||||
}
|
||||
|
||||
@media (max-width: 820px) {
|
||||
@@ -659,17 +671,18 @@ const mobileEndorsementRows = [
|
||||
height: 44px;
|
||||
}
|
||||
|
||||
/* Two above the title, two flanking the call-to-action area. */
|
||||
/* Three stacked on the left, two on the right — keeps the center CTA clear. */
|
||||
.hero-float-mark.hf-claude {
|
||||
top: 44px;
|
||||
left: 10px;
|
||||
transform: rotate(-10deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-codex {
|
||||
top: 44px;
|
||||
right: 10px;
|
||||
transform: rotate(8deg);
|
||||
.hero-float-mark.hf-grok {
|
||||
top: 240px;
|
||||
left: 4px;
|
||||
right: auto;
|
||||
transform: rotate(-4deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-opencode {
|
||||
@@ -679,6 +692,12 @@ const mobileEndorsementRows = [
|
||||
transform: rotate(-6deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-codex {
|
||||
top: 44px;
|
||||
right: 10px;
|
||||
transform: rotate(8deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-cursor {
|
||||
top: 474px;
|
||||
right: 4px;
|
||||
@@ -688,6 +707,14 @@ const mobileEndorsementRows = [
|
||||
}
|
||||
|
||||
@media (max-width: 340px) {
|
||||
.hero-float-mark.hf-grok {
|
||||
top: 220px;
|
||||
left: 0;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-opencode,
|
||||
.hero-float-mark.hf-cursor {
|
||||
top: 580px;
|
||||
@@ -704,6 +731,7 @@ const mobileEndorsementRows = [
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-grok img,
|
||||
.hero-float-mark.hf-opencode img,
|
||||
.hero-float-mark.hf-cursor img {
|
||||
width: 30px;
|
||||
@@ -750,7 +778,7 @@ const mobileEndorsementRows = [
|
||||
|
||||
.harness-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
grid-template-columns: repeat(5, 1fr);
|
||||
gap: 0;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
@@ -1205,6 +1233,10 @@ const mobileEndorsementRows = [
|
||||
.harness-grid { grid-template-columns: 1fr 1fr; }
|
||||
.harness { border-right: 0; border-bottom: 1px solid var(--border); }
|
||||
.harness:nth-child(odd) { border-right: 1px solid var(--border); }
|
||||
.harness:nth-child(5):last-child {
|
||||
grid-column: 1 / -1;
|
||||
border-right: 0;
|
||||
}
|
||||
.git-inner { grid-template-columns: 1fr; gap: 40px; }
|
||||
.open-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
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",
|
||||
};
|
||||
@@ -35,8 +35,8 @@ vp run ios:dev
|
||||
```
|
||||
|
||||
If your Xcode account only has a Personal Team, use a bundle identifier you control and opt into the
|
||||
reduced-capability local build. Personal Team builds omit the widget extension, push entitlement, and
|
||||
native Sign in with Apple entitlement; builds without this opt-in are unchanged.
|
||||
reduced-capability local build. Personal Team builds omit the widget and share extensions, push
|
||||
entitlement, and native Sign in with Apple entitlement; builds without this opt-in are unchanged.
|
||||
|
||||
```bash
|
||||
T3CODE_IOS_PERSONAL_TEAM=1 \
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ExpoConfig } from "expo/config";
|
||||
|
||||
import { BRAND_ASSET_PATHS } from "../../scripts/lib/brand-assets.ts";
|
||||
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
|
||||
|
||||
type AppVariant = "development" | "preview" | "production";
|
||||
@@ -13,6 +14,8 @@ const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
|
||||
const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim();
|
||||
const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
|
||||
|
||||
const fromRepoRoot = (relativePath: string) => `../../${relativePath}`;
|
||||
|
||||
if (
|
||||
isIosPersonalTeamBuild &&
|
||||
(!personalTeamBundleIdentifier ||
|
||||
@@ -24,20 +27,31 @@ if (
|
||||
}
|
||||
|
||||
const DEVELOPMENT_ASSETS = {
|
||||
appIcon: "./assets/splash-icon-dev.png",
|
||||
iosIcon: "./assets/icon-composer-dev.icon",
|
||||
splashIcon: "./assets/splash-icon-dev.png",
|
||||
androidAdaptiveForeground: "./assets/android-icon-dev-foreground.png",
|
||||
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
|
||||
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIconComposerProject),
|
||||
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
|
||||
androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.developmentUniversalIconPng),
|
||||
androidAdaptiveBackgroundColor: "#00639B",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
androidNotificationIcon: "./assets/android-notification-icon.png",
|
||||
androidNotificationColor: "#00639B",
|
||||
} as const;
|
||||
|
||||
const PREVIEW_ASSETS = {
|
||||
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
|
||||
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIconComposerProject),
|
||||
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
|
||||
androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.nightlyLinuxIconPng),
|
||||
androidAdaptiveBackgroundColor: "#111533",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
androidNotificationIcon: "./assets/android-notification-icon.png",
|
||||
androidNotificationColor: "#7565C7",
|
||||
} as const;
|
||||
|
||||
const RELEASE_ASSETS = {
|
||||
appIcon: "./assets/splash-icon-prod.png",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
|
||||
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIconComposerProject),
|
||||
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
|
||||
androidAdaptiveForeground: "./assets/android-icon-mark.png",
|
||||
androidAdaptiveBackgroundColor: "#000000",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
@@ -60,7 +74,7 @@ const VARIANT_CONFIG = {
|
||||
iosBundleIdentifier: "com.t3tools.t3code.preview",
|
||||
androidPackage: "com.t3tools.t3code.preview",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
assets: RELEASE_ASSETS,
|
||||
assets: PREVIEW_ASSETS,
|
||||
},
|
||||
production: {
|
||||
appName: "T3 Code",
|
||||
@@ -84,6 +98,9 @@ function resolveAppVariant(value: string | undefined): AppVariant {
|
||||
}
|
||||
|
||||
const variant = VARIANT_CONFIG[APP_VARIANT];
|
||||
const iosBundleIdentifier = isIosPersonalTeamBuild
|
||||
? personalTeamBundleIdentifier!
|
||||
: variant.iosBundleIdentifier;
|
||||
|
||||
const dmSansFonts = {
|
||||
regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf",
|
||||
@@ -94,8 +111,8 @@ const dmSansFonts = {
|
||||
const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
"expo-widgets",
|
||||
{
|
||||
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
|
||||
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
|
||||
bundleIdentifier: `${iosBundleIdentifier}.widgets`,
|
||||
groupIdentifier: `group.${iosBundleIdentifier}`,
|
||||
enablePushNotifications: true,
|
||||
// Agent activity can update many times an hour; without the
|
||||
// frequent-updates entitlement iOS throttles the update budget sooner.
|
||||
@@ -111,6 +128,30 @@ const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
},
|
||||
];
|
||||
|
||||
const sharingPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
"expo-sharing",
|
||||
{
|
||||
ios: {
|
||||
// Personal Teams cannot sign App Groups or extension targets. Keep the
|
||||
// reduced-capability local build usable while release builds expose the
|
||||
// real system share target.
|
||||
enabled: !isIosPersonalTeamBuild,
|
||||
extensionBundleIdentifier: `${iosBundleIdentifier}.sharing`,
|
||||
appGroupId: `group.${iosBundleIdentifier}`,
|
||||
activationRule: {
|
||||
supportsText: true,
|
||||
supportsWebUrlWithMaxCount: 1,
|
||||
supportsImageWithMaxCount: 8,
|
||||
},
|
||||
},
|
||||
android: {
|
||||
enabled: true,
|
||||
singleShareMimeTypes: ["text/plain", "image/*"],
|
||||
multipleShareMimeTypes: ["image/*"],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// These aliases match the fonts' PostScript names on iOS. Register the same
|
||||
// names on Android so React Native and the native composer use one set of
|
||||
// family names without waiting for runtime font loading.
|
||||
@@ -140,7 +181,7 @@ const config: ExpoConfig = {
|
||||
ios: {
|
||||
icon: variant.assets.iosIcon,
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: variant.iosBundleIdentifier,
|
||||
bundleIdentifier: iosBundleIdentifier,
|
||||
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
|
||||
// does not fall back to a personal team (which cannot sign app groups,
|
||||
// Sign in with Apple, or push notification entitlements).
|
||||
@@ -202,6 +243,9 @@ const config: ExpoConfig = {
|
||||
],
|
||||
"expo-secure-store",
|
||||
"expo-sqlite",
|
||||
...(isIosPersonalTeamBuild
|
||||
? [sharingPlugin]
|
||||
: ["./plugins/withShareExtensionDisplayName.cjs", sharingPlugin]),
|
||||
[
|
||||
"expo-notifications",
|
||||
{
|
||||
|
||||
|
Before Width: | Height: | Size: 323 KiB |
|
Before Width: | Height: | Size: 10 MiB |
|
Before Width: | Height: | Size: 1.7 MiB |
@@ -1,3 +0,0 @@
|
||||
<svg width="77" height="47" viewBox="0 0 77 47" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M14.56 45.5V8.58H1.69082e-06V-3.09944e-06H39.65V8.58H25.09V45.5H14.56ZM57.8454 46.28C54.6821 46.28 51.5404 45.8683 48.4204 45.045C45.3004 44.1783 42.6571 42.965 40.4904 41.405L44.5854 33.345C46.3188 34.6017 48.3338 35.5983 50.6304 36.335C52.9271 37.0717 55.2454 37.44 57.5854 37.44C60.2288 37.44 62.3088 36.92 63.8254 35.88C65.3421 34.84 66.1004 33.41 66.1004 31.59C66.1004 29.8567 65.4288 28.4917 64.0854 27.495C62.7421 26.4983 60.5754 26 57.5854 26H52.7754V19.045L65.4504 4.68L66.6204 8.45H42.7654V-3.09944e-06H74.6154V6.825L62.0054 21.19L56.6754 18.135H59.7304C65.3204 18.135 69.5454 19.3917 72.4054 21.905C75.2654 24.4183 76.6954 27.6467 76.6954 31.59C76.6954 34.1467 76.0238 36.5517 74.6804 38.805C73.3371 41.015 71.2788 42.8133 68.5054 44.2C65.7321 45.5867 62.1788 46.28 57.8454 46.28Z" fill="white"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 920 B |
|
Before Width: | Height: | Size: 2.0 MiB |
|
Before Width: | Height: | Size: 302 KiB |
@@ -1,5 +1,6 @@
|
||||
import { registerRootComponent } from "expo";
|
||||
import "react-native-gesture-handler";
|
||||
import { LogBox } from "react-native";
|
||||
import { featureFlags } from "react-native-screens";
|
||||
|
||||
import App from "./src/App";
|
||||
@@ -8,4 +9,8 @@ import App from "./src/App";
|
||||
// native stack is rendered inside a non-fitToContents formSheet.
|
||||
featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
|
||||
|
||||
if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
|
||||
LogBox.ignoreAllLogs();
|
||||
}
|
||||
|
||||
registerRootComponent(App);
|
||||
@@ -7,6 +7,32 @@ class T3NativeControlsModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("T3NativeControls")
|
||||
|
||||
Function("getShowcasePairingUrl") {
|
||||
appContext.currentActivity?.intent?.getStringExtra("showcasePairingUrl")
|
||||
}
|
||||
|
||||
Function("getShowcaseScene") {
|
||||
val storedScene = appContext.reactContext
|
||||
?.filesDir
|
||||
?.resolve("t3-showcase-scene")
|
||||
?.takeIf { it.isFile }
|
||||
?.readText()
|
||||
?.trim()
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
storedScene ?: appContext.currentActivity?.intent?.getStringExtra("showcaseScene")
|
||||
}
|
||||
|
||||
Function("prepareShowcaseCapture") {
|
||||
// Android app data is cleared by the host runner before launch.
|
||||
}
|
||||
|
||||
Function("markShowcaseReady") { scene: String ->
|
||||
appContext.reactContext
|
||||
?.filesDir
|
||||
?.resolve("t3-showcase-ready")
|
||||
?.writeText(scene)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView::class) {
|
||||
Prop("label") { view: T3HeaderButtonView, label: String ->
|
||||
view.setLabel(label)
|
||||
|
||||
@@ -1,9 +1,48 @@
|
||||
import ExpoModulesCore
|
||||
import Security
|
||||
|
||||
public final class T3NativeControlsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3NativeControls")
|
||||
|
||||
Function("getShowcasePairingUrl") {
|
||||
let arguments = ProcessInfo.processInfo.arguments
|
||||
guard
|
||||
let flagIndex = arguments.firstIndex(of: "--showcasePairingUrl"),
|
||||
arguments.indices.contains(flagIndex + 1)
|
||||
else {
|
||||
return nil as String?
|
||||
}
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
Function("getShowcaseScene") { () -> String? in
|
||||
let scenePath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseScene"
|
||||
if let storedScene = try? String(contentsOfFile: scenePath, encoding: .utf8)
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines), !storedScene.isEmpty {
|
||||
return storedScene
|
||||
}
|
||||
let arguments = ProcessInfo.processInfo.arguments
|
||||
guard
|
||||
let flagIndex = arguments.firstIndex(of: "--showcaseScene"),
|
||||
arguments.indices.contains(flagIndex + 1)
|
||||
else {
|
||||
return nil as String?
|
||||
}
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
Function("prepareShowcaseCapture") {
|
||||
for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
|
||||
SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
|
||||
}
|
||||
}
|
||||
|
||||
Function("markShowcaseReady") { (scene: String) in
|
||||
let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
|
||||
try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView.self) {
|
||||
Prop("label") { (view: T3HeaderButtonView, label: String) in
|
||||
view.setLabel(label)
|
||||
|
||||
@@ -30,6 +30,10 @@ class T3TerminalModule : Module() {
|
||||
view.focusRequest = focusRequest
|
||||
}
|
||||
|
||||
Prop("autoFocus") { view: T3TerminalView, autoFocus: Boolean ->
|
||||
view.autoFocus = autoFocus
|
||||
}
|
||||
|
||||
Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String ->
|
||||
view.appearanceScheme = appearanceScheme
|
||||
}
|
||||
|
||||
@@ -76,6 +76,17 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
|
||||
}
|
||||
}
|
||||
|
||||
var autoFocus: Boolean = true
|
||||
set(value) {
|
||||
field = value
|
||||
if (value) {
|
||||
requestKeyboardFocus()
|
||||
} else {
|
||||
inputView.clearFocus()
|
||||
hideKeyboard()
|
||||
}
|
||||
}
|
||||
|
||||
var backgroundColorHex: String = "#24292E"
|
||||
set(value) {
|
||||
field = value
|
||||
@@ -368,6 +379,13 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
|
||||
inputMethodManager?.showSoftInput(inputView, InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
|
||||
private fun hideKeyboard() {
|
||||
val inputMethodManager = context.getSystemService(
|
||||
Context.INPUT_METHOD_SERVICE
|
||||
) as? InputMethodManager
|
||||
inputMethodManager?.hideSoftInputFromWindow(windowToken, 0)
|
||||
}
|
||||
|
||||
private fun applyTheme() {
|
||||
setBackgroundColor(backgroundColorValue)
|
||||
container.setBackgroundColor(backgroundColorValue)
|
||||
|
||||
@@ -7,7 +7,7 @@ public class T3TerminalModule: Module {
|
||||
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
|
||||
// logs so a stale native binary is distinguishable from a broken key pipeline.
|
||||
Constants([
|
||||
"hardwareKeyRevision": 2,
|
||||
"hardwareKeyRevision": 3,
|
||||
])
|
||||
|
||||
View(T3TerminalView.self) {
|
||||
@@ -27,6 +27,10 @@ public class T3TerminalModule: Module {
|
||||
view.focusRequest = focusRequest
|
||||
}
|
||||
|
||||
Prop("autoFocus") { (view: T3TerminalView, autoFocus: Bool) in
|
||||
view.autoFocus = autoFocus
|
||||
}
|
||||
|
||||
Prop("appearanceScheme") { (view: T3TerminalView, appearanceScheme: String) in
|
||||
view.appearanceScheme = appearanceScheme
|
||||
}
|
||||
|
||||
@@ -119,6 +119,21 @@ private enum TerminalHardwareKeyEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
private enum TerminalInputSequence {
|
||||
/// Terminal Enter is carriage return. Sending line feed instead is Ctrl+J,
|
||||
/// which raw-mode TUIs may interpret as the literal J key.
|
||||
static let carriageReturn = "\r"
|
||||
|
||||
static func normalizingReturn(_ input: String) -> String {
|
||||
switch input {
|
||||
case "\n", "\r\n":
|
||||
return carriageReturn
|
||||
default:
|
||||
return input
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class TerminalInputField: UITextField {
|
||||
var onDeleteBackward: (() -> Void)?
|
||||
var onInsert: ((String) -> Void)?
|
||||
@@ -233,6 +248,17 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
var autoFocus = true {
|
||||
didSet {
|
||||
guard oldValue != autoFocus else { return }
|
||||
if autoFocus {
|
||||
requestKeyboardFocus()
|
||||
} else {
|
||||
inputField.resignFirstResponder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
|
||||
didSet {
|
||||
guard oldValue != appearanceScheme else { return }
|
||||
@@ -344,7 +370,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
public override func didMoveToWindow() {
|
||||
super.didMoveToWindow()
|
||||
|
||||
guard window != nil else { return }
|
||||
guard window != nil, autoFocus else { return }
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.requestKeyboardFocus()
|
||||
}
|
||||
@@ -352,7 +378,9 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
|
||||
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
|
||||
if !string.isEmpty {
|
||||
emitInput(string)
|
||||
// Some software keyboards deliver Return through this delegate instead of
|
||||
// textFieldShouldReturn, so normalize that path too.
|
||||
emitInput(TerminalInputSequence.normalizingReturn(string))
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -360,7 +388,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
}
|
||||
|
||||
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
|
||||
emitInput("\n")
|
||||
emitInput(TerminalInputSequence.carriageReturn)
|
||||
textField.text = ""
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
"start:dev": "APP_VARIANT=development expo start",
|
||||
"start:preview": "APP_VARIANT=preview expo start",
|
||||
"start:prod": "APP_VARIANT=production expo start",
|
||||
"showcase": "APP_VARIANT=development EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code-dev --clear",
|
||||
"screenshots": "node ../../scripts/mobile-showcase.ts",
|
||||
"android": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
|
||||
"android:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && REACT_NATIVE_PACKAGER_HOSTNAME=localhost expo run:android",
|
||||
"android:preview": "APP_VARIANT=preview EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
|
||||
@@ -91,6 +93,7 @@
|
||||
"expo-paste-input": "^0.1.15",
|
||||
"expo-quick-actions": "^6.0.2",
|
||||
"expo-secure-store": "~56.0.4",
|
||||
"expo-sharing": "~56.0.18",
|
||||
"expo-splash-screen": "~56.0.10",
|
||||
"expo-sqlite": "~56.0.5",
|
||||
"expo-symbols": "~56.0.6",
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"use strict";
|
||||
|
||||
// expo-sharing intentionally uses a fixed target name and also uses that
|
||||
// internal target name as CFBundleDisplayName. Brand the extension while
|
||||
// leaving its initially-empty signing team intact: Expo uses that state to
|
||||
// select ios.appleTeamId and enable first-time profile provisioning.
|
||||
//
|
||||
// ORDERING: list this plugin BEFORE expo-sharing. Expo runs same-type mods in
|
||||
// reverse registration order, so this executes after the extension exists.
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { withDangerousMod, withXcodeProject } = require("expo/config-plugins");
|
||||
|
||||
const TARGET_NAME = "expo-sharing-extension";
|
||||
|
||||
function stripComments(section) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(section ?? {}).filter(([key]) => !key.endsWith("_comment")),
|
||||
);
|
||||
}
|
||||
|
||||
function findByName(section, name) {
|
||||
return Object.entries(stripComments(section)).find(([, value]) => value?.name === name) ?? null;
|
||||
}
|
||||
|
||||
function escapeXml(value) {
|
||||
return value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
}
|
||||
|
||||
function withDisplayNamePlist(config, displayName) {
|
||||
return withDangerousMod(config, [
|
||||
"ios",
|
||||
(cfg) => {
|
||||
const plistPath = path.join(cfg.modRequest.platformProjectRoot, TARGET_NAME, "Info.plist");
|
||||
if (!fs.existsSync(plistPath)) {
|
||||
throw new Error(
|
||||
`${TARGET_NAME}/Info.plist was not generated. Register withShareExtensionDisplayName before expo-sharing.`,
|
||||
);
|
||||
}
|
||||
const source = fs.readFileSync(plistPath, "utf8");
|
||||
const displayNamePattern = /(<key>CFBundleDisplayName<\/key>\s*<string>)[^<]*(<\/string>)/;
|
||||
if (!displayNamePattern.test(source)) {
|
||||
throw new Error(`Could not update CFBundleDisplayName in ${plistPath}.`);
|
||||
}
|
||||
const next = source.replace(displayNamePattern, `$1${escapeXml(displayName)}$2`);
|
||||
if (next !== source) {
|
||||
fs.writeFileSync(plistPath, next);
|
||||
}
|
||||
return cfg;
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function withExtensionDisplayNameBuildSetting(config, displayName) {
|
||||
return withXcodeProject(config, (cfg) => {
|
||||
const objects = cfg.modResults.hash.project.objects;
|
||||
const targetEntry = findByName(objects.PBXNativeTarget, TARGET_NAME);
|
||||
if (!targetEntry) {
|
||||
throw new Error(
|
||||
`${TARGET_NAME} Xcode target was not generated. Register withShareExtensionDisplayName before expo-sharing.`,
|
||||
);
|
||||
}
|
||||
const target = targetEntry[1];
|
||||
const configurationList = stripComments(objects.XCConfigurationList)[
|
||||
target.buildConfigurationList
|
||||
];
|
||||
if (!configurationList) {
|
||||
throw new Error(`Could not find build configurations for ${TARGET_NAME}.`);
|
||||
}
|
||||
const buildConfigurations = stripComments(objects.XCBuildConfiguration);
|
||||
for (const reference of configurationList.buildConfigurations ?? []) {
|
||||
const buildConfiguration = buildConfigurations[reference.value];
|
||||
if (buildConfiguration?.buildSettings) {
|
||||
buildConfiguration.buildSettings.INFOPLIST_KEY_CFBundleDisplayName = `"${displayName}"`;
|
||||
}
|
||||
}
|
||||
return cfg;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = function withShareExtensionDisplayName(config) {
|
||||
const displayName = config.name;
|
||||
return withExtensionDisplayNameBuildSetting(
|
||||
withDisplayNamePlist(config, displayName),
|
||||
displayName,
|
||||
);
|
||||
};
|
||||
@@ -11,7 +11,12 @@ import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigati
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { ConfirmDialogHost } from "./components/ConfirmDialogHost";
|
||||
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
|
||||
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
|
||||
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
|
||||
import {
|
||||
AppearancePreferencesProvider,
|
||||
useAppearancePreferences,
|
||||
} from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { RootStack } from "./Stack";
|
||||
import { appAtomRegistry } from "./state/atom-registry";
|
||||
import { OverlayPortalHost } from "./components/OverlayPortal";
|
||||
@@ -20,29 +25,47 @@ import { useThemeColor } from "./lib/useThemeColor";
|
||||
|
||||
import "../global.css";
|
||||
|
||||
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
|
||||
// <scheme>://expo-development-client/?url=<packager> — that URL addresses
|
||||
// the launcher, not app navigation. Without this filter it falls through
|
||||
// to the NotFound wildcard route on every dev launch.
|
||||
filter: (url: string) => !url.includes("expo-development-client"),
|
||||
// expo-sharing uses a private lifecycle URL only to wake the app. The
|
||||
// persisted share inbox below owns navigation once the payload is durable.
|
||||
filter: (url: string) =>
|
||||
!url.includes("expo-development-client") && !url.includes("://expo-sharing"),
|
||||
};
|
||||
|
||||
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>
|
||||
@@ -58,10 +81,12 @@ export default function App() {
|
||||
the system is in dark mode. */}
|
||||
{/* Blur target for Android dropdown backdrops — see appBlurTarget.ts. */}
|
||||
<BlurTargetView ref={appBlurTargetRef} style={{ flex: 1 }}>
|
||||
<Navigation
|
||||
linking={appLinking}
|
||||
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
|
||||
/>
|
||||
<IncomingShareProvider>
|
||||
<Navigation
|
||||
linking={appLinking}
|
||||
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
|
||||
/>
|
||||
</IncomingShareProvider>
|
||||
<ConfirmDialogHost />
|
||||
</BlurTargetView>
|
||||
{/* Anchored-menu overlays render here — in-window, so the
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
createNativeStackScreen,
|
||||
type NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
@@ -47,11 +48,18 @@ import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnv
|
||||
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
|
||||
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
|
||||
import {
|
||||
SettingsLegalDocumentCloseHeaderButton,
|
||||
SettingsLegalDocumentExternalHeaderButton,
|
||||
} from "./features/settings/components/SettingsLegalDocumentRouteScreen";
|
||||
import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts";
|
||||
import { useIncomingShare } from "./features/sharing/IncomingShareProvider";
|
||||
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";
|
||||
|
||||
@@ -71,19 +79,24 @@ 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, with the iOS 26
|
||||
// scroll-edge blur sampling the content (Home, Thread, Files tree, settings sheet).
|
||||
// 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.
|
||||
const GLASS_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerBackTitle: "",
|
||||
headerLargeTitle: false,
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,
|
||||
headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED
|
||||
? { backgroundColor: "transparent" }
|
||||
: SHEET_BACKGROUND_COLOR !== undefined
|
||||
? { backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
|
||||
: undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: Platform.OS === "ios",
|
||||
scrollEdgeEffects: Platform.OS === "ios" ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
|
||||
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
|
||||
headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
|
||||
scrollEdgeEffects: NATIVE_LIQUID_GLASS_SUPPORTED ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
|
||||
unstable_navigationItemStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? "editor" : undefined,
|
||||
};
|
||||
|
||||
// SOLID: opaque sheet-colored header for surfaces whose content scrolls internally
|
||||
@@ -275,12 +288,30 @@ function RootStackLayout(props: {
|
||||
readonly children: React.ReactNode;
|
||||
readonly state: NavigationState;
|
||||
}) {
|
||||
const navigation = useNavigation();
|
||||
const { pendingShare } = useIncomingShare();
|
||||
const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
|
||||
useAgentNotificationNavigation();
|
||||
useThreadOutboxDrain();
|
||||
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
|
||||
useConnectOnboardingNavigation();
|
||||
// Launcher app shortcuts: routes shortcut taps and tracks opened threads.
|
||||
useAppShortcuts(props.state);
|
||||
useEffect(() => {
|
||||
const topRouteName = props.state.routes[props.state.index]?.name;
|
||||
const transition = transitionIncomingSharePresentation(sharePresentationRef.current, {
|
||||
isShareSheetPresented: topRouteName === "NewTaskSheet",
|
||||
pendingShareId: pendingShare?.id ?? null,
|
||||
});
|
||||
sharePresentationRef.current = transition.state;
|
||||
if (!transition.shareIdToPresent) {
|
||||
return;
|
||||
}
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTask",
|
||||
params: { incomingShareId: transition.shareIdToPresent },
|
||||
});
|
||||
}, [navigation, pendingShare, props.state]);
|
||||
// Full pathname (sheets included) for keyboard-command scoping; the
|
||||
// workspace layout only reacts to the underlying non-overlay route.
|
||||
const path = getPathFromState(props.state, navigationPathConfig);
|
||||
@@ -289,6 +320,7 @@ function RootStackLayout(props: {
|
||||
|
||||
return (
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
|
||||
@@ -1,13 +1,23 @@
|
||||
import { Image, View } from "react-native";
|
||||
import Constants from "expo-constants";
|
||||
import { Image } from "expo-image";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "./AppText";
|
||||
|
||||
const BRAND_MARK_SOURCE = require("../../../../assets/dev/blueprint-ios-1024.png");
|
||||
const appVariant = Constants.expoConfig?.extra?.appVariant;
|
||||
const BRAND_MARK_SOURCE =
|
||||
appVariant === "development"
|
||||
? require("../../../../assets/dev/blueprint-ios-1024.png")
|
||||
: appVariant === "preview"
|
||||
? require("../../../../assets/nightly/nightly-ios-1024.png")
|
||||
: require("../../../../assets/prod/black-ios-1024.png");
|
||||
const DEFAULT_STAGE_LABEL =
|
||||
appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Alpha";
|
||||
|
||||
export function BrandMark(props: { readonly compact?: boolean; readonly stageLabel?: string }) {
|
||||
const compact = props.compact ?? false;
|
||||
const iconSize = compact ? 32 : 44;
|
||||
const stageLabel = props.stageLabel ?? "Alpha";
|
||||
const stageLabel = props.stageLabel ?? DEFAULT_STAGE_LABEL;
|
||||
|
||||
return (
|
||||
<View className="flex-row items-center gap-3">
|
||||
|
||||
@@ -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 || state.isInternetReachable === false) {
|
||||
if (state.isConnected === false) {
|
||||
return "offline";
|
||||
}
|
||||
if (state.isConnected === true) {
|
||||
|
||||
@@ -41,6 +41,8 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,8 @@ import { type RelayEnvironmentView, useConnectionController } from "./useConnect
|
||||
export function CloudEnvironmentRows(props: {
|
||||
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
|
||||
readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
|
||||
readonly showcaseSignedIn?: boolean;
|
||||
/**
|
||||
* Hide the "T3 Connect" section title + refresh button for hosts that
|
||||
* provide their own chrome (the onboarding sheet's native header and
|
||||
@@ -43,7 +45,8 @@ export function CloudEnvironmentRows(props: {
|
||||
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const controller = useConnectionController();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const availableCloudEnvironments = controller.availableRelayEnvironments;
|
||||
const availableCloudEnvironments =
|
||||
props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments;
|
||||
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
|
||||
const hasCloudRows =
|
||||
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
|
||||
@@ -64,7 +67,7 @@ export function CloudEnvironmentRows(props: {
|
||||
|
||||
const showHeader = props.showHeader ?? true;
|
||||
|
||||
if (!isSignedIn) return null;
|
||||
if (!(props.showcaseSignedIn ?? isSignedIn)) return null;
|
||||
|
||||
return (
|
||||
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
|
||||
|
||||
@@ -58,6 +58,9 @@ 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"
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { NativeReviewDiffRow } from "./nativeReviewDiffSurface";
|
||||
import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";
|
||||
import { highlightNativeReviewDiffVisibleRows } from "./nativeReviewDiffHighlighter";
|
||||
|
||||
const TYPESCRIPT_FILE: NativeReviewDiffFile = {
|
||||
id: "file-1",
|
||||
path: "example.ts",
|
||||
language: "typescript",
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
};
|
||||
|
||||
function makeLine(
|
||||
input: Pick<NativeReviewDiffRow, "id" | "content" | "change" | "oldLineNumber" | "newLineNumber">,
|
||||
): NativeReviewDiffRow {
|
||||
return {
|
||||
kind: "line",
|
||||
fileId: TYPESCRIPT_FILE.id,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function makeHunk(id: string): NativeReviewDiffRow {
|
||||
return {
|
||||
kind: "hunk",
|
||||
id,
|
||||
fileId: TYPESCRIPT_FILE.id,
|
||||
text: "@@",
|
||||
};
|
||||
}
|
||||
|
||||
function highlight(
|
||||
rows: ReadonlyArray<NativeReviewDiffRow>,
|
||||
alreadyHighlightedRowIds?: ReadonlySet<string>,
|
||||
) {
|
||||
return highlightNativeReviewDiffVisibleRows({
|
||||
rows,
|
||||
files: [TYPESCRIPT_FILE],
|
||||
scheme: "dark",
|
||||
engine: "javascript",
|
||||
firstRowIndex: 0,
|
||||
lastRowIndex: rows.length - 1,
|
||||
overscanRows: 0,
|
||||
maxRows: 100,
|
||||
alreadyHighlightedRowIds,
|
||||
});
|
||||
}
|
||||
|
||||
describe("highlightNativeReviewDiffVisibleRows", () => {
|
||||
it("does not carry grammar state across hunk boundaries", async () => {
|
||||
const exportRow = makeLine({
|
||||
id: "export-row",
|
||||
content: "export async function run() {}",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 100,
|
||||
});
|
||||
const rows = [
|
||||
makeHunk("hunk-1"),
|
||||
makeLine({
|
||||
id: "import-open",
|
||||
content: "import {",
|
||||
change: "context",
|
||||
oldLineNumber: 1,
|
||||
newLineNumber: 1,
|
||||
}),
|
||||
makeLine({
|
||||
id: "import-entry",
|
||||
content: " Model,",
|
||||
change: "context",
|
||||
oldLineNumber: 2,
|
||||
newLineNumber: 2,
|
||||
}),
|
||||
makeHunk("hunk-2"),
|
||||
exportRow,
|
||||
];
|
||||
|
||||
const [highlighted, standalone] = await Promise.all([
|
||||
highlight(rows),
|
||||
highlight([makeHunk("standalone-hunk"), exportRow]),
|
||||
]);
|
||||
|
||||
expect(highlighted.tokensByRowId[exportRow.id]).toEqual(standalone.tokensByRowId[exportRow.id]);
|
||||
});
|
||||
|
||||
it("keeps grammar state across inline comment rows", async () => {
|
||||
const openingRow = makeLine({
|
||||
id: "template-open",
|
||||
content: "const message = `open",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 1,
|
||||
});
|
||||
const closingRow = makeLine({
|
||||
id: "template-close",
|
||||
content: "closed`;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 2,
|
||||
});
|
||||
const trailingRow = makeLine({
|
||||
id: "trailing-row",
|
||||
content: "export const answer = 42;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 3,
|
||||
});
|
||||
const commentRow: NativeReviewDiffRow = {
|
||||
kind: "comment",
|
||||
id: "comment-1",
|
||||
fileId: TYPESCRIPT_FILE.id,
|
||||
commentText: "Review note",
|
||||
};
|
||||
|
||||
const [withComment, contiguous] = await Promise.all([
|
||||
highlight([openingRow, commentRow, closingRow, trailingRow]),
|
||||
highlight([openingRow, closingRow, trailingRow]),
|
||||
]);
|
||||
|
||||
expect(withComment.tokensByRowId).toEqual(contiguous.tokensByRowId);
|
||||
});
|
||||
|
||||
it("does not join unhighlighted rows across cached gaps", async () => {
|
||||
const trailingRow = makeLine({
|
||||
id: "trailing-row",
|
||||
content: "export const answer = 42;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 3,
|
||||
});
|
||||
const rows = [
|
||||
makeLine({
|
||||
id: "template-open",
|
||||
content: "const message = `open",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 1,
|
||||
}),
|
||||
makeLine({
|
||||
id: "template-close",
|
||||
content: "closed`;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 2,
|
||||
}),
|
||||
trailingRow,
|
||||
];
|
||||
|
||||
const [highlighted, standalone] = await Promise.all([
|
||||
highlight(rows, new Set(["template-close"])),
|
||||
highlight([trailingRow]),
|
||||
]);
|
||||
|
||||
expect(highlighted.tokensByRowId[trailingRow.id]).toEqual(
|
||||
standalone.tokensByRowId[trailingRow.id],
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps deletion grammar state out of addition rows", async () => {
|
||||
const additionRow = makeLine({
|
||||
id: "addition-row",
|
||||
content: "export const answer = 42;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 1,
|
||||
});
|
||||
const rows = [
|
||||
makeLine({
|
||||
id: "deletion-row",
|
||||
content: "const removed = `open",
|
||||
change: "delete",
|
||||
oldLineNumber: 1,
|
||||
newLineNumber: null,
|
||||
}),
|
||||
additionRow,
|
||||
];
|
||||
|
||||
const [highlighted, standalone] = await Promise.all([
|
||||
highlight(rows),
|
||||
highlight([additionRow]),
|
||||
]);
|
||||
|
||||
expect(highlighted.tokensByRowId[additionRow.id]).toEqual(
|
||||
standalone.tokensByRowId[additionRow.id],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -56,6 +56,11 @@ interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
|
||||
readonly content: string;
|
||||
}
|
||||
|
||||
interface IndexedNativeReviewDiffLineRow {
|
||||
readonly row: NativeReviewDiffLineRow;
|
||||
readonly rowIndex: number;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffTokenChunk {
|
||||
readonly chunkIndex: number;
|
||||
readonly fileId: string;
|
||||
@@ -308,6 +313,58 @@ function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDi
|
||||
return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";
|
||||
}
|
||||
|
||||
function hasConsecutiveLineNumbers(
|
||||
previous: number | null | undefined,
|
||||
next: number | null | undefined,
|
||||
): boolean {
|
||||
return typeof previous === "number" && typeof next === "number" && next === previous + 1;
|
||||
}
|
||||
|
||||
function hasOnlyCommentRowsBetween(
|
||||
rows: ReadonlyArray<NativeReviewDiffRow>,
|
||||
previousRowIndex: number,
|
||||
nextRowIndex: number,
|
||||
): boolean {
|
||||
for (let rowIndex = previousRowIndex + 1; rowIndex < nextRowIndex; rowIndex += 1) {
|
||||
if (rows[rowIndex]?.kind !== "comment") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function canShareGrammarContext(
|
||||
previous: IndexedNativeReviewDiffLineRow,
|
||||
next: IndexedNativeReviewDiffLineRow,
|
||||
rows: ReadonlyArray<NativeReviewDiffRow>,
|
||||
): boolean {
|
||||
if (
|
||||
next.row.fileId !== previous.row.fileId ||
|
||||
!hasOnlyCommentRowsBetween(rows, previous.rowIndex, next.rowIndex)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (previous.row.change === "delete" || next.row.change === "delete") {
|
||||
return (
|
||||
previous.row.change !== "add" &&
|
||||
next.row.change !== "add" &&
|
||||
hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber)
|
||||
);
|
||||
}
|
||||
|
||||
if (previous.row.change === "add" || next.row.change === "add") {
|
||||
return hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber);
|
||||
}
|
||||
|
||||
return (
|
||||
previous.row.change === "context" &&
|
||||
next.row.change === "context" &&
|
||||
hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber) &&
|
||||
hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber)
|
||||
);
|
||||
}
|
||||
|
||||
function groupLineRowsByFileId(rows: ReadonlyArray<NativeReviewDiffRow>) {
|
||||
const rowsByFileId = new Map<string, NativeReviewDiffLineRow[]>();
|
||||
for (const row of rows) {
|
||||
@@ -360,7 +417,7 @@ export async function highlightNativeReviewDiffVisibleRows(
|
||||
const maxRows = input.maxRows ?? NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS;
|
||||
const startIndex = clampRowIndex(input.firstRowIndex - overscanRows, input.rows);
|
||||
const endIndex = clampRowIndex(input.lastRowIndex + overscanRows, input.rows);
|
||||
const selectedRows: NativeReviewDiffLineRow[] = [];
|
||||
const selectedRows: IndexedNativeReviewDiffLineRow[] = [];
|
||||
|
||||
for (
|
||||
let rowIndex = startIndex;
|
||||
@@ -374,12 +431,12 @@ export async function highlightNativeReviewDiffVisibleRows(
|
||||
!input.alreadyHighlightedRowIds?.has(row.id) &&
|
||||
fileMap.has(row.fileId)
|
||||
) {
|
||||
selectedRows.push(row);
|
||||
selectedRows.push({ row, rowIndex });
|
||||
}
|
||||
}
|
||||
|
||||
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
|
||||
let segmentRows: NativeReviewDiffLineRow[] = [];
|
||||
let segmentRows: IndexedNativeReviewDiffLineRow[] = [];
|
||||
let segmentFile: NativeReviewDiffFile | undefined;
|
||||
|
||||
const flushSegment = () => {
|
||||
@@ -389,27 +446,34 @@ export async function highlightNativeReviewDiffVisibleRows(
|
||||
return;
|
||||
}
|
||||
|
||||
const code = segmentRows.map((row) => row.content).join("\n");
|
||||
const code = segmentRows.map(({ row }) => row.content).join("\n");
|
||||
const tokenLines = highlighter.tokenize(code, { lang: segmentFile.language, theme });
|
||||
segmentRows.forEach((row, rowIndex) => {
|
||||
segmentRows.forEach(({ row }, rowIndex) => {
|
||||
tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
|
||||
});
|
||||
segmentRows = [];
|
||||
segmentFile = undefined;
|
||||
};
|
||||
|
||||
for (const row of selectedRows) {
|
||||
for (const selectedRow of selectedRows) {
|
||||
const { row } = selectedRow;
|
||||
const file = fileMap.get(row.fileId);
|
||||
if (!file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (segmentFile && segmentFile.id !== file.id) {
|
||||
const previousRow = segmentRows.at(-1);
|
||||
if (
|
||||
segmentFile &&
|
||||
(segmentFile.id !== file.id ||
|
||||
(previousRow !== undefined &&
|
||||
!canShareGrammarContext(previousRow, selectedRow, input.rows)))
|
||||
) {
|
||||
flushSegment();
|
||||
}
|
||||
|
||||
segmentFile = file;
|
||||
segmentRows.push(row);
|
||||
segmentRows.push(selectedRow);
|
||||
}
|
||||
flushSegment();
|
||||
|
||||
|
||||
@@ -96,5 +96,22 @@ describe("isPendingNativeViewRegistration", () => {
|
||||
new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPendingNativeViewRegistration(
|
||||
new Error(
|
||||
"Unable to find the class expo.modules.t3reviewdiff.T3ReviewDiffView view with tag 1150",
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isNativeReviewDiffDrawEvent", () => {
|
||||
it("accepts only native events emitted after diff rows draw", async () => {
|
||||
const { isNativeReviewDiffDrawEvent } = await import("./nativeReviewDiffSurface");
|
||||
|
||||
expect(isNativeReviewDiffDrawEvent({ message: "draw-metrics" })).toBe(true);
|
||||
expect(isNativeReviewDiffDrawEvent({ message: "visible-range" })).toBe(true);
|
||||
expect(isNativeReviewDiffDrawEvent({ message: "rows-decoded" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -149,6 +149,10 @@ export interface NativeReviewDiffViewHandle {
|
||||
readonly scrollToTop: (animated?: boolean) => Promise<void>;
|
||||
}
|
||||
|
||||
export function isNativeReviewDiffDrawEvent(payload: Readonly<Record<string, unknown>>): boolean {
|
||||
return payload.message === "draw-metrics" || payload.message === "visible-range";
|
||||
}
|
||||
|
||||
interface NativeReviewDiffViewRef {
|
||||
readonly setRowsJson: (rowsJson: string) => Promise<void>;
|
||||
readonly setTokensJson: (tokensJson: string) => Promise<void>;
|
||||
@@ -170,9 +174,11 @@ let nativeReviewDiffViewResolutionFailed = false;
|
||||
type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
|
||||
|
||||
export function isPendingNativeViewRegistration(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
return (
|
||||
error instanceof Error &&
|
||||
error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`)
|
||||
error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`) ||
|
||||
(error.message.includes("Unable to find the class") &&
|
||||
error.message.includes("T3ReviewDiffView view with tag"))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
import type { ProjectEntry } from "@t3tools/contracts";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
FlatList,
|
||||
Platform,
|
||||
Pressable,
|
||||
RefreshControl,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { ActivityIndicator, FlatList, 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,
|
||||
@@ -129,7 +123,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 = Platform.OS === "ios" ? insets.top + 44 : 0;
|
||||
const headerInset = NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 44 : 0;
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
const { onPreviewFile, onSelectFile, selectedPath: controlledSelectedPath } = props;
|
||||
const controlledSelectedPathRef = useRef(controlledSelectedPath);
|
||||
@@ -249,9 +243,11 @@ export function FileTreeBrowser(props: {
|
||||
className="flex-1"
|
||||
data={visibleNodes}
|
||||
keyExtractor={(item) => item.node.path}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"}
|
||||
scrollIndicatorInsets={
|
||||
Platform.OS === "ios" ? { top: headerInset, left: 0, right: 0, bottom: 0 } : undefined
|
||||
NATIVE_LIQUID_GLASS_SUPPORTED
|
||||
? { top: headerInset, left: 0, right: 0, bottom: 0 }
|
||||
: undefined
|
||||
}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
|
||||
@@ -14,6 +12,7 @@ import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { T3Wordmark } from "../../components/T3Wordmark";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
@@ -21,10 +20,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";
|
||||
@@ -33,16 +32,17 @@ 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,11 +59,24 @@ 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 hasCustomListOptions = hasCustomHomeListOptions(props);
|
||||
const threadListV2Enabled = useThreadListV2FilterGate();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
const menuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{
|
||||
@@ -82,40 +95,57 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
})),
|
||||
],
|
||||
},
|
||||
{
|
||||
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.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[])),
|
||||
],
|
||||
[
|
||||
props.environments,
|
||||
props.projectGroupingMode,
|
||||
props.projectSortOrder,
|
||||
props.projects,
|
||||
props.selectedEnvironmentId,
|
||||
props.selectedProjectKey,
|
||||
props.threadSortOrder,
|
||||
threadListV2Enabled,
|
||||
],
|
||||
);
|
||||
const handleMenuAction = useCallback(
|
||||
@@ -137,6 +167,19 @@ 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}`,
|
||||
);
|
||||
@@ -150,13 +193,6 @@ 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],
|
||||
);
|
||||
@@ -255,17 +291,24 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
function IosHomeHeader(props: HomeHeaderProps) {
|
||||
const searchBarRef = useRef<SearchBarCommands>(null);
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const hasCustomListOptions = hasCustomHomeListOptions(props);
|
||||
const threadListV2Enabled = useThreadListV2FilterGate();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
const focusSearch = useCallback(() => {
|
||||
searchBarRef.current?.focus();
|
||||
return searchBarRef.current !== null;
|
||||
}, []);
|
||||
useHardwareKeyboardCommand("focusSearch", focusSearch);
|
||||
const filterMenu = buildHomeListFilterMenu(props);
|
||||
const filterMenu = buildHomeListFilterMenu({
|
||||
...props,
|
||||
listOrganization: !threadListV2Enabled,
|
||||
});
|
||||
|
||||
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.
|
||||
@@ -342,10 +385,6 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
title="Thread list options"
|
||||
separateBackground
|
||||
>
|
||||
<NativeHeaderToolbar.MenuAction onPress={props.onOpenSettings}>
|
||||
<NativeHeaderToolbar.Label>Settings</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
|
||||
<NativeHeaderToolbar.Menu title="Environment">
|
||||
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
@@ -366,6 +405,28 @@ 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) => (
|
||||
@@ -391,20 +452,6 @@ 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,7 +1,7 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
@@ -15,6 +15,7 @@ import { AndroidHomeFabLayout } from "./AndroidHomeFab";
|
||||
import { HomeScreen } from "./HomeScreen";
|
||||
import { HomeHeader } from "./HomeHeader";
|
||||
import { useHomeListOptions } from "./home-list-options";
|
||||
import { buildHomeProjectScopes } from "./homeThreadList";
|
||||
import { usePendingTaskListActions } from "./usePendingTaskListActions";
|
||||
import { useThreadListActions } from "./useThreadListActions";
|
||||
|
||||
@@ -53,11 +54,31 @@ 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(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: selectedEnvironmentId,
|
||||
projectGroupingMode: listOptions.projectGroupingMode,
|
||||
}).map((scope) => ({
|
||||
key: scope.key,
|
||||
label: scope.title,
|
||||
})),
|
||||
[listOptions.projectGroupingMode, 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.
|
||||
@@ -90,14 +111,15 @@ export function HomeRouteScreen() {
|
||||
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
|
||||
<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" })}
|
||||
@@ -115,14 +137,16 @@ export function HomeRouteScreen() {
|
||||
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,
|
||||
@@ -149,6 +173,7 @@ export function HomeRouteScreen() {
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
selectedProjectKey={selectedProjectKey}
|
||||
threads={threads}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
/>
|
||||
|
||||
@@ -15,7 +15,7 @@ import type {
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Platform, Pressable, View } from "react-native";
|
||||
import { ActivityIndicator, FlatList, Platform, Pressable, 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";
|
||||
@@ -24,9 +24,10 @@ 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, scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { useArchivedThreadSnapshots } from "../archive/useArchivedThreadSnapshots";
|
||||
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,7 +36,12 @@ import {
|
||||
ThreadListShowMoreRow,
|
||||
} from "../threads/thread-list-items";
|
||||
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
|
||||
import { buildThreadListV2Items, type ThreadListV2Item } from "../threads/threadListV2";
|
||||
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,
|
||||
@@ -46,7 +52,12 @@ import {
|
||||
type HomeGroupDisplayState,
|
||||
type HomeListItem,
|
||||
} from "./homeListItems";
|
||||
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
type HomeProjectSortOrder,
|
||||
} from "./homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
|
||||
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
|
||||
@@ -62,14 +73,15 @@ 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;
|
||||
@@ -88,10 +100,6 @@ interface HomeScreenProps {
|
||||
/* ─── Layout constants ───────────────────────────────────────────────── */
|
||||
|
||||
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
|
||||
// v2 settled-tail paging: recent history is the common lookup; the deep
|
||||
// tail stays behind an explicit Show more.
|
||||
const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
|
||||
const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
|
||||
/**
|
||||
* Top spacing between the list and the Android custom header. The Android
|
||||
* header (AndroidHomeHeader) is rendered in-flow above this screen and
|
||||
@@ -181,7 +189,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
const insets = useSafeAreaInsets();
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
|
||||
const effectiveGroupDisplayStates = useMemo(() => {
|
||||
const next = new Map(groupDisplayStates);
|
||||
if (!AsyncResult.isSuccess(preferencesResult)) {
|
||||
@@ -238,12 +245,77 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onScrollBeginDrag: handleScrollBeginDrag,
|
||||
});
|
||||
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
buildHomeProjectScopes({
|
||||
projects: props.projects,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
[props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
|
||||
);
|
||||
const selectedProjectScope = useMemo(
|
||||
() =>
|
||||
props.selectedProjectKey === null
|
||||
? null
|
||||
: (projectScopes.find(
|
||||
(scope) =>
|
||||
scope.key === props.selectedProjectKey ||
|
||||
scope.projectRefs.some(
|
||||
(projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
|
||||
props.selectedProjectKey,
|
||||
),
|
||||
) ?? null),
|
||||
[projectScopes, props.selectedProjectKey],
|
||||
);
|
||||
const selectedProjectRefKeys = useMemo(
|
||||
() =>
|
||||
selectedProjectScope === null
|
||||
? null
|
||||
: new Set(
|
||||
selectedProjectScope.projectRefs.map((projectRef) =>
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
),
|
||||
),
|
||||
[selectedProjectScope],
|
||||
);
|
||||
const scopedProjects = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
? props.projects
|
||||
: props.projects.filter((project) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(project.environmentId, project.id)),
|
||||
),
|
||||
[props.projects, selectedProjectRefKeys],
|
||||
);
|
||||
const scopedThreads = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
? props.threads
|
||||
: props.threads.filter((thread) =>
|
||||
selectedProjectRefKeys.has(scopedProjectKey(thread.environmentId, thread.projectId)),
|
||||
),
|
||||
[props.threads, selectedProjectRefKeys],
|
||||
);
|
||||
const scopedPendingTasks = useMemo(
|
||||
() =>
|
||||
selectedProjectRefKeys === null
|
||||
? props.pendingTasks
|
||||
: props.pendingTasks.filter((pendingTask) =>
|
||||
selectedProjectRefKeys.has(
|
||||
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
|
||||
),
|
||||
),
|
||||
[props.pendingTasks, selectedProjectRefKeys],
|
||||
);
|
||||
|
||||
const projectGroups = useMemo(
|
||||
() =>
|
||||
buildHomeThreadGroups({
|
||||
projects: props.projects,
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
projects: scopedProjects,
|
||||
threads: scopedThreads,
|
||||
pendingTasks: scopedPendingTasks,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
@@ -251,14 +323,14 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projectGroupingMode,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threadSortOrder,
|
||||
props.threads,
|
||||
scopedPendingTasks,
|
||||
scopedProjects,
|
||||
scopedThreads,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -289,17 +361,70 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
const v2ProjectScopeKey = props.selectedProjectKey;
|
||||
const v2ScopeProjects = useMemo(
|
||||
() =>
|
||||
sortHomeProjectScopes({
|
||||
scopes: projectScopes,
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
projectScopes,
|
||||
],
|
||||
);
|
||||
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 v2ProjectTitleByProjectKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
v2ScopeProjects.flatMap((scope) =>
|
||||
scope.projectRefs.map(
|
||||
(projectRef) =>
|
||||
[
|
||||
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
|
||||
scope.title,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
[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.
|
||||
// Settle = archive in the client-only model, and the live shell stream
|
||||
// drops archived threads — merge them back from the archived snapshot so
|
||||
// they render as the settled tail. Live shells win on overlap.
|
||||
const archivedEnvironmentIds = useMemo(
|
||||
() =>
|
||||
threadListV2Enabled ? props.environments.map((environment) => environment.environmentId) : [],
|
||||
[props.environments, threadListV2Enabled],
|
||||
);
|
||||
const { snapshots: archivedSnapshots } = useArchivedThreadSnapshots(archivedEnvironmentIds);
|
||||
// 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<
|
||||
@@ -320,83 +445,20 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[],
|
||||
);
|
||||
// Bridge the gap between the live stream dropping a just-settled thread
|
||||
// and the archived snapshot returning it: hold the shell we settled,
|
||||
// marked archived, until the snapshot carries it. Held explicitly at
|
||||
// settle time so deleted threads are never resurrected.
|
||||
const [settledHolds, setSettledHolds] = useState<ReadonlyMap<string, EnvironmentThreadShell>>(
|
||||
() => new Map(),
|
||||
);
|
||||
const handleSettleThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
|
||||
setSettledHolds((current) =>
|
||||
new Map(current).set(threadKey, {
|
||||
...thread,
|
||||
archivedAt: thread.archivedAt ?? new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
void (async () => {
|
||||
// Roll the optimistic hold back if the settle was blocked or failed —
|
||||
// otherwise a never-archived thread would render settled forever.
|
||||
const succeeded = await props.onSettleThread(thread);
|
||||
if (!succeeded) {
|
||||
setSettledHolds((current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(threadKey);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
})();
|
||||
void props.onSettleThread(thread);
|
||||
},
|
||||
[props.onSettleThread],
|
||||
);
|
||||
// Delete and un-settle both invalidate any hold for the thread.
|
||||
const dropSettledHold = useCallback((thread: EnvironmentThreadShell) => {
|
||||
setSettledHolds((current) => {
|
||||
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (!current.has(threadKey)) return current;
|
||||
const next = new Map(current);
|
||||
next.delete(threadKey);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
const handleDeleteThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
dropSettledHold(thread);
|
||||
props.onDeleteThread(thread);
|
||||
},
|
||||
[dropSettledHold, props.onDeleteThread],
|
||||
);
|
||||
const handleUnsettleThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
dropSettledHold(thread);
|
||||
props.onUnsettleThread(thread);
|
||||
},
|
||||
[dropSettledHold, props.onUnsettleThread],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (settledHolds.size === 0) return;
|
||||
const covered = new Set<string>();
|
||||
for (const { environmentId, snapshot } of archivedSnapshots) {
|
||||
for (const thread of snapshot.threads) {
|
||||
covered.add(scopedThreadKey(environmentId, thread.id));
|
||||
}
|
||||
}
|
||||
if ([...settledHolds.keys()].some((threadKey) => covered.has(threadKey))) {
|
||||
setSettledHolds((current) => {
|
||||
const next = new Map(current);
|
||||
for (const threadKey of covered) next.delete(threadKey);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, [archivedSnapshots, settledHolds]);
|
||||
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"}:${props.searchQuery.trim()}`;
|
||||
const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
|
||||
const lastSettledResetKeyRef = useRef(settledResetKey);
|
||||
if (lastSettledResetKeyRef.current !== settledResetKey) {
|
||||
lastSettledResetKeyRef.current = settledResetKey;
|
||||
@@ -406,42 +468,92 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
const merged = new Map<string, EnvironmentThreadShell>();
|
||||
for (const { environmentId, snapshot } of archivedSnapshots) {
|
||||
for (const thread of snapshot.threads) {
|
||||
merged.set(scopedThreadKey(environmentId, thread.id), { ...thread, environmentId });
|
||||
// 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));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
// thread reappears immediately instead of on the next minute tick.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
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);
|
||||
}
|
||||
}
|
||||
for (const thread of props.threads) {
|
||||
merged.set(scopedThreadKey(thread.environmentId, thread.id), thread);
|
||||
}
|
||||
for (const [threadKey, shell] of settledHolds) {
|
||||
if (merged.has(threadKey)) continue;
|
||||
merged.set(threadKey, shell);
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const snoozeEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadSnooze === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
|
||||
// Settled threads are live shells; archived threads keep their original
|
||||
// "hidden from lists" meaning.
|
||||
return buildThreadListV2Items({
|
||||
threads: [...merged.values()],
|
||||
threads: props.threads.filter((thread) => thread.archivedAt === null),
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
snoozeNow: new Date().toISOString(),
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
settledHolds,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
settledVisibleCount,
|
||||
archivedSnapshots,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
threadListV2Enabled,
|
||||
v2ScopedProjectGroup,
|
||||
]);
|
||||
// Re-partition the moment the earliest snooze expires (clamped to the
|
||||
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
|
||||
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
|
||||
useEffect(() => {
|
||||
if (nextSnoozeWakeAt === null) return;
|
||||
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
|
||||
if (Number.isNaN(wakeAtMs)) return;
|
||||
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
|
||||
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
|
||||
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
|
||||
// range) the boundary string is identical and the chain would die.
|
||||
}, [nextSnoozeWakeAt, snoozeWakeTick]);
|
||||
const threadListV2Items = threadListV2Layout.items;
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
({ item }: LegendListRenderItemProps<ThreadListV2Item>) => (
|
||||
({ item }: { readonly item: ThreadListV2Item }) => (
|
||||
<ThreadListV2Row
|
||||
thread={item.thread}
|
||||
variant={item.variant}
|
||||
@@ -450,9 +562,27 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
projectTitle={v2ProjectTitleByProjectKey.get(
|
||||
scopedProjectKey(item.thread.environmentId, item.thread.projectId),
|
||||
)}
|
||||
providerDriver={
|
||||
serverConfigs
|
||||
.get(item.thread.environmentId)
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(item.thread.session?.providerInstanceId ?? item.thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
Object.keys(props.savedConnectionsById).length > 1
|
||||
? (props.savedConnectionsById[item.thread.environmentId]?.environmentLabel ?? null)
|
||||
: null
|
||||
}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
settlementSupported={settlementEnvironmentIds.has(item.thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
@@ -475,6 +605,10 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onSelectThread,
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
v2ProjectTitleByProjectKey,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback(
|
||||
@@ -575,12 +709,12 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
|
||||
|
||||
/* Empty states */
|
||||
// v2 shows archived threads as its settled tail, so an archived-only
|
||||
// workspace still has a list to render there.
|
||||
// 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 ||
|
||||
(threadListV2Enabled && threadListV2Items.length > 0);
|
||||
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
|
||||
const hasResults = projectGroups.length > 0;
|
||||
const selectedEnvironmentLabel =
|
||||
props.selectedEnvironmentId === null
|
||||
@@ -608,7 +742,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: Platform.OS === "ios" ? insets.top + 72 : 0,
|
||||
paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
|
||||
}}
|
||||
>
|
||||
<View className="w-full max-w-[430px]">
|
||||
@@ -619,11 +753,20 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||
variant="plain"
|
||||
/>
|
||||
{emptyState.loading ? (
|
||||
{emptyState.loading && !shouldShowConnectionStatus ? (
|
||||
<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>
|
||||
@@ -648,11 +791,25 @@ 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.
|
||||
// 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}
|
||||
{props.pendingTasks.map((pendingTask, index) => (
|
||||
{v2PendingTasks.map((pendingTask, index) => (
|
||||
<PendingTaskListRow
|
||||
key={pendingTask.message.messageId}
|
||||
variant="compact"
|
||||
@@ -660,7 +817,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
environmentLabel={
|
||||
props.savedConnectionsById[pendingTask.message.environmentId]?.environmentLabel ?? null
|
||||
}
|
||||
isLast={index === props.pendingTasks.length - 1}
|
||||
isLast={index === v2PendingTasks.length - 1}
|
||||
onSelectPendingTask={props.onSelectPendingTask}
|
||||
onDeletePendingTask={props.onDeletePendingTask}
|
||||
/>
|
||||
@@ -671,6 +828,11 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : selectedProjectScope !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedProjectScope.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : selectedEnvironmentLabel ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedEnvironmentLabel}`}
|
||||
@@ -680,18 +842,56 @@ 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. Snoozed threads outrank the rest: "No
|
||||
// threads yet" over an inbox that is merely all-snoozed reads as data
|
||||
// loss. Pending tasks render in the header, so the list showing them
|
||||
// isn't empty in the user's eyes.
|
||||
const v2SnoozedCount = threadListV2Layout.snoozedCount;
|
||||
const v2ListEmpty =
|
||||
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
|
||||
v2SnoozedCount > 0 ? (
|
||||
// The snoozed threads already passed this search filter: "No
|
||||
// results" would claim nothing matched when matches are merely
|
||||
// parked.
|
||||
<EmptyState
|
||||
title={
|
||||
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
|
||||
}
|
||||
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
)
|
||||
) : v2SnoozedCount > 0 ? (
|
||||
<EmptyState
|
||||
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
|
||||
detail="Snoozed threads return when their wake time passes."
|
||||
/>
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : (
|
||||
listEmpty
|
||||
);
|
||||
|
||||
if (threadListV2Enabled) {
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<SwipeableScrollGateProvider enabled={swipeEnabled}>
|
||||
<LegendList
|
||||
<FlatList
|
||||
data={threadListV2Items}
|
||||
renderItem={renderV2Item}
|
||||
keyExtractor={v2KeyExtractor}
|
||||
drawDistance={500}
|
||||
estimatedItemSize={ESTIMATED_THREAD_ROW_HEIGHT}
|
||||
extraData={projectByKey}
|
||||
extraData={{
|
||||
projectByKey,
|
||||
serverConfigs,
|
||||
savedConnectionsById: props.savedConnectionsById,
|
||||
}}
|
||||
ListHeaderComponent={v2ListHeader}
|
||||
ListFooterComponent={
|
||||
threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
@@ -699,16 +899,16 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
|
||||
onPress={showMoreSettled}
|
||||
className="mx-5 mt-1 items-center rounded-full bg-subtle py-2"
|
||||
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-sm font-t3-medium text-foreground-muted">
|
||||
<Text className="text-xs font-t3-medium text-foreground-muted">
|
||||
Show more ({threadListV2Layout.hiddenSettledCount} settled hidden)
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null
|
||||
}
|
||||
ListEmptyComponent={listEmpty}
|
||||
ListEmptyComponent={v2ListEmpty}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
@@ -716,12 +916,11 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
{...scrollGateHandlers}
|
||||
recycleItems
|
||||
scrollEventThrottle={16}
|
||||
contentContainerStyle={{
|
||||
paddingBottom:
|
||||
Platform.OS === "ios"
|
||||
? Math.max(insets.bottom, 24) + 24
|
||||
? Math.max(insets.bottom, 24) + 96
|
||||
: Math.max(insets.bottom, 16) + 88,
|
||||
}}
|
||||
/>
|
||||
@@ -752,8 +951,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
ListHeaderComponent={listHeader}
|
||||
ListEmptyComponent={listEmpty}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
|
||||
contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"}
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
|
||||
@@ -67,4 +67,21 @@ 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,7 +12,10 @@ export function WorkspaceConnectionStatus(props: {
|
||||
readonly variant?: "floating" | "sidebar";
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon-muted");
|
||||
const isReconnecting = props.state.connectingEnvironments.length > 0;
|
||||
const isSynchronizing =
|
||||
props.state.networkStatus !== "offline" &&
|
||||
props.state.connectionError === null &&
|
||||
(props.state.connectingEnvironments.length > 0 || props.state.hasPendingShellSnapshot);
|
||||
const variant = props.variant ?? "floating";
|
||||
|
||||
return (
|
||||
@@ -37,7 +40,7 @@ export function WorkspaceConnectionStatus(props: {
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{isReconnecting ? (
|
||||
{isSynchronizing ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView name="wifi.slash" size={15} tintColor={iconColor} type="monochrome" />
|
||||
|
||||