diff --git a/.agents/skills/ios-debugger-agent/LICENSE b/.agents/skills/ios-debugger-agent/LICENSE new file mode 100644 index 0000000000..0d193abe04 --- /dev/null +++ b/.agents/skills/ios-debugger-agent/LICENSE @@ -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. diff --git a/.agents/skills/ios-debugger-agent/SKILL.md b/.agents/skills/ios-debugger-agent/SKILL.md new file mode 100644 index 0000000000..7afa579383 --- /dev/null +++ b/.agents/skills/ios-debugger-agent/SKILL.md @@ -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 xcodebuildmcp@2.6.2 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. diff --git a/.agents/skills/ios-debugger-agent/agents/openai.yaml b/.agents/skills/ios-debugger-agent/agents/openai.yaml new file mode 100644 index 0000000000..094bae6620 --- /dev/null +++ b/.agents/skills/ios-debugger-agent/agents/openai.yaml @@ -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" diff --git a/.agents/skills/ios-simulator-browser/LICENSE b/.agents/skills/ios-simulator-browser/LICENSE new file mode 100644 index 0000000000..0d193abe04 --- /dev/null +++ b/.agents/skills/ios-simulator-browser/LICENSE @@ -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. diff --git a/.agents/skills/ios-simulator-browser/SKILL.md b/.agents/skills/ios-simulator-browser/SKILL.md new file mode 100644 index 0000000000..74b9753079 --- /dev/null +++ b/.agents/skills/ios-simulator-browser/SKILL.md @@ -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= + cleanup_serve_sim() { + npx --yes serve-sim@0.1.45 --kill "$SIMULATOR_ID" >/dev/null 2>&1 || true + } + trap cleanup_serve_sim EXIT INT TERM HUP + cleanup_serve_sim + npx --yes serve-sim@0.1.45 "$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 ` 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. diff --git a/.agents/skills/ios-simulator-browser/agents/openai.yaml b/.agents/skills/ios-simulator-browser/agents/openai.yaml new file mode 100644 index 0000000000..9e8cdf7a16 --- /dev/null +++ b/.agents/skills/ios-simulator-browser/agents/openai.yaml @@ -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." diff --git a/.agents/skills/test-t3-app/SKILL.md b/.agents/skills/test-t3-app/SKILL.md new file mode 100644 index 0000000000..c3dc1c103d --- /dev/null +++ b/.agents/skills/test-t3-app/SKILL.md @@ -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 `. +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= node apps/server/src/bin.ts auth pairing create \ + --base-dir \ + --dev-url \ + --base-url \ + --ttl 15m \ + --label agent-ui-test +``` + +Use the `Pair URL` from this command once. Derive `` and `` 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 `/userdata`; the `/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`. diff --git a/.agents/skills/test-t3-app/agents/openai.yaml b/.agents/skills/test-t3-app/agents/openai.yaml new file mode 100644 index 0000000000..a3b89c95e6 --- /dev/null +++ b/.agents/skills/test-t3-app/agents/openai.yaml @@ -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." diff --git a/.agents/skills/test-t3-app/references/sqlite-fixtures.md b/.agents/skills/test-t3-app/references/sqlite-fixtures.md new file mode 100644 index 0000000000..8eca543cf9 --- /dev/null +++ b/.agents/skills/test-t3-app/references/sqlite-fixtures.md @@ -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 `/userdata` and the database path is `/userdata/state.sqlite`. The `/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 \ + --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 \ + --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 \ + --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()` 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`. diff --git a/.agents/skills/test-t3-mobile/SKILL.md b/.agents/skills/test-t3-mobile/SKILL.md new file mode 100644 index 0000000000..f3e3dcfd8c --- /dev/null +++ b/.agents/skills/test-t3-mobile/SKILL.md @@ -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 `/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 \ + --base-dir \ + --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 \ + --base-dir \ + --no-browser +``` + +Use these client origins: + +- iOS Simulator: `http://127.0.0.1:` +- Android Emulator: `http://10.0.2.2:` +- 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 --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 + ``` + + 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: `/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 com.t3tools.t3code.dev app +xcrun simctl openurl +``` + +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 shell pm path com.t3tools.t3code.dev +adb -s reverse tcp: tcp: +adb -s shell am start -W \ + -a android.intent.action.VIEW \ + -d '' \ + 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= node apps/server/src/bin.ts auth pairing create \ + --base-dir \ + --base-url \ + --ttl 15m \ + --label agent-mobile- +``` + +In PowerShell, set `$env:T3CODE_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 't3code-dev://connections/new' +adb -s 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 `` 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 reverse --remove tcp:`. +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. diff --git a/.agents/skills/test-t3-mobile/agents/openai.yaml b/.agents/skills/test-t3-mobile/agents/openai.yaml new file mode 100644 index 0000000000..e9518ce9e0 --- /dev/null +++ b/.agents/skills/test-t3-mobile/agents/openai.yaml @@ -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." diff --git a/.claude/skills b/.claude/skills new file mode 120000 index 0000000000..2b7a412b8f --- /dev/null +++ b/.claude/skills @@ -0,0 +1 @@ +../.agents/skills \ No newline at end of file diff --git a/.codex/config.toml b/.codex/config.toml new file mode 100644 index 0000000000..a6369d240f --- /dev/null +++ b/.codex/config.toml @@ -0,0 +1,9 @@ +[mcp_servers.xcodebuildmcp] +enabled = true +required = false +command = "npx" +args = ["--yes", "xcodebuildmcp@2.6.2", "mcp"] +startup_timeout_sec = 20.0 + +[mcp_servers.xcodebuildmcp.env] +XCODEBUILDMCP_ENABLED_WORKFLOWS = "simulator,ui-automation,debugging,logging" diff --git a/.cursor/rules/cursor-cloud.mdc b/.cursor/rules/cursor-cloud.mdc new file mode 100644 index 0000000000..98fcb1d576 --- /dev/null +++ b/.cursor/rules/cursor-cloud.mdc @@ -0,0 +1,72 @@ +--- +description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI) +alwaysApply: true +--- + +# Cursor Cloud specific instructions + +These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is +developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats. + +## Toolchain + +Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global +`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo +(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter + + diff --git a/apps/marketing/src/layouts/Layout.astro b/apps/marketing/src/layouts/Layout.astro index 5d9fc4e8f3..9c454c4b78 100644 --- a/apps/marketing/src/layouts/Layout.astro +++ b/apps/marketing/src/layouts/Layout.astro @@ -4,11 +4,13 @@ import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site"; interface Props { title?: string; description?: string; + pageClass?: string; } const { title = "T3 Code", description = "T3 Code — The open-source control plane for coding agents.", + pageClass, } = Astro.props; --- @@ -30,7 +32,7 @@ const { {title} -
+ @@ -279,7 +284,7 @@ const { min-height: 100vh; display: flex; flex-direction: column; - overflow-x: hidden; + overflow-x: clip; } .nav { @@ -402,6 +407,8 @@ const { .footer-links { display: flex; + flex-wrap: wrap; + justify-content: flex-end; gap: 20px; } @@ -421,6 +428,28 @@ const { padding-left: 20px; padding-right: 20px; } + + .legal-document-page .nav { + display: none; + } + + .footer { + padding-bottom: max(32px, env(safe-area-inset-bottom)); + } + + .footer-inner { + align-items: flex-start; + flex-direction: column; + gap: 28px; + } + + .footer-links { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + width: 100%; + gap: 14px 20px; + justify-content: initial; + } } @media (max-width: 420px) { diff --git a/apps/marketing/src/lib/site.ts b/apps/marketing/src/lib/site.ts index 5ff5958c58..92e491a077 100644 --- a/apps/marketing/src/lib/site.ts +++ b/apps/marketing/src/lib/site.ts @@ -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; diff --git a/apps/marketing/src/pages/index.astro b/apps/marketing/src/pages/index.astro index dbd9f7c4f2..841c6a622b 100644 --- a/apps/marketing/src/pages/index.astro +++ b/apps/marketing/src/pages/index.astro @@ -33,6 +33,9 @@ const mobileEndorsementRows = [ + + +
@@ -41,7 +44,7 @@ const mobileEndorsementRows = [

- 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.

@@ -173,7 +176,7 @@ const mobileEndorsementRows = [

Bring your own sub

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.

@@ -207,6 +210,13 @@ const mobileEndorsementRows = [
@cursor/sdk
+
+
+
+
Grok CLI
+
grok login
+
+
@@ -403,12 +413,14 @@ const mobileEndorsementRows = [ const label = document.getElementById("download-label"); const ctaBtn = document.getElementById("cta-download-btn") as HTMLAnchorElement | null; const ctaLabel = document.getElementById("cta-download-label"); + const kbd = document.getElementById("pr-button-kbd"); const platform = detectPlatform(); if (!platform) return; document.documentElement.dataset.platform = platform.os; if (label) label.textContent = platform.label; if (ctaLabel) ctaLabel.textContent = platform.label; + if (kbd && platform.os !== "mac") kbd.textContent = "Ctrl ⏎"; try { const release = await fetchLatestRelease(); @@ -613,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; } @@ -623,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) { @@ -657,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 { @@ -677,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; @@ -686,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; @@ -702,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; @@ -748,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); @@ -1203,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; } } diff --git a/apps/marketing/src/pages/legal.astro b/apps/marketing/src/pages/legal.astro new file mode 100644 index 0000000000..d75413a8da --- /dev/null +++ b/apps/marketing/src/pages/legal.astro @@ -0,0 +1,172 @@ +--- +import Layout from "../layouts/Layout.astro"; + +const documents = [ + { + number: "01", + title: "Privacy Policy", + description: "How T3 Code handles information, connected services, and your privacy choices.", + href: "/privacy-policy", + }, + { + number: "02", + title: "Terms of Service", + description: "The terms that govern your use of T3 Code and T3 Tools-operated services.", + href: "/terms-of-service", + }, + { + number: "03", + title: "Security Policy", + description: "Our security practices, responsible disclosure process, and shared responsibilities.", + href: "/security-policy", + }, +] as const; +--- + + + + + + diff --git a/apps/marketing/src/pages/privacy-policy.astro b/apps/marketing/src/pages/privacy-policy.astro new file mode 100644 index 0000000000..b85bc0b12b --- /dev/null +++ b/apps/marketing/src/pages/privacy-policy.astro @@ -0,0 +1,445 @@ +--- +import LegalPage from "../components/LegalPage.astro"; + +const sections = [ + ["introduction", "Introduction"], + ["information", "Personal information we collect"], + ["uses", "How we use your personal information"], + ["sharing", "How we share your personal information"], + ["choices", "Your choices regarding your personal information"], + ["security", "Security of your personal information"], + ["international", "International users"], + ["children", "Children"], + ["do-not-track", "Do Not Track"], + ["updates", "Updates to this Privacy Policy"], + ["contact", "Contact us"], +] as const; +--- + + +
+

01

+

Introduction

+

+ This Privacy Policy (the “Policy”) describes how T3 Tools, Inc. (the “Company,” “T3 + Tools,” “we,” or “us”) collects, uses, and shares personal information when you use the T3 + Code desktop and mobile applications, the hosted T3 Code web application located at + {" "}https://app.t3.codes, or the optional T3 Connect + service (together, the “Services”), or visit the T3 Code marketing website located at + {" "}https://t3.codes (the “Site”). This Policy applies to + personal information we collect through the Site and the Services, as well as personal + information you provide to us directly. +

+

+ By using the Site or the Services, you acknowledge the practices described in this + Policy. If you do not agree with this Policy, please do not use the Site or the Services. + This Policy does not govern third-party coding agents, artificial-intelligence providers, + identity providers, or environments that you choose to connect to T3 Code; those third + parties process information under their own terms and privacy policies. +

+
+ +
+

02

+

Personal Information We Collect

+ +

+ We collect personal information about you in different ways depending on how you use + T3 Code and which optional features you enable. +

+ +

Personal Information From Users of T3 Code

+ +

+ When you use T3 Code, we may collect the following categories of personal information: +

+
    +
  • + Account information. If you create or sign in to a T3 account, we + receive general identifiers and profile information from our authentication provider + and the identity provider you select. This may include your name, email address, + profile image, user ID, sign-in method, and authentication credentials or tokens. +
  • +
  • + Environment and device information. If you enable T3 Connect, we + process information needed to connect and secure your environments and devices, + including identifiers, labels you assign, public keys, connection endpoints, + credential hashes, connection status, app and operating-system versions, and + notification preferences. +
  • +
  • + Agent activity and notifications. If you enable notifications or Live + Activities, we process push tokens and limited activity information needed to provide + those features, such as project and thread titles, model name, status, and activity + headline. +
  • +
  • + Information you provide to us. We collect information that you choose + to provide when you request support, send feedback, or otherwise communicate with us. +
  • +
+ +

Personal Information From Users of Our Site Generally

+

+ When you visit the Site or use online portions of the Services, we and our service + providers may automatically log online identifiers and internet-activity information, + including your Internet Protocol (IP) address, device and operating-system type, browser + or app type and version, pages viewed, access times, request timestamps, connection + events, latency, error details, and diagnostic traces. The amount of information we + collect depends on the Services you use and your device and browser settings. +

+

+ We use operational and diagnostic information to provide, secure, maintain, and + troubleshoot the Services, not for targeted advertising. +

+ +

Information We Get From Others

+

+ We may receive personal information from service providers that help us operate the + Services, such as authentication and identity providers, app stores, device-platform + providers, and coding-agent providers you choose to use. We may combine this information + with information we collect through the Site and the Services. +

+ +

Cookies and Local Storage

+

+ The Site and online portions of the Services may use cookies or similar technologies to + operate essential features, maintain sessions, remember preferences, and understand + whether the Services are functioning correctly. T3 Code also stores connection settings, + credentials, preferences, drafts, and cached thread, file, branch, and server metadata on + your device. Credentials and session tokens use platform-provided protected storage where + supported. Information stored only on your device is not collected by T3 Tools unless it + is transmitted as part of a feature you use. +

+ +

Device Permissions

+
    +
  • + Camera. Used when you choose to scan a pairing QR code. Camera frames + are processed on your device. +
  • +
  • + Photos and files. Items you select are accessed only to preview them or + attach them to a request you initiate. +
  • +
  • + Notifications. Used only if you enable agent-status notifications or + Live Activities. +
  • +
  • + Local network. Used to discover or connect to T3 Code environments + accessible from your machine over the network. +
  • +
+
+ +
+

03

+

How We Use Your Personal Information

+

+ Subject to this Policy and applicable terms governing third-party applications and + services, we may use personal information for the following purposes: +

+
    +
  • To establish and verify your identity and authenticate your account;
  • +
  • To link and protect devices and environments and deliver optional notifications;
  • +
  • To process and fulfill requests you make through the Services;
  • +
  • To provide customer service and respond to support requests and feedback;
  • +
  • To communicate with you about the Services and your relationship with us;
  • +
  • To monitor reliability, prevent abuse, and investigate security incidents;
  • +
  • To comply with applicable law and enforce the terms governing the Services; and
  • +
  • + To analyze and improve T3 Code using aggregated, de-identified, or other anonymous + operational information. +
  • +
+ +

Training of AI Models

+

+ We do not use your personal information, source code, prompts, or agent responses to + train artificial-intelligence models. +

+ +

Compliance and Protection

+

We may use personal information to:

+
    +
  • Comply with applicable laws, lawful requests, and legal process;
  • +
  • Protect the rights, privacy, safety, and property of T3 Tools, our users, and others;
  • +
  • Audit our internal processes for legal, contractual, and policy compliance;
  • +
  • Enforce the terms and conditions that govern the Site and the Services; and
  • +
  • + Prevent, identify, investigate, and deter fraudulent, harmful, unauthorized, + unethical, or illegal activity, including cyberattacks and identity theft. +
  • +
+

+ We may also use personal information for other purposes consistent with this Policy or + explained to you when we collect the information. +

+
+ +
+

04

+

How We Share Your Personal Information

+

+ We may disclose the categories of personal information described above to the following + categories of third parties: +

+ +

Providers You Choose

+

+ At your direction, prompts, files, and related content are sent to coding agents and + artificial-intelligence providers configured in your environment. Because you bring and + configure your own coding-agent harness and provider, the applicable third parties vary. + Those providers process information under their own terms and privacy policies. +

+ +

Third-Party Service Providers

+

+ We use third-party service providers to help provide the Services and operate our + business. Depending on the features you use, these providers may include: +

+
    +
  • + Clerk (Clerk, Inc.).
    + We use Clerk to provide account authentication.
    + You can view Clerk's privacy policy here:{" "}https://clerk.com/legal/privacy. +
  • +
  • + Cloudflare (Cloudflare, Inc.).
    + We use Cloudflare for networking, T3 Connect infrastructure, and content delivery.
    + You can view Cloudflare's privacy policy here:{" "}https://www.cloudflare.com/policies/privacy/. +
  • +
  • + PlanetScale (PlanetScale, Inc.).
    + We use PlanetScale to host the database that supports T3 Connect.
    + You can view PlanetScale's privacy policy here:{" "}https://planetscale.com/legal/privacy. +
  • +
  • + Vercel (Vercel Inc.).
    + We use Vercel to host and deploy the T3 Code Site.
    + You can view Vercel's privacy notice here:{" "}https://vercel.com/legal/privacy-notice. +
  • +
  • + Axiom (Axiom, Inc.).
    + We use Axiom for operational diagnostics that help us maintain and troubleshoot the + Services.
    + You can view Axiom's privacy policy here:{" "}https://axiom.co/docs/legal/privacy. +
  • +
  • + Expo (650 Industries, Inc.).
    + We use Expo for application updates and related mobile-app services.
    + You can view Expo's privacy policy here:{" "}https://expo.dev/privacy. +
  • +
  • + Apple (Apple Inc.).
    + We use Apple services for app distribution, optional authentication, and platform + notifications.
    + You can view Apple's privacy policy here:{" "}https://www.apple.com/legal/privacy/. +
  • +
  • + Google (Google LLC).
    + We use Google services for app distribution and optional authentication.
    + You can view Google's privacy policy here:{" "}https://policies.google.com/privacy. +
  • +
+

+ These providers process information for us under their own contractual and privacy + obligations. +

+ +

Affiliates and Professional Advisors

+

+ We may share personal information with our affiliates for purposes consistent with this + Policy and with lawyers, accountants, bankers, and other professional advisors in the + course of the services they provide to us. +

+ +

Corporate Restructuring

+

+ We may share some or all personal information in connection with or during negotiation of + a merger, financing, acquisition, reorganization, bankruptcy, dissolution, sale of + assets, or similar transaction. If another company acquires T3 Tools or its assets, that + company may possess the personal information collected by us and assume the rights and + obligations described in this Policy. +

+ +

Legal and Safety Disclosures

+

+ We may disclose personal information if we believe in good faith that disclosure is + necessary to comply with law or legal process; protect or defend the rights, property, or + safety of T3 Tools, users of the Site or the Services, or others; investigate or prevent + fraud, abuse, or unlawful activity; or enforce this Policy and the terms governing the + Services. We may also share personal information at your direction, with your consent, or + as described to you when the information is collected. +

+ +

No Sale of Personal Information

+

+ We do not sell your personal information or share it for cross-context behavioral or + targeted advertising. +

+ +

Third-Party Websites and Services

+

+ The Site and the Services may contain links to third-party websites or services. When you + follow a third-party link or connect a third-party service, that third party may collect + personal information from you. We do not control and are not responsible for the privacy + practices or content of third parties. +

+
+ +
+

05

+

Your Choices Regarding Your Personal Information

+ +

Account and Connection Choices

+

+ You may use local or direct connections without signing in to a T3 account. You can + disconnect environments, sign out, disable optional notifications and Live Activities, + and clear local caches from Settings. You can grant or revoke camera, photo, local-network, + and notification permissions in your device settings. +

+ +

Cookies and Local Data

+

+ You can use your browser settings to stop accepting or to delete cookies, although some + portions of the Site or the Services may not function correctly as a result. Information + stored only on your device remains there until you clear it, remove the relevant + connection, or uninstall the app. The mobile app provides cache controls under + {" "}Settings → App → Client Storage. +

+ +

Retention and Deletion

+

+ We retain account, environment-link, device-registration, notification, and security + information while your account or the relevant feature is active and for as long as + reasonably necessary to provide the Services, protect them from abuse, comply with law, + and resolve disputes. Operational diagnostic traces are configured to expire after 30 + days. Some records may remain longer in backups or where retention is required for + security, fraud prevention, or legal compliance. +

+

+ To request deletion of your T3 account and associated T3 Connect data, email{" "}privacy@t3.tools{" "}from the email address associated with your account. We may need to verify your + identity. Deleting a T3 account does not delete information held by an environment or + coding-agent provider you control; contact those providers or delete that information + directly. +

+ +

Your Privacy Rights

+

+ Depending on where you live, you may have rights to request access to, correction of, + deletion of, or a portable copy of your personal information, or to restrict or object + to certain processing. You may also have the right to appeal our response or complain to + a data-protection authority. We will honor applicable rights after verifying your + request. +

+
+ +
+

06

+

Security of Your Personal Information

+

+ T3 Tools is committed to protecting the security of your personal information. We use + administrative, technical, and organizational safeguards designed to protect personal + information from unauthorized access, use, or disclosure. These safeguards include + encrypted network transport, scoped and proof-bound access tokens for supported + connection flows, protected credential storage, and redaction of authorization headers + from relay diagnostics. +

+

+ No method of transmission over the Internet or method of electronic storage is completely + secure. While we use reasonable efforts to protect personal information, we cannot + guarantee its absolute security. You are responsible for securing the environments, + coding-agent accounts, credentials, and networks that you connect to T3 Code. +

+
+ +
+

07

+

International Users

+

+ The Site and the Services are provided from the United States and are governed by United + States law. If you use the Site or the Services from outside the United States, your + personal information may be transferred to and processed in the United States and other + countries where we or our service providers operate. Where required, we use lawful + safeguards for international transfers of personal information. +

+
+ +
+

08

+

Children

+

+ The Site and the Services are not intended for children under 13 years of age, and you + must be at least 13 years old to use them. We do not knowingly collect, use, or disclose + personal information from children under 13. If you believe a child under 13 has provided + us with personal information, please contact us so that we can take appropriate action. +

+
+ +
+

09

+

Do Not Track

+

+ We currently do not respond to browser “Do Not Track” signals. T3 Code does not use + personal information for cross-context behavioral or targeted advertising. +

+
+ +
+

10

+

Updates to This Privacy Policy

+

+ We reserve the right to update this Policy from time to time. If we make material changes, + we will post the revised Policy at this URL, update the “Last Updated” and “Effective Date” + above, and provide any additional notice required by law. Except as otherwise indicated, + changes become effective when the revised Policy is posted. +

+
+ +
+

11

+

Contact Us

+

+ If you have questions about this Policy or wish to make a privacy or deletion request, + please contact us at: +

+
+ T3 Tools, Inc.
+ 2261 Market Street #5309
+ San Francisco, CA 94114
+ United States +
+ privacy@t3.tools +
+
diff --git a/apps/marketing/src/pages/security-policy.astro b/apps/marketing/src/pages/security-policy.astro new file mode 100644 index 0000000000..c9b05ec36f --- /dev/null +++ b/apps/marketing/src/pages/security-policy.astro @@ -0,0 +1,187 @@ +--- +import LegalPage from "../components/LegalPage.astro"; + +const sections = [ + ["introduction", "Introduction"], + ["reporting", "Reporting security issues"], + ["safe-harbor", "Responsible research and safe harbor"], + ["practices", "Our security practices"], + ["responsibilities", "Your responsibilities"], + ["updates", "Updates to this policy"], + ["contact", "Contact us"], +] as const; +--- + + +
+

01

+

Introduction

+

+ This Security Policy describes the vulnerability-reporting process and security practices for + the T3 Code desktop and mobile applications, the hosted application at{" "}https://app.t3.codes, the optional T3 Connect service, and the T3 Code website at{" "}https://t3.codes. +

+

+ T3 Code connects software running on your devices and in environments you control with + coding-agent harnesses and providers you choose. We secure the software and infrastructure + operated by T3 Tools, but we do not control the security of your devices, environments, + repositories, networks, credentials, or third-party providers. Please review the shared + responsibilities below when assessing risk. +

+
+ +
+

02

+

Reporting Security Issues

+

+ If you believe you have found a security vulnerability affecting T3 Code or T3 Tools-operated + infrastructure, email{" "}security@ping.gg. Please do not + disclose the issue publicly until we have had a reasonable opportunity to investigate and + remediate it. +

+

Please include, when available:

+
    +
  • A description of the issue and its potential impact;
  • +
  • The affected application, version, URL, endpoint, or component;
  • +
  • Clear reproduction steps or a minimal proof of concept;
  • +
  • Relevant logs, screenshots, or request and response details with secrets removed; and
  • +
  • Your preferred contact information and whether you want public credit.
  • +
+

+ We aim to acknowledge complete reports within one business day, keep reporters informed of + material progress, and coordinate disclosure after a fix is available. Resolution time varies + with severity, complexity, and dependencies on third parties. +

+
+ +
+

03

+

Responsible Research and Safe Harbor

+

+ We support good-faith security research. If you make a genuine effort to comply with this + policy, avoid harm, respect privacy, and report findings promptly, we will treat your research + as authorized and will not initiate legal action against you for accidental, good-faith + violations of this policy. If a third party initiates legal action concerning compliant + research, we will make our authorization known where appropriate. +

+

To remain within this safe harbor, you must:

+
    +
  • Test only accounts, data, and systems you own or have explicit permission to test;
  • +
  • Stop and report immediately if you encounter personal, confidential, or production data;
  • +
  • Access only the minimum information needed to demonstrate the issue;
  • +
  • Avoid disrupting availability, degrading performance, or damaging or deleting data;
  • +
  • Not use social engineering, phishing, physical attacks, or denial-of-service testing;
  • +
  • Not test third-party services or infrastructure outside T3 Tools’ control; and
  • +
  • Give us reasonable time to address the issue before public disclosure.
  • +
+

+ This safe harbor does not authorize violations of law or activity outside the scope of this + policy. Vulnerability rewards are not guaranteed and, if offered, are determined by T3 Tools + in its discretion. +

+
+ +
+

04

+

Our Security Practices

+

+ We use administrative, technical, and organizational safeguards designed for the nature of T3 + Code and the information processed by T3 Tools-operated services. These practices include: +

+
    +
  • + Data minimization. T3 Code is designed so coding-session content can remain + between your clients, your environment, and the harnesses and providers you configure. We + process information through T3 Tools-operated infrastructure only when needed for a feature + you enable. +
  • +
  • + Encrypted transport. T3 Tools-operated network services use encrypted + transport. Supported connection flows use scoped credentials and security controls designed + to reduce unauthorized reuse. +
  • +
  • + Credential protection. T3 Code uses platform-provided protected storage for + credentials and session tokens where supported. We design operational logging to avoid + collecting secrets that are not needed to operate or troubleshoot the Services. +
  • +
  • + Access controls. Access to production systems and operational data is limited + according to job responsibilities and protected using authentication and authorization + controls. +
  • +
  • + Maintenance and monitoring. We monitor T3 Tools-operated services for + reliability and security events, review dependencies, and deploy updates and mitigations as + appropriate. +
  • +
  • + Established providers. We use specialized providers for services such as + authentication, hosting, and application distribution and evaluate the controls relevant to + their role. +
  • +
+

+ No system is completely secure. These practices reduce risk but do not guarantee that the Site + or Services will be free from vulnerabilities or unauthorized access. +

+
+ +
+

05

+

Your Responsibilities

+

+ Because you control much of the T3 Code execution path, you play an important role in securing + it. You are responsible for: +

+
    +
  • Keeping T3 Code, your operating systems, and connected tools up to date;
  • +
  • Securing your devices, repositories, environments, networks, and backups;
  • +
  • Protecting account, provider, repository, and environment credentials;
  • +
  • Using multi-factor authentication where your identity and coding-agent providers support it;
  • +
  • Granting providers and integrations only the permissions they need;
  • +
  • Reviewing commands, source changes, and other agent output before applying or executing it;
  • +
  • Removing lost or unused devices and revoking credentials you believe may be compromised; and
  • +
  • Following the security policies of your selected harnesses, providers, and infrastructure.
  • +
+

+ Do not send passwords, API keys, access tokens, or private keys in a vulnerability report. + Revoke any secret that may have been exposed before sharing sanitized evidence with us. +

+
+ +
+

06

+

Updates to This Policy

+

+ We may update this Security Policy as T3 Code, our infrastructure, and security practices + evolve. We will post revisions at this URL and update the dates above. Material changes to the + vulnerability-reporting process or safe-harbor terms will apply prospectively. +

+
+ +
+

07

+

Contact Us

+

+ Report security issues or ask security-related questions at{" "}security@ping.gg. +

+

+ For general legal questions, contact{" "}legal@t3.tools. + For privacy requests, contact{" "}privacy@t3.tools. +

+
+
diff --git a/apps/marketing/src/pages/terms-of-service.astro b/apps/marketing/src/pages/terms-of-service.astro new file mode 100644 index 0000000000..e6de5f2c75 --- /dev/null +++ b/apps/marketing/src/pages/terms-of-service.astro @@ -0,0 +1,396 @@ +--- +import LegalPage from "../components/LegalPage.astro"; + +const sections = [ + ["introduction", "Introduction"], + ["accounts", "Accounts"], + ["content", "Your content and providers"], + ["rights", "T3 Code and proprietary rights"], + ["acceptable-use", "Acceptable use"], + ["availability", "Availability and changes"], + ["fees", "Fees"], + ["privacy", "Privacy"], + ["termination", "Suspension and termination"], + ["beta", "Beta services"], + ["disclaimers", "Disclaimers"], + ["liability", "Limitation of liability"], + ["indemnification", "Indemnification"], + ["copyright", "Copyright complaints"], + ["third-parties", "Third-party services"], + ["feedback", "Feedback"], + ["disputes", "Dispute resolution"], + ["miscellaneous", "Miscellaneous"], + ["changes", "Changes to these Terms"], + ["contact", "Contact us"], +] as const; +--- + + +
+

01

+

Introduction

+

+ These Terms of Service (the “Terms”) are a binding agreement between you and T3 Tools, Inc. + (“T3 Tools,” “we,” “us,” or “our”). They govern your access to and use of the T3 Code desktop + and mobile applications, the hosted T3 Code application at{" "}https://app.t3.codes, and the optional T3 Connect service (together, the “Services”), as well as the T3 Code + marketing website at{" "}https://t3.codes (the “Site”). +

+

+ By accessing or using the Site or Services, you agree to these Terms. If you use the Services + for an organization, you represent that you have authority to bind that organization, and + “you” includes the organization. If you do not agree to these Terms, do not use the Site or + Services. +

+

+ You must be at least 13 years old to use the Site or Services. If the law where you live + requires a greater age to enter into these Terms, you must meet that requirement or have a + parent or legal guardian agree on your behalf. +

+
+ +
+

02

+

Accounts

+

+ You can use some T3 Code features without creating a T3 account. An account may be required + for account-backed features, including T3 Connect. You agree to provide accurate account + information, keep your credentials secure, and promptly notify us if you suspect unauthorized + access. You are responsible for activity performed through your account and connected devices, + except to the extent caused by our failure to use reasonable security measures. +

+

+ You may not share credentials in a way that compromises the Services, impersonate another + person, or create accounts through unauthorized automated means. We may require reasonable + verification before restoring access or acting on an account request. +

+
+ +
+

03

+

Your Content and Providers

+

+ T3 Code can help you send prompts, source files, images, attachments, review comments, and + instructions to coding-agent harnesses and providers you choose, and display their responses, + command output, file changes, source code, and diffs (collectively, “User Content”). You retain + all rights you have in your User Content. +

+

+ You bring and configure your own coding-agent harness and provider. Your User Content is + ordinarily processed in the environment you control and by the providers you select, not by + T3 Tools. When you enable a T3 Tools-operated feature that must transmit or process User + Content, you grant us a limited, non-exclusive license to host, transmit, reproduce, and + process that content only as reasonably necessary to provide, secure, and troubleshoot that + feature. This license ends when the content is no longer needed for those purposes, subject to + reasonable backup, security, and legal-retention requirements. +

+

+ You represent that you have the rights and permissions needed to use and submit User Content + and to direct its processing by your selected harnesses and providers. You are responsible for + reviewing those providers’ terms, privacy practices, data controls, and output before using + them with confidential, proprietary, regulated, or personal information. +

+
+ +
+

04

+

T3 Code and Proprietary Rights

+

+ T3 Tools and its licensors own the Site, the Services, and their branding, designs, hosted + infrastructure, documentation, and other materials, excluding User Content and third-party + materials. These Terms do not transfer ownership of either party’s intellectual property. +

+

+ Portions of T3 Code are available as open-source software. Your use, copying, modification, and + distribution of that source code are governed by the license included with the applicable + repository or component. These Terms govern your use of the hosted Services and do not limit + rights granted to you by an applicable open-source license. +

+

+ Subject to these Terms, we grant you a limited, non-exclusive, non-transferable, revocable right + to access and use the Services for lawful personal or internal business purposes. You may not + use our trademarks, service marks, or trade dress without written permission. +

+
+ +
+

05

+

Acceptable Use

+

You may not use the Site or Services to:

+
    +
  • Violate applicable law or another person’s rights;
  • +
  • Upload, transmit, or generate content you do not have the right to use;
  • +
  • Distribute malware, exploit code, or harmful content except in authorized security work;
  • +
  • Probe, attack, disrupt, or gain unauthorized access to the Services or another system;
  • +
  • Bypass rate limits, access controls, security measures, or usage restrictions;
  • +
  • Interfere with other users or place an unreasonable load on shared infrastructure;
  • +
  • Use the Services to facilitate fraud, harassment, abuse, or deceptive conduct; or
  • +
  • Misrepresent that output or activity from a third-party agent was produced or endorsed by us.
  • +
+

+ Authorized security research must follow our{" "}Security Policy. + We may investigate suspected violations and take proportionate action to protect users and the + Services. +

+
+ +
+

06

+

Availability and Changes

+

+ We may add, change, suspend, or discontinue features, integrations, or supported platforms. We + aim to provide reasonable notice when a change materially reduces an account-backed feature, + but urgent security, legal, or reliability changes may take effect immediately. The Services + may be unavailable because of maintenance, provider outages, network conditions, or events + outside our control. +

+

+ T3 Code depends on software, environments, networks, and coding-agent providers that you + configure or that third parties operate. We do not control their availability, compatibility, + pricing, or behavior. +

+
+ +
+

07

+

Fees

+

+ T3 Code is currently offered without a T3 Tools subscription fee unless we clearly state + otherwise for a feature. You remain responsible for charges from your coding-agent providers, + cloud infrastructure, network operators, app stores, and other third parties. If we introduce + a paid feature, we will present its price and applicable payment terms before you purchase it. +

+
+ +
+

08

+

Privacy

+

+ Our{" "}Privacy Policy explains how T3 Tools collects, uses, and + shares personal information when you use the Site and Services. Third-party environments, + harnesses, identity providers, and coding-agent providers process information under their own + terms and privacy policies. +

+
+ +
+

09

+

Suspension and Termination

+

+ You may stop using the Services at any time. You may disconnect environments and devices from + within T3 Code and may request deletion of an account as described in our Privacy Policy. +

+

+ We may suspend or terminate access to account-backed or hosted features if we reasonably + believe you materially violated these Terms, created a security or legal risk, failed to pay an + applicable fee, or used the Services in a way that could harm other users or shared + infrastructure. When practicable, we will give notice and an opportunity to cure. We may act + immediately where needed to prevent harm or comply with law. +

+

+ Provisions that by their nature should survive termination—including ownership, disclaimers, + limitations of liability, indemnification, and dispute terms—will survive. +

+
+ +
+

10

+

Beta Services

+

+ T3 Code is an early-stage product, and some or all features may be identified as alpha, beta, + preview, experimental, or pre-release (“Beta Services”). Beta Services may be incomplete, + change without notice, contain errors, or lose data. Do not rely on Beta Services as the sole + copy of important work, and review proposed commands and file changes before applying them. +

+
+ +
+

11

+

Disclaimers

+ +

+ Coding agents and artificial-intelligence systems can produce incorrect, insecure, incomplete, + or harmful output. You are responsible for reviewing output, commands, patches, and other + actions before relying on or executing them. We do not warrant that the Services or third-party + output will be uninterrupted, secure, accurate, error-free, or suitable for your purpose. +

+

+ Some jurisdictions do not allow certain warranty exclusions, so some of the foregoing may not + apply to you. +

+
+ +
+

12

+

Limitation of Liability

+ +

+ To the maximum extent permitted by law, our aggregate liability for all claims arising from or + relating to the Site, Services, or these Terms will not exceed the greater of $100 or the amount + you paid directly to T3 Tools for the Services during the 12 months before the event giving rise + to the claim. These limitations apply regardless of the legal theory and even if a remedy fails + of its essential purpose. They do not limit liability that cannot lawfully be limited. +

+
+ +
+

13

+

Indemnification

+

+ To the extent permitted by law, you will defend, indemnify, and hold harmless T3 Tools and its + affiliates, officers, employees, and agents from third-party claims, damages, losses, and + reasonable legal fees arising from your User Content, your use of the Site or Services in + violation of these Terms or law, or your infringement of another person’s rights. We will + promptly notify you of a covered claim and reasonably cooperate in its defense. You may not + settle a claim in a way that admits fault by or imposes obligations on us without our written + consent. +

+
+ + + +
+

15

+

Third-Party Services

+

+ The Services may connect to or display content from third-party coding agents, model providers, + identity providers, repositories, app stores, websites, and infrastructure. Your use of those + services is governed by their terms. We do not endorse or control third-party services and are + not responsible for their content, security, availability, output, or data practices. +

+

+ Third-party and open-source software included with T3 Code is governed by its applicable + license notices. Where those licenses conflict with these Terms for that software, the + applicable open-source license controls. +

+
+ +
+

16

+

Feedback

+

+ If you send us ideas, suggestions, or other feedback about T3 Code, you grant T3 Tools a + perpetual, irrevocable, worldwide, royalty-free right to use and commercialize that feedback + without restriction or compensation. This does not transfer ownership of your User Content. +

+
+ +
+

17

+

Dispute Resolution

+ +

Informal Resolution

+

+ Before starting arbitration or a court proceeding, the party raising a dispute must send a + written notice describing the dispute and requested relief. Notices to us must be sent to{" "}legal@t3.tools. The parties will try in good faith to resolve the dispute for at least 30 days. +

+

Binding Arbitration

+

+ Except for disputes eligible for small-claims court and requests for injunctive relief to + protect intellectual property or prevent unauthorized access, unresolved disputes will be + resolved by binding individual arbitration administered by JAMS under its applicable consumer + or comprehensive rules. The Federal Arbitration Act governs this agreement. Arbitration may + take place remotely unless the arbitrator determines that an in-person hearing is necessary. +

+

No Class Actions

+

+ Disputes must be brought only on an individual basis. Neither party may participate in a class, + collective, consolidated, or representative action or arbitration to the extent permitted by + law. +

+

Opt Out

+

+ You may opt out of this arbitration agreement by emailing{" "}legal@t3.tools within 30 days after you first accept these Terms. Include your name, the email associated + with your account if any, and a clear statement that you opt out of arbitration. +

+

+ If the arbitration agreement does not apply, exclusive jurisdiction and venue will lie in the + state and federal courts located in San Francisco County, California, and each party consents + to those courts. +

+
+ +
+

18

+

Miscellaneous

+

+ California law governs these Terms without regard to conflict-of-law principles, except that + the Federal Arbitration Act governs the arbitration provisions. These Terms and documents + incorporated by reference are the entire agreement between you and us regarding the Site and + Services. If a provision is unenforceable, it will be modified to the minimum extent necessary + or severed, and the remaining provisions will continue in effect. +

+

+ Our failure to enforce a provision is not a waiver. You may not assign these Terms without our + written consent. We may assign them in connection with a merger, acquisition, reorganization, + or sale of assets. We are not liable for delays or failures caused by events beyond our + reasonable control. Headings are for convenience only, and “including” means “including without + limitation.” +

+
+ +
+

19

+

Changes to These Terms

+

+ We may update these Terms from time to time. We will post updated Terms at this URL and update + the dates above. If a change materially affects your rights, we will provide additional notice + when reasonably practicable or as required by law. Changes apply prospectively from their + effective date. Your continued use of the Site or Services after that date means you accept the + updated Terms. +

+
+ +
+

20

+

Contact Us

+

If you have questions about these Terms, contact us at:

+
+ T3 Tools, Inc.
+ 2261 Market Street #5309
+ San Francisco, CA 94114
+ United States +
+ legal@t3.tools +
+
diff --git a/apps/mobile/.swiftlint.yml b/apps/mobile/.swiftlint.yml index 0714ce90e6..c56a56251f 100644 --- a/apps/mobile/.swiftlint.yml +++ b/apps/mobile/.swiftlint.yml @@ -1,6 +1,7 @@ included: - ios/T3Code - modules/t3-composer-editor/ios + - modules/t3-native-controls/ios - modules/t3-terminal/ios - modules/t3-review-diff/ios diff --git a/apps/mobile/README.md b/apps/mobile/README.md index ad0242c271..0eb865cb79 100644 --- a/apps/mobile/README.md +++ b/apps/mobile/README.md @@ -34,6 +34,30 @@ Build and run the local iOS dev client: 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 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 \ +T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code.dev \ +vp run ios:dev +``` + +Build and install a self-contained Release app that does not need Metro: + +```bash +vp run ios:release +``` + +The Personal Team equivalent also needs a unique bundle identifier: + +```bash +T3CODE_IOS_PERSONAL_TEAM=1 \ +T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code \ +vp run ios:release +``` + Build and run the local iOS preview app: ```bash diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 680d689f36..4a0c761f2c 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -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"; @@ -8,43 +9,82 @@ const repoEnv = loadRepoEnv(); Object.assign(process.env, repoEnv); const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT); +const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1"; -const VARIANT_CONFIG: Record< - AppVariant, - { - readonly appName: string; - readonly scheme: string; - readonly iosIcon: string; - readonly iosBundleIdentifier: string; - readonly androidPackage: string; - readonly relyingParty?: string; - } -> = { +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 || + !IOS_BUNDLE_IDENTIFIER_PATTERN.test(personalTeamBundleIdentifier)) +) { + throw new Error( + "T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID must be a reverse-DNS identifier such as com.example.t3code when T3CODE_IOS_PERSONAL_TEAM=1.", + ); +} + +const DEVELOPMENT_ASSETS = { + 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: 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", + androidNotificationIcon: "./assets/android-notification-icon.png", + androidNotificationColor: "#FFFFFF", +} as const; + +const VARIANT_CONFIG = { development: { appName: "T3 Code Dev", scheme: "t3code-dev", - iosIcon: "./assets/icon-composer-dev.icon", iosBundleIdentifier: "com.t3tools.t3code.dev", androidPackage: "com.t3tools.t3code.dev", relyingParty: "clerk.t3.codes", + assets: DEVELOPMENT_ASSETS, }, preview: { appName: "T3 Code Preview", scheme: "t3code-preview", - iosIcon: "./assets/icon-composer-prod.icon", iosBundleIdentifier: "com.t3tools.t3code.preview", androidPackage: "com.t3tools.t3code.preview", relyingParty: "clerk.t3.codes", + assets: PREVIEW_ASSETS, }, production: { appName: "T3 Code", scheme: "t3code", - iosIcon: "./assets/icon-composer-prod.icon", iosBundleIdentifier: "com.t3tools.t3code", androidPackage: "com.t3tools.t3code", relyingParty: "clerk.t3.codes", + assets: RELEASE_ASSETS, }, -}; +} as const; function resolveAppVariant(value: string | undefined): AppVariant { switch (value) { @@ -58,6 +98,63 @@ 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", + medium: "@expo-google-fonts/dm-sans/500Medium/DMSans_500Medium.ttf", + bold: "@expo-google-fonts/dm-sans/700Bold/DMSans_700Bold.ttf", +} as const; + +const widgetsPlugin: NonNullable[number] = [ + "expo-widgets", + { + 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. + frequentUpdates: true, + widgets: [ + { + name: "AgentActivity", + displayName: "Agent Activity", + description: "Shows the current state of active T3 Code agents.", + supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"], + }, + ], + }, +]; + +const sharingPlugin: NonNullable[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. const config: ExpoConfig = { name: variant.appName, @@ -66,10 +163,14 @@ const config: ExpoConfig = { scheme: variant.scheme, version: "0.1.0", runtimeVersion: { - policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion", + // Fingerprint (not appVersion) so an OTA only reaches binaries whose native + // project — native deps, config plugins, AND patches/ — matches the update. + // With appVersion, every 0.1.0 build shares a runtime version, so a JS update + // could land on a binary missing the native changes it needs and crash. + policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint", }, orientation: "portrait", - icon: "./assets/icon.png", + icon: variant.assets.appIcon, userInterfaceStyle: "automatic", updates: { enabled: true, @@ -78,9 +179,13 @@ const config: ExpoConfig = { fallbackToCacheTimeout: 0, }, ios: { - icon: variant.iosIcon, + 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). + appleTeamId: "ARK85ZXQ4Z", associatedDomains: [ `applinks:${variant.relyingParty}`, `webcredentials:${variant.relyingParty}`, @@ -95,41 +200,94 @@ const config: ExpoConfig = { }, }, android: { - icon: "./assets/icon.png", + icon: variant.assets.appIcon, package: variant.androidPackage, adaptiveIcon: { - backgroundColor: "#E6F4FE", - foregroundImage: "./assets/android-icon-foreground.png", - backgroundImage: "./assets/android-icon-background.png", - monochromeImage: "./assets/android-icon-monochrome.png", + backgroundColor: variant.assets.androidAdaptiveBackgroundColor, + foregroundImage: variant.assets.androidAdaptiveForeground, + monochromeImage: variant.assets.androidMonochromeIcon, }, - predictiveBackGestureEnabled: false, + // Opts into OnBackInvokedCallback-based back dispatch (Android 13+). + // JS back handling survives it via react-native's Android 16 shim plus + // withAndroidPredictiveBackCompat on Android 13-15. + predictiveBackGestureEnabled: true, }, web: { - favicon: "./assets/favicon.png", + favicon: variant.assets.appIcon, }, plugins: [ - "expo-router", - "expo-font", + "expo-asset", + [ + "expo-font", + { + ios: { + fonts: [dmSansFonts.regular, dmSansFonts.medium, dmSansFonts.bold], + }, + android: { + fonts: [ + { + fontFamily: "DMSans-Regular", + fontDefinitions: [{ path: dmSansFonts.regular, weight: 400 }], + }, + { + fontFamily: "DMSans-Medium", + fontDefinitions: [{ path: dmSansFonts.medium, weight: 500 }], + }, + { + fontFamily: "DMSans-Bold", + fontDefinitions: [{ path: dmSansFonts.bold, weight: 700 }], + }, + ], + }, + }, + ], "expo-secure-store", - ["@clerk/expo", { theme: "./clerk-theme.json" }], + "expo-sqlite", + ...(isIosPersonalTeamBuild + ? [sharingPlugin] + : ["./plugins/withShareExtensionDisplayName.cjs", sharingPlugin]), + [ + "expo-notifications", + { + icon: variant.assets.androidNotificationIcon, + color: variant.assets.androidNotificationColor, + mode: APP_VARIANT === "development" ? "development" : "production", + }, + ], + // appleSignIn must be gated here: withoutIosPersonalTeamCapabilities.cjs runs before + // plugins earlier in this array, so it cannot strip the entitlement Clerk would add. + ["@clerk/expo", { theme: "./clerk-theme.json", appleSignIn: !isIosPersonalTeamBuild }], "expo-web-browser", + [ + "expo-quick-actions", + { + // Adaptive launcher-shortcut icon; referenced by resource name from + // the shortcut items set in src/features/shortcuts. + androidIcons: { + shortcut_icon: { + foregroundImage: variant.assets.androidAdaptiveForeground, + backgroundColor: variant.assets.androidAdaptiveBackgroundColor, + }, + }, + }, + ], [ "expo-camera", { cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.", barcodeScannerEnabled: true, + recordAudioAndroid: false, }, ], [ "expo-splash-screen", { - image: "./assets/splash-icon.png", + image: variant.assets.splashIcon, resizeMode: "contain", backgroundColor: "#ffffff", imageWidth: 220, dark: { - image: "./assets/splash-icon.png", + image: variant.assets.splashIcon, backgroundColor: "#0a0a0a", }, }, @@ -147,26 +305,24 @@ const config: ExpoConfig = { }, }, ], - [ - "expo-widgets", - { - bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`, - groupIdentifier: `group.${variant.iosBundleIdentifier}`, - enablePushNotifications: true, - widgets: [ - { - name: "AgentActivity", - displayName: "Agent Activity", - description: "Shows the current state of active T3 Code agents.", - supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"], - }, - ], - }, - ], + "./plugins/withIosCocoaPodsUuidCache.cjs", + // Must be listed BEFORE expo-widgets: same-type mods run last-registered- + // first, so registering earlier makes this plugin's mods run AFTER + // expo-widgets' — its dangerous mod wipes ios/ExpoWidgetsTarget/ (which + // would delete the asset catalog) and its xcodeproj mod creates the widget + // target (which must exist before the compile phase can be attached). + ...(!isIosPersonalTeamBuild ? ["./plugins/withWidgetLogoAsset.cjs", widgetsPlugin] : []), + "./plugins/withIosSceneLifecycle.cjs", "./plugins/withAndroidCleartextTraffic.cjs", + "./plugins/withAndroidGradleHeap.cjs", + "./plugins/withAndroidModernPopupMenu.cjs", + "./plugins/withAndroidModernAlertDialog.cjs", + "./plugins/withAndroidPredictiveBackCompat.cjs", + ...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []), ], extra: { appVariant: APP_VARIANT, + iosPersonalTeamBuild: isIosPersonalTeamBuild, relay: { url: repoEnv.T3CODE_RELAY_URL ?? null, }, @@ -174,6 +330,15 @@ const config: ExpoConfig = { publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null, jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null, }, + // Native Google sign-in credentials. @clerk/expo reads these from `extra` + // under their exact env-var names (not nested), and its config plugin reads + // the iOS URL scheme at prebuild to register it in Info.plist. + // Unset values must be omitted (not null): the public manifest serializes + // null to {}, which is truthy and would defeat Clerk's fallback checks. + EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID, + EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID, + EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID, + EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME, observability: { tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces", tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null, diff --git a/apps/mobile/assets/android-icon-background.png b/apps/mobile/assets/android-icon-background.png deleted file mode 100644 index b33d7978d7..0000000000 Binary files a/apps/mobile/assets/android-icon-background.png and /dev/null differ diff --git a/apps/mobile/assets/android-icon-foreground.png b/apps/mobile/assets/android-icon-foreground.png deleted file mode 100644 index b33d7978d7..0000000000 Binary files a/apps/mobile/assets/android-icon-foreground.png and /dev/null differ diff --git a/apps/mobile/assets/android-icon-mark.png b/apps/mobile/assets/android-icon-mark.png new file mode 100644 index 0000000000..3300f22fd5 Binary files /dev/null and b/apps/mobile/assets/android-icon-mark.png differ diff --git a/apps/mobile/assets/android-icon-monochrome.png b/apps/mobile/assets/android-icon-monochrome.png deleted file mode 100644 index b33d7978d7..0000000000 Binary files a/apps/mobile/assets/android-icon-monochrome.png and /dev/null differ diff --git a/apps/mobile/assets/android-notification-icon.png b/apps/mobile/assets/android-notification-icon.png new file mode 100644 index 0000000000..74de6633cb Binary files /dev/null and b/apps/mobile/assets/android-notification-icon.png differ diff --git a/apps/mobile/assets/favicon.png b/apps/mobile/assets/favicon.png deleted file mode 100644 index e0e1b9659b..0000000000 Binary files a/apps/mobile/assets/favicon.png and /dev/null differ diff --git a/apps/mobile/assets/icon-composer-dev.icon/Assets/Texturelabs_Paper_381XL.jpg b/apps/mobile/assets/icon-composer-dev.icon/Assets/Texturelabs_Paper_381XL.jpg deleted file mode 100644 index d98c41a4e3..0000000000 Binary files a/apps/mobile/assets/icon-composer-dev.icon/Assets/Texturelabs_Paper_381XL.jpg and /dev/null differ diff --git a/apps/mobile/assets/icon-composer-dev.icon/Assets/gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr.png b/apps/mobile/assets/icon-composer-dev.icon/Assets/gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr.png deleted file mode 100644 index de5a82d8c4..0000000000 Binary files a/apps/mobile/assets/icon-composer-dev.icon/Assets/gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr.png and /dev/null differ diff --git a/apps/mobile/assets/icon-composer-prod.icon/Assets/T3.svg b/apps/mobile/assets/icon-composer-prod.icon/Assets/T3.svg deleted file mode 100644 index b12706fdfc..0000000000 --- a/apps/mobile/assets/icon-composer-prod.icon/Assets/T3.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/apps/mobile/assets/icon.png b/apps/mobile/assets/icon.png deleted file mode 100644 index b33d6f337b..0000000000 Binary files a/apps/mobile/assets/icon.png and /dev/null differ diff --git a/apps/mobile/assets/splash-icon.png b/apps/mobile/assets/splash-icon.png deleted file mode 100644 index b33d6f337b..0000000000 Binary files a/apps/mobile/assets/splash-icon.png and /dev/null differ diff --git a/apps/mobile/assets/widget/T3Mark.svg b/apps/mobile/assets/widget/T3Mark.svg new file mode 100644 index 0000000000..48d1b09446 --- /dev/null +++ b/apps/mobile/assets/widget/T3Mark.svg @@ -0,0 +1,3 @@ + + + diff --git a/apps/mobile/eas.json b/apps/mobile/eas.json index 14c5ea5866..a1d315b7e1 100644 --- a/apps/mobile/eas.json +++ b/apps/mobile/eas.json @@ -6,25 +6,31 @@ }, "build": { "development": { + "corepack": true, "env": { - "APP_VARIANT": "development" + "APP_VARIANT": "development", + "NODE_OPTIONS": "--max-old-space-size=4096" }, "channel": "development", "developmentClient": true, "distribution": "internal" }, "preview": { + "corepack": true, "env": { - "APP_VARIANT": "preview" + "APP_VARIANT": "preview", + "NODE_OPTIONS": "--max-old-space-size=4096" }, "channel": "preview", "environment": "preview", "distribution": "internal" }, "preview:dev": { + "corepack": true, "env": { "APP_VARIANT": "preview", - "MOBILE_VERSION_POLICY": "fingerprint" + "MOBILE_VERSION_POLICY": "fingerprint", + "NODE_OPTIONS": "--max-old-space-size=4096" }, "channel": "preview", "environment": "preview", @@ -35,8 +41,10 @@ } }, "production": { + "corepack": true, "env": { - "APP_VARIANT": "production" + "APP_VARIANT": "production", + "NODE_OPTIONS": "--max-old-space-size=4096" }, "channel": "production", "environment": "production", @@ -46,7 +54,10 @@ "submit": { "production": { "ios": { - "ascAppId": "6761315631" + "ascAppId": "6787819824" + }, + "android": { + "track": "internal" } } } diff --git a/apps/mobile/global.css b/apps/mobile/global.css index b2014bf935..6d36bf77ca 100644 --- a/apps/mobile/global.css +++ b/apps/mobile/global.css @@ -12,7 +12,7 @@ /* Card / surface */ --color-card: #ffffff; --color-card-alt: #f5f5f5; - --color-card-translucent: rgba(255, 255, 255, 0.94); + --color-card-translucent: rgba(255, 255, 255, 0.8); /* Text */ --color-foreground: #262626; @@ -51,6 +51,7 @@ /* Inputs */ --color-input: #ffffff; --color-input-border: rgba(0, 0, 0, 0.1); + --color-sidebar-search: rgba(118, 118, 128, 0.12); --color-placeholder: #a3a3a3; /* Icons */ @@ -105,7 +106,7 @@ /* Card / surface */ --color-card: #171717; --color-card-alt: #1c1c1c; - --color-card-translucent: rgba(17, 17, 17, 0.94); + --color-card-translucent: rgba(17, 17, 17, 0.8); /* Text */ --color-foreground: #f5f5f5; @@ -144,6 +145,7 @@ /* Inputs */ --color-input: #141414; --color-input-border: rgba(255, 255, 255, 0.08); + --color-sidebar-search: rgba(118, 118, 128, 0.24); --color-placeholder: #8e8e93; /* Icons */ @@ -194,41 +196,42 @@ /* ─── Typography ────────────────────────────────────────────────────── */ @theme { - --font-sans: "DMSans_400Regular"; - --font-medium: "DMSans_500Medium"; - --font-bold: "DMSans_700Bold"; + /* Keep these native family names aligned with app.config.ts. */ + --font-sans: "DMSans-Regular"; + --font-medium: "DMSans-Medium"; + --font-bold: "DMSans-Bold"; /* Keep this scale aligned with src/lib/typography.ts for native style props. */ - --text-3xs: 10px; - --text-3xs--line-height: 13px; - --text-2xs: 11px; - --text-2xs--line-height: 15px; - --text-xs: 12px; - --text-xs--line-height: 16px; - --text-sm: 13px; - --text-sm--line-height: 18px; - --text-base: 15px; - --text-base--line-height: 22px; - --text-lg: 17px; - --text-lg--line-height: 22px; - --text-xl: 20px; - --text-xl--line-height: 26px; - --text-2xl: 24px; - --text-2xl--line-height: 30px; - --text-3xl: 28px; - --text-3xl--line-height: 34px; + --text-3xs: 11px; + --text-3xs--line-height: 14px; + --text-2xs: 12px; + --text-2xs--line-height: 16px; + --text-xs: 13px; + --text-xs--line-height: 17px; + --text-sm: 14px; + --text-sm--line-height: 19px; + --text-base: 16px; + --text-base--line-height: 23px; + --text-lg: 18px; + --text-lg--line-height: 23px; + --text-xl: 21px; + --text-xl--line-height: 28px; + --text-2xl: 26px; + --text-2xl--line-height: 32px; + --text-3xl: 30px; + --text-3xl--line-height: 36px; } /* ─── Custom utilities ──────────────────────────────────────────────── */ @utility font-t3-medium { - font-family: "DMSans_500Medium"; + font-family: var(--font-medium); } @utility font-t3-bold { - font-family: "DMSans_700Bold"; + font-family: var(--font-bold); } @utility font-t3-extrabold { - font-family: "DMSans_700Bold"; + font-family: var(--font-bold); font-weight: 800; } diff --git a/apps/mobile/index.ts b/apps/mobile/index.ts index 642e1b77be..9b887f58a2 100644 --- a/apps/mobile/index.ts +++ b/apps/mobile/index.ts @@ -1,2 +1,16 @@ +import { registerRootComponent } from "expo"; import "react-native-gesture-handler"; -import "expo-router/entry"; +import { LogBox } from "react-native"; +import { featureFlags } from "react-native-screens"; + +import App from "./src/App"; + +// Required for react-native-screens' iOS FormSheet sizing fix when a nested +// native stack is rendered inside a non-fitToContents formSheet. +featureFlags.experiment.synchronousScreenUpdatesEnabled = true; + +if (process.env.EXPO_PUBLIC_SHOWCASE === "1") { + LogBox.ignoreAllLogs(); +} + +registerRootComponent(App); diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js index d314f6206c..fe88607769 100644 --- a/apps/mobile/metro.config.js +++ b/apps/mobile/metro.config.js @@ -6,6 +6,7 @@ const { withUniwindConfig } = require("uniwind/metro"); /** @type {import("expo/metro-config").MetroConfig} */ const config = getDefaultConfig(__dirname); const workspaceRoot = path.resolve(__dirname, "../.."); +const escapedWorkspaceRoot = workspaceRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const mobileShikiRoot = path.dirname(require.resolve("shiki/package.json", { paths: [__dirname] })); const resolveShikiDependencyRoot = (packageName) => { const entryPath = require.resolve(packageName, { paths: [mobileShikiRoot] }); @@ -25,6 +26,14 @@ const resolveShikiDependencyRoot = (packageName) => { config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])]; config.resolver = { ...config.resolver, + blockList: [ + ...(Array.isArray(config.resolver?.blockList) + ? config.resolver.blockList + : config.resolver?.blockList + ? [config.resolver.blockList] + : []), + new RegExp(`${escapedWorkspaceRoot}[/\\\\]\\.t3[/\\\\].*`), + ], extraNodeModules: { // oxlint-disable-next-line unicorn/no-useless-fallback-in-spread ...(config.resolver?.extraNodeModules ?? {}), diff --git a/apps/mobile/modules/t3-composer-editor/android/build.gradle b/apps/mobile/modules/t3-composer-editor/android/build.gradle new file mode 100644 index 0000000000..dfdb4d16a1 --- /dev/null +++ b/apps/mobile/modules/t3-composer-editor/android/build.gradle @@ -0,0 +1,19 @@ +apply plugin: 'com.android.library' +apply plugin: 'org.jetbrains.kotlin.android' + +group = 'com.t3tools.composereditor' +version = '0.0.0' + +android { + namespace 'expo.modules.t3composereditor' + compileSdk rootProject.ext.compileSdkVersion + + defaultConfig { + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + } +} + +dependencies { + implementation project(':expo-modules-core') +} diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/AndroidManifest.xml b/apps/mobile/modules/t3-composer-editor/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..94cbbcfc39 --- /dev/null +++ b/apps/mobile/modules/t3-composer-editor/android/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt new file mode 100644 index 0000000000..e11181e81a --- /dev/null +++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt @@ -0,0 +1,72 @@ +package expo.modules.t3composereditor + +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition + +class T3ComposerEditorModule : Module() { + override fun definition() = ModuleDefinition { + Name("T3ComposerEditor") + + View(T3ComposerEditorView::class) { + Prop("controlledDocumentJson") { view: T3ComposerEditorView, documentJson: String -> + view.setControlledDocumentJson(documentJson) + } + Prop("themeJson") { view: T3ComposerEditorView, themeJson: String -> + view.setThemeJson(themeJson) + } + Prop("placeholder") { view: T3ComposerEditorView, placeholder: String -> + view.setPlaceholder(placeholder) + } + Prop("fontFamily") { view: T3ComposerEditorView, fontFamily: String -> + view.setFontFamily(fontFamily) + } + Prop("fontSize") { view: T3ComposerEditorView, fontSize: Double -> + view.setFontSize(fontSize.toFloat()) + } + Prop("lineHeight") { view: T3ComposerEditorView, lineHeight: Double -> + view.setLineHeight(lineHeight.toFloat()) + } + Prop("contentInsetVertical") { view: T3ComposerEditorView, contentInsetVertical: Double -> + view.setContentInsetVertical(contentInsetVertical.toInt()) + } + + Prop("singleLineCentered") { view: T3ComposerEditorView, singleLineCentered: Boolean -> + view.setSingleLineCentered(singleLineCentered) + } + Prop("editable") { view: T3ComposerEditorView, editable: Boolean -> + view.setEditable(editable) + } + Prop("scrollEnabled") { view: T3ComposerEditorView, scrollEnabled: Boolean -> + view.setScrollEnabled(scrollEnabled) + } + Prop("autoFocus") { view: T3ComposerEditorView, autoFocus: Boolean -> + view.setAutoFocus(autoFocus) + } + Prop("autoCorrect") { view: T3ComposerEditorView, autoCorrect: Boolean -> + view.setAutoCorrect(autoCorrect) + } + Prop("spellCheck") { view: T3ComposerEditorView, spellCheck: Boolean -> + view.setSpellCheck(spellCheck) + } + + Events( + "onComposerChange", + "onComposerSelectionChange", + "onComposerFocus", + "onComposerBlur", + "onComposerPasteImages", + "onComposerContentSizeChange", + ) + + AsyncFunction("focus") { view: T3ComposerEditorView -> + view.focusEditor() + } + AsyncFunction("blur") { view: T3ComposerEditorView -> + view.blurEditor() + } + AsyncFunction("setSelection") { view: T3ComposerEditorView, start: Int, end: Int -> + view.setSelection(start, end) + } + } + } +} diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt new file mode 100644 index 0000000000..e13c0a5218 --- /dev/null +++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt @@ -0,0 +1,480 @@ +package expo.modules.t3composereditor + +import android.content.Context +import android.content.ClipboardManager +import android.graphics.Color +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.RectF +import android.graphics.Typeface +import android.text.Editable +import android.text.InputType +import android.text.Spanned +import android.text.TextWatcher +import android.text.style.ReplacementSpan +import android.view.Gravity +import android.view.ViewGroup +import android.view.inputmethod.InputMethodManager +import android.widget.EditText +import expo.modules.kotlin.AppContext +import expo.modules.kotlin.viewevent.EventDispatcher +import expo.modules.kotlin.views.ExpoView +import org.json.JSONObject +import kotlin.math.max + +class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView( + context, + appContext +) { + private val editor = SelectionAwareEditText(context) + private val onComposerChange by EventDispatcher() + private val onComposerSelectionChange by EventDispatcher() + private val onComposerFocus by EventDispatcher() + private val onComposerBlur by EventDispatcher() + private val onComposerPasteImages by EventDispatcher() + private val onComposerContentSizeChange by EventDispatcher() + private var applyingNativeValue = false + private var desiredLineHeightPx = 0 + private var lastContentHeight = 0 + private var contentInsetVertical = 0 + private var tokensJson = "[]" + private var tokens: List = emptyList() + private var chipTheme = ComposerChipTheme.default() + private var autoCorrect = true + private var spellCheck = true + private var nativeEventCount = 0 + + init { + editor.setBackgroundColor(Color.TRANSPARENT) + editor.gravity = Gravity.TOP or Gravity.START + editor.includeFontPadding = false + editor.isSingleLine = false + editor.minLines = 1 + editor.inputType = + InputType.TYPE_CLASS_TEXT or + InputType.TYPE_TEXT_FLAG_MULTI_LINE or + InputType.TYPE_TEXT_FLAG_CAP_SENTENCES + editor.setTextColor(Color.BLACK) + editor.setHintTextColor(Color.GRAY) + editor.setPadding(0, 0, 0, 0) + editor.selectionListener = { start, end -> + if (!applyingNativeValue) { + emitSelectionChange(start, end) + } + } + editor.pasteImagesListener = { uris -> + onComposerPasteImages(mapOf("uris" to uris)) + } + editor.setOnFocusChangeListener { _, hasFocus -> + if (hasFocus) { + onComposerFocus(emptyMap()) + } else { + onComposerBlur(emptyMap()) + } + } + editor.addTextChangedListener( + object : TextWatcher { + override fun beforeTextChanged( + text: CharSequence?, + start: Int, + count: Int, + after: Int + ) = Unit + override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) = Unit + + override fun afterTextChanged(editable: Editable?) { + if (applyingNativeValue) return + val nextValue = editable.toString() + val selection = currentSelectionPayload() + nativeEventCount += 1 + onComposerChange( + mapOf( + "value" to nextValue, + "selection" to selection, + "eventCount" to nativeEventCount, + ), + ) + emitContentSizeIfNeeded() + } + }, + ) + editor.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> emitContentSizeIfNeeded() } + addView( + editor, + LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT), + ) + } + + @Suppress("ReturnCount") + fun setControlledDocumentJson(documentJson: String) { + val document = try { + JSONObject(documentJson) + } catch (_: Exception) { + return + } + val mostRecentEventCount = document.optInt("mostRecentEventCount", -1) + if (mostRecentEventCount < nativeEventCount) return + + val value = document.optString("value") + if (document.optBoolean("isNativeEcho") && editor.text.toString() != value) return + + val nextTokensJson = document.optString("tokensJson", "[]") + val nextTokens = if (nextTokensJson == tokensJson) tokens else parseTokens(nextTokensJson) + val requestedSelection = document.optJSONObject("selection") + val previousSelectionStart = editor.selectionStart.coerceAtLeast(0) + val previousSelectionEnd = editor.selectionEnd.coerceAtLeast(0) + val valueChanged = editor.text.toString() != value + + applyingNativeValue = true + try { + if (valueChanged) { + editor.setText(value) + } + tokensJson = nextTokensJson + tokens = nextTokens + applyTokenSpans() + if (requestedSelection != null) { + applySelection( + requestedSelection.optInt("start", previousSelectionStart), + requestedSelection.optInt("end", previousSelectionEnd), + ) + } else if (valueChanged) { + applySelection(previousSelectionStart, previousSelectionEnd) + } + } finally { + applyingNativeValue = false + } + emitContentSizeIfNeeded() + } + + fun setThemeJson(themeJson: String) { + try { + val theme = JSONObject(themeJson) + editor.setTextColor(parseColor(theme.optString("text"), Color.BLACK)) + editor.setHintTextColor(parseColor(theme.optString("placeholder"), Color.GRAY)) + chipTheme = ComposerChipTheme( + chipBackground = parseColor(theme.optString("chipBackground"), chipTheme.chipBackground), + chipBorder = parseColor(theme.optString("chipBorder"), chipTheme.chipBorder), + chipText = parseColor(theme.optString("chipText"), chipTheme.chipText), + skillBackground = parseColor( + theme.optString("skillBackground"), + chipTheme.skillBackground, + ), + skillBorder = parseColor(theme.optString("skillBorder"), chipTheme.skillBorder), + skillText = parseColor(theme.optString("skillText"), chipTheme.skillText), + ) + applyTokenSpans() + } catch (_: Exception) { + } + } + + fun setPlaceholder(placeholder: String) { + editor.hint = placeholder + } + + fun setFontFamily(fontFamily: String) { + editor.typeface = if (fontFamily.contains("Mono", ignoreCase = true)) { + Typeface.MONOSPACE + } else { + Typeface.DEFAULT + } + } + + fun setFontSize(fontSize: Float) { + editor.textSize = fontSize + applyLineHeight() + } + + fun setLineHeight(lineHeight: Float) { + desiredLineHeightPx = (lineHeight * resources.displayMetrics.density).toInt() + applyLineHeight() + } + + fun setSingleLineCentered(centered: Boolean) { + editor.gravity = if (centered) { + Gravity.CENTER_VERTICAL or Gravity.START + } else { + Gravity.TOP or Gravity.START + } + } + + fun setContentInsetVertical(contentInsetVertical: Int) { + this.contentInsetVertical = + max(0, (contentInsetVertical * resources.displayMetrics.density).toInt()) + editor.setPadding(0, this.contentInsetVertical, 0, this.contentInsetVertical) + emitContentSizeIfNeeded() + } + + fun setEditable(editable: Boolean) { + editor.isEnabled = editable + editor.isFocusable = editable + editor.isFocusableInTouchMode = editable + editor.isCursorVisible = editable + } + + fun setScrollEnabled(scrollEnabled: Boolean) { + editor.isVerticalScrollBarEnabled = scrollEnabled + } + + fun setAutoFocus(autoFocus: Boolean) { + if (autoFocus) { + post { focusEditor() } + } + } + + fun setAutoCorrect(autoCorrect: Boolean) { + this.autoCorrect = autoCorrect + updateInputFlags() + } + + fun setSpellCheck(spellCheck: Boolean) { + this.spellCheck = spellCheck + updateInputFlags() + } + + fun focusEditor() { + editor.requestFocus() + val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager + imm?.showSoftInput(editor, InputMethodManager.SHOW_IMPLICIT) + } + + fun blurEditor() { + editor.clearFocus() + val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager + imm?.hideSoftInputFromWindow(editor.windowToken, 0) + } + + fun setSelection(start: Int, end: Int) { + applySelection(start, end) + } + + private fun applySelection(start: Int, end: Int) { + val textLength = editor.text?.length ?: 0 + val safeStart = start.coerceIn(0, textLength) + val safeEnd = end.coerceIn(0, textLength) + editor.setSelection(safeStart, safeEnd) + } + + private fun updateInputFlags() { + var flags = + InputType.TYPE_CLASS_TEXT or + InputType.TYPE_TEXT_FLAG_MULTI_LINE or + InputType.TYPE_TEXT_FLAG_CAP_SENTENCES + flags = if (autoCorrect && spellCheck) { + flags or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT + } else { + flags or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS + } + editor.inputType = flags + } + + private fun applyLineHeight() { + if (desiredLineHeightPx <= 0) return + val fontHeight = editor.paint.fontMetricsInt.descent - editor.paint.fontMetricsInt.ascent + editor.setLineSpacing(max(0, desiredLineHeightPx - fontHeight).toFloat(), 1f) + } + + private fun currentSelectionPayload(): Map = + mapOf( + "start" to editor.selectionStart.coerceAtLeast(0), + "end" to editor.selectionEnd.coerceAtLeast(0), + ) + + private fun emitSelectionChange(start: Int, end: Int) { + onComposerSelectionChange( + mapOf( + "value" to editor.text.toString(), + "selection" to mapOf("start" to start, "end" to end), + "eventCount" to nativeEventCount, + ), + ) + } + + private fun emitContentSizeIfNeeded() { + val height = editor.layout?.height ?: editor.measuredHeight + val contentHeight = height + contentInsetVertical * 2 + if (contentHeight == lastContentHeight) return + lastContentHeight = contentHeight + onComposerContentSizeChange( + mapOf("height" to contentHeight / resources.displayMetrics.density), + ) + } + + private fun applyTokenSpans() { + val editable = editor.text ?: return + editable.getSpans( + 0, + editable.length, + ComposerChipSpan::class.java + ).forEach(editable::removeSpan) + tokens.forEach { token -> + if (token.start < 0 || token.end <= token.start || token.end > editable.length) return@forEach + val expectedSource = editable.substring(token.start, token.end) + if (expectedSource != token.source) return@forEach + editable.setSpan( + ComposerChipSpan( + token.label, + token.type == "skill", + chipTheme, + resources.displayMetrics.density + ), + token.start, + token.end, + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE, + ) + } + editor.invalidate() + } + + private fun parseColor(value: String, fallback: Int): Int = + try { + Color.parseColor(value) + } catch (_: Exception) { + fallback + } +} + +private data class ComposerToken( + val type: String, + val source: String, + val label: String, + val start: Int, + val end: Int +) + +private data class ComposerChipTheme( + val chipBackground: Int, + val chipBorder: Int, + val chipText: Int, + val skillBackground: Int, + val skillBorder: Int, + val skillText: Int +) { + companion object { + fun default() = ComposerChipTheme( + chipBackground = Color.rgb(238, 240, 243), + chipBorder = Color.rgb(210, 214, 220), + chipText = Color.rgb(35, 39, 45), + skillBackground = Color.rgb(233, 239, 255), + skillBorder = Color.rgb(185, 200, 245), + skillText = Color.rgb(45, 72, 155), + ) + } +} + +private class ComposerChipSpan( + private val label: String, + private val skill: Boolean, + private val theme: ComposerChipTheme, + density: Float +) : ReplacementSpan() { + private val horizontalPadding = 7f * density + private val verticalPadding = 2f * density + private val cornerRadius = 6f * density + private val borderWidth = density + + override fun getSize( + paint: Paint, + text: CharSequence, + start: Int, + end: Int, + fontMetrics: Paint.FontMetricsInt? + ): Int { + fontMetrics?.let { + val extra = verticalPadding.toInt() + val base = paint.fontMetricsInt + it.top = base.top - extra + it.ascent = base.ascent - extra + it.descent = base.descent + extra + it.bottom = base.bottom + extra + } + return (paint.measureText(label) + horizontalPadding * 2).toInt() + } + + override fun draw( + canvas: Canvas, + text: CharSequence, + start: Int, + end: Int, + x: Float, + top: Int, + y: Int, + bottom: Int, + paint: Paint + ) { + val width = paint.measureText(label) + horizontalPadding * 2 + val metrics = paint.fontMetrics + val rect = RectF( + x, + y + metrics.ascent - verticalPadding, + x + width, + y + metrics.descent + verticalPadding, + ) + val originalColor = paint.color + val originalStyle = paint.style + val originalStrokeWidth = paint.strokeWidth + + paint.color = if (skill) theme.skillBackground else theme.chipBackground + paint.style = Paint.Style.FILL + canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint) + paint.color = if (skill) theme.skillBorder else theme.chipBorder + paint.style = Paint.Style.STROKE + paint.strokeWidth = borderWidth + canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint) + paint.color = if (skill) theme.skillText else theme.chipText + paint.style = Paint.Style.FILL + canvas.drawText(label, x + horizontalPadding, y.toFloat(), paint) + + paint.color = originalColor + paint.style = originalStyle + paint.strokeWidth = originalStrokeWidth + } +} + +private fun parseTokens(value: String): List = try { + val array = org.json.JSONArray(value) + List(array.length()) { index -> + val token = array.getJSONObject(index) + ComposerToken( + type = token.optString("type"), + source = token.optString("source"), + label = token.optString("label"), + start = token.optInt("start"), + end = token.optInt("end"), + ) + } +} catch (_: Exception) { + emptyList() +} + +private class SelectionAwareEditText(context: Context) : EditText(context) { + var selectionListener: ((Int, Int) -> Unit)? = null + var pasteImagesListener: ((List) -> Unit)? = null + + override fun onSelectionChanged(selStart: Int, selEnd: Int) { + super.onSelectionChanged(selStart, selEnd) + selectionListener?.invoke(selStart, selEnd) + } + + override fun onTextContextMenuItem(id: Int): Boolean { + if (id == android.R.id.paste || id == android.R.id.pasteAsPlainText) { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager + val clip = clipboard?.primaryClip + val imageUris = buildList { + if (clip != null) { + for (index in 0 until clip.itemCount) { + clip.getItemAt(index).uri?.let { uri -> + val mimeType = context.contentResolver.getType(uri) + if (mimeType?.startsWith("image/") == true) add(uri.toString()) + } + } + } + } + if (imageUris.isNotEmpty()) { + pasteImagesListener?.invoke(imageUris) + return true + } + } + return super.onTextContextMenuItem(id) + } +} diff --git a/apps/mobile/modules/t3-composer-editor/expo-module.config.json b/apps/mobile/modules/t3-composer-editor/expo-module.config.json index 0d6384cd91..56fd899920 100644 --- a/apps/mobile/modules/t3-composer-editor/expo-module.config.json +++ b/apps/mobile/modules/t3-composer-editor/expo-module.config.json @@ -1,6 +1,9 @@ { - "platforms": ["apple"], + "platforms": ["apple", "android"], "apple": { "modules": ["T3ComposerEditorModule"] + }, + "android": { + "modules": ["expo.modules.t3composereditor.T3ComposerEditorModule"] } } diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift index d3b12770b0..a56619b7d4 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift @@ -47,6 +47,7 @@ public class T3ComposerEditorModule: Module { "onComposerSelectionChange", "onComposerFocus", "onComposerBlur", + "onComposerSubmit", "onComposerPasteImages", "onComposerContentSizeChange" ) diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift index afb3ba2d94..180da20300 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift @@ -63,6 +63,24 @@ private final class ComposerTextView: UITextView { var onPasteImages: (([String]) -> Void)? var onAttributedMutation: (() -> Void)? + var onSubmit: (() -> Void)? + + override var keyCommands: [UIKeyCommand]? { + var commands = super.keyCommands ?? [] + let submit = UIKeyCommand( + input: "\r", + modifierFlags: .command, + action: #selector(submitMessage(_:)) + ) + submit.discoverabilityTitle = "Send Message" + submit.wantsPriorityOverSystemBehavior = true + commands.append(submit) + return commands + } + + @objc private func submitMessage(_ sender: UIKeyCommand) { + onSubmit?() + } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { if action == #selector(paste(_:)) { @@ -282,7 +300,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate { skillText: "#a21caf", fileTint: "#737373" ) - private var fontFamily = "DMSans_400Regular" + private var fontFamily = "DMSans-Regular" private var fontSize: CGFloat = 14 private var lineHeight: CGFloat = 20 private var contentInsetVertical: CGFloat = 0 @@ -299,6 +317,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate { let onComposerSelectionChange = EventDispatcher() let onComposerFocus = EventDispatcher() let onComposerBlur = EventDispatcher() + let onComposerSubmit = EventDispatcher() let onComposerPasteImages = EventDispatcher() let onComposerContentSizeChange = EventDispatcher() @@ -320,6 +339,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate { textView.onAttributedMutation = { [weak self] in self?.emitTextChange() } + textView.onSubmit = { [weak self] in + self?.onComposerSubmit([:]) + } addSubview(textView) placeholderLabel.numberOfLines = 0 @@ -586,7 +608,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate { iconImage: UIImage?, style: ComposerChipStyle ) -> UIImage { - let font = UIFont(name: "DMSans_500Medium", size: max(12, fontSize - 2)) + let font = UIFont(name: "DMSans-Medium", size: max(12, fontSize - 2)) ?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium) let fallbackIcon = UIImage( systemName: iconName, diff --git a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx index 212c385124..e6a045b3cd 100644 --- a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx +++ b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx @@ -26,6 +26,15 @@ function nodeKey(node: MarkdownNode, index: number): string { return `${node.type}:${node.beg ?? index}:${node.end ?? index}`; } +/** Code inside markdown scales with the base text size (12pt at the default 15pt body). */ +function codeBlockFontSize(textStyle: NativeMarkdownTextStyle): number { + return Math.max(10, Math.round(textStyle.fontSize * 0.8)); +} + +function codeBlockLineHeight(textStyle: NativeMarkdownTextStyle): number { + return codeBlockFontSize(textStyle) + 6; +} + function nodeText(node: MarkdownNode): string { if (node.content !== undefined) { return node.content; @@ -161,8 +170,8 @@ function HighlightedCodeText(props: { style={{ color: props.textStyle.codeColor, fontFamily: "ui-monospace", - fontSize: 12, - lineHeight: 18, + fontSize: codeBlockFontSize(props.textStyle), + lineHeight: codeBlockLineHeight(props.textStyle), }} > {props.content} @@ -196,8 +205,8 @@ function HighlightedCodeText(props: { style={{ color: props.textStyle.codeColor, fontFamily: "ui-monospace", - fontSize: 12, - lineHeight: 18, + fontSize: codeBlockFontSize(props.textStyle), + lineHeight: codeBlockLineHeight(props.textStyle), }} > {keyedLines.map((line, lineIndex) => ( @@ -264,7 +273,7 @@ function NativeCodeBlock(props: { flex: 1, color: props.textStyle.mutedColor, fontFamily: "ui-monospace", - fontSize: 12, + fontSize: codeBlockFontSize(props.textStyle), }} > {languageLabel} diff --git a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx index c7a5a16d6f..994c8ce2ed 100644 --- a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx +++ b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx @@ -32,11 +32,25 @@ function runKeySignature(run: NativeMarkdownTextRun): string { ].join(":"); } +const DEFAULT_BODY_FONT_SIZE = 15; +const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const; + +function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number { + const index = Math.max(0, Math.min(5, headingLevel - 1)); + const configured = textStyle.headingFontSizes?.[index]; + if (typeof configured === "number" && Number.isFinite(configured)) { + return configured; + } + + const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE; + return Math.max(12, Math.round(DEFAULT_HEADING_FONT_SIZES[index] * scale)); +} + function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle { const isFile = run.fileIcon != null; const isSkill = run.skillName != null; const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1)); - const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15; + const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel); const isHeading = run.role === "heading"; const isCodeBlock = run.role === "code-block" || run.role === "code-language"; const hasParagraphStyle = run.headIndent !== undefined; @@ -88,7 +102,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle : isHeading ? headingFontSize : run.role === "code-language" - ? 11 + ? Math.max(10, Math.round(textStyle.fontSize * 0.73)) : run.code || isCodeBlock ? Math.max(12, textStyle.fontSize - 2) : textStyle.fontSize, @@ -98,9 +112,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle : run.role === "list-break" ? textStyle.lineHeight + (run.spacing ?? 0) : isHeading - ? Math.max(headingFontSize + 6, 20) + ? Math.max(headingFontSize + 6, textStyle.lineHeight + 2) : isCodeBlock - ? 18 + ? Math.max(16, textStyle.lineHeight - 2) : textStyle.lineHeight, fontStyle: run.italic ? "italic" : "normal", fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400", @@ -148,6 +162,9 @@ export function NativeMarkdownSelectableText(props: { // color-only child update can otherwise leave the previous appearance cached. const appearanceKey = [ colorScheme ?? "unspecified", + props.textStyle.fontSize, + props.textStyle.lineHeight, + props.textStyle.headingFontSizes?.join(","), props.textStyle.color, props.textStyle.strongColor, props.textStyle.mutedColor, diff --git a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts index 76c1402d3c..42cc3cd6fb 100644 --- a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts +++ b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts @@ -16,6 +16,7 @@ export interface NativeMarkdownTextStyle { readonly fontFamily: string; readonly headingFontFamily: string; readonly boldFontFamily: string; + readonly headingFontSizes?: ReadonlyArray; } export interface MarkdownHighlightedToken { diff --git a/apps/mobile/modules/t3-native-controls/android/build.gradle b/apps/mobile/modules/t3-native-controls/android/build.gradle new file mode 100644 index 0000000000..ba0622b7f0 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/build.gradle @@ -0,0 +1,19 @@ +apply plugin: 'com.android.library' +apply plugin: 'org.jetbrains.kotlin.android' + +group = 'com.t3tools.nativecontrols' +version = '0.0.0' + +android { + namespace 'expo.modules.t3nativecontrols' + compileSdk rootProject.ext.compileSdkVersion + + defaultConfig { + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + } +} + +dependencies { + implementation project(':expo-modules-core') +} diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/AndroidManifest.xml b/apps/mobile/modules/t3-native-controls/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..94cbbcfc39 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3HeaderButtonView.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3HeaderButtonView.kt new file mode 100644 index 0000000000..47db92d92a --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3HeaderButtonView.kt @@ -0,0 +1,97 @@ +package expo.modules.t3nativecontrols + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.view.View +import expo.modules.kotlin.AppContext +import expo.modules.kotlin.viewevent.EventDispatcher +import expo.modules.kotlin.views.ExpoView + +class T3HeaderButtonView(context: Context, appContext: AppContext) : ExpoView(context, appContext) { + private val iconView = HeaderIconView(context) + private val onTriggered by EventDispatcher() + + init { + isClickable = true + isFocusable = true + setOnClickListener { + onTriggered(emptyMap()) + } + addView(iconView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + } + + fun setLabel(label: String) { + contentDescription = label + } + + fun setSystemImage(systemImage: String) { + iconView.systemImage = systemImage + } +} + +private class HeaderIconView(context: Context) : View(context) { + private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.parseColor("#6B7280") + strokeCap = Paint.Cap.ROUND + strokeJoin = Paint.Join.ROUND + strokeWidth = 3f * resources.displayMetrics.density + style = Paint.Style.STROKE + } + + var systemImage: String = "gearshape" + set(value) { + field = value + invalidate() + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + val cx = width / 2f + val cy = height / 2f + val size = minOf(width, height).toFloat() + if (systemImage == "square.and.pencil") { + drawNewTask(canvas, cx, cy, size) + } else { + drawSettings(canvas, cx, cy, size) + } + } + + private fun drawSettings(canvas: Canvas, cx: Float, cy: Float, size: Float) { + val radius = size * 0.12f + canvas.drawCircle(cx, cy, radius, paint) + for (index in 0 until 8) { + val angle = Math.PI * index / 4.0 + val inner = size * 0.19f + val outer = size * 0.27f + val sx = cx + kotlin.math.cos(angle).toFloat() * inner + val sy = cy + kotlin.math.sin(angle).toFloat() * inner + val ex = cx + kotlin.math.cos(angle).toFloat() * outer + val ey = cy + kotlin.math.sin(angle).toFloat() * outer + canvas.drawLine(sx, sy, ex, ey, paint) + } + } + + private fun drawNewTask(canvas: Canvas, cx: Float, cy: Float, size: Float) { + val left = cx - size * 0.2f + val top = cy - size * 0.16f + val right = cx + size * 0.14f + val bottom = cy + size * 0.2f + canvas.drawRoundRect(left, top, right, bottom, size * 0.04f, size * 0.04f, paint) + canvas.drawLine( + cx - size * 0.02f, + cy + size * 0.13f, + cx + size * 0.24f, + cy - size * 0.13f, + paint + ) + canvas.drawLine( + cx + size * 0.17f, + cy - size * 0.2f, + cx + size * 0.24f, + cy - size * 0.13f, + paint + ) + } +} diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt new file mode 100644 index 0000000000..b15a1cd442 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt @@ -0,0 +1,47 @@ +package expo.modules.t3nativecontrols + +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition + +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) + } + Prop("systemImage") { view: T3HeaderButtonView, systemImage: String -> + view.setSystemImage(systemImage) + } + + Events("onTriggered") + } + } +} diff --git a/apps/mobile/modules/t3-native-controls/expo-module.config.json b/apps/mobile/modules/t3-native-controls/expo-module.config.json new file mode 100644 index 0000000000..d9a77f14e2 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/expo-module.config.json @@ -0,0 +1,9 @@ +{ + "platforms": ["apple", "android"], + "apple": { + "modules": ["T3NativeControlsModule", "T3KeyboardCommandsModule"] + }, + "android": { + "modules": ["expo.modules.t3nativecontrols.T3NativeControlsModule"] + } +} diff --git a/apps/mobile/modules/t3-native-controls/ios/T3HeaderButtonView.swift b/apps/mobile/modules/t3-native-controls/ios/T3HeaderButtonView.swift new file mode 100644 index 0000000000..7b7f9db670 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/ios/T3HeaderButtonView.swift @@ -0,0 +1,62 @@ +import ExpoModulesCore +import UIKit + +public final class T3HeaderButtonView: ExpoView { + private static let size: CGFloat = 44 + private static let symbolSize: CGFloat = 18 + + private let button = UIButton(type: .system) + private var systemImage = "circle" + + let onTriggered = EventDispatcher() + + public required init(appContext: AppContext? = nil) { + super.init(appContext: appContext) + + isAccessibilityElement = false + button.frame = bounds + button.autoresizingMask = [.flexibleWidth, .flexibleHeight] + button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered) + addSubview(button) + applyConfiguration() + } + + public override var intrinsicContentSize: CGSize { + CGSize(width: Self.size, height: Self.size) + } + + public func setLabel(_ label: String) { + button.accessibilityLabel = label + } + + public func setSystemImage(_ systemImage: String) { + guard self.systemImage != systemImage else { + return + } + self.systemImage = systemImage + applyConfiguration() + } + + private func applyConfiguration() { + var configuration: UIButton.Configuration + if #available(iOS 26.0, *) { + configuration = .glass() + configuration.cornerStyle = .capsule + } else { + configuration = .plain() + } + + configuration.baseForegroundColor = .label + configuration.contentInsets = .zero + configuration.image = UIImage(systemName: systemImage) + configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration( + pointSize: Self.symbolSize, + weight: .regular + ) + button.configuration = configuration + } + + @objc private func handlePress() { + onTriggered() + } +} diff --git a/apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift new file mode 100644 index 0000000000..ea572cc7a0 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift @@ -0,0 +1,131 @@ +import ExpoModulesCore +import UIKit + +public final class T3KeyboardCommandsModule: Module { + public func definition() -> ModuleDefinition { + Name("T3KeyboardCommands") + + View(T3KeyboardCommandsView.self) { + Prop("enabledCommands") { (view: T3KeyboardCommandsView, commands: [String]) in + view.setEnabledCommands(commands) + } + Events("onCommand") + } + } +} + +public final class T3KeyboardCommandsView: ExpoView { + let onCommand = EventDispatcher() + private var enabledCommands = Set() + + public override var canBecomeFirstResponder: Bool { true } + + public override var keyCommands: [UIKeyCommand]? { + [ + enabledCommand("newTask", input: "n", modifiers: .command, action: #selector(newTask), title: "New Task"), + enabledCommand("focusSearch", input: "f", modifiers: .command, action: #selector(focusSearch), title: "Find"), + enabledCommand("focusSearch", input: "k", modifiers: .command, action: #selector(focusSearch), title: "Focus Search"), + enabledCommand("back", input: "[", modifiers: .command, action: #selector(goBack), title: "Back"), + enabledCommand("files", input: "f", modifiers: [.command, .shift], action: #selector(openFiles), title: "Open Files"), + enabledCommand("terminal", input: "t", modifiers: [.command, .shift], action: #selector(openTerminal), title: "Open Terminal"), + enabledCommand("review", input: "r", modifiers: [.command, .shift], action: #selector(openReview), title: "Open Review"), + enabledCommand("toggleSidebar", input: "\\", modifiers: .command, action: #selector(handleToggleSidebar), title: "Toggle Sidebar"), + ].compactMap { $0 } + } + + func setEnabledCommands(_ commands: [String]) { + enabledCommands = Set(commands) + if isFirstResponder { + resignFirstResponder() + } + reclaimFirstResponderIfAvailable() + } + + private func enabledCommand( + _ identifier: String, + input: String, + modifiers: UIKeyModifierFlags, + action: Selector, + title: String + ) -> UIKeyCommand? { + guard enabledCommands.contains(identifier) else { return nil } + return command(input, modifiers: modifiers, action: action, title: title) + } + + public required init(appContext: AppContext? = nil) { + super.init(appContext: appContext) + NotificationCenter.default.addObserver( + self, + selector: #selector(reclaimFirstResponderIfAvailable), + name: UITextView.textDidEndEditingNotification, + object: nil + ) + NotificationCenter.default.addObserver( + self, + selector: #selector(reclaimFirstResponderIfAvailable), + name: UITextField.textDidEndEditingNotification, + object: nil + ) + NotificationCenter.default.addObserver( + self, + selector: #selector(reclaimFirstResponderIfAvailable), + name: UIApplication.didBecomeActiveNotification, + object: nil + ) + } + + deinit { + NotificationCenter.default.removeObserver(self) + } + + public override func didMoveToWindow() { + super.didMoveToWindow() + reclaimFirstResponderIfAvailable() + } + + public override func layoutSubviews() { + super.layoutSubviews() + reclaimFirstResponderIfAvailable() + } + + private func command( + _ input: String, + modifiers: UIKeyModifierFlags, + action: Selector, + title: String + ) -> UIKeyCommand { + let command = UIKeyCommand(input: input, modifierFlags: modifiers, action: action) + command.discoverabilityTitle = title + command.wantsPriorityOverSystemBehavior = true + return command + } + + @objc private func newTask() { emit("newTask") } + @objc private func focusSearch() { emit("focusSearch") } + @objc private func goBack() { emit("back") } + @objc private func openFiles() { emit("files") } + @objc private func openTerminal() { emit("terminal") } + @objc private func openReview() { emit("review") } + @objc private func handleToggleSidebar() { emit("toggleSidebar") } + + private func emit(_ command: String) { + onCommand(["command": command]) + } + + @objc private func reclaimFirstResponderIfAvailable() { + DispatchQueue.main.async { [weak self] in + guard let self, self.window?.t3FirstResponder == nil else { return } + self.becomeFirstResponder() + } + } +} + +private extension UIView { + var t3FirstResponder: UIResponder? { + if isFirstResponder { return self } + for subview in subviews { + if let responder = subview.t3FirstResponder { return responder } + } + return nil + } +} diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec new file mode 100644 index 0000000000..29735c301c --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec @@ -0,0 +1,19 @@ +Pod::Spec.new do |s| + s.name = 'T3NativeControls' + s.version = '1.0.0' + s.summary = 'Native UIKit controls for T3 Code mobile.' + s.description = 'UIKit-backed controls that match native iOS navigation chrome.' + s.author = 'T3 Tools' + s.homepage = 'https://t3tools.com' + s.platforms = { + :ios => '18.0', + } + s.source = { :path => '.' } + s.static_framework = true + + s.dependency 'ExpoModulesCore' + s.pod_target_xcconfig = { + 'DEFINES_MODULE' => 'YES', + } + s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}' +end diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift new file mode 100644 index 0000000000..7781b164a2 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift @@ -0,0 +1,57 @@ +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) + } + Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in + view.setSystemImage(systemImage) + } + + Events("onTriggered") + } + } +} diff --git a/apps/mobile/modules/t3-review-diff/android/build.gradle b/apps/mobile/modules/t3-review-diff/android/build.gradle new file mode 100644 index 0000000000..22bb070b3b --- /dev/null +++ b/apps/mobile/modules/t3-review-diff/android/build.gradle @@ -0,0 +1,19 @@ +apply plugin: 'com.android.library' +apply plugin: 'org.jetbrains.kotlin.android' + +group = 'com.t3tools.reviewdiff' +version = '0.0.0' + +android { + namespace 'expo.modules.t3reviewdiff' + compileSdk rootProject.ext.compileSdkVersion + + defaultConfig { + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + } +} + +dependencies { + implementation project(':expo-modules-core') +} diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/AndroidManifest.xml b/apps/mobile/modules/t3-review-diff/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..94cbbcfc39 --- /dev/null +++ b/apps/mobile/modules/t3-review-diff/android/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt new file mode 100644 index 0000000000..6782e6894d --- /dev/null +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt @@ -0,0 +1,315 @@ +package expo.modules.t3reviewdiff + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.LinearGradient +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RectF +import android.graphics.Shader +import android.graphics.Typeface +import kotlin.math.max +import kotlin.math.min + +internal class ReviewDiffCanvasDrawing(context: Context) { + private val density = context.resources.displayMetrics.density + var theme: DiffTheme = DiffTheme.fallback("light") + + val backgroundPaint = Paint() + val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG) + val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + hinting = Paint.HINTING_ON + isSubpixelText = false + clearShadowLayer() + } + val uiPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + hinting = Paint.HINTING_ON + isSubpixelText = false + clearShadowLayer() + } + + private val italicCodeTypeface by lazy { + Typeface.create(ReviewDiffTypefaces.regular, Typeface.ITALIC) + } + private val boldItalicCodeTypeface by lazy { + Typeface.create(ReviewDiffTypefaces.bold, Typeface.ITALIC) + } + + init { + textPaint.typeface = ReviewDiffTypefaces.regular + uiPaint.typeface = Typeface.DEFAULT_BOLD + } + + fun fileHeaderChevronRect(top: Int, bottom: Int, style: DiffStyle): RectF { + val centerY = (top + bottom) / 2f + val left = style.fileHeaderHorizontalPaddingPx + return RectF(left, centerY - 10f * density, left + 20f * density, centerY + 10f * density) + } + + fun fileHeaderIconRect(top: Int, bottom: Int, style: DiffStyle): RectF { + val chevron = fileHeaderChevronRect(top, bottom, style) + return RectF( + chevron.right + 8f * density, + chevron.top, + chevron.right + 28f * density, + chevron.bottom, + ) + } + + fun fileHeaderCheckboxRect(top: Int, bottom: Int, width: Int, style: DiffStyle): RectF { + val centerY = (top + bottom) / 2f + val right = width - style.fileHeaderHorizontalPaddingPx + return RectF( + right - 20f * density, + centerY - 10f * density, + right, + centerY + 10f * density, + ) + } + + fun drawDisclosureChevron( + canvas: Canvas, + rect: RectF, + color: Int, + collapsed: Boolean + ) { + borderPaint.style = Paint.Style.STROKE + borderPaint.color = color + borderPaint.strokeWidth = 2f * density + borderPaint.strokeCap = Paint.Cap.ROUND + borderPaint.strokeJoin = Paint.Join.ROUND + val path = Path() + if (collapsed) { + path.moveTo(rect.left + rect.width() * 0.4f, rect.top + rect.height() * 0.28f) + path.lineTo(rect.left + rect.width() * 0.6f, rect.centerY()) + path.lineTo(rect.left + rect.width() * 0.4f, rect.bottom - rect.height() * 0.28f) + } else { + path.moveTo(rect.left + rect.width() * 0.28f, rect.top + rect.height() * 0.42f) + path.lineTo(rect.centerX(), rect.top + rect.height() * 0.62f) + path.lineTo(rect.right - rect.width() * 0.28f, rect.top + rect.height() * 0.42f) + } + canvas.drawPath(path, borderPaint) + borderPaint.style = Paint.Style.FILL + } + + fun drawFileIcon(canvas: Canvas, rect: RectF, changeType: String) { + val color = when (changeType) { + "new" -> theme.addText + "deleted" -> theme.deleteText + else -> theme.hunkText + } + borderPaint.style = Paint.Style.STROKE + borderPaint.color = color + borderPaint.strokeWidth = 2f * density + canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint) + + if (changeType == "rename-pure" || changeType == "rename-changed" || changeType == "renamed") { + drawRenameChevronIcon(canvas, rect, color) + } else { + backgroundPaint.color = color + canvas.drawCircle(rect.centerX(), rect.centerY(), 3f * density, backgroundPaint) + } + borderPaint.style = Paint.Style.FILL + } + + fun drawViewedCheckbox(canvas: Canvas, rect: RectF, checked: Boolean) { + if (checked) { + backgroundPaint.color = theme.hunkText + canvas.drawRoundRect(rect, 6f * density, 6f * density, backgroundPaint) + } + borderPaint.style = Paint.Style.STROKE + borderPaint.color = if (checked) theme.hunkText else theme.mutedText + borderPaint.strokeWidth = 1.8f * density + canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint) + if (checked) { + borderPaint.color = theme.background + borderPaint.strokeWidth = 2f * density + borderPaint.strokeCap = Paint.Cap.ROUND + borderPaint.strokeJoin = Paint.Join.ROUND + val path = Path().apply { + moveTo(rect.left + rect.width() * 0.28f, rect.centerY()) + lineTo(rect.left + rect.width() * 0.44f, rect.bottom - rect.height() * 0.3f) + lineTo(rect.right - rect.width() * 0.25f, rect.top + rect.height() * 0.3f) + } + canvas.drawPath(path, borderPaint) + } + borderPaint.style = Paint.Style.FILL + } + + fun drawNoticeIcon(canvas: Canvas, rect: RectF, color: Int) { + borderPaint.style = Paint.Style.STROKE + borderPaint.color = color + borderPaint.strokeWidth = 1.7f * density + borderPaint.strokeCap = Paint.Cap.ROUND + canvas.drawOval(rect, borderPaint) + canvas.drawLine( + rect.centerX(), + rect.top + rect.height() * 0.3f, + rect.centerX(), + rect.top + rect.height() * 0.58f, + borderPaint, + ) + borderPaint.style = Paint.Style.FILL + canvas.drawCircle(rect.centerX(), rect.bottom - rect.height() * 0.24f, density, borderPaint) + } + + fun configureUiPaint(paint: Paint, color: Int, size: Float, weight: String) { + paint.typeface = if (isBoldFontWeight(weight)) Typeface.DEFAULT_BOLD else Typeface.DEFAULT + configureTextPaint(paint, color, size) + } + + fun configureMonospacePaint(color: Int, size: Float, weight: String) { + textPaint.typeface = ReviewDiffTypefaces.forWeight(weight) + configureTextPaint(textPaint, color, size) + } + + fun configureCodePaint(color: Int, fontStyle: Int, style: DiffStyle) { + val tokenBold = fontStyle and 2 != 0 + val italic = fontStyle and 1 != 0 + textPaint.typeface = when { + tokenBold && italic -> boldItalicCodeTypeface + tokenBold -> ReviewDiffTypefaces.bold + italic -> italicCodeTypeface + else -> ReviewDiffTypefaces.forWeight(style.codeFontWeight) + } + configureTextPaint(textPaint, color, style.codeFontSizePx) + textPaint.isUnderlineText = fontStyle and 4 != 0 + } + + fun lineNumberColor(change: String): Int = when (change) { + "add" -> theme.addText + "delete" -> theme.deleteText + else -> theme.mutedText + } + + fun drawDeleteStripes( + canvas: Canvas, + top: Int, + bottom: Int, + width: Float, + color: Int + ) { + backgroundPaint.color = color + var y = top.toFloat() + while (y < bottom) { + canvas.drawRect(0f, y, width, min(bottom.toFloat(), y + density), backgroundPaint) + y += 2f * density + } + } + + fun drawWordDiffRanges( + canvas: Canvas, + row: DiffRow, + codeX: Float, + top: Int, + bottom: Int + ) { + if (row.wordDiffRanges.isEmpty() || (row.change != "add" && row.change != "delete")) return + val color = if (row.change == "add") theme.addBar else theme.deleteBar + backgroundPaint.color = withAlpha(color, 71) + val characterWidth = textPaint.measureText("M") + val fontHeight = textPaint.fontMetrics.run { descent - ascent } + val highlightHeight = max(4f * density, min(bottom - top - 4f * density, fontHeight)) + val highlightTop = (top + bottom - highlightHeight) / 2f + row.wordDiffRanges.forEach { range -> + val left = codeX + range.start * characterWidth + val right = max(left + 2f * density, codeX + range.end * characterWidth) + canvas.drawRoundRect( + RectF(left, highlightTop, right, highlightTop + highlightHeight), + 3f * density, + 3f * density, + backgroundPaint, + ) + } + } + + fun drawFileHeaderPathScrollFades( + canvas: Canvas, + pathRect: RectF, + horizontalOffset: Int, + maxOffset: Int + ) { + if (maxOffset <= 0 || pathRect.width() <= 0f) return + val fadeWidth = min(28f * density, pathRect.width() / 3f) + if (horizontalOffset > 0) { + drawHorizontalFade( + canvas, + RectF(pathRect.left, pathRect.top, pathRect.left + fadeWidth, pathRect.bottom), + fadesToRight = false, + ) + } + if (horizontalOffset < maxOffset) { + drawHorizontalFade( + canvas, + RectF(pathRect.right - fadeWidth, pathRect.top, pathRect.right, pathRect.bottom), + fadesToRight = true, + ) + } + } + + private fun drawRenameChevronIcon(canvas: Canvas, rect: RectF, color: Int) { + borderPaint.style = Paint.Style.STROKE + borderPaint.color = color + borderPaint.strokeWidth = 1.8f * density + borderPaint.strokeCap = Paint.Cap.ROUND + borderPaint.strokeJoin = Paint.Join.ROUND + val chevronWidth = 3.6f * density + val chevronHeight = 8f * density + val gap = 2.4f * density + val startX = rect.centerX() - (chevronWidth * 2f + gap) / 2f + val path = Path() + for (x in listOf(startX, startX + chevronWidth + gap)) { + path.moveTo(x, rect.centerY() - chevronHeight / 2f) + path.lineTo(x + chevronWidth, rect.centerY()) + path.lineTo(x, rect.centerY() + chevronHeight / 2f) + } + canvas.drawPath(path, borderPaint) + } + + private fun configureTextPaint(paint: Paint, color: Int, size: Float) { + paint.textSize = size + paint.color = color + paint.style = Paint.Style.FILL + paint.textAlign = Paint.Align.LEFT + paint.isUnderlineText = false + paint.isFakeBoldText = false + paint.clearShadowLayer() + } + + private fun drawHorizontalFade(canvas: Canvas, rect: RectF, fadesToRight: Boolean) { + val opaque = theme.headerBackground + val transparent = Color.argb(0, Color.red(opaque), Color.green(opaque), Color.blue(opaque)) + backgroundPaint.shader = LinearGradient( + rect.left, + rect.centerY(), + rect.right, + rect.centerY(), + if (fadesToRight) transparent else opaque, + if (fadesToRight) opaque else transparent, + Shader.TileMode.CLAMP, + ) + canvas.drawRect(rect, backgroundPaint) + backgroundPaint.shader = null + } + + private fun isBoldFontWeight(weight: String): Boolean = when (weight.lowercase()) { + "medium", "semibold", "semi-bold", "bold", "heavy", "black" -> true + else -> false + } + + private fun withAlpha(color: Int, alpha: Int): Int = + Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color)) +} + +private object ReviewDiffTypefaces { + val regular: Typeface = Typeface.create("monospace", Typeface.NORMAL) + private val medium: Typeface = Typeface.create("monospace-medium", Typeface.NORMAL) + val bold: Typeface = Typeface.create("monospace", Typeface.BOLD) + + fun forWeight(weight: String): Typeface = when (weight.lowercase()) { + "medium", "semibold", "semi-bold" -> medium + "bold", "heavy", "black" -> bold + else -> regular + } +} diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt new file mode 100644 index 0000000000..ee40275ede --- /dev/null +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt @@ -0,0 +1,78 @@ +package expo.modules.t3reviewdiff + +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition + +class T3ReviewDiffModule : Module() { + override fun definition() = ModuleDefinition { + Name("T3ReviewDiffSurface") + + View(T3ReviewDiffView::class) { + Prop("tokensResetKey") { view: T3ReviewDiffView, tokensResetKey: String -> + view.setTokensResetKey(tokensResetKey) + } + Prop("contentResetKey") { view: T3ReviewDiffView, contentResetKey: String -> + view.setContentResetKey(contentResetKey) + } + Prop("collapsedFileIdsJson") { view: T3ReviewDiffView, collapsedFileIdsJson: String -> + view.setCollapsedFileIdsJson(collapsedFileIdsJson) + } + Prop("viewedFileIdsJson") { view: T3ReviewDiffView, viewedFileIdsJson: String -> + view.setViewedFileIdsJson(viewedFileIdsJson) + } + Prop("selectedRowIdsJson") { view: T3ReviewDiffView, selectedRowIdsJson: String -> + view.setSelectedRowIdsJson(selectedRowIdsJson) + } + Prop("collapsedCommentIdsJson") { view: T3ReviewDiffView, collapsedCommentIdsJson: String -> + view.setCollapsedCommentIdsJson(collapsedCommentIdsJson) + } + Prop("appearanceScheme") { view: T3ReviewDiffView, appearanceScheme: String -> + view.setAppearanceScheme(appearanceScheme) + } + Prop("themeJson") { view: T3ReviewDiffView, themeJson: String -> + view.setThemeJson(themeJson) + } + Prop("styleJson") { view: T3ReviewDiffView, styleJson: String -> + view.setStyleJson(styleJson) + } + Prop("rowHeight") { view: T3ReviewDiffView, rowHeight: Double -> + view.setRowHeight(rowHeight.toFloat()) + } + Prop("contentWidth") { view: T3ReviewDiffView, contentWidth: Double -> + view.setContentWidth(contentWidth.toFloat()) + } + Prop("initialRowIndex") { view: T3ReviewDiffView, initialRowIndex: Double -> + view.setInitialRowIndex(initialRowIndex) + } + + Events( + "onDebug", + "onVisibleFileChange", + "onToggleFile", + "onToggleViewedFile", + "onPressLine", + "onToggleComment", + ) + + AsyncFunction("scrollToFile") { view: T3ReviewDiffView, fileId: String, animated: Boolean -> + view.scrollToFile(fileId, animated) + } + AsyncFunction("scrollToTop") { view: T3ReviewDiffView, animated: Boolean -> + view.scrollToTop(animated) + } + AsyncFunction("setRowsJson") { view: T3ReviewDiffView, rowsJson: String -> + view.setRowsJson(rowsJson) + } + AsyncFunction("setTokensJson") { view: T3ReviewDiffView, tokensJson: String -> + view.setTokensJson(tokensJson) + } + AsyncFunction("setTokensPatchJson") { view: T3ReviewDiffView, tokensPatchJson: String -> + view.setTokensPatchJson(tokensPatchJson) + } + + OnViewDestroys { view: T3ReviewDiffView -> + view.cleanup() + } + } + } +} diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt new file mode 100644 index 0000000000..97e9f696db --- /dev/null +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -0,0 +1,1429 @@ +package expo.modules.t3reviewdiff + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.RectF +import android.view.GestureDetector +import android.view.MotionEvent +import android.view.VelocityTracker +import android.view.View +import android.view.ViewGroup +import android.view.ViewConfiguration +import android.widget.OverScroller +import expo.modules.kotlin.AppContext +import expo.modules.kotlin.viewevent.EventDispatcher +import expo.modules.kotlin.views.ExpoView +import org.json.JSONArray +import org.json.JSONObject +import java.util.concurrent.Executors +import kotlin.math.abs +import kotlin.math.ceil +import kotlin.math.max +import kotlin.math.min + +class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(context, appContext) { + private val canvasView = DiffCanvasView(context) + private val onDebug by EventDispatcher() + private val onVisibleFileChange by EventDispatcher() + private val onToggleFile by EventDispatcher() + private val onToggleViewedFile by EventDispatcher() + private val onPressLine by EventDispatcher() + private val onToggleComment by EventDispatcher() + private var rows: List = emptyList() + private var visibleRows: List = emptyList() + private var collapsedFileIds: Set = emptySet() + private var viewedFileIds: Set = emptySet() + private var selectedRowIds: Set = emptySet() + private var collapsedCommentIds: Set = emptySet() + private var initialRowIndex = 0 + private var pendingInitialScroll = false + private var lastVisibleFileId: String? = null + private var tokensResetKey = "" + private var contentResetKey = "" + private var rowsDecodeGeneration = 0 + private var tokensDecodeGeneration = 0 + private val payloadDecodeExecutor = Executors.newSingleThreadExecutor() + private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop + private val minimumFlingVelocity = ViewConfiguration.get(context).scaledMinimumFlingVelocity + private val verticalScroller = OverScroller(context) + private val horizontalScroller = OverScroller(context) + private var dragAxis: DragAxis? = null + private var horizontalDragTarget: HorizontalPanTarget? = null + private var lastTouchX = 0f + private var lastTouchY = 0f + private var velocityTracker: VelocityTracker? = null + + init { + canvasView.onRowTap = { row, gesture, target -> handleRowTap(row, gesture, target) } + canvasView.onVisibleRowsChanged = { first, last -> + onDebug( + mapOf( + "message" to "visible-range", + "firstRowIndex" to first, + "lastRowIndex" to last, + ), + ) + emitVisibleFile(first) + } + + addView( + canvasView, + LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT), + ) + } + + fun setTokensResetKey(value: String) { + if (tokensResetKey == value) return + tokensResetKey = value + canvasView.tokensByRowId = emptyMap() + } + + fun setContentResetKey(value: String) { + if (contentResetKey == value) return + contentResetKey = value + tokensDecodeGeneration += 1 + canvasView.tokensByRowId = emptyMap() + lastVisibleFileId = null + pendingInitialScroll = true + canvasView.setVerticalOffset(0) + canvasView.resetHorizontalOffsets() + applyPendingInitialScroll() + } + + fun setCollapsedFileIdsJson(value: String) { + collapsedFileIds = parseStringSet(value) + canvasView.collapsedFileIds = collapsedFileIds + rebuildVisibleRows() + } + + fun setViewedFileIdsJson(value: String) { + viewedFileIds = parseStringSet(value) + canvasView.viewedFileIds = viewedFileIds + } + + fun setSelectedRowIdsJson(value: String) { + selectedRowIds = parseStringSet(value) + canvasView.selectedRowIds = selectedRowIds + } + + fun setCollapsedCommentIdsJson(value: String) { + collapsedCommentIds = parseStringSet(value) + canvasView.collapsedCommentIds = collapsedCommentIds + rebuildVisibleRows() + } + + fun setAppearanceScheme(value: String) { + canvasView.theme = DiffTheme.fallback(value) + } + + fun setThemeJson(value: String) { + canvasView.theme = DiffTheme.fromJson(value, canvasView.theme) + } + + fun setStyleJson(value: String) { + canvasView.style = DiffStyle.fromJson(value, canvasView.style, resources.displayMetrics.density) + } + + fun setRowHeight(value: Float) { + canvasView.style = canvasView.style.copy(rowHeightPx = dp(value)) + } + + fun setContentWidth(value: Float) { + canvasView.contentWidthPx = max(width, dp(value).toInt()) + } + + fun setInitialRowIndex(value: Double) { + initialRowIndex = value.toInt().coerceAtLeast(0) + pendingInitialScroll = true + applyPendingInitialScroll() + } + + fun setRowsJson(value: String) { + rowsDecodeGeneration += 1 + val generation = rowsDecodeGeneration + payloadDecodeExecutor.execute { + val decodedRows = parseRows(value) + post { + if (generation != rowsDecodeGeneration) return@post + rows = decodedRows + lastVisibleFileId = null + rebuildVisibleRows() + } + } + } + + fun setTokensJson(value: String) { + tokensDecodeGeneration += 1 + val generation = tokensDecodeGeneration + payloadDecodeExecutor.execute { + val decodedTokens = parseTokensObject(value) + post { + if (generation != tokensDecodeGeneration) return@post + canvasView.tokensByRowId = decodedTokens + } + } + } + + fun setTokensPatchJson(value: String) { + payloadDecodeExecutor.execute { + try { + val payload = JSONObject(value) + val resetKey = payload.optString("resetKey") + val decodedTokens = parseTokensObject( + payload.optJSONObject("tokensByRowId") ?: JSONObject(), + ) + post { + if (resetKey.isNotEmpty() && resetKey != tokensResetKey) return@post + if (decodedTokens.isNotEmpty()) { + canvasView.tokensByRowId = canvasView.tokensByRowId + decodedTokens + } + } + } catch (_: Exception) { + } + } + } + + fun cleanup() { + payloadDecodeExecutor.shutdownNow() + } + + fun scrollToFile(fileId: String, animated: Boolean) { + val index = visibleRows.indexOfFirst { it.kind == "file" && it.resolvedFileId == fileId } + if (index < 0) return + scrollToY(canvasView.rowTop(index), animated) + } + + fun scrollToTop(animated: Boolean) { + scrollToY(0, animated) + } + + @Suppress("NestedBlockDepth", "ReturnCount") + override fun onInterceptTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + verticalScroller.forceFinished(true) + horizontalScroller.forceFinished(true) + dragAxis = null + horizontalDragTarget = canvasView.horizontalPanTarget(event.y) + lastTouchX = event.x + lastTouchY = event.y + parent?.requestDisallowInterceptTouchEvent(true) + return false + } + MotionEvent.ACTION_MOVE -> { + if (dragAxis == null) { + val deltaX = event.x - lastTouchX + val deltaY = event.y - lastTouchY + if (max(abs(deltaX), abs(deltaY)) > touchSlop) { + dragAxis = if (abs(deltaY) >= abs(deltaX)) { + DragAxis.VERTICAL + } else { + horizontalDragTarget + ?.takeIf { canvasView.maxHorizontalOffset(it) > 0 } + ?.let { DragAxis.HORIZONTAL } + } + } + } + return dragAxis != null + } + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> return dragAxis != null + } + return false + } + + override fun dispatchTouchEvent(event: MotionEvent): Boolean { + if (event.actionMasked == MotionEvent.ACTION_DOWN) { + velocityTracker?.recycle() + velocityTracker = VelocityTracker.obtain() + } + velocityTracker?.addMovement(event) + val handled = super.dispatchTouchEvent(event) + if ( + ( + event.actionMasked == MotionEvent.ACTION_UP || + event.actionMasked == MotionEvent.ACTION_CANCEL + ) && + dragAxis == null + ) { + velocityTracker?.recycle() + velocityTracker = null + horizontalDragTarget = null + parent?.requestDisallowInterceptTouchEvent(false) + } + return handled + } + + @Suppress("NestedBlockDepth") + override fun onTouchEvent(event: MotionEvent): Boolean { + val axis = dragAxis ?: return false + when (event.actionMasked) { + MotionEvent.ACTION_MOVE -> { + val deltaX = (lastTouchX - event.x).toInt() + val deltaY = (lastTouchY - event.y).toInt() + if (axis == DragAxis.VERTICAL) { + canvasView.scrollByVertical(deltaY) + } else { + horizontalDragTarget?.let { canvasView.scrollByHorizontal(deltaX, it) } + } + lastTouchX = event.x + lastTouchY = event.y + } + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + if (event.actionMasked == MotionEvent.ACTION_UP) { + velocityTracker?.computeCurrentVelocity(1000) + if (axis == DragAxis.VERTICAL) { + val velocity = -(velocityTracker?.yVelocity ?: 0f).toInt() + if (abs(velocity) >= minimumFlingVelocity) { + verticalScroller.fling( + 0, + canvasView.verticalOffset(), + 0, + velocity, + 0, + 0, + 0, + canvasView.maxVerticalOffset(), + ) + postInvalidateOnAnimation() + } + } else if (horizontalDragTarget?.kind == HorizontalPanKind.CODE) { + val velocity = -(velocityTracker?.xVelocity ?: 0f).toInt() + if (abs(velocity) >= minimumFlingVelocity) { + horizontalScroller.fling( + canvasView.horizontalOffset(), + 0, + velocity, + 0, + 0, + canvasView.maxHorizontalOffset(), + 0, + 0, + ) + postInvalidateOnAnimation() + } + } + } + dragAxis = null + horizontalDragTarget = null + velocityTracker?.recycle() + velocityTracker = null + parent?.requestDisallowInterceptTouchEvent(false) + } + } + return true + } + + override fun computeScroll() { + var animating = false + if (verticalScroller.computeScrollOffset()) { + canvasView.setVerticalOffset(verticalScroller.currY) + animating = true + } + if (horizontalScroller.computeScrollOffset()) { + canvasView.setHorizontalOffset(horizontalScroller.currX) + animating = true + } + if (animating) { + postInvalidateOnAnimation() + } + } + + private fun rebuildVisibleRows() { + val filtered = ArrayList(rows.size) + var currentFileCollapsed = false + rows.forEach { row -> + if (row.kind == "file") { + currentFileCollapsed = collapsedFileIds.contains(row.resolvedFileId) + filtered.add(row) + } else if (!currentFileCollapsed) { + filtered.add(row) + } + } + visibleRows = filtered + canvasView.rows = filtered + canvasView.viewedFileIds = viewedFileIds + canvasView.selectedRowIds = selectedRowIds + applyPendingInitialScroll() + } + + private fun handleRowTap(row: DiffRow, gesture: String, target: RowTapTarget) { + when (row.kind) { + "file" -> { + if (gesture != "tap") return + if (target == RowTapTarget.VIEWED_CHECKBOX) { + onToggleViewedFile(mapOf("fileId" to row.resolvedFileId)) + } else { + onToggleFile(mapOf("fileId" to row.resolvedFileId)) + } + } + "comment" -> onToggleComment(mapOf("commentId" to row.id)) + "line" -> { + val payload = mutableMapOf( + "rowId" to row.id, + "fileId" to row.resolvedFileId, + "gesture" to gesture, + "change" to row.change, + ) + row.oldLineNumber?.let { payload["oldLineNumber"] = it } + row.newLineNumber?.let { payload["newLineNumber"] = it } + onPressLine(payload) + } + } + } + + @Suppress("ReturnCount") + private fun emitVisibleFile(firstVisibleIndex: Int) { + if (visibleRows.isEmpty()) return + val start = firstVisibleIndex.coerceIn(0, visibleRows.lastIndex) + val fileId = (start downTo 0) + .asSequence() + .map { visibleRows[it].resolvedFileId } + .firstOrNull { it.isNotEmpty() } + ?: return + if (fileId == lastVisibleFileId) return + lastVisibleFileId = fileId + onVisibleFileChange(mapOf("fileId" to fileId)) + } + + private fun applyPendingInitialScroll() { + if (!pendingInitialScroll || visibleRows.isEmpty()) return + pendingInitialScroll = false + val index = initialRowIndex.coerceIn(0, visibleRows.lastIndex) + post { canvasView.setVerticalOffset(canvasView.rowTop(index)) } + } + + private fun scrollToY(y: Int, animated: Boolean) { + val target = y.coerceIn(0, canvasView.maxVerticalOffset()) + if (animated) { + verticalScroller.startScroll( + 0, + canvasView.verticalOffset(), + 0, + target - canvasView.verticalOffset(), + 250, + ) + postInvalidateOnAnimation() + } else { + canvasView.setVerticalOffset(target) + } + } + + private fun dp(value: Float): Float = value * resources.displayMetrics.density + + private enum class DragAxis { + VERTICAL, + HORIZONTAL + } +} + +private enum class RowTapTarget { + ROW, + VIEWED_CHECKBOX +} + +private enum class HorizontalPanKind { + CODE, + FILE_HEADER_PATH +} + +private data class HorizontalPanTarget( + val fileId: String, + val kind: HorizontalPanKind +) + +internal data class DiffRow( + val kind: String, + val id: String, + val fileId: String, + val filePath: String, + val previousPath: String?, + val changeType: String, + val additions: Int, + val deletions: Int, + val text: String, + val content: String, + val change: String, + val oldLineNumber: Int?, + val newLineNumber: Int?, + val wordDiffRanges: List, + val commentText: String, + val commentRangeLabel: String, + val commentSectionTitle: String +) { + val resolvedFileId: String get() = fileId.ifEmpty { id } +} + +internal data class DiffWordDiffRange( + val start: Int, + val end: Int +) + +private data class DiffToken( + val content: String, + val color: Int?, + val fontStyle: Int +) + +internal data class DiffTheme( + val background: Int, + val text: Int, + val mutedText: Int, + val headerBackground: Int, + val border: Int, + val hunkBackground: Int, + val hunkText: Int, + val addBackground: Int, + val deleteBackground: Int, + val addBar: Int, + val deleteBar: Int, + val addText: Int, + val deleteText: Int +) { + companion object { + fun fallback(scheme: String): DiffTheme = if (scheme == "dark") { + DiffTheme( + background = Color.rgb(20, 22, 25), + text = Color.rgb(236, 238, 240), + mutedText = Color.rgb(153, 160, 170), + headerBackground = Color.rgb(26, 29, 33), + border = Color.rgb(52, 57, 64), + hunkBackground = Color.rgb(7, 31, 40), + hunkText = Color.rgb(0, 159, 255), + addBackground = Color.rgb(13, 47, 40), + deleteBackground = Color.rgb(57, 20, 21), + addBar = Color.rgb(0, 202, 177), + deleteBar = Color.rgb(255, 46, 63), + addText = Color.rgb(94, 204, 113), + deleteText = Color.rgb(255, 103, 98), + ) + } else { + DiffTheme( + background = Color.WHITE, + text = Color.rgb(7, 7, 7), + mutedText = Color.rgb(102, 106, 115), + headerBackground = Color.WHITE, + border = Color.rgb(222, 224, 228), + hunkBackground = Color.rgb(224, 242, 255), + hunkText = Color.rgb(0, 130, 220), + addBackground = Color.rgb(229, 248, 245), + deleteBackground = Color.rgb(255, 230, 231), + addBar = Color.rgb(0, 172, 151), + deleteBar = Color.rgb(213, 44, 54), + addText = Color.rgb(25, 130, 67), + deleteText = Color.rgb(190, 38, 48), + ) + } + + fun fromJson(value: String, fallback: DiffTheme): DiffTheme = try { + val json = JSONObject(value) + DiffTheme( + background = color(json, "background", fallback.background), + text = color(json, "text", fallback.text), + mutedText = color(json, "mutedText", fallback.mutedText), + headerBackground = color(json, "headerBackground", fallback.headerBackground), + border = color(json, "border", fallback.border), + hunkBackground = color(json, "hunkBackground", fallback.hunkBackground), + hunkText = color(json, "hunkText", fallback.hunkText), + addBackground = color(json, "addBackground", fallback.addBackground), + deleteBackground = color(json, "deleteBackground", fallback.deleteBackground), + addBar = color(json, "addBar", fallback.addBar), + deleteBar = color(json, "deleteBar", fallback.deleteBar), + addText = color(json, "addText", fallback.addText), + deleteText = color(json, "deleteText", fallback.deleteText), + ) + } catch (_: Exception) { + fallback + } + + private fun color(json: JSONObject, key: String, fallback: Int): Int = + parseColor(json.optString(key), fallback) + } +} + +internal data class DiffStyle( + val rowHeightPx: Float, + val gutterWidthPx: Float, + val codePaddingPx: Float, + val changeBarWidthPx: Float, + val fileHeaderHeightPx: Float, + val fileHeaderHorizontalPaddingPx: Float, + val codeFontSizePx: Float, + val codeFontWeight: String, + val lineNumberFontSizePx: Float, + val lineNumberFontWeight: String, + val hunkFontSizePx: Float, + val hunkFontWeight: String, + val fileHeaderFontSizePx: Float, + val fileHeaderFontWeight: String, + val fileHeaderMetaFontSizePx: Float, + val fileHeaderMetaFontWeight: String, + val fileHeaderSubtextFontSizePx: Float, + val fileHeaderSubtextFontWeight: String +) { + companion object { + fun defaults(density: Float): DiffStyle = DiffStyle( + rowHeightPx = 20f * density, + gutterWidthPx = 72f * density, + codePaddingPx = 10f * density, + changeBarWidthPx = 3f * density, + fileHeaderHeightPx = 44f * density, + fileHeaderHorizontalPaddingPx = 10f * density, + codeFontSizePx = 12f * density, + codeFontWeight = "regular", + lineNumberFontSizePx = 10f * density, + lineNumberFontWeight = "regular", + hunkFontSizePx = 11f * density, + hunkFontWeight = "medium", + fileHeaderFontSizePx = 11f * density, + fileHeaderFontWeight = "semibold", + fileHeaderMetaFontSizePx = 10f * density, + fileHeaderMetaFontWeight = "semibold", + fileHeaderSubtextFontSizePx = 11f * density, + fileHeaderSubtextFontWeight = "medium", + ) + + fun fromJson(value: String, fallback: DiffStyle, density: Float): DiffStyle = try { + val json = JSONObject(value) + DiffStyle( + rowHeightPx = json.floatDp("rowHeight", fallback.rowHeightPx, density), + gutterWidthPx = json.floatDp("gutterWidth", fallback.gutterWidthPx, density), + codePaddingPx = json.floatDp("codePadding", fallback.codePaddingPx, density), + changeBarWidthPx = json.floatDp("changeBarWidth", fallback.changeBarWidthPx, density), + fileHeaderHeightPx = json.floatDp("fileHeaderHeight", fallback.fileHeaderHeightPx, density), + fileHeaderHorizontalPaddingPx = json.floatDp( + "fileHeaderHorizontalPadding", + fallback.fileHeaderHorizontalPaddingPx, + density, + ), + codeFontSizePx = json.floatSp("codeFontSize", fallback.codeFontSizePx, density), + codeFontWeight = json.optString("codeFontWeight", fallback.codeFontWeight), + lineNumberFontSizePx = json.floatSp( + "lineNumberFontSize", + fallback.lineNumberFontSizePx, + density, + ), + lineNumberFontWeight = json.optString( + "lineNumberFontWeight", + fallback.lineNumberFontWeight, + ), + hunkFontSizePx = json.floatSp("hunkFontSize", fallback.hunkFontSizePx, density), + hunkFontWeight = json.optString("hunkFontWeight", fallback.hunkFontWeight), + fileHeaderFontSizePx = json.floatSp( + "fileHeaderFontSize", + fallback.fileHeaderFontSizePx, + density, + ), + fileHeaderFontWeight = json.optString( + "fileHeaderFontWeight", + fallback.fileHeaderFontWeight, + ), + fileHeaderMetaFontSizePx = json.floatSp( + "fileHeaderMetaFontSize", + fallback.fileHeaderMetaFontSizePx, + density, + ), + fileHeaderMetaFontWeight = json.optString( + "fileHeaderMetaFontWeight", + fallback.fileHeaderMetaFontWeight, + ), + fileHeaderSubtextFontSizePx = json.floatSp( + "fileHeaderSubtextFontSize", + fallback.fileHeaderSubtextFontSizePx, + density, + ), + fileHeaderSubtextFontWeight = json.optString( + "fileHeaderSubtextFontWeight", + fallback.fileHeaderSubtextFontWeight, + ), + ) + } catch (_: Exception) { + fallback + } + } +} + +private class DiffCanvasView(context: Context) : View(context) { + private val density = resources.displayMetrics.density + private val drawing = ReviewDiffCanvasDrawing(context) + private val backgroundPaint = drawing.backgroundPaint + private val borderPaint = drawing.borderPaint + private val textPaint = drawing.textPaint + private val boldTextPaint = drawing.uiPaint + private val gestureDetector = GestureDetector( + context, + object : GestureDetector.SimpleOnGestureListener() { + override fun onDown(event: MotionEvent): Boolean = true + + override fun onSingleTapUp(event: MotionEvent): Boolean { + rowHitAt(event.y)?.let { hit -> + val target = if ( + hit.row.kind == "file" && + drawing.fileHeaderCheckboxRect( + hit.top, + hit.bottom, + width, + style + ).contains(event.x, event.y) + ) { + RowTapTarget.VIEWED_CHECKBOX + } else { + RowTapTarget.ROW + } + onRowTap?.invoke(hit.row, "tap", target) + } + return true + } + + override fun onLongPress(event: MotionEvent) { + rowHitAt(event.y)?.row + ?.takeIf { it.kind == "line" } + ?.let { onRowTap?.invoke(it, "longPress", RowTapTarget.ROW) } + } + }, + ) + private var rowOffsets = intArrayOf(0) + private var verticalOffset = 0 + private var horizontalOffset = 0 + private val headerPathOffsetsByFileId = mutableMapOf() + private var lastVisibleRange: Pair? = null + var rows: List = emptyList() + set(value) { + field = value + headerPathOffsetsByFileId.keys.retainAll( + value.asSequence().filter { it.kind == "file" }.map { it.resolvedFileId }.toSet(), + ) + rebuildOffsets() + } + var tokensByRowId: Map> = emptyMap() + set(value) { + field = value + invalidate() + } + var viewedFileIds: Set = emptySet() + set(value) { + field = value + invalidate() + } + var collapsedFileIds: Set = emptySet() + set(value) { + field = value + invalidate() + } + var collapsedCommentIds: Set = emptySet() + set(value) { + field = value + rebuildOffsets() + } + var selectedRowIds: Set = emptySet() + set(value) { + field = value + invalidate() + } + var theme: DiffTheme = DiffTheme.fallback("light") + set(value) { + field = value + drawing.theme = value + invalidate() + } + var style: DiffStyle = DiffStyle.defaults(density) + set(value) { + field = value + rebuildOffsets() + } + var contentWidthPx: Int = (1200 * density).toInt() + set(value) { + field = max(value, suggestedMinimumWidth) + setHorizontalOffset(horizontalOffset) + clampHeaderPathOffsets() + invalidate() + } + var onRowTap: ((DiffRow, String, RowTapTarget) -> Unit)? = null + var onVisibleRowsChanged: ((Int, Int) -> Unit)? = null + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + setMeasuredDimension( + MeasureSpec.getSize(widthMeasureSpec), + MeasureSpec.getSize(heightMeasureSpec), + ) + } + + override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { + super.onSizeChanged(width, height, oldWidth, oldHeight) + setVerticalOffset(verticalOffset) + setHorizontalOffset(horizontalOffset) + clampHeaderPathOffsets() + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + canvas.drawColor(theme.background) + if (rows.isEmpty()) return + val first = rowIndexAt(max(0, verticalOffset + canvas.clipBounds.top)) + val last = rowIndexAt( + min(max(0, rowOffsets.last() - 1), verticalOffset + canvas.clipBounds.bottom), + ).coerceAtLeast(first) + for (index in first..last.coerceAtMost(rows.lastIndex)) { + drawRow( + canvas, + rows[index], + rowOffsets[index] - verticalOffset, + rowOffsets[index + 1] - verticalOffset, + ) + } + drawStickyFileHeader(canvas, first) + drawHorizontalScrollIndicator(canvas) + emitVisibleRange() + } + + override fun onTouchEvent(event: MotionEvent): Boolean = gestureDetector.onTouchEvent(event) + + fun rowTop(index: Int): Int = rowOffsets[index.coerceIn(0, max(0, rowOffsets.size - 2))] + + fun setVerticalOffset(value: Int) { + val maxOffset = max(0, (rowOffsets.lastOrNull() ?: 0) - height) + val nextOffset = value.coerceIn(0, maxOffset) + if (verticalOffset == nextOffset) return + verticalOffset = nextOffset + invalidate() + emitVisibleRange() + } + + fun scrollByVertical(delta: Int) { + setVerticalOffset(verticalOffset + delta) + } + + fun verticalOffset(): Int = verticalOffset + + fun maxVerticalOffset(): Int = max(0, (rowOffsets.lastOrNull() ?: 0) - height) + + fun setHorizontalOffset(value: Int) { + val nextOffset = value.coerceIn(0, maxHorizontalOffset()) + if (horizontalOffset == nextOffset) return + horizontalOffset = nextOffset + invalidate() + } + + fun scrollByHorizontal(delta: Int, target: HorizontalPanTarget) { + if (target.kind == HorizontalPanKind.FILE_HEADER_PATH) { + setHeaderPathOffset( + target.fileId, + (headerPathOffsetsByFileId[target.fileId] ?: 0) + delta, + ) + } else { + setHorizontalOffset(horizontalOffset + delta) + } + } + + fun horizontalOffset(): Int = horizontalOffset + + fun maxHorizontalOffset(): Int = max(0, contentWidthPx - width) + + fun maxHorizontalOffset(target: HorizontalPanTarget): Int = + if (target.kind == HorizontalPanKind.FILE_HEADER_PATH) { + maxHeaderPathOffset(target.fileId) + } else { + maxHorizontalOffset() + } + + fun horizontalPanTarget(y: Float): HorizontalPanTarget? { + val row = rowHitAt(y)?.row ?: return null + return HorizontalPanTarget( + fileId = row.resolvedFileId, + kind = if (row.kind == "file") HorizontalPanKind.FILE_HEADER_PATH else HorizontalPanKind.CODE, + ) + } + + fun resetHorizontalOffsets() { + setHorizontalOffset(0) + if (headerPathOffsetsByFileId.isNotEmpty()) { + headerPathOffsetsByFileId.clear() + invalidate() + } + } + + private fun rebuildOffsets() { + rowOffsets = IntArray(rows.size + 1) + rows.forEachIndexed { index, row -> + rowOffsets[index + 1] = rowOffsets[index] + rowHeight(row) + } + setVerticalOffset(verticalOffset) + clampHeaderPathOffsets() + requestLayout() + invalidate() + } + + private fun rowHeight(row: DiffRow): Int = when (row.kind) { + "file" -> style.fileHeaderHeightPx.toInt() + "notice" -> max((style.rowHeightPx * 2f).toInt(), (44 * density).toInt()) + "comment" -> if (collapsedCommentIds.contains(row.id)) { + (44 * density).toInt() + } else { + (124 * density).toInt() + } + else -> style.rowHeightPx.toInt() + }.coerceAtLeast(1) + + @Suppress("ReturnCount") + private fun rowIndexAt(y: Int): Int { + if (rows.isEmpty()) return 0 + var low = 0 + var high = rows.lastIndex + while (low <= high) { + val middle = (low + high) ushr 1 + when { + y < rowOffsets[middle] -> high = middle - 1 + y >= rowOffsets[middle + 1] -> low = middle + 1 + else -> return middle + } + } + return low.coerceIn(0, rows.lastIndex) + } + + private fun rowHitAt(y: Float): RowHit? { + stickyFileHeader(firstVisibleRow())?.let { sticky -> + if (y >= max(0, sticky.top).toFloat() && y < sticky.bottom.toFloat()) { + return rows.getOrNull(sticky.index)?.let { RowHit(it, sticky.top, sticky.bottom) } + } + } + val index = rowIndexAt(verticalOffset + y.toInt()) + return rows.getOrNull(index)?.let { + RowHit( + row = it, + top = rowOffsets[index] - verticalOffset, + bottom = rowOffsets[index + 1] - verticalOffset, + ) + } + } + + private fun firstVisibleRow(): Int = rowIndexAt(verticalOffset) + + private fun emitVisibleRange() { + if (rows.isEmpty()) return + val first = rowIndexAt(verticalOffset) + val last = rowIndexAt(verticalOffset + max(1, height)) + val range = first to last + if (range == lastVisibleRange) return + lastVisibleRange = range + onVisibleRowsChanged?.invoke(first, last) + } + + private fun drawRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { + when (row.kind) { + "file" -> drawFileRow(canvas, row, top, bottom) + "hunk" -> drawHunkRow(canvas, row, top, bottom) + "notice" -> drawNoticeRow(canvas, row, top, bottom) + "comment" -> drawCommentRow(canvas, row, top, bottom) + else -> drawLineRow(canvas, row, top, bottom) + } + } + + private fun drawFileRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { + fill(canvas, theme.headerBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat()) + + val chevronRect = drawing.fileHeaderChevronRect(top, bottom, style) + val iconRect = drawing.fileHeaderIconRect(top, bottom, style) + val checkboxRect = drawing.fileHeaderCheckboxRect(top, bottom, width, style) + drawing.drawDisclosureChevron( + canvas, + chevronRect, + theme.mutedText, + collapsed = collapsedFileIds.contains(row.resolvedFileId), + ) + drawing.drawFileIcon(canvas, iconRect, row.changeType) + drawing.drawViewedCheckbox( + canvas, + checkboxRect, + viewedFileIds.contains(row.resolvedFileId), + ) + + drawing.configureUiPaint( + paint = boldTextPaint, + color = theme.deleteText, + size = style.fileHeaderMetaFontSizePx, + weight = style.fileHeaderMetaFontWeight, + ) + val deleteText = "-${row.deletions}" + val deleteWidth = boldTextPaint.measureText(deleteText) + val addText = "+${row.additions}" + val addWidth = boldTextPaint.measureText(addText) + val countGap = 4f * density + val countsX = checkboxRect.left - 10f * density - deleteWidth - countGap - addWidth + val baseline = centeredBaseline(top, bottom, boldTextPaint) + canvas.drawText(deleteText, countsX, baseline, boldTextPaint) + boldTextPaint.color = theme.addText + canvas.drawText(addText, countsX + deleteWidth + countGap, baseline, boldTextPaint) + + val pathLayout = fileHeaderPathLayout(row, top, bottom, iconRect, countsX) + val maxPathOffset = maxHeaderPathOffset(pathLayout) + val pathOffset = (headerPathOffsetsByFileId[row.resolvedFileId] ?: 0) + .coerceIn(0, maxPathOffset) + canvas.save() + canvas.clipRect(pathLayout.rect) + canvas.drawText( + pathLayout.displayPath, + pathLayout.rect.left - pathOffset, + centeredBaseline(top, bottom, boldTextPaint), + boldTextPaint, + ) + canvas.restore() + drawing.drawFileHeaderPathScrollFades( + canvas, + pathLayout.rect, + pathOffset, + maxPathOffset, + ) + drawBottomBorder(canvas, bottom) + } + + private fun fileHeaderPathLayout( + row: DiffRow, + top: Int, + bottom: Int, + iconRect: RectF, + countsX: Float + ): FileHeaderPathLayout { + drawing.configureUiPaint( + paint = boldTextPaint, + color = theme.text, + size = style.fileHeaderFontSizePx, + weight = style.fileHeaderFontWeight, + ) + val pathX = iconRect.right + 10f * density + val pathWidth = max(24f * density, countsX - pathX - 12f * density) + val centerY = (top + bottom) / 2f + val displayPath = if ( + !row.previousPath.isNullOrEmpty() && row.previousPath != row.filePath + ) { + "${row.previousPath} -> ${row.filePath}" + } else { + row.filePath + } + return FileHeaderPathLayout( + displayPath = displayPath, + rect = RectF(pathX, centerY - 10f * density, pathX + pathWidth, centerY + 10f * density), + ) + } + + private fun maxHeaderPathOffset(fileId: String): Int { + val row = rows.firstOrNull { it.kind == "file" && it.resolvedFileId == fileId } ?: return 0 + val top = 0 + val bottom = rowHeight(row) + val iconRect = drawing.fileHeaderIconRect(top, bottom, style) + val checkboxRect = drawing.fileHeaderCheckboxRect(top, bottom, width, style) + drawing.configureUiPaint( + paint = boldTextPaint, + color = theme.deleteText, + size = style.fileHeaderMetaFontSizePx, + weight = style.fileHeaderMetaFontWeight, + ) + val countsX = checkboxRect.left - 10f * density - + boldTextPaint.measureText("-${row.deletions}") - 4f * density - + boldTextPaint.measureText("+${row.additions}") + return maxHeaderPathOffset(fileHeaderPathLayout(row, top, bottom, iconRect, countsX)) + } + + private fun maxHeaderPathOffset(layout: FileHeaderPathLayout): Int = max( + 0, + ceil(boldTextPaint.measureText(layout.displayPath) - layout.rect.width()).toInt(), + ) + + private fun setHeaderPathOffset(fileId: String, value: Int) { + val nextOffset = value.coerceIn(0, maxHeaderPathOffset(fileId)) + if ((headerPathOffsetsByFileId[fileId] ?: 0) == nextOffset) return + headerPathOffsetsByFileId[fileId] = nextOffset + invalidate() + } + + private fun clampHeaderPathOffsets() { + headerPathOffsetsByFileId.keys.toList().forEach { fileId -> + val nextOffset = (headerPathOffsetsByFileId[fileId] ?: 0) + .coerceIn(0, maxHeaderPathOffset(fileId)) + if (nextOffset == 0) { + headerPathOffsetsByFileId.remove(fileId) + } else { + headerPathOffsetsByFileId[fileId] = nextOffset + } + } + } + + private fun drawHunkRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { + fill(canvas, theme.hunkBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat()) + drawing.configureMonospacePaint( + color = theme.hunkText, + size = style.hunkFontSizePx, + weight = style.hunkFontWeight, + ) + drawScrollableCode(canvas, top, bottom) { codeX -> + canvas.drawText( + row.text.ifEmpty { row.content }, + codeX, + centeredBaseline(top, bottom, textPaint), + textPaint, + ) + } + } + + private fun drawNoticeRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { + fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat()) + val iconSize = 16f * density + val iconRect = RectF( + style.fileHeaderHorizontalPaddingPx + 2f * density, + (top + bottom - iconSize) / 2f, + style.fileHeaderHorizontalPaddingPx + 2f * density + iconSize, + (top + bottom + iconSize) / 2f, + ) + drawing.drawNoticeIcon(canvas, iconRect, theme.mutedText) + drawing.configureUiPaint( + paint = textPaint, + color = theme.mutedText, + size = style.fileHeaderSubtextFontSizePx, + weight = style.fileHeaderSubtextFontWeight, + ) + val textX = iconRect.right + 10f * density + canvas.drawText( + ellipsize(row.text, textPaint, width - textX - style.fileHeaderHorizontalPaddingPx), + textX, + centeredBaseline(top, bottom, textPaint), + textPaint, + ) + drawBottomBorder(canvas, bottom) + } + + private fun drawCommentRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { + fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat()) + val cardRect = RectF( + 8f * density, + top + 5f * density, + width - 8f * density, + bottom - 5f * density, + ) + backgroundPaint.color = theme.headerBackground + canvas.drawRoundRect(cardRect, 10f * density, 10f * density, backgroundPaint) + borderPaint.style = Paint.Style.STROKE + borderPaint.color = withAlpha(theme.border, 217) + borderPaint.strokeWidth = density + canvas.drawRoundRect(cardRect, 10f * density, 10f * density, borderPaint) + borderPaint.style = Paint.Style.FILL + + val collapsed = collapsedCommentIds.contains(row.id) + val chevronRect = RectF( + cardRect.left + 10f * density, + cardRect.top + 11f * density, + cardRect.left + 26f * density, + cardRect.top + 27f * density, + ) + drawing.drawDisclosureChevron(canvas, chevronRect, theme.mutedText, collapsed) + drawing.configureUiPaint( + paint = textPaint, + color = theme.mutedText, + size = style.fileHeaderSubtextFontSizePx, + weight = style.fileHeaderSubtextFontWeight, + ) + val title = "Comment on ${row.commentRangeLabel.ifEmpty { "line" }}" + canvas.drawText( + ellipsize(title, textPaint, cardRect.right - chevronRect.right - 20f * density), + chevronRect.right + 10f * density, + cardRect.top + 22f * density, + textPaint, + ) + if (!collapsed) { + textPaint.color = theme.text + val bodyX = cardRect.left + 18f * density + canvas.drawText( + ellipsize( + row.commentText.ifEmpty { "Comment" }, + textPaint, + cardRect.right - bodyX - 18f * density + ), + bodyX, + cardRect.top + 58f * density, + textPaint, + ) + } + } + + @Suppress("CyclomaticComplexMethod") + private fun drawLineRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { + val background = when (row.change) { + "add" -> theme.addBackground + "delete" -> theme.deleteBackground + else -> theme.background + } + fill(canvas, background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat()) + if (style.changeBarWidthPx > 0) { + when (row.change) { + "add" -> fill( + canvas, + theme.addBar, + 0f, + top.toFloat(), + style.changeBarWidthPx, + bottom.toFloat() + ) + "delete" -> drawing.drawDeleteStripes( + canvas, + top, + bottom, + style.changeBarWidthPx, + theme.deleteBar, + ) + } + } + val selected = selectedRowIds.contains(row.id) + if (selected) { + fill( + canvas, + withAlpha(theme.hunkText, 56), + 0f, + top.toFloat(), + width.toFloat(), + bottom.toFloat(), + ) + fill( + canvas, + withAlpha(theme.hunkText, 242), + 0f, + top.toFloat(), + style.changeBarWidthPx, + bottom.toFloat() + ) + } + + val tokens = tokensByRowId[row.id] + drawScrollableCode(canvas, top, bottom) { codeX -> + drawing.configureCodePaint(theme.text, 0, style) + drawing.drawWordDiffRanges(canvas, row, codeX, top, bottom) + if (tokens.isNullOrEmpty()) { + canvas.drawText(row.content, codeX, centeredBaseline(top, bottom, textPaint), textPaint) + } else { + var x = codeX + tokens.forEach { token -> + drawing.configureCodePaint(token.color ?: theme.text, token.fontStyle, style) + canvas.drawText(token.content, x, centeredBaseline(top, bottom, textPaint), textPaint) + x += textPaint.measureText(token.content) + } + } + } + + drawLineNumber(canvas, row, top, bottom) + } + + private fun drawLineNumber(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { + val lineNumber = row.newLineNumber ?: row.oldLineNumber ?: return + drawing.configureMonospacePaint( + color = drawing.lineNumberColor(row.change), + size = style.lineNumberFontSizePx, + weight = style.lineNumberFontWeight, + ) + textPaint.textAlign = Paint.Align.RIGHT + canvas.drawText( + lineNumber.toString(), + style.changeBarWidthPx + style.gutterWidthPx - style.codePaddingPx, + centeredBaseline(top, bottom, textPaint), + textPaint, + ) + textPaint.textAlign = Paint.Align.LEFT + } + + private fun drawScrollableCode( + canvas: Canvas, + top: Int, + bottom: Int, + draw: (Float) -> Unit + ) { + val gutterEnd = style.changeBarWidthPx + style.gutterWidthPx + canvas.save() + canvas.clipRect(gutterEnd, top.toFloat(), width.toFloat(), bottom.toFloat()) + draw(gutterEnd + style.codePaddingPx - horizontalOffset) + canvas.restore() + } + + private fun drawStickyFileHeader(canvas: Canvas, firstVisibleIndex: Int) { + val sticky = stickyFileHeader(firstVisibleIndex) ?: return + val naturalTop = rowOffsets[sticky.index] - verticalOffset + if (naturalTop == sticky.top) return + drawFileRow(canvas, rows[sticky.index], sticky.top, sticky.bottom) + } + + @Suppress("ReturnCount") + private fun stickyFileHeader(firstVisibleIndex: Int): StickyFileHeader? { + if (rows.isEmpty()) return null + val fileIndex = (firstVisibleIndex.coerceIn(0, rows.lastIndex) downTo 0) + .firstOrNull { rows[it].kind == "file" } + ?: return null + val headerHeight = rowHeight(rows[fileIndex]) + val nextFileIndex = ((fileIndex + 1)..rows.lastIndex).firstOrNull { rows[it].kind == "file" } + val top = nextFileIndex + ?.let { min(0, rowOffsets[it] - verticalOffset - headerHeight) } + ?: 0 + return StickyFileHeader(fileIndex, top, top + headerHeight) + } + + private fun drawHorizontalScrollIndicator(canvas: Canvas) { + val maxOffset = maxHorizontalOffset() + if (maxOffset <= 0 || width <= 0) return + val trackWidth = width.toFloat() + val thumbWidth = max(24f * density, trackWidth * trackWidth / contentWidthPx) + val thumbTravel = trackWidth - thumbWidth + val left = thumbTravel * horizontalOffset / maxOffset + fill( + canvas, + withAlpha(theme.mutedText, 110), + left, + height - 2f * density, + left + thumbWidth, + height.toFloat(), + ) + } + + @Suppress("LongParameterList") + private fun fill( + canvas: Canvas, + color: Int, + left: Float, + top: Float, + right: Float, + bottom: Float + ) { + backgroundPaint.color = color + canvas.drawRect(left, top, right, bottom, backgroundPaint) + } + + private fun drawBottomBorder(canvas: Canvas, bottom: Int) { + borderPaint.color = theme.border + borderPaint.strokeWidth = density + canvas.drawLine(0f, bottom - density / 2f, width.toFloat(), bottom - density / 2f, borderPaint) + } + + private fun centeredBaseline(top: Int, bottom: Int, paint: Paint): Float { + val metrics = paint.fontMetrics + return (top + bottom) / 2f - (metrics.ascent + metrics.descent) / 2f + } + + private fun ellipsize(value: String, paint: Paint, width: Float): String { + if (paint.measureText(value) <= width) return value + val suffix = "..." + val available = max(0f, width - paint.measureText(suffix)) + var end = value.length + while (end > 0 && paint.measureText(value, 0, end) > available) end -= 1 + return value.substring(0, end) + suffix + } + + private data class StickyFileHeader( + val index: Int, + val top: Int, + val bottom: Int + ) + + private data class RowHit( + val row: DiffRow, + val top: Int, + val bottom: Int + ) + + private data class FileHeaderPathLayout( + val displayPath: String, + val rect: RectF + ) +} + +private fun withAlpha(color: Int, alpha: Int): Int = + Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color)) + +private fun parseRows(value: String): List = try { + val array = JSONArray(value) + List(array.length()) { index -> + val row = array.getJSONObject(index) + DiffRow( + kind = row.optString("kind"), + id = row.optString("id"), + fileId = row.optString("fileId"), + filePath = row.optString("filePath"), + previousPath = row.optNullableString("previousPath"), + changeType = row.optString("changeType"), + additions = row.optInt("additions"), + deletions = row.optInt("deletions"), + text = row.optString("text"), + content = row.optString("content"), + change = row.optString("change", "context"), + oldLineNumber = row.optNullableInt("oldLineNumber"), + newLineNumber = row.optNullableInt("newLineNumber"), + wordDiffRanges = row.optJSONArray("wordDiffRanges")?.let(::parseWordDiffRanges).orEmpty(), + commentText = row.optString("commentText"), + commentRangeLabel = row.optString("commentRangeLabel"), + commentSectionTitle = row.optString("commentSectionTitle"), + ) + } +} catch (_: Exception) { + emptyList() +} + +private fun parseWordDiffRanges(value: JSONArray): List = buildList { + for (index in 0 until value.length()) { + val range = value.optJSONObject(index) ?: continue + val start = range.optInt("start", -1) + val end = range.optInt("end", -1) + if (start >= 0 && end > start) { + add(DiffWordDiffRange(start = start, end = end)) + } + } +} + +private fun parseTokensObject(value: String): Map> = try { + parseTokensObject(JSONObject(value)) +} catch (_: Exception) { + emptyMap() +} + +private fun parseTokensObject(value: JSONObject): Map> { + val result = LinkedHashMap>() + val keys = value.keys() + while (keys.hasNext()) { + val rowId = keys.next() + val array = value.optJSONArray(rowId) ?: continue + result[rowId] = List(array.length()) { index -> + val token = array.getJSONObject(index) + DiffToken( + content = token.optString("content"), + color = token.optNullableString("color")?.let(::parseColorOrNull), + fontStyle = token.optInt("fontStyle"), + ) + } + } + return result +} + +private fun parseStringSet(value: String): Set = try { + val array = JSONArray(value) + buildSet { + for (index in 0 until array.length()) add(array.getString(index)) + } +} catch (_: Exception) { + emptySet() +} + +private fun parseColor(value: String, fallback: Int): Int = try { + Color.parseColor(value) +} catch (_: Exception) { + fallback +} + +private fun parseColorOrNull(value: String): Int? = try { + Color.parseColor(value) +} catch (_: Exception) { + null +} + +private fun JSONObject.optNullableString(key: String): String? = + if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() } + +private fun JSONObject.optNullableInt(key: String): Int? = + if (isNull(key) || !has(key)) null else optInt(key) + +private fun JSONObject.floatDp(key: String, fallbackPx: Float, density: Float): Float = + if (has(key)) optDouble(key).toFloat() * density else fallbackPx + +private fun JSONObject.floatSp(key: String, fallbackPx: Float, density: Float): Float = + if (has(key)) optDouble(key).toFloat() * density else fallbackPx diff --git a/apps/mobile/modules/t3-review-diff/expo-module.config.json b/apps/mobile/modules/t3-review-diff/expo-module.config.json index fe6b11b649..bf5baf4fc5 100644 --- a/apps/mobile/modules/t3-review-diff/expo-module.config.json +++ b/apps/mobile/modules/t3-review-diff/expo-module.config.json @@ -1,7 +1,10 @@ { - "platforms": ["apple"], + "platforms": ["apple", "android"], "apple": { "modules": ["T3ReviewDiffModule"], "podspecPath": "T3ReviewDiffNative.podspec" + }, + "android": { + "modules": ["expo.modules.t3reviewdiff.T3ReviewDiffModule"] } } diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift index 81cdd8417d..96a1785f9f 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift @@ -5,22 +5,14 @@ public class T3ReviewDiffModule: Module { Name("T3ReviewDiffSurface") View(T3ReviewDiffView.self) { - Prop("rowsJson") { (view: T3ReviewDiffView, rowsJson: String) in - view.setRowsJson(rowsJson) - } - - Prop("tokensJson") { (view: T3ReviewDiffView, tokensJson: String) in - view.setTokensJson(tokensJson) - } - - Prop("tokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in - view.setTokensPatchJson(tokensPatchJson) - } - Prop("tokensResetKey") { (view: T3ReviewDiffView, tokensResetKey: String) in view.setTokensResetKey(tokensResetKey) } + Prop("contentResetKey") { (view: T3ReviewDiffView, contentResetKey: String) in + view.setContentResetKey(contentResetKey) + } + Prop("collapsedFileIdsJson") { (view: T3ReviewDiffView, collapsedFileIdsJson: String) in view.setCollapsedFileIdsJson(collapsedFileIdsJson) } @@ -61,7 +53,42 @@ public class T3ReviewDiffModule: Module { view.setInitialRowIndex(initialRowIndex) } - Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment") + Prop("refreshing") { (view: T3ReviewDiffView, refreshing: Bool) in + view.setRefreshing(refreshing) + } + + Events( + "onDebug", + "onVisibleFileChange", + "onToggleFile", + "onToggleViewedFile", + "onPressLine", + "onToggleComment", + "onPullToRefresh" + ) + + AsyncFunction("scrollToFile") { (view: T3ReviewDiffView, fileId: String, animated: Bool) in + view.scrollToFile(fileId, animated: animated) + } + + AsyncFunction("scrollToTop") { (view: T3ReviewDiffView, animated: Bool) in + view.scrollToTop(animated: animated) + } + + // Large, frequently changing JSON values cannot be regular Fabric props. Expo's + // prop adapter compares strings on the main thread before invoking a setter, which + // makes a syntax-token patch capable of blocking a frame by itself. + AsyncFunction("setRowsJson") { (view: T3ReviewDiffView, rowsJson: String) in + view.setRowsJson(rowsJson) + } + + AsyncFunction("setTokensJson") { (view: T3ReviewDiffView, tokensJson: String) in + view.setTokensJson(tokensJson) + } + + AsyncFunction("setTokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in + view.setTokensPatchJson(tokensPatchJson) + } } } } diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index f8e080e760..ef2157d435 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -1,7 +1,7 @@ import ExpoModulesCore import UIKit -private struct ReviewDiffNativeRow: Decodable { +private struct ReviewDiffNativeRow: Decodable, Sendable { let kind: String let id: String let fileId: String? @@ -21,18 +21,18 @@ private struct ReviewDiffNativeRow: Decodable { let commentSectionTitle: String? } -private struct ReviewDiffNativeWordDiffRange: Decodable { +private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable { let start: Int let end: Int } -private struct ReviewDiffNativeToken: Decodable { +private struct ReviewDiffNativeToken: Decodable, Sendable { let content: String let color: String? let fontStyle: Int? } -private struct ReviewDiffNativeTokenPatch: Decodable { +private struct ReviewDiffNativeTokenPatch: Decodable, Sendable { let resetKey: String? let chunkIndex: Int? let tokensByRowId: [String: [ReviewDiffNativeToken]]? @@ -312,6 +312,10 @@ private struct ReviewDiffNativeStyle { } public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { + private let payloadDecodeQueue = DispatchQueue( + label: "com.t3tools.review-diff.payload-decode", + qos: .userInitiated + ) private let scrollView = UIScrollView() private let contentView = ReviewDiffContentView() private var rows: [ReviewDiffNativeRow] = [] @@ -323,14 +327,25 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { private var lastMetricsDebugKey = "" private var lastVisibleRangeDebugKey = "" private var tokensResetKey = "" + private var contentResetKey = "" private var initialRowIndex: Int? private var hasAppliedInitialRowIndex = false + private var lastVisibleFileId: String? + private var pendingScrollFileId: String? + private var pendingScrollAnimated = false + private var isProgrammaticScrollActive = false + private var rowsDecodeGeneration = 0 + private var tokensDecodeGeneration = 0 let onDebug = EventDispatcher() + let onVisibleFileChange = EventDispatcher() let onToggleFile = EventDispatcher() let onToggleViewedFile = EventDispatcher() let onPressLine = EventDispatcher() let onToggleComment = EventDispatcher() + let onPullToRefresh = EventDispatcher() + + private let pullRefreshControl = UIRefreshControl() public required init(appContext: AppContext? = nil) { super.init(appContext: appContext) @@ -345,6 +360,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { scrollView.showsVerticalScrollIndicator = true scrollView.showsHorizontalScrollIndicator = false scrollView.backgroundColor = contentView.theme.background + pullRefreshControl.addTarget(self, action: #selector(handlePullToRefresh), for: .valueChanged) + scrollView.refreshControl = pullRefreshControl addSubview(scrollView) contentView.backgroundColor = contentView.theme.background @@ -379,6 +396,13 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { updateViewportFrame() } + public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { + // A direct gesture takes ownership from any interrupted programmatic jump. + // Resume visible-file events immediately so the inspector follows the finger. + isProgrammaticScrollActive = false + contentView.isVerticalScrollActive = true + } + public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { guard !decelerate else { return @@ -396,77 +420,125 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { } func setRowsJson(_ rowsJson: String) { - guard let data = rowsJson.data(using: .utf8) else { - return - } + rowsDecodeGeneration += 1 + let generation = rowsDecodeGeneration - do { - rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data) - contentView.rows = rows - hasAppliedInitialRowIndex = false - emitDebug("rows-decoded", [ - "rows": rows.count, - "firstKind": rows.first?.kind ?? "none", - ]) - updateContentMetrics() - } catch { - rows = [] - contentView.rows = [] - hasAppliedInitialRowIndex = false - updateContentMetrics() - emitDebug("rows-decode-failed", [ - "error": error.localizedDescription, - ]) + payloadDecodeQueue.async { [weak self] in + guard let data = rowsJson.data(using: .utf8) else { + return + } + + do { + let decodedRows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data) + DispatchQueue.main.async { [weak self] in + guard let self, generation == self.rowsDecodeGeneration else { + return + } + self.rows = decodedRows + self.contentView.rows = decodedRows + self.hasAppliedInitialRowIndex = false + self.lastVisibleFileId = nil + self.emitDebug("rows-decoded", [ + "rows": decodedRows.count, + "firstKind": decodedRows.first?.kind ?? "none", + ]) + self.updateContentMetrics() + self.applyPendingScrollIfNeeded() + } + } catch { + let message = error.localizedDescription + DispatchQueue.main.async { [weak self] in + guard let self, generation == self.rowsDecodeGeneration else { + return + } + self.rows = [] + self.contentView.rows = [] + self.hasAppliedInitialRowIndex = false + self.lastVisibleFileId = nil + self.pendingScrollFileId = nil + self.updateContentMetrics() + self.emitDebug("rows-decode-failed", ["error": message]) + } + } } } func setTokensJson(_ tokensJson: String) { - guard let data = tokensJson.data(using: .utf8) else { - return - } + tokensDecodeGeneration += 1 + let generation = tokensDecodeGeneration - do { - contentView.tokensByRowId = try JSONDecoder().decode( - [String: [ReviewDiffNativeToken]].self, - from: data - ) - } catch { - contentView.tokensByRowId = [:] - emitDebug("tokens-decode-failed", [ - "error": error.localizedDescription, - ]) + payloadDecodeQueue.async { [weak self] in + guard let data = tokensJson.data(using: .utf8) else { + return + } + + do { + let decodedTokens = try JSONDecoder().decode( + [String: [ReviewDiffNativeToken]].self, + from: data + ) + DispatchQueue.main.async { [weak self] in + guard let self, generation == self.tokensDecodeGeneration else { + return + } + self.contentView.tokensByRowId = decodedTokens + } + } catch { + let message = error.localizedDescription + DispatchQueue.main.async { [weak self] in + guard let self, generation == self.tokensDecodeGeneration else { + return + } + self.contentView.tokensByRowId = [:] + self.emitDebug("tokens-decode-failed", ["error": message]) + } + } } } func setTokensPatchJson(_ tokensPatchJson: String) { - guard let data = tokensPatchJson.data(using: .utf8) else { - return - } + let contentResetKey = self.contentResetKey - do { - let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data) - if let resetKey = patch.resetKey, resetKey != tokensResetKey { - tokensResetKey = resetKey - contentView.tokensByRowId = [:] - } - - let tokensByRowId = patch.tokensByRowId ?? [:] - if tokensByRowId.isEmpty { + payloadDecodeQueue.async { [weak self] in + guard let data = tokensPatchJson.data(using: .utf8) else { return } - contentView.mergeTokensByRowId(tokensByRowId) - if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) { - emitDebug("tokens-patch-decoded", [ - "chunkIndex": chunkIndex, - "rows": tokensByRowId.count, - "totalRows": contentView.tokensByRowId.count, - ]) + do { + let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data) + DispatchQueue.main.async { [weak self] in + guard let self else { + return + } + guard contentResetKey == self.contentResetKey else { + return + } + // A highlighter request from the previous file can finish after the view has + // already reset. Never let that stale patch roll the native token state back. + if let resetKey = patch.resetKey, resetKey != self.tokensResetKey { + return + } + + let tokensByRowId = patch.tokensByRowId ?? [:] + if tokensByRowId.isEmpty { + return + } + + self.contentView.mergeTokensByRowId(tokensByRowId) + if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) { + self.emitDebug("tokens-patch-decoded", [ + "chunkIndex": chunkIndex, + "rows": tokensByRowId.count, + "totalRows": self.contentView.tokensByRowId.count, + ]) + } + } + } catch { + let message = error.localizedDescription + DispatchQueue.main.async { [weak self] in + self?.emitDebug("tokens-patch-decode-failed", ["error": message]) + } } - } catch { - emitDebug("tokens-patch-decode-failed", [ - "error": error.localizedDescription, - ]) } } @@ -482,6 +554,27 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { ]) } + func setContentResetKey(_ contentResetKey: String) { + guard contentResetKey != self.contentResetKey else { + return + } + + self.contentResetKey = contentResetKey + rowsDecodeGeneration += 1 + tokensDecodeGeneration += 1 + contentView.tokensByRowId = [:] + rows = [] + contentView.rows = [] + hasAppliedInitialRowIndex = false + pendingScrollFileId = nil + isProgrammaticScrollActive = false + scrollView.setContentOffset(.zero, animated: false) + updateContentMetrics() + updateViewportFrame() + lastVisibleFileId = nil + applyInitialRowIndexIfNeeded() + } + func setCollapsedFileIdsJson(_ collapsedFileIdsJson: String) { let nextCollapsedFileIds = decodeFileIdSet(collapsedFileIdsJson) let changedFileIds = contentView.collapsedFileIds.symmetricDifference(nextCollapsedFileIds) @@ -573,6 +666,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { contentView.invalidateVisibleViewport() contentView.setNeedsDisplay() applyInitialRowIndexIfNeeded() + applyPendingScrollIfNeeded() + emitVisibleFileIfNeeded() let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))" if debugKey != lastMetricsDebugKey { @@ -596,11 +691,41 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { } private func finishVerticalScroll() { + isProgrammaticScrollActive = false contentView.isVerticalScrollActive = false updateViewportFrame() emitVisibleRange(reason: "scroll-end") } + private func emitVisibleFileIfNeeded() { + // Keep the explicit destination selected while UIKit animates through the files + // between the old and new offsets. Emitting every intermediate header forces a + // React render per crossing and makes the navigator visibly flash. + guard !isProgrammaticScrollActive else { + return + } + + // The top of the combined diff is the explicit "All files" destination. + // Treat it as a first-class selection instead of immediately resolving the + // first file header and undoing the navigator's optimistic selection. + if scrollView.contentOffset.y <= 0.5 { + guard lastVisibleFileId != nil else { + return + } + lastVisibleFileId = nil + onVisibleFileChange(["fileId": NSNull()]) + return + } + + guard let fileId = contentView.visibleFileId(atVerticalOffset: scrollView.contentOffset.y), + fileId != lastVisibleFileId else { + return + } + + lastVisibleFileId = fileId + onVisibleFileChange(["fileId": fileId]) + } + private func emitVisibleRange(reason: String) { guard let range = contentView.currentVisibleRowRange() else { return @@ -670,6 +795,33 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { applyInitialRowIndexIfNeeded() } + func scrollToFile(_ fileId: String, animated: Bool) { + pendingScrollFileId = fileId + pendingScrollAnimated = animated + applyPendingScrollIfNeeded() + } + + func scrollToTop(animated: Bool) { + pendingScrollFileId = nil + pendingScrollAnimated = false + setVerticalContentOffset(0, animated: animated) + } + + @objc private func handlePullToRefresh() { + onPullToRefresh([:]) + } + + /// Driven from JS: set to false once the reload completes to dismiss the spinner. + func setRefreshing(_ refreshing: Bool) { + if refreshing { + if !pullRefreshControl.isRefreshing { + pullRefreshControl.beginRefreshing() + } + } else if pullRefreshControl.isRefreshing { + pullRefreshControl.endRefreshing() + } + } + private func applyStyle() { contentView.style = ReviewDiffNativeStyle .resolve(stylePayload) @@ -686,6 +838,38 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { ) contentView.verticalOffset = scrollView.contentOffset.y contentView.invalidateVisibleViewport() + emitVisibleFileIfNeeded() + } + + private func applyPendingScrollIfNeeded() { + guard let fileId = pendingScrollFileId, + bounds.height > 0 else { + return + } + + guard let headerOffset = contentView.fileHeaderOffset(forFileId: fileId) else { + if !rows.isEmpty { + pendingScrollFileId = nil + } + return + } + + let animated = pendingScrollAnimated + pendingScrollFileId = nil + pendingScrollAnimated = false + setVerticalContentOffset(headerOffset, animated: animated) + } + + private func setVerticalContentOffset(_ targetOffset: CGFloat, animated: Bool) { + let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0) + let clampedOffset = min(max(targetOffset, 0), maxOffset) + let shouldAnimate = animated && abs(scrollView.contentOffset.y - clampedOffset) > 0.5 + isProgrammaticScrollActive = shouldAnimate + contentView.isVerticalScrollActive = shouldAnimate + scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: shouldAnimate) + if !shouldAnimate { + updateViewportFrame() + } } private func applyInitialRowIndexIfNeeded() { @@ -1255,6 +1439,32 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return rowOffsets[rowIndex] } + func visibleFileId(atVerticalOffset verticalOffset: CGFloat) -> String? { + guard let firstHeaderRowIndex = fileHeaderRowIndices.first else { + return nil + } + + var lowerBound = 0 + var upperBound = fileHeaderRowIndices.count + while lowerBound < upperBound { + let midpoint = (lowerBound + upperBound) / 2 + let rowIndex = fileHeaderRowIndices[midpoint] + if rowOffsets[rowIndex] <= verticalOffset + 0.5 { + lowerBound = midpoint + 1 + } else { + upperBound = midpoint + } + } + + let rowIndex = lowerBound > 0 + ? fileHeaderRowIndices[lowerBound - 1] + : firstHeaderRowIndex + guard rows.indices.contains(rowIndex) else { + return nil + } + return resolvedFileId(for: rows[rowIndex]) + } + private func fileHeaderRowIndex(forFileId fileId: String) -> Int? { fileHeaderRowIndices.first { rowIndex in rows.indices.contains(rowIndex) && resolvedFileId(for: rows[rowIndex]) == fileId diff --git a/apps/mobile/modules/t3-review-diff/package.json b/apps/mobile/modules/t3-review-diff/package.json index 75ac49e5a9..4b3f91dbd8 100644 --- a/apps/mobile/modules/t3-review-diff/package.json +++ b/apps/mobile/modules/t3-review-diff/package.json @@ -7,6 +7,11 @@ "modules": [ "T3ReviewDiffModule" ] + }, + "android": { + "modules": [ + "expo.modules.t3reviewdiff.T3ReviewDiffModule" + ] } } } diff --git a/apps/mobile/modules/t3-terminal/README.md b/apps/mobile/modules/t3-terminal/README.md index 09d927f473..768e3c0704 100644 --- a/apps/mobile/modules/t3-terminal/README.md +++ b/apps/mobile/modules/t3-terminal/README.md @@ -18,9 +18,9 @@ uses that callback I/O model: 4. send user input back to JS with the write callback 5. emit Ghostty's measured terminal size through `onResize` -Android currently implements the same view name (`T3TerminalSurface`) and event payloads so the -React Native screen and RPC code stay platform-neutral. The renderer backend can be replaced with a -future Android Ghostty build without changing JS. +Android implements the same view contract with upstream `libghostty-vt` for terminal state, parsing, +reflow, and scrollback. An Android Canvas view renders compact snapshots produced by the JNI bridge, +so the React Native screen and RPC code stay platform-neutral. Vendored Ghostty revision and license details are in `THIRD_PARTY_NOTICES.md`. @@ -36,3 +36,15 @@ apps/mobile/modules/t3-terminal/scripts/build-libghostty-ios16.sh The script builds Ghostty with Zig 0.15.2, strips the iOS archives, and replaces only the `ios-arm64` and `ios-arm64-simulator` slices. Xcode's Metal toolchain must be installed; if `metal` fails, run `xcodebuild -downloadComponent MetalToolchain`. + +## Rebuilding libghostty-vt for Android + +The checked-in Android shared libraries and headers are pinned to the revision recorded in +`Vendor/libghostty-vt/VERSION`. Set `ANDROID_NDK_HOME` and run: + +```bash +apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh +``` + +The script downloads Zig 0.15.2 when needed, checks out the pinned upstream Ghostty revision, and +rebuilds all four Android ABIs with 16 KB page-size support. diff --git a/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md b/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md index 0ed6e1d148..990dd4bbe9 100644 --- a/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md +++ b/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md @@ -14,3 +14,21 @@ iOS 16 support fork. That fork was created from VVTerm's custom-I/O Ghostty fork Ghostty's MIT license applies to the vendored framework. Keep this notice in sync when updating `Vendor/libghostty`. + +## Ghostty / libghostty-vt + +The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers. + +- Upstream project: https://github.com/ghostty-org/ghostty +- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697` +- License: MIT + +Ghostty's MIT license applies to the vendored Android libraries. Keep this notice in sync when +updating `Vendor/libghostty-vt`. + +## MesloLGS NF (Android terminal font) + +- Files: `android/src/main/assets/fonts/MesloLGS-NF-{Regular,Bold}.ttf` +- Source: https://github.com/romkatv/powerlevel10k-media (Meslo LG patched with Nerd Fonts glyphs) +- Upstream: Meslo LG by André Berg (customization of Apple's Menlo), Nerd Fonts patcher +- License: Apache License 2.0 diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/LICENSE b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/LICENSE new file mode 100644 index 0000000000..0a07a66cd1 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Mitchell Hashimoto, Ghostty contributors + +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. diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/VERSION b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/VERSION new file mode 100644 index 0000000000..aa5d5e7421 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/VERSION @@ -0,0 +1 @@ +9f62873bf195e4d8a762d768a1405a5f2f7b1697 diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt.h new file mode 100644 index 0000000000..94a8503343 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt.h @@ -0,0 +1,154 @@ +/** + * @file vt.h + * + * libghostty-vt - Virtual terminal emulator library + * + * This library provides functionality for parsing and handling terminal + * escape sequences as well as maintaining terminal state such as styles, + * cursor position, screen, scrollback, and more. + * + * WARNING: This is an incomplete, work-in-progress API. It is not yet + * stable and is definitely going to change. + */ + +/** + * @mainpage libghostty-vt - Virtual Terminal Emulator Library + * + * libghostty-vt is a C library which implements a modern terminal emulator, + * extracted from the [Ghostty](https://ghostty.org) terminal emulator. + * + * libghostty-vt contains the logic for handling the core parts of a terminal + * emulator: parsing terminal escape sequences, maintaining terminal state, + * encoding input events, etc. It can handle scrollback, line wrapping, + * reflow on resize, and more. + * + * @warning This library is currently in development and the API is not yet stable. + * Breaking changes are expected in future versions. Use with caution in production code. + * + * @section groups_sec API Reference + * + * The API is organized into the following groups: + * - @ref terminal "Terminal" - Complete terminal emulator state and rendering + * - @ref render "Render State" - Incremental render state updates for custom renderers + * - @ref formatter "Formatter" - Format terminal content as plain text, VT sequences, or HTML + * - @ref osc "OSC Parser" - Parse OSC (Operating System Command) sequences + * - @ref sgr "SGR Parser" - Parse SGR (Select Graphic Rendition) sequences + * - @ref paste "Paste Utilities" - Validate paste data safety + * - @ref build_info "Build Info" - Query compile-time build configuration + * - @ref allocator "Memory Management" - Memory management and custom allocators + * - @ref wasm "WebAssembly Utilities" - WebAssembly convenience functions + * + * Encoding related APIs: + * - @ref focus "Focus Encoding" - Encode focus in/out events into terminal sequences + * - @ref key "Key Encoding" - Encode key events into terminal sequences + * - @ref mouse "Mouse Encoding" - Encode mouse events into terminal sequences + * + * @section examples_sec Examples + * + * Complete working examples: + * - @ref c-vt-build-info/src/main.c - Build info query example + * - @ref c-vt/src/main.c - OSC parser example + * - @ref c-vt-encode-key/src/main.c - Key encoding example + * - @ref c-vt-encode-mouse/src/main.c - Mouse encoding example + * - @ref c-vt-paste/src/main.c - Paste safety check example + * - @ref c-vt-sgr/src/main.c - SGR parser example + * - @ref c-vt-formatter/src/main.c - Terminal formatter example + * - @ref c-vt-grid-traverse/src/main.c - Grid traversal example using grid refs + * - @ref c-vt-grid-ref-tracked/src/main.c - Tracked grid ref example + * + */ + +/** @example c-vt-build-info/src/main.c + * This example demonstrates how to query compile-time build configuration + * such as SIMD support, Kitty graphics, and tmux control mode availability. + */ + +/** @example c-vt/src/main.c + * This example demonstrates how to use the OSC parser to parse an OSC sequence, + * extract command information, and retrieve command-specific data like window titles. + */ + +/** @example c-vt-encode-key/src/main.c + * This example demonstrates how to use the key encoder to convert key events + * into terminal escape sequences using the Kitty keyboard protocol. + */ + +/** @example c-vt-encode-mouse/src/main.c + * This example demonstrates how to use the mouse encoder to convert mouse events + * into terminal escape sequences using the SGR mouse format. + */ + +/** @example c-vt-paste/src/main.c + * This example demonstrates how to use the paste utilities to check if + * paste data is safe before sending it to the terminal. + */ + +/** @example c-vt-sgr/src/main.c + * This example demonstrates how to use the SGR parser to parse terminal + * styling sequences and extract text attributes like colors and underline styles. + */ + +/** @example c-vt-formatter/src/main.c + * This example demonstrates how to use the terminal and formatter APIs to + * create a terminal, write VT-encoded content into it, and format the screen + * contents as plain text. + */ + +/** @example c-vt-grid-traverse/src/main.c + * This example demonstrates how to traverse the entire terminal grid using + * grid refs to inspect cell codepoints, row wrap state, and cell styles. + */ + +/** @example c-vt-grid-ref-tracked/src/main.c + * This example demonstrates how to track a grid ref as the terminal scrolls, + * detect when it loses its value, and move it to a new point. + */ + +/** @example c-vt-selection-gesture/src/main.c + * This example demonstrates how to use synthetic selection gesture events to + * derive drag and deep-press selection snapshots. + */ + +/** @example c-vt-kitty-graphics/src/main.c + * This example demonstrates how to use the system interface to install a + * PNG decoder callback and send a Kitty Graphics Protocol image. + */ + +#ifndef GHOSTTY_VT_H +#define GHOSTTY_VT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/allocator.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/allocator.h new file mode 100644 index 0000000000..2e8685e844 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/allocator.h @@ -0,0 +1,255 @@ +/** + * @file allocator.h + * + * Memory management interface for libghostty-vt. + */ + +#ifndef GHOSTTY_VT_ALLOCATOR_H +#define GHOSTTY_VT_ALLOCATOR_H + +#include +#include +#include +#include + +/** @defgroup allocator Memory Management + * + * libghostty-vt does require memory allocation for various operations, + * but is resilient to allocation failures and will gracefully handle + * out-of-memory situations by returning error codes. + * + * The exact memory management semantics are documented in the relevant + * functions and data structures. + * + * libghostty-vt uses explicit memory allocation via an allocator + * interface provided by GhosttyAllocator. The interface is based on the + * [Zig](https://ziglang.org) allocator interface, since this has been + * shown to be a flexible and powerful interface in practice and enables + * a wide variety of allocation strategies. + * + * **For the common case, you can pass NULL as the allocator for any + * function that accepts one,** and libghostty will use a default allocator. + * The default allocator will be libc malloc/free if libc is linked. + * Otherwise, a custom allocator is used (currently Zig's SMP allocator) + * that doesn't require any external dependencies. + * + * ## Basic Usage + * + * For simple use cases, you can ignore this interface entirely by passing NULL + * as the allocator parameter to functions that accept one. This will use the + * default allocator (typically libc malloc/free, if libc is linked, but + * we provide our own default allocator if libc isn't linked). + * + * To use a custom allocator: + * 1. Implement the GhosttyAllocatorVtable function pointers + * 2. Create a GhosttyAllocator struct with your vtable and context + * 3. Pass the allocator to functions that accept one + * + * ## Alloc/Free Helpers + * + * ghostty_alloc() and ghostty_free() provide a simple malloc/free-style + * interface for allocating and freeing byte buffers through the library's + * allocator. These are useful when: + * + * - You need to allocate a buffer to pass into a libghostty-vt function + * (e.g. preparing input data for ghostty_terminal_vt_write()). + * - You need to free a buffer returned by a libghostty-vt function + * (e.g. the output of ghostty_formatter_format_alloc()). + * - You are on a platform where the library's internal allocator differs + * from the consumer's C runtime (e.g. Windows, where Zig's libc and + * MSVC's CRT maintain separate heaps), so calling the standard C + * free() on library-allocated memory would be undefined behavior. + * + * Always use the same allocator (or NULL) for both the allocation and + * the corresponding free. + * + * @{ + */ + +/** + * Function table for custom memory allocator operations. + * + * This vtable defines the interface for a custom memory allocator. All + * function pointers must be valid and non-NULL. + * + * @ingroup allocator + * + * If you're not going to use a custom allocator, you can ignore all of + * this. All functions that take an allocator pointer allow NULL to use a + * default allocator. + * + * The interface is based on the Zig allocator interface. I'll say up front + * that it is easy to look at this interface and think "wow, this is really + * overcomplicated". The reason for this complexity is well thought out by + * the Zig folks, and it enables a diverse set of allocation strategies + * as shown by the Zig ecosystem. As a consolation, please note that many + * of the arguments are only needed for advanced use cases and can be + * safely ignored in simple implementations. For example, if you look at + * the Zig implementation of the libc allocator in `lib/std/heap.zig` + * (search for CAllocator), you'll see it is very simple. + * + * We chose to align with the Zig allocator interface because: + * + * 1. It is a proven interface that serves a wide variety of use cases + * in the real world via the Zig ecosystem. It's shown to work. + * + * 2. Our core implementation itself is Zig, and this lets us very + * cheaply and easily convert between C and Zig allocators. + * + * NOTE(mitchellh): In the future, we can have default implementations of + * resize/remap and allow those to be null. + */ +typedef struct { + /** + * Return a pointer to `len` bytes with specified `alignment`, or return + * `NULL` indicating the allocation failed. + * + * @param ctx The allocator context + * @param len Number of bytes to allocate + * @param alignment Required alignment for the allocation. Guaranteed to + * be a power of two between 1 and 16 inclusive. + * @param ret_addr First return address of the allocation call stack (0 if not provided) + * @return Pointer to allocated memory, or NULL if allocation failed + */ + void* (*alloc)(void *ctx, size_t len, uint8_t alignment, uintptr_t ret_addr); + + /** + * Attempt to expand or shrink memory in place. + * + * `memory_len` must equal the length requested from the most recent + * successful call to `alloc`, `resize`, or `remap`. `alignment` must + * equal the same value that was passed as the `alignment` parameter to + * the original `alloc` call. + * + * `new_len` must be greater than zero. + * + * @param ctx The allocator context + * @param memory Pointer to the memory block to resize + * @param memory_len Current size of the memory block + * @param alignment Alignment (must match original allocation) + * @param new_len New requested size + * @param ret_addr First return address of the allocation call stack (0 if not provided) + * @return true if resize was successful in-place, false if relocation would be required + */ + bool (*resize)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr); + + /** + * Attempt to expand or shrink memory, allowing relocation. + * + * `memory_len` must equal the length requested from the most recent + * successful call to `alloc`, `resize`, or `remap`. `alignment` must + * equal the same value that was passed as the `alignment` parameter to + * the original `alloc` call. + * + * A non-`NULL` return value indicates the resize was successful. The + * allocation may have same address, or may have been relocated. In either + * case, the allocation now has size of `new_len`. A `NULL` return value + * indicates that the resize would be equivalent to allocating new memory, + * copying the bytes from the old memory, and then freeing the old memory. + * In such case, it is more efficient for the caller to perform the copy. + * + * `new_len` must be greater than zero. + * + * @param ctx The allocator context + * @param memory Pointer to the memory block to remap + * @param memory_len Current size of the memory block + * @param alignment Alignment (must match original allocation) + * @param new_len New requested size + * @param ret_addr First return address of the allocation call stack (0 if not provided) + * @return Pointer to resized memory (may be relocated), or NULL if manual copy is needed + */ + void* (*remap)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr); + + /** + * Free and invalidate a region of memory. + * + * `memory_len` must equal the length requested from the most recent + * successful call to `alloc`, `resize`, or `remap`. `alignment` must + * equal the same value that was passed as the `alignment` parameter to + * the original `alloc` call. + * + * @param ctx The allocator context + * @param memory Pointer to the memory block to free + * @param memory_len Size of the memory block + * @param alignment Alignment (must match original allocation) + * @param ret_addr First return address of the allocation call stack (0 if not provided) + */ + void (*free)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, uintptr_t ret_addr); +} GhosttyAllocatorVtable; + +/** + * Custom memory allocator. + * + * For functions that take an allocator pointer, a NULL pointer indicates + * that the default allocator should be used. The default allocator will + * be libc malloc/free if we're linking to libc. If libc isn't linked, + * a custom allocator is used (currently Zig's SMP allocator). + * + * @ingroup allocator + * + * Usage example: + * @code + * GhosttyAllocator allocator = { + * .vtable = &my_allocator_vtable, + * .ctx = my_allocator_state + * }; + * @endcode + */ +typedef struct GhosttyAllocator { + /** + * Opaque context pointer passed to all vtable functions. + * This allows the allocator implementation to maintain state + * or reference external resources needed for memory management. + */ + void *ctx; + + /** + * Pointer to the allocator's vtable containing function pointers + * for memory operations (alloc, resize, remap, free). + */ + const GhosttyAllocatorVtable *vtable; +} GhosttyAllocator; + +/** + * Allocate a buffer of `len` bytes. + * + * Uses the provided allocator, or the default allocator if NULL is passed. + * The returned buffer must be freed with ghostty_free() using the same + * allocator. + * + * @param allocator Pointer to the allocator to use, or NULL for the default + * @param len Number of bytes to allocate + * @return Pointer to the allocated buffer, or NULL if allocation failed + * + * @ingroup allocator + */ +GHOSTTY_API uint8_t* ghostty_alloc(const GhosttyAllocator* allocator, size_t len); + +/** + * Free memory that was allocated by a libghostty-vt function. + * + * Use this to free buffers returned by functions such as + * ghostty_formatter_format_alloc(). Pass the same allocator that was + * used for the allocation, or NULL if the default allocator was used. + * + * On platforms where the library's internal allocator differs from the + * consumer's C runtime (e.g. Windows, where Zig's libc and MSVC's CRT + * maintain separate heaps), calling the standard C free() on memory + * allocated by the library causes undefined behavior. This function + * guarantees the correct allocator is used regardless of platform. + * + * It is safe to pass a NULL pointer; the call is a no-op in that case. + * + * @param allocator Pointer to the allocator that was used to allocate the + * memory, or NULL if the default allocator was used + * @param ptr Pointer to the memory to free (may be NULL) + * @param len Length of the allocation in bytes (must match the original + * allocation size) + * + * @ingroup allocator + */ +GHOSTTY_API void ghostty_free(const GhosttyAllocator* allocator, uint8_t* ptr, size_t len); + +/** @} */ + +#endif /* GHOSTTY_VT_ALLOCATOR_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/build_info.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/build_info.h new file mode 100644 index 0000000000..8573556f7f --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/build_info.h @@ -0,0 +1,150 @@ +/** + * @file build_info.h + * + * Build info - query compile-time build configuration of libghostty-vt. + */ + +#ifndef GHOSTTY_VT_BUILD_INFO_H +#define GHOSTTY_VT_BUILD_INFO_H + +/** @defgroup build_info Build Info + * + * Query compile-time build configuration of libghostty-vt. + * + * These values reflect the options the library was built with and are + * constant for the lifetime of the process. + * + * ## Basic Usage + * + * Use ghostty_build_info() to query individual build options: + * + * @snippet c-vt-build-info/src/main.c build-info-query + * + * @{ + */ + +#include +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Build optimization mode. + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_OPTIMIZE_DEBUG = 0, + GHOSTTY_OPTIMIZE_RELEASE_SAFE = 1, + GHOSTTY_OPTIMIZE_RELEASE_SMALL = 2, + GHOSTTY_OPTIMIZE_RELEASE_FAST = 3, + GHOSTTY_OPTIMIZE_MODE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyOptimizeMode; + +/** + * Build info data types that can be queried. + * + * Each variant documents the expected output pointer type. + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Invalid data type. Never results in any data extraction. */ + GHOSTTY_BUILD_INFO_INVALID = 0, + + /** + * Whether SIMD-accelerated code paths are enabled. + * + * Output type: bool * + */ + GHOSTTY_BUILD_INFO_SIMD = 1, + + /** + * Whether Kitty graphics protocol support is available. + * + * Output type: bool * + */ + GHOSTTY_BUILD_INFO_KITTY_GRAPHICS = 2, + + /** + * Whether tmux control mode support is available. + * + * Output type: bool * + */ + GHOSTTY_BUILD_INFO_TMUX_CONTROL_MODE = 3, + + /** + * The optimization mode the library was built with. + * + * Output type: GhosttyOptimizeMode * + */ + GHOSTTY_BUILD_INFO_OPTIMIZE = 4, + + /** + * The full version string (e.g. "1.2.3" or "1.2.3-dev+abcdef"). + * + * Output type: GhosttyString * + */ + GHOSTTY_BUILD_INFO_VERSION_STRING = 5, + + /** + * The major version number. + * + * Output type: size_t * + */ + GHOSTTY_BUILD_INFO_VERSION_MAJOR = 6, + + /** + * The minor version number. + * + * Output type: size_t * + */ + GHOSTTY_BUILD_INFO_VERSION_MINOR = 7, + + /** + * The patch version number. + * + * Output type: size_t * + */ + GHOSTTY_BUILD_INFO_VERSION_PATCH = 8, + + /** + * The pre metadata string (e.g. "alpha", "beta", "dev"). Has zero length if + * no pre metadata is present. + * + * Output type: GhosttyString * + */ + GHOSTTY_BUILD_INFO_VERSION_PRE = 9, + + /** + * The build metadata string (e.g. commit hash). Has zero length if + * no build metadata is present. + * + * Output type: GhosttyString * + */ + GHOSTTY_BUILD_INFO_VERSION_BUILD = 10, + GHOSTTY_BUILD_INFO_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyBuildInfo; + +/** + * Query a compile-time build configuration value. + * + * The caller must pass a pointer to the correct output type for the + * requested data (see GhosttyBuildInfo variants for types). + * + * @param data The build info field to query + * @param out Pointer to store the result (type depends on data parameter) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the + * data type is invalid + * + * @ingroup build_info + */ +GHOSTTY_API GhosttyResult ghostty_build_info(GhosttyBuildInfo data, void *out); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_BUILD_INFO_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/color.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/color.h new file mode 100644 index 0000000000..9dc21864eb --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/color.h @@ -0,0 +1,97 @@ +/** + * @file color.h + * + * Color types and utilities. + */ + +#ifndef GHOSTTY_VT_COLOR_H +#define GHOSTTY_VT_COLOR_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * RGB color value. + * + * @ingroup sgr + */ +typedef struct { + uint8_t r; /**< Red component (0-255) */ + uint8_t g; /**< Green component (0-255) */ + uint8_t b; /**< Blue component (0-255) */ +} GhosttyColorRgb; + +/** + * Palette color index (0-255). + * + * @ingroup sgr + */ +typedef uint8_t GhosttyColorPaletteIndex; + +/** @addtogroup sgr + * @{ + */ + +/** Black color (0) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BLACK 0 +/** Red color (1) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_RED 1 +/** Green color (2) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_GREEN 2 +/** Yellow color (3) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_YELLOW 3 +/** Blue color (4) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BLUE 4 +/** Magenta color (5) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_MAGENTA 5 +/** Cyan color (6) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_CYAN 6 +/** White color (7) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_WHITE 7 +/** Bright black color (8) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_BLACK 8 +/** Bright red color (9) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_RED 9 +/** Bright green color (10) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_GREEN 10 +/** Bright yellow color (11) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_YELLOW 11 +/** Bright blue color (12) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_BLUE 12 +/** Bright magenta color (13) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_MAGENTA 13 +/** Bright cyan color (14) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_CYAN 14 +/** Bright white color (15) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_WHITE 15 + +/** @} */ + +/** + * Get the RGB color components. + * + * This function extracts the individual red, green, and blue components + * from a GhosttyColorRgb value. Primarily useful in WebAssembly environments + * where accessing struct fields directly is difficult. + * + * @param color The RGB color value + * @param r Pointer to store the red component (0-255) + * @param g Pointer to store the green component (0-255) + * @param b Pointer to store the blue component (0-255) + * + * @ingroup sgr + */ +GHOSTTY_API void ghostty_color_rgb_get(GhosttyColorRgb color, + uint8_t* r, + uint8_t* g, + uint8_t* b); + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_COLOR_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/device.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/device.h new file mode 100644 index 0000000000..0a1567280b --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/device.h @@ -0,0 +1,151 @@ +/** + * @file device.h + * + * Device types used by the terminal for device status and device attribute + * queries. + */ + +#ifndef GHOSTTY_VT_DEVICE_H +#define GHOSTTY_VT_DEVICE_H + +#include +#include + +/* DA1 conformance levels (Pp parameter). */ +#define GHOSTTY_DA_CONFORMANCE_VT100 1 +#define GHOSTTY_DA_CONFORMANCE_VT101 1 +#define GHOSTTY_DA_CONFORMANCE_VT102 6 +#define GHOSTTY_DA_CONFORMANCE_VT125 12 +#define GHOSTTY_DA_CONFORMANCE_VT131 7 +#define GHOSTTY_DA_CONFORMANCE_VT132 4 +#define GHOSTTY_DA_CONFORMANCE_VT220 62 +#define GHOSTTY_DA_CONFORMANCE_VT240 62 +#define GHOSTTY_DA_CONFORMANCE_VT320 63 +#define GHOSTTY_DA_CONFORMANCE_VT340 63 +#define GHOSTTY_DA_CONFORMANCE_VT420 64 +#define GHOSTTY_DA_CONFORMANCE_VT510 65 +#define GHOSTTY_DA_CONFORMANCE_VT520 65 +#define GHOSTTY_DA_CONFORMANCE_VT525 65 +#define GHOSTTY_DA_CONFORMANCE_LEVEL_2 62 +#define GHOSTTY_DA_CONFORMANCE_LEVEL_3 63 +#define GHOSTTY_DA_CONFORMANCE_LEVEL_4 64 +#define GHOSTTY_DA_CONFORMANCE_LEVEL_5 65 + +/* DA1 feature codes (Ps parameters). */ +#define GHOSTTY_DA_FEATURE_COLUMNS_132 1 +#define GHOSTTY_DA_FEATURE_PRINTER 2 +#define GHOSTTY_DA_FEATURE_REGIS 3 +#define GHOSTTY_DA_FEATURE_SIXEL 4 +#define GHOSTTY_DA_FEATURE_SELECTIVE_ERASE 6 +#define GHOSTTY_DA_FEATURE_USER_DEFINED_KEYS 8 +#define GHOSTTY_DA_FEATURE_NATIONAL_REPLACEMENT 9 +#define GHOSTTY_DA_FEATURE_TECHNICAL_CHARACTERS 15 +#define GHOSTTY_DA_FEATURE_LOCATOR 16 +#define GHOSTTY_DA_FEATURE_TERMINAL_STATE 17 +#define GHOSTTY_DA_FEATURE_WINDOWING 18 +#define GHOSTTY_DA_FEATURE_HORIZONTAL_SCROLLING 21 +#define GHOSTTY_DA_FEATURE_ANSI_COLOR 22 +#define GHOSTTY_DA_FEATURE_RECTANGULAR_EDITING 28 +#define GHOSTTY_DA_FEATURE_ANSI_TEXT_LOCATOR 29 +#define GHOSTTY_DA_FEATURE_CLIPBOARD 52 + +/* DA2 device type identifiers (Pp parameter). */ +#define GHOSTTY_DA_DEVICE_TYPE_VT100 0 +#define GHOSTTY_DA_DEVICE_TYPE_VT220 1 +#define GHOSTTY_DA_DEVICE_TYPE_VT240 2 +#define GHOSTTY_DA_DEVICE_TYPE_VT330 18 +#define GHOSTTY_DA_DEVICE_TYPE_VT340 19 +#define GHOSTTY_DA_DEVICE_TYPE_VT320 24 +#define GHOSTTY_DA_DEVICE_TYPE_VT382 32 +#define GHOSTTY_DA_DEVICE_TYPE_VT420 41 +#define GHOSTTY_DA_DEVICE_TYPE_VT510 61 +#define GHOSTTY_DA_DEVICE_TYPE_VT520 64 +#define GHOSTTY_DA_DEVICE_TYPE_VT525 65 + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Color scheme reported in response to a CSI ? 996 n query. + * + * @ingroup terminal + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_COLOR_SCHEME_LIGHT = 0, + GHOSTTY_COLOR_SCHEME_DARK = 1, + GHOSTTY_COLOR_SCHEME_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyColorScheme; + +/** + * Primary device attributes (DA1) response data. + * + * Returned as part of GhosttyDeviceAttributes in response to a CSI c query. + * The conformance_level is the Pp parameter and features contains the Ps + * feature codes. + * + * @ingroup terminal + */ +typedef struct { + /** Conformance level (Pp parameter). E.g. 62 for VT220. */ + uint16_t conformance_level; + + /** DA1 feature codes. Only the first num_features entries are valid. */ + uint16_t features[64]; + + /** Number of valid entries in the features array. */ + size_t num_features; +} GhosttyDeviceAttributesPrimary; + +/** + * Secondary device attributes (DA2) response data. + * + * Returned as part of GhosttyDeviceAttributes in response to a CSI > c query. + * Response format: CSI > Pp ; Pv ; Pc c + * + * @ingroup terminal + */ +typedef struct { + /** Terminal type identifier (Pp). E.g. 1 for VT220. */ + uint16_t device_type; + + /** Firmware/patch version number (Pv). */ + uint16_t firmware_version; + + /** ROM cartridge registration number (Pc). Always 0 for emulators. */ + uint16_t rom_cartridge; +} GhosttyDeviceAttributesSecondary; + +/** + * Tertiary device attributes (DA3) response data. + * + * Returned as part of GhosttyDeviceAttributes in response to a CSI = c query. + * Response format: DCS ! | D...D ST (DECRPTUI). + * + * @ingroup terminal + */ +typedef struct { + /** Unit ID encoded as 8 uppercase hex digits in the response. */ + uint32_t unit_id; +} GhosttyDeviceAttributesTertiary; + +/** + * Device attributes response data for all three DA levels. + * + * Filled by the device_attributes callback in response to CSI c, + * CSI > c, or CSI = c queries. The terminal uses whichever sub-struct + * matches the request type. + * + * @ingroup terminal + */ +typedef struct { + GhosttyDeviceAttributesPrimary primary; + GhosttyDeviceAttributesSecondary secondary; + GhosttyDeviceAttributesTertiary tertiary; +} GhosttyDeviceAttributes; + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_DEVICE_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/focus.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/focus.h new file mode 100644 index 0000000000..b9940f7924 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/focus.h @@ -0,0 +1,76 @@ +/** + * @file focus.h + * + * Focus encoding - encode focus in/out events into terminal escape sequences. + */ + +#ifndef GHOSTTY_VT_FOCUS_H +#define GHOSTTY_VT_FOCUS_H + +/** @defgroup focus Focus Encoding + * + * Utilities for encoding focus gained/lost events into terminal escape + * sequences (CSI I / CSI O) for focus reporting mode (mode 1004). + * + * ## Basic Usage + * + * Use ghostty_focus_encode() to encode a focus event into a caller-provided + * buffer. If the buffer is too small, the function returns + * GHOSTTY_OUT_OF_SPACE and sets the required size in the output parameter. + * + * ## Example + * + * @snippet c-vt-encode-focus/src/main.c focus-encode + * + * @{ + */ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Focus event types for focus reporting mode (mode 1004). + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Terminal window gained focus */ + GHOSTTY_FOCUS_GAINED = 0, + /** Terminal window lost focus */ + GHOSTTY_FOCUS_LOST = 1, + GHOSTTY_FOCUS_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyFocusEvent; + +/** + * Encode a focus event into a terminal escape sequence. + * + * Encodes a focus gained (CSI I) or focus lost (CSI O) report into the + * provided buffer. + * + * If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE + * and writes the required buffer size to @p out_written. The caller can + * then retry with a sufficiently sized buffer. + * + * @param event The focus event to encode + * @param buf Output buffer to write the encoded sequence into (may be NULL) + * @param buf_len Size of the output buffer in bytes + * @param[out] out_written On success, the number of bytes written. On + * GHOSTTY_OUT_OF_SPACE, the required buffer size. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer + * is too small + */ +GHOSTTY_API GhosttyResult ghostty_focus_encode( + GhosttyFocusEvent event, + char* buf, + size_t buf_len, + size_t* out_written); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_FOCUS_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/formatter.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/formatter.h new file mode 100644 index 0000000000..5cdcd11a3a --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/formatter.h @@ -0,0 +1,207 @@ +/** + * @file formatter.h + * + * Format terminal content as plain text, VT sequences, or HTML. + */ + +#ifndef GHOSTTY_VT_FORMATTER_H +#define GHOSTTY_VT_FORMATTER_H + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup formatter Formatter + * + * Format terminal content as plain text, VT sequences, or HTML. + * + * A formatter captures a reference to a terminal and formatting options. + * It can be used repeatedly to produce output that reflects the current + * terminal state at the time of each format call. + * + * The terminal must outlive the formatter. + * + * @{ + */ + +/** + * Extra screen state to include in styled output. + * + * @ingroup formatter + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterScreenExtra). */ + size_t size; + + /** Emit cursor position using CUP (CSI H). */ + bool cursor; + + /** Emit current SGR style state based on the cursor's active style_id. */ + bool style; + + /** Emit current hyperlink state using OSC 8 sequences. */ + bool hyperlink; + + /** Emit character protection mode using DECSCA. */ + bool protection; + + /** Emit Kitty keyboard protocol state using CSI > u and CSI = sequences. */ + bool kitty_keyboard; + + /** Emit character set designations and invocations. */ + bool charsets; +} GhosttyFormatterScreenExtra; + +/** + * Extra terminal state to include in styled output. + * + * @ingroup formatter + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterTerminalExtra). */ + size_t size; + + /** Emit the palette using OSC 4 sequences. */ + bool palette; + + /** Emit terminal modes that differ from their defaults using CSI h/l. */ + bool modes; + + /** Emit scrolling region state using DECSTBM and DECSLRM sequences. */ + bool scrolling_region; + + /** Emit tabstop positions by clearing all tabs and setting each one. */ + bool tabstops; + + /** Emit the present working directory using OSC 7. */ + bool pwd; + + /** Emit keyboard modes such as ModifyOtherKeys. */ + bool keyboard; + + /** Screen-level extras. */ + GhosttyFormatterScreenExtra screen; +} GhosttyFormatterTerminalExtra; + +/** + * Options for creating a terminal formatter. + * + * @ingroup formatter + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterTerminalOptions). */ + size_t size; + + /** Output format to emit. */ + GhosttyFormatterFormat emit; + + /** Whether to unwrap soft-wrapped lines. */ + bool unwrap; + + /** Whether to trim trailing whitespace on non-blank lines. */ + bool trim; + + /** Extra terminal state to include in styled output. */ + GhosttyFormatterTerminalExtra extra; + + /** Optional selection to restrict output to a range. + * If NULL, the entire screen is formatted. */ + const GhosttySelection *selection; +} GhosttyFormatterTerminalOptions; + +/** + * Create a formatter for a terminal's active screen. + * + * The terminal must outlive the formatter. The formatter stores a borrowed + * reference to the terminal and reads its current state on each format call. + * + * @param allocator Pointer to allocator, or NULL to use the default allocator + * @param formatter Pointer to store the created formatter handle + * @param terminal The terminal to format (must not be NULL) + * @param options Formatting options + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup formatter + */ +GHOSTTY_API GhosttyResult ghostty_formatter_terminal_new( + const GhosttyAllocator* allocator, + GhosttyFormatter* formatter, + GhosttyTerminal terminal, + GhosttyFormatterTerminalOptions options); + +/** + * Run the formatter and produce output into the caller-provided buffer. + * + * Each call formats the current terminal state. Pass NULL for buf to + * query the required buffer size without writing any output; in that case + * out_written receives the required size and the return value is + * GHOSTTY_OUT_OF_SPACE. + * + * If the buffer is too small, returns GHOSTTY_OUT_OF_SPACE and sets + * out_written to the required size. The caller can then retry with a + * larger buffer. + * + * @param formatter The formatter handle (must not be NULL) + * @param buf Pointer to the output buffer, or NULL to query size + * @param buf_len Length of the output buffer in bytes + * @param out_written Pointer to receive the number of bytes written, + * or the required size on failure + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup formatter + */ +GHOSTTY_API GhosttyResult ghostty_formatter_format_buf(GhosttyFormatter formatter, + uint8_t* buf, + size_t buf_len, + size_t* out_written); + +/** + * Run the formatter and return an allocated buffer with the output. + * + * Each call formats the current terminal state. The buffer is allocated + * using the provided allocator (or the default allocator if NULL). + * The caller is responsible for freeing the returned buffer with + * ghostty_free(), passing the same allocator (or NULL for the default) + * that was used for the allocation. + * + * @param formatter The formatter handle (must not be NULL) + * @param allocator Pointer to allocator, or NULL to use the default allocator + * @param out_ptr Pointer to receive the allocated buffer + * @param out_len Pointer to receive the length of the output in bytes + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation + * failure + * + * @ingroup formatter + */ +GHOSTTY_API GhosttyResult ghostty_formatter_format_alloc(GhosttyFormatter formatter, + const GhosttyAllocator* allocator, + uint8_t** out_ptr, + size_t* out_len); + +/** + * Free a formatter instance. + * + * Releases all resources associated with the formatter. After this call, + * the formatter handle becomes invalid. + * + * @param formatter The formatter handle to free (may be NULL) + * + * @ingroup formatter + */ +GHOSTTY_API void ghostty_formatter_free(GhosttyFormatter formatter); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_FORMATTER_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/grid_ref.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/grid_ref.h new file mode 100644 index 0000000000..c43791dc23 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/grid_ref.h @@ -0,0 +1,212 @@ +/** + * @file grid_ref.h + * + * Terminal grid reference type for referencing a resolved position in the + * terminal grid. + */ + +#ifndef GHOSTTY_VT_GRID_REF_H +#define GHOSTTY_VT_GRID_REF_H + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup grid_ref Grid Reference + * + * A grid reference is a reference to a specific cell position in the + * terminal. Obtain a grid reference from `ghostty_terminal_grid_ref` + * for untracked or `ghostty_terminal_grid_ref_track` for tracked. Untracked + * vs tracked is explained next. + * + * Important: The grid reference APIs are not meant to be used as the core of a render + * loop. They are not built to sustain the framerates needed for rendering large + * screens. Use the render state API for that. + * + * ## Untracked vs Tracked References + * + * ### Untracked Reference + * + * An untracked grid reference is a value type that snapshots a specific + * cell. It is only valid until the next update to the terminal instance. + * There is no guarantee that it will remain valid after any operation, + * even if a seemingly unrelated part of the grid is changed. These are meant + * to be read and have their values cached immediately after obtaining it. + * + * An untracked grid reference has a performance cost in its initial lookup, + * but doesn't affect the ongoing performance of the terminal in any way, + * since it is a one-time snapshot. + * + * ### Tracked Reference + * + * A tracked grid reference follows its cell across normal screen operations. + * For example scrolling, scrollback pruning, resize/reflow, and other + * terminal mutations update the tracked reference automatically. + * + * A tracked reference can still lose its original semantic location. This can + * happen when the underlying grid is reset, pruned, or otherwise discarded in a + * way that cannot be mapped to a meaningful new cell. In that state, + * ghostty_tracked_grid_ref_has_value() returns false and + * ghostty_tracked_grid_ref_snapshot() / ghostty_tracked_grid_ref_point() return + * GHOSTTY_NO_VALUE. The handle remains valid, and callers may move it to a new + * point with ghostty_tracked_grid_ref_set(). + * + * To read cell data from a tracked reference, first snapshot it with + * ghostty_tracked_grid_ref_snapshot(). The returned `GhosttyGridRef` is again + * an untracked reference and follows the same short lifetime rules as any other + * untracked grid reference. + * + * A tracked reference belongs to the terminal screen/page-list that was active + * when it was created or last set. Converting it to a point uses that owning + * screen/page-list, even if the terminal has since switched between primary and + * alternate screens. Calling ghostty_tracked_grid_ref_set() resolves the new + * point against the terminal's currently active screen/page-list and may move + * the tracked reference between screens. + * + * Tracked references are owned by the caller and must be freed with + * ghostty_tracked_grid_ref_free(). If the terminal that created a tracked + * reference is freed first, the handle remains valid only for tracked-grid-ref + * APIs: it reports no value and can still be freed. + * + * Each tracked reference adds bookkeeping to terminal mutations. Use them + * sparingly for long-lived anchors such as selections, search state, marks, + * or application-side bookmarks. + * + * ## Lifetime + * + * An untracked reference is a snapshot. It doesn't need to be freed. + * The safety of accessing the value is documented explicitly above: it + * is only safe to access any data until the next terminal mutating + * operation (including free). + * + * A tracked reference is allocated and must be freed when it is no + * longer needed. A tracked reference may outlive the terminal that created it; + * after terminal free, it reports no value and can still be freed. + * + * ## Examples + * + * @snippet c-vt-grid-traverse/src/main.c grid-ref-traverse + * @snippet c-vt-grid-ref-tracked/src/main.c grid-ref-tracked + * + * @{ + */ + +/** + * A resolved reference to a terminal cell position. + * + * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it. + * + * @ingroup grid_ref + */ +typedef struct { + size_t size; + void *node; + uint16_t x; + uint16_t y; +} GhosttyGridRef; + +/** + * Get the cell from a grid reference. + * + * @param ref Pointer to the grid reference + * @param[out] out_cell On success, set to the cell at the ref's position (may be NULL) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's + * node is NULL + * + * @ingroup grid_ref + */ +GHOSTTY_API GhosttyResult ghostty_grid_ref_cell(const GhosttyGridRef *ref, + GhosttyCell *out_cell); + +/** + * Get the row from a grid reference. + * + * @param ref Pointer to the grid reference + * @param[out] out_row On success, set to the row at the ref's position (may be NULL) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's + * node is NULL + * + * @ingroup grid_ref + */ +GHOSTTY_API GhosttyResult ghostty_grid_ref_row(const GhosttyGridRef *ref, + GhosttyRow *out_row); + +/** + * Get the grapheme cluster codepoints for the cell at the grid reference's + * position. + * + * Writes the full grapheme cluster (the cell's primary codepoint followed by + * any combining codepoints) into the provided buffer. If the cell has no text, + * out_len is set to 0 and GHOSTTY_SUCCESS is returned. + * + * If the buffer is too small (or NULL), the function returns + * GHOSTTY_OUT_OF_SPACE and writes the required number of codepoints to + * out_len. The caller can then retry with a sufficiently sized buffer. + * + * @param ref Pointer to the grid reference + * @param buf Output buffer of uint32_t codepoints (may be NULL) + * @param buf_len Number of uint32_t elements in the buffer + * @param[out] out_len On success, the number of codepoints written. On + * GHOSTTY_OUT_OF_SPACE, the required buffer size in codepoints. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's + * node is NULL, GHOSTTY_OUT_OF_SPACE if the buffer is too small + * + * @ingroup grid_ref + */ +GHOSTTY_API GhosttyResult ghostty_grid_ref_graphemes(const GhosttyGridRef *ref, + uint32_t *buf, + size_t buf_len, + size_t *out_len); + +/** + * Get the hyperlink URI for the cell at the grid reference's position. + * + * Writes the URI bytes into the provided buffer. If the cell has no + * hyperlink, out_len is set to 0 and GHOSTTY_SUCCESS is returned. + * + * If the buffer is too small (or NULL), the function returns + * GHOSTTY_OUT_OF_SPACE and writes the required number of bytes to + * out_len. The caller can then retry with a sufficiently sized buffer. + * + * @param ref Pointer to the grid reference + * @param buf Output buffer for the URI bytes (may be NULL) + * @param buf_len Size of the output buffer in bytes + * @param[out] out_len On success, the number of bytes written. On + * GHOSTTY_OUT_OF_SPACE, the required buffer size in bytes. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's + * node is NULL, GHOSTTY_OUT_OF_SPACE if the buffer is too small + * + * @ingroup grid_ref + */ +GHOSTTY_API GhosttyResult ghostty_grid_ref_hyperlink_uri( + const GhosttyGridRef *ref, + uint8_t *buf, + size_t buf_len, + size_t *out_len); + +/** + * Get the style of the cell at the grid reference's position. + * + * @param ref Pointer to the grid reference + * @param[out] out_style On success, set to the cell's style (may be NULL) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's + * node is NULL + * + * @ingroup grid_ref + */ +GHOSTTY_API GhosttyResult ghostty_grid_ref_style(const GhosttyGridRef *ref, + GhosttyStyle *out_style); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_GRID_REF_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/grid_ref_tracked.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/grid_ref_tracked.h new file mode 100644 index 0000000000..b56aefacdb --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/grid_ref_tracked.h @@ -0,0 +1,139 @@ +/** + * @file grid_ref_tracked.h + * + * Tracked terminal grid references. + */ + +#ifndef GHOSTTY_VT_GRID_REF_TRACKED_H +#define GHOSTTY_VT_GRID_REF_TRACKED_H + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Tracked grid references are owned grid references that move with the + * terminal. See @ref grid_ref for the full overview of tracked and untracked + * grid reference behavior. + * + * @ingroup grid_ref + */ + +/** + * Free a tracked grid reference. + * + * Passing NULL is allowed and has no effect. A tracked reference may be freed + * after the terminal that created it is freed. + * + * @param ref Tracked grid reference to free. + * + * @ingroup grid_ref + */ +GHOSTTY_API void ghostty_tracked_grid_ref_free(GhosttyTrackedGridRef ref); + +/** + * Return whether a tracked grid reference currently has a meaningful value. + * + * If the terminal that created the tracked reference has been freed, this + * returns false. + * + * @param ref Tracked grid reference. + * @return true if the reference currently has a meaningful value. + * + * @ingroup grid_ref + */ +GHOSTTY_API bool ghostty_tracked_grid_ref_has_value( + GhosttyTrackedGridRef ref); + +/** + * Convert a tracked grid reference to a point in the requested coordinate + * space. + * + * This is the tracked equivalent of ghostty_terminal_point_from_grid_ref(). + * Unlike snapshotting, this does not expose an intermediate untracked + * GhosttyGridRef. + * + * A tracked reference is resolved against the terminal screen/page-list that + * currently owns the reference. If the terminal has switched between primary + * and alternate screens since the reference was created or last set, this may + * be different from the terminal's currently active screen. + * + * If the tracked reference no longer has a meaningful value, this returns + * GHOSTTY_NO_VALUE. GHOSTTY_NO_VALUE is also returned when the reference cannot + * be represented in the requested coordinate space, including after the + * terminal that created the tracked reference has been freed. + * + * @param ref Tracked grid reference. + * @param tag Coordinate space to convert into. + * @param[out] out_point On success, receives the coordinate. May be NULL. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref is invalid, + * or GHOSTTY_NO_VALUE if there is no representable value. + * + * @ingroup grid_ref + */ +GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_point( + GhosttyTrackedGridRef ref, + GhosttyPointTag tag, + GhosttyPointCoordinate *out_point); + +/** + * Move an existing tracked grid reference to a new terminal point. + * + * On success, the tracked reference begins tracking the new point and any prior + * "no value" state is cleared. On GHOSTTY_OUT_OF_MEMORY, the original tracked + * reference is left unchanged. + * + * The terminal must be the same terminal that created the tracked reference. + * The point is resolved against the terminal screen/page-list that is active at + * the time this function is called. If the terminal has switched between + * primary and alternate screens, this may move the tracked reference from one + * screen/page-list to the other. + * + * @param ref Tracked grid reference. + * @param terminal Terminal instance that owns the reference. + * @param point New point to track. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref, terminal, + * or point is invalid, or GHOSTTY_OUT_OF_MEMORY if allocation fails. + * + * @ingroup grid_ref + */ +GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_set( + GhosttyTrackedGridRef ref, + GhosttyTerminal terminal, + GhosttyPoint point); + +/** + * Snapshot a tracked grid reference into a regular GhosttyGridRef. + * + * The returned GhosttyGridRef is an untracked snapshot and has the same + * lifetime rules as ghostty_terminal_grid_ref(): it is only valid until the + * next terminal update. Snapshot immediately before calling + * ghostty_grid_ref_cell(), ghostty_grid_ref_row(), + * ghostty_grid_ref_graphemes(), ghostty_grid_ref_hyperlink_uri(), or + * ghostty_grid_ref_style(). + * + * If the tracked reference no longer has a meaningful value, this returns + * GHOSTTY_NO_VALUE. This includes references whose owning terminal has been + * freed. + * + * @param ref Tracked grid reference. + * @param[out] out_ref On success, receives an untracked snapshot. May be NULL. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref is invalid, + * or GHOSTTY_NO_VALUE if the tracked location was discarded. + * + * @ingroup grid_ref + */ +GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_snapshot( + GhosttyTrackedGridRef ref, + GhosttyGridRef *out_ref); + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_GRID_REF_TRACKED_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key.h new file mode 100644 index 0000000000..61b9547535 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key.h @@ -0,0 +1,73 @@ +/** + * @file key.h + * + * Key encoding module - encode key events into terminal escape sequences. + */ + +#ifndef GHOSTTY_VT_KEY_H +#define GHOSTTY_VT_KEY_H + +/** @defgroup key Key Encoding + * + * Utilities for encoding key events into terminal escape sequences, + * supporting both legacy encoding as well as Kitty Keyboard Protocol. + * + * ## Basic Usage + * + * 1. Create an encoder instance with ghostty_key_encoder_new() + * 2. Configure encoder options with ghostty_key_encoder_setopt() + * or ghostty_key_encoder_setopt_from_terminal() if you have a + * GhosttyTerminal. + * 3. For each key event: + * - Create a key event with ghostty_key_event_new() + * - Set event properties (action, key, modifiers, etc.) + * - Encode with ghostty_key_encoder_encode() + * - Free the event with ghostty_key_event_free() + * - Note: You can also reuse the same key event multiple times by + * changing its properties. + * 4. Free the encoder with ghostty_key_encoder_free() when done + * + * For a complete working example, see example/c-vt-encode-key in the + * repository. + * + * ## Example + * + * @snippet c-vt-encode-key/src/main.c key-encode + * + * ## Example: Encoding with Terminal State + * + * When you have a GhosttyTerminal, you can sync its modes (cursor key + * application, Kitty flags, etc.) into the encoder automatically: + * + * @code{.c} + * // Create a terminal and feed it some VT data that changes modes + * GhosttyTerminal terminal; + * ghostty_terminal_new(NULL, &terminal, + * (GhosttyTerminalOptions){.cols = 80, .rows = 24, .max_scrollback = 0}); + * + * // Application might write data that enables Kitty keyboard protocol, etc. + * ghostty_terminal_vt_write(terminal, vt_data, vt_len); + * + * // Create an encoder and sync its options from the terminal + * GhosttyKeyEncoder encoder; + * ghostty_key_encoder_new(NULL, &encoder); + * ghostty_key_encoder_setopt_from_terminal(encoder, terminal); + * + * // Encode a key event using the terminal-derived options + * char buf[128]; + * size_t written = 0; + * ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written); + * + * ghostty_key_encoder_free(encoder); + * ghostty_terminal_free(terminal); + * @endcode + * + * @{ + */ + +#include +#include + +/** @} */ + +#endif /* GHOSTTY_VT_KEY_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key/encoder.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key/encoder.h new file mode 100644 index 0000000000..3aeec6597b --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key/encoder.h @@ -0,0 +1,255 @@ +/** + * @file encoder.h + * + * Key event encoding to terminal escape sequences. + */ + +#ifndef GHOSTTY_VT_KEY_ENCODER_H +#define GHOSTTY_VT_KEY_ENCODER_H + +#include +#include +#include +#include +#include +#include + +/** + * Opaque handle to a key encoder instance. + * + * This handle represents a key encoder that converts key events into terminal + * escape sequences. + * + * @ingroup key + */ +typedef struct GhosttyKeyEncoderImpl *GhosttyKeyEncoder; + +/** + * Kitty keyboard protocol flags. + * + * Bitflags representing the various modes of the Kitty keyboard protocol. + * These can be combined using bitwise OR operations. Valid values all + * start with `GHOSTTY_KITTY_KEY_`. + * + * @ingroup key + */ +typedef uint8_t GhosttyKittyKeyFlags; + +/** Kitty keyboard protocol disabled (all flags off) */ +#define GHOSTTY_KITTY_KEY_DISABLED 0 + +/** Disambiguate escape codes */ +#define GHOSTTY_KITTY_KEY_DISAMBIGUATE (1 << 0) + +/** Report key press and release events */ +#define GHOSTTY_KITTY_KEY_REPORT_EVENTS (1 << 1) + +/** Report alternate key codes */ +#define GHOSTTY_KITTY_KEY_REPORT_ALTERNATES (1 << 2) + +/** Report all key events including those normally handled by the terminal */ +#define GHOSTTY_KITTY_KEY_REPORT_ALL (1 << 3) + +/** Report associated text with key events */ +#define GHOSTTY_KITTY_KEY_REPORT_ASSOCIATED (1 << 4) + +/** All Kitty keyboard protocol flags enabled */ +#define GHOSTTY_KITTY_KEY_ALL (GHOSTTY_KITTY_KEY_DISAMBIGUATE | GHOSTTY_KITTY_KEY_REPORT_EVENTS | GHOSTTY_KITTY_KEY_REPORT_ALTERNATES | GHOSTTY_KITTY_KEY_REPORT_ALL | GHOSTTY_KITTY_KEY_REPORT_ASSOCIATED) + +/** + * macOS option key behavior. + * + * Determines whether the "option" key on macOS is treated as "alt" or not. + * See the Ghostty `macos-option-as-alt` configuration option for more details. + * + * @ingroup key + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Option key is not treated as alt */ + GHOSTTY_OPTION_AS_ALT_FALSE = 0, + /** Option key is treated as alt */ + GHOSTTY_OPTION_AS_ALT_TRUE = 1, + /** Only left option key is treated as alt */ + GHOSTTY_OPTION_AS_ALT_LEFT = 2, + /** Only right option key is treated as alt */ + GHOSTTY_OPTION_AS_ALT_RIGHT = 3, + GHOSTTY_OPTION_AS_ALT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyOptionAsAlt; + +/** + * Key encoder option identifiers. + * + * These values are used with ghostty_key_encoder_setopt() to configure + * the behavior of the key encoder. + * + * @ingroup key + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Terminal DEC mode 1: cursor key application mode (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_CURSOR_KEY_APPLICATION = 0, + + /** Terminal DEC mode 66: keypad key application mode (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_KEYPAD_KEY_APPLICATION = 1, + + /** Terminal DEC mode 1035: ignore keypad with numlock (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_IGNORE_KEYPAD_WITH_NUMLOCK = 2, + + /** Terminal DEC mode 1036: alt sends escape prefix (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_ALT_ESC_PREFIX = 3, + + /** xterm modifyOtherKeys mode 2 (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_MODIFY_OTHER_KEYS_STATE_2 = 4, + + /** Kitty keyboard protocol flags (value: GhosttyKittyKeyFlags bitmask) */ + GHOSTTY_KEY_ENCODER_OPT_KITTY_FLAGS = 5, + + /** macOS option-as-alt setting (value: GhosttyOptionAsAlt) */ + GHOSTTY_KEY_ENCODER_OPT_MACOS_OPTION_AS_ALT = 6, + + /** Backarrow key mode (value: bool) + * See https://vt100.net/dec/ek-vt3xx-tp-002.pdf page 170 + * If `false` (the default), `backspace` emits 0x7f + * If `true`, `backspace` emits 0x08 + */ + GHOSTTY_KEY_ENCODER_OPT_BACKARROW_KEY_MODE = 7, + + GHOSTTY_KEY_ENCODER_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyKeyEncoderOption; + +/** + * Create a new key encoder instance. + * + * Creates a new key encoder with default options. The encoder can be configured + * using ghostty_key_encoder_setopt() and must be freed using + * ghostty_key_encoder_free() when no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator + * @param encoder Pointer to store the created encoder handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup key + */ +GHOSTTY_API GhosttyResult ghostty_key_encoder_new(const GhosttyAllocator *allocator, GhosttyKeyEncoder *encoder); + +/** + * Free a key encoder instance. + * + * Releases all resources associated with the key encoder. After this call, + * the encoder handle becomes invalid and must not be used. + * + * @param encoder The encoder handle to free (may be NULL) + * + * @ingroup key + */ +GHOSTTY_API void ghostty_key_encoder_free(GhosttyKeyEncoder encoder); + +/** + * Set an option on the key encoder. + * + * Configures the behavior of the key encoder. Options control various aspects + * of encoding such as terminal modes (cursor key application mode, keypad mode), + * protocol selection (Kitty keyboard protocol flags), and platform-specific + * behaviors (macOS option-as-alt). + * + * If you are using a terminal instance, you can set the key encoding + * options based on the active terminal state (e.g. legacy vs Kitty mode + * and associated flags) with ghostty_key_encoder_setopt_from_terminal(). + * + * A null pointer value does nothing. It does not reset the value to the + * default. The setopt call will do nothing. + * + * @param encoder The encoder handle, must not be NULL + * @param option The option to set + * @param value Pointer to the value to set (type depends on the option) + * + * @ingroup key + */ +GHOSTTY_API void ghostty_key_encoder_setopt(GhosttyKeyEncoder encoder, GhosttyKeyEncoderOption option, const void *value); + +/** + * Set encoder options from a terminal's current state. + * + * Reads the terminal's current modes and flags and applies them to the + * encoder's options. This sets cursor key application mode, keypad mode, + * alt escape prefix, modifyOtherKeys state, and Kitty keyboard protocol + * flags from the terminal state. + * + * Note that the `macos_option_as_alt` option cannot be determined from + * terminal state and is reset to `GHOSTTY_OPTION_AS_ALT_FALSE` by this + * call. Use ghostty_key_encoder_setopt() to set it afterward if needed. + * + * @param encoder The encoder handle, must not be NULL + * @param terminal The terminal handle, must not be NULL + * + * @ingroup key + */ +GHOSTTY_API void ghostty_key_encoder_setopt_from_terminal(GhosttyKeyEncoder encoder, GhosttyTerminal terminal); + +/** + * Encode a key event into a terminal escape sequence. + * + * Converts a key event into the appropriate terminal escape sequence based on + * the encoder's current options. The sequence is written to the provided buffer. + * + * Not all key events produce output. For example, unmodified modifier keys + * typically don't generate escape sequences. Check the out_len parameter to + * determine if any data was written. + * + * If the output buffer is too small, this function returns GHOSTTY_OUT_OF_SPACE + * and out_len will contain the required buffer size. The caller can then + * allocate a larger buffer and call the function again. + * + * @param encoder The encoder handle, must not be NULL + * @param event The key event to encode, must not be NULL + * @param out_buf Buffer to write the encoded sequence to + * @param out_buf_size Size of the output buffer in bytes + * @param out_len Pointer to store the number of bytes written (may be NULL) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if buffer too small, or other error code + * + * ## Example: Calculate required buffer size + * + * @code{.c} + * // Query the required size with a NULL buffer (always returns OUT_OF_SPACE) + * size_t required = 0; + * GhosttyResult result = ghostty_key_encoder_encode(encoder, event, NULL, 0, &required); + * assert(result == GHOSTTY_OUT_OF_SPACE); + * + * // Allocate buffer of required size + * char *buf = malloc(required); + * + * // Encode with properly sized buffer + * size_t written = 0; + * result = ghostty_key_encoder_encode(encoder, event, buf, required, &written); + * assert(result == GHOSTTY_SUCCESS); + * + * // Use the encoded sequence... + * + * free(buf); + * @endcode + * + * ## Example: Direct encoding with static buffer + * + * @code{.c} + * // Most escape sequences are short, so a static buffer often suffices + * char buf[128]; + * size_t written = 0; + * GhosttyResult result = ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written); + * + * if (result == GHOSTTY_SUCCESS) { + * // Write the encoded sequence to the terminal + * write(pty_fd, buf, written); + * } else if (result == GHOSTTY_OUT_OF_SPACE) { + * // Buffer too small, written contains required size + * char *dynamic_buf = malloc(written); + * result = ghostty_key_encoder_encode(encoder, event, dynamic_buf, written, &written); + * assert(result == GHOSTTY_SUCCESS); + * write(pty_fd, dynamic_buf, written); + * free(dynamic_buf); + * } + * @endcode + * + * @ingroup key + */ +GHOSTTY_API GhosttyResult ghostty_key_encoder_encode(GhosttyKeyEncoder encoder, GhosttyKeyEvent event, char *out_buf, size_t out_buf_size, size_t *out_len); + +#endif /* GHOSTTY_VT_KEY_ENCODER_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key/event.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key/event.h new file mode 100644 index 0000000000..eba433c6a5 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/key/event.h @@ -0,0 +1,482 @@ +/** + * @file event.h + * + * Key event representation and manipulation. + */ + +#ifndef GHOSTTY_VT_KEY_EVENT_H +#define GHOSTTY_VT_KEY_EVENT_H + +#include +#include +#include +#include +#include + +/** + * Opaque handle to a key event. + * + * This handle represents a keyboard input event containing information about + * the physical key pressed, modifiers, and generated text. + * + * @ingroup key + */ +typedef struct GhosttyKeyEventImpl *GhosttyKeyEvent; + +/** + * Keyboard input event types. + * + * @ingroup key + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Key was released */ + GHOSTTY_KEY_ACTION_RELEASE = 0, + /** Key was pressed */ + GHOSTTY_KEY_ACTION_PRESS = 1, + /** Key is being repeated (held down) */ + GHOSTTY_KEY_ACTION_REPEAT = 2, + GHOSTTY_KEY_ACTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyKeyAction; + +/** + * Keyboard modifier keys bitmask. + * + * A bitmask representing all keyboard modifiers. This tracks which modifier keys + * are pressed and, where supported by the platform, which side (left or right) + * of each modifier is active. + * + * Use the GHOSTTY_MODS_* constants to test and set individual modifiers. + * + * Modifier side bits are only meaningful when the corresponding modifier bit is set. + * Not all platforms support distinguishing between left and right modifier + * keys and Ghostty is built to expect that some platforms may not provide this + * information. + * + * @ingroup key + */ +typedef uint16_t GhosttyMods; + +/** Shift key is pressed */ +#define GHOSTTY_MODS_SHIFT (1 << 0) +/** Control key is pressed */ +#define GHOSTTY_MODS_CTRL (1 << 1) +/** Alt/Option key is pressed */ +#define GHOSTTY_MODS_ALT (1 << 2) +/** Super/Command/Windows key is pressed */ +#define GHOSTTY_MODS_SUPER (1 << 3) +/** Caps Lock is active */ +#define GHOSTTY_MODS_CAPS_LOCK (1 << 4) +/** Num Lock is active */ +#define GHOSTTY_MODS_NUM_LOCK (1 << 5) + +/** + * Right shift is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_SHIFT is set. + */ +#define GHOSTTY_MODS_SHIFT_SIDE (1 << 6) +/** + * Right ctrl is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_CTRL is set. + */ +#define GHOSTTY_MODS_CTRL_SIDE (1 << 7) +/** + * Right alt is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_ALT is set. + */ +#define GHOSTTY_MODS_ALT_SIDE (1 << 8) +/** + * Right super is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_SUPER is set. + */ +#define GHOSTTY_MODS_SUPER_SIDE (1 << 9) + +/** + * Physical key codes. + * + * The set of key codes that Ghostty is aware of. These represent physical keys + * on the keyboard and are layout-independent. For example, the "a" key on a US + * keyboard is the same as the "ф" key on a Russian keyboard, but both will + * report the same key_a value. + * + * Layout-dependent strings are provided separately as UTF-8 text and are produced + * by the platform. These values are based on the W3C UI Events KeyboardEvent code + * standard. See: https://www.w3.org/TR/uievents-code + * + * @ingroup key + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_KEY_UNIDENTIFIED = 0, + + // Writing System Keys (W3C § 3.1.1) + GHOSTTY_KEY_BACKQUOTE, + GHOSTTY_KEY_BACKSLASH, + GHOSTTY_KEY_BRACKET_LEFT, + GHOSTTY_KEY_BRACKET_RIGHT, + GHOSTTY_KEY_COMMA, + GHOSTTY_KEY_DIGIT_0, + GHOSTTY_KEY_DIGIT_1, + GHOSTTY_KEY_DIGIT_2, + GHOSTTY_KEY_DIGIT_3, + GHOSTTY_KEY_DIGIT_4, + GHOSTTY_KEY_DIGIT_5, + GHOSTTY_KEY_DIGIT_6, + GHOSTTY_KEY_DIGIT_7, + GHOSTTY_KEY_DIGIT_8, + GHOSTTY_KEY_DIGIT_9, + GHOSTTY_KEY_EQUAL, + GHOSTTY_KEY_INTL_BACKSLASH, + GHOSTTY_KEY_INTL_RO, + GHOSTTY_KEY_INTL_YEN, + GHOSTTY_KEY_A, + GHOSTTY_KEY_B, + GHOSTTY_KEY_C, + GHOSTTY_KEY_D, + GHOSTTY_KEY_E, + GHOSTTY_KEY_F, + GHOSTTY_KEY_G, + GHOSTTY_KEY_H, + GHOSTTY_KEY_I, + GHOSTTY_KEY_J, + GHOSTTY_KEY_K, + GHOSTTY_KEY_L, + GHOSTTY_KEY_M, + GHOSTTY_KEY_N, + GHOSTTY_KEY_O, + GHOSTTY_KEY_P, + GHOSTTY_KEY_Q, + GHOSTTY_KEY_R, + GHOSTTY_KEY_S, + GHOSTTY_KEY_T, + GHOSTTY_KEY_U, + GHOSTTY_KEY_V, + GHOSTTY_KEY_W, + GHOSTTY_KEY_X, + GHOSTTY_KEY_Y, + GHOSTTY_KEY_Z, + GHOSTTY_KEY_MINUS, + GHOSTTY_KEY_PERIOD, + GHOSTTY_KEY_QUOTE, + GHOSTTY_KEY_SEMICOLON, + GHOSTTY_KEY_SLASH, + + // Functional Keys (W3C § 3.1.2) + GHOSTTY_KEY_ALT_LEFT, + GHOSTTY_KEY_ALT_RIGHT, + GHOSTTY_KEY_BACKSPACE, + GHOSTTY_KEY_CAPS_LOCK, + GHOSTTY_KEY_CONTEXT_MENU, + GHOSTTY_KEY_CONTROL_LEFT, + GHOSTTY_KEY_CONTROL_RIGHT, + GHOSTTY_KEY_ENTER, + GHOSTTY_KEY_META_LEFT, + GHOSTTY_KEY_META_RIGHT, + GHOSTTY_KEY_SHIFT_LEFT, + GHOSTTY_KEY_SHIFT_RIGHT, + GHOSTTY_KEY_SPACE, + GHOSTTY_KEY_TAB, + GHOSTTY_KEY_CONVERT, + GHOSTTY_KEY_KANA_MODE, + GHOSTTY_KEY_NON_CONVERT, + + // Control Pad Section (W3C § 3.2) + GHOSTTY_KEY_DELETE, + GHOSTTY_KEY_END, + GHOSTTY_KEY_HELP, + GHOSTTY_KEY_HOME, + GHOSTTY_KEY_INSERT, + GHOSTTY_KEY_PAGE_DOWN, + GHOSTTY_KEY_PAGE_UP, + + // Arrow Pad Section (W3C § 3.3) + GHOSTTY_KEY_ARROW_DOWN, + GHOSTTY_KEY_ARROW_LEFT, + GHOSTTY_KEY_ARROW_RIGHT, + GHOSTTY_KEY_ARROW_UP, + + // Numpad Section (W3C § 3.4) + GHOSTTY_KEY_NUM_LOCK, + GHOSTTY_KEY_NUMPAD_0, + GHOSTTY_KEY_NUMPAD_1, + GHOSTTY_KEY_NUMPAD_2, + GHOSTTY_KEY_NUMPAD_3, + GHOSTTY_KEY_NUMPAD_4, + GHOSTTY_KEY_NUMPAD_5, + GHOSTTY_KEY_NUMPAD_6, + GHOSTTY_KEY_NUMPAD_7, + GHOSTTY_KEY_NUMPAD_8, + GHOSTTY_KEY_NUMPAD_9, + GHOSTTY_KEY_NUMPAD_ADD, + GHOSTTY_KEY_NUMPAD_BACKSPACE, + GHOSTTY_KEY_NUMPAD_CLEAR, + GHOSTTY_KEY_NUMPAD_CLEAR_ENTRY, + GHOSTTY_KEY_NUMPAD_COMMA, + GHOSTTY_KEY_NUMPAD_DECIMAL, + GHOSTTY_KEY_NUMPAD_DIVIDE, + GHOSTTY_KEY_NUMPAD_ENTER, + GHOSTTY_KEY_NUMPAD_EQUAL, + GHOSTTY_KEY_NUMPAD_MEMORY_ADD, + GHOSTTY_KEY_NUMPAD_MEMORY_CLEAR, + GHOSTTY_KEY_NUMPAD_MEMORY_RECALL, + GHOSTTY_KEY_NUMPAD_MEMORY_STORE, + GHOSTTY_KEY_NUMPAD_MEMORY_SUBTRACT, + GHOSTTY_KEY_NUMPAD_MULTIPLY, + GHOSTTY_KEY_NUMPAD_PAREN_LEFT, + GHOSTTY_KEY_NUMPAD_PAREN_RIGHT, + GHOSTTY_KEY_NUMPAD_SUBTRACT, + GHOSTTY_KEY_NUMPAD_SEPARATOR, + GHOSTTY_KEY_NUMPAD_UP, + GHOSTTY_KEY_NUMPAD_DOWN, + GHOSTTY_KEY_NUMPAD_RIGHT, + GHOSTTY_KEY_NUMPAD_LEFT, + GHOSTTY_KEY_NUMPAD_BEGIN, + GHOSTTY_KEY_NUMPAD_HOME, + GHOSTTY_KEY_NUMPAD_END, + GHOSTTY_KEY_NUMPAD_INSERT, + GHOSTTY_KEY_NUMPAD_DELETE, + GHOSTTY_KEY_NUMPAD_PAGE_UP, + GHOSTTY_KEY_NUMPAD_PAGE_DOWN, + + // Function Section (W3C § 3.5) + GHOSTTY_KEY_ESCAPE, + GHOSTTY_KEY_F1, + GHOSTTY_KEY_F2, + GHOSTTY_KEY_F3, + GHOSTTY_KEY_F4, + GHOSTTY_KEY_F5, + GHOSTTY_KEY_F6, + GHOSTTY_KEY_F7, + GHOSTTY_KEY_F8, + GHOSTTY_KEY_F9, + GHOSTTY_KEY_F10, + GHOSTTY_KEY_F11, + GHOSTTY_KEY_F12, + GHOSTTY_KEY_F13, + GHOSTTY_KEY_F14, + GHOSTTY_KEY_F15, + GHOSTTY_KEY_F16, + GHOSTTY_KEY_F17, + GHOSTTY_KEY_F18, + GHOSTTY_KEY_F19, + GHOSTTY_KEY_F20, + GHOSTTY_KEY_F21, + GHOSTTY_KEY_F22, + GHOSTTY_KEY_F23, + GHOSTTY_KEY_F24, + GHOSTTY_KEY_F25, + GHOSTTY_KEY_FN, + GHOSTTY_KEY_FN_LOCK, + GHOSTTY_KEY_PRINT_SCREEN, + GHOSTTY_KEY_SCROLL_LOCK, + GHOSTTY_KEY_PAUSE, + + // Media Keys (W3C § 3.6) + GHOSTTY_KEY_BROWSER_BACK, + GHOSTTY_KEY_BROWSER_FAVORITES, + GHOSTTY_KEY_BROWSER_FORWARD, + GHOSTTY_KEY_BROWSER_HOME, + GHOSTTY_KEY_BROWSER_REFRESH, + GHOSTTY_KEY_BROWSER_SEARCH, + GHOSTTY_KEY_BROWSER_STOP, + GHOSTTY_KEY_EJECT, + GHOSTTY_KEY_LAUNCH_APP_1, + GHOSTTY_KEY_LAUNCH_APP_2, + GHOSTTY_KEY_LAUNCH_MAIL, + GHOSTTY_KEY_MEDIA_PLAY_PAUSE, + GHOSTTY_KEY_MEDIA_SELECT, + GHOSTTY_KEY_MEDIA_STOP, + GHOSTTY_KEY_MEDIA_TRACK_NEXT, + GHOSTTY_KEY_MEDIA_TRACK_PREVIOUS, + GHOSTTY_KEY_POWER, + GHOSTTY_KEY_SLEEP, + GHOSTTY_KEY_AUDIO_VOLUME_DOWN, + GHOSTTY_KEY_AUDIO_VOLUME_MUTE, + GHOSTTY_KEY_AUDIO_VOLUME_UP, + GHOSTTY_KEY_WAKE_UP, + + // Legacy, Non-standard, and Special Keys (W3C § 3.7) + GHOSTTY_KEY_COPY, + GHOSTTY_KEY_CUT, + GHOSTTY_KEY_PASTE, + GHOSTTY_KEY_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyKey; + +/** + * Create a new key event instance. + * + * Creates a new key event with default values. The event must be freed using + * ghostty_key_event_free() when no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator + * @param event Pointer to store the created key event handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup key + */ +GHOSTTY_API GhosttyResult ghostty_key_event_new(const GhosttyAllocator *allocator, GhosttyKeyEvent *event); + +/** + * Free a key event instance. + * + * Releases all resources associated with the key event. After this call, + * the event handle becomes invalid and must not be used. + * + * @param event The key event handle to free (may be NULL) + * + * @ingroup key + */ +GHOSTTY_API void ghostty_key_event_free(GhosttyKeyEvent event); + +/** + * Set the key action (press, release, repeat). + * + * @param event The key event handle, must not be NULL + * @param action The action to set + * + * @ingroup key + */ +GHOSTTY_API void ghostty_key_event_set_action(GhosttyKeyEvent event, GhosttyKeyAction action); + +/** + * Get the key action (press, release, repeat). + * + * @param event The key event handle, must not be NULL + * @return The key action + * + * @ingroup key + */ +GHOSTTY_API GhosttyKeyAction ghostty_key_event_get_action(GhosttyKeyEvent event); + +/** + * Set the physical key code. + * + * @param event The key event handle, must not be NULL + * @param key The physical key code to set + * + * @ingroup key + */ +GHOSTTY_API void ghostty_key_event_set_key(GhosttyKeyEvent event, GhosttyKey key); + +/** + * Get the physical key code. + * + * @param event The key event handle, must not be NULL + * @return The physical key code + * + * @ingroup key + */ +GHOSTTY_API GhosttyKey ghostty_key_event_get_key(GhosttyKeyEvent event); + +/** + * Set the modifier keys bitmask. + * + * @param event The key event handle, must not be NULL + * @param mods The modifier keys bitmask to set + * + * @ingroup key + */ +GHOSTTY_API void ghostty_key_event_set_mods(GhosttyKeyEvent event, GhosttyMods mods); + +/** + * Get the modifier keys bitmask. + * + * @param event The key event handle, must not be NULL + * @return The modifier keys bitmask + * + * @ingroup key + */ +GHOSTTY_API GhosttyMods ghostty_key_event_get_mods(GhosttyKeyEvent event); + +/** + * Set the consumed modifiers bitmask. + * + * @param event The key event handle, must not be NULL + * @param consumed_mods The consumed modifiers bitmask to set + * + * @ingroup key + */ +GHOSTTY_API void ghostty_key_event_set_consumed_mods(GhosttyKeyEvent event, GhosttyMods consumed_mods); + +/** + * Get the consumed modifiers bitmask. + * + * @param event The key event handle, must not be NULL + * @return The consumed modifiers bitmask + * + * @ingroup key + */ +GHOSTTY_API GhosttyMods ghostty_key_event_get_consumed_mods(GhosttyKeyEvent event); + +/** + * Set whether the key event is part of a composition sequence. + * + * @param event The key event handle, must not be NULL + * @param composing Whether the key event is part of a composition sequence + * + * @ingroup key + */ +GHOSTTY_API void ghostty_key_event_set_composing(GhosttyKeyEvent event, bool composing); + +/** + * Get whether the key event is part of a composition sequence. + * + * @param event The key event handle, must not be NULL + * @return Whether the key event is part of a composition sequence + * + * @ingroup key + */ +GHOSTTY_API bool ghostty_key_event_get_composing(GhosttyKeyEvent event); + +/** + * Set the UTF-8 text generated by the key for the current keyboard layout. + * + * Must contain the unmodified character before any Ctrl/Meta transformations. + * The encoder derives modifier sequences from the logical key and mods + * bitmask, not from this text. Do not pass C0 control characters + * (U+0000-U+001F, U+007F) or platform function key codes (e.g. macOS PUA + * U+F700-U+F8FF); pass NULL instead and let the encoder use the logical key. + * + * The key event does NOT take ownership of the text pointer. The caller + * must ensure the string remains valid for the lifetime needed by the event. + * + * @param event The key event handle, must not be NULL + * @param utf8 The UTF-8 text to set (or NULL for empty) + * @param len Length of the UTF-8 text in bytes + * + * @ingroup key + */ +GHOSTTY_API void ghostty_key_event_set_utf8(GhosttyKeyEvent event, const char *utf8, size_t len); + +/** + * Get the UTF-8 text generated by the key event. + * + * The returned pointer is valid until the event is freed or the UTF-8 text is modified. + * + * @param event The key event handle, must not be NULL + * @param len Pointer to store the length of the UTF-8 text in bytes (may be NULL) + * @return The UTF-8 text (or NULL for empty) + * + * @ingroup key + */ +GHOSTTY_API const char *ghostty_key_event_get_utf8(GhosttyKeyEvent event, size_t *len); + +/** + * Set the unshifted Unicode codepoint. + * + * @param event The key event handle, must not be NULL + * @param codepoint The unshifted Unicode codepoint to set + * + * @ingroup key + */ +GHOSTTY_API void ghostty_key_event_set_unshifted_codepoint(GhosttyKeyEvent event, uint32_t codepoint); + +/** + * Get the unshifted Unicode codepoint. + * + * @param event The key event handle, must not be NULL + * @return The unshifted Unicode codepoint + * + * @ingroup key + */ +GHOSTTY_API uint32_t ghostty_key_event_get_unshifted_codepoint(GhosttyKeyEvent event); + +#endif /* GHOSTTY_VT_KEY_EVENT_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/kitty_graphics.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/kitty_graphics.h new file mode 100644 index 0000000000..9bace3a3cc --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/kitty_graphics.h @@ -0,0 +1,775 @@ +/** + * @file kitty_graphics.h + * + * Kitty graphics protocol + * + * See @ref kitty_graphics for a full usage guide. + */ + +#ifndef GHOSTTY_VT_KITTY_GRAPHICS_H +#define GHOSTTY_VT_KITTY_GRAPHICS_H + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup kitty_graphics Kitty Graphics + * + * API for inspecting images and placements stored via the + * [Kitty graphics protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/). + * + * The central object is @ref GhosttyKittyGraphics, an opaque handle to + * the image storage associated with a terminal's active screen. From it + * you can iterate over placements and look up individual images. + * + * ## Obtaining a KittyGraphics Handle + * + * A @ref GhosttyKittyGraphics handle is obtained from a terminal via + * ghostty_terminal_get() with @ref GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS. + * The handle is borrowed from the terminal and remains valid until the + * next mutating terminal call (e.g. ghostty_terminal_vt_write() or + * ghostty_terminal_reset()). + * + * Before images can be stored, Kitty graphics must be enabled on the + * terminal by setting a non-zero storage limit with + * @ref GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_STORAGE_LIMIT, and a PNG + * decoder callback must be installed via ghostty_sys_set() with + * @ref GHOSTTY_SYS_OPT_DECODE_PNG. + * + * @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-decode-png + * + * ## Iterating Placements + * + * Placements are inspected through a @ref GhosttyKittyGraphicsPlacementIterator. + * The typical workflow is: + * + * 1. Create an iterator with ghostty_kitty_graphics_placement_iterator_new(). + * 2. Populate it from the storage with ghostty_kitty_graphics_get() using + * @ref GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR. + * 3. Optionally filter by z-layer with + * ghostty_kitty_graphics_placement_iterator_set(). + * 4. Advance with ghostty_kitty_graphics_placement_next() and read + * per-placement data with ghostty_kitty_graphics_placement_get(). + * 5. For each placement, look up its image with + * ghostty_kitty_graphics_image() to access pixel data and dimensions. + * 6. Free the iterator with ghostty_kitty_graphics_placement_iterator_free(). + * + * ## Looking Up Images + * + * Given an image ID (obtained from a placement via + * @ref GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID), call + * ghostty_kitty_graphics_image() to get a @ref GhosttyKittyGraphicsImage + * handle. From this handle, ghostty_kitty_graphics_image_get() provides + * the image dimensions, pixel format, compression, and a borrowed pointer + * to the raw pixel data. + * + * ## Rendering Helpers + * + * Several functions assist with rendering a placement: + * + * - ghostty_kitty_graphics_placement_pixel_size() — rendered pixel + * dimensions accounting for source rect and aspect ratio. + * - ghostty_kitty_graphics_placement_grid_size() — number of grid + * columns and rows the placement occupies. + * - ghostty_kitty_graphics_placement_viewport_pos() — viewport-relative + * grid position (may be negative for partially scrolled placements). + * - ghostty_kitty_graphics_placement_source_rect() — resolved source + * rectangle in pixels, clamped to image bounds. + * - ghostty_kitty_graphics_placement_rect() — bounding rectangle as a + * @ref GhosttySelection. + * + * ## Lifetime and Thread Safety + * + * All handles borrowed from the terminal (GhosttyKittyGraphics, + * GhosttyKittyGraphicsImage) are invalidated by any mutating terminal + * call. The placement iterator is independently owned and must be freed + * by the caller, but the data it yields is only valid while the + * underlying terminal is not mutated. + * + * ## Example + * + * The following example creates a terminal, sends a Kitty graphics + * image, then iterates placements and prints image metadata: + * + * @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-main + * + * @{ + */ + +/** + * Queryable data kinds for ghostty_kitty_graphics_get(). + * + * @ingroup kitty_graphics + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Invalid / sentinel value. */ + GHOSTTY_KITTY_GRAPHICS_DATA_INVALID = 0, + + /** + * Populate a pre-allocated placement iterator with placement data from + * the storage. Iterator data is only valid as long as the underlying + * terminal is not mutated. + * + * Output type: GhosttyKittyGraphicsPlacementIterator * + */ + GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR = 1, + GHOSTTY_KITTY_GRAPHICS_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyKittyGraphicsData; + +/** + * Queryable data kinds for ghostty_kitty_graphics_placement_get(). + * + * @ingroup kitty_graphics + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Invalid / sentinel value. */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_INVALID = 0, + + /** + * The image ID this placement belongs to. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID = 1, + + /** + * The placement ID. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_PLACEMENT_ID = 2, + + /** + * Whether this is a virtual placement (unicode placeholder). + * + * Output type: bool * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IS_VIRTUAL = 3, + + /** + * Pixel offset from the left edge of the cell. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_X_OFFSET = 4, + + /** + * Pixel offset from the top edge of the cell. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Y_OFFSET = 5, + + /** + * Source rectangle x origin in pixels. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_X = 6, + + /** + * Source rectangle y origin in pixels. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_Y = 7, + + /** + * Source rectangle width in pixels (0 = full image width). + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_WIDTH = 8, + + /** + * Source rectangle height in pixels (0 = full image height). + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_HEIGHT = 9, + + /** + * Number of columns this placement occupies. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_COLUMNS = 10, + + /** + * Number of rows this placement occupies. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_ROWS = 11, + + /** + * Z-index for this placement. + * + * Output type: int32_t * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Z = 12, + + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyKittyGraphicsPlacementData; + +/** + * Z-layer classification for kitty graphics placements. + * + * Based on the kitty protocol z-index conventions: + * - BELOW_BG: z < INT32_MIN/2 (drawn below cell background) + * - BELOW_TEXT: INT32_MIN/2 <= z < 0 (above background, below text) + * - ABOVE_TEXT: z >= 0 (above text) + * - ALL: no filtering (current behavior) + * + * @ingroup kitty_graphics + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_KITTY_PLACEMENT_LAYER_ALL = 0, + GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_BG = 1, + GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_TEXT = 2, + GHOSTTY_KITTY_PLACEMENT_LAYER_ABOVE_TEXT = 3, + GHOSTTY_KITTY_PLACEMENT_LAYER_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyKittyPlacementLayer; + +/** + * Settable options for ghostty_kitty_graphics_placement_iterator_set(). + * + * @ingroup kitty_graphics + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** + * Set the z-layer filter for the iterator. + * + * Input type: GhosttyKittyPlacementLayer * + */ + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER = 0, + GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyKittyGraphicsPlacementIteratorOption; + +/** + * Pixel format of a Kitty graphics image. + * + * @ingroup kitty_graphics + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_KITTY_IMAGE_FORMAT_RGB = 0, + GHOSTTY_KITTY_IMAGE_FORMAT_RGBA = 1, + GHOSTTY_KITTY_IMAGE_FORMAT_PNG = 2, + GHOSTTY_KITTY_IMAGE_FORMAT_GRAY_ALPHA = 3, + GHOSTTY_KITTY_IMAGE_FORMAT_GRAY = 4, + GHOSTTY_KITTY_IMAGE_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyKittyImageFormat; + +/** + * Compression of a Kitty graphics image. + * + * @ingroup kitty_graphics + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_KITTY_IMAGE_COMPRESSION_NONE = 0, + GHOSTTY_KITTY_IMAGE_COMPRESSION_ZLIB_DEFLATE = 1, + GHOSTTY_KITTY_IMAGE_COMPRESSION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyKittyImageCompression; + +/** + * Queryable data kinds for ghostty_kitty_graphics_image_get(). + * + * @ingroup kitty_graphics + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Invalid / sentinel value. */ + GHOSTTY_KITTY_IMAGE_DATA_INVALID = 0, + + /** + * The image ID. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_IMAGE_DATA_ID = 1, + + /** + * The image number. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_IMAGE_DATA_NUMBER = 2, + + /** + * Image width in pixels. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_IMAGE_DATA_WIDTH = 3, + + /** + * Image height in pixels. + * + * Output type: uint32_t * + */ + GHOSTTY_KITTY_IMAGE_DATA_HEIGHT = 4, + + /** + * Pixel format of the image. + * + * Output type: GhosttyKittyImageFormat * + */ + GHOSTTY_KITTY_IMAGE_DATA_FORMAT = 5, + + /** + * Compression of the image. + * + * Output type: GhosttyKittyImageCompression * + */ + GHOSTTY_KITTY_IMAGE_DATA_COMPRESSION = 6, + + /** + * Borrowed pointer to the raw pixel data. Valid as long as the + * underlying terminal is not mutated. + * + * Output type: const uint8_t ** + */ + GHOSTTY_KITTY_IMAGE_DATA_DATA_PTR = 7, + + /** + * Length of the raw pixel data in bytes. + * + * Output type: size_t * + */ + GHOSTTY_KITTY_IMAGE_DATA_DATA_LEN = 8, + + GHOSTTY_KITTY_IMAGE_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyKittyGraphicsImageData; + +/** + * Combined rendering geometry for a placement in a single sized struct. + * + * Combines the results of ghostty_kitty_graphics_placement_pixel_size(), + * ghostty_kitty_graphics_placement_grid_size(), + * ghostty_kitty_graphics_placement_viewport_pos(), and + * ghostty_kitty_graphics_placement_source_rect() into one call. This is + * an optimization over calling those four functions individually, + * particularly useful in environments with high per-call overhead such + * as FFI or Cgo. + * + * This struct uses the sized-struct ABI pattern. Initialize with + * GHOSTTY_INIT_SIZED(GhosttyKittyGraphicsPlacementRenderInfo) before calling + * ghostty_kitty_graphics_placement_render_info(). + * + * @ingroup kitty_graphics + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttyKittyGraphicsPlacementRenderInfo). */ + size_t size; + /** Rendered width in pixels. */ + uint32_t pixel_width; + /** Rendered height in pixels. */ + uint32_t pixel_height; + /** Number of grid columns the placement occupies. */ + uint32_t grid_cols; + /** Number of grid rows the placement occupies. */ + uint32_t grid_rows; + /** Viewport-relative column (may be negative for partially visible placements). */ + int32_t viewport_col; + /** Viewport-relative row (may be negative for partially visible placements). */ + int32_t viewport_row; + /** False when the placement is fully off-screen or virtual. */ + bool viewport_visible; + /** Resolved source rectangle x origin in pixels. */ + uint32_t source_x; + /** Resolved source rectangle y origin in pixels. */ + uint32_t source_y; + /** Resolved source rectangle width in pixels. */ + uint32_t source_width; + /** Resolved source rectangle height in pixels. */ + uint32_t source_height; +} GhosttyKittyGraphicsPlacementRenderInfo; + +/** + * Get data from a kitty graphics storage instance. + * + * The output pointer must be of the appropriate type for the requested + * data kind. + * + * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time. + * + * @param graphics The kitty graphics handle + * @param data The type of data to extract + * @param[out] out Pointer to store the extracted data + * @return GHOSTTY_SUCCESS on success + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_get( + GhosttyKittyGraphics graphics, + GhosttyKittyGraphicsData data, + void* out); + +/** + * Look up a Kitty graphics image by its image ID. + * + * Returns NULL if no image with the given ID exists or if Kitty graphics + * are disabled at build time. + * + * @param graphics The kitty graphics handle + * @param image_id The image ID to look up + * @return An opaque image handle, or NULL if not found + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyKittyGraphicsImage ghostty_kitty_graphics_image( + GhosttyKittyGraphics graphics, + uint32_t image_id); + +/** + * Get data from a Kitty graphics image. + * + * The output pointer must be of the appropriate type for the requested + * data kind. + * + * @param image The image handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param data The data kind to query + * @param[out] out Pointer to receive the queried value + * @return GHOSTTY_SUCCESS on success + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get( + GhosttyKittyGraphicsImage image, + GhosttyKittyGraphicsImageData data, + void* out); + +/** + * Get multiple data fields from a Kitty graphics image in a single call. + * + * This is an optimization over calling ghostty_kitty_graphics_image_get() + * repeatedly, particularly useful in environments with high per-call + * overhead such as FFI or Cgo. + * + * Each element in the keys array specifies a data kind, and the + * corresponding element in the values array receives the result. + * The type of each values[i] pointer must match the output type + * documented for keys[i]. + * + * Processing stops at the first error; on success out_written + * is set to count, on error it is set to the index of the + * failing key (i.e. the number of values successfully written). + * + * @param image The image handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param count Number of key/value pairs + * @param keys Array of data kinds to query + * @param values Array of output pointers (types must match each key's + * documented output type) + * @param[out] out_written On return, receives the number of values + * successfully written (may be NULL) + * @return GHOSTTY_SUCCESS if all queries succeed + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get_multi( + GhosttyKittyGraphicsImage image, + size_t count, + const GhosttyKittyGraphicsImageData* keys, + void** values, + size_t* out_written); + +/** + * Create a new placement iterator instance. + * + * All fields except the allocator are left undefined until populated + * via ghostty_kitty_graphics_get() with + * GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR. + * + * @param allocator Pointer to allocator, or NULL to use the default allocator + * @param[out] out_iterator On success, receives the created iterator handle + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation + * failure + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_iterator_new( + const GhosttyAllocator* allocator, + GhosttyKittyGraphicsPlacementIterator* out_iterator); + +/** + * Free a placement iterator. + * + * @param iterator The iterator handle to free (may be NULL) + * + * @ingroup kitty_graphics + */ +GHOSTTY_API void ghostty_kitty_graphics_placement_iterator_free( + GhosttyKittyGraphicsPlacementIterator iterator); + +/** + * Set an option on a placement iterator. + * + * Use GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER with a + * GhosttyKittyPlacementLayer value to filter placements by z-layer. + * The filter is applied during iteration: ghostty_kitty_graphics_placement_next() + * will skip placements that do not match the configured layer. + * + * The default layer is GHOSTTY_KITTY_PLACEMENT_LAYER_ALL (no filtering). + * + * @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param option The option to set + * @param value Pointer to the value (type depends on option; NULL returns + * GHOSTTY_INVALID_VALUE) + * @return GHOSTTY_SUCCESS on success + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_iterator_set( + GhosttyKittyGraphicsPlacementIterator iterator, + GhosttyKittyGraphicsPlacementIteratorOption option, + const void* value); + +/** + * Advance the placement iterator to the next placement. + * + * If a layer filter has been set via + * ghostty_kitty_graphics_placement_iterator_set(), only placements + * matching that layer are returned. + * + * @param iterator The iterator handle (may be NULL) + * @return true if advanced to the next placement, false if at the end + * + * @ingroup kitty_graphics + */ +GHOSTTY_API bool ghostty_kitty_graphics_placement_next( + GhosttyKittyGraphicsPlacementIterator iterator); + +/** + * Get data from the current placement in a placement iterator. + * + * Call ghostty_kitty_graphics_placement_next() at least once before + * calling this function. + * + * @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param data The data kind to query + * @param[out] out Pointer to receive the queried value + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the + * iterator is NULL or not positioned on a placement + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_get( + GhosttyKittyGraphicsPlacementIterator iterator, + GhosttyKittyGraphicsPlacementData data, + void* out); + +/** + * Get multiple data fields from the current placement in a single call. + * + * This is an optimization over calling ghostty_kitty_graphics_placement_get() + * repeatedly, particularly useful in environments with high per-call + * overhead such as FFI or Cgo. + * + * Each element in the keys array specifies a data kind, and the + * corresponding element in the values array receives the result. + * The type of each values[i] pointer must match the output type + * documented for keys[i]. + * + * Processing stops at the first error; on success out_written + * is set to count, on error it is set to the index of the + * failing key (i.e. the number of values successfully written). + * + * @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param count Number of key/value pairs + * @param keys Array of data kinds to query + * @param values Array of output pointers (types must match each key's + * documented output type) + * @param[out] out_written On return, receives the number of values + * successfully written (may be NULL) + * @return GHOSTTY_SUCCESS if all queries succeed + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_get_multi( + GhosttyKittyGraphicsPlacementIterator iterator, + size_t count, + const GhosttyKittyGraphicsPlacementData* keys, + void** values, + size_t* out_written); + +/** + * Compute the grid rectangle occupied by the current placement. + * + * Uses the placement's pin, the image dimensions, and the terminal's + * cell/pixel geometry to calculate the bounding rectangle. Virtual + * placements (unicode placeholders) return GHOSTTY_NO_VALUE. + * + * @param terminal The terminal handle + * @param image The image handle for this placement's image + * @param iterator The placement iterator positioned on a placement + * @param[out] out_selection On success, receives the bounding rectangle + * as a selection with rectangle=true + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle + * is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE for + * virtual placements or when Kitty graphics are disabled + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_rect( + GhosttyKittyGraphicsPlacementIterator iterator, + GhosttyKittyGraphicsImage image, + GhosttyTerminal terminal, + GhosttySelection* out_selection); + +/** + * Compute the rendered pixel size of the current placement. + * + * Takes into account the placement's source rectangle, specified + * columns/rows, and aspect ratio to calculate the final rendered + * pixel dimensions. + * + * @param iterator The placement iterator positioned on a placement + * @param image The image handle for this placement's image + * @param terminal The terminal handle + * @param[out] out_width On success, receives the width in pixels + * @param[out] out_height On success, receives the height in pixels + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle + * is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE when + * Kitty graphics are disabled + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_pixel_size( + GhosttyKittyGraphicsPlacementIterator iterator, + GhosttyKittyGraphicsImage image, + GhosttyTerminal terminal, + uint32_t* out_width, + uint32_t* out_height); + +/** + * Compute the grid cell size of the current placement. + * + * Returns the number of columns and rows that the placement occupies + * in the terminal grid. If the placement specifies explicit columns + * and rows, those are returned directly; otherwise they are calculated + * from the pixel size and cell dimensions. + * + * @param iterator The placement iterator positioned on a placement + * @param image The image handle for this placement's image + * @param terminal The terminal handle + * @param[out] out_cols On success, receives the number of columns + * @param[out] out_rows On success, receives the number of rows + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle + * is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE when + * Kitty graphics are disabled + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_grid_size( + GhosttyKittyGraphicsPlacementIterator iterator, + GhosttyKittyGraphicsImage image, + GhosttyTerminal terminal, + uint32_t* out_cols, + uint32_t* out_rows); + +/** + * Get the viewport-relative grid position of the current placement. + * + * Converts the placement's internal pin to viewport-relative column and + * row coordinates. The returned coordinates represent the top-left + * corner of the placement in the viewport's grid coordinate space. + * + * The row value can be negative when the placement's origin has + * scrolled above the top of the viewport. For example, a 4-row + * image that has scrolled up by 2 rows returns row=-2, meaning + * its top 2 rows are above the visible area but its bottom 2 rows + * are still on screen. Embedders should use these coordinates + * directly when computing the destination rectangle for rendering; + * the embedder is responsible for clipping the portion of the image + * that falls outside the viewport. + * + * Returns GHOSTTY_SUCCESS for any placement that is at least + * partially visible in the viewport. Returns GHOSTTY_NO_VALUE when + * the placement is completely outside the viewport (its bottom edge + * is above the viewport or its top edge is at or below the last + * viewport row), or when the placement is a virtual (unicode + * placeholder) placement. + * + * @param iterator The placement iterator positioned on a placement + * @param image The image handle for this placement's image + * @param terminal The terminal handle + * @param[out] out_col On success, receives the viewport-relative column + * @param[out] out_row On success, receives the viewport-relative row + * (may be negative for partially visible placements) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if fully + * off-screen or virtual, GHOSTTY_INVALID_VALUE if any handle + * is NULL or the iterator is not positioned + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_viewport_pos( + GhosttyKittyGraphicsPlacementIterator iterator, + GhosttyKittyGraphicsImage image, + GhosttyTerminal terminal, + int32_t* out_col, + int32_t* out_row); + +/** + * Get the resolved source rectangle for the current placement. + * + * Applies kitty protocol semantics: a width or height of 0 in the + * placement means "use the full image dimension", and the resulting + * rectangle is clamped to the actual image bounds. The returned + * values are in pixels and are ready to use for texture sampling. + * + * @param iterator The placement iterator positioned on a placement + * @param image The image handle for this placement's image + * @param[out] out_x Source rect x origin in pixels + * @param[out] out_y Source rect y origin in pixels + * @param[out] out_width Source rect width in pixels + * @param[out] out_height Source rect height in pixels + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any + * handle is NULL or the iterator is not positioned + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_source_rect( + GhosttyKittyGraphicsPlacementIterator iterator, + GhosttyKittyGraphicsImage image, + uint32_t* out_x, + uint32_t* out_y, + uint32_t* out_width, + uint32_t* out_height); + +/** + * Get all rendering geometry for a placement in a single call. + * + * Combines pixel size, grid size, viewport position, and source + * rectangle into one struct. Initialize with + * GHOSTTY_INIT_SIZED(GhosttyKittyGraphicsPlacementRenderInfo). + * + * When viewport_visible is false, the placement is fully off-screen + * or is a virtual placement; viewport_col and viewport_row may + * contain meaningless values in that case. + * + * @param iterator The iterator positioned on a placement + * @param image The image handle for this placement's image + * @param terminal The terminal handle + * @param[out] out_info Pointer to receive the rendering geometry + * @return GHOSTTY_SUCCESS on success + * + * @ingroup kitty_graphics + */ +GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_render_info( + GhosttyKittyGraphicsPlacementIterator iterator, + GhosttyKittyGraphicsImage image, + GhosttyTerminal terminal, + GhosttyKittyGraphicsPlacementRenderInfo* out_info); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_KITTY_GRAPHICS_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/modes.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/modes.h new file mode 100644 index 0000000000..8e1fd91179 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/modes.h @@ -0,0 +1,198 @@ +/** + * @file modes.h + * + * Terminal mode utilities - pack and unpack ANSI/DEC mode identifiers. + */ + +#ifndef GHOSTTY_VT_MODES_H +#define GHOSTTY_VT_MODES_H + +/** @defgroup modes Mode Utilities + * + * Utilities for working with terminal modes. A mode is a compact + * 16-bit representation of a terminal mode identifier that encodes both + * the numeric mode value (up to 15 bits) and whether the mode is an ANSI + * mode or a DEC private mode (?-prefixed). + * + * The packed layout (least-significant bit first) is: + * - Bits 0–14: mode value (u15) + * - Bit 15: ANSI flag (0 = DEC private mode, 1 = ANSI mode) + * + * ## Example + * + * @snippet c-vt-modes/src/main.c modes-pack-unpack + * + * ## DECRPM Report Encoding + * + * Use ghostty_mode_report_encode() to encode a DECRPM response into a + * caller-provided buffer: + * + * @snippet c-vt-modes/src/main.c modes-decrpm + * + * @{ + */ + +#include +#include +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** @name ANSI Modes + * Modes for standard ANSI modes. + * @{ + */ +#define GHOSTTY_MODE_KAM (ghostty_mode_new(2, true)) /**< Keyboard action (disable keyboard) */ +#define GHOSTTY_MODE_INSERT (ghostty_mode_new(4, true)) /**< Insert mode */ +#define GHOSTTY_MODE_SRM (ghostty_mode_new(12, true)) /**< Send/receive mode */ +#define GHOSTTY_MODE_LINEFEED (ghostty_mode_new(20, true)) /**< Linefeed/new line mode */ +/** @} */ + +/** @name DEC Private Modes + * Modes for DEC private modes (?-prefixed). + * @{ + */ +#define GHOSTTY_MODE_DECCKM (ghostty_mode_new(1, false)) /**< Cursor keys */ +#define GHOSTTY_MODE_132_COLUMN (ghostty_mode_new(3, false)) /**< 132/80 column mode */ +#define GHOSTTY_MODE_SLOW_SCROLL (ghostty_mode_new(4, false)) /**< Slow scroll */ +#define GHOSTTY_MODE_REVERSE_COLORS (ghostty_mode_new(5, false)) /**< Reverse video */ +#define GHOSTTY_MODE_ORIGIN (ghostty_mode_new(6, false)) /**< Origin mode */ +#define GHOSTTY_MODE_WRAPAROUND (ghostty_mode_new(7, false)) /**< Auto-wrap mode */ +#define GHOSTTY_MODE_AUTOREPEAT (ghostty_mode_new(8, false)) /**< Auto-repeat keys */ +#define GHOSTTY_MODE_X10_MOUSE (ghostty_mode_new(9, false)) /**< X10 mouse reporting */ +#define GHOSTTY_MODE_CURSOR_BLINKING (ghostty_mode_new(12, false)) /**< Cursor blink */ +#define GHOSTTY_MODE_CURSOR_VISIBLE (ghostty_mode_new(25, false)) /**< Cursor visible (DECTCEM) */ +#define GHOSTTY_MODE_ENABLE_MODE_3 (ghostty_mode_new(40, false)) /**< Allow 132 column mode */ +#define GHOSTTY_MODE_REVERSE_WRAP (ghostty_mode_new(45, false)) /**< Reverse wrap */ +#define GHOSTTY_MODE_ALT_SCREEN_LEGACY (ghostty_mode_new(47, false)) /**< Alternate screen (legacy) */ +#define GHOSTTY_MODE_KEYPAD_KEYS (ghostty_mode_new(66, false)) /**< Application keypad */ +#define GHOSTTY_MODE_BACKARROW_KEY_MODE (ghostty_mode_new(67, false)) /**< Backarrow key mode (DECBKM) */ +#define GHOSTTY_MODE_LEFT_RIGHT_MARGIN (ghostty_mode_new(69, false)) /**< Left/right margin mode */ +#define GHOSTTY_MODE_NORMAL_MOUSE (ghostty_mode_new(1000, false)) /**< Normal mouse tracking */ +#define GHOSTTY_MODE_BUTTON_MOUSE (ghostty_mode_new(1002, false)) /**< Button-event mouse tracking */ +#define GHOSTTY_MODE_ANY_MOUSE (ghostty_mode_new(1003, false)) /**< Any-event mouse tracking */ +#define GHOSTTY_MODE_FOCUS_EVENT (ghostty_mode_new(1004, false)) /**< Focus in/out events */ +#define GHOSTTY_MODE_UTF8_MOUSE (ghostty_mode_new(1005, false)) /**< UTF-8 mouse format */ +#define GHOSTTY_MODE_SGR_MOUSE (ghostty_mode_new(1006, false)) /**< SGR mouse format */ +#define GHOSTTY_MODE_ALT_SCROLL (ghostty_mode_new(1007, false)) /**< Alternate scroll mode */ +#define GHOSTTY_MODE_URXVT_MOUSE (ghostty_mode_new(1015, false)) /**< URxvt mouse format */ +#define GHOSTTY_MODE_SGR_PIXELS_MOUSE (ghostty_mode_new(1016, false)) /**< SGR-Pixels mouse format */ +#define GHOSTTY_MODE_NUMLOCK_KEYPAD (ghostty_mode_new(1035, false)) /**< Ignore keypad with NumLock */ +#define GHOSTTY_MODE_ALT_ESC_PREFIX (ghostty_mode_new(1036, false)) /**< Alt key sends ESC prefix */ +#define GHOSTTY_MODE_ALT_SENDS_ESC (ghostty_mode_new(1039, false)) /**< Alt sends escape */ +#define GHOSTTY_MODE_REVERSE_WRAP_EXT (ghostty_mode_new(1045, false)) /**< Extended reverse wrap */ +#define GHOSTTY_MODE_ALT_SCREEN (ghostty_mode_new(1047, false)) /**< Alternate screen */ +#define GHOSTTY_MODE_SAVE_CURSOR (ghostty_mode_new(1048, false)) /**< Save cursor (DECSC) */ +#define GHOSTTY_MODE_ALT_SCREEN_SAVE (ghostty_mode_new(1049, false)) /**< Alt screen + save cursor + clear */ +#define GHOSTTY_MODE_BRACKETED_PASTE (ghostty_mode_new(2004, false)) /**< Bracketed paste mode */ +#define GHOSTTY_MODE_SYNC_OUTPUT (ghostty_mode_new(2026, false)) /**< Synchronized output */ +#define GHOSTTY_MODE_GRAPHEME_CLUSTER (ghostty_mode_new(2027, false)) /**< Grapheme cluster mode */ +#define GHOSTTY_MODE_COLOR_SCHEME_REPORT (ghostty_mode_new(2031, false)) /**< Report color scheme */ +#define GHOSTTY_MODE_IN_BAND_RESIZE (ghostty_mode_new(2048, false)) /**< In-band size reports */ +/** @} */ + +/** + * A packed 16-bit terminal mode. + * + * Encodes a mode value (bits 0–14) and an ANSI flag (bit 15) into a + * single 16-bit integer. Use the inline helper functions to construct + * and inspect modes rather than manipulating bits directly. + */ +typedef uint16_t GhosttyMode; + +/** + * Create a mode from a mode value and ANSI flag. + * + * @param value The numeric mode value (0–32767) + * @param ansi true for an ANSI mode, false for a DEC private mode + * @return The packed mode + * + * @ingroup modes + */ +static inline GhosttyMode ghostty_mode_new(uint16_t value, bool ansi) { + return (GhosttyMode)((value & 0x7FFF) | ((uint16_t)ansi << 15)); +} + +/** + * Extract the numeric mode value from a mode. + * + * @param mode The mode + * @return The mode value (0–32767) + * + * @ingroup modes + */ +static inline uint16_t ghostty_mode_value(GhosttyMode mode) { + return mode & 0x7FFF; +} + +/** + * Check whether a mode represents an ANSI mode. + * + * @param mode The mode + * @return true if this is an ANSI mode, false if it is a DEC private mode + * + * @ingroup modes + */ +static inline bool ghostty_mode_ansi(GhosttyMode mode) { + return (mode >> 15) != 0; +} + +/** + * DECRPM report state values. + * + * These correspond to the Ps2 parameter in a DECRPM response + * sequence (CSI ? Ps1 ; Ps2 $ y). + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Mode is not recognized */ + GHOSTTY_MODE_REPORT_NOT_RECOGNIZED = 0, + /** Mode is set (enabled) */ + GHOSTTY_MODE_REPORT_SET = 1, + /** Mode is reset (disabled) */ + GHOSTTY_MODE_REPORT_RESET = 2, + /** Mode is permanently set */ + GHOSTTY_MODE_REPORT_PERMANENTLY_SET = 3, + /** Mode is permanently reset */ + GHOSTTY_MODE_REPORT_PERMANENTLY_RESET = 4, + GHOSTTY_MODE_REPORT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyModeReportState; + +/** + * Encode a DECRPM (DEC Private Mode Report) response sequence. + * + * Writes a mode report escape sequence into the provided buffer. + * The generated sequence has the form: + * - DEC private mode: CSI ? Ps1 ; Ps2 $ y + * - ANSI mode: CSI Ps1 ; Ps2 $ y + * + * If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE + * and writes the required buffer size to @p out_written. The caller can + * then retry with a sufficiently sized buffer. + * + * @param mode The mode identifying the mode to report on + * @param state The report state for this mode + * @param buf Output buffer to write the encoded sequence into (may be NULL) + * @param buf_len Size of the output buffer in bytes + * @param[out] out_written On success, the number of bytes written. On + * GHOSTTY_OUT_OF_SPACE, the required buffer size. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer + * is too small + */ +GHOSTTY_API GhosttyResult ghostty_mode_report_encode( + GhosttyMode mode, + GhosttyModeReportState state, + char* buf, + size_t buf_len, + size_t* out_written); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_MODES_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse.h new file mode 100644 index 0000000000..4ba5f52e38 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse.h @@ -0,0 +1,70 @@ +/** + * @file mouse.h + * + * Mouse encoding module - encode mouse events into terminal escape sequences. + */ + +#ifndef GHOSTTY_VT_MOUSE_H +#define GHOSTTY_VT_MOUSE_H + +/** @defgroup mouse Mouse Encoding + * + * Utilities for encoding mouse events into terminal escape sequences, + * supporting X10, UTF-8, SGR, URxvt, and SGR-Pixels mouse protocols. + * + * ## Basic Usage + * + * 1. Create an encoder instance with ghostty_mouse_encoder_new(). + * 2. Configure encoder options with ghostty_mouse_encoder_setopt() or + * ghostty_mouse_encoder_setopt_from_terminal(). + * 3. For each mouse event: + * - Create a mouse event with ghostty_mouse_event_new(). + * - Set event properties (action, button, modifiers, position). + * - Encode with ghostty_mouse_encoder_encode(). + * - Free the event with ghostty_mouse_event_free() or reuse it. + * 4. Free the encoder with ghostty_mouse_encoder_free() when done. + * + * For a complete working example, see example/c-vt-encode-mouse in the + * repository. + * + * ## Example + * + * @snippet c-vt-encode-mouse/src/main.c mouse-encode + * + * ## Example: Encoding with Terminal State + * + * When you have a GhosttyTerminal, you can sync its tracking mode and + * output format into the encoder automatically: + * + * @code{.c} + * // Create a terminal and feed it some VT data that enables mouse tracking + * GhosttyTerminal terminal; + * ghostty_terminal_new(NULL, &terminal, + * (GhosttyTerminalOptions){.cols = 80, .rows = 24, .max_scrollback = 0}); + * + * // Application might write data that enables mouse reporting, etc. + * ghostty_terminal_vt_write(terminal, vt_data, vt_len); + * + * // Create an encoder and sync its options from the terminal + * GhosttyMouseEncoder encoder; + * ghostty_mouse_encoder_new(NULL, &encoder); + * ghostty_mouse_encoder_setopt_from_terminal(encoder, terminal); + * + * // Encode a mouse event using the terminal-derived options + * char buf[128]; + * size_t written = 0; + * ghostty_mouse_encoder_encode(encoder, event, buf, sizeof(buf), &written); + * + * ghostty_mouse_encoder_free(encoder); + * ghostty_terminal_free(terminal); + * @endcode + * + * @{ + */ + +#include +#include + +/** @} */ + +#endif /* GHOSTTY_VT_MOUSE_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse/encoder.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse/encoder.h new file mode 100644 index 0000000000..d84d863c8d --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse/encoder.h @@ -0,0 +1,214 @@ +/** + * @file encoder.h + * + * Mouse event encoding to terminal escape sequences. + */ + +#ifndef GHOSTTY_VT_MOUSE_ENCODER_H +#define GHOSTTY_VT_MOUSE_ENCODER_H + +#include +#include +#include +#include +#include +#include +#include + +/** + * Opaque handle to a mouse encoder instance. + * + * This handle represents a mouse encoder that converts normalized + * mouse events into terminal escape sequences. + * + * @ingroup mouse + */ +typedef struct GhosttyMouseEncoderImpl *GhosttyMouseEncoder; + +/** + * Mouse tracking mode. + * + * @ingroup mouse + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Mouse reporting disabled. */ + GHOSTTY_MOUSE_TRACKING_NONE = 0, + + /** X10 mouse mode. */ + GHOSTTY_MOUSE_TRACKING_X10 = 1, + + /** Normal mouse mode (button press/release only). */ + GHOSTTY_MOUSE_TRACKING_NORMAL = 2, + + /** Button-event tracking mode. */ + GHOSTTY_MOUSE_TRACKING_BUTTON = 3, + + /** Any-event tracking mode. */ + GHOSTTY_MOUSE_TRACKING_ANY = 4, + GHOSTTY_MOUSE_TRACKING_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyMouseTrackingMode; + +/** + * Mouse output format. + * + * @ingroup mouse + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_MOUSE_FORMAT_X10 = 0, + GHOSTTY_MOUSE_FORMAT_UTF8 = 1, + GHOSTTY_MOUSE_FORMAT_SGR = 2, + GHOSTTY_MOUSE_FORMAT_URXVT = 3, + GHOSTTY_MOUSE_FORMAT_SGR_PIXELS = 4, + GHOSTTY_MOUSE_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyMouseFormat; + +/** + * Mouse encoder size and geometry context. + * + * This describes the rendered terminal geometry used to convert + * surface-space positions into encoded coordinates. + * + * @ingroup mouse + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttyMouseEncoderSize). */ + size_t size; + + /** Full screen width in pixels. */ + uint32_t screen_width; + + /** Full screen height in pixels. */ + uint32_t screen_height; + + /** Cell width in pixels. Must be non-zero. */ + uint32_t cell_width; + + /** Cell height in pixels. Must be non-zero. */ + uint32_t cell_height; + + /** Top padding in pixels. */ + uint32_t padding_top; + + /** Bottom padding in pixels. */ + uint32_t padding_bottom; + + /** Right padding in pixels. */ + uint32_t padding_right; + + /** Left padding in pixels. */ + uint32_t padding_left; +} GhosttyMouseEncoderSize; + +/** + * Mouse encoder option identifiers. + * + * These values are used with ghostty_mouse_encoder_setopt() to configure + * the behavior of the mouse encoder. + * + * @ingroup mouse + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Mouse tracking mode (value: GhosttyMouseTrackingMode). */ + GHOSTTY_MOUSE_ENCODER_OPT_EVENT = 0, + + /** Mouse output format (value: GhosttyMouseFormat). */ + GHOSTTY_MOUSE_ENCODER_OPT_FORMAT = 1, + + /** Renderer size context (value: GhosttyMouseEncoderSize). */ + GHOSTTY_MOUSE_ENCODER_OPT_SIZE = 2, + + /** Whether any mouse button is currently pressed (value: bool). */ + GHOSTTY_MOUSE_ENCODER_OPT_ANY_BUTTON_PRESSED = 3, + + /** Whether to enable motion deduplication by last cell (value: bool). */ + GHOSTTY_MOUSE_ENCODER_OPT_TRACK_LAST_CELL = 4, + GHOSTTY_MOUSE_ENCODER_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyMouseEncoderOption; + +/** + * Create a new mouse encoder instance. + * + * @param allocator Pointer to allocator, or NULL to use the default allocator + * @param encoder Pointer to store the created encoder handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup mouse + */ +GHOSTTY_API GhosttyResult ghostty_mouse_encoder_new(const GhosttyAllocator *allocator, + GhosttyMouseEncoder *encoder); + +/** + * Free a mouse encoder instance. + * + * @param encoder The encoder handle to free (may be NULL) + * + * @ingroup mouse + */ +GHOSTTY_API void ghostty_mouse_encoder_free(GhosttyMouseEncoder encoder); + +/** + * Set an option on the mouse encoder. + * + * A null pointer value does nothing. It does not reset to defaults. + * + * @param encoder The encoder handle, must not be NULL + * @param option The option to set + * @param value Pointer to option value (type depends on option) + * + * @ingroup mouse + */ +GHOSTTY_API void ghostty_mouse_encoder_setopt(GhosttyMouseEncoder encoder, + GhosttyMouseEncoderOption option, + const void *value); + +/** + * Set encoder options from a terminal's current state. + * + * This sets tracking mode and output format from terminal state. + * It does not modify size or any-button state. + * + * @param encoder The encoder handle, must not be NULL + * @param terminal The terminal handle, must not be NULL + * + * @ingroup mouse + */ +GHOSTTY_API void ghostty_mouse_encoder_setopt_from_terminal(GhosttyMouseEncoder encoder, + GhosttyTerminal terminal); + +/** + * Reset internal encoder state. + * + * This clears motion deduplication state (last tracked cell). + * + * @param encoder The encoder handle (may be NULL) + * + * @ingroup mouse + */ +GHOSTTY_API void ghostty_mouse_encoder_reset(GhosttyMouseEncoder encoder); + +/** + * Encode a mouse event into a terminal escape sequence. + * + * Not all mouse events produce output. In such cases this returns + * GHOSTTY_SUCCESS with out_len set to 0. + * + * If the output buffer is too small, this returns GHOSTTY_OUT_OF_SPACE + * and out_len contains the required size. + * + * @param encoder The encoder handle, must not be NULL + * @param event The mouse event to encode, must not be NULL + * @param out_buf Buffer to write encoded bytes to, or NULL to query required size + * @param out_buf_size Size of out_buf in bytes + * @param out_len Pointer to store bytes written (or required bytes on failure) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if buffer is too small, + * or another error code + * + * @ingroup mouse + */ +GHOSTTY_API GhosttyResult ghostty_mouse_encoder_encode(GhosttyMouseEncoder encoder, + GhosttyMouseEvent event, + char *out_buf, + size_t out_buf_size, + size_t *out_len); + +#endif /* GHOSTTY_VT_MOUSE_ENCODER_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse/event.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse/event.h new file mode 100644 index 0000000000..a24b0c079b --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/mouse/event.h @@ -0,0 +1,195 @@ +/** + * @file event.h + * + * Mouse event representation and manipulation. + */ + +#ifndef GHOSTTY_VT_MOUSE_EVENT_H +#define GHOSTTY_VT_MOUSE_EVENT_H + +#include +#include +#include +#include + +/** + * Opaque handle to a mouse event. + * + * This handle represents a normalized mouse input event containing + * action, button, modifiers, and surface-space position. + * + * @ingroup mouse + */ +typedef struct GhosttyMouseEventImpl *GhosttyMouseEvent; + +/** + * Mouse event action type. + * + * @ingroup mouse + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Mouse button was pressed. */ + GHOSTTY_MOUSE_ACTION_PRESS = 0, + + /** Mouse button was released. */ + GHOSTTY_MOUSE_ACTION_RELEASE = 1, + + /** Mouse moved. */ + GHOSTTY_MOUSE_ACTION_MOTION = 2, + GHOSTTY_MOUSE_ACTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyMouseAction; + +/** + * Mouse button identity. + * + * @ingroup mouse + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_MOUSE_BUTTON_UNKNOWN = 0, + GHOSTTY_MOUSE_BUTTON_LEFT = 1, + GHOSTTY_MOUSE_BUTTON_RIGHT = 2, + GHOSTTY_MOUSE_BUTTON_MIDDLE = 3, + GHOSTTY_MOUSE_BUTTON_FOUR = 4, + GHOSTTY_MOUSE_BUTTON_FIVE = 5, + GHOSTTY_MOUSE_BUTTON_SIX = 6, + GHOSTTY_MOUSE_BUTTON_SEVEN = 7, + GHOSTTY_MOUSE_BUTTON_EIGHT = 8, + GHOSTTY_MOUSE_BUTTON_NINE = 9, + GHOSTTY_MOUSE_BUTTON_TEN = 10, + GHOSTTY_MOUSE_BUTTON_ELEVEN = 11, + GHOSTTY_MOUSE_BUTTON_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyMouseButton; + +/** + * Mouse position in surface-space pixels. + * + * @ingroup mouse + */ +typedef struct { + float x; + float y; +} GhosttyMousePosition; + +/** + * Create a new mouse event instance. + * + * @param allocator Pointer to allocator, or NULL to use the default allocator + * @param event Pointer to store the created event handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup mouse + */ +GHOSTTY_API GhosttyResult ghostty_mouse_event_new(const GhosttyAllocator *allocator, + GhosttyMouseEvent *event); + +/** + * Free a mouse event instance. + * + * @param event The mouse event handle to free (may be NULL) + * + * @ingroup mouse + */ +GHOSTTY_API void ghostty_mouse_event_free(GhosttyMouseEvent event); + +/** + * Set the event action. + * + * @param event The event handle, must not be NULL + * @param action The action to set + * + * @ingroup mouse + */ +GHOSTTY_API void ghostty_mouse_event_set_action(GhosttyMouseEvent event, + GhosttyMouseAction action); + +/** + * Get the event action. + * + * @param event The event handle, must not be NULL + * @return The event action + * + * @ingroup mouse + */ +GHOSTTY_API GhosttyMouseAction ghostty_mouse_event_get_action(GhosttyMouseEvent event); + +/** + * Set the event button. + * + * This sets a concrete button identity for the event. + * To represent "no button" (for motion events), use + * ghostty_mouse_event_clear_button(). + * + * @param event The event handle, must not be NULL + * @param button The button to set + * + * @ingroup mouse + */ +GHOSTTY_API void ghostty_mouse_event_set_button(GhosttyMouseEvent event, + GhosttyMouseButton button); + +/** + * Clear the event button. + * + * This sets the event button to "none". + * + * @param event The event handle, must not be NULL + * + * @ingroup mouse + */ +GHOSTTY_API void ghostty_mouse_event_clear_button(GhosttyMouseEvent event); + +/** + * Get the event button. + * + * @param event The event handle, must not be NULL + * @param out_button Output pointer for the button value (may be NULL) + * @return true if a button is set, false if no button is set + * + * @ingroup mouse + */ +GHOSTTY_API bool ghostty_mouse_event_get_button(GhosttyMouseEvent event, + GhosttyMouseButton *out_button); + +/** + * Set keyboard modifiers held during the event. + * + * @param event The event handle, must not be NULL + * @param mods Modifier bitmask + * + * @ingroup mouse + */ +GHOSTTY_API void ghostty_mouse_event_set_mods(GhosttyMouseEvent event, + GhosttyMods mods); + +/** + * Get keyboard modifiers held during the event. + * + * @param event The event handle, must not be NULL + * @return Modifier bitmask + * + * @ingroup mouse + */ +GHOSTTY_API GhosttyMods ghostty_mouse_event_get_mods(GhosttyMouseEvent event); + +/** + * Set the event position in surface-space pixels. + * + * @param event The event handle, must not be NULL + * @param position The position to set + * + * @ingroup mouse + */ +GHOSTTY_API void ghostty_mouse_event_set_position(GhosttyMouseEvent event, + GhosttyMousePosition position); + +/** + * Get the event position in surface-space pixels. + * + * @param event The event handle, must not be NULL + * @return The current event position + * + * @ingroup mouse + */ +GHOSTTY_API GhosttyMousePosition ghostty_mouse_event_get_position(GhosttyMouseEvent event); + +#endif /* GHOSTTY_VT_MOUSE_EVENT_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/osc.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/osc.h new file mode 100644 index 0000000000..9409ebc738 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/osc.h @@ -0,0 +1,215 @@ +/** + * @file osc.h + * + * OSC (Operating System Command) sequence parser and command handling. + */ + +#ifndef GHOSTTY_VT_OSC_H +#define GHOSTTY_VT_OSC_H + +#include +#include +#include +#include +#include + +/** @defgroup osc OSC Parser + * + * OSC (Operating System Command) sequence parser and command handling. + * + * The parser operates in a streaming fashion, processing input byte-by-byte + * to handle OSC sequences that may arrive in fragments across multiple reads. + * This interface makes it easy to integrate into most environments and avoids + * over-allocating buffers. + * + * ## Basic Usage + * + * 1. Create a parser instance with ghostty_osc_new() + * 2. Feed bytes to the parser using ghostty_osc_next() + * 3. Finalize parsing with ghostty_osc_end() to get the command + * 4. Query command type and extract data using ghostty_osc_command_type() + * and ghostty_osc_command_data() + * 5. Free the parser with ghostty_osc_free() when done + * + * @{ + */ + +/** + * OSC command types. + * + * @ingroup osc + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_OSC_COMMAND_INVALID = 0, + GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_TITLE = 1, + GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_ICON = 2, + GHOSTTY_OSC_COMMAND_SEMANTIC_PROMPT = 3, + GHOSTTY_OSC_COMMAND_CLIPBOARD_CONTENTS = 4, + GHOSTTY_OSC_COMMAND_REPORT_PWD = 5, + GHOSTTY_OSC_COMMAND_MOUSE_SHAPE = 6, + GHOSTTY_OSC_COMMAND_COLOR_OPERATION = 7, + GHOSTTY_OSC_COMMAND_KITTY_COLOR_PROTOCOL = 8, + GHOSTTY_OSC_COMMAND_SHOW_DESKTOP_NOTIFICATION = 9, + GHOSTTY_OSC_COMMAND_HYPERLINK_START = 10, + GHOSTTY_OSC_COMMAND_HYPERLINK_END = 11, + GHOSTTY_OSC_COMMAND_CONEMU_SLEEP = 12, + GHOSTTY_OSC_COMMAND_CONEMU_SHOW_MESSAGE_BOX = 13, + GHOSTTY_OSC_COMMAND_CONEMU_CHANGE_TAB_TITLE = 14, + GHOSTTY_OSC_COMMAND_CONEMU_PROGRESS_REPORT = 15, + GHOSTTY_OSC_COMMAND_CONEMU_WAIT_INPUT = 16, + GHOSTTY_OSC_COMMAND_CONEMU_GUIMACRO = 17, + GHOSTTY_OSC_COMMAND_CONEMU_RUN_PROCESS = 18, + GHOSTTY_OSC_COMMAND_CONEMU_OUTPUT_ENVIRONMENT_VARIABLE = 19, + GHOSTTY_OSC_COMMAND_CONEMU_XTERM_EMULATION = 20, + GHOSTTY_OSC_COMMAND_CONEMU_COMMENT = 21, + GHOSTTY_OSC_COMMAND_KITTY_TEXT_SIZING = 22, + GHOSTTY_OSC_COMMAND_TYPE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyOscCommandType; + +/** + * OSC command data types. + * + * These values specify what type of data to extract from an OSC command + * using `ghostty_osc_command_data`. + * + * @ingroup osc + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Invalid data type. Never results in any data extraction. */ + GHOSTTY_OSC_DATA_INVALID = 0, + + /** + * Window title string data. + * + * Valid for: GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_TITLE + * + * Output type: const char ** (pointer to null-terminated string) + * + * Lifetime: Valid until the next call to any ghostty_osc_* function with + * the same parser instance. Memory is owned by the parser. + */ + GHOSTTY_OSC_DATA_CHANGE_WINDOW_TITLE_STR = 1, + GHOSTTY_OSC_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyOscCommandData; + +/** + * Create a new OSC parser instance. + * + * Creates a new OSC (Operating System Command) parser using the provided + * allocator. The parser must be freed using ghostty_vt_osc_free() when + * no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator + * @param parser Pointer to store the created parser handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup osc + */ +GHOSTTY_API GhosttyResult ghostty_osc_new(const GhosttyAllocator *allocator, GhosttyOscParser *parser); + +/** + * Free an OSC parser instance. + * + * Releases all resources associated with the OSC parser. After this call, + * the parser handle becomes invalid and must not be used. + * + * @param parser The parser handle to free (may be NULL) + * + * @ingroup osc + */ +GHOSTTY_API void ghostty_osc_free(GhosttyOscParser parser); + +/** + * Reset an OSC parser instance to its initial state. + * + * Resets the parser state, clearing any partially parsed OSC sequences + * and returning the parser to its initial state. This is useful for + * reusing a parser instance or recovering from parse errors. + * + * @param parser The parser handle to reset, must not be null. + * + * @ingroup osc + */ +GHOSTTY_API void ghostty_osc_reset(GhosttyOscParser parser); + +/** + * Parse the next byte in an OSC sequence. + * + * Processes a single byte as part of an OSC sequence. The parser maintains + * internal state to track the progress through the sequence. Call this + * function for each byte in the sequence data. + * + * When finished pumping the parser with bytes, call ghostty_osc_end + * to get the final result. + * + * @param parser The parser handle, must not be null. + * @param byte The next byte to parse + * + * @ingroup osc + */ +GHOSTTY_API void ghostty_osc_next(GhosttyOscParser parser, uint8_t byte); + +/** + * Finalize OSC parsing and retrieve the parsed command. + * + * Call this function after feeding all bytes of an OSC sequence to the parser + * using ghostty_osc_next() with the exception of the terminating character + * (ESC or ST). This function finalizes the parsing process and returns the + * parsed OSC command. + * + * The return value is never NULL. Invalid commands will return a command + * with type GHOSTTY_OSC_COMMAND_INVALID. + * + * The terminator parameter specifies the byte that terminated the OSC sequence + * (typically 0x07 for BEL or 0x5C for ST after ESC). This information is + * preserved in the parsed command so that responses can use the same terminator + * format for better compatibility with the calling program. For commands that + * do not require a response, this parameter is ignored and the resulting + * command will not retain the terminator information. + * + * The returned command handle is valid until the next call to any + * `ghostty_osc_*` function with the same parser instance with the exception + * of command introspection functions such as `ghostty_osc_command_type`. + * + * @param parser The parser handle, must not be null. + * @param terminator The terminating byte of the OSC sequence (0x07 for BEL, 0x5C for ST) + * @return Handle to the parsed OSC command + * + * @ingroup osc + */ +GHOSTTY_API GhosttyOscCommand ghostty_osc_end(GhosttyOscParser parser, uint8_t terminator); + +/** + * Get the type of an OSC command. + * + * Returns the type identifier for the given OSC command. This can be used + * to determine what kind of command was parsed and what data might be + * available from it. + * + * @param command The OSC command handle to query (may be NULL) + * @return The command type, or GHOSTTY_OSC_COMMAND_INVALID if command is NULL + * + * @ingroup osc + */ +GHOSTTY_API GhosttyOscCommandType ghostty_osc_command_type(GhosttyOscCommand command); + +/** + * Extract data from an OSC command. + * + * Extracts typed data from the given OSC command based on the specified + * data type. The output pointer must be of the appropriate type for the + * requested data kind. Valid command types, output types, and memory + * safety information are documented in the `GhosttyOscCommandData` enum. + * + * @param command The OSC command handle to query (may be NULL) + * @param data The type of data to extract + * @param out Pointer to store the extracted data (type depends on data parameter) + * @return true if data extraction was successful, false otherwise + * + * @ingroup osc + */ +GHOSTTY_API bool ghostty_osc_command_data(GhosttyOscCommand command, GhosttyOscCommandData data, void *out); + +/** @} */ + +#endif /* GHOSTTY_VT_OSC_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/paste.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/paste.h new file mode 100644 index 0000000000..b3df5be4e0 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/paste.h @@ -0,0 +1,101 @@ +/** + * @file paste.h + * + * Paste utilities - validate and encode paste data for terminal input. + */ + +#ifndef GHOSTTY_VT_PASTE_H +#define GHOSTTY_VT_PASTE_H + +/** @defgroup paste Paste Utilities + * + * Utilities for validating and encoding paste data for terminal input. + * + * ## Basic Usage + * + * Use ghostty_paste_is_safe() to check if paste data contains potentially + * dangerous sequences before sending it to the terminal. + * + * Use ghostty_paste_encode() to encode paste data for writing to the pty, + * including bracketed paste wrapping and unsafe byte stripping. + * + * ## Examples + * + * ### Safety Check + * + * @snippet c-vt-paste/src/main.c paste-safety + * + * ### Encoding + * + * @snippet c-vt-paste/src/main.c paste-encode + * + * @{ + */ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Check if paste data is safe to paste into the terminal. + * + * Data is considered unsafe if it contains: + * - Newlines (`\n`) which can inject commands + * - The bracketed paste end sequence (`\x1b[201~`) which can be used + * to exit bracketed paste mode and inject commands + * + * This check is conservative and considers data unsafe regardless of + * current terminal state. + * + * @param data The paste data to check (must not be NULL) + * @param len The length of the data in bytes + * @return true if the data is safe to paste, false otherwise + */ +GHOSTTY_API bool ghostty_paste_is_safe(const char* data, size_t len); + +/** + * Encode paste data for writing to the terminal pty. + * + * This function prepares paste data for terminal input by: + * - Stripping unsafe control bytes (NUL, ESC, DEL, etc.) by replacing + * them with spaces + * - Wrapping the data in bracketed paste sequences if @p bracketed is true + * - Replacing newlines with carriage returns if @p bracketed is false + * + * The input @p data buffer is modified in place during encoding. The + * encoded result (potentially with bracketed paste prefix/suffix) is + * written to the output buffer. + * + * If the output buffer is too small, the function returns + * GHOSTTY_OUT_OF_SPACE and sets the required size in @p out_written. + * The caller can then retry with a sufficiently sized buffer. + * + * @param data The paste data to encode (modified in place, may be NULL) + * @param data_len The length of the input data in bytes + * @param bracketed Whether bracketed paste mode is active + * @param buf Output buffer to write the encoded result into (may be NULL) + * @param buf_len Size of the output buffer in bytes + * @param[out] out_written On success, the number of bytes written. On + * GHOSTTY_OUT_OF_SPACE, the required buffer size. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer + * is too small + */ +GHOSTTY_API GhosttyResult ghostty_paste_encode( + char* data, + size_t data_len, + bool bracketed, + char* buf, + size_t buf_len, + size_t* out_written); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_PASTE_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/point.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/point.h new file mode 100644 index 0000000000..8b717f4940 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/point.h @@ -0,0 +1,89 @@ +/** + * @file point.h + * + * Terminal point types for referencing locations in the terminal grid. + */ + +#ifndef GHOSTTY_VT_POINT_H +#define GHOSTTY_VT_POINT_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup point Point + * + * Types for referencing x/y positions in the terminal grid under + * different coordinate systems (active area, viewport, full screen, + * scrollback history). + * + * @{ + */ + +/** + * A coordinate in the terminal grid. + * + * @ingroup point + */ +typedef struct { + /** Column (0-indexed). */ + uint16_t x; + + /** Row (0-indexed). May exceed page size for screen/history tags. */ + uint32_t y; +} GhosttyPointCoordinate; + +/** + * Point reference tag. + * + * Determines which coordinate system a point uses. + * + * @ingroup point + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Active area where the cursor can move. */ + GHOSTTY_POINT_TAG_ACTIVE = 0, + + /** Visible viewport (changes when scrolled). */ + GHOSTTY_POINT_TAG_VIEWPORT = 1, + + /** Full screen including scrollback. */ + GHOSTTY_POINT_TAG_SCREEN = 2, + + /** Scrollback history only (before active area). */ + GHOSTTY_POINT_TAG_HISTORY = 3, + GHOSTTY_POINT_TAG_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, + } GhosttyPointTag; + +/** + * Point value union. + * + * @ingroup point + */ +typedef union { + /** Coordinate (used for all tag variants). */ + GhosttyPointCoordinate coordinate; + + /** Padding for ABI compatibility. Do not use. */ + uint64_t _padding[2]; +} GhosttyPointValue; + +/** + * Tagged union for a point in the terminal grid. + * + * @ingroup point + */ +typedef struct { + GhosttyPointTag tag; + GhosttyPointValue value; +} GhosttyPoint; + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_POINT_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/render.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/render.h new file mode 100644 index 0000000000..c5b1d0d4fc --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/render.h @@ -0,0 +1,729 @@ +/** + * @file render.h + * + * Render state for creating high performance renderers. + */ + +#ifndef GHOSTTY_VT_RENDER_H +#define GHOSTTY_VT_RENDER_H + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup render Render State + * + * Represents the state required to render a visible screen (a viewport) + * of a terminal instance. This is stateful and optimized for repeated + * updates from a single terminal instance and only updating dirty regions + * of the screen. + * + * The key design principle of this API is that it only needs read/write + * access to the terminal instance during the update call. This allows + * the render state to minimally impact terminal IO performance and also + * allows the renderer to be safely multi-threaded (as long as a lock is + * held during the update call to ensure exclusive access to the terminal + * instance). + * + * The basic usage of this API is: + * + * 1. Create an empty render state + * 2. Update it from a terminal instance whenever you need. + * 3. Read from the render state to get the data needed to draw your frame. + * + * ## Dirty Tracking + * + * Dirty tracking is a key feature of the render state that allows renderers + * to efficiently determine what parts of the screen have changed and only + * redraw changed regions. + * + * The render state API keeps track of dirty state at two independent layers: + * a global dirty state that indicates whether the entire frame is clean, + * partially dirty, or fully dirty, and a per-row dirty state that allows + * tracking which rows in a partially dirty frame have changed. + * + * The user of the render state API is expected to unset both of these. + * The `update` call does not unset dirty state, it only updates it. + * + * An extremely important detail: setting one dirty state doesn't unset + * the other. For example, setting the global dirty state to false does not + * reset the row-level dirty flags. So, the caller of the render state API must + * be careful to manage both layers of dirty state correctly. + * + * ## Examples + * + * ### Creating and updating render state + * @snippet c-vt-render/src/main.c render-state-update + * + * ### Checking dirty state + * @snippet c-vt-render/src/main.c render-dirty-check + * + * ### Reading colors + * @snippet c-vt-render/src/main.c render-colors + * + * ### Reading cursor state + * @snippet c-vt-render/src/main.c render-cursor + * + * ### Iterating rows and cells + * @snippet c-vt-render/src/main.c render-row-iterate + * + * ### Resetting dirty state after rendering + * @snippet c-vt-render/src/main.c render-dirty-reset + * + * @{ + */ + +/** + * Dirty state of a render state after update. + * + * @ingroup render + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Not dirty at all; rendering can be skipped. */ + GHOSTTY_RENDER_STATE_DIRTY_FALSE = 0, + + /** Some rows changed; renderer can redraw incrementally. */ + GHOSTTY_RENDER_STATE_DIRTY_PARTIAL = 1, + + /** Global state changed; renderer should redraw everything. */ + GHOSTTY_RENDER_STATE_DIRTY_FULL = 2, + GHOSTTY_RENDER_STATE_DIRTY_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyRenderStateDirty; + +/** + * Visual style of the cursor. + * + * @ingroup render + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Bar cursor (DECSCUSR 5, 6). */ + GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BAR = 0, + + /** Block cursor (DECSCUSR 1, 2). */ + GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BLOCK = 1, + + /** Underline cursor (DECSCUSR 3, 4). */ + GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_UNDERLINE = 2, + + /** Hollow block cursor. */ + GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BLOCK_HOLLOW = 3, + GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyRenderStateCursorVisualStyle; + +/** + * Queryable data kinds for ghostty_render_state_get(). + * + * @ingroup render + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Invalid / sentinel value. */ + GHOSTTY_RENDER_STATE_DATA_INVALID = 0, + + /** Viewport width in cells (uint16_t). */ + GHOSTTY_RENDER_STATE_DATA_COLS = 1, + + /** Viewport height in cells (uint16_t). */ + GHOSTTY_RENDER_STATE_DATA_ROWS = 2, + + /** Current dirty state (GhosttyRenderStateDirty). */ + GHOSTTY_RENDER_STATE_DATA_DIRTY = 3, + + /** Populate a pre-allocated GhosttyRenderStateRowIterator with row data + * from the render state (GhosttyRenderStateRowIterator). Row data is + * only valid as long as the underlying render state is not updated. + * It is unsafe to use row data after updating the render state. + * */ + GHOSTTY_RENDER_STATE_DATA_ROW_ITERATOR = 4, + + /** Default/current background color (GhosttyColorRgb). */ + GHOSTTY_RENDER_STATE_DATA_COLOR_BACKGROUND = 5, + + /** Default/current foreground color (GhosttyColorRgb). */ + GHOSTTY_RENDER_STATE_DATA_COLOR_FOREGROUND = 6, + + /** Cursor color when explicitly set by terminal state (GhosttyColorRgb). + * Returns GHOSTTY_INVALID_VALUE if no explicit cursor color is set; + * use COLOR_CURSOR_HAS_VALUE to check first. */ + GHOSTTY_RENDER_STATE_DATA_COLOR_CURSOR = 7, + + /** Whether an explicit cursor color is set (bool). */ + GHOSTTY_RENDER_STATE_DATA_COLOR_CURSOR_HAS_VALUE = 8, + + /** The active 256-color palette (GhosttyColorRgb[256]). */ + GHOSTTY_RENDER_STATE_DATA_COLOR_PALETTE = 9, + + /** The visual style of the cursor (GhosttyRenderStateCursorVisualStyle). */ + GHOSTTY_RENDER_STATE_DATA_CURSOR_VISUAL_STYLE = 10, + + /** Whether the cursor is visible based on terminal modes (bool). */ + GHOSTTY_RENDER_STATE_DATA_CURSOR_VISIBLE = 11, + + /** Whether the cursor should blink based on terminal modes (bool). */ + GHOSTTY_RENDER_STATE_DATA_CURSOR_BLINKING = 12, + + /** Whether the cursor is at a password input field (bool). */ + GHOSTTY_RENDER_STATE_DATA_CURSOR_PASSWORD_INPUT = 13, + + /** Whether the cursor is visible within the viewport (bool). + * If false, the cursor viewport position values are undefined. */ + GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_HAS_VALUE = 14, + + /** Cursor viewport x position in cells (uint16_t). + * Only valid when CURSOR_VIEWPORT_HAS_VALUE is true. */ + GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_X = 15, + + /** Cursor viewport y position in cells (uint16_t). + * Only valid when CURSOR_VIEWPORT_HAS_VALUE is true. */ + GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_Y = 16, + + /** Whether the cursor is on the tail of a wide character (bool). + * Only valid when CURSOR_VIEWPORT_HAS_VALUE is true. */ + GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_WIDE_TAIL = 17, + GHOSTTY_RENDER_STATE_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyRenderStateData; + +/** + * Settable options for ghostty_render_state_set(). + * + * @ingroup render + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Set dirty state (GhosttyRenderStateDirty). */ + GHOSTTY_RENDER_STATE_OPTION_DIRTY = 0, + GHOSTTY_RENDER_STATE_OPTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyRenderStateOption; + +/** + * Queryable data kinds for ghostty_render_state_row_get(). + * + * @ingroup render + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Invalid / sentinel value. */ + GHOSTTY_RENDER_STATE_ROW_DATA_INVALID = 0, + + /** Whether the current row is dirty (bool). */ + GHOSTTY_RENDER_STATE_ROW_DATA_DIRTY = 1, + + /** The raw row value (GhosttyRow). */ + GHOSTTY_RENDER_STATE_ROW_DATA_RAW = 2, + + /** Populate a pre-allocated GhosttyRenderStateRowCells with cell data for + * the current row (GhosttyRenderStateRowCells). Cell data is only + * valid as long as the underlying render state is not updated. + * It is unsafe to use cell data after updating the render state. */ + GHOSTTY_RENDER_STATE_ROW_DATA_CELLS = 3, + + /** Row-local selected cell range (GhosttyRenderStateRowSelection). */ + GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION = 4, + GHOSTTY_RENDER_STATE_ROW_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyRenderStateRowData; + +/** + * Settable options for ghostty_render_state_row_set(). + * + * @ingroup render + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Set dirty state for the current row (bool). */ + GHOSTTY_RENDER_STATE_ROW_OPTION_DIRTY = 0, + GHOSTTY_RENDER_STATE_ROW_OPTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyRenderStateRowOption; + +/** + * Row-local selection range. + * + * This struct uses the sized-struct ABI pattern. Initialize with + * GHOSTTY_INIT_SIZED(GhosttyRenderStateRowSelection) before querying + * GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION. + * + * Querying GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION returns GHOSTTY_NO_VALUE + * if the current row does not intersect the current selection. + * + * @ingroup render + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttyRenderStateRowSelection). */ + size_t size; + + /** Start column of the row-local selection range, inclusive. */ + uint16_t start_x; + + /** End column of the row-local selection range, inclusive. */ + uint16_t end_x; +} GhosttyRenderStateRowSelection; + +/** + * Render-state color information. + * + * This struct uses the sized-struct ABI pattern. Initialize with + * GHOSTTY_INIT_SIZED(GhosttyRenderStateColors) before calling + * ghostty_render_state_colors_get(). + * + * Example: + * @code + * GhosttyRenderStateColors colors = GHOSTTY_INIT_SIZED(GhosttyRenderStateColors); + * GhosttyResult result = ghostty_render_state_colors_get(state, &colors); + * @endcode + * + * @ingroup render + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttyRenderStateColors). */ + size_t size; + + /** The default/current background color for the render state. */ + GhosttyColorRgb background; + + /** The default/current foreground color for the render state. */ + GhosttyColorRgb foreground; + + /** The cursor color when explicitly set by terminal state. */ + GhosttyColorRgb cursor; + + /** + * True when cursor contains a valid explicit cursor color value. + * If this is false, the cursor color should be ignored; it will + * contain undefined data. + * */ + bool cursor_has_value; + + /** The active 256-color palette for this render state. */ + GhosttyColorRgb palette[256]; +} GhosttyRenderStateColors; + +/** + * Create a new render state instance. + * + * @param allocator Pointer to allocator, or NULL to use the default allocator + * @param state Pointer to store the created render state handle + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation + * failure + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_new(const GhosttyAllocator* allocator, + GhosttyRenderState* state); + +/** + * Free a render state instance. + * + * Releases all resources associated with the render state. After this call, + * the render state handle becomes invalid. + * + * @param state The render state handle to free (may be NULL) + * + * @ingroup render + */ +GHOSTTY_API void ghostty_render_state_free(GhosttyRenderState state); + +/** + * Update a render state instance from a terminal. + * + * This consumes terminal/screen dirty state in the same way as the internal + * render state update path. + * + * @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param terminal The terminal handle to read from (NULL returns GHOSTTY_INVALID_VALUE) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` or + * `terminal` is NULL, GHOSTTY_OUT_OF_MEMORY if updating the state requires + * allocation and that allocation fails + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_update(GhosttyRenderState state, + GhosttyTerminal terminal); + +/** + * Get a value from a render state. + * + * The `out` pointer must point to a value of the type corresponding to the + * requested data kind (see GhosttyRenderStateData). + * + * @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param data The data kind to query + * @param[out] out Pointer to receive the queried value + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` is + * NULL or `data` is not a recognized enum value + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_get(GhosttyRenderState state, + GhosttyRenderStateData data, + void* out); + +/** + * Get multiple data fields from a render state in a single call. + * + * Each element in the keys array specifies a data kind, and the + * corresponding element in the values array receives the result. + * + * Processing stops at the first error; on success out_written + * is set to count, on error it is set to the index of the + * failing key (i.e. the number of values successfully written). + * + * @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param count Number of key/value pairs + * @param keys Array of data kinds to query + * @param values Array of output pointers (types must match each key's + * documented output type) + * @param[out] out_written On return, receives the number of values + * successfully written (may be NULL) + * @return GHOSTTY_SUCCESS if all queries succeed + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_get_multi( + GhosttyRenderState state, + size_t count, + const GhosttyRenderStateData* keys, + void** values, + size_t* out_written); + +/** + * Set an option on a render state. + * + * The `value` pointer must point to a value of the type corresponding to the + * requested option kind (see GhosttyRenderStateOption). + * + * @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param option The option to set + * @param[in] value Pointer to the value to set (NULL returns + * GHOSTTY_INVALID_VALUE) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` or + * `value` is NULL + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_set(GhosttyRenderState state, + GhosttyRenderStateOption option, + const void* value); + +/** + * Get the current color information from a render state. + * + * This writes as many fields as fit in the caller-provided sized struct. + * `out_colors->size` must be set by the caller (typically via + * GHOSTTY_INIT_SIZED(GhosttyRenderStateColors)). + * + * @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param[out] out_colors Sized output struct to receive render-state colors + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` or + * `out_colors` is NULL, or if `out_colors->size` is smaller than + * `sizeof(size_t)` + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_colors_get(GhosttyRenderState state, + GhosttyRenderStateColors* out_colors); + +/** + * Create a new row iterator instance. + * + * All fields except the allocator are left undefined until populated + * via ghostty_render_state_get() with + * GHOSTTY_RENDER_STATE_DATA_ROW_ITERATOR. + * + * @param allocator Pointer to allocator, or NULL to use the default allocator + * @param[out] out_iterator On success, receives the created iterator handle + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation + * failure + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_row_iterator_new( + const GhosttyAllocator* allocator, + GhosttyRenderStateRowIterator* out_iterator); + +/** + * Free a render-state row iterator. + * + * @param iterator The iterator handle to free (may be NULL) + * + * @ingroup render + */ +GHOSTTY_API void ghostty_render_state_row_iterator_free(GhosttyRenderStateRowIterator iterator); + +/** + * Move a render-state row iterator to the next row. + * + * Returns true if the iterator moved successfully and row data is + * available to read at the new position. + * + * @param iterator The iterator handle to advance (may be NULL) + * @return true if advanced to the next row, false if `iterator` is + * NULL or if the iterator has reached the end + * + * @ingroup render + */ +GHOSTTY_API bool ghostty_render_state_row_iterator_next(GhosttyRenderStateRowIterator iterator); + +/** + * Get a value from the current row in a render-state row iterator. + * + * The `out` pointer must point to a value of the type corresponding to the + * requested data kind (see GhosttyRenderStateRowData). + * Call ghostty_render_state_row_iterator_next() at least once before + * calling this function. + * + * @param iterator The iterator handle to query (NULL returns GHOSTTY_INVALID_VALUE) + * @param data The data kind to query + * @param[out] out Pointer to receive the queried value + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if + * `iterator` is NULL or the iterator is not positioned on a row + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_row_get( + GhosttyRenderStateRowIterator iterator, + GhosttyRenderStateRowData data, + void* out); + +/** + * Get multiple data fields from the current row in a single call. + * + * Each element in the keys array specifies a data kind, and the + * corresponding element in the values array receives the result. + * + * Processing stops at the first error; on success out_written + * is set to count, on error it is set to the index of the + * failing key (i.e. the number of values successfully written). + * + * @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param count Number of key/value pairs + * @param keys Array of data kinds to query + * @param values Array of output pointers (types must match each key's + * documented output type) + * @param[out] out_written On return, receives the number of values + * successfully written (may be NULL) + * @return GHOSTTY_SUCCESS if all queries succeed + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_row_get_multi( + GhosttyRenderStateRowIterator iterator, + size_t count, + const GhosttyRenderStateRowData* keys, + void** values, + size_t* out_written); + +/** + * Set an option on the current row in a render-state row iterator. + * + * The `value` pointer must point to a value of the type corresponding to the + * requested option kind (see GhosttyRenderStateRowOption). + * Call ghostty_render_state_row_iterator_next() at least once before + * calling this function. + * + * @param iterator The iterator handle to update (NULL returns GHOSTTY_INVALID_VALUE) + * @param option The option to set + * @param[in] value Pointer to the value to set (NULL returns + * GHOSTTY_INVALID_VALUE) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if + * `iterator` is NULL or the iterator is not positioned on a row + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_row_set( + GhosttyRenderStateRowIterator iterator, + GhosttyRenderStateRowOption option, + const void* value); + +/** + * Create a new row cells instance. + * + * All fields except the allocator are left undefined until populated + * via ghostty_render_state_row_get() with + * GHOSTTY_RENDER_STATE_ROW_DATA_CELLS. + * + * You can reuse this value repeatedly with ghostty_render_state_row_get() to + * avoid allocating a new cells container for every row. + * + * @param allocator Pointer to allocator, or NULL to use the default allocator + * @param[out] out_cells On success, receives the created row cells handle + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation + * failure + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_new( + const GhosttyAllocator* allocator, + GhosttyRenderStateRowCells* out_cells); + +/** + * Queryable data kinds for ghostty_render_state_row_cells_get(). + * + * @ingroup render + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Invalid / sentinel value. */ + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_INVALID = 0, + + /** The raw cell value (GhosttyCell). */ + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_RAW = 1, + + /** The style for the current cell (GhosttyStyle). */ + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_STYLE = 2, + + /** The total number of grapheme codepoints including the base codepoint + * (uint32_t). Returns 0 if the cell has no text. */ + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_LEN = 3, + + /** Write grapheme codepoints into a caller-provided buffer (uint32_t*). + * The buffer must be at least graphemes_len elements. The base codepoint + * is written first, followed by any extra codepoints. */ + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_BUF = 4, + + /** The resolved background color of the cell (GhosttyColorRgb). + * Flattens the three possible sources: content-tag bg_color_rgb, + * content-tag bg_color_palette (looked up in the palette), or the + * style's bg_color. Returns GHOSTTY_INVALID_VALUE if the cell has + * no background color, in which case the caller should use whatever + * default background color it wants (e.g. the terminal background). */ + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_BG_COLOR = 5, + + /** The resolved foreground color of the cell (GhosttyColorRgb). + * Resolves palette indices through the palette. Bold color handling + * is not applied; the caller should handle bold styling separately. + * Returns GHOSTTY_INVALID_VALUE if the cell has no explicit foreground + * color, in which case the caller should use whatever default foreground + * color it wants (e.g. the terminal foreground). */ + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_FG_COLOR = 6, + + /** Whether the cell is contained within the current selection (bool). + * This returns true when the cell's column is within the current row's + * row-local selection range, and false otherwise. Rendering policy for + * selected cells (colors, inversion, etc.) is left to the caller. + * + * Renderers that can draw cells in spans may be more efficient querying + * GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION once per row and applying that + * range directly, avoiding one C API call per cell for selection state. */ + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_SELECTED = 7, + + /** Whether the cell has any explicit styling (bool). + * This is equivalent to querying the raw cell's + * GHOSTTY_CELL_DATA_HAS_STYLING value, but avoids materializing the raw + * GhosttyCell for renderers that only need to know whether fetching the + * full style is necessary. */ + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_HAS_STYLING = 8, + + /** + * Encode the current cell's full grapheme cluster as UTF-8 into a + * caller-provided buffer (GhosttyBuffer). + * + * The base codepoint is encoded first, followed by any extra grapheme + * codepoints. Returns GHOSTTY_SUCCESS with len=0 when the cell has no text. + * + * If ptr is NULL or cap is too small for a non-empty cell, returns + * GHOSTTY_OUT_OF_SPACE without writing any bytes and sets len to the required + * buffer size in bytes. + */ + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_UTF8 = 9, + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyRenderStateRowCellsData; + +/** + * Move a render-state row cells iterator to the next cell. + * + * Returns true if the iterator moved successfully and cell data is + * available to read at the new position. + * + * @param cells The row cells handle to advance (may be NULL) + * @return true if advanced to the next cell, false if `cells` is + * NULL or if the iterator has reached the end + * + * @ingroup render + */ +GHOSTTY_API bool ghostty_render_state_row_cells_next(GhosttyRenderStateRowCells cells); + +/** + * Move a render-state row cells iterator to a specific column. + * + * Positions the iterator at the given x (column) index so that + * subsequent reads return data for that cell. + * + * @param cells The row cells handle to reposition (NULL returns + * GHOSTTY_INVALID_VALUE) + * @param x The zero-based column index to select + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `cells` + * is NULL or `x` is out of range + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_select( + GhosttyRenderStateRowCells cells, uint16_t x); + +/** + * Get a value from the current cell in a render-state row cells iterator. + * + * The `out` pointer must point to a value of the type corresponding to the + * requested data kind (see GhosttyRenderStateRowCellsData). + * Call ghostty_render_state_row_cells_next() or + * ghostty_render_state_row_cells_select() at least once before + * calling this function. + * + * @param cells The row cells handle to query (NULL returns GHOSTTY_INVALID_VALUE) + * @param data The data kind to query + * @param[out] out Pointer to receive the queried value + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if + * `cells` is NULL or the iterator is not positioned on a cell + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_get( + GhosttyRenderStateRowCells cells, + GhosttyRenderStateRowCellsData data, + void* out); + +/** + * Get multiple data fields from the current cell in a single call. + * + * Each element in the keys array specifies a data kind, and the + * corresponding element in the values array receives the result. + * + * Processing stops at the first error; on success out_written + * is set to count, on error it is set to the index of the + * failing key (i.e. the number of values successfully written). + * + * @param cells The row cells handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param count Number of key/value pairs + * @param keys Array of data kinds to query + * @param values Array of output pointers (types must match each key's + * documented output type) + * @param[out] out_written On return, receives the number of values + * successfully written (may be NULL) + * @return GHOSTTY_SUCCESS if all queries succeed + * + * @ingroup render + */ +GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_get_multi( + GhosttyRenderStateRowCells cells, + size_t count, + const GhosttyRenderStateRowCellsData* keys, + void** values, + size_t* out_written); + +/** + * Free a row cells instance. + * + * @param cells The row cells handle to free (may be NULL) + * + * @ingroup render + */ +GHOSTTY_API void ghostty_render_state_row_cells_free(GhosttyRenderStateRowCells cells); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_RENDER_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/screen.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/screen.h new file mode 100644 index 0000000000..9f639b5831 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/screen.h @@ -0,0 +1,400 @@ +/** + * @file screen.h + * + * Terminal screen cell and row types. + */ + +#ifndef GHOSTTY_VT_SCREEN_H +#define GHOSTTY_VT_SCREEN_H + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup screen Screen + * + * Terminal screen cell and row types. + * + * These types represent the contents of a terminal screen. A GhosttyCell + * is a single grid cell and a GhosttyRow is a single row. Both are opaque + * values whose fields are accessed via ghostty_cell_get() and + * ghostty_row_get() respectively. + * + * @{ + */ + +/** + * Opaque cell value. + * + * Represents a single terminal cell. The internal layout is opaque and + * must be queried via ghostty_cell_get(). Obtain cell values from + * terminal query APIs. + * + * @ingroup screen + */ +typedef uint64_t GhosttyCell; + +/** + * Opaque row value. + * + * Represents a single terminal row. The internal layout is opaque and + * must be queried via ghostty_row_get(). Obtain row values from + * terminal query APIs. + * + * @ingroup screen + */ +typedef uint64_t GhosttyRow; + +/** + * Cell content tag. + * + * Describes what kind of content a cell holds. + * + * @ingroup screen + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** A single codepoint (may be zero for empty). */ + GHOSTTY_CELL_CONTENT_CODEPOINT = 0, + + /** A codepoint that is part of a multi-codepoint grapheme cluster. */ + GHOSTTY_CELL_CONTENT_CODEPOINT_GRAPHEME = 1, + + /** No text; background color from palette. */ + GHOSTTY_CELL_CONTENT_BG_COLOR_PALETTE = 2, + + /** No text; background color as RGB. */ + GHOSTTY_CELL_CONTENT_BG_COLOR_RGB = 3, + GHOSTTY_CELL_CONTENT_TAG_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyCellContentTag; + +/** + * Cell wide property. + * + * Describes the width behavior of a cell. + * + * @ingroup screen + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Not a wide character, cell width 1. */ + GHOSTTY_CELL_WIDE_NARROW = 0, + + /** Wide character, cell width 2. */ + GHOSTTY_CELL_WIDE_WIDE = 1, + + /** Spacer after wide character. Do not render. */ + GHOSTTY_CELL_WIDE_SPACER_TAIL = 2, + + /** Spacer at end of soft-wrapped line for a wide character. */ + GHOSTTY_CELL_WIDE_SPACER_HEAD = 3, + GHOSTTY_CELL_WIDE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyCellWide; + +/** + * Semantic content type of a cell. + * + * Set by semantic prompt sequences (OSC 133) to distinguish between + * command output, user input, and shell prompt text. + * + * @ingroup screen + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Regular output content, such as command output. */ + GHOSTTY_CELL_SEMANTIC_OUTPUT = 0, + + /** Content that is part of user input. */ + GHOSTTY_CELL_SEMANTIC_INPUT = 1, + + /** Content that is part of a shell prompt. */ + GHOSTTY_CELL_SEMANTIC_PROMPT = 2, + GHOSTTY_CELL_SEMANTIC_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyCellSemanticContent; + +/** + * Cell data types. + * + * These values specify what type of data to extract from a cell + * using `ghostty_cell_get`. + * + * @ingroup screen + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Invalid data type. Never results in any data extraction. */ + GHOSTTY_CELL_DATA_INVALID = 0, + + /** + * The codepoint of the cell (0 if empty or bg-color-only). + * + * Output type: uint32_t * + */ + GHOSTTY_CELL_DATA_CODEPOINT = 1, + + /** + * The content tag describing what kind of content is in the cell. + * + * Output type: GhosttyCellContentTag * + */ + GHOSTTY_CELL_DATA_CONTENT_TAG = 2, + + /** + * The wide property of the cell. + * + * Output type: GhosttyCellWide * + */ + GHOSTTY_CELL_DATA_WIDE = 3, + + /** + * Whether the cell has text to render. + * + * Output type: bool * + */ + GHOSTTY_CELL_DATA_HAS_TEXT = 4, + + /** + * Whether the cell has non-default styling. + * + * Output type: bool * + */ + GHOSTTY_CELL_DATA_HAS_STYLING = 5, + + /** + * The style ID for the cell (for use with style lookups). + * + * Output type: uint16_t * + */ + GHOSTTY_CELL_DATA_STYLE_ID = 6, + + /** + * Whether the cell has a hyperlink. + * + * Output type: bool * + */ + GHOSTTY_CELL_DATA_HAS_HYPERLINK = 7, + + /** + * Whether the cell is protected. + * + * Output type: bool * + */ + GHOSTTY_CELL_DATA_PROTECTED = 8, + + /** + * The semantic content type of the cell (from OSC 133). + * + * Output type: GhosttyCellSemanticContent * + */ + GHOSTTY_CELL_DATA_SEMANTIC_CONTENT = 9, + + /** + * The palette index for the cell's background color. + * Only valid when content_tag is GHOSTTY_CELL_CONTENT_BG_COLOR_PALETTE. + * + * Output type: GhosttyColorPaletteIndex * + */ + GHOSTTY_CELL_DATA_COLOR_PALETTE = 10, + + /** + * The RGB value for the cell's background color. + * Only valid when content_tag is GHOSTTY_CELL_CONTENT_BG_COLOR_RGB. + * + * Output type: GhosttyColorRgb * + */ + GHOSTTY_CELL_DATA_COLOR_RGB = 11, + GHOSTTY_CELL_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyCellData; + +/** + * Row semantic prompt state. + * + * Indicates whether any cells in a row are part of a shell prompt, + * as reported by OSC 133 sequences. + * + * @ingroup screen + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** No prompt cells in this row. */ + GHOSTTY_ROW_SEMANTIC_NONE = 0, + + /** Prompt cells exist and this is a primary prompt line. */ + GHOSTTY_ROW_SEMANTIC_PROMPT = 1, + + /** Prompt cells exist and this is a continuation line. */ + GHOSTTY_ROW_SEMANTIC_PROMPT_CONTINUATION = 2, + GHOSTTY_ROW_SEMANTIC_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyRowSemanticPrompt; + +/** + * Row data types. + * + * These values specify what type of data to extract from a row + * using `ghostty_row_get`. + * + * @ingroup screen + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Invalid data type. Never results in any data extraction. */ + GHOSTTY_ROW_DATA_INVALID = 0, + + /** + * Whether this row is soft-wrapped. + * + * Output type: bool * + */ + GHOSTTY_ROW_DATA_WRAP = 1, + + /** + * Whether this row is a continuation of a soft-wrapped row. + * + * Output type: bool * + */ + GHOSTTY_ROW_DATA_WRAP_CONTINUATION = 2, + + /** + * Whether any cells in this row have grapheme clusters. + * + * Output type: bool * + */ + GHOSTTY_ROW_DATA_GRAPHEME = 3, + + /** + * Whether any cells in this row have styling (may have false positives). + * + * Output type: bool * + */ + GHOSTTY_ROW_DATA_STYLED = 4, + + /** + * Whether any cells in this row have hyperlinks (may have false positives). + * + * Output type: bool * + */ + GHOSTTY_ROW_DATA_HYPERLINK = 5, + + /** + * The semantic prompt state of this row. + * + * Output type: GhosttyRowSemanticPrompt * + */ + GHOSTTY_ROW_DATA_SEMANTIC_PROMPT = 6, + + /** + * Whether this row contains a Kitty virtual placeholder. + * + * Output type: bool * + */ + GHOSTTY_ROW_DATA_KITTY_VIRTUAL_PLACEHOLDER = 7, + + /** + * Whether this row is dirty and requires a redraw. + * + * Output type: bool * + */ + GHOSTTY_ROW_DATA_DIRTY = 8, + GHOSTTY_ROW_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyRowData; + +/** + * Get data from a cell. + * + * Extracts typed data from the given cell based on the specified + * data type. The output pointer must be of the appropriate type for the + * requested data kind. Valid data types and output types are documented + * in the `GhosttyCellData` enum. + * + * @param cell The cell value + * @param data The type of data to extract + * @param out Pointer to store the extracted data (type depends on data parameter) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the + * data type is invalid + * + * @ingroup screen + */ +GHOSTTY_API GhosttyResult ghostty_cell_get(GhosttyCell cell, + GhosttyCellData data, + void *out); + +/** + * Get multiple data fields from a cell in a single call. + * + * Each element in the keys array specifies a data kind, and the + * corresponding element in the values array receives the result. + * + * Processing stops at the first error; on success out_written + * is set to count, on error it is set to the index of the + * failing key (i.e. the number of values successfully written). + * + * @param cell The cell value + * @param count Number of key/value pairs + * @param keys Array of data kinds to query + * @param values Array of output pointers (types must match each key's + * documented output type) + * @param[out] out_written On return, receives the number of values + * successfully written (may be NULL) + * @return GHOSTTY_SUCCESS if all queries succeed + * + * @ingroup screen + */ +GHOSTTY_API GhosttyResult ghostty_cell_get_multi(GhosttyCell cell, + size_t count, + const GhosttyCellData* keys, + void** values, + size_t* out_written); + +/** + * Get data from a row. + * + * Extracts typed data from the given row based on the specified + * data type. The output pointer must be of the appropriate type for the + * requested data kind. Valid data types and output types are documented + * in the `GhosttyRowData` enum. + * + * @param row The row value + * @param data The type of data to extract + * @param out Pointer to store the extracted data (type depends on data parameter) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the + * data type is invalid + * + * @ingroup screen + */ +GHOSTTY_API GhosttyResult ghostty_row_get(GhosttyRow row, + GhosttyRowData data, + void *out); + +/** + * Get multiple data fields from a row in a single call. + * + * Each element in the keys array specifies a data kind, and the + * corresponding element in the values array receives the result. + * + * Processing stops at the first error; on success out_written + * is set to count, on error it is set to the index of the + * failing key (i.e. the number of values successfully written). + * + * @param row The row value + * @param count Number of key/value pairs + * @param keys Array of data kinds to query + * @param values Array of output pointers (types must match each key's + * documented output type) + * @param[out] out_written On return, receives the number of values + * successfully written (may be NULL) + * @return GHOSTTY_SUCCESS if all queries succeed + * + * @ingroup screen + */ +GHOSTTY_API GhosttyResult ghostty_row_get_multi(GhosttyRow row, + size_t count, + const GhosttyRowData* keys, + void** values, + size_t* out_written); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_SCREEN_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/selection.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/selection.h new file mode 100644 index 0000000000..3b926aab62 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/selection.h @@ -0,0 +1,1061 @@ +/** + * @file selection.h + * + * Selection range type for specifying a region of terminal content. + */ + +#ifndef GHOSTTY_VT_SELECTION_H +#define GHOSTTY_VT_SELECTION_H + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup selection Selection + * + * A snapshot selection range defined by two grid references that identifies + * a contiguous or rectangular region of terminal content. + * + * The start and end values are GhosttyGridRef values. They are therefore + * untracked grid references and inherit the same lifetime rules: they are + * only safe to use until the next mutating operation on the terminal that + * produced them, including freeing the terminal. To keep a selection valid + * across terminal mutations, callers must maintain tracked grid references + * for the endpoints and reconstruct a GhosttySelection from fresh snapshots + * when needed. + * + * Selection gestures provide a reusable state machine for turning UI pointer + * interactions into selection snapshots. A caller creates one + * GhosttySelectionGesture per active gesture stream, reuses typed + * GhosttySelectionGestureEvent objects for synthetic press, drag, release, + * autoscroll tick, and deep-press events, and applies each event with + * ghostty_selection_gesture_event(). The returned GhosttySelection is a + * snapshot; the embedder decides whether to render it, format/copy it, or + * install it as the terminal's active selection. + * + * ## Examples + * + * @snippet c-vt-selection/src/main.c selection-main + * @snippet c-vt-selection-gesture/src/main.c selection-gesture-main + * + * @{ + */ + +/** + * Opaque handle to state for interpreting terminal selection gestures. + * + * The gesture owns only the state required to interpret pointer events. Calls + * that use a gesture are not concurrency-safe and must be serialized with + * terminal mutations. + * + * @ingroup selection + */ +typedef struct GhosttySelectionGestureImpl* GhosttySelectionGesture; + +/** + * Opaque handle to reusable input data for selection gesture operations. + * + * Event options are set with ghostty_selection_gesture_event_set(). Individual + * gesture operations document which options are required or optional. + * + * @ingroup selection + */ +typedef struct GhosttySelectionGestureEventImpl* GhosttySelectionGestureEvent; + +/** + * A snapshot selection range defined by two grid references. + * + * Both endpoints are inclusive. The endpoints preserve selection direction + * and may be reversed; callers must not assume that start is the top-left + * endpoint or that end is the bottom-right endpoint. + * + * When rectangle is false, the endpoints describe a linear selection. When + * rectangle is true, the same endpoints are interpreted as opposite corners + * of a rectangular/block selection. + * + * The start and end values are untracked GhosttyGridRef snapshots and are + * only valid until the next mutating operation on the terminal that produced + * them unless the selection is reconstructed from tracked references. + * + * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it. + * + * @ingroup selection + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttySelection). */ + size_t size; + + /** + * Start of the selection range (inclusive). + * + * This may be after end in terminal order. It is an untracked + * GhosttyGridRef snapshot and follows untracked grid-ref lifetime rules. + */ + GhosttyGridRef start; + + /** + * End of the selection range (inclusive). + * + * This may be before start in terminal order. It is an untracked + * GhosttyGridRef snapshot and follows untracked grid-ref lifetime rules. + */ + GhosttyGridRef end; + + /** + * Whether the endpoints are interpreted as a rectangular/block selection + * rather than a linear selection. + */ + bool rectangle; +} GhosttySelection; + +/** + * Options for deriving a word selection from a terminal grid reference. + * + * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it. + * If boundary_codepoints is NULL and boundary_codepoints_len is 0, Ghostty's + * default word-boundary codepoints are used. If boundary_codepoints_len is + * non-zero, boundary_codepoints must not be NULL. + * + * @ingroup selection + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttyTerminalSelectWordOptions). */ + size_t size; + + /** Grid reference under which to derive the word selection. */ + GhosttyGridRef ref; + + /** Optional word-boundary codepoints as uint32_t scalar values. */ + const uint32_t* boundary_codepoints; + + /** Number of entries in boundary_codepoints. */ + size_t boundary_codepoints_len; +} GhosttyTerminalSelectWordOptions; + +/** + * Options for deriving the nearest word selection between two grid references. + * + * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it. + * If boundary_codepoints is NULL and boundary_codepoints_len is 0, Ghostty's + * default word-boundary codepoints are used. If boundary_codepoints_len is + * non-zero, boundary_codepoints must not be NULL. + * + * @ingroup selection + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttyTerminalSelectWordBetweenOptions). */ + size_t size; + + /** Starting grid reference for the inclusive search range. */ + GhosttyGridRef start; + + /** Ending grid reference for the inclusive search range. */ + GhosttyGridRef end; + + /** Optional word-boundary codepoints as uint32_t scalar values. */ + const uint32_t* boundary_codepoints; + + /** Number of entries in boundary_codepoints. */ + size_t boundary_codepoints_len; +} GhosttyTerminalSelectWordBetweenOptions; + +/** + * Options for deriving a line selection from a terminal grid reference. + * + * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it. + * If whitespace is NULL and whitespace_len is 0, Ghostty's default line-trim + * whitespace codepoints are used. If whitespace_len is non-zero, whitespace + * must not be NULL. + * + * @ingroup selection + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttyTerminalSelectLineOptions). */ + size_t size; + + /** Grid reference under which to derive the line selection. */ + GhosttyGridRef ref; + + /** Optional codepoints to trim from the start and end of the line. */ + const uint32_t* whitespace; + + /** Number of entries in whitespace. */ + size_t whitespace_len; + + /** Whether semantic prompt state changes should bound the line selection. */ + bool semantic_prompt_boundary; +} GhosttyTerminalSelectLineOptions; + +/** + * Options for one-shot formatting of a terminal selection. + * + * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it. + * + * If selection is NULL, the terminal's current active selection is used. + * If selection is non-NULL, that caller-provided snapshot selection is used. + * + * The selection is formatted from the terminal's active screen using the same + * formatting semantics as GhosttyFormatter. For copy/clipboard behavior + * matching Ghostty's Screen.selectionString(), use plain output with unwrap + * and trim both set to true. + * + * @ingroup selection + */ +typedef struct { + /** Size of this struct in bytes. Must be set to sizeof(GhosttyTerminalSelectionFormatOptions). */ + size_t size; + + /** Output format to emit. */ + GhosttyFormatterFormat emit; + + /** Whether to unwrap soft-wrapped lines. */ + bool unwrap; + + /** Whether to trim trailing whitespace on non-blank lines. */ + bool trim; + + /** + * Optional selection to format. + * + * If NULL, the terminal's current active selection is used. If the terminal + * has no active selection, formatting returns GHOSTTY_NO_VALUE. + * + * If non-NULL, the pointed-to selection must be a valid snapshot selection + * for this terminal and must obey GhosttySelection lifetime rules. + */ + const GhosttySelection *selection; +} GhosttyTerminalSelectionFormatOptions; + +/** + * Ordering of a selection's endpoints in terminal coordinates. + * + * Mirrored orders are only produced by rectangular selections whose start + * and end endpoints are on opposite diagonal corners that are not simple + * top-left-to-bottom-right or bottom-right-to-top-left orderings. + * + * @ingroup selection + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Start is before end in top-left to bottom-right order. */ + GHOSTTY_SELECTION_ORDER_FORWARD = 0, + + /** End is before start in top-left to bottom-right order. */ + GHOSTTY_SELECTION_ORDER_REVERSE = 1, + + /** Rectangular selection from top-right to bottom-left. */ + GHOSTTY_SELECTION_ORDER_MIRRORED_FORWARD = 2, + + /** Rectangular selection from bottom-left to top-right. */ + GHOSTTY_SELECTION_ORDER_MIRRORED_REVERSE = 3, + + GHOSTTY_SELECTION_ORDER_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySelectionOrder; + +/** + * Operation used to adjust a selection endpoint. + * + * Adjustment mutates the selection's logical end endpoint, not whichever + * endpoint is visually bottom/right. This preserves keyboard and drag + * behavior for both forward and reversed selections. + * + * @ingroup selection + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Move left to the previous non-empty cell, wrapping upward. */ + GHOSTTY_SELECTION_ADJUST_LEFT = 0, + + /** Move right to the next non-empty cell, wrapping downward. */ + GHOSTTY_SELECTION_ADJUST_RIGHT = 1, + + /** + * Move up one row at the current column, or to the beginning of the + * line if already at the top. + */ + GHOSTTY_SELECTION_ADJUST_UP = 2, + + /** + * Move down to the next non-blank row at the current column, or to the + * end of the line if none exists. + */ + GHOSTTY_SELECTION_ADJUST_DOWN = 3, + + /** Move to the top-left cell of the screen. */ + GHOSTTY_SELECTION_ADJUST_HOME = 4, + + /** Move to the right edge of the last non-blank row on the screen. */ + GHOSTTY_SELECTION_ADJUST_END = 5, + + /** + * Move up by one terminal page height, or to home if that would move + * past the top. + */ + GHOSTTY_SELECTION_ADJUST_PAGE_UP = 6, + + /** + * Move down by one terminal page height, or to end if that would move + * past the bottom. + */ + GHOSTTY_SELECTION_ADJUST_PAGE_DOWN = 7, + + /** Move to the left edge of the current line. */ + GHOSTTY_SELECTION_ADJUST_BEGINNING_OF_LINE = 8, + + /** Move to the right edge of the current line. */ + GHOSTTY_SELECTION_ADJUST_END_OF_LINE = 9, + + GHOSTTY_SELECTION_ADJUST_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySelectionAdjust; + +/** + * Selection behavior chosen for a gesture's click sequence. + * + * @ingroup selection + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Cell-granular drag selection. */ + GHOSTTY_SELECTION_GESTURE_BEHAVIOR_CELL = 0, + + /** Word selection on press and word-granular drag selection. */ + GHOSTTY_SELECTION_GESTURE_BEHAVIOR_WORD = 1, + + /** Line selection on press and line-granular drag selection. */ + GHOSTTY_SELECTION_GESTURE_BEHAVIOR_LINE = 2, + + /** Semantic command output selection on press and drag. */ + GHOSTTY_SELECTION_GESTURE_BEHAVIOR_OUTPUT = 3, + + GHOSTTY_SELECTION_GESTURE_BEHAVIOR_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySelectionGestureBehavior; + +/** + * Selection behaviors for single-, double-, and triple-click gestures. + * + * @ingroup selection + */ +typedef struct { + /** Behavior for single-click selection gestures. */ + GhosttySelectionGestureBehavior single_click; + + /** Behavior for double-click selection gestures. */ + GhosttySelectionGestureBehavior double_click; + + /** Behavior for triple-click selection gestures. */ + GhosttySelectionGestureBehavior triple_click; +} GhosttySelectionGestureBehaviors; + +/** + * Display geometry used to interpret selection gesture drag events. + * + * @ingroup selection + */ +typedef struct { + /** Number of columns in the rendered terminal grid. Must be non-zero. */ + uint32_t columns; + + /** Width of one terminal cell in surface pixels. Must be non-zero. */ + uint32_t cell_width; + + /** Left padding before the terminal grid begins in surface pixels. */ + uint32_t padding_left; + + /** Height of the rendered terminal surface in surface pixels. Must be non-zero. */ + uint32_t screen_height; +} GhosttySelectionGestureGeometry; + +/** + * Current autoscroll direction for an active selection drag gesture. + * + * @ingroup selection + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** No selection autoscroll is requested. */ + GHOSTTY_SELECTION_GESTURE_AUTOSCROLL_NONE = 0, + + /** Selection dragging should autoscroll the viewport upward. */ + GHOSTTY_SELECTION_GESTURE_AUTOSCROLL_UP = 1, + + /** Selection dragging should autoscroll the viewport downward. */ + GHOSTTY_SELECTION_GESTURE_AUTOSCROLL_DOWN = 2, + + GHOSTTY_SELECTION_GESTURE_AUTOSCROLL_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySelectionGestureAutoscroll; + +/** + * Data fields readable from a selection gesture with + * ghostty_selection_gesture_get(). + * + * @ingroup selection + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Current click count: uint8_t*. 0 means inactive. */ + GHOSTTY_SELECTION_GESTURE_DATA_CLICK_COUNT = 0, + + /** Whether the current/last left-click gesture has dragged: bool*. */ + GHOSTTY_SELECTION_GESTURE_DATA_DRAGGED = 1, + + /** Current autoscroll request: GhosttySelectionGestureAutoscroll*. */ + GHOSTTY_SELECTION_GESTURE_DATA_AUTOSCROLL = 2, + + /** Current gesture behavior: GhosttySelectionGestureBehavior*. */ + GHOSTTY_SELECTION_GESTURE_DATA_BEHAVIOR = 3, + + /** + * Current left-click anchor: GhosttyGridRef*. + * + * Returns GHOSTTY_NO_VALUE if there is no valid active anchor. On success, + * writes an untracked GhosttyGridRef snapshot with normal GhosttyGridRef + * lifetime rules. + */ + GHOSTTY_SELECTION_GESTURE_DATA_ANCHOR = 4, + + GHOSTTY_SELECTION_GESTURE_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySelectionGestureData; + +/** + * Selection gesture event type. + * + * The event type is fixed when the event is created. Each event type documents + * which options are valid and which options are required by gesture operations. + * + * @ingroup selection + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Press event for ghostty_selection_gesture_event(). */ + GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_PRESS = 0, + + /** Release event for ghostty_selection_gesture_event(). */ + GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_RELEASE = 1, + + /** Drag event for ghostty_selection_gesture_event(). */ + GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_DRAG = 2, + + /** Autoscroll tick event for ghostty_selection_gesture_event(). */ + GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_AUTOSCROLL_TICK = 3, + + /** Deep press event for ghostty_selection_gesture_event(). */ + GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_DEEP_PRESS = 4, + + GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySelectionGestureEventType; + +/** + * Options stored on a reusable selection gesture event. + * + * Passing NULL as the value to ghostty_selection_gesture_event_set() clears the + * corresponding option. + * + * @ingroup selection + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** + * Grid reference under the pointer: GhosttyGridRef*. + * + * Required for PRESS and DRAG events. Optional for RELEASE events; when unset + * or cleared, release records that the pointer did not map to a valid cell. + */ + GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REF = 0, + + /** + * Surface-space pointer position: GhosttySurfacePosition*. + * + * Valid for PRESS, DRAG, and AUTOSCROLL_TICK. + */ + GHOSTTY_SELECTION_GESTURE_EVENT_OPT_POSITION = 1, + + /** Maximum repeat-click distance in pixels: double*. */ + GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REPEAT_DISTANCE = 2, + + /** + * Optional monotonic event time in nanoseconds: uint64_t*. + * + * If unset, press treats the event as untimed and only single-click behavior + * is available. + */ + GHOSTTY_SELECTION_GESTURE_EVENT_OPT_TIME_NS = 3, + + /** Maximum interval between repeat clicks in nanoseconds: uint64_t*. */ + GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REPEAT_INTERVAL_NS = 4, + + /** + * Word-boundary codepoints: GhosttyCodepoints*. + * + * The codepoints are copied into event-owned storage when set. If unset, + * operations that need word boundaries use Ghostty's defaults. + * + * Valid for PRESS, DRAG, AUTOSCROLL_TICK, and DEEP_PRESS. + */ + GHOSTTY_SELECTION_GESTURE_EVENT_OPT_WORD_BOUNDARY_CODEPOINTS = 5, + + /** + * Selection behavior table: GhosttySelectionGestureBehaviors*. + * + * If unset, press uses the default behavior table: cell, word, line. + */ + GHOSTTY_SELECTION_GESTURE_EVENT_OPT_BEHAVIORS = 6, + + /** Whether a drag or autoscroll tick should produce a rectangular selection: bool*. */ + GHOSTTY_SELECTION_GESTURE_EVENT_OPT_RECTANGLE = 7, + + /** Drag display geometry: GhosttySelectionGestureGeometry*. Required for DRAG and AUTOSCROLL_TICK. */ + GHOSTTY_SELECTION_GESTURE_EVENT_OPT_GEOMETRY = 8, + + /** Viewport coordinate for an autoscroll tick: GhosttyPointCoordinate*. Required for AUTOSCROLL_TICK. */ + GHOSTTY_SELECTION_GESTURE_EVENT_OPT_VIEWPORT = 9, + + GHOSTTY_SELECTION_GESTURE_EVENT_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySelectionGestureEventOption; + +/** + * Create a reusable selection gesture event object. + * + * @param allocator Allocator, or NULL for the default allocator + * @param out_event Receives the created event handle + * @param type Event type. This is fixed for the lifetime of the event. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if out_event is + * NULL or type is invalid, or GHOSTTY_OUT_OF_MEMORY if allocation fails + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_selection_gesture_event_new( + const GhosttyAllocator* allocator, + GhosttySelectionGestureEvent* out_event, + GhosttySelectionGestureEventType type); + +/** + * Free a selection gesture event object. + * + * Passing NULL is allowed and is a no-op. + * + * @param event Selection gesture event handle to free + * + * @ingroup selection + */ +GHOSTTY_API void ghostty_selection_gesture_event_free( + GhosttySelectionGestureEvent event); + +/** + * Set or clear an option on a selection gesture event. + * + * The value type depends on option and is documented by + * GhosttySelectionGestureEventOption. Passing NULL for value clears the option. + * + * @param event Selection gesture event handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param option Event option to set or clear + * @param value Pointer to the input value for option, or NULL to clear + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY if copying + * event-owned data fails, or GHOSTTY_INVALID_VALUE if event, option, or + * value is invalid + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_selection_gesture_event_set( + GhosttySelectionGestureEvent event, + GhosttySelectionGestureEventOption option, + const void* value); + +/** + * Apply a selection gesture event and return the resulting selection snapshot. + * + * This dispatches to the gesture operation matching the event's fixed type. + * For GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_PRESS, the event must have + * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REF set before calling this function. + * All other press options use their initialized defaults when unset or cleared. + * + * For GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_RELEASE, only + * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REF is valid. It is optional; if unset or + * cleared, release records that the pointer did not map to a valid cell. Release + * events update gesture state but do not produce a selection, so this function + * returns GHOSTTY_NO_VALUE after applying them. + * + * For GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_DRAG, + * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REF and + * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_GEOMETRY are required. Position, + * rectangle, and word-boundary codepoints are optional and use initialized + * defaults when unset or cleared. + * + * For GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_AUTOSCROLL_TICK, + * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_VIEWPORT and + * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_GEOMETRY are required. Position, + * rectangle, and word-boundary codepoints are optional and use initialized + * defaults when unset or cleared. + * + * For GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_DEEP_PRESS, only + * GHOSTTY_SELECTION_GESTURE_EVENT_OPT_WORD_BOUNDARY_CODEPOINTS is valid. It is + * optional and uses initialized defaults when unset or cleared. + * + * The returned selection is not installed as the terminal's current selection. + * It is a snapshot with the same lifetime rules as GhosttySelection. + * + * @param gesture Selection gesture handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param terminal Terminal used to interpret and update gesture state + * @param event Selection gesture event handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param[out] out_selection On success, receives the resulting selection. May + * be NULL to apply the event and discard the selection result. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if the event does not + * currently produce a selection, GHOSTTY_OUT_OF_MEMORY if tracking + * gesture state fails, or GHOSTTY_INVALID_VALUE if gesture, terminal, + * event, or required event data is invalid + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_selection_gesture_event( + GhosttySelectionGesture gesture, + GhosttyTerminal terminal, + GhosttySelectionGestureEvent event, + GhosttySelection* out_selection); + +/** + * Create a selection gesture object. + * + * The gesture stores mutable state for terminal text selection gestures. The + * gesture is not bound to a terminal at creation time; terminal-dependent APIs + * take the terminal explicitly. + * + * @param allocator Allocator, or NULL for the default allocator + * @param out_gesture Receives the created gesture handle + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if out_gesture is + * NULL, or GHOSTTY_OUT_OF_MEMORY if allocation fails + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_selection_gesture_new( + const GhosttyAllocator* allocator, + GhosttySelectionGesture* out_gesture); + +/** + * Free a selection gesture object. + * + * This releases any tracked terminal references owned by the gesture using the + * provided terminal, then frees the gesture object. Passing NULL for gesture is + * allowed and is a no-op. + * + * If the terminal is still alive, pass the terminal most recently used with the + * gesture so any tracked terminal references can be released correctly. If the + * terminal has already been freed, pass NULL for terminal; the terminal's page + * storage has already released the underlying tracked references, so the + * gesture wrapper can be safely discarded without touching the stale terminal + * state. + * + * @param gesture Selection gesture handle to free + * @param terminal Terminal used to release tracked gesture state, or NULL if + * the terminal has already been freed + * + * @ingroup selection + */ +GHOSTTY_API void ghostty_selection_gesture_free( + GhosttySelectionGesture gesture, + GhosttyTerminal terminal); + +/** + * Reset any active selection gesture state. + * + * This cancels the active click sequence and releases any tracked terminal + * references owned by the gesture without freeing the gesture object. + * Passing NULL is allowed and is a no-op. + * + * @param gesture Selection gesture handle to reset + * @param terminal Terminal used to release tracked gesture state + * + * @ingroup selection + */ +GHOSTTY_API void ghostty_selection_gesture_reset( + GhosttySelectionGesture gesture, + GhosttyTerminal terminal); + +/** + * Read data from a selection gesture. + * + * The type of value depends on data and is documented by + * GhosttySelectionGestureData. For GHOSTTY_SELECTION_GESTURE_DATA_ANCHOR, + * the returned GhosttyGridRef is an untracked snapshot with normal grid-ref + * lifetime rules. + * + * @param gesture Selection gesture handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param terminal Terminal used to validate terminal-backed gesture state + * @param data Data field to read + * @param value Output pointer whose type depends on data + * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if the requested data + * has no value, or GHOSTTY_INVALID_VALUE if gesture, terminal, data, or + * value is invalid + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_selection_gesture_get( + GhosttySelectionGesture gesture, + GhosttyTerminal terminal, + GhosttySelectionGestureData data, + void* value); + +/** + * Read multiple data fields from a selection gesture in a single call. + * + * This is an optimization over calling ghostty_selection_gesture_get() multiple + * times. Each entry in values must point to storage of the type documented by + * the corresponding GhosttySelectionGestureData key. + * + * If any individual read fails, the function returns that error and writes the + * index of the failing key to out_written when out_written is non-NULL. On + * success, out_written receives count when non-NULL. + * + * @param gesture Selection gesture handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param terminal Terminal used to validate terminal-backed gesture state + * @param count Number of data fields to read + * @param keys Data fields to read (must not be NULL) + * @param values Output pointers corresponding to keys (must not be NULL) + * @param out_written Optional number of fields read, or failing index on error + * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if a requested data + * field has no value, or GHOSTTY_INVALID_VALUE if gesture, terminal, + * keys, values, or a value pointer is invalid + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_selection_gesture_get_multi( + GhosttySelectionGesture gesture, + GhosttyTerminal terminal, + size_t count, + const GhosttySelectionGestureData* keys, + void** values, + size_t* out_written); + +/** + * Derive a word selection snapshot from a terminal grid reference. + * + * The returned selection is not installed as the terminal's current + * selection. It is a snapshot with the same lifetime rules as GhosttySelection. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param options Word-selection options + * @param[out] out_selection On success, receives the derived selection + * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if the valid ref has + * no selectable word content, or GHOSTTY_INVALID_VALUE if the + * terminal, options, ref, codepoint pointer, or output pointer are + * invalid. + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_select_word( + GhosttyTerminal terminal, + const GhosttyTerminalSelectWordOptions* options, + GhosttySelection* out_selection); + +/** + * Derive the nearest word selection snapshot between two terminal grid refs. + * + * Starting at options->start, this searches toward options->end (inclusive) + * and returns the first selectable word found using Ghostty's word-selection + * rules. + * + * This is useful for implementing double-click-and-drag selection in a UI. If + * a user double-clicks one word and drags across spaces or punctuation toward + * another word, selecting only the word directly under the current pointer can + * flicker or collapse when the pointer is between words. Instead, ask for the + * nearest word between the original click and the drag point, ask again in the + * reverse direction, and combine the two word bounds into the drag selection. + * + * @snippet c-vt-selection/src/main.c selection-word-between + * + * The returned selection is not installed as the terminal's current + * selection. It is a snapshot with the same lifetime rules as GhosttySelection. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param options Word-between-selection options + * @param[out] out_selection On success, receives the derived selection + * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if there is no + * selectable word content between the valid refs, or + * GHOSTTY_INVALID_VALUE if the terminal, options, refs, codepoint + * pointer, or output pointer are invalid. + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_select_word_between( + GhosttyTerminal terminal, + const GhosttyTerminalSelectWordBetweenOptions* options, + GhosttySelection* out_selection); + +/** + * Derive a line selection snapshot from a terminal grid reference. + * + * The returned selection is not installed as the terminal's current + * selection. It is a snapshot with the same lifetime rules as GhosttySelection. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param options Line-selection options + * @param[out] out_selection On success, receives the derived selection + * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if the valid ref has + * no selectable line content, or GHOSTTY_INVALID_VALUE if the + * terminal, options, ref, codepoint pointer, or output pointer are + * invalid. + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_select_line( + GhosttyTerminal terminal, + const GhosttyTerminalSelectLineOptions* options, + GhosttySelection* out_selection); + +/** + * Derive a selection snapshot covering all selectable terminal content. + * + * The returned selection is not installed as the terminal's current + * selection. It is a snapshot with the same lifetime rules as GhosttySelection. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param[out] out_selection On success, receives the derived selection + * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if there is no + * selectable content, or GHOSTTY_INVALID_VALUE if the terminal or + * output pointer is invalid. + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_select_all( + GhosttyTerminal terminal, + GhosttySelection* out_selection); + +/** + * Derive a command-output selection snapshot from a terminal grid reference. + * + * The returned selection is not installed as the terminal's current + * selection. It is a snapshot with the same lifetime rules as GhosttySelection. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param ref Grid reference within command output to select + * @param[out] out_selection On success, receives the derived selection + * @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if the valid ref is + * not selectable command output, or GHOSTTY_INVALID_VALUE if the + * terminal, ref, or output pointer is invalid. + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_select_output( + GhosttyTerminal terminal, + GhosttyGridRef ref, + GhosttySelection* out_selection); + +/** + * Format a terminal selection into a caller-provided buffer. + * + * This is a one-shot convenience API for formatting either the terminal's + * active selection or a caller-provided GhosttySelection without explicitly + * creating a GhosttyFormatter. + * + * Pass NULL for buf to query the required output size. In that case, + * out_written receives the required size and the function returns + * GHOSTTY_OUT_OF_SPACE. + * + * If buf is too small, the function returns GHOSTTY_OUT_OF_SPACE and writes + * the required size to out_written. The caller can then retry with a larger + * buffer. + * + * If options.selection is NULL and the terminal has no active selection, the + * function returns GHOSTTY_NO_VALUE. + * + * @param terminal The terminal to read from (must not be NULL) + * @param options Selection formatting options + * @param buf Output buffer, or NULL to query required size + * @param buf_len Length of buf in bytes + * @param out_written Number of bytes written, or required size on + * GHOSTTY_OUT_OF_SPACE (must not be NULL) + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_selection_format_buf( + GhosttyTerminal terminal, + GhosttyTerminalSelectionFormatOptions options, + uint8_t* buf, + size_t buf_len, + size_t* out_written); + +/** + * Format a terminal selection into an allocated buffer. + * + * This is a one-shot convenience API for formatting either the terminal's + * active selection or a caller-provided GhosttySelection without explicitly + * creating a GhosttyFormatter. + * + * The returned buffer is allocated using allocator, or the default allocator + * if NULL is passed. The caller owns the returned buffer and must free it with + * ghostty_free(), passing the same allocator and returned length. + * + * The returned bytes are not NUL-terminated. This supports plain text, VT, and + * HTML uniformly as byte output. + * + * If options.selection is NULL and the terminal has no active selection, the + * function returns GHOSTTY_NO_VALUE and leaves out_ptr as NULL and out_len as 0. + * + * @param terminal The terminal to read from (must not be NULL) + * @param allocator Allocator used for the returned buffer, or NULL for the default allocator + * @param options Selection formatting options + * @param out_ptr Receives the allocated output buffer (must not be NULL) + * @param out_len Receives the output length in bytes (must not be NULL) + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_selection_format_alloc( + GhosttyTerminal terminal, + const GhosttyAllocator* allocator, + GhosttyTerminalSelectionFormatOptions options, + uint8_t** out_ptr, + size_t* out_len); + +/** + * Adjust a selection snapshot using terminal selection semantics. + * + * This mutates the caller-provided GhosttySelection in place. The logical end + * endpoint is always moved, regardless of whether the selection is forward or + * reversed visually. The input selection remains a snapshot: after adjustment, + * call ghostty_terminal_set() with GHOSTTY_TERMINAL_OPT_SELECTION to install it + * as the terminal-owned selection if desired. + * + * The selection's start and end grid refs must both be valid untracked + * snapshots for the given terminal's currently active screen. In practice, + * they must come from that terminal and screen, and no mutating terminal call + * may have occurred since the refs were produced or reconstructed from + * tracked refs. Passing refs from another terminal, another screen, or stale + * refs violates this precondition. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param selection Selection snapshot to adjust in place + * @param adjustment The adjustment operation to apply + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal, + * selection, or adjustment are invalid. Selection reference validity + * is a precondition and is not checked. + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_selection_adjust( + GhosttyTerminal terminal, + GhosttySelection* selection, + GhosttySelectionAdjust adjustment); + +/** + * Get the current endpoint ordering of a selection snapshot. + * + * The selection's start and end grid refs must both be valid untracked + * snapshots for the given terminal's currently active screen. In practice, + * they must come from that terminal and screen, and no mutating terminal call + * may have occurred since the refs were produced or reconstructed from + * tracked refs. Passing refs from another terminal, another screen, or stale + * refs violates this precondition. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param selection Selection snapshot to inspect + * @param[out] out_order On success, receives the selection order + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal, + * selection, or output pointer are invalid. Selection reference + * validity is a precondition and is not checked. + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_selection_order( + GhosttyTerminal terminal, + const GhosttySelection* selection, + GhosttySelectionOrder* out_order); + +/** + * Return a selection snapshot with endpoints ordered as requested. + * + * Use GHOSTTY_SELECTION_ORDER_FORWARD to get top-left to bottom-right bounds, + * and GHOSTTY_SELECTION_ORDER_REVERSE to get bottom-right to top-left bounds. + * Mirrored desired orders are accepted but normalized the same as forward. + * The output selection is a fresh untracked snapshot and is not installed as + * the terminal's current selection. + * + * The selection's start and end grid refs must both be valid untracked + * snapshots for the given terminal's currently active screen. In practice, + * they must come from that terminal and screen, and no mutating terminal call + * may have occurred since the refs were produced or reconstructed from + * tracked refs. Passing refs from another terminal, another screen, or stale + * refs violates this precondition. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param selection Selection snapshot to order + * @param desired Desired endpoint order + * @param[out] out_selection On success, receives the ordered selection + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal, + * selection, desired order, or output pointer are invalid. Selection + * reference validity is a precondition and is not checked. + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_selection_ordered( + GhosttyTerminal terminal, + const GhosttySelection* selection, + GhosttySelectionOrder desired, + GhosttySelection* out_selection); + +/** + * Test whether a terminal point is inside a selection snapshot. + * + * This uses the same selection semantics as the terminal, including + * rectangular/block selections and linear selections spanning multiple rows. + * + * The selection's start and end grid refs must both be valid untracked + * snapshots for the given terminal's currently active screen. In practice, + * they must come from that terminal and screen, and no mutating terminal call + * may have occurred since the refs were produced or reconstructed from + * tracked refs. Passing refs from another terminal, another screen, or stale + * refs violates this precondition. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param selection Selection snapshot to inspect + * @param point Point to test for containment + * @param[out] out_contains On success, receives whether point is inside selection + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal, + * selection, point, or output pointer are invalid. Selection reference + * validity is a precondition and is not checked. + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_selection_contains( + GhosttyTerminal terminal, + const GhosttySelection* selection, + GhosttyPoint point, + bool* out_contains); + +/** + * Test whether two selection snapshots are equal. + * + * Equality uses the terminal's internal selection semantics: both endpoint + * pins must match and both selections must have the same rectangular/block + * state. This avoids requiring callers to compare raw GhosttyGridRef internals. + * + * Both selections' start and end grid refs must be valid untracked snapshots + * for the given terminal's currently active screen. In practice, they must + * come from that terminal and screen, and no mutating terminal call may have + * occurred since the refs were produced or reconstructed from tracked refs. + * Passing refs from another terminal, another screen, or stale refs violates + * this precondition. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param a First selection snapshot to compare + * @param b Second selection snapshot to compare + * @param[out] out_equal On success, receives whether the selections are equal + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal, + * selections, or output pointer are invalid. Selection reference + * validity is a precondition and is not checked. + * + * @ingroup selection + */ +GHOSTTY_API GhosttyResult ghostty_terminal_selection_equal( + GhosttyTerminal terminal, + const GhosttySelection* a, + const GhosttySelection* b, + bool* out_equal); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_SELECTION_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/sgr.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/sgr.h new file mode 100644 index 0000000000..8eec11dc97 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/sgr.h @@ -0,0 +1,350 @@ +/** + * @file sgr.h + * + * SGR (Select Graphic Rendition) attribute parsing and handling. + */ + +#ifndef GHOSTTY_VT_SGR_H +#define GHOSTTY_VT_SGR_H + +/** @defgroup sgr SGR Parser + * + * SGR (Select Graphic Rendition) attribute parser. + * + * SGR sequences are the syntax used to set styling attributes such as + * bold, italic, underline, and colors for text in terminal emulators. + * For example, you may be familiar with sequences like `ESC[1;31m`. The + * `1;31` is the SGR attribute list. + * + * The parser processes SGR parameters from CSI sequences (e.g., `ESC[1;31m`) + * and returns individual text attributes like bold, italic, colors, etc. + * It supports both semicolon (`;`) and colon (`:`) separators, possibly mixed, + * and handles various color formats including 8-color, 16-color, 256-color, + * X11 named colors, and RGB in multiple formats. + * + * ## Basic Usage + * + * 1. Create a parser instance with ghostty_sgr_new() + * 2. Set SGR parameters with ghostty_sgr_set_params() + * 3. Iterate through attributes using ghostty_sgr_next() + * 4. Free the parser with ghostty_sgr_free() when done + * + * ## Example + * + * @snippet c-vt-sgr/src/main.c sgr-basic + * + * @{ + */ + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * SGR attribute tags. + * + * These values identify the type of an SGR attribute in a tagged union. + * Use the tag to determine which field in the attribute value union to access. + * + * @ingroup sgr + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_SGR_ATTR_UNSET = 0, + GHOSTTY_SGR_ATTR_UNKNOWN = 1, + GHOSTTY_SGR_ATTR_BOLD = 2, + GHOSTTY_SGR_ATTR_RESET_BOLD = 3, + GHOSTTY_SGR_ATTR_ITALIC = 4, + GHOSTTY_SGR_ATTR_RESET_ITALIC = 5, + GHOSTTY_SGR_ATTR_FAINT = 6, + GHOSTTY_SGR_ATTR_UNDERLINE = 7, + GHOSTTY_SGR_ATTR_UNDERLINE_COLOR = 8, + GHOSTTY_SGR_ATTR_UNDERLINE_COLOR_256 = 9, + GHOSTTY_SGR_ATTR_RESET_UNDERLINE_COLOR = 10, + GHOSTTY_SGR_ATTR_OVERLINE = 11, + GHOSTTY_SGR_ATTR_RESET_OVERLINE = 12, + GHOSTTY_SGR_ATTR_BLINK = 13, + GHOSTTY_SGR_ATTR_RESET_BLINK = 14, + GHOSTTY_SGR_ATTR_INVERSE = 15, + GHOSTTY_SGR_ATTR_RESET_INVERSE = 16, + GHOSTTY_SGR_ATTR_INVISIBLE = 17, + GHOSTTY_SGR_ATTR_RESET_INVISIBLE = 18, + GHOSTTY_SGR_ATTR_STRIKETHROUGH = 19, + GHOSTTY_SGR_ATTR_RESET_STRIKETHROUGH = 20, + GHOSTTY_SGR_ATTR_DIRECT_COLOR_FG = 21, + GHOSTTY_SGR_ATTR_DIRECT_COLOR_BG = 22, + GHOSTTY_SGR_ATTR_BG_8 = 23, + GHOSTTY_SGR_ATTR_FG_8 = 24, + GHOSTTY_SGR_ATTR_RESET_FG = 25, + GHOSTTY_SGR_ATTR_RESET_BG = 26, + GHOSTTY_SGR_ATTR_BRIGHT_BG_8 = 27, + GHOSTTY_SGR_ATTR_BRIGHT_FG_8 = 28, + GHOSTTY_SGR_ATTR_BG_256 = 29, + GHOSTTY_SGR_ATTR_FG_256 = 30, + GHOSTTY_SGR_ATTR_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySgrAttributeTag; + +/** + * Underline style types. + * + * @ingroup sgr + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_SGR_UNDERLINE_NONE = 0, + GHOSTTY_SGR_UNDERLINE_SINGLE = 1, + GHOSTTY_SGR_UNDERLINE_DOUBLE = 2, + GHOSTTY_SGR_UNDERLINE_CURLY = 3, + GHOSTTY_SGR_UNDERLINE_DOTTED = 4, + GHOSTTY_SGR_UNDERLINE_DASHED = 5, + GHOSTTY_SGR_UNDERLINE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySgrUnderline; + +/** + * Unknown SGR attribute data. + * + * Contains the full parameter list and the partial list where parsing + * encountered an unknown or invalid sequence. + * + * @ingroup sgr + */ +typedef struct { + const uint16_t* full_ptr; + size_t full_len; + const uint16_t* partial_ptr; + size_t partial_len; +} GhosttySgrUnknown; + +/** + * SGR attribute value union. + * + * This union contains all possible attribute values. Use the tag field + * to determine which union member is active. Attributes without associated + * data (like bold, italic) don't use the union value. + * + * @ingroup sgr + */ +typedef union { + GhosttySgrUnknown unknown; + GhosttySgrUnderline underline; + GhosttyColorRgb underline_color; + GhosttyColorPaletteIndex underline_color_256; + GhosttyColorRgb direct_color_fg; + GhosttyColorRgb direct_color_bg; + GhosttyColorPaletteIndex bg_8; + GhosttyColorPaletteIndex fg_8; + GhosttyColorPaletteIndex bright_bg_8; + GhosttyColorPaletteIndex bright_fg_8; + GhosttyColorPaletteIndex bg_256; + GhosttyColorPaletteIndex fg_256; + uint64_t _padding[8]; +} GhosttySgrAttributeValue; + +/** + * SGR attribute (tagged union). + * + * A complete SGR attribute with both its type tag and associated value. + * Always check the tag field to determine which value union member is valid. + * + * Attributes without associated data (e.g., GHOSTTY_SGR_ATTR_BOLD) can be + * identified by tag alone; the value union is not used for these and + * the memory in the value field is undefined. + * + * @ingroup sgr + */ +typedef struct { + GhosttySgrAttributeTag tag; + GhosttySgrAttributeValue value; +} GhosttySgrAttribute; + +/** + * Create a new SGR parser instance. + * + * Creates a new SGR (Select Graphic Rendition) parser using the provided + * allocator. The parser must be freed using ghostty_sgr_free() when + * no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or + * NULL to use the default allocator + * @param parser Pointer to store the created parser handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup sgr + */ +GHOSTTY_API GhosttyResult ghostty_sgr_new(const GhosttyAllocator* allocator, + GhosttySgrParser* parser); + +/** + * Free an SGR parser instance. + * + * Releases all resources associated with the SGR parser. After this call, + * the parser handle becomes invalid and must not be used. This includes + * any attributes previously returned by ghostty_sgr_next(). + * + * @param parser The parser handle to free (may be NULL) + * + * @ingroup sgr + */ +GHOSTTY_API void ghostty_sgr_free(GhosttySgrParser parser); + +/** + * Reset an SGR parser instance to the beginning of the parameter list. + * + * Resets the parser's iteration state without clearing the parameters. + * After calling this, ghostty_sgr_next() will start from the beginning + * of the parameter list again. + * + * @param parser The parser handle to reset, must not be NULL + * + * @ingroup sgr + */ +GHOSTTY_API void ghostty_sgr_reset(GhosttySgrParser parser); + +/** + * Set SGR parameters for parsing. + * + * Sets the SGR parameter list to parse. Parameters are the numeric values + * from a CSI SGR sequence (e.g., for `ESC[1;31m`, params would be {1, 31}). + * + * The separators array optionally specifies the separator type for each + * parameter position. Each byte should be either ';' for semicolon or ':' + * for colon. This is needed for certain color formats that use colon + * separators (e.g., `ESC[4:3m` for curly underline). Any invalid separator + * values are treated as semicolons. The separators array must have the same + * length as the params array, if it is not NULL. + * + * If separators is NULL, all parameters are assumed to be semicolon-separated. + * + * This function makes an internal copy of the parameter and separator data, + * so the caller can safely free or modify the input arrays after this call. + * + * After calling this function, the parser is automatically reset and ready + * to iterate from the beginning. + * + * @param parser The parser handle, must not be NULL + * @param params Array of SGR parameter values + * @param separators Optional array of separator characters (';' or ':'), or + * NULL + * @param len Number of parameters (and separators if provided) + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup sgr + */ +GHOSTTY_API GhosttyResult ghostty_sgr_set_params(GhosttySgrParser parser, + const uint16_t* params, + const char* separators, + size_t len); + +/** + * Get the next SGR attribute. + * + * Parses and returns the next attribute from the parameter list. + * Call this function repeatedly until it returns false to process + * all attributes in the sequence. + * + * @param parser The parser handle, must not be NULL + * @param attr Pointer to store the next attribute + * @return true if an attribute was returned, false if no more attributes + * + * @ingroup sgr + */ +GHOSTTY_API bool ghostty_sgr_next(GhosttySgrParser parser, GhosttySgrAttribute* attr); + +/** + * Get the full parameter list from an unknown SGR attribute. + * + * This function retrieves the full parameter list that was provided to the + * parser when an unknown attribute was encountered. Primarily useful in + * WebAssembly environments where accessing struct fields directly is difficult. + * + * @param unknown The unknown attribute data + * @param ptr Pointer to store the pointer to the parameter array (may be NULL) + * @return The length of the full parameter array + * + * @ingroup sgr + */ +GHOSTTY_API size_t ghostty_sgr_unknown_full(GhosttySgrUnknown unknown, + const uint16_t** ptr); + +/** + * Get the partial parameter list from an unknown SGR attribute. + * + * This function retrieves the partial parameter list where parsing stopped + * when an unknown attribute was encountered. Primarily useful in WebAssembly + * environments where accessing struct fields directly is difficult. + * + * @param unknown The unknown attribute data + * @param ptr Pointer to store the pointer to the parameter array (may be NULL) + * @return The length of the partial parameter array + * + * @ingroup sgr + */ +GHOSTTY_API size_t ghostty_sgr_unknown_partial(GhosttySgrUnknown unknown, + const uint16_t** ptr); + +/** + * Get the tag from an SGR attribute. + * + * This function extracts the tag that identifies which type of attribute + * this is. Primarily useful in WebAssembly environments where accessing + * struct fields directly is difficult. + * + * @param attr The SGR attribute + * @return The attribute tag + * + * @ingroup sgr + */ +GHOSTTY_API GhosttySgrAttributeTag ghostty_sgr_attribute_tag(GhosttySgrAttribute attr); + +/** + * Get the value from an SGR attribute. + * + * This function returns a pointer to the value union from an SGR attribute. Use + * the tag to determine which field of the union is valid. Primarily useful in + * WebAssembly environments where accessing struct fields directly is difficult. + * + * @param attr Pointer to the SGR attribute + * @return Pointer to the attribute value union + * + * @ingroup sgr + */ +GHOSTTY_API GhosttySgrAttributeValue* ghostty_sgr_attribute_value( + GhosttySgrAttribute* attr); + +#ifdef __wasm__ +/** + * Allocate memory for an SGR attribute (WebAssembly only). + * + * This is a convenience function for WebAssembly environments to allocate + * memory for an SGR attribute structure that can be passed to ghostty_sgr_next. + * + * @return Pointer to the allocated attribute structure + * + * @ingroup wasm + */ +GHOSTTY_API GhosttySgrAttribute* ghostty_wasm_alloc_sgr_attribute(void); + +/** + * Free memory for an SGR attribute (WebAssembly only). + * + * Frees memory allocated by ghostty_wasm_alloc_sgr_attribute. + * + * @param attr Pointer to the attribute structure to free + * + * @ingroup wasm + */ +GHOSTTY_API void ghostty_wasm_free_sgr_attribute(GhosttySgrAttribute* attr); +#endif + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_SGR_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/size_report.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/size_report.h new file mode 100644 index 0000000000..da33e5e559 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/size_report.h @@ -0,0 +1,101 @@ +/** + * @file size_report.h + * + * Size report encoding - encode terminal size reports into escape sequences. + */ + +#ifndef GHOSTTY_VT_SIZE_REPORT_H +#define GHOSTTY_VT_SIZE_REPORT_H + +/** @defgroup size_report Size Report Encoding + * + * Utilities for encoding terminal size reports into escape sequences, + * supporting in-band size reports (mode 2048) and XTWINOPS responses + * (CSI 14 t, CSI 16 t, CSI 18 t). + * + * ## Basic Usage + * + * Use ghostty_size_report_encode() to encode a size report into a + * caller-provided buffer. If the buffer is too small, the function + * returns GHOSTTY_OUT_OF_SPACE and sets the required size in the + * output parameter. + * + * ## Example + * + * @snippet c-vt-size-report/src/main.c size-report-encode + * + * @{ + */ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Size report style. + * + * Determines the output format for the terminal size report. + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** In-band size report (mode 2048): ESC [ 48 ; rows ; cols ; height ; width t */ + GHOSTTY_SIZE_REPORT_MODE_2048 = 0, + /** XTWINOPS text area size in pixels: ESC [ 4 ; height ; width t */ + GHOSTTY_SIZE_REPORT_CSI_14_T = 1, + /** XTWINOPS cell size in pixels: ESC [ 6 ; height ; width t */ + GHOSTTY_SIZE_REPORT_CSI_16_T = 2, + /** XTWINOPS text area size in characters: ESC [ 8 ; rows ; cols t */ + GHOSTTY_SIZE_REPORT_CSI_18_T = 3, + GHOSTTY_SIZE_REPORT_STYLE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySizeReportStyle; + +/** + * Terminal size information for encoding size reports. + */ +typedef struct { + /** Terminal row count in cells. */ + uint16_t rows; + /** Terminal column count in cells. */ + uint16_t columns; + /** Width of a single terminal cell in pixels. */ + uint32_t cell_width; + /** Height of a single terminal cell in pixels. */ + uint32_t cell_height; +} GhosttySizeReportSize; + +/** + * Encode a terminal size report into an escape sequence. + * + * Encodes a size report in the format specified by @p style into the + * provided buffer. + * + * If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE + * and writes the required buffer size to @p out_written. The caller can + * then retry with a sufficiently sized buffer. + * + * @param style The size report format to encode + * @param size Terminal size information + * @param buf Output buffer to write the encoded sequence into (may be NULL) + * @param buf_len Size of the output buffer in bytes + * @param[out] out_written On success, the number of bytes written. On + * GHOSTTY_OUT_OF_SPACE, the required buffer size. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer + * is too small + */ +GHOSTTY_API GhosttyResult ghostty_size_report_encode( + GhosttySizeReportStyle style, + GhosttySizeReportSize size, + char* buf, + size_t buf_len, + size_t* out_written); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_SIZE_REPORT_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/style.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/style.h new file mode 100644 index 0000000000..b6bf860ebe --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/style.h @@ -0,0 +1,139 @@ +/** + * @file style.h + * + * Terminal cell style types. + */ + +#ifndef GHOSTTY_VT_STYLE_H +#define GHOSTTY_VT_STYLE_H + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup style Style + * + * Terminal cell style attributes. + * + * A style describes the visual attributes of a terminal cell, including + * foreground, background, and underline colors, as well as flags for + * bold, italic, underline, and other text decorations. + * + * @{ + */ + +/** + * Style identifier type. + * + * Used to look up the full style from a grid reference. + * Obtain this from a cell via GHOSTTY_CELL_DATA_STYLE_ID. + * + * @ingroup style + */ +typedef uint16_t GhosttyStyleId; + +/** + * Style color tags. + * + * These values identify the type of color in a style color. + * Use the tag to determine which field in the color value union to access. + * + * @ingroup style + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_STYLE_COLOR_NONE = 0, + GHOSTTY_STYLE_COLOR_PALETTE = 1, + GHOSTTY_STYLE_COLOR_RGB = 2, + GHOSTTY_STYLE_COLOR_TAG_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, + } GhosttyStyleColorTag; + +/** + * Style color value union. + * + * Use the tag to determine which field is active. + * + * @ingroup style + */ +typedef union { + GhosttyColorPaletteIndex palette; + GhosttyColorRgb rgb; + uint64_t _padding; +} GhosttyStyleColorValue; + +/** + * Style color (tagged union). + * + * A color used in a style attribute. Can be unset (none), a palette + * index, or a direct RGB value. + * + * @ingroup style + */ +typedef struct { + GhosttyStyleColorTag tag; + GhosttyStyleColorValue value; +} GhosttyStyleColor; + +/** + * Terminal cell style. + * + * Describes the complete visual style for a terminal cell, including + * foreground, background, and underline colors, as well as text + * decoration flags. The underline field uses the same values as + * GhosttySgrUnderline. + * + * This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it. + * + * @ingroup style + */ +typedef struct { + size_t size; + GhosttyStyleColor fg_color; + GhosttyStyleColor bg_color; + GhosttyStyleColor underline_color; + bool bold; + bool italic; + bool faint; + bool blink; + bool inverse; + bool invisible; + bool strikethrough; + bool overline; + int underline; /**< One of GHOSTTY_SGR_UNDERLINE_* values */ +} GhosttyStyle; + +/** + * Get the default style. + * + * Initializes the style to the default values (no colors, no flags). + * + * @param style Pointer to the style to initialize + * + * @ingroup style + */ +GHOSTTY_API void ghostty_style_default(GhosttyStyle* style); + +/** + * Check if a style is the default style. + * + * Returns true if all colors are unset and all flags are off. + * + * @param style Pointer to the style to check + * @return true if the style is the default style + * + * @ingroup style + */ +GHOSTTY_API bool ghostty_style_is_default(const GhosttyStyle* style); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_STYLE_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/sys.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/sys.h new file mode 100644 index 0000000000..ae90596927 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/sys.h @@ -0,0 +1,210 @@ +/** + * @file sys.h + * + * System interface - runtime-swappable implementations for external dependencies. + */ + +#ifndef GHOSTTY_VT_SYS_H +#define GHOSTTY_VT_SYS_H + +#include +#include +#include +#include +#include + +/** @defgroup sys System Interface + * + * Runtime-swappable function pointers for operations that depend on + * external implementations (e.g. image decoding). + * + * These are process-global settings that must be configured at startup + * before any terminal functionality that depends on them is used. + * Setting these enables various optional features of the terminal. For + * example, setting a PNG decoder enables PNG image support in the Kitty + * Graphics Protocol. + * + * Use ghostty_sys_set() with a `GhosttySysOption` to install or clear + * an implementation. Passing NULL as the value clears the implementation + * and disables the corresponding feature. + * + * ## Example + * + * ### Defining a PNG decode callback + * @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-decode-png + * + * ### Installing the callback and sending a PNG image + * @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-main + * + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Result of decoding an image. + * + * The `data` buffer must be allocated through the allocator provided to + * the decode callback. The library takes ownership and will free it + * with the same allocator. + */ +typedef struct { + /** Image width in pixels. */ + uint32_t width; + + /** Image height in pixels. */ + uint32_t height; + + /** Pointer to the decoded RGBA pixel data. */ + uint8_t* data; + + /** Length of the pixel data in bytes. */ + size_t data_len; +} GhosttySysImage; + +/** + * Log severity levels for the log callback. + */ +typedef enum GHOSTTY_ENUM_TYPED { + GHOSTTY_SYS_LOG_LEVEL_ERROR = 0, + GHOSTTY_SYS_LOG_LEVEL_WARNING = 1, + GHOSTTY_SYS_LOG_LEVEL_INFO = 2, + GHOSTTY_SYS_LOG_LEVEL_DEBUG = 3, + GHOSTTY_SYS_LOG_LEVEL_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySysLogLevel; + +/** + * Callback type for logging. + * + * When installed, internal library log messages are delivered through + * this callback instead of being discarded. The embedder is responsible + * for formatting and routing log output. + * + * @p scope is the log scope name as UTF-8 bytes (e.g. "osc", "kitty"). + * When the log is unscoped (default scope), @p scope_len is 0. + * + * All pointer arguments are only valid for the duration of the callback. + * The callback must be safe to call from any thread. + * + * @param userdata The userdata pointer set via GHOSTTY_SYS_OPT_USERDATA + * @param level The severity level of the log message + * @param scope Pointer to the scope name bytes + * @param scope_len Length of the scope name in bytes + * @param message Pointer to the log message bytes + * @param message_len Length of the log message in bytes + */ +typedef void (*GhosttySysLogFn)( + void* userdata, + GhosttySysLogLevel level, + const uint8_t* scope, + size_t scope_len, + const uint8_t* message, + size_t message_len); + +/** + * Callback type for PNG decoding. + * + * Decodes raw PNG data into RGBA pixels. The output pixel data must be + * allocated through the provided allocator. The library takes ownership + * of the buffer and will free it with the same allocator. + * + * @param userdata The userdata pointer set via GHOSTTY_SYS_OPT_USERDATA + * @param allocator The allocator to use for the output pixel buffer + * @param data Pointer to the raw PNG data + * @param data_len Length of the raw PNG data in bytes + * @param[out] out On success, filled with the decoded image + * @return true on success, false on failure + */ +typedef bool (*GhosttySysDecodePngFn)( + void* userdata, + const GhosttyAllocator* allocator, + const uint8_t* data, + size_t data_len, + GhosttySysImage* out); + +/** + * System option identifiers for ghostty_sys_set(). + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** + * Set the userdata pointer passed to all sys callbacks. + * + * Input type: void* (or NULL) + */ + GHOSTTY_SYS_OPT_USERDATA = 0, + + /** + * Set the PNG decode function. + * + * When set, the terminal can accept PNG images via the Kitty + * Graphics Protocol. When cleared (NULL value), PNG decoding is + * unsupported and PNG image data will be rejected. + * + * Input type: GhosttySysDecodePngFn (function pointer, or NULL) + */ + GHOSTTY_SYS_OPT_DECODE_PNG = 1, + + /** + * Set the log callback. + * + * When set, internal library log messages are delivered to this + * callback. When cleared (NULL value), log messages are silently + * discarded. + * + * Use ghostty_sys_log_stderr as a convenience callback that + * writes formatted messages to stderr. + * + * Which log levels are emitted depends on the build mode of the + * library and is not configurable at runtime. Debug builds emit + * all levels (debug and above). Release builds emit info and + * above; debug-level messages are compiled out entirely and will + * never reach the callback. + * + * Input type: GhosttySysLogFn (function pointer, or NULL) + */ + GHOSTTY_SYS_OPT_LOG = 2, + GHOSTTY_SYS_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttySysOption; + +/** + * Set a system-level option. + * + * Configures a process-global implementation function. These should be + * set once at startup before using any terminal functionality that + * depends on them. + * + * @param option The option to set + * @param value Pointer to the value (type depends on the option), + * or NULL to clear it + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the + * option is not recognized + */ +GHOSTTY_API GhosttyResult ghostty_sys_set(GhosttySysOption option, + const void* value); + +/** + * Built-in log callback that writes to stderr. + * + * Formats each message as "[level](scope): message\n". + * Can be passed directly to ghostty_sys_set(): + * + * @code + * ghostty_sys_set(GHOSTTY_SYS_OPT_LOG, &ghostty_sys_log_stderr); + * @endcode + */ +GHOSTTY_API void ghostty_sys_log_stderr(void* userdata, + GhosttySysLogLevel level, + const uint8_t* scope, + size_t scope_len, + const uint8_t* message, + size_t message_len); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_SYS_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/terminal.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/terminal.h new file mode 100644 index 0000000000..b22e8aedc8 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/terminal.h @@ -0,0 +1,1322 @@ +/** + * @file terminal.h + * + * Complete terminal emulator state and rendering. + */ + +#ifndef GHOSTTY_VT_TERMINAL_H +#define GHOSTTY_VT_TERMINAL_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup terminal Terminal + * + * Complete terminal emulator state and rendering. + * + * A terminal instance manages the full emulator state including the screen, + * scrollback, cursor, styles, modes, and VT stream processing. + * + * Once a terminal session is up and running, you can configure a key encoder + * to write keyboard input via ghostty_key_encoder_setopt_from_terminal(). + * + * ### Example: VT stream processing + * @snippet c-vt-stream/src/main.c vt-stream-init + * @snippet c-vt-stream/src/main.c vt-stream-write + * + * ## Effects + * + * By default, the terminal sequence processing with ghostty_terminal_vt_write() + * only process sequences that directly affect terminal state and + * ignores sequences that have side effect behavior or require responses. + * These sequences include things like bell characters, title changes, device + * attributes queries, and more. To handle these sequences, the embedder + * must configure "effects." + * + * Effects are callbacks that the terminal invokes in response to VT + * sequences processed during ghostty_terminal_vt_write(). They let the + * embedding application react to terminal-initiated events such as bell + * characters, title changes, device status report responses, and more. + * + * Each effect is registered with ghostty_terminal_set() using the + * corresponding `GhosttyTerminalOption` identifier. A `NULL` value + * pointer clears the callback and disables the effect. + * + * A userdata pointer can be attached via `GHOSTTY_TERMINAL_OPT_USERDATA` + * and is passed to every callback, allowing callers to route events + * back to their own application state without global variables. + * You cannot specify different userdata for different callbacks. + * + * All callbacks are invoked synchronously during + * ghostty_terminal_vt_write(). Callbacks **must not** call + * ghostty_terminal_vt_write() on the same terminal (no reentrancy). + * And callbacks must be very careful to not block for too long or perform + * expensive operations, since they are blocking further IO processing. + * + * The available effects are: + * + * | Option | Callback Type | Trigger | + * |-----------------------------------------|-----------------------------------|-------------------------------------------| + * | `GHOSTTY_TERMINAL_OPT_WRITE_PTY` | `GhosttyTerminalWritePtyFn` | Query responses written back to the pty | + * | `GHOSTTY_TERMINAL_OPT_BELL` | `GhosttyTerminalBellFn` | BEL character (0x07) | + * | `GHOSTTY_TERMINAL_OPT_TITLE_CHANGED` | `GhosttyTerminalTitleChangedFn` | Title change via OSC 0 / OSC 2 | + * | `GHOSTTY_TERMINAL_OPT_PWD_CHANGED` | `GhosttyTerminalPwdChangedFn` | Pwd change via OSC 7 / OSC 9 / OSC 1337 | + * | `GHOSTTY_TERMINAL_OPT_ENQUIRY` | `GhosttyTerminalEnquiryFn` | ENQ character (0x05) | + * | `GHOSTTY_TERMINAL_OPT_XTVERSION` | `GhosttyTerminalXtversionFn` | XTVERSION query (CSI > q) | + * | `GHOSTTY_TERMINAL_OPT_SIZE` | `GhosttyTerminalSizeFn` | XTWINOPS size query (CSI 14/16/18 t) | + * | `GHOSTTY_TERMINAL_OPT_COLOR_SCHEME` | `GhosttyTerminalColorSchemeFn` | Color scheme query (CSI ? 996 n) | + * | `GHOSTTY_TERMINAL_OPT_DEVICE_ATTRIBUTES`| `GhosttyTerminalDeviceAttributesFn`| Device attributes query (CSI c / > c / = c)| + * + * ### Defining a write_pty callback + * @snippet c-vt-effects/src/main.c effects-write-pty + * + * ### Defining a bell callback + * @snippet c-vt-effects/src/main.c effects-bell + * + * ### Defining a title_changed callback + * @snippet c-vt-effects/src/main.c effects-title-changed + * + * ### Registering effects and processing VT data + * @snippet c-vt-effects/src/main.c effects-register + * + * ## Color Theme + * + * The terminal maintains a set of colors used for rendering: a foreground + * color, a background color, a cursor color, and a 256-color palette. Each + * of these has two layers: a **default** value set by the embedder, and an + * **override** value that programs running in the terminal can set via OSC + * escape sequences (e.g. OSC 10/11/12 for foreground/background/cursor, + * OSC 4 for individual palette entries). + * + * ### Default Colors + * + * Use ghostty_terminal_set() with the color options to configure the + * default colors. These represent the theme or configuration chosen by + * the embedder. Passing `NULL` clears the default, leaving the color + * unset. + * + * | Option | Input Type | Description | + * |-----------------------------------------|-------------------------|--------------------------------------| + * | `GHOSTTY_TERMINAL_OPT_COLOR_FOREGROUND` | `GhosttyColorRgb*` | Default foreground color | + * | `GHOSTTY_TERMINAL_OPT_COLOR_BACKGROUND` | `GhosttyColorRgb*` | Default background color | + * | `GHOSTTY_TERMINAL_OPT_COLOR_CURSOR` | `GhosttyColorRgb*` | Default cursor color | + * | `GHOSTTY_TERMINAL_OPT_COLOR_PALETTE` | `GhosttyColorRgb[256]*` | Default 256-color palette | + * + * For the palette, passing `NULL` resets to the built-in default palette. + * The palette set operation preserves any per-index OSC overrides that + * programs have applied; only unmodified indices are updated. + * + * ### Reading colors + * + * Use ghostty_terminal_get() to read colors. There are two variants for + * each color: the **effective** value (which returns the OSC override if + * one is active, otherwise the default) and the **default** value (which + * ignores any OSC overrides). + * + * | Data | Output Type | Description | + * |---------------------------------------------------|-------------------------|------------------------------------------------| + * | `GHOSTTY_TERMINAL_DATA_COLOR_FOREGROUND` | `GhosttyColorRgb*` | Effective foreground (override or default) | + * | `GHOSTTY_TERMINAL_DATA_COLOR_BACKGROUND` | `GhosttyColorRgb*` | Effective background (override or default) | + * | `GHOSTTY_TERMINAL_DATA_COLOR_CURSOR` | `GhosttyColorRgb*` | Effective cursor (override or default) | + * | `GHOSTTY_TERMINAL_DATA_COLOR_PALETTE` | `GhosttyColorRgb[256]*` | Current palette (with any OSC overrides) | + * | `GHOSTTY_TERMINAL_DATA_COLOR_FOREGROUND_DEFAULT` | `GhosttyColorRgb*` | Default foreground only (ignores OSC override) | + * | `GHOSTTY_TERMINAL_DATA_COLOR_BACKGROUND_DEFAULT` | `GhosttyColorRgb*` | Default background only (ignores OSC override) | + * | `GHOSTTY_TERMINAL_DATA_COLOR_CURSOR_DEFAULT` | `GhosttyColorRgb*` | Default cursor only (ignores OSC override) | + * | `GHOSTTY_TERMINAL_DATA_COLOR_PALETTE_DEFAULT` | `GhosttyColorRgb[256]*` | Default palette only (ignores OSC overrides) | + * + * For foreground, background, and cursor colors, the getters return + * `GHOSTTY_NO_VALUE` if no color is configured (neither a default nor an + * OSC override). The palette getters always succeed since the palette + * always has a value (the built-in default if nothing else is set). + * + * ### Setting a color theme + * @snippet c-vt-colors/src/main.c colors-set-defaults + * + * ### Reading effective and default colors + * @snippet c-vt-colors/src/main.c colors-read + * + * ### Full example with OSC overrides + * @snippet c-vt-colors/src/main.c colors-main + * + * @{ + */ + +/** + * Terminal initialization options. + * + * @ingroup terminal + */ +typedef struct { + /** Terminal width in cells. Must be greater than zero. */ + uint16_t cols; + + /** Terminal height in cells. Must be greater than zero. */ + uint16_t rows; + + /** Maximum number of lines to keep in scrollback history. */ + size_t max_scrollback; + + // TODO: Consider ABI compatibility implications of this struct. + // We may want to artificially pad it significantly to support + // future options. +} GhosttyTerminalOptions; + +/** + * Scroll viewport behavior tag. + * + * @ingroup terminal + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Scroll to the top of the scrollback. */ + GHOSTTY_SCROLL_VIEWPORT_TOP, + + /** Scroll to the bottom (active area). */ + GHOSTTY_SCROLL_VIEWPORT_BOTTOM, + + /** Scroll by a delta amount (up is negative). */ + GHOSTTY_SCROLL_VIEWPORT_DELTA, + GHOSTTY_SCROLL_VIEWPORT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyTerminalScrollViewportTag; + +/** + * Scroll viewport value. + * + * @ingroup terminal + */ +typedef union { + /** Scroll delta (only used with GHOSTTY_SCROLL_VIEWPORT_DELTA). Up is negative. */ + intptr_t delta; + + /** Padding for ABI compatibility. Do not use. */ + uint64_t _padding[2]; +} GhosttyTerminalScrollViewportValue; + +/** + * Tagged union for scroll viewport behavior. + * + * @ingroup terminal + */ +typedef struct { + GhosttyTerminalScrollViewportTag tag; + GhosttyTerminalScrollViewportValue value; +} GhosttyTerminalScrollViewport; + +/** + * Terminal screen identifier. + * + * Identifies which screen buffer is active in the terminal. + * + * @ingroup terminal + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** The primary (normal) screen. */ + GHOSTTY_TERMINAL_SCREEN_PRIMARY = 0, + + /** The alternate screen. */ + GHOSTTY_TERMINAL_SCREEN_ALTERNATE = 1, + GHOSTTY_TERMINAL_SCREEN_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyTerminalScreen; + +/** + * Visual style of the terminal cursor. + * + * @ingroup terminal + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Bar cursor (DECSCUSR 5, 6). */ + GHOSTTY_TERMINAL_CURSOR_STYLE_BAR = 0, + + /** Block cursor (DECSCUSR 1, 2). */ + GHOSTTY_TERMINAL_CURSOR_STYLE_BLOCK = 1, + + /** Underline cursor (DECSCUSR 3, 4). */ + GHOSTTY_TERMINAL_CURSOR_STYLE_UNDERLINE = 2, + + /** Hollow block cursor. */ + GHOSTTY_TERMINAL_CURSOR_STYLE_BLOCK_HOLLOW = 3, + GHOSTTY_TERMINAL_CURSOR_STYLE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyTerminalCursorStyle; + +/** + * Scrollbar state for the terminal viewport. + * + * Represents the scrollable area dimensions needed to render a scrollbar. + * + * @ingroup terminal + */ +typedef struct { + /** Total size of the scrollable area in rows. */ + uint64_t total; + + /** Offset into the total area that the viewport is at. */ + uint64_t offset; + + /** Length of the visible area in rows. */ + uint64_t len; +} GhosttyTerminalScrollbar; + +/** + * Callback function type for bell. + * + * Called when the terminal receives a BEL character (0x07). + * + * @param terminal The terminal handle + * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA + * + * @ingroup terminal + */ +typedef void (*GhosttyTerminalBellFn)(GhosttyTerminal terminal, + void* userdata); + +/** + * Callback function type for color scheme queries (CSI ? 996 n). + * + * Called when the terminal receives a color scheme device status report + * query. Return true and fill *out_scheme with the current color scheme, + * or return false to silently ignore the query. + * + * @param terminal The terminal handle + * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA + * @param[out] out_scheme Pointer to store the current color scheme + * @return true if the color scheme was filled, false to ignore the query + * + * @ingroup terminal + */ +typedef bool (*GhosttyTerminalColorSchemeFn)(GhosttyTerminal terminal, + void* userdata, + GhosttyColorScheme* out_scheme); + +/** + * Callback function type for device attributes queries (DA1/DA2/DA3). + * + * Called when the terminal receives a device attributes query (CSI c, + * CSI > c, or CSI = c). Return true and fill *out_attrs with the + * response data, or return false to silently ignore the query. + * + * The terminal uses whichever sub-struct (primary, secondary, tertiary) + * matches the request type, but all three should be filled for simplicity. + * + * @param terminal The terminal handle + * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA + * @param[out] out_attrs Pointer to store the device attributes response + * @return true if attributes were filled, false to ignore the query + * + * @ingroup terminal + */ +typedef bool (*GhosttyTerminalDeviceAttributesFn)(GhosttyTerminal terminal, + void* userdata, + GhosttyDeviceAttributes* out_attrs); + +/** + * Callback function type for enquiry (ENQ, 0x05). + * + * Called when the terminal receives an ENQ character. Return the + * response bytes as a GhosttyString. The memory must remain valid + * until the callback returns. Return a zero-length string to send + * no response. + * + * @param terminal The terminal handle + * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA + * @return The response bytes to write back to the pty + * + * @ingroup terminal + */ +typedef GhosttyString (*GhosttyTerminalEnquiryFn)(GhosttyTerminal terminal, + void* userdata); + +/** + * Callback function type for size queries (XTWINOPS). + * + * Called in response to XTWINOPS size queries (CSI 14/16/18 t). + * Return true and fill *out_size with the current terminal geometry, + * or return false to silently ignore the query. + * + * @param terminal The terminal handle + * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA + * @param[out] out_size Pointer to store the terminal size information + * @return true if size was filled, false to ignore the query + * + * @ingroup terminal + */ +typedef bool (*GhosttyTerminalSizeFn)(GhosttyTerminal terminal, + void* userdata, + GhosttySizeReportSize* out_size); + +/** + * Callback function type for title_changed. + * + * Called when the terminal title changes via escape sequences + * (e.g. OSC 0 or OSC 2). The new title can be queried from the + * terminal after the callback returns. + * + * @param terminal The terminal handle + * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA + * + * @ingroup terminal + */ +typedef void (*GhosttyTerminalTitleChangedFn)(GhosttyTerminal terminal, + void* userdata); + +/** + * Callback function type for pwd_changed. + * + * Called when the terminal pwd (current working directory) changes via + * escape sequences: OSC 7 (file:// URI), OSC 9 (ConEmu CurrentDir), or + * OSC 1337 CurrentDir (iTerm2). Use ghostty_terminal_get() with + * GHOSTTY_TERMINAL_DATA_PWD inside the callback to read the new value. + * + * The terminal stores whatever bytes the shell emitted, without parsing. + * That means for OSC 7 the value is the raw URI (typically file://...); + * for OSC 9/OSC 1337 it is typically a bare path. The embedder is + * responsible for decoding any URI scheme or host if it cares about them. + * + * The callback also fires when the shell clears the pwd (e.g. an empty + * OSC 7). In that case GHOSTTY_TERMINAL_DATA_PWD returns a zero-length + * string. + * + * @param terminal The terminal handle + * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA + * + * @ingroup terminal + */ +typedef void (*GhosttyTerminalPwdChangedFn)(GhosttyTerminal terminal, + void* userdata); + +/** + * Callback function type for write_pty. + * + * Called when the terminal needs to write data back to the pty, for + * example in response to a device status report or mode query. The + * data is only valid for the duration of the call; callers must copy + * it if it needs to persist. + * + * @param terminal The terminal handle + * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA + * @param data Pointer to the response bytes + * @param len Length of the response in bytes + * + * @ingroup terminal + */ +typedef void (*GhosttyTerminalWritePtyFn)(GhosttyTerminal terminal, + void* userdata, + const uint8_t* data, + size_t len); + +/** + * Callback function type for XTVERSION. + * + * Called when the terminal receives an XTVERSION query (CSI > q). + * Return the version string (e.g. "myterm 1.0") as a GhosttyString. + * The memory must remain valid until the callback returns. Return a + * zero-length string to report the default "libghostty" version. + * + * @param terminal The terminal handle + * @param userdata The userdata pointer set via GHOSTTY_TERMINAL_OPT_USERDATA + * @return The version string to report + * + * @ingroup terminal + */ +typedef GhosttyString (*GhosttyTerminalXtversionFn)(GhosttyTerminal terminal, + void* userdata); + +/** + * Terminal option identifiers. + * + * These values are used with ghostty_terminal_set() to configure + * terminal callbacks and associated state. + * + * @ingroup terminal + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** + * Opaque userdata pointer passed to all callbacks. + * + * Input type: void* + */ + GHOSTTY_TERMINAL_OPT_USERDATA = 0, + + /** + * Callback invoked when the terminal needs to write data back + * to the pty (e.g. in response to a DECRQM query or device + * status report). Set to NULL to ignore such sequences. + * + * Input type: GhosttyTerminalWritePtyFn + */ + GHOSTTY_TERMINAL_OPT_WRITE_PTY = 1, + + /** + * Callback invoked when the terminal receives a BEL character + * (0x07). Set to NULL to ignore bell events. + * + * Input type: GhosttyTerminalBellFn + */ + GHOSTTY_TERMINAL_OPT_BELL = 2, + + /** + * Callback invoked when the terminal receives an ENQ character + * (0x05). Set to NULL to send no response. + * + * Input type: GhosttyTerminalEnquiryFn + */ + GHOSTTY_TERMINAL_OPT_ENQUIRY = 3, + + /** + * Callback invoked when the terminal receives an XTVERSION query + * (CSI > q). Set to NULL to report the default "libghostty" string. + * + * Input type: GhosttyTerminalXtversionFn + */ + GHOSTTY_TERMINAL_OPT_XTVERSION = 4, + + /** + * Callback invoked when the terminal title changes via escape + * sequences (e.g. OSC 0 or OSC 2). Set to NULL to ignore title + * change events. + * + * Input type: GhosttyTerminalTitleChangedFn + */ + GHOSTTY_TERMINAL_OPT_TITLE_CHANGED = 5, + + /** + * Callback invoked in response to XTWINOPS size queries + * (CSI 14/16/18 t). Set to NULL to silently ignore size queries. + * + * Input type: GhosttyTerminalSizeFn + */ + GHOSTTY_TERMINAL_OPT_SIZE = 6, + + /** + * Callback invoked in response to a color scheme device status + * report query (CSI ? 996 n). Return true and fill the out pointer + * to report the current scheme, or return false to silently ignore. + * Set to NULL to ignore color scheme queries. + * + * Input type: GhosttyTerminalColorSchemeFn + */ + GHOSTTY_TERMINAL_OPT_COLOR_SCHEME = 7, + + /** + * Callback invoked in response to a device attributes query + * (CSI c, CSI > c, or CSI = c). Return true and fill the out + * pointer with response data, or return false to silently ignore. + * Set to NULL to ignore device attributes queries. + * + * Input type: GhosttyTerminalDeviceAttributesFn + */ + GHOSTTY_TERMINAL_OPT_DEVICE_ATTRIBUTES = 8, + + /** + * Set the terminal title manually. + * + * The string data is copied into the terminal. A NULL value pointer + * clears the title (equivalent to setting an empty string). + * + * Input type: GhosttyString* + */ + GHOSTTY_TERMINAL_OPT_TITLE = 9, + + /** + * Set the terminal working directory manually. + * + * The string data is copied into the terminal. A NULL value pointer + * clears the pwd (equivalent to setting an empty string). + * + * Input type: GhosttyString* + */ + GHOSTTY_TERMINAL_OPT_PWD = 10, + + /** + * Set the default foreground color. + * + * A NULL value pointer clears the default (unset). + * + * Input type: GhosttyColorRgb* + */ + GHOSTTY_TERMINAL_OPT_COLOR_FOREGROUND = 11, + + /** + * Set the default background color. + * + * A NULL value pointer clears the default (unset). + * + * Input type: GhosttyColorRgb* + */ + GHOSTTY_TERMINAL_OPT_COLOR_BACKGROUND = 12, + + /** + * Set the default cursor color. + * + * A NULL value pointer clears the default (unset). + * + * Input type: GhosttyColorRgb* + */ + GHOSTTY_TERMINAL_OPT_COLOR_CURSOR = 13, + + /** + * Set the default 256-color palette. + * + * The value must point to an array of exactly 256 GhosttyColorRgb values. + * A NULL value pointer resets to the built-in default palette. + * + * Input type: GhosttyColorRgb[256]* + */ + GHOSTTY_TERMINAL_OPT_COLOR_PALETTE = 14, + + /** + * Set the Kitty image storage limit in bytes. + * + * Applied to all initialized screens (primary and alternate). + * A value of zero disables the Kitty graphics protocol entirely, + * deleting all stored images and placements. A NULL value pointer + * is equivalent to zero (disables). Has no effect when Kitty graphics + * are disabled at build time. + * + * Input type: uint64_t* + */ + GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_STORAGE_LIMIT = 15, + + /** + * Enable or disable Kitty image loading via the file medium. + * + * A NULL value pointer is a no-op. Has no effect when Kitty graphics + * are disabled at build time. + * + * Input type: bool* + */ + GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_MEDIUM_FILE = 16, + + /** + * Enable or disable Kitty image loading via the temporary file medium. + * + * A NULL value pointer is a no-op. Has no effect when Kitty graphics + * are disabled at build time. + * + * Input type: bool* + */ + GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_MEDIUM_TEMP_FILE = 17, + + /** + * Enable or disable Kitty image loading via the shared memory medium. + * + * A NULL value pointer is a no-op. Has no effect when Kitty graphics + * are disabled at build time. + * + * Input type: bool* + */ + GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_MEDIUM_SHARED_MEM = 18, + + /** + * Set the maximum bytes the APC handler will buffer for all protocols. + * This prevents malicious input from causing unbounded memory allocation. + * A NULL value pointer removes all overrides, reverting to the built-in + * defaults. + * + * Input type: size_t* + */ + GHOSTTY_TERMINAL_OPT_APC_MAX_BYTES = 19, + + /** + * Set the maximum bytes the APC handler will buffer for Kitty graphics + * protocol data. A NULL value pointer removes the override, reverting + * to the built-in default. + * + * Input type: size_t* + */ + GHOSTTY_TERMINAL_OPT_APC_MAX_BYTES_KITTY = 20, + + /** + * Set the active screen selection. + * + * The value must point to a GhosttySelection whose grid references are + * valid for this terminal's active screen at the time of the call. The + * terminal copies the selection immediately and converts it to + * terminal-owned tracked state, so the GhosttySelection struct and its + * untracked grid references do not need to outlive this call. + * + * Passing NULL clears the active screen selection. + * + * Input type: GhosttySelection* + */ + GHOSTTY_TERMINAL_OPT_SELECTION = 21, + + /** + * Set the default cursor style used by DECSCUSR reset (CSI 0 q). + * + * A NULL value pointer resets to the built-in default block cursor. + * + * Input type: GhosttyTerminalCursorStyle* + */ + GHOSTTY_TERMINAL_OPT_DEFAULT_CURSOR_STYLE = 22, + + /** + * Set whether the default cursor should blink when reset by DECSCUSR + * (CSI 0 q). + * + * A NULL value pointer resets to the built-in default of not blinking. + * + * Input type: bool* + */ + GHOSTTY_TERMINAL_OPT_DEFAULT_CURSOR_BLINK = 23, + + /** + * Enable or disable Glyph Protocol APC handling. + * + * When disabled, Glyph Protocol APC sequences are ignored and no + * support/query/register/clear responses are emitted. Disabling also clears + * the terminal session's glyph glossary. A NULL value pointer is a no-op. + * + * Input type: bool* + */ + GHOSTTY_TERMINAL_OPT_GLYPH_PROTOCOL = 24, + + /** + * Callback invoked when the terminal pwd changes via escape + * sequences (OSC 7, OSC 9, or OSC 1337 CurrentDir). Set to NULL + * to ignore pwd change events. + * + * Input type: GhosttyTerminalPwdChangedFn + */ + GHOSTTY_TERMINAL_OPT_PWD_CHANGED = 25, + GHOSTTY_TERMINAL_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyTerminalOption; + +/** + * Terminal data types. + * + * These values specify what type of data to extract from a terminal + * using `ghostty_terminal_get`. + * + * @ingroup terminal + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Invalid data type. Never results in any data extraction. */ + GHOSTTY_TERMINAL_DATA_INVALID = 0, + + /** + * Terminal width in cells. + * + * Output type: uint16_t * + */ + GHOSTTY_TERMINAL_DATA_COLS = 1, + + /** + * Terminal height in cells. + * + * Output type: uint16_t * + */ + GHOSTTY_TERMINAL_DATA_ROWS = 2, + + /** + * Cursor column position (0-indexed). + * + * Output type: uint16_t * + */ + GHOSTTY_TERMINAL_DATA_CURSOR_X = 3, + + /** + * Cursor row position within the active area (0-indexed). + * + * Output type: uint16_t * + */ + GHOSTTY_TERMINAL_DATA_CURSOR_Y = 4, + + /** + * Whether the cursor has a pending wrap (next print will soft-wrap). + * + * Output type: bool * + */ + GHOSTTY_TERMINAL_DATA_CURSOR_PENDING_WRAP = 5, + + /** + * The currently active screen. + * + * Output type: GhosttyTerminalScreen * + */ + GHOSTTY_TERMINAL_DATA_ACTIVE_SCREEN = 6, + + /** + * Whether the cursor is visible (DEC mode 25). + * + * Output type: bool * + */ + GHOSTTY_TERMINAL_DATA_CURSOR_VISIBLE = 7, + + /** + * Current Kitty keyboard protocol flags. + * + * Output type: GhosttyKittyKeyFlags * (uint8_t *) + */ + GHOSTTY_TERMINAL_DATA_KITTY_KEYBOARD_FLAGS = 8, + + /** + * Scrollbar state for the terminal viewport. + * + * This may be expensive to calculate depending on where the viewport + * is (arbitrary pins are expensive). The caller should take care to only + * call this as needed and not too frequently. + * + * Output type: GhosttyTerminalScrollbar * + */ + GHOSTTY_TERMINAL_DATA_SCROLLBAR = 9, + + /** + * The current SGR style of the cursor. + * + * This is the style that will be applied to newly printed characters. + * + * Output type: GhosttyStyle * + */ + GHOSTTY_TERMINAL_DATA_CURSOR_STYLE = 10, + + /** + * Whether any mouse tracking mode is active. + * + * Returns true if any of the mouse tracking modes (X10, normal, button, + * or any-event) are enabled. + * + * Output type: bool * + */ + GHOSTTY_TERMINAL_DATA_MOUSE_TRACKING = 11, + + /** + * The terminal title as set by escape sequences (e.g. OSC 0/2). + * + * Returns a borrowed string. The pointer is valid until the next call + * to ghostty_terminal_vt_write() or ghostty_terminal_reset(). An empty + * string (len=0) is returned when no title has been set. + * + * Output type: GhosttyString * + */ + GHOSTTY_TERMINAL_DATA_TITLE = 12, + + /** + * The terminal's current working directory as set by escape sequences + * (e.g. OSC 7). + * + * Returns a borrowed string. The pointer is valid until the next call + * to ghostty_terminal_vt_write() or ghostty_terminal_reset(). An empty + * string (len=0) is returned when no pwd has been set. + * + * Output type: GhosttyString * + */ + GHOSTTY_TERMINAL_DATA_PWD = 13, + + /** + * The total number of rows in the active screen including scrollback. + * + * Output type: size_t * + */ + GHOSTTY_TERMINAL_DATA_TOTAL_ROWS = 14, + + /** + * The number of scrollback rows (total rows minus viewport rows). + * + * Output type: size_t * + */ + GHOSTTY_TERMINAL_DATA_SCROLLBACK_ROWS = 15, + + /** + * The total width of the terminal in pixels. + * + * This is cols * cell_width_px as set by ghostty_terminal_resize(). + * + * Output type: uint32_t * + */ + GHOSTTY_TERMINAL_DATA_WIDTH_PX = 16, + + /** + * The total height of the terminal in pixels. + * + * This is rows * cell_height_px as set by ghostty_terminal_resize(). + * + * Output type: uint32_t * + */ + GHOSTTY_TERMINAL_DATA_HEIGHT_PX = 17, + + /** + * The effective foreground color (override or default). + * + * Returns GHOSTTY_NO_VALUE if no foreground color is set. + * + * Output type: GhosttyColorRgb * + */ + GHOSTTY_TERMINAL_DATA_COLOR_FOREGROUND = 18, + + /** + * The effective background color (override or default). + * + * Returns GHOSTTY_NO_VALUE if no background color is set. + * + * Output type: GhosttyColorRgb * + */ + GHOSTTY_TERMINAL_DATA_COLOR_BACKGROUND = 19, + + /** + * The effective cursor color (override or default). + * + * Returns GHOSTTY_NO_VALUE if no cursor color is set. + * + * Output type: GhosttyColorRgb * + */ + GHOSTTY_TERMINAL_DATA_COLOR_CURSOR = 20, + + /** + * The current 256-color palette. + * + * Output type: GhosttyColorRgb[256] * + */ + GHOSTTY_TERMINAL_DATA_COLOR_PALETTE = 21, + + /** + * The default foreground color (ignoring any OSC override). + * + * Returns GHOSTTY_NO_VALUE if no default foreground color is set. + * + * Output type: GhosttyColorRgb * + */ + GHOSTTY_TERMINAL_DATA_COLOR_FOREGROUND_DEFAULT = 22, + + /** + * The default background color (ignoring any OSC override). + * + * Returns GHOSTTY_NO_VALUE if no default background color is set. + * + * Output type: GhosttyColorRgb * + */ + GHOSTTY_TERMINAL_DATA_COLOR_BACKGROUND_DEFAULT = 23, + + /** + * The default cursor color (ignoring any OSC override). + * + * Returns GHOSTTY_NO_VALUE if no default cursor color is set. + * + * Output type: GhosttyColorRgb * + */ + GHOSTTY_TERMINAL_DATA_COLOR_CURSOR_DEFAULT = 24, + + /** + * The default 256-color palette (ignoring any OSC overrides). + * + * Output type: GhosttyColorRgb[256] * + */ + GHOSTTY_TERMINAL_DATA_COLOR_PALETTE_DEFAULT = 25, + + /** + * The Kitty image storage limit in bytes for the active screen. + * + * A value of zero means the Kitty graphics protocol is disabled. + * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time. + * + * Output type: uint64_t * + */ + GHOSTTY_TERMINAL_DATA_KITTY_IMAGE_STORAGE_LIMIT = 26, + + /** + * Whether the file medium is enabled for Kitty image loading on the + * active screen. + * + * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time. + * + * Output type: bool * + */ + GHOSTTY_TERMINAL_DATA_KITTY_IMAGE_MEDIUM_FILE = 27, + + /** + * Whether the temporary file medium is enabled for Kitty image loading + * on the active screen. + * + * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time. + * + * Output type: bool * + */ + GHOSTTY_TERMINAL_DATA_KITTY_IMAGE_MEDIUM_TEMP_FILE = 28, + + /** + * Whether the shared memory medium is enabled for Kitty image loading + * on the active screen. + * + * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time. + * + * Output type: bool * + */ + GHOSTTY_TERMINAL_DATA_KITTY_IMAGE_MEDIUM_SHARED_MEM = 29, + + /** + * The Kitty graphics image storage for the active screen. + * + * Returns a borrowed pointer to the image storage. The pointer is valid + * until the next mutating terminal call (e.g. ghostty_terminal_vt_write() + * or ghostty_terminal_reset()). + * + * Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time. + * + * Output type: GhosttyKittyGraphics * + */ + GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS = 30, + + /** + * The active screen's current selection. + * + * On success, writes an untracked snapshot of the terminal-owned selection + * to the caller-provided GhosttySelection. The GhosttySelection struct is + * caller-owned and may be kept, but the grid references inside it are + * untracked borrowed references into the active screen. They are only valid + * until the next mutating terminal call, such as ghostty_terminal_set(), + * ghostty_terminal_vt_write(), ghostty_terminal_resize(), or + * ghostty_terminal_reset(). + * + * Returns GHOSTTY_NO_VALUE when there is no active selection. + * + * Output type: GhosttySelection * + */ + GHOSTTY_TERMINAL_DATA_SELECTION = 31, + + /** + * Whether the viewport is currently pinned to the active area. + * + * This is true when the viewport is following the active terminal area, + * and false when the user has scrolled into history. + * + * Output type: bool * + */ + GHOSTTY_TERMINAL_DATA_VIEWPORT_ACTIVE = 32, + GHOSTTY_TERMINAL_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyTerminalData; + +/** + * Create a new terminal instance. + * + * @param allocator Pointer to allocator, or NULL to use the default allocator + * @param terminal Pointer to store the created terminal handle + * @param options Terminal initialization options + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup terminal + */ +GHOSTTY_API GhosttyResult ghostty_terminal_new(const GhosttyAllocator* allocator, + GhosttyTerminal* terminal, + GhosttyTerminalOptions options); + +/** + * Free a terminal instance. + * + * Releases all resources associated with the terminal. After this call, + * the terminal handle becomes invalid and must not be used. + * + * @param terminal The terminal handle to free (may be NULL) + * + * @ingroup terminal + */ +GHOSTTY_API void ghostty_terminal_free(GhosttyTerminal terminal); + +/** + * Perform a full reset of the terminal (RIS). + * + * Resets all terminal state back to its initial configuration, including + * modes, scrollback, scrolling region, and screen contents. The terminal + * dimensions are preserved. + * + * @param terminal The terminal handle (may be NULL, in which case this is a no-op) + * + * @ingroup terminal + */ +GHOSTTY_API void ghostty_terminal_reset(GhosttyTerminal terminal); + +/** + * Resize the terminal to the given dimensions. + * + * Changes the number of columns and rows in the terminal. The primary + * screen will reflow content if wraparound mode is enabled; the alternate + * screen does not reflow. If the dimensions are unchanged, this is a no-op. + * + * This also updates the terminal's pixel dimensions (used for image + * protocols and size reports), disables synchronized output mode (allowed + * by the spec so that resize results are shown immediately), and sends an + * in-band size report if mode 2048 is enabled. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param cols New width in cells (must be greater than zero) + * @param rows New height in cells (must be greater than zero) + * @param cell_width_px Width of a single cell in pixels + * @param cell_height_px Height of a single cell in pixels + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup terminal + */ +GHOSTTY_API GhosttyResult ghostty_terminal_resize(GhosttyTerminal terminal, + uint16_t cols, + uint16_t rows, + uint32_t cell_width_px, + uint32_t cell_height_px); + +/** + * Set an option on the terminal. + * + * Configures terminal callbacks and associated state such as the + * write_pty callback and userdata pointer. The value is passed + * directly for pointer types (callbacks, userdata) or as a pointer + * to the value for non-pointer types (e.g. GhosttyString*). + * NULL clears the option to its default. + * + * Callbacks are invoked synchronously during ghostty_terminal_vt_write(). + * Callbacks must not call ghostty_terminal_vt_write() on the same + * terminal (no reentrancy). + * + * @param terminal The terminal handle (may be NULL, in which case this is a no-op) + * @param option The option to set + * @param value Pointer to the value to set (type depends on the option), + * or NULL to clear the option + * + * @ingroup terminal + */ +GHOSTTY_API GhosttyResult ghostty_terminal_set(GhosttyTerminal terminal, + GhosttyTerminalOption option, + const void* value); + +/** + * Write VT-encoded data to the terminal for processing. + * + * Feeds raw bytes through the terminal's VT stream parser, updating + * terminal state accordingly. By default, sequences that require output + * (queries, device status reports) are silently ignored. Use + * ghostty_terminal_set() with GHOSTTY_TERMINAL_OPT_WRITE_PTY to install + * a callback that receives response data. + * + * This never fails. Any erroneous input or errors in processing the + * input are logged internally but do not cause this function to fail + * because this input is assumed to be untrusted and from an external + * source; so the primary goal is to keep the terminal state consistent and + * not allow malformed input to corrupt or crash. + * + * @param terminal The terminal handle + * @param data Pointer to the data to write + * @param len Length of the data in bytes + * + * @ingroup terminal + */ +GHOSTTY_API void ghostty_terminal_vt_write(GhosttyTerminal terminal, + const uint8_t* data, + size_t len); + +/** + * Scroll the terminal viewport. + * + * Scrolls the terminal's viewport according to the given behavior. + * When using GHOSTTY_SCROLL_VIEWPORT_DELTA, set the delta field in + * the value union to specify the number of rows to scroll (negative + * for up, positive for down). For other behaviors, the value is ignored. + * + * @param terminal The terminal handle (may be NULL, in which case this is a no-op) + * @param behavior The scroll behavior as a tagged union + * + * @ingroup terminal + */ +GHOSTTY_API void ghostty_terminal_scroll_viewport(GhosttyTerminal terminal, + GhosttyTerminalScrollViewport behavior); + +/** + * Get the current value of a terminal mode. + * + * Returns the value of the mode identified by the given mode. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param mode The mode identifying the mode to query + * @param[out] out_value On success, set to true if the mode is set, false + * if it is reset + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal + * is NULL or the mode does not correspond to a known mode + * + * @ingroup terminal + */ +GHOSTTY_API GhosttyResult ghostty_terminal_mode_get(GhosttyTerminal terminal, + GhosttyMode mode, + bool* out_value); + +/** + * Set the value of a terminal mode. + * + * Sets the mode identified by the given mode to the specified value. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param mode The mode identifying the mode to set + * @param value true to set the mode, false to reset it + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal + * is NULL or the mode does not correspond to a known mode + * + * @ingroup terminal + */ +GHOSTTY_API GhosttyResult ghostty_terminal_mode_set(GhosttyTerminal terminal, + GhosttyMode mode, + bool value); + +/** + * Get data from a terminal instance. + * + * Extracts typed data from the given terminal based on the specified + * data type. The output pointer must be of the appropriate type for the + * requested data kind. Valid data types and output types are documented + * in the `GhosttyTerminalData` enum. + * + * @param terminal The terminal handle (may be NULL) + * @param data The type of data to extract + * @param out Pointer to store the extracted data (type depends on data parameter) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal + * is NULL or the data type is invalid + * + * @ingroup terminal + */ +GHOSTTY_API GhosttyResult ghostty_terminal_get(GhosttyTerminal terminal, + GhosttyTerminalData data, + void *out); + +/** + * Get multiple data fields from a terminal in a single call. + * + * This is an optimization over calling ghostty_terminal_get() + * repeatedly, particularly useful in environments with high per-call + * overhead such as FFI or Cgo. + * + * Each element in the keys array specifies a data kind, and the + * corresponding element in the values array receives the result. + * The type of each values[i] pointer must match the output type + * documented for keys[i]. + * + * Processing stops at the first error; on success out_written + * is set to count, on error it is set to the index of the + * failing key (i.e. the number of values successfully written). + * + * @param terminal The terminal handle (may be NULL) + * @param count Number of key/value pairs + * @param keys Array of data kinds to query + * @param values Array of output pointers (types must match each key's + * documented output type) + * @param[out] out_written On return, receives the number of values + * successfully written (may be NULL) + * @return GHOSTTY_SUCCESS if all queries succeed + * + * @ingroup terminal + */ +GHOSTTY_API GhosttyResult ghostty_terminal_get_multi(GhosttyTerminal terminal, + size_t count, + const GhosttyTerminalData* keys, + void** values, + size_t* out_written); + +/** + * Resolve a point in the terminal grid to a grid reference. + * + * Resolves the given point (which can be in active, viewport, screen, + * or history coordinates) to a grid reference for that location. Use + * ghostty_grid_ref_cell() and ghostty_grid_ref_row() to extract the cell + * and row. + * + * Lookups using the `active` and `viewport` tags are fast. The `screen` + * and `history` tags may require traversing the full scrollback page list + * to resolve the y coordinate, so they can be expensive for large + * scrollback buffers. + * + * This function isn't meant to be used as the core of render loop. It + * isn't built to sustain the framerates needed for rendering large screens. + * Use the render state API for that. This API is instead meant for less + * strictly performance-sensitive use cases. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param point The point specifying which cell to look up + * @param[out] out_ref On success, set to the grid reference at the given point (may be NULL) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal + * is NULL or the point is out of bounds + * + * @ingroup terminal + */ +GHOSTTY_API GhosttyResult ghostty_terminal_grid_ref(GhosttyTerminal terminal, + GhosttyPoint point, + GhosttyGridRef *out_ref); + +/** + * Create an owned tracked grid reference for a terminal point. + * + * This is the tracked variant of ghostty_terminal_grid_ref(). The returned + * handle follows the referenced cell as the terminal's page list is modified: + * scrolling, pruning, resize/reflow, and other page-list operations update the + * tracked reference automatically. + * + * The reference is attached to the terminal screen/page-list that is active at + * creation time. + * + * If the point is outside the requested coordinate space, this returns + * GHOSTTY_INVALID_VALUE and writes NULL to out_ref. + * + * The returned handle must be freed with ghostty_tracked_grid_ref_free(). If + * the terminal is freed first, the handle remains valid only for + * tracked-grid-ref APIs: it reports no value and can still be freed. + * + * @param terminal Terminal instance. + * @param point Point to track. + * @param[out] out_ref On success, receives the tracked reference handle. + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if terminal, + * point, or out_ref is invalid, or GHOSTTY_OUT_OF_MEMORY if allocation + * fails. + * + * @ingroup terminal + */ +GHOSTTY_API GhosttyResult ghostty_terminal_grid_ref_track( + GhosttyTerminal terminal, + GhosttyPoint point, + GhosttyTrackedGridRef *out_ref); + +/** + * Convert a grid reference back to a point in the given coordinate system. + * + * This is the inverse of ghostty_terminal_grid_ref(): given a grid reference, + * it returns the x/y coordinates in the requested coordinate system (active, + * viewport, screen, or history). + * + * The grid reference must have been obtained from the same terminal instance. + * Like all grid references, it is only valid until the next mutating terminal + * call. + * + * Not every grid reference is representable in every coordinate system. For + * example, a cell in scrollback history cannot be expressed in active + * coordinates, and a cell that has scrolled off the visible area cannot be + * expressed in viewport coordinates. In these cases, the function returns + * GHOSTTY_NO_VALUE. + * + * @param terminal The terminal handle (NULL returns GHOSTTY_INVALID_VALUE) + * @param ref Pointer to the grid reference to convert + * @param tag The target coordinate system + * @param[out] out On success, set to the coordinate in the requested system (may be NULL) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the terminal + * or ref is NULL/invalid, GHOSTTY_NO_VALUE if the ref falls outside + * the requested coordinate system + * + * @ingroup terminal + */ +GHOSTTY_API GhosttyResult ghostty_terminal_point_from_grid_ref( + GhosttyTerminal terminal, + const GhosttyGridRef *ref, + GhosttyPointTag tag, + GhosttyPointCoordinate *out); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_TERMINAL_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/types.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/types.h new file mode 100644 index 0000000000..214d282296 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/types.h @@ -0,0 +1,335 @@ +/** + * @file types.h + * + * Common types, macros, and utilities for libghostty-vt. + */ + +#ifndef GHOSTTY_VT_TYPES_H +#define GHOSTTY_VT_TYPES_H + +#include +#include +#include + +// Symbol visibility for shared library builds. On Windows, functions +// are exported from the DLL when building and imported when consuming. +// On other platforms with GCC/Clang, functions are marked with default +// visibility so they remain accessible when the library is built with +// -fvisibility=hidden. For static library builds, define GHOSTTY_STATIC +// before including this header to make this a no-op. +#ifndef GHOSTTY_API +#if defined(GHOSTTY_STATIC) + #define GHOSTTY_API +#elif defined(_WIN32) || defined(_WIN64) + #ifdef GHOSTTY_BUILD_SHARED + #define GHOSTTY_API __declspec(dllexport) + #else + #define GHOSTTY_API __declspec(dllimport) + #endif +#elif defined(__GNUC__) && __GNUC__ >= 4 + #define GHOSTTY_API __attribute__((visibility("default"))) +#else + #define GHOSTTY_API +#endif +#endif + +/** + * Enum int-sizing helpers. + * + * The Zig side backs all C enums with c_int, so the C declarations + * must use int as their underlying type to maintain ABI compatibility. + * + * C23 (detected via __STDC_VERSION__ >= 202311L) supports explicit + * enum underlying types with `enum : int { ... }`. For pre-C23 + * compilers, which are free to choose any type that can represent + * all values (C11 §6.7.2.2), we add an INT_MAX sentinel as the last + * entry to force the compiler to use int. + * + * INT_MAX is used rather than a fixed constant like 0xFFFFFFFF + * because enum constants must have type int (which is signed). + * Values above INT_MAX overflow signed int and are a constraint + * violation in standard C; compilers that accept them interpret them + * as negative values via two's complement, which can collide with + * legitimate negative enum values. + * + * Usage: + * @code + * typedef enum GHOSTTY_ENUM_TYPED { + * FOO_A = 0, + * FOO_B = 1, + * FOO_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, + * } Foo; + * @endcode + */ +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L +#define GHOSTTY_ENUM_TYPED : int +#else +#define GHOSTTY_ENUM_TYPED +#endif +#define GHOSTTY_ENUM_MAX_VALUE INT_MAX + +/** + * Result codes for libghostty-vt operations. + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Operation completed successfully */ + GHOSTTY_SUCCESS = 0, + /** Operation failed due to failed allocation */ + GHOSTTY_OUT_OF_MEMORY = -1, + /** Operation failed due to invalid value */ + GHOSTTY_INVALID_VALUE = -2, + /** Operation failed because the provided buffer was too small */ + GHOSTTY_OUT_OF_SPACE = -3, + /** The requested value has no value */ + GHOSTTY_NO_VALUE = -4, + GHOSTTY_RESULT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyResult; + +/* ---- Opaque handles ---- */ + +/** + * Opaque handle to a terminal instance. + * + * @ingroup terminal + */ +typedef struct GhosttyTerminalImpl* GhosttyTerminal; + +/** + * Opaque handle to a tracked grid reference. + * + * A tracked grid reference is owned by the caller and must be freed with + * ghostty_tracked_grid_ref_free(). If the terminal that created it is freed + * first, the handle remains valid only for tracked-grid-ref APIs: it reports no + * value and can still be freed. + * + * @ingroup grid_ref + */ +typedef struct GhosttyTrackedGridRefImpl* GhosttyTrackedGridRef; + +/** + * Opaque handle to a Kitty graphics image storage. + * + * Obtained via ghostty_terminal_get() with + * GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS. The pointer is borrowed from + * the terminal and remains valid until the next mutating terminal call + * (e.g. ghostty_terminal_vt_write() or ghostty_terminal_reset()). + * + * @ingroup kitty_graphics + */ +typedef struct GhosttyKittyGraphicsImpl* GhosttyKittyGraphics; + +/** + * Opaque handle to a Kitty graphics image. + * + * Obtained via ghostty_kitty_graphics_image() with an image ID. The + * pointer is borrowed from the storage and remains valid until the next + * mutating terminal call. + * + * @ingroup kitty_graphics + */ +typedef const struct GhosttyKittyGraphicsImageImpl* GhosttyKittyGraphicsImage; + +/** + * Opaque handle to a Kitty graphics placement iterator. + * + * @ingroup kitty_graphics + */ +typedef struct GhosttyKittyGraphicsPlacementIteratorImpl* GhosttyKittyGraphicsPlacementIterator; + +/** + * Opaque handle to a render state instance. + * + * @ingroup render + */ +typedef struct GhosttyRenderStateImpl* GhosttyRenderState; + +/** + * Opaque handle to a render-state row iterator. + * + * @ingroup render + */ +typedef struct GhosttyRenderStateRowIteratorImpl* GhosttyRenderStateRowIterator; + +/** + * Opaque handle to render-state row cells. + * + * @ingroup render + */ +typedef struct GhosttyRenderStateRowCellsImpl* GhosttyRenderStateRowCells; + +/** + * Opaque handle to an SGR parser instance. + * + * This handle represents an SGR (Select Graphic Rendition) parser that can + * be used to parse SGR sequences and extract individual text attributes. + * + * @ingroup sgr + */ +typedef struct GhosttySgrParserImpl* GhosttySgrParser; + +/** + * Opaque handle to a formatter instance. + * + * @ingroup formatter + */ +typedef struct GhosttyFormatterImpl* GhosttyFormatter; + +/** + * Opaque handle to an OSC parser instance. + * + * This handle represents an OSC (Operating System Command) parser that can + * be used to parse the contents of OSC sequences. + * + * @ingroup osc + */ +typedef struct GhosttyOscParserImpl* GhosttyOscParser; + +/** + * Opaque handle to a single OSC command. + * + * This handle represents a parsed OSC (Operating System Command) command. + * The command can be queried for its type and associated data. + * + * @ingroup osc + */ +typedef struct GhosttyOscCommandImpl* GhosttyOscCommand; + +/* ---- Common value types ---- */ + +/** + * Terminal content output format. + * + * @ingroup formatter + */ +typedef enum GHOSTTY_ENUM_TYPED { + /** Plain text (no escape sequences). */ + GHOSTTY_FORMATTER_FORMAT_PLAIN, + + /** VT sequences preserving colors, styles, URLs, etc. */ + GHOSTTY_FORMATTER_FORMAT_VT, + + /** HTML with inline styles. */ + GHOSTTY_FORMATTER_FORMAT_HTML, + GHOSTTY_FORMATTER_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE, +} GhosttyFormatterFormat; + +/** + * A borrowed byte string (pointer + length). + * + * The memory is not owned by this struct. The pointer is only valid + * for the lifetime documented by the API that produces or consumes it. + */ +typedef struct { + /** Pointer to the string bytes. */ + const uint8_t* ptr; + + /** Length of the string in bytes. */ + size_t len; +} GhosttyString; + +/** + * A caller-provided byte buffer. + * + * APIs that write to this type use `len` for the number of bytes written on + * GHOSTTY_SUCCESS and the required byte capacity on GHOSTTY_OUT_OF_SPACE. + */ +typedef struct { + /** Destination buffer for bytes. May be NULL when cap is 0 to query required size. */ + uint8_t* ptr; + + /** Capacity of ptr in bytes. */ + size_t cap; + + /** Bytes written on success, or required byte capacity on GHOSTTY_OUT_OF_SPACE. */ + size_t len; +} GhosttyBuffer; + +/** + * A surface-space position in pixels. + * + * This is not a terminal grid coordinate. It represents an x/y position in the + * rendered surface coordinate space, with (0, 0) at the top-left of the + * surface. + */ +typedef struct { + /** X position in surface pixels. */ + double x; + + /** Y position in surface pixels. */ + double y; +} GhosttySurfacePosition; + +/** + * A borrowed list of Unicode scalar values. + * + * Values are encoded as uint32_t scalar values. The memory is not owned by this + * struct. The pointer is only valid for the lifetime documented by the API that + * consumes or produces it. + * + * APIs may document special handling for NULL + len 0, such as “use defaults”. + */ +typedef struct { + /** Pointer to Unicode scalar values. */ + const uint32_t* ptr; + + /** Number of entries in ptr. */ + size_t len; +} GhosttyCodepoints; + +/** + * Initialize a sized struct to zero and set its size field. + * + * Sized structs use a `size` field as the first member for ABI + * compatibility. This macro zero-initializes the struct and sets the + * size field to `sizeof(type)`, which allows the library to detect + * which version of the struct the caller was compiled against. + * + * @param type The struct type to initialize + * @return A zero-initialized struct with the size field set + * + * Example: + * @code + * GhosttyFormatterTerminalOptions opts = GHOSTTY_INIT_SIZED(GhosttyFormatterTerminalOptions); + * opts.emit = GHOSTTY_FORMATTER_FORMAT_PLAIN; + * opts.trim = true; + * @endcode + */ +#define GHOSTTY_INIT_SIZED(type) \ + ((type){ .size = sizeof(type) }) + +/** + * Return a pointer to a null-terminated JSON string describing the + * layout of every C API struct for the current target. + * + * This is primarily useful for language bindings that can't easily + * set C struct fields and need to do so via byte offsets. For example, + * WebAssembly modules can't share struct definitions with the host. + * + * Example (abbreviated): + * @code{.json} + * { + * "GhosttyMouseEncoderSize": { + * "size": 40, + * "align": 8, + * "fields": { + * "size": { "offset": 0, "size": 8, "type": "u64" }, + * "screen_width": { "offset": 8, "size": 4, "type": "u32" }, + * "screen_height": { "offset": 12, "size": 4, "type": "u32" }, + * "cell_width": { "offset": 16, "size": 4, "type": "u32" }, + * "cell_height": { "offset": 20, "size": 4, "type": "u32" }, + * "padding_top": { "offset": 24, "size": 4, "type": "u32" }, + * "padding_bottom": { "offset": 28, "size": 4, "type": "u32" }, + * "padding_right": { "offset": 32, "size": 4, "type": "u32" }, + * "padding_left": { "offset": 36, "size": 4, "type": "u32" } + * } + * } + * } + * @endcode + * + * The returned pointer is valid for the lifetime of the process. + * + * @return Pointer to the null-terminated JSON string. + */ +GHOSTTY_API const char *ghostty_type_json(void); + +#endif /* GHOSTTY_VT_TYPES_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/wasm.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/wasm.h new file mode 100644 index 0000000000..e2b63e2c60 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/include/ghostty/vt/wasm.h @@ -0,0 +1,160 @@ +/** + * @file wasm.h + * + * WebAssembly utility functions for libghostty-vt. + */ + +#ifndef GHOSTTY_VT_WASM_H +#define GHOSTTY_VT_WASM_H + +#ifdef __wasm__ + +#include +#include +#include + +/** @defgroup wasm WebAssembly Utilities + * + * Convenience functions for allocating various types in WebAssembly builds. + * **These are only available the libghostty-vt wasm module.** + * + * Ghostty relies on pointers to various types for ABI compatibility, and + * creating those pointers in Wasm can be tedious. These functions provide + * a purely additive set of utilities that simplify memory management in + * Wasm environments without changing the core C library API. + * + * @note These functions always use the default allocator. If you need + * custom allocation strategies, you should allocate types manually using + * your custom allocator. This is a very rare use case in the WebAssembly + * world so these are optimized for simplicity. + * + * ## Example Usage + * + * Here's a simple example of using the Wasm utilities with the key encoder: + * + * @code + * const { exports } = wasmInstance; + * const view = new DataView(wasmMemory.buffer); + * + * // Create key encoder + * const encoderPtr = exports.ghostty_wasm_alloc_opaque(); + * exports.ghostty_key_encoder_new(null, encoderPtr); + * const encoder = view.getUint32(encoder, true); + * + * // Configure encoder with Kitty protocol flags + * const flagsPtr = exports.ghostty_wasm_alloc_u8(); + * view.setUint8(flagsPtr, 0x1F); + * exports.ghostty_key_encoder_setopt(encoder, 5, flagsPtr); + * + * // Allocate output buffer and size pointer + * const bufferSize = 32; + * const bufPtr = exports.ghostty_wasm_alloc_u8_array(bufferSize); + * const writtenPtr = exports.ghostty_wasm_alloc_usize(); + * + * // Encode the key event + * exports.ghostty_key_encoder_encode( + * encoder, eventPtr, bufPtr, bufferSize, writtenPtr + * ); + * + * // Read encoded output + * const bytesWritten = view.getUint32(writtenPtr, true); + * const encoded = new Uint8Array(wasmMemory.buffer, bufPtr, bytesWritten); + * @endcode + * + * @remark The code above is pretty ugly! This is the lowest level interface + * to the libghostty-vt Wasm module. In practice, this should be wrapped + * in a higher-level API that abstracts away all this. + * + * @{ + */ + +/** + * Allocate an opaque pointer. This can be used for any opaque pointer + * types such as GhosttyKeyEncoder, GhosttyKeyEvent, etc. + * + * @return Pointer to allocated opaque pointer, or NULL if allocation failed + * @ingroup wasm + */ +GHOSTTY_API void** ghostty_wasm_alloc_opaque(void); + +/** + * Free an opaque pointer allocated by ghostty_wasm_alloc_opaque(). + * + * @param ptr Pointer to free, or NULL (NULL is safely ignored) + * @ingroup wasm + */ +GHOSTTY_API void ghostty_wasm_free_opaque(void **ptr); + +/** + * Allocate an array of uint8_t values. + * + * @param len Number of uint8_t elements to allocate + * @return Pointer to allocated array, or NULL if allocation failed + * @ingroup wasm + */ +GHOSTTY_API uint8_t* ghostty_wasm_alloc_u8_array(size_t len); + +/** + * Free an array allocated by ghostty_wasm_alloc_u8_array(). + * + * @param ptr Pointer to the array to free, or NULL (NULL is safely ignored) + * @param len Length of the array (must match the length passed to alloc) + * @ingroup wasm + */ +GHOSTTY_API void ghostty_wasm_free_u8_array(uint8_t *ptr, size_t len); + +/** + * Allocate an array of uint16_t values. + * + * @param len Number of uint16_t elements to allocate + * @return Pointer to allocated array, or NULL if allocation failed + * @ingroup wasm + */ +GHOSTTY_API uint16_t* ghostty_wasm_alloc_u16_array(size_t len); + +/** + * Free an array allocated by ghostty_wasm_alloc_u16_array(). + * + * @param ptr Pointer to the array to free, or NULL (NULL is safely ignored) + * @param len Length of the array (must match the length passed to alloc) + * @ingroup wasm + */ +GHOSTTY_API void ghostty_wasm_free_u16_array(uint16_t *ptr, size_t len); + +/** + * Allocate a single uint8_t value. + * + * @return Pointer to allocated uint8_t, or NULL if allocation failed + * @ingroup wasm + */ +GHOSTTY_API uint8_t* ghostty_wasm_alloc_u8(void); + +/** + * Free a uint8_t allocated by ghostty_wasm_alloc_u8(). + * + * @param ptr Pointer to free, or NULL (NULL is safely ignored) + * @ingroup wasm + */ +GHOSTTY_API void ghostty_wasm_free_u8(uint8_t *ptr); + +/** + * Allocate a single size_t value. + * + * @return Pointer to allocated size_t, or NULL if allocation failed + * @ingroup wasm + */ +GHOSTTY_API size_t* ghostty_wasm_alloc_usize(void); + +/** + * Free a size_t allocated by ghostty_wasm_alloc_usize(). + * + * @param ptr Pointer to free, or NULL (NULL is safely ignored) + * @ingroup wasm + */ +GHOSTTY_API void ghostty_wasm_free_usize(size_t *ptr); + +/** @} */ + +#endif /* __wasm__ */ + +#endif /* GHOSTTY_VT_WASM_H */ diff --git a/apps/mobile/modules/t3-terminal/android/.gitignore b/apps/mobile/modules/t3-terminal/android/.gitignore new file mode 100644 index 0000000000..3166b90b04 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/android/.gitignore @@ -0,0 +1 @@ +.cxx/ diff --git a/apps/mobile/modules/t3-terminal/android/build.gradle b/apps/mobile/modules/t3-terminal/android/build.gradle index 90c0d4fc21..0da0777cf4 100644 --- a/apps/mobile/modules/t3-terminal/android/build.gradle +++ b/apps/mobile/modules/t3-terminal/android/build.gradle @@ -6,11 +6,25 @@ version = '0.0.0' android { namespace 'expo.modules.t3terminal' + ndkVersion rootProject.ext.ndkVersion compileSdk rootProject.ext.compileSdkVersion defaultConfig { minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion + + externalNativeBuild { + cmake { + cppFlags '-std=c++17 -Wall -Wextra -Werror' + } + } + } + + externalNativeBuild { + cmake { + path 'src/main/cpp/CMakeLists.txt' + version '3.22.1' + } } } diff --git a/apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Bold.ttf b/apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Bold.ttf new file mode 100644 index 0000000000..e0e39544b0 Binary files /dev/null and b/apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Bold.ttf differ diff --git a/apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Regular.ttf b/apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Regular.ttf new file mode 100644 index 0000000000..88b81490cd Binary files /dev/null and b/apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Regular.ttf differ diff --git a/apps/mobile/modules/t3-terminal/android/src/main/cpp/CMakeLists.txt b/apps/mobile/modules/t3-terminal/android/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000000..0273ff6c86 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/android/src/main/cpp/CMakeLists.txt @@ -0,0 +1,23 @@ +cmake_minimum_required(VERSION 3.22.1) + +project(t3terminal LANGUAGES CXX) + +add_library(ghostty-vt SHARED IMPORTED) +set_target_properties( + ghostty-vt + PROPERTIES IMPORTED_LOCATION + "${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libghostty-vt.so" +) + +add_library(t3terminal SHARED t3_terminal_jni.cpp) + +target_include_directories( + t3terminal + PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../Vendor/libghostty-vt/include" +) + +target_link_options( + t3terminal PRIVATE "-Wl,-z,common-page-size=16384" "-Wl,-z,max-page-size=16384" +) + +target_link_libraries(t3terminal PRIVATE ghostty-vt log) diff --git a/apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp b/apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp new file mode 100644 index 0000000000..95760e8ead --- /dev/null +++ b/apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp @@ -0,0 +1,516 @@ +#include + +#include +#include +#include +#include +#include + +#include + +namespace { + +constexpr uint32_t kSnapshotMagic = 0x54563354; // "T3VT" in little endian. +constexpr uint16_t kSnapshotVersion = 1; +constexpr size_t kMaxScrollbackRows = 10000; + +enum CellFlag : uint16_t { + kBold = 1 << 0, + kItalic = 1 << 1, + kFaint = 1 << 2, + kInverse = 1 << 3, + kInvisible = 1 << 4, + kStrikethrough = 1 << 5, + kOverline = 1 << 6, + kUnderline = 1 << 7, + kSelected = 1 << 8, +}; + +struct Session { + GhosttyTerminal terminal = nullptr; + GhosttyRenderState render_state = nullptr; + GhosttyRenderStateRowIterator row_iterator = nullptr; + GhosttyRenderStateRowCells row_cells = nullptr; + std::vector responses; + std::mutex mutex; +}; + +class ByteWriter { + public: + explicit ByteWriter(size_t capacity) { bytes_.reserve(capacity); } + + void U8(uint8_t value) { bytes_.push_back(value); } + + void U16(uint16_t value) { + U8(static_cast(value)); + U8(static_cast(value >> 8)); + } + + void U32(uint32_t value) { + U16(static_cast(value)); + U16(static_cast(value >> 16)); + } + + void Bytes(const std::vector& value) { + bytes_.insert(bytes_.end(), value.begin(), value.end()); + } + + std::vector Take() { return std::move(bytes_); } + + private: + std::vector bytes_; +}; + +Session* FromHandle(jlong handle) { + return reinterpret_cast(static_cast(handle)); +} + +jbyteArray ToJavaBytes(JNIEnv* env, const std::vector& bytes) { + auto result = env->NewByteArray(static_cast(bytes.size())); + if (result != nullptr && !bytes.empty()) { + env->SetByteArrayRegion(result, 0, static_cast(bytes.size()), + reinterpret_cast(bytes.data())); + } + return result; +} + +GhosttyColorRgb RgbFromArgb(jint color) { + const auto value = static_cast(color); + return { + .r = static_cast(value >> 16), + .g = static_cast(value >> 8), + .b = static_cast(value), + }; +} + +uint32_t ArgbFromRgb(GhosttyColorRgb color) { + return 0xFF000000U | (static_cast(color.r) << 16U) | + (static_cast(color.g) << 8U) | color.b; +} + +GhosttyColorRgb Blend(GhosttyColorRgb foreground, GhosttyColorRgb background, + uint8_t foreground_weight) { + const auto blend = [foreground_weight](uint8_t front, uint8_t back) { + const uint16_t back_weight = 255 - foreground_weight; + return static_cast((front * foreground_weight + back * back_weight) / 255); + }; + return { + .r = blend(foreground.r, background.r), + .g = blend(foreground.g, background.g), + .b = blend(foreground.b, background.b), + }; +} + +void AppendUtf8(std::vector* output, uint32_t codepoint) { + if (codepoint <= 0x7F) { + output->push_back(static_cast(codepoint)); + } else if (codepoint <= 0x7FF) { + output->push_back(static_cast(0xC0 | (codepoint >> 6))); + output->push_back(static_cast(0x80 | (codepoint & 0x3F))); + } else if (codepoint <= 0xFFFF && !(codepoint >= 0xD800 && codepoint <= 0xDFFF)) { + output->push_back(static_cast(0xE0 | (codepoint >> 12))); + output->push_back(static_cast(0x80 | ((codepoint >> 6) & 0x3F))); + output->push_back(static_cast(0x80 | (codepoint & 0x3F))); + } else if (codepoint <= 0x10FFFF) { + output->push_back(static_cast(0xF0 | (codepoint >> 18))); + output->push_back(static_cast(0x80 | ((codepoint >> 12) & 0x3F))); + output->push_back(static_cast(0x80 | ((codepoint >> 6) & 0x3F))); + output->push_back(static_cast(0x80 | (codepoint & 0x3F))); + } +} + +void OnWritePty(GhosttyTerminal, void* userdata, const uint8_t* data, size_t len) { + auto* session = static_cast(userdata); + if (session == nullptr || data == nullptr || len == 0) return; + session->responses.insert(session->responses.end(), data, data + len); +} + +void ApplyTheme(Session* session, jint foreground, jint background, jint cursor, + JNIEnv* env, jintArray palette_array) { + auto foreground_rgb = RgbFromArgb(foreground); + auto background_rgb = RgbFromArgb(background); + auto cursor_rgb = RgbFromArgb(cursor); + ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_FOREGROUND, + &foreground_rgb); + ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_BACKGROUND, + &background_rgb); + ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_CURSOR, &cursor_rgb); + + if (palette_array == nullptr) return; + const auto palette_length = env->GetArrayLength(palette_array); + if (palette_length <= 0) return; + + GhosttyColorRgb palette[256]; + if (ghostty_terminal_get(session->terminal, + GHOSTTY_TERMINAL_DATA_COLOR_PALETTE_DEFAULT, + palette) != GHOSTTY_SUCCESS) { + return; + } + + const auto copied_length = std::min(palette_length, 256); + std::vector colors(static_cast(copied_length)); + env->GetIntArrayRegion(palette_array, 0, copied_length, colors.data()); + for (jsize index = 0; index < copied_length; ++index) { + palette[index] = RgbFromArgb(colors[index]); + } + ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_PALETTE, palette); +} + +void FreeSession(Session* session) { + if (session == nullptr) return; + ghostty_render_state_row_cells_free(session->row_cells); + ghostty_render_state_row_iterator_free(session->row_iterator); + ghostty_render_state_free(session->render_state); + ghostty_terminal_free(session->terminal); + delete session; +} + +std::vector DrainResponses(Session* session) { + std::vector responses; + responses.swap(session->responses); + return responses; +} + +bool ViewportGridRef(Session* session, jint x, jint y, GhosttyGridRef* out) { + *out = GhosttyGridRef{}; + out->size = sizeof(*out); + GhosttyPoint point{}; + point.tag = GHOSTTY_POINT_TAG_VIEWPORT; + point.value.coordinate.x = static_cast(std::max(x, 0)); + point.value.coordinate.y = static_cast(std::max(y, 0)); + return ghostty_terminal_grid_ref(session->terminal, point, out) == GHOSTTY_SUCCESS; +} + +uint16_t StyleFlags(const GhosttyStyle& style, bool selected) { + uint16_t flags = 0; + if (style.bold) flags |= kBold; + if (style.italic) flags |= kItalic; + if (style.faint) flags |= kFaint; + if (style.inverse) flags |= kInverse; + if (style.invisible) flags |= kInvisible; + if (style.strikethrough) flags |= kStrikethrough; + if (style.overline) flags |= kOverline; + if (style.underline != 0) flags |= kUnderline; + if (selected) flags |= kSelected; + return flags; +} + +} // namespace + +extern "C" JNIEXPORT jlong JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeCreate( + JNIEnv* env, jclass, jint cols, jint rows, jint cell_width, jint cell_height, + jint foreground, jint background, jint cursor, jintArray palette) { + auto* session = new Session(); + GhosttyTerminalOptions options = { + .cols = static_cast(std::clamp(cols, 1, 65535)), + .rows = static_cast(std::clamp(rows, 1, 65535)), + .max_scrollback = kMaxScrollbackRows, + }; + if (ghostty_terminal_new(nullptr, &session->terminal, options) != GHOSTTY_SUCCESS || + ghostty_render_state_new(nullptr, &session->render_state) != GHOSTTY_SUCCESS || + ghostty_render_state_row_iterator_new(nullptr, &session->row_iterator) != GHOSTTY_SUCCESS || + ghostty_render_state_row_cells_new(nullptr, &session->row_cells) != GHOSTTY_SUCCESS) { + FreeSession(session); + return 0; + } + + ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_USERDATA, session); + ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_WRITE_PTY, + reinterpret_cast(OnWritePty)); + ApplyTheme(session, foreground, background, cursor, env, palette); + ghostty_terminal_resize(session->terminal, options.cols, options.rows, + static_cast(std::max(cell_width, 1)), + static_cast(std::max(cell_height, 1))); + return static_cast(reinterpret_cast(session)); +} + +extern "C" JNIEXPORT void JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeDestroy(JNIEnv*, jclass, jlong handle) { + FreeSession(FromHandle(handle)); +} + +extern "C" JNIEXPORT jbyteArray JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeFeed(JNIEnv* env, jclass, jlong handle, + jbyteArray data) { + auto* session = FromHandle(handle); + if (session == nullptr || data == nullptr) return env->NewByteArray(0); + std::lock_guard lock(session->mutex); + const auto length = env->GetArrayLength(data); + std::vector bytes(static_cast(length)); + if (length > 0) { + env->GetByteArrayRegion(data, 0, length, reinterpret_cast(bytes.data())); + ghostty_terminal_vt_write(session->terminal, bytes.data(), bytes.size()); + } + return ToJavaBytes(env, DrainResponses(session)); +} + +extern "C" JNIEXPORT jbyteArray JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeResize( + JNIEnv* env, jclass, jlong handle, jint cols, jint rows, jint cell_width, jint cell_height) { + auto* session = FromHandle(handle); + if (session == nullptr) return env->NewByteArray(0); + std::lock_guard lock(session->mutex); + ghostty_terminal_resize(session->terminal, + static_cast(std::clamp(cols, 1, 65535)), + static_cast(std::clamp(rows, 1, 65535)), + static_cast(std::max(cell_width, 1)), + static_cast(std::max(cell_height, 1))); + return ToJavaBytes(env, DrainResponses(session)); +} + +extern "C" JNIEXPORT void JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeScroll(JNIEnv*, jclass, jlong handle, + jint rows) { + auto* session = FromHandle(handle); + if (session == nullptr || rows == 0) return; + std::lock_guard lock(session->mutex); + GhosttyTerminalScrollViewport scroll = { + .tag = GHOSTTY_SCROLL_VIEWPORT_DELTA, + .value = {.delta = rows}, + }; + ghostty_terminal_scroll_viewport(session->terminal, scroll); +} + +extern "C" JNIEXPORT void JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeSetTheme( + JNIEnv* env, jclass, jlong handle, jint foreground, jint background, jint cursor, + jintArray palette) { + auto* session = FromHandle(handle); + if (session == nullptr) return; + std::lock_guard lock(session->mutex); + ApplyTheme(session, foreground, background, cursor, env, palette); +} + +extern "C" JNIEXPORT jboolean JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeSelectWordAt(JNIEnv*, jclass, + jlong handle, jint x, + jint y) { + auto* session = FromHandle(handle); + if (session == nullptr) return JNI_FALSE; + std::lock_guard lock(session->mutex); + GhosttyTerminalSelectWordOptions options{}; + options.size = sizeof(options); + if (!ViewportGridRef(session, x, y, &options.ref)) return JNI_FALSE; + GhosttySelection selection{}; + selection.size = sizeof(selection); + if (ghostty_terminal_select_word(session->terminal, &options, &selection) != + GHOSTTY_SUCCESS) { + return JNI_FALSE; + } + return ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION, + &selection) == GHOSTTY_SUCCESS + ? JNI_TRUE + : JNI_FALSE; +} + +extern "C" JNIEXPORT void JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeExtendSelection( + JNIEnv*, jclass, jlong handle, jint anchor_x, jint anchor_y, jint x, jint y) { + auto* session = FromHandle(handle); + if (session == nullptr) return; + std::lock_guard lock(session->mutex); + GhosttySelection selection{}; + selection.size = sizeof(selection); + if (!ViewportGridRef(session, anchor_x, anchor_y, &selection.start)) return; + if (!ViewportGridRef(session, x, y, &selection.end)) return; + ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION, &selection); +} + +extern "C" JNIEXPORT jboolean JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeSelectAll(JNIEnv*, jclass, + jlong handle) { + auto* session = FromHandle(handle); + if (session == nullptr) return JNI_FALSE; + std::lock_guard lock(session->mutex); + GhosttySelection selection{}; + selection.size = sizeof(selection); + if (ghostty_terminal_select_all(session->terminal, &selection) != GHOSTTY_SUCCESS) { + return JNI_FALSE; + } + return ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION, + &selection) == GHOSTTY_SUCCESS + ? JNI_TRUE + : JNI_FALSE; +} + +extern "C" JNIEXPORT void JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeClearSelection(JNIEnv*, jclass, + jlong handle) { + auto* session = FromHandle(handle); + if (session == nullptr) return; + std::lock_guard lock(session->mutex); + ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION, nullptr); +} + +// Returns the active selection as UTF-8 bytes (soft-wrapped lines unwrapped, +// trailing whitespace trimmed), or null when there is no selection. +extern "C" JNIEXPORT jbyteArray JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeGetSelectionText(JNIEnv* env, jclass, + jlong handle) { + auto* session = FromHandle(handle); + if (session == nullptr) return nullptr; + std::lock_guard lock(session->mutex); + GhosttyTerminalSelectionFormatOptions options{}; + options.size = sizeof(options); + options.emit = GHOSTTY_FORMATTER_FORMAT_PLAIN; + options.unwrap = true; + options.trim = true; + uint8_t* bytes = nullptr; + size_t len = 0; + if (ghostty_terminal_selection_format_alloc(session->terminal, nullptr, options, + &bytes, &len) != GHOSTTY_SUCCESS || + bytes == nullptr) { + return nullptr; + } + auto result = env->NewByteArray(static_cast(len)); + if (result != nullptr && len > 0) { + env->SetByteArrayRegion(result, 0, static_cast(len), + reinterpret_cast(bytes)); + } + ghostty_free(nullptr, bytes, len); + return result; +} + +extern "C" JNIEXPORT jbyteArray JNICALL +Java_expo_modules_t3terminal_GhosttyBridge_nativeSnapshot(JNIEnv* env, jclass, + jlong handle) { + auto* session = FromHandle(handle); + if (session == nullptr) return env->NewByteArray(0); + std::lock_guard lock(session->mutex); + + if (ghostty_render_state_update(session->render_state, session->terminal) != GHOSTTY_SUCCESS) { + return env->NewByteArray(0); + } + + uint16_t cols = 0; + uint16_t rows = 0; + bool cursor_visible = false; + bool cursor_in_viewport = false; + bool cursor_blinking = false; + uint16_t cursor_x = 0xFFFF; + uint16_t cursor_y = 0xFFFF; + GhosttyRenderStateCursorVisualStyle cursor_style = + GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BLOCK; + ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_COLS, &cols); + ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_ROWS, &rows); + ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_CURSOR_VISIBLE, + &cursor_visible); + ghostty_render_state_get(session->render_state, + GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_HAS_VALUE, + &cursor_in_viewport); + ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_CURSOR_BLINKING, + &cursor_blinking); + ghostty_render_state_get(session->render_state, + GHOSTTY_RENDER_STATE_DATA_CURSOR_VISUAL_STYLE, &cursor_style); + if (cursor_in_viewport) { + ghostty_render_state_get(session->render_state, + GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_X, &cursor_x); + ghostty_render_state_get(session->render_state, + GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_Y, &cursor_y); + } + + GhosttyRenderStateColors colors{}; + colors.size = sizeof(colors); + if (ghostty_render_state_colors_get(session->render_state, &colors) != GHOSTTY_SUCCESS) { + return env->NewByteArray(0); + } + const auto cursor_color = colors.cursor_has_value ? colors.cursor : colors.foreground; + + ByteWriter writer(32 + static_cast(cols) * rows * 14); + writer.U32(kSnapshotMagic); + writer.U16(kSnapshotVersion); + writer.U16(cols); + writer.U16(rows); + writer.U16(cursor_x); + writer.U16(cursor_y); + writer.U8(cursor_visible && cursor_in_viewport ? 1 : 0); + writer.U8(static_cast(cursor_style)); + writer.U8(cursor_blinking ? 1 : 0); + writer.U8(0); + writer.U32(ArgbFromRgb(colors.foreground)); + writer.U32(ArgbFromRgb(colors.background)); + writer.U32(ArgbFromRgb(cursor_color)); + + if (ghostty_render_state_get(session->render_state, + GHOSTTY_RENDER_STATE_DATA_ROW_ITERATOR, + &session->row_iterator) != GHOSTTY_SUCCESS) { + return env->NewByteArray(0); + } + + uint16_t written_rows = 0; + while (written_rows < rows && + ghostty_render_state_row_iterator_next(session->row_iterator)) { + if (ghostty_render_state_row_get(session->row_iterator, + GHOSTTY_RENDER_STATE_ROW_DATA_CELLS, + &session->row_cells) != GHOSTTY_SUCCESS) { + break; + } + + uint16_t written_cols = 0; + while (written_cols < cols && ghostty_render_state_row_cells_next(session->row_cells)) { + GhosttyStyle style{}; + style.size = sizeof(style); + bool selected = false; + GhosttyColorRgb foreground = colors.foreground; + GhosttyColorRgb background = colors.background; + ghostty_render_state_row_cells_get(session->row_cells, + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_STYLE, + &style); + ghostty_render_state_row_cells_get(session->row_cells, + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_SELECTED, + &selected); + ghostty_render_state_row_cells_get(session->row_cells, + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_FG_COLOR, + &foreground); + ghostty_render_state_row_cells_get(session->row_cells, + GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_BG_COLOR, + &background); + if (style.inverse) std::swap(foreground, background); + if (style.faint) foreground = Blend(foreground, background, 155); + + uint32_t grapheme_count = 0; + ghostty_render_state_row_cells_get( + session->row_cells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_LEN, + &grapheme_count); + std::vector utf8; + if (grapheme_count > 0) { + std::vector codepoints(grapheme_count); + if (ghostty_render_state_row_cells_get( + session->row_cells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_BUF, + codepoints.data()) == GHOSTTY_SUCCESS) { + utf8.reserve(grapheme_count * 4); + for (const auto codepoint : codepoints) AppendUtf8(&utf8, codepoint); + } + } + + const auto text_length = static_cast(std::min(utf8.size(), 65535)); + writer.U32(ArgbFromRgb(foreground)); + writer.U32(ArgbFromRgb(background)); + writer.U16(StyleFlags(style, selected)); + writer.U16(text_length); + if (text_length != utf8.size()) utf8.resize(text_length); + writer.Bytes(utf8); + ++written_cols; + } + + while (written_cols++ < cols) { + writer.U32(ArgbFromRgb(colors.foreground)); + writer.U32(ArgbFromRgb(colors.background)); + writer.U16(0); + writer.U16(0); + } + ++written_rows; + } + + while (written_rows++ < rows) { + for (uint16_t column = 0; column < cols; ++column) { + writer.U32(ArgbFromRgb(colors.foreground)); + writer.U32(ArgbFromRgb(colors.background)); + writer.U16(0); + writer.U16(0); + } + } + + return ToJavaBytes(env, writer.Take()); +} diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/GhosttyBridge.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/GhosttyBridge.kt new file mode 100644 index 0000000000..06c13a2824 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/GhosttyBridge.kt @@ -0,0 +1,64 @@ +package expo.modules.t3terminal + +internal object GhosttyBridge { + init { + System.loadLibrary("ghostty-vt") + System.loadLibrary("t3terminal") + } + + @JvmStatic + @Suppress("LongParameterList") + external fun nativeCreate( + cols: Int, + rows: Int, + cellWidth: Int, + cellHeight: Int, + foreground: Int, + background: Int, + cursor: Int, + palette: IntArray + ): Long + + @JvmStatic external fun nativeDestroy(handle: Long) + + @JvmStatic external fun nativeFeed(handle: Long, data: ByteArray): ByteArray + + @JvmStatic + external fun nativeResize( + handle: Long, + cols: Int, + rows: Int, + cellWidth: Int, + cellHeight: Int + ): ByteArray + + @JvmStatic external fun nativeScroll(handle: Long, rows: Int) + + @JvmStatic + external fun nativeSetTheme( + handle: Long, + foreground: Int, + background: Int, + cursor: Int, + palette: IntArray + ) + + @JvmStatic external fun nativeSnapshot(handle: Long): ByteArray + + @JvmStatic external fun nativeSelectWordAt(handle: Long, col: Int, row: Int): Boolean + + @JvmStatic + external fun nativeExtendSelection( + handle: Long, + anchorCol: Int, + anchorRow: Int, + col: Int, + row: Int + ) + + @JvmStatic external fun nativeSelectAll(handle: Long): Boolean + + @JvmStatic external fun nativeClearSelection(handle: Long) + + @JvmStatic external fun nativeGetSelectionText(handle: Long): ByteArray? +} diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt index abb3982be1..1631c7fe68 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt @@ -7,6 +7,12 @@ class T3TerminalModule : Module() { override fun definition() = ModuleDefinition { Name("T3TerminalSurface") + // 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" to 2, + ) + View(T3TerminalView::class) { Prop("terminalKey") { view: T3TerminalView, terminalKey: String -> view.terminalKey = terminalKey @@ -20,6 +26,14 @@ class T3TerminalModule : Module() { view.fontSize = fontSize.toFloat() } + Prop("focusRequest") { view: T3TerminalView, focusRequest: Double -> + view.focusRequest = focusRequest + } + + Prop("autoFocus") { view: T3TerminalView, autoFocus: Boolean -> + view.autoFocus = autoFocus + } + Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String -> view.appearanceScheme = appearanceScheme } @@ -41,6 +55,10 @@ class T3TerminalModule : Module() { } Events("onInput", "onResize") + + OnViewDestroys { view: T3TerminalView -> + view.cleanup() + } } } } diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt index ec85d0ba07..88de793a8f 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt @@ -3,64 +3,89 @@ package expo.modules.t3terminal import android.content.Context import android.graphics.Color import android.graphics.Typeface -import android.view.View +import android.text.Editable +import android.text.InputType +import android.text.TextWatcher +import android.view.KeyEvent import android.view.ViewGroup -import android.view.inputmethod.InputMethodManager import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputMethodManager import android.widget.EditText -import android.widget.LinearLayout -import android.widget.ScrollView -import android.widget.TextView -import androidx.core.widget.doAfterTextChanged +import android.widget.FrameLayout import expo.modules.kotlin.AppContext -import expo.modules.kotlin.views.ExpoView import expo.modules.kotlin.viewevent.EventDispatcher +import expo.modules.kotlin.views.ExpoView import kotlin.math.max -import kotlin.math.min class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(context, appContext) { - private val container = LinearLayout(context) - private val scrollView = ScrollView(context) - private val textView = TextView(context) + private val container = FrameLayout(context) + private val terminalCanvas = TerminalCanvasView(context) private val inputView = EditText(context) private val onInput by EventDispatcher() private val onResize by EventDispatcher() - private var lastWidth = 0 - private var lastHeight = 0 + private var terminalHandle = 0L + private var fedBuffer = "" + private var cols = 0 + private var rows = 0 private var clearingInput = false + private var isCleanedUp = false private var backgroundColorValue = Color.parseColor("#24292E") private var foregroundColorValue = Color.parseColor("#D1D5DA") private var mutedForegroundColorValue = Color.parseColor("#959DA5") + private var cursorColorValue = Color.parseColor("#009FFF") + private var paletteColors = IntArray(0) var terminalKey: String = "" set(value) { + if (field == value) return field = value contentDescription = "t3-terminal-$value" + recreateTerminal() } var initialBuffer: String = "" set(value) { + if (field == value) return field = value - textView.text = value.ifEmpty { "$ " } - scrollView.post { - scrollView.fullScroll(View.FOCUS_DOWN) - } + feedPendingBuffer() } var fontSize: Float = 10f set(value) { field = value - textView.textSize = value + terminalCanvas.fontSizeSp = value inputView.textSize = max(value, 13f) emitResize() } var appearanceScheme: String = "dark" - set(value) { - field = value - } var themeConfig: String = "" + set(value) { + field = value + parseThemeConfig(value) + applyTheme() + } + + var focusRequest: Double = 0.0 + set(value) { + val previous = field + field = value + if (value != previous && value > 0) { + requestKeyboardFocus() + } + } + + var autoFocus: Boolean = true + set(value) { + field = value + if (value) { + requestKeyboardFocus() + } else { + inputView.clearFocus() + hideKeyboard() + } + } var backgroundColorHex: String = "#24292E" set(value) { @@ -80,121 +105,327 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex set(value) { field = value mutedForegroundColorValue = parseColor(value, mutedForegroundColorValue) - applyTheme() } init { - applyTheme() - container.orientation = LinearLayout.VERTICAL - textView.typeface = Typeface.MONOSPACE - textView.textSize = fontSize - textView.setPadding(8, 8, 8, 8) - textView.text = "$ " + terminalCanvas.fontSizeSp = fontSize + terminalCanvas.onRequestKeyboard = { requestKeyboardFocus() } + terminalCanvas.onScrollRows = { delta -> + if (terminalHandle != 0L) { + GhosttyBridge.nativeScroll(terminalHandle, delta) + renderSnapshot() + } + } + terminalCanvas.onCellMetricsChanged = { emitResize() } + terminalCanvas.selectionDelegate = object : TerminalSelectionDelegate { + override fun selectWordAt(col: Int, row: Int): Boolean { + if (terminalHandle == 0L) return false + val selected = GhosttyBridge.nativeSelectWordAt(terminalHandle, col, row) + if (selected) renderSnapshot() + return selected + } + override fun extendSelection(anchorCol: Int, anchorRow: Int, col: Int, row: Int) { + if (terminalHandle == 0L) return + GhosttyBridge.nativeExtendSelection(terminalHandle, anchorCol, anchorRow, col, row) + renderSnapshot() + } + + override fun selectAll(): Boolean { + if (terminalHandle == 0L) return false + val selected = GhosttyBridge.nativeSelectAll(terminalHandle) + if (selected) renderSnapshot() + return selected + } + + override fun clearSelection() { + if (terminalHandle == 0L) return + GhosttyBridge.nativeClearSelection(terminalHandle) + renderSnapshot() + } + + override fun selectionText(): String? = + if (terminalHandle == 0L) { + null + } else { + GhosttyBridge.nativeGetSelectionText(terminalHandle)?.let { String(it, Charsets.UTF_8) } + } + } + + configureInputView() + container.addView( + terminalCanvas, + FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, + ), + ) + container.addView(inputView, FrameLayout.LayoutParams(1, 1)) + addView( + container, + LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT), + ) + applyTheme() + } + + override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { + super.onSizeChanged(width, height, oldWidth, oldHeight) + if (width != oldWidth || height != oldHeight) emitResize() + } + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec) + val childWidthSpec = MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY) + val childHeightSpec = MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY) + container.measure(childWidthSpec, childHeightSpec) + } + + override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + container.layout(0, 0, right - left, bottom - top) + if (changed) emitResize() + } + + fun cleanup() { + if (isCleanedUp) return + isCleanedUp = true + inputView.setOnEditorActionListener(null) + terminalCanvas.onScrollRows = null + terminalCanvas.onRequestKeyboard = null + terminalCanvas.onCellMetricsChanged = null + terminalCanvas.selectionDelegate = null + destroyTerminal() + } + + private fun configureInputView() { inputView.setSingleLine(true) inputView.setTextColor(Color.TRANSPARENT) inputView.setHintTextColor(Color.TRANSPARENT) inputView.setBackgroundColor(Color.TRANSPARENT) inputView.typeface = Typeface.MONOSPACE inputView.textSize = max(fontSize, 13f) - inputView.hint = "" - inputView.alpha = 0.02f - inputView.imeOptions = EditorInfo.IME_ACTION_SEND + inputView.alpha = 0.01f + inputView.isFocusableInTouchMode = true + inputView.imeOptions = EditorInfo.IME_ACTION_SEND or + EditorInfo.IME_FLAG_NO_EXTRACT_UI or + EditorInfo.IME_FLAG_NO_FULLSCREEN or + EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING + inputView.inputType = InputType.TYPE_CLASS_TEXT or + InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD or + InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS inputView.setPadding(0, 0, 0, 0) - inputView.setOnFocusChangeListener { _, hasFocus -> - if (hasFocus) { - showKeyboard() + inputView.setOnEditorActionListener { _, actionId, event -> + val isKeyUp = event?.action == KeyEvent.ACTION_UP + val isImeSend = actionId == EditorInfo.IME_ACTION_SEND && !isKeyUp + val isHardwareEnter = event?.keyCode == KeyEvent.KEYCODE_ENTER && + event.action == KeyEvent.ACTION_DOWN + val isEnter = isImeSend || isHardwareEnter + if (isEnter) { + // Enter must send CR: raw-mode TUIs treat LF as Ctrl+J (insert newline). + onInput(mapOf("data" to "\r")) + true + } else { + false } } - inputView.setOnEditorActionListener { view, actionId, _ -> - if (actionId != EditorInfo.IME_ACTION_SEND) return@setOnEditorActionListener false - onInput(mapOf("data" to "\n")) - true - } inputView.setOnKeyListener { _, keyCode, event -> - if (event.action != android.view.KeyEvent.ACTION_DOWN) return@setOnKeyListener false - when (keyCode) { - android.view.KeyEvent.KEYCODE_DEL -> { + if (event.action != KeyEvent.ACTION_DOWN) return@setOnKeyListener false + when { + keyCode == KeyEvent.KEYCODE_DEL -> { onInput(mapOf("data" to "\u007F")) true } + // Hardware keyboard Ctrl+A..Z -> control bytes 0x01..0x1A (Ctrl+C, Ctrl+Z, ...). + event.isCtrlPressed && keyCode in KeyEvent.KEYCODE_A..KeyEvent.KEYCODE_Z -> { + onInput( + mapOf("data" to (keyCode - KeyEvent.KEYCODE_A + 1).toChar().toString()), + ) + true + } else -> false } } - inputView.doAfterTextChanged { editable -> - if (clearingInput) return@doAfterTextChanged - val text = editable?.toString().orEmpty() - if (text.isEmpty()) return@doAfterTextChanged - onInput(mapOf("data" to text)) - clearingInput = true - inputView.text?.clear() - clearingInput = false - } + inputView.addTextChangedListener( + object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit - textView.setOnClickListener { requestKeyboardFocus() } - scrollView.setOnClickListener { requestKeyboardFocus() } - container.setOnClickListener { requestKeyboardFocus() } - isClickable = true - setOnClickListener { requestKeyboardFocus() } + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { + if (clearingInput || s == null || count <= 0) return + val end = (start + count).coerceAtMost(s.length) + if (start >= end) return + val insertedText = s.subSequence(start, end).toString() + if (insertedText.isNotEmpty()) { + onInput(mapOf("data" to insertedText)) + } + } - scrollView.addView( - textView, - LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT), + override fun afterTextChanged(editable: Editable?) { + if (clearingInput || editable.isNullOrEmpty()) return + clearingInput = true + editable.clear() + clearingInput = false + } + }, ) - container.addView( - scrollView, - LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - 0, - 1f, - ), - ) - container.addView( - inputView, - LinearLayout.LayoutParams(1, 1), - ) - addView( - container, - LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT), - ) - - post { - requestKeyboardFocus() - } - } - - override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { - super.onSizeChanged(width, height, oldWidth, oldHeight) - if (width == lastWidth && height == lastHeight) return - lastWidth = width - lastHeight = height - emitResize() } + @Suppress("ComplexCondition") private fun emitResize() { - if (width <= 0 || height <= 0) return - val density = resources.displayMetrics.scaledDensity - val fontPx = max(fontSize * density, 1f) - val cols = max(20, min(400, (width / (fontPx * 0.62f)).toInt())) - val terminalHeight = max(height - inputView.height, 0) - val rows = max(5, min(200, (terminalHeight / (fontPx * 1.35f)).toInt())) + if ( + width <= 0 || + height <= 0 || + terminalCanvas.width <= 0 || + terminalCanvas.height <= 0 || + isCleanedUp + ) { + return + } + val nextCols = (terminalCanvas.usableWidth() / terminalCanvas.cellWidthPx) + .toInt() + .coerceIn(2, 400) + val nextRows = (terminalCanvas.usableHeight() / terminalCanvas.cellHeightPx) + .toInt() + .coerceIn(2, 200) + if (nextCols == cols && nextRows == rows && terminalHandle != 0L) return + cols = nextCols + rows = nextRows + val response = if (terminalHandle == 0L) { + createTerminal() + ByteArray(0) + } else { + GhosttyBridge.nativeResize( + terminalHandle, + cols, + rows, + terminalCanvas.cellWidthPx.toInt(), + terminalCanvas.cellHeightPx.toInt(), + ) + } + emitResponse(response) onResize(mapOf("cols" to cols, "rows" to rows)) + feedPendingBuffer() + renderSnapshot() + } + + @Suppress("ComplexCondition") + private fun createTerminal() { + if (terminalHandle != 0L || cols <= 0 || rows <= 0 || isCleanedUp) return + terminalHandle = GhosttyBridge.nativeCreate( + cols, + rows, + terminalCanvas.cellWidthPx.toInt(), + terminalCanvas.cellHeightPx.toInt(), + foregroundColorValue, + backgroundColorValue, + cursorColorValue, + paletteColors, + ) + fedBuffer = "" + } + + private fun recreateTerminal() { + if (terminalHandle == 0L) return + destroyTerminal() + createTerminal() + feedPendingBuffer() + renderSnapshot() + } + + private fun destroyTerminal() { + if (terminalHandle == 0L) return + GhosttyBridge.nativeDestroy(terminalHandle) + terminalHandle = 0L + fedBuffer = "" + terminalCanvas.resetSelectionState() + } + + private fun feedPendingBuffer() { + if (terminalHandle == 0L || initialBuffer == fedBuffer) return + if (!initialBuffer.startsWith(fedBuffer)) { + recreateTerminal() + if (terminalHandle == 0L) return + } + val suffix = initialBuffer.substring(fedBuffer.length) + if (suffix.isNotEmpty()) { + emitResponse(GhosttyBridge.nativeFeed(terminalHandle, suffix.toByteArray(Charsets.UTF_8))) + // New output invalidates an active selection (matches the web drawer); + // otherwise the copy toolbar drifts out of sync with the grid. + if (terminalCanvas.hasActiveSelection()) { + GhosttyBridge.nativeClearSelection(terminalHandle) + terminalCanvas.resetSelectionState() + } + } + fedBuffer = initialBuffer + renderSnapshot() + } + + private fun renderSnapshot() { + if (terminalHandle == 0L) return + TerminalFrame.decode( + GhosttyBridge.nativeSnapshot(terminalHandle) + )?.let(terminalCanvas::setFrame) + } + + private fun emitResponse(response: ByteArray) { + if (response.isNotEmpty()) { + onInput(mapOf("data" to String(response, Charsets.UTF_8))) + } } private fun requestKeyboardFocus() { inputView.requestFocus() - showKeyboard() + val inputMethodManager = context.getSystemService( + Context.INPUT_METHOD_SERVICE + ) as? InputMethodManager + 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) - scrollView.setBackgroundColor(backgroundColorValue) - textView.setTextColor(foregroundColorValue) - textView.setBackgroundColor(backgroundColorValue) - inputView.setTextColor(Color.TRANSPARENT) - inputView.setHintTextColor(mutedForegroundColorValue) - inputView.setBackgroundColor(Color.TRANSPARENT) + terminalCanvas.setBackgroundColor(backgroundColorValue) + if (terminalHandle != 0L) { + GhosttyBridge.nativeSetTheme( + terminalHandle, + foregroundColorValue, + backgroundColorValue, + cursorColorValue, + paletteColors, + ) + renderSnapshot() + } + } + + @Suppress("LoopWithTooManyJumpStatements") + private fun parseThemeConfig(config: String) { + val palette = sortedMapOf() + for (line in config.lineSequence()) { + val parts = line.split('=', limit = 2) + if (parts.size != 2) continue + val key = parts[0].trim() + val value = parts[1].trim() + when (key) { + "cursor-color" -> cursorColorValue = parseColor(value, cursorColorValue) + "palette" -> { + val paletteParts = value.split('=', limit = 2) + val index = paletteParts.firstOrNull()?.trim()?.toIntOrNull() ?: continue + val color = paletteParts.getOrNull(1)?.trim() ?: continue + if (index in 0..255) palette[index] = parseColor(color, foregroundColorValue) + } + } + } + if (palette.isNotEmpty()) { + val lastIndex = palette.lastKey() + paletteColors = IntArray(lastIndex + 1) { index -> + palette[index] ?: foregroundColorValue + } + } } private fun parseColor(value: String, fallback: Int): Int = @@ -203,9 +434,4 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex } catch (_: IllegalArgumentException) { fallback } - - private fun showKeyboard() { - val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager - imm?.showSoftInput(inputView, InputMethodManager.SHOW_IMPLICIT) - } } diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt new file mode 100644 index 0000000000..f713bdb4ff --- /dev/null +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt @@ -0,0 +1,628 @@ +package expo.modules.t3terminal + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Rect +import android.graphics.Typeface +import android.util.Log +import android.view.ActionMode +import android.view.GestureDetector +import android.view.HapticFeedbackConstants +import android.view.Menu +import android.view.MenuItem +import android.view.MotionEvent +import android.view.View +import android.widget.OverScroller +import kotlin.math.ceil +import kotlin.math.max +import kotlin.math.min + +/** + * Bundled terminal font with Nerd Font glyphs (powerline, file icons). + * MesloLGS NF is the powerlevel10k-tuned Meslo Nerd Font patch. + */ +internal object TerminalTypefaces { + private var loaded = false + var regular: Typeface = Typeface.MONOSPACE + private set + var bold: Typeface = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD) + private set + + @Suppress("TooGenericExceptionCaught") // Typeface.createFromAsset exposes RuntimeException. + fun ensureLoaded(context: Context) { + if (loaded) return + loaded = true + try { + regular = Typeface.createFromAsset(context.assets, "fonts/MesloLGS-NF-Regular.ttf") + bold = Typeface.createFromAsset(context.assets, "fonts/MesloLGS-NF-Bold.ttf") + } catch (error: RuntimeException) { + Log.w("TerminalCanvasView", "bundled terminal font unavailable, using monospace", error) + } + } +} + +/** + * Selection operations backed by the native terminal. The terminal owns the + * selection state; the canvas only drives gestures and renders the result. + */ +internal interface TerminalSelectionDelegate { + fun selectWordAt(col: Int, row: Int): Boolean + + fun extendSelection(anchorCol: Int, anchorRow: Int, col: Int, row: Int) + + fun selectAll(): Boolean + + fun clearSelection() + + fun selectionText(): String? +} + +internal class TerminalCanvasView(context: Context) : View(context) { + companion object { + const val FLAG_BOLD = 1 shl 0 + const val FLAG_ITALIC = 1 shl 1 + const val FLAG_INVISIBLE = 1 shl 4 + const val FLAG_STRIKETHROUGH = 1 shl 5 + const val FLAG_OVERLINE = 1 shl 6 + const val FLAG_UNDERLINE = 1 shl 7 + const val FLAG_SELECTED = 1 shl 8 + + private const val MENU_COPY = 1 + private const val MENU_SELECT_ALL = 2 + private const val HANDLE_COLOR = 0xFF7AA2F7.toInt() + } + + private val density = resources.displayMetrics.density + private val scaledDensity = density * resources.configuration.fontScale + private val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG) + + init { + TerminalTypefaces.ensureLoaded(context) + } + + private val regularTypeface = TerminalTypefaces.regular + private val boldTypeface = TerminalTypefaces.bold + private val italicTypeface = Typeface.create(TerminalTypefaces.regular, Typeface.ITALIC) + private val boldItalicTypeface = Typeface.create(TerminalTypefaces.bold, Typeface.ITALIC) + private val gestureDetector = GestureDetector(context, TerminalGestureListener()) + private val contentPadding = 8f * density + private var frame: TerminalFrame? = null + private var scrollRemainder = 0f + private val scroller = OverScroller(context) + private var flingLastY = 0 + private val flingRunnable = object : Runnable { + override fun run() { + if (!scroller.computeScrollOffset()) return + val currentY = scroller.currY + val deltaPx = (currentY - flingLastY).toFloat() + flingLastY = currentY + scrollRemainder += -deltaPx / cellHeightPx + val rows = scrollRemainder.toInt() + if (rows != 0) { + scrollRemainder -= rows + onScrollRows?.invoke(rows) + } + postOnAnimation(this) + } + } + private var cursorOn = true + private val cursorBlink = object : Runnable { + override fun run() { + val currentFrame = frame ?: return + if (!currentFrame.cursorBlinking || !currentFrame.cursorVisible) return + cursorOn = !cursorOn + invalidate() + postDelayed(this, 500) + } + } + + var onScrollRows: ((Int) -> Unit)? = null + var onRequestKeyboard: (() -> Unit)? = null + var onCellMetricsChanged: (() -> Unit)? = null + var selectionDelegate: TerminalSelectionDelegate? = null + + private val handlePaint = Paint(Paint.ANTI_ALIAS_FLAG) + private var selectionActive = false + private var dragSelecting = false + private var draggingHandle = false + private var anchorCol = 0 + private var anchorRow = 0 + private var extentCol = 0 + private var extentRow = 0 + + // Word-snapped span from the initial long-press; extending anchors to the + // far word edge so the word never shrinks mid-drag. + private var wordStartCol = 0 + private var wordStartRow = 0 + private var wordEndCol = 0 + private var wordEndRow = 0 + private var actionMode: ActionMode? = null + + // Actual selection endpoints in viewport cells, derived from the decoded + // frame (word-snap can extend past the pressed cell). Drive handle + // placement and hit testing. + private var selectionEndpointsValid = false + private var selectionStartCol = 0 + private var selectionStartRow = 0 + private var selectionEndCol = 0 + private var selectionEndRow = 0 + + var fontSizeSp: Float = 10f + set(value) { + if (field == value) return + field = value + updateCellMetrics() + } + + var cellWidthPx: Float = 1f + private set + var cellHeightPx: Float = 1f + private set + private var baselineOffsetPx: Float = 1f + + init { + isClickable = true + isFocusable = true + isFocusableInTouchMode = true + paint.typeface = regularTypeface + updateCellMetrics() + } + + fun setFrame(value: TerminalFrame) { + frame = value + cursorOn = true + updateSelectionEndpoints() + removeCallbacks(cursorBlink) + if (value.cursorBlinking && value.cursorVisible) postDelayed(cursorBlink, 500) + invalidate() + } + + fun resetSelectionState() { + selectionActive = false + dragSelecting = false + draggingHandle = false + selectionEndpointsValid = false + actionMode?.finish() + } + + fun hasActiveSelection(): Boolean = selectionActive + + fun usableWidth(): Float = max(width - contentPadding * 2f, 1f) + fun usableHeight(): Float = max(height - contentPadding * 2f, 1f) + + @Suppress("NestedBlockDepth", "ComplexCondition") + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + val currentFrame = frame + if (currentFrame == null) { + canvas.drawColor(Color.TRANSPARENT) + return + } + canvas.drawColor(currentFrame.background) + canvas.save() + canvas.clipRect( + contentPadding, + contentPadding, + width - contentPadding, + height - contentPadding, + ) + + for (row in 0 until currentFrame.rows) { + val top = contentPadding + row * cellHeightPx + val bottom = top + cellHeightPx + for (column in 0 until currentFrame.cols) { + val index = row * currentFrame.cols + column + val left = contentPadding + column * cellWidthPx + val right = left + cellWidthPx + val background = currentFrame.cellBackgrounds[index] + val flags = currentFrame.cellFlags[index] + paint.style = Paint.Style.FILL + paint.color = if (flags and FLAG_SELECTED != 0) { + blend(currentFrame.cursorColor, background, 0.32f) + } else { + background + } + if (paint.color != currentFrame.background || flags and FLAG_SELECTED != 0) { + canvas.drawRect(left, top, right + 0.5f, bottom + 0.5f, paint) + } + + val text = currentFrame.cellText[index] + if (text.isNotEmpty() && flags and FLAG_INVISIBLE == 0) { + configureTextPaint(flags, currentFrame.cellForegrounds[index]) + canvas.drawText(text, left, top + baselineOffsetPx, paint) + if (flags and FLAG_OVERLINE != 0) { + canvas.drawRect(left, top + 1f, right, top + max(2f, density), paint) + } + } + } + } + + if (currentFrame.cursorVisible && cursorOn && + currentFrame.cursorX in 0 until currentFrame.cols && + currentFrame.cursorY in 0 until currentFrame.rows + ) { + drawCursor(canvas, currentFrame) + } + canvas.restore() + drawSelectionHandles(canvas) + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + if (event.actionMasked == MotionEvent.ACTION_DOWN) { + parent?.requestDisallowInterceptTouchEvent(true) + // Touch-down always stops momentum, even when the event is consumed by + // a selection-handle grab and never reaches the gesture detector. + scroller.forceFinished(true) + removeCallbacks(flingRunnable) + } else if (event.actionMasked == MotionEvent.ACTION_UP || + event.actionMasked == MotionEvent.ACTION_CANCEL + ) { + parent?.requestDisallowInterceptTouchEvent(false) + } + return when { + dragSelecting -> { + when (event.actionMasked) { + MotionEvent.ACTION_MOVE -> extendSelectionTo(event.x, event.y) + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + dragSelecting = false + showSelectionActions() + } + } + true + } + event.actionMasked == MotionEvent.ACTION_DOWN && grabHandleAt(event.x, event.y) -> true + else -> gestureDetector.onTouchEvent(event) || super.onTouchEvent(event) + } + } + + override fun onDetachedFromWindow() { + removeCallbacks(cursorBlink) + removeCallbacks(flingRunnable) + actionMode?.finish() + super.onDetachedFromWindow() + } + + private fun updateCellMetrics() { + paint.textSize = fontSizeSp * scaledDensity + paint.typeface = regularTypeface + cellWidthPx = ceil(paint.measureText("M").toDouble()).toFloat().coerceAtLeast(1f) + val metrics = paint.fontMetrics + val glyphHeight = metrics.descent - metrics.ascent + cellHeightPx = ceil((glyphHeight * 1.12f).toDouble()).toFloat().coerceAtLeast(1f) + baselineOffsetPx = (cellHeightPx - glyphHeight) / 2f - metrics.ascent + onCellMetricsChanged?.invoke() + invalidate() + } + + private fun configureTextPaint(flags: Int, color: Int) { + val bold = flags and FLAG_BOLD != 0 + val italic = flags and FLAG_ITALIC != 0 + paint.typeface = when { + bold && italic -> boldItalicTypeface + bold -> boldTypeface + italic -> italicTypeface + else -> regularTypeface + } + paint.textSize = fontSizeSp * scaledDensity + paint.color = color + paint.style = Paint.Style.FILL + paint.isUnderlineText = flags and FLAG_UNDERLINE != 0 + paint.isStrikeThruText = flags and FLAG_STRIKETHROUGH != 0 + } + + private fun drawCursor(canvas: Canvas, currentFrame: TerminalFrame) { + val left = contentPadding + currentFrame.cursorX * cellWidthPx + val top = contentPadding + currentFrame.cursorY * cellHeightPx + val right = left + cellWidthPx + val bottom = top + cellHeightPx + paint.color = currentFrame.cursorColor + paint.isUnderlineText = false + paint.isStrikeThruText = false + when (currentFrame.cursorStyle) { + 0 -> canvas.drawRect(left, top, left + max(2f * density, 2f), bottom, paint) + 2 -> canvas.drawRect(left, bottom - max(2f * density, 2f), right, bottom, paint) + 3 -> { + paint.style = Paint.Style.STROKE + paint.strokeWidth = max(density, 1f) + canvas.drawRect(left, top, right, bottom, paint) + } + else -> { + paint.style = Paint.Style.FILL + canvas.drawRect(left, top, right, bottom, paint) + val index = currentFrame.cursorY * currentFrame.cols + currentFrame.cursorX + val text = currentFrame.cellText[index] + if (text.isNotEmpty()) { + configureTextPaint(currentFrame.cellFlags[index], currentFrame.background) + canvas.drawText(text, left, top + baselineOffsetPx, paint) + } + } + } + } + + private fun columnAt(px: Float): Int { + val cols = frame?.cols ?: return 0 + return ((px - contentPadding) / cellWidthPx).toInt().coerceIn(0, max(cols - 1, 0)) + } + + private fun rowAt(py: Float): Int { + val rows = frame?.rows ?: return 0 + return ((py - contentPadding) / cellHeightPx).toInt().coerceIn(0, max(rows - 1, 0)) + } + + private fun startWordSelection(px: Float, py: Float) { + val delegate = selectionDelegate ?: return + val col = columnAt(px) + val row = rowAt(py) + // Set before selectWordAt: the delegate re-renders synchronously and + // updateSelectionEndpoints only scans while a selection is active. + selectionActive = true + if (!delegate.selectWordAt(col, row)) { + selectionActive = false + return + } + dragSelecting = true + draggingHandle = false + if (selectionEndpointsValid) { + wordStartCol = selectionStartCol + wordStartRow = selectionStartRow + wordEndCol = selectionEndCol + wordEndRow = selectionEndRow + } else { + wordStartCol = col + wordStartRow = row + wordEndCol = col + wordEndRow = row + } + anchorCol = wordStartCol + anchorRow = wordStartRow + extentCol = col + extentRow = row + performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) + } + + private fun extendSelectionTo(px: Float, py: Float) { + if (!selectionActive) return + val col = columnAt(px) + val row = rowAt(py) + if (col == extentCol && row == extentRow) return + extentCol = col + extentRow = row + if (!draggingHandle) { + val beforeWord = row < wordStartRow || (row == wordStartRow && col < wordStartCol) + if (beforeWord) { + anchorCol = wordEndCol + anchorRow = wordEndRow + } else { + anchorCol = wordStartCol + anchorRow = wordStartRow + } + } + selectionDelegate?.extendSelection(anchorCol, anchorRow, col, row) + } + + private fun clearSelection() { + if (!selectionActive) return + selectionActive = false + dragSelecting = false + draggingHandle = false + selectionEndpointsValid = false + actionMode?.finish() + selectionDelegate?.clearSelection() + } + + private fun copySelection() { + val text = selectionDelegate?.selectionText() ?: return + if (text.isEmpty()) return + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager + clipboard?.setPrimaryClip(ClipData.newPlainText("Terminal", text)) + } + + private fun handleCenterX(col: Int, leadingEdge: Boolean): Float = + contentPadding + (col + if (leadingEdge) 0 else 1) * cellWidthPx + + private fun handleCenterY(row: Int): Float = + contentPadding + (row + 1) * cellHeightPx + handleRadius() + + private fun handleRadius(): Float = max(cellHeightPx * 0.45f, 12f) + + /** + * Begin dragging when the touch lands on a selection handle. The opposite + * endpoint becomes the drag anchor so the grabbed end follows the finger. + */ + private fun grabHandleAt(px: Float, py: Float): Boolean { + if (!selectionActive || !selectionEndpointsValid) return false + val slop = max(handleRadius() * 2f, 24 * density) + + fun near(cx: Float, cy: Float): Boolean { + val dx = px - cx + val dy = py - cy + return dx * dx + dy * dy <= slop * slop + } + + val startGrabbed = + near(handleCenterX(selectionStartCol, true), handleCenterY(selectionStartRow)) + val endGrabbed = + !startGrabbed && near(handleCenterX(selectionEndCol, false), handleCenterY(selectionEndRow)) + val handleGrabbed = startGrabbed || endGrabbed + if (handleGrabbed) { + if (startGrabbed) { + anchorCol = selectionEndCol + anchorRow = selectionEndRow + extentCol = selectionStartCol + extentRow = selectionStartRow + } else { + anchorCol = selectionStartCol + anchorRow = selectionStartRow + extentCol = selectionEndCol + extentRow = selectionEndRow + } + dragSelecting = true + draggingHandle = true + actionMode?.finish() + } + return handleGrabbed + } + + /** Scan the decoded frame for the first/last selected cells. */ + private fun updateSelectionEndpoints() { + selectionEndpointsValid = false + val currentFrame = frame + if (!selectionActive || currentFrame == null) return + val totalCells = currentFrame.cols * currentFrame.rows + var first = -1 + var last = -1 + for (index in 0 until totalCells) { + if (currentFrame.cellFlags[index] and FLAG_SELECTED != 0) { + if (first < 0) first = index + last = index + } + } + if (first >= 0 && currentFrame.cols > 0) { + selectionStartCol = first % currentFrame.cols + selectionStartRow = first / currentFrame.cols + selectionEndCol = last % currentFrame.cols + selectionEndRow = last / currentFrame.cols + selectionEndpointsValid = true + } + } + + // Anchor the toolbar to the actual word-snapped endpoints when known; + // gesture cells can lag behind what the terminal selected. + private fun selectionBounds(): Rect { + val startCol = if (selectionEndpointsValid) selectionStartCol else min(anchorCol, extentCol) + val endCol = if (selectionEndpointsValid) selectionEndCol else max(anchorCol, extentCol) + val startRow = if (selectionEndpointsValid) selectionStartRow else min(anchorRow, extentRow) + val endRow = if (selectionEndpointsValid) selectionEndRow else max(anchorRow, extentRow) + val left = contentPadding + min(startCol, endCol) * cellWidthPx + val right = contentPadding + (max(startCol, endCol) + 1) * cellWidthPx + val top = contentPadding + startRow * cellHeightPx + val bottom = contentPadding + (endRow + 1) * cellHeightPx + return Rect(left.toInt(), top.toInt(), right.toInt(), bottom.toInt()) + } + + private fun showSelectionActions() { + if (actionMode != null || !selectionActive) return + actionMode = startActionMode( + object : ActionMode.Callback2() { + override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { + menu.add(Menu.NONE, MENU_COPY, 0, android.R.string.copy) + menu.add(Menu.NONE, MENU_SELECT_ALL, 1, android.R.string.selectAll) + return true + } + + override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean = false + + override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean = + when (item.itemId) { + MENU_COPY -> { + copySelection() + clearSelection() + true + } + MENU_SELECT_ALL -> { + val currentFrame = frame + if (currentFrame != null && selectionDelegate?.selectAll() == true) { + anchorCol = 0 + anchorRow = 0 + extentCol = max(currentFrame.cols - 1, 0) + extentRow = max(currentFrame.rows - 1, 0) + } + true + } + else -> false + } + + override fun onDestroyActionMode(mode: ActionMode) { + actionMode = null + // Dismissing the toolbar (e.g. Back) drops the selection too — + // except mid-drag, where grabHandleAt finishes the mode on purpose. + if (selectionActive && !dragSelecting) clearSelection() + } + + override fun onGetContentRect(mode: ActionMode, view: View, outRect: Rect) { + outRect.set(selectionBounds()) + } + }, + ActionMode.TYPE_FLOATING, + ) + } + + private fun drawSelectionHandles(canvas: Canvas) { + if (!selectionActive || !selectionEndpointsValid) return + val radius = handleRadius() + handlePaint.color = HANDLE_COLOR + val stemWidth = max(radius / 4f, 2f) + + fun drawHandle(cx: Float, row: Int) { + val cornerY = contentPadding + (row + 1) * cellHeightPx + val cy = handleCenterY(row) + canvas.drawRect(cx - stemWidth / 2f, cornerY, cx + stemWidth / 2f, cy, handlePaint) + canvas.drawCircle(cx, cy, radius, handlePaint) + } + + drawHandle(handleCenterX(selectionStartCol, true), selectionStartRow) + drawHandle(handleCenterX(selectionEndCol, false), selectionEndRow) + } + + private fun blend(foreground: Int, background: Int, amount: Float): Int { + val inverseAmount = 1f - amount + return Color.rgb( + (Color.red(foreground) * amount + Color.red(background) * inverseAmount).toInt(), + (Color.green(foreground) * amount + Color.green(background) * inverseAmount).toInt(), + (Color.blue(foreground) * amount + Color.blue(background) * inverseAmount).toInt(), + ) + } + + private inner class TerminalGestureListener : GestureDetector.SimpleOnGestureListener() { + override fun onDown(event: MotionEvent): Boolean { + scroller.forceFinished(true) + removeCallbacks(flingRunnable) + onRequestKeyboard?.invoke() + return true + } + + override fun onSingleTapUp(event: MotionEvent): Boolean { + if (selectionActive) { + clearSelection() + } else { + performClick() + } + return true + } + + override fun onLongPress(event: MotionEvent) { + startWordSelection(event.x, event.y) + } + + override fun onScroll( + first: MotionEvent?, + current: MotionEvent, + distanceX: Float, + distanceY: Float + ): Boolean { + scrollRemainder += distanceY / cellHeightPx + val rows = scrollRemainder.toInt() + if (rows != 0) { + scrollRemainder -= rows + onScrollRows?.invoke(rows) + } + return true + } + + override fun onFling( + first: MotionEvent?, + current: MotionEvent, + velocityX: Float, + velocityY: Float + ): Boolean { + flingLastY = 0 + scroller.fling(0, 0, 0, velocityY.toInt(), 0, 0, Int.MIN_VALUE / 2, Int.MAX_VALUE / 2) + postOnAnimation(flingRunnable) + return true + } + } +} diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalFrame.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalFrame.kt new file mode 100644 index 0000000000..2234d628e0 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalFrame.kt @@ -0,0 +1,82 @@ +package expo.modules.t3terminal + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +internal data class TerminalFrame( + val cols: Int, + val rows: Int, + val cursorX: Int, + val cursorY: Int, + val cursorVisible: Boolean, + val cursorStyle: Int, + val cursorBlinking: Boolean, + val foreground: Int, + val background: Int, + val cursorColor: Int, + val cellForegrounds: IntArray, + val cellBackgrounds: IntArray, + val cellFlags: IntArray, + val cellText: Array +) { + companion object { + private const val MAGIC = 0x54563354 + private const val VERSION = 1 + private const val HEADER_BYTES = 32 + private const val CELL_HEADER_BYTES = 12 + + @Suppress("ReturnCount") + fun decode(bytes: ByteArray): TerminalFrame? { + if (bytes.size < HEADER_BYTES) return null + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + if (buffer.int != MAGIC || buffer.short.toInt() != VERSION) return null + + val cols = buffer.short.toInt() and 0xFFFF + val rows = buffer.short.toInt() and 0xFFFF + val cursorX = buffer.short.toInt() and 0xFFFF + val cursorY = buffer.short.toInt() and 0xFFFF + val cursorVisible = buffer.get().toInt() != 0 + val cursorStyle = buffer.get().toInt() and 0xFF + val cursorBlinking = buffer.get().toInt() != 0 + buffer.get() + val foreground = buffer.int + val background = buffer.int + val cursorColor = buffer.int + val cellCount = cols * rows + val foregrounds = IntArray(cellCount) + val backgrounds = IntArray(cellCount) + val flags = IntArray(cellCount) + val text = Array(cellCount) { "" } + + for (index in 0 until cellCount) { + if (buffer.remaining() < CELL_HEADER_BYTES) return null + foregrounds[index] = buffer.int + backgrounds[index] = buffer.int + flags[index] = buffer.short.toInt() and 0xFFFF + val textLength = buffer.short.toInt() and 0xFFFF + if (buffer.remaining() < textLength) return null + if (textLength > 0) { + text[index] = String(bytes, buffer.position(), textLength, Charsets.UTF_8) + buffer.position(buffer.position() + textLength) + } + } + + return TerminalFrame( + cols = cols, + rows = rows, + cursorX = cursorX, + cursorY = cursorY, + cursorVisible = cursorVisible, + cursorStyle = cursorStyle, + cursorBlinking = cursorBlinking, + foreground = foreground, + background = background, + cursorColor = cursorColor, + cellForegrounds = foregrounds, + cellBackgrounds = backgrounds, + cellFlags = flags, + cellText = text, + ) + } + } +} diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so new file mode 100755 index 0000000000..e086ca8315 Binary files /dev/null and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/arm64-v8a/libghostty-vt.so differ diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so new file mode 100755 index 0000000000..5592142ffc Binary files /dev/null and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/armeabi-v7a/libghostty-vt.so differ diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so new file mode 100755 index 0000000000..bacab79083 Binary files /dev/null and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86/libghostty-vt.so differ diff --git a/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so new file mode 100755 index 0000000000..f6e0b646a2 Binary files /dev/null and b/apps/mobile/modules/t3-terminal/android/src/main/jniLibs/x86_64/libghostty-vt.so differ diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift index 8f35bcc3aa..f68cc6b4a1 100644 --- a/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift +++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift @@ -4,6 +4,12 @@ public class T3TerminalModule: Module { public func definition() -> ModuleDefinition { Name("T3TerminalSurface") + // 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": 3, + ]) + View(T3TerminalView.self) { Prop("terminalKey") { (view: T3TerminalView, terminalKey: String) in view.terminalKey = terminalKey @@ -17,6 +23,14 @@ public class T3TerminalModule: Module { view.fontSize = CGFloat(fontSize) } + Prop("focusRequest") { (view: T3TerminalView, focusRequest: Double) in + view.focusRequest = focusRequest + } + + Prop("autoFocus") { (view: T3TerminalView, autoFocus: Bool) in + view.autoFocus = autoFocus + } + Prop("appearanceScheme") { (view: T3TerminalView, appearanceScheme: String) in view.appearanceScheme = appearanceScheme } diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift index 685c2642a1..659837fc7a 100644 --- a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift +++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift @@ -22,13 +22,144 @@ private enum GhosttyRuntime { } } +/// Encodes hardware-keyboard combos that UITextField never surfaces through its +/// text-editing delegate (control combos, Escape, Tab, arrow keys) into the byte +/// sequences a terminal expects. +/// +/// Capture uses UIKeyCommand with `wantsPriorityOverSystemBehavior` rather than +/// `pressesBegan`: while a text field is first responder, iPadOS routes hardware key +/// events through the text-input system, which can consume presses before they reach +/// responder press callbacks. Registered key commands are matched deterministically +/// before that happens. +private enum TerminalHardwareKeyEncoder { + /// Characters that produce a control byte when combined with Ctrl. + private static let controlInputs = "abcdefghijklmnopqrstuvwxyz@[\\]^_-? " + + static func makeKeyCommands(action: Selector) -> [UIKeyCommand] { + var commands: [UIKeyCommand] = [] + + let specialInputs = [ + UIKeyCommand.inputEscape, + UIKeyCommand.inputUpArrow, + UIKeyCommand.inputDownArrow, + UIKeyCommand.inputLeftArrow, + UIKeyCommand.inputRightArrow, + "\t", + ] + for input in specialInputs { + commands.append(makeCommand(input: input, modifierFlags: [], action: action)) + } + commands.append(makeCommand(input: "\t", modifierFlags: .shift, action: action)) + + for character in controlInputs { + commands.append(makeCommand(input: String(character), modifierFlags: .control, action: action)) + commands.append( + makeCommand(input: String(character), modifierFlags: [.control, .shift], action: action) + ) + } + + return commands + } + + private static func makeCommand( + input: String, + modifierFlags: UIKeyModifierFlags, + action: Selector + ) -> UIKeyCommand { + let command = UIKeyCommand(input: input, modifierFlags: modifierFlags, action: action) + command.wantsPriorityOverSystemBehavior = true + return command + } + + static func sequence(input: String, modifiers: UIKeyModifierFlags) -> String? { + switch input { + case UIKeyCommand.inputEscape: + return "\u{1B}" + case UIKeyCommand.inputUpArrow: + return "\u{1B}[A" + case UIKeyCommand.inputDownArrow: + return "\u{1B}[B" + case UIKeyCommand.inputRightArrow: + return "\u{1B}[C" + case UIKeyCommand.inputLeftArrow: + return "\u{1B}[D" + case "\t": + return modifiers.contains(.shift) ? "\u{1B}[Z" : "\t" + default: + break + } + + guard modifiers.contains(.control) else { return nil } + guard let scalar = input.lowercased().unicodeScalars.first else { return nil } + return controlSequence(for: scalar) + } + + private static func controlSequence(for scalar: Unicode.Scalar) -> String? { + switch scalar { + case "a"..."z": + // Ctrl+A..Z -> 0x01..0x1A (Ctrl+C = ETX, Ctrl+Z = SUB, ...). + return UnicodeScalar(scalar.value - 96).map(String.init) + case " ", "@": + return "\u{00}" + case "[": + return "\u{1B}" + case "\\": + return "\u{1C}" + case "]": + return "\u{1D}" + case "^": + return "\u{1E}" + case "_", "-": + return "\u{1F}" + case "?": + return "\u{7F}" + default: + return nil + } + } +} + +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)? + + private static let hardwareKeyCommands = TerminalHardwareKeyEncoder.makeKeyCommands( + action: #selector(handleHardwareKeyCommand(_:)) + ) + + override var keyCommands: [UIKeyCommand]? { + Self.hardwareKeyCommands + } override func deleteBackward() { onDeleteBackward?() super.deleteBackward() } + + @objc + private func handleHardwareKeyCommand(_ command: UIKeyCommand) { + guard let input = command.input else { return } + guard let sequence = TerminalHardwareKeyEncoder.sequence( + input: input, + modifiers: command.modifierFlags + ) else { return } + onInsert?(sequence) + } } private enum TerminalAppearanceScheme: String { @@ -108,6 +239,26 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate { } } + var focusRequest: Double = 0 { + didSet { + guard oldValue != focusRequest else { return } + DispatchQueue.main.async { [weak self] in + self?.requestKeyboardFocus() + } + } + } + + 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 } @@ -167,6 +318,9 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate { inputField.onDeleteBackward = { [weak self] in self?.emitInput("\u{7F}") } + inputField.onInsert = { [weak self] data in + self?.emitInput(data) + } focusTapGesture.addTarget(self, action: #selector(handleViewportTap)) terminalViewport.addGestureRecognizer(focusTapGesture) @@ -216,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() } @@ -224,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 } @@ -232,7 +388,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate { } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { - emitInput("\n") + emitInput(TerminalInputSequence.carriageReturn) textField.text = "" return false } diff --git a/apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh b/apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh new file mode 100755 index 0000000000..7b9aa9b6dc --- /dev/null +++ b/apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh @@ -0,0 +1,152 @@ +#!/usr/bin/env bash + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +MODULE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" +VENDOR_DIR="${MODULE_DIR}/Vendor/libghostty-vt" +PATCH_DIR="${SCRIPT_DIR}/libghostty-android-patches" + +GHOSTTY_REVISION="${GHOSTTY_REVISION:-9f62873bf195e4d8a762d768a1405a5f2f7b1697}" +GHOSTTY_SOURCE_DIR="${GHOSTTY_SOURCE_DIR:-${HOME}/.cache/t3code/ghostty-${GHOSTTY_REVISION:0:8}}" +GHOSTTY_ZIG_VERSION="${GHOSTTY_ZIG_VERSION:-0.15.2}" +GHOSTTY_ZIG="${GHOSTTY_ZIG:-}" +ANDROID_NDK_HOME="${ANDROID_NDK_HOME:-}" + +log() { + printf '[libghostty-vt-android] %s\n' "$*" +} + +die() { + printf '[libghostty-vt-android] error: %s\n' "$*" >&2 + exit 1 +} + +require_cmd() { + command -v "$1" >/dev/null 2>&1 || die "missing required command: $1" +} + +ensure_zig() { + if [[ -n "${GHOSTTY_ZIG}" ]]; then + [[ -x "${GHOSTTY_ZIG}" ]] || die "GHOSTTY_ZIG is not executable: ${GHOSTTY_ZIG}" + return + fi + if command -v zig >/dev/null 2>&1 && [[ "$(zig version)" == "${GHOSTTY_ZIG_VERSION}" ]]; then + GHOSTTY_ZIG="$(command -v zig)" + return + fi + + local host_os host_arch cache_dir + host_os="$(uname -s | tr '[:upper:]' '[:lower:]')" + host_arch="$(uname -m)" + case "${host_os}" in + darwin) host_os="macos" ;; + linux) ;; + *) die "unsupported host OS for Zig download: ${host_os}" ;; + esac + case "${host_arch}" in + arm64) host_arch="aarch64" ;; + aarch64 | x86_64) ;; + *) die "unsupported host architecture for Zig download: ${host_arch}" ;; + esac + + cache_dir="${HOME}/.cache/t3code/zig-${GHOSTTY_ZIG_VERSION}" + GHOSTTY_ZIG="${cache_dir}/zig" + if [[ -x "${GHOSTTY_ZIG}" ]]; then + return + fi + + require_cmd curl + require_cmd tar + mkdir -p "${cache_dir}" + log "downloading Zig ${GHOSTTY_ZIG_VERSION}" + curl -fsSL \ + "https://ziglang.org/download/${GHOSTTY_ZIG_VERSION}/zig-${host_arch}-${host_os}-${GHOSTTY_ZIG_VERSION}.tar.xz" \ + | tar -xJ --strip-components=1 -C "${cache_dir}" +} + +ensure_ghostty_source() { + if [[ ! -d "${GHOSTTY_SOURCE_DIR}/.git" ]]; then + require_cmd git + log "cloning Ghostty ${GHOSTTY_REVISION}" + git clone --filter=blob:none --no-checkout https://github.com/ghostty-org/ghostty.git \ + "${GHOSTTY_SOURCE_DIR}" + git -C "${GHOSTTY_SOURCE_DIR}" fetch --depth=1 origin "${GHOSTTY_REVISION}" + git -C "${GHOSTTY_SOURCE_DIR}" checkout --detach "${GHOSTTY_REVISION}" + fi + + local actual_revision + actual_revision="$(git -C "${GHOSTTY_SOURCE_DIR}" rev-parse HEAD)" + [[ "${actual_revision}" == "${GHOSTTY_REVISION}" ]] || \ + die "expected Ghostty ${GHOSTTY_REVISION}, found ${actual_revision}" +} + +apply_ghostty_patches() { + [[ -d "${PATCH_DIR}" ]] || return + + local patch_file patch_name + for patch_file in "${PATCH_DIR}"/*.patch; do + [[ -e "${patch_file}" ]] || continue + patch_name="$(basename "${patch_file}")" + if git -C "${GHOSTTY_SOURCE_DIR}" apply --reverse --check "${patch_file}" >/dev/null 2>&1; then + log "patch already applied: ${patch_name}" + continue + fi + log "applying patch: ${patch_name}" + git -C "${GHOSTTY_SOURCE_DIR}" apply --check "${patch_file}" + git -C "${GHOSTTY_SOURCE_DIR}" apply "${patch_file}" + done +} + +if [[ -z "${ANDROID_NDK_HOME}" ]]; then + die "ANDROID_NDK_HOME must point to an installed Android NDK" +fi +[[ -d "${ANDROID_NDK_HOME}" ]] || die "Android NDK not found: ${ANDROID_NDK_HOME}" + +ensure_zig +ensure_ghostty_source +apply_ghostty_patches + +strip_tool="${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt" +strip_tool="$(find "${strip_tool}" -path '*/bin/llvm-strip' -print -quit)" +[[ -x "${strip_tool}" ]] || die "llvm-strip not found under ${ANDROID_NDK_HOME}" + +targets=( + "arm64-v8a:aarch64-linux-android" + "armeabi-v7a:arm-linux-androideabi" + "x86:x86-linux-android" + "x86_64:x86_64-linux-android" +) + +build_root="$(mktemp -d)" +trap 'rm -rf "${build_root}"' EXIT +mkdir -p "${VENDOR_DIR}/include" + +for entry in "${targets[@]}"; do + abi="${entry%%:*}" + target="${entry#*:}" + prefix="${build_root}/${abi}" + log "building ${abi} (${target})" + ( + cd "${GHOSTTY_SOURCE_DIR}" + ANDROID_NDK_HOME="${ANDROID_NDK_HOME}" "${GHOSTTY_ZIG}" build \ + -Demit-lib-vt \ + -Dtarget="${target}" \ + -Doptimize=ReleaseFast \ + -Dstrip=true \ + -Dsimd=false \ + -p "${prefix}" + ) + + mkdir -p "${MODULE_DIR}/android/src/main/jniLibs/${abi}" + cp "${prefix}/lib/libghostty-vt.so.0.1.0" \ + "${MODULE_DIR}/android/src/main/jniLibs/${abi}/libghostty-vt.so" + "${strip_tool}" --strip-unneeded \ + "${MODULE_DIR}/android/src/main/jniLibs/${abi}/libghostty-vt.so" +done + +rm -rf "${VENDOR_DIR}/include/ghostty" +cp -R "${build_root}/arm64-v8a/include/ghostty" "${VENDOR_DIR}/include/ghostty" +cp "${GHOSTTY_SOURCE_DIR}/LICENSE" "${VENDOR_DIR}/LICENSE" +printf '%s\n' "${GHOSTTY_REVISION}" > "${VENDOR_DIR}/VERSION" +log "done" diff --git a/apps/mobile/modules/t3-terminal/scripts/libghostty-android-patches/0001-link-android-libvt-with-libc.patch b/apps/mobile/modules/t3-terminal/scripts/libghostty-android-patches/0001-link-android-libvt-with-libc.patch new file mode 100644 index 0000000000..2713eb739a --- /dev/null +++ b/apps/mobile/modules/t3-terminal/scripts/libghostty-android-patches/0001-link-android-libvt-with-libc.patch @@ -0,0 +1,25 @@ +diff --git a/src/build/GhosttyZig.zig b/src/build/GhosttyZig.zig +index 44c300e15..f8d4296a2 100644 +--- a/src/build/GhosttyZig.zig ++++ b/src/build/GhosttyZig.zig +@@ -123,7 +123,7 @@ fn initVt( + // no-libcxx mode (HWY_NO_LIBCXX / SIMDUTF_NO_LIBCXX) so we + // don't need libcpp. System-provided simdutf headers still + // use C++ stdlib headers, so we need libcpp in that case. +- .link_libc = if (cfg.simd) true else null, ++ .link_libc = if (cfg.simd or cfg.target.result.abi.isAndroid()) true else null, + .link_libcpp = if (cfg.simd and + b.systemIntegrationOption("simdutf", .{}) and + cfg.target.result.abi != .msvc) true else null, +diff --git a/src/terminal/c/sys.zig b/src/terminal/c/sys.zig +index c4b2b17f2..afb98ed4b 100644 +--- a/src/terminal/c/sys.zig ++++ b/src/terminal/c/sys.zig +@@ -227,6 +227,7 @@ pub fn logStderr( + message_len: usize, + ) callconv(lib.calling_conv) void { + if (comptime builtin.target.cpu.arch.isWasm()) return; ++ if (comptime builtin.target.abi.isAndroid()) return; + + const scope = scope_ptr[0..scope_len]; + const message = message_ptr[0..message_len]; diff --git a/apps/mobile/modules/t3-terminal/scripts/libghostty-android-patches/0002-align-android-libvt-to-16kb-pages.patch b/apps/mobile/modules/t3-terminal/scripts/libghostty-android-patches/0002-align-android-libvt-to-16kb-pages.patch new file mode 100644 index 0000000000..2fdffd2ccb --- /dev/null +++ b/apps/mobile/modules/t3-terminal/scripts/libghostty-android-patches/0002-align-android-libvt-to-16kb-pages.patch @@ -0,0 +1,11 @@ +diff --git a/src/build/GhosttyLibVt.zig b/src/build/GhosttyLibVt.zig +--- a/src/build/GhosttyLibVt.zig ++++ b/src/build/GhosttyLibVt.zig +@@ -236,6 +236,7 @@ fn initLib( + if (lib.rootModuleTarget().abi.isAndroid()) { + // Support 16kb page sizes, required for Android 15+. ++ lib.link_z_common_page_size = 16384; // 16kb + lib.link_z_max_page_size = 16384; // 16kb + + try @import("android_ndk").addPaths(b, lib); + } diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 963cefd6b7..c99351547b 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -5,13 +5,16 @@ "main": "index.ts", "scripts": { "dev": "expo start --clear", - "dev:client": "APP_VARIANT=development expo start --dev-client --clear", + "dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear --lan", + "dev:client:preview": "eas env:exec preview 'EXPO_NO_DOTENV=1 APP_VARIANT=preview expo start --dev-client --scheme t3code-preview --clear --lan'", "start": "expo start", "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 && 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", "android:prod": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android", "eas:android:dev": "eas build --profile development -p android", @@ -22,6 +25,7 @@ "ios:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios", "ios:preview": "APP_VARIANT=preview EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios", "ios:prod": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios", + "ios:release": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios --configuration Release --no-bundler", "eas:ios:dev": "eas build --profile development -p ios", "eas:ios:preview": "eas build --profile preview -p ios", "eas:ios:preview:dev": "eas build --profile preview:dev -p ios", @@ -43,12 +47,16 @@ "@clerk/expo": "catalog:", "@effect/atom-react": "catalog:", "@expo-google-fonts/dm-sans": "^0.4.2", - "@expo/ui": "~56.0.8", + "@expo/metro-runtime": "~56.0.15", + "@expo/ui": "~56.0.18", "@legendapp/list": "3.2.0", "@noble/curves": "catalog:", "@noble/hashes": "catalog:", "@pierre/diffs": "catalog:", "@react-native-menu/menu": "^2.0.0", + "@react-navigation/elements": "2.9.26", + "@react-navigation/native": "7.3.4", + "@react-navigation/native-stack": "7.17.6", "@shikijs/core": "4.2.0", "@shikijs/engine-javascript": "4.2.0", "@shikijs/langs": "4.2.0", @@ -59,41 +67,46 @@ "@t3tools/mobile-review-diff-native": "file:./modules/t3-review-diff", "@t3tools/mobile-terminal-native": "file:./modules/t3-terminal", "@t3tools/shared": "workspace:*", + "@tabler/icons-react-native": "^3.44.0", "clsx": "^2.1.1", "diff": "8.0.3", "effect": "catalog:", - "expo": "^56.0.0", - "expo-asset": "~56.0.15", - "expo-auth-session": "~56.0.12", - "expo-build-properties": "~56.0.15", - "expo-camera": "~56.0.7", - "expo-clipboard": "~56.0.3", - "expo-constants": "~56.0.16", + "expo": "~56.0.12", + "expo-asset": "~56.0.17", + "expo-auth-session": "~56.0.14", + "expo-blur": "~56.0.3", + "expo-build-properties": "~56.0.19", + "expo-camera": "~56.0.8", + "expo-clipboard": "~56.0.4", + "expo-constants": "~56.0.18", "expo-crypto": "~56.0.4", - "expo-dev-client": "~56.0.16", - "expo-file-system": "~56.0.7", - "expo-font": "~56.0.5", + "expo-dev-client": "~56.0.20", + "expo-file-system": "~56.0.8", + "expo-font": "~56.0.7", "expo-glass-effect": "~56.0.4", "expo-haptics": "~56.0.3", - "expo-image-picker": "~56.0.14", - "expo-linking": "~56.0.12", + "expo-image": "~56.0.11", + "expo-image-picker": "~56.0.18", + "expo-linking": "~56.0.14", "expo-network": "~56.0.5", - "expo-notifications": "~56.0.14", + "expo-notifications": "~56.0.18", "expo-paste-input": "^0.1.15", - "expo-router": "~56.2.7", + "expo-quick-actions": "^6.0.2", "expo-secure-store": "~56.0.4", + "expo-sharing": "~56.0.18", "expo-splash-screen": "~56.0.10", - "expo-symbols": "~56.0.5", - "expo-updates": "~56.0.17", + "expo-sqlite": "~56.0.5", + "expo-symbols": "~56.0.6", + "expo-updates": "~56.0.19", "expo-web-browser": "~56.0.5", - "expo-widgets": "~56.0.15", + "expo-widgets": "~56.0.19", "punycode": "^2.3.1", "react": "19.2.3", "react-dom": "19.2.3", "react-native": "0.85.3", "react-native-gesture-handler": "~2.31.1", "react-native-image-viewing": "^0.2.2", - "react-native-keyboard-controller": "1.21.7", + "react-native-keyboard-controller": "1.21.13", "react-native-nitro-markdown": "^0.5.0", "react-native-nitro-modules": "0.35.9", "react-native-reanimated": "4.3.1", @@ -117,5 +130,13 @@ }, "overrides": { "react-native-nitro-markdown": "file:deps/react-native-nitro-markdown-0.5.0.tgz" + }, + "expo": { + "autolinking": { + "buildFromSource": [ + "react-native-screens", + "@react-native-menu/menu" + ] + } } } diff --git a/apps/mobile/plugins/lib/addWidgetAssetCatalog.cjs b/apps/mobile/plugins/lib/addWidgetAssetCatalog.cjs new file mode 100644 index 0000000000..817b7b9f6a --- /dev/null +++ b/apps/mobile/plugins/lib/addWidgetAssetCatalog.cjs @@ -0,0 +1,81 @@ +"use strict"; + +// Bundle the widget asset catalog into an app-extension (widget) target. +// +// expo-widgets generates the widget target without a Resources build phase, and +// hand-adding a PBXResourcesBuildPhase does NOT get picked up — xcodebuild's +// planner never schedules `actool` for it (verified: even a full re-plan skips +// it). So instead we add a shell-script phase that runs `actool` directly and +// drops the compiled Assets.car into the extension bundle. Marked +// alwaysOutOfDate so the build system always runs it. +// +// Idempotent across re-runs. Returns true when it added the phase, false when +// it was already present. Throws when the target does not exist — that means +// this ran before expo-widgets created the target (plugin ordering bug) and +// silently skipping would ship a widget without its assets. + +const PHASE_NAME = "Compile Widget Assets"; + +// Compiles ExpoWidgetsTarget/Assets.xcassets into the extension's resources dir. +// Uses only Xcode-provided build settings so it works for device + simulator. +const ACTOOL_SCRIPT = [ + "set -e", + 'CATALOG="${SRCROOT}/ExpoWidgetsTarget/Assets.xcassets"', + 'if [ ! -d "$CATALOG" ]; then', + ' echo "error: widget asset catalog not found at $CATALOG (expo-widgets wiped it? check plugin ordering in app.config.ts)"', + " exit 1", + "fi", + 'DEST="${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"', + 'mkdir -p "$DEST"', + 'xcrun actool "$CATALOG" --compile "$DEST" --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET:-16.0}" --output-format human-readable-text', +].join("\n"); + +function stripComments(map) { + const out = {}; + for (const key of Object.keys(map || {})) { + if (key.endsWith("_comment")) continue; + out[key] = map[key]; + } + return out; +} + +function findByName(map, name) { + for (const [uuid, value] of Object.entries(stripComments(map))) { + if (value && value.name === name) return { uuid, value }; + } + return null; +} + +/** + * @param {import('xcode').XcodeProject} proj + * @param {{ targetName: string }} opts + */ +function addWidgetAssetCatalog(proj, opts) { + const objects = proj.hash.project.objects; + const target = findByName(objects.PBXNativeTarget, opts.targetName); + if (!target) { + throw new Error( + `addWidgetAssetCatalog: target "${opts.targetName}" not found — ` + + "withWidgetLogoAsset must be registered before expo-widgets so its " + + "xcodeproj mod runs after the widget target is created.", + ); + } + + const phases = target.value.buildPhases || []; + const existing = objects.PBXShellScriptBuildPhase || {}; + const already = Object.entries(stripComments(existing)).some( + ([uuid, value]) => + value && value.name === `"${PHASE_NAME}"` && phases.some((p) => p.value === uuid), + ); + if (already) return false; + + const { uuid } = proj.addBuildPhase([], "PBXShellScriptBuildPhase", PHASE_NAME, target.uuid, { + shellPath: "/bin/sh", + shellScript: ACTOOL_SCRIPT, + }); + // Always run: input-analysis is exactly what skipped the Resources phase. + objects.PBXShellScriptBuildPhase[uuid].alwaysOutOfDate = 1; + return true; +} + +module.exports = { addWidgetAssetCatalog }; diff --git a/apps/mobile/plugins/withAndroidGradleHeap.cjs b/apps/mobile/plugins/withAndroidGradleHeap.cjs new file mode 100644 index 0000000000..0ec26507d5 --- /dev/null +++ b/apps/mobile/plugins/withAndroidGradleHeap.cjs @@ -0,0 +1,22 @@ +const { withGradleProperties } = require("expo/config-plugins"); + +// The Expo template's 2GB heap is too small for D8 dex merging in this app, +// causing OutOfMemoryError in :app:mergeExtDexDebug. +const JVM_ARGS = "-Xmx4096m -XX:MaxMetaspaceSize=1024m"; + +module.exports = function withAndroidGradleHeap(config) { + return withGradleProperties(config, (nextConfig) => { + const properties = nextConfig.modResults.filter( + (item) => !(item.type === "property" && item.key === "org.gradle.jvmargs"), + ); + + properties.push({ + type: "property", + key: "org.gradle.jvmargs", + value: JVM_ARGS, + }); + + nextConfig.modResults = properties; + return nextConfig; + }); +}; diff --git a/apps/mobile/plugins/withAndroidModernAlertDialog.cjs b/apps/mobile/plugins/withAndroidModernAlertDialog.cjs new file mode 100644 index 0000000000..8c8b2b8000 --- /dev/null +++ b/apps/mobile/plugins/withAndroidModernAlertDialog.cjs @@ -0,0 +1,188 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const { + AndroidConfig, + withAndroidColors, + withAndroidColorsNight, + withAndroidStyles, + withDangerousMod, +} = require("expo/config-plugins"); + +// React Native's Alert renders an AppCompat AlertDialog on Android, which +// inherits the dated framework dialog chrome (square gray panel, teal +// all-caps buttons) from the app theme. These resources restyle it with the +// app's uniwind tokens from global.css: --color-card panel, --color-foreground +// text, --color-primary buttons, DM Sans type. The @font resources referenced +// here are embedded by the expo-font plugin config in app.config.ts. + +// AppCompat's default dialog window background is an inset rounded rect, so +// the replacement keeps the same 16dp inset to preserve the dialog's margins. +const DIALOG_BACKGROUND_DRAWABLE = ` + + + + + + +`; + +const COLORS = { + light: { + background: "#FFFFFF", // --color-card + text: "#262626", // --color-foreground + secondaryText: "#525252", // --color-foreground-secondary + buttonText: "#262626", // --color-primary + }, + night: { + background: "#171717", + text: "#F5F5F5", + secondaryText: "#A3A3A3", + buttonText: "#F5F5F5", + }, +}; + +function assignStyleItem(style, name, value) { + style.item = style.item ?? []; + const existing = style.item.find((item) => item.$?.name === name); + if (existing) { + existing._ = value; + } else { + style.item.push({ _: value, $: { name } }); + } +} + +function withAlertDialogStyles(config) { + return withAndroidStyles(config, (config) => { + const resources = config.modResults.resources; + resources.style = resources.style ?? []; + + const appTheme = resources.style.find((style) => style.$?.name === "AppTheme"); + if (appTheme) { + // React Native's dialog module builds an androidx.appcompat AlertDialog, + // which resolves its theme from the AppCompat attr; the framework attr is + // set too for any native code that inflates a platform AlertDialog. + assignStyleItem(appTheme, "alertDialogTheme", "@style/AppAlertDialog"); + assignStyleItem(appTheme, "android:alertDialogTheme", "@style/AppAlertDialog"); + } + + resources.style = resources.style.filter( + (style) => + !["AppAlertDialog", "AppAlertDialog.Title", "AppAlertDialog.Button"].includes( + style.$?.name, + ), + ); + resources.style.push( + { + $: { name: "AppAlertDialog", parent: "ThemeOverlay.AppCompat.Dialog.Alert" }, + item: [ + { _: "@drawable/alert_dialog_background", $: { name: "android:windowBackground" } }, + // The message body resolves textColorPrimary in AppCompat's alert + // layout; pointing it at the secondary token dims the message + // relative to the title, which keeps full-strength text via the + // explicit color in AppAlertDialog.Title. + { _: "@color/alert_dialog_secondary_text", $: { name: "android:textColorPrimary" } }, + { _: "@color/alert_dialog_secondary_text", $: { name: "android:textColorSecondary" } }, + // Theme-level fontFamily is the lowest-priority fallback in attribute + // resolution, so it reaches every text view in the dialog that does + // not carry its own fontFamily (the message body in particular). + { _: "@font/xml_dm_sans_regular", $: { name: "android:fontFamily" } }, + // AppCompat's alert title view styles itself from the framework + // attr (?android:attr/windowTitleStyle); there is no unprefixed + // AppCompat equivalent. + { _: "@style/AppAlertDialog.Title", $: { name: "android:windowTitleStyle" } }, + { _: "@style/AppAlertDialog.Button", $: { name: "buttonBarPositiveButtonStyle" } }, + { _: "@style/AppAlertDialog.Button", $: { name: "buttonBarNegativeButtonStyle" } }, + { _: "@style/AppAlertDialog.Button", $: { name: "buttonBarNeutralButtonStyle" } }, + ], + }, + { + $: { name: "AppAlertDialog.Title", parent: "RtlOverlay.DialogWindowTitle.AppCompat" }, + item: [ + { _: "@font/dm_sans_500medium", $: { name: "android:fontFamily" } }, + { _: "18sp", $: { name: "android:textSize" } }, + { _: "@color/alert_dialog_text", $: { name: "android:textColor" } }, + ], + }, + { + $: { + name: "AppAlertDialog.Button", + parent: "Widget.AppCompat.Button.ButtonBar.AlertDialog", + }, + item: [ + // The AppCompat button appearance hardcodes sans-serif-medium, so + // the font must be set here rather than relying on the theme + // fallback. + { _: "@font/dm_sans_500medium", $: { name: "android:fontFamily" } }, + { _: "@color/alert_dialog_button_text", $: { name: "android:textColor" } }, + { _: "false", $: { name: "android:textAllCaps" } }, + { _: "0", $: { name: "android:letterSpacing" } }, + ], + }, + ); + + return config; + }); +} + +function assignColors(colorsResource, palette) { + let result = colorsResource; + result = AndroidConfig.Colors.assignColorValue(result, { + name: "alert_dialog_background", + value: palette.background, + }); + result = AndroidConfig.Colors.assignColorValue(result, { + name: "alert_dialog_text", + value: palette.text, + }); + result = AndroidConfig.Colors.assignColorValue(result, { + name: "alert_dialog_secondary_text", + value: palette.secondaryText, + }); + result = AndroidConfig.Colors.assignColorValue(result, { + name: "alert_dialog_button_text", + value: palette.buttonText, + }); + return result; +} + +function withAlertDialogColors(config) { + config = withAndroidColors(config, (config) => { + config.modResults = assignColors(config.modResults, COLORS.light); + return config; + }); + config = withAndroidColorsNight(config, (config) => { + config.modResults = assignColors(config.modResults, COLORS.night); + return config; + }); + return config; +} + +function withAlertDialogBackgroundDrawable(config) { + return withDangerousMod(config, [ + "android", + async (config) => { + const drawableDir = path.join( + config.modRequest.platformProjectRoot, + "app", + "src", + "main", + "res", + "drawable", + ); + fs.mkdirSync(drawableDir, { recursive: true }); + fs.writeFileSync( + path.join(drawableDir, "alert_dialog_background.xml"), + DIALOG_BACKGROUND_DRAWABLE, + ); + return config; + }, + ]); +} + +module.exports = function withAndroidModernAlertDialog(config) { + return withAlertDialogBackgroundDrawable(withAlertDialogColors(withAlertDialogStyles(config))); +}; diff --git a/apps/mobile/plugins/withAndroidModernPopupMenu.cjs b/apps/mobile/plugins/withAndroidModernPopupMenu.cjs new file mode 100644 index 0000000000..68409cbd0f --- /dev/null +++ b/apps/mobile/plugins/withAndroidModernPopupMenu.cjs @@ -0,0 +1,250 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const { + AndroidConfig, + withAndroidColors, + withAndroidColorsNight, + withAndroidStyles, + withDangerousMod, +} = require("expo/config-plugins"); + +// @react-native-menu/menu renders an AppCompat PopupMenu on Android, which +// inherits the dated default popup chrome from the app theme. These resources +// restyle it to match the app palette (global.css --color-card / --color-foreground) +// with rounded corners, and anchor it below the button instead of overlapping it. + +const POPUP_BACKGROUND_DRAWABLE = ` + + + + +`; + +// Checkable menu rows insert a CheckBox at the row's right edge; the theme +// swaps its square-box button for this check glyph so the selected option +// shows a plain right-aligned check. +const CHECK_DRAWABLE = ` + + + +`; + +// CheckBox button drawable: check glyph when selected, nothing otherwise. +const CHECKBOX_BUTTON_SELECTOR = ` + + + + +`; + +// Replaces the default filled-triangle submenu indicator with a stroked ">" +// chevron. +const SUBMENU_ARROW_DRAWABLE = ` + + + +`; + +const COLORS = { + light: { background: "#F7F7F7", itemText: "#262626" }, + night: { background: "#161616", itemText: "#F5F5F5" }, +}; + +function assignStyleItem(style, name, value) { + style.item = style.item ?? []; + const existing = style.item.find((item) => item.$?.name === name); + if (existing) { + existing._ = value; + } else { + style.item.push({ _: value, $: { name } }); + } +} + +function withPopupMenuStyles(config) { + return withAndroidStyles(config, (config) => { + const resources = config.modResults.resources; + resources.style = resources.style ?? []; + + const appTheme = resources.style.find((style) => style.$?.name === "AppTheme"); + if (appTheme) { + assignStyleItem(appTheme, "popupMenuStyle", "@style/AppPopupMenu"); + assignStyleItem(appTheme, "android:popupMenuStyle", "@style/AppPopupMenu"); + assignStyleItem( + appTheme, + "textAppearanceLargePopupMenu", + "@style/AppPopupMenu.TextAppearance", + ); + assignStyleItem( + appTheme, + "textAppearanceSmallPopupMenu", + "@style/AppPopupMenu.TextAppearance", + ); + // Submenu popups show their parent item as a header row that reads a + // separate theme attribute, so it needs the same themed text color. + assignStyleItem( + appTheme, + "textAppearancePopupMenuHeader", + "@style/AppPopupMenu.HeaderTextAppearance", + ); + // Menu item views resolve their submenu arrow from this style + // (android:listMenuViewStyle / android:subMenuArrow are public attrs). + assignStyleItem(appTheme, "android:listMenuViewStyle", "@style/AppPopupMenuListMenuView"); + // Checkable rows inflate a plain CheckBox at the row end; restyle its + // button so the selected option shows a right-aligned check glyph + // instead of a square box. Both framework and AppCompat attrs are set + // since the popup may inflate either CheckBox flavor. App-wide for + // native checkboxes, which the app otherwise doesn't use. + assignStyleItem(appTheme, "android:checkboxStyle", "@style/AppPopupMenuCheckBox"); + assignStyleItem(appTheme, "checkboxStyle", "@style/AppPopupMenuCheckBoxCompat"); + } + + resources.style = resources.style.filter( + (style) => + ![ + "AppPopupMenu", + "AppPopupMenu.TextAppearance", + "AppPopupMenu.HeaderTextAppearance", + "AppPopupMenuListMenuView", + "AppPopupMenuCheckBox", + "AppPopupMenuCheckBoxCompat", + ].includes(style.$?.name), + ); + resources.style.push( + { + $: { name: "AppPopupMenu", parent: "Widget.AppCompat.PopupMenu" }, + item: [ + { _: "@drawable/popup_menu_background", $: { name: "android:popupBackground" } }, + { _: "false", $: { name: "android:overlapAnchor" } }, + { _: "4dp", $: { name: "android:dropDownVerticalOffset" } }, + ], + }, + { + $: { name: "AppPopupMenu.TextAppearance", parent: "TextAppearance.AppCompat.Menu" }, + item: [ + { _: "15sp", $: { name: "android:textSize" } }, + { _: "@color/popup_menu_item_text", $: { name: "android:textColor" } }, + // DM Sans (--font-sans); embedded by the expo-font plugin config in + // app.config.ts. + { _: "@font/xml_dm_sans_regular", $: { name: "android:fontFamily" } }, + ], + }, + { + $: { + name: "AppPopupMenu.HeaderTextAppearance", + parent: "TextAppearance.AppCompat.Widget.PopupMenu.Header", + }, + item: [ + { _: "15sp", $: { name: "android:textSize" } }, + { _: "@color/popup_menu_item_text", $: { name: "android:textColor" } }, + { _: "@font/xml_dm_sans_regular", $: { name: "android:fontFamily" } }, + ], + }, + // The framework default (Widget.Material.ListMenuView) only carries + // subMenuArrow, so replacing the style wholesale is safe. + { + $: { name: "AppPopupMenuListMenuView" }, + item: [{ _: "@drawable/popup_menu_submenu_arrow", $: { name: "android:subMenuArrow" } }], + }, + { + $: { + name: "AppPopupMenuCheckBox", + parent: "android:Widget.Material.CompoundButton.CheckBox", + }, + item: [{ _: "@drawable/popup_menu_check_button", $: { name: "android:button" } }], + }, + { + $: { + name: "AppPopupMenuCheckBoxCompat", + parent: "Widget.AppCompat.CompoundButton.CheckBox", + }, + item: [ + { _: "@drawable/popup_menu_check_button", $: { name: "android:button" } }, + // buttonCompat wins over android:button in AppCompatCheckBox. + { _: "@drawable/popup_menu_check_button", $: { name: "buttonCompat" } }, + ], + }, + ); + + return config; + }); +} + +function withPopupMenuColors(config) { + config = withAndroidColors(config, (config) => { + config.modResults = AndroidConfig.Colors.assignColorValue(config.modResults, { + name: "popup_menu_background", + value: COLORS.light.background, + }); + config.modResults = AndroidConfig.Colors.assignColorValue(config.modResults, { + name: "popup_menu_item_text", + value: COLORS.light.itemText, + }); + return config; + }); + config = withAndroidColorsNight(config, (config) => { + config.modResults = AndroidConfig.Colors.assignColorValue(config.modResults, { + name: "popup_menu_background", + value: COLORS.night.background, + }); + config.modResults = AndroidConfig.Colors.assignColorValue(config.modResults, { + name: "popup_menu_item_text", + value: COLORS.night.itemText, + }); + return config; + }); + return config; +} + +function withPopupMenuBackgroundDrawable(config) { + return withDangerousMod(config, [ + "android", + async (config) => { + const drawableDir = path.join( + config.modRequest.platformProjectRoot, + "app", + "src", + "main", + "res", + "drawable", + ); + fs.mkdirSync(drawableDir, { recursive: true }); + fs.writeFileSync( + path.join(drawableDir, "popup_menu_background.xml"), + POPUP_BACKGROUND_DRAWABLE, + ); + fs.writeFileSync(path.join(drawableDir, "ic_menu_check.xml"), CHECK_DRAWABLE); + fs.writeFileSync( + path.join(drawableDir, "popup_menu_check_button.xml"), + CHECKBOX_BUTTON_SELECTOR, + ); + fs.writeFileSync( + path.join(drawableDir, "popup_menu_submenu_arrow.xml"), + SUBMENU_ARROW_DRAWABLE, + ); + return config; + }, + ]); +} + +module.exports = function withAndroidModernPopupMenu(config) { + return withPopupMenuBackgroundDrawable(withPopupMenuColors(withPopupMenuStyles(config))); +}; diff --git a/apps/mobile/plugins/withAndroidPredictiveBackCompat.cjs b/apps/mobile/plugins/withAndroidPredictiveBackCompat.cjs new file mode 100644 index 0000000000..0014ca053f --- /dev/null +++ b/apps/mobile/plugins/withAndroidPredictiveBackCompat.cjs @@ -0,0 +1,104 @@ +const { withMainActivity } = require("expo/config-plugins"); + +// predictiveBackGestureEnabled writes android:enableOnBackInvokedCallback="true", +// which retires the legacy KEYCODE_BACK/onBackPressed() delivery on Android 13+. +// From then on back gestures only reach the app through OnBackPressedDispatcher +// callbacks. react-native 0.85 registers its own always-enabled callback, but +// only on Android 16 with targetSdk 36 (ReactActivity's enforced-predictive-back +// workaround) — on Android 13-15 nothing is registered, the system consumes +// every back gesture itself, and JS back handling (React Navigation pops, +// BackHandler listeners) silently dies: each gesture just backgrounds the app. +// This plugin mirrors react-native's shim on API 33-35 so back keeps flowing +// to JS there. See https://github.com/software-mansion/react-native-screens/discussions/2540. + +const CALLBACK_PROPERTY = ` + // Routes predictive-back gestures to JS on Android 13-15, where react-native + // registers no OnBackPressedDispatcher callback of its own (it only does on + // Android 16+). Registered in onCreate; added by withAndroidPredictiveBackCompat. + private val predictiveBackCompatCallback = object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + isEnabled = false + onBackPressed() + isEnabled = true + } + } +`; + +const CALLBACK_REGISTRATION = ` + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && Build.VERSION.SDK_INT < Build.VERSION_CODES.BAKLAVA) { + onBackPressedDispatcher.addCallback(this, predictiveBackCompatCallback) + }`; + +// Wraps the template's invokeDefaultOnBackPressed: the default action ends in +// ComponentActivity.onBackPressed(), which re-enters the dispatcher — with the +// compat callback still enabled that would bounce back into JS forever instead +// of backgrounding the app. +const INVOKE_DEFAULT_WRAPPER = `override fun invokeDefaultOnBackPressed() { + predictiveBackCompatCallback.isEnabled = false + try { + invokeDefaultOnBackPressedLegacy() + } finally { + predictiveBackCompatCallback.isEnabled = true + } + } + + private fun invokeDefaultOnBackPressedLegacy() {`; + +function insertAfter(contents, anchor, insertion, description) { + const index = contents.indexOf(anchor); + if (index === -1) { + throw new Error( + `withAndroidPredictiveBackCompat: could not find ${description} in MainActivity — the Expo template changed; update the plugin anchors.`, + ); + } + const end = index + anchor.length; + return contents.slice(0, end) + insertion + contents.slice(end); +} + +module.exports = function withAndroidPredictiveBackCompat(config) { + if (config.android?.predictiveBackGestureEnabled !== true) { + return config; + } + + return withMainActivity(config, (nextConfig) => { + let contents = nextConfig.modResults.contents; + if (nextConfig.modResults.language !== "kt") { + throw new Error("withAndroidPredictiveBackCompat: MainActivity must be Kotlin."); + } + if (contents.includes("predictiveBackCompatCallback")) { + return nextConfig; + } + + contents = insertAfter( + contents, + "import android.os.Bundle", + "\nimport androidx.activity.OnBackPressedCallback", + "the android.os.Bundle import", + ); + contents = insertAfter( + contents, + "class MainActivity : ReactActivity() {", + CALLBACK_PROPERTY, + "the MainActivity class declaration", + ); + contents = insertAfter( + contents, + "super.onCreate(null)", + CALLBACK_REGISTRATION, + "the super.onCreate call", + ); + + if (!contents.includes("override fun invokeDefaultOnBackPressed() {")) { + throw new Error( + "withAndroidPredictiveBackCompat: could not find invokeDefaultOnBackPressed in MainActivity — the Expo template changed; update the plugin anchors.", + ); + } + contents = contents.replace( + "override fun invokeDefaultOnBackPressed() {", + INVOKE_DEFAULT_WRAPPER, + ); + + nextConfig.modResults.contents = contents; + return nextConfig; + }); +}; diff --git a/apps/mobile/plugins/withIosCocoaPodsUuidCache.cjs b/apps/mobile/plugins/withIosCocoaPodsUuidCache.cjs new file mode 100644 index 0000000000..e0de313bbd --- /dev/null +++ b/apps/mobile/plugins/withIosCocoaPodsUuidCache.cjs @@ -0,0 +1,52 @@ +const fs = require("node:fs"); +const path = require("node:path"); + +const { withDangerousMod } = require("expo/config-plugins"); + +const MARKER = "# t3code: repair cached CocoaPods UUID allocation before SPM integration"; +const UUID_REPAIR = `${MARKER} + pods_project = installer.pods_project + existing_uuids = pods_project.objects.map(&:uuid) + uuid_prefix = pods_project.instance_variable_get(:@uuid_prefix)[0, 6] + sequential_uuid = /\\A#{Regexp.escape(uuid_prefix)}([0-9A-F]{7})0\\z/ + highest_index = existing_uuids.filter_map do |uuid| + match = sequential_uuid.match(uuid) + match && match[1].to_i(16) + end.max || -1 + + # Pod::Project generates sequential UUIDs without collision checks because CocoaPods + # normally creates the project in this process. EAS can restore Pods.xcodeproj from + # cache, leaving the allocator behind the loaded objects. React Native's SPM support + # then reuses an existing UUID and silently corrupts the project graph. + next_index = highest_index + 1 + pods_project.instance_variable_set(:@generated_uuids, Array.new(next_index)) + pods_project.instance_variable_set(:@available_uuids, []) + pods_project.generate_available_uuid_list(1_000) + Pod::UI.puts "T3Code: reset CocoaPods UUID allocator at #{next_index} (#{existing_uuids.length} existing objects)" +`; + +module.exports = function withIosCocoaPodsUuidCache(config) { + return withDangerousMod(config, [ + "ios", + (nextConfig) => { + const podfilePath = path.join(nextConfig.modRequest.platformProjectRoot, "Podfile"); + const podfile = fs.readFileSync(podfilePath, "utf8"); + + if (podfile.includes(MARKER)) { + return nextConfig; + } + + const postInstallStart = "post_install do |installer|\n"; + if (!podfile.includes(postInstallStart)) { + throw new Error("Unable to repair CocoaPods UUID allocation: post_install is missing."); + } + + fs.writeFileSync( + podfilePath, + podfile.replace(postInstallStart, `${postInstallStart}${UUID_REPAIR}`), + "utf8", + ); + return nextConfig; + }, + ]); +}; diff --git a/apps/mobile/plugins/withIosSceneLifecycle.cjs b/apps/mobile/plugins/withIosSceneLifecycle.cjs new file mode 100644 index 0000000000..d426475250 --- /dev/null +++ b/apps/mobile/plugins/withIosSceneLifecycle.cjs @@ -0,0 +1,99 @@ +const { withAppDelegate, withInfoPlist } = require("expo/config-plugins"); + +const SCENE_DELEGATE = ` + +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + var window: UIWindow? + + func scene( + _ scene: UIScene, + willConnectTo session: UISceneSession, + options connectionOptions: UIScene.ConnectionOptions + ) { + guard + let windowScene = scene as? UIWindowScene, + let appDelegate = UIApplication.shared.delegate as? AppDelegate + else { + return + } + + let appWindow: UIWindow + if let existingWindow = appDelegate.window { + appWindow = existingWindow + } else { + appWindow = UIWindow(windowScene: windowScene) + appDelegate.window = appWindow + appDelegate.reactNativeFactory?.startReactNative( + withModuleName: "main", + in: appWindow, + launchOptions: nil) + } + + window = appWindow + appWindow.windowScene = windowScene + appWindow.makeKeyAndVisible() + + if let url = connectionOptions.urlContexts.first?.url { + _ = appDelegate.application(UIApplication.shared, open: url, options: [:]) + } + + if let userActivity = connectionOptions.userActivities.first { + _ = appDelegate.application( + UIApplication.shared, + continue: userActivity, + restorationHandler: { _ in }) + } + } + + func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { + guard + let url = URLContexts.first?.url, + let appDelegate = UIApplication.shared.delegate as? AppDelegate + else { + return + } + + _ = appDelegate.application(UIApplication.shared, open: url, options: [:]) + } + + func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { + guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { + return + } + + _ = appDelegate.application( + UIApplication.shared, + continue: userActivity, + restorationHandler: { _ in }) + } +}`; + +module.exports = function withIosSceneLifecycle(config) { + config = withInfoPlist(config, (nextConfig) => { + nextConfig.modResults.UIApplicationSceneManifest = { + UIApplicationSupportsMultipleScenes: false, + UISceneConfigurations: { + UIWindowSceneSessionRoleApplication: [ + { + UISceneConfigurationName: "Default Configuration", + UISceneDelegateClassName: "$(PRODUCT_MODULE_NAME).SceneDelegate", + }, + ], + }, + }; + + return nextConfig; + }); + + return withAppDelegate(config, (nextConfig) => { + if (nextConfig.modResults.language !== "swift") { + throw new Error("The iOS scene lifecycle plugin requires a Swift AppDelegate."); + } + + if (!nextConfig.modResults.contents.includes("class SceneDelegate:")) { + nextConfig.modResults.contents += SCENE_DELEGATE; + } + + return nextConfig; + }); +}; diff --git a/apps/mobile/plugins/withShareExtensionDisplayName.cjs b/apps/mobile/plugins/withShareExtensionDisplayName.cjs new file mode 100644 index 0000000000..27c57925e8 --- /dev/null +++ b/apps/mobile/plugins/withShareExtensionDisplayName.cjs @@ -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 = /(CFBundleDisplayName<\/key>\s*)[^<]*(<\/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, + ); +}; diff --git a/apps/mobile/plugins/withWidgetLogoAsset.cjs b/apps/mobile/plugins/withWidgetLogoAsset.cjs new file mode 100644 index 0000000000..5c976c2a0c --- /dev/null +++ b/apps/mobile/plugins/withWidgetLogoAsset.cjs @@ -0,0 +1,68 @@ +"use strict"; + +// Ships the branded T3 mark to the Live Activity / widget extension. +// +// expo-widgets generates ExpoWidgetsTarget without a Resources build phase and +// has no asset support, so this plugin (a) writes an SVG template image set into +// the generated widget asset catalog and (b) wires that catalog into the widget +// target with an actool build phase. +// +// ORDERING: must be listed BEFORE "expo-widgets" in the plugins array. Expo +// chains same-type mods so the last-registered runs FIRST; registering this +// plugin earlier makes its mods run AFTER expo-widgets' mods. That matters +// twice: expo-widgets' dangerous mod rmSync's ios/ExpoWidgetsTarget/ (deleting +// any catalog written before it), and its xcodeproj mod is what creates the +// widget target. Listed after expo-widgets, both steps silently no-op on a +// fresh prebuild — which is how prod build 8 shipped without the logo. + +const path = require("path"); +const fs = require("fs"); +const { withDangerousMod, withXcodeProject } = require("expo/config-plugins"); +const { addWidgetAssetCatalog } = require("./lib/addWidgetAssetCatalog.cjs"); + +const TARGET_NAME = "ExpoWidgetsTarget"; +const CATALOG_NAME = "Assets.xcassets"; +const IMAGE_SET = "T3Mark.imageset"; +const SVG_NAME = "T3Mark.svg"; + +const CATALOG_CONTENTS = JSON.stringify({ info: { author: "expo", version: 1 } }, null, 2) + "\n"; +const IMAGE_SET_CONTENTS = + JSON.stringify( + { + images: [{ idiom: "universal", filename: SVG_NAME }], + info: { author: "expo", version: 1 }, + properties: { + "preserves-vector-representation": true, + "template-rendering-intent": "template", + }, + }, + null, + 2, + ) + "\n"; + +function withAssetFiles(config) { + return withDangerousMod(config, [ + "ios", + (cfg) => { + const source = path.join(cfg.modRequest.projectRoot, "assets", "widget", SVG_NAME); + const catalogDir = path.join(cfg.modRequest.platformProjectRoot, TARGET_NAME, CATALOG_NAME); + const imageSetDir = path.join(catalogDir, IMAGE_SET); + fs.mkdirSync(imageSetDir, { recursive: true }); + fs.writeFileSync(path.join(catalogDir, "Contents.json"), CATALOG_CONTENTS); + fs.writeFileSync(path.join(imageSetDir, "Contents.json"), IMAGE_SET_CONTENTS); + fs.copyFileSync(source, path.join(imageSetDir, SVG_NAME)); + return cfg; + }, + ]); +} + +function withAssetWiring(config) { + return withXcodeProject(config, (cfg) => { + addWidgetAssetCatalog(cfg.modResults, { targetName: TARGET_NAME }); + return cfg; + }); +} + +module.exports = function withWidgetLogoAsset(config) { + return withAssetWiring(withAssetFiles(config)); +}; diff --git a/apps/mobile/plugins/withoutIosPersonalTeamCapabilities.cjs b/apps/mobile/plugins/withoutIosPersonalTeamCapabilities.cjs new file mode 100644 index 0000000000..035c46b34c --- /dev/null +++ b/apps/mobile/plugins/withoutIosPersonalTeamCapabilities.cjs @@ -0,0 +1,10 @@ +const { withEntitlementsPlist } = require("expo/config-plugins"); + +module.exports = function withoutIosPersonalTeamCapabilities(config) { + return withEntitlementsPlist(config, (modConfig) => { + delete modConfig.modResults["aps-environment"]; + delete modConfig.modResults["com.apple.developer.applesignin"]; + delete modConfig.modResults["com.apple.security.application-groups"]; + return modConfig; + }); +}; diff --git a/apps/mobile/scripts/wire-widget-asset-catalog.cjs b/apps/mobile/scripts/wire-widget-asset-catalog.cjs new file mode 100644 index 0000000000..b7c70f0cdc --- /dev/null +++ b/apps/mobile/scripts/wire-widget-asset-catalog.cjs @@ -0,0 +1,30 @@ +"use strict"; + +// One-off: apply the widget asset-catalog wiring to the already-generated +// ios/ project so the current build compiles ExpoWidgetsTarget/Assets.xcassets +// without a full `expo prebuild`. The durable equivalent lives in +// plugins/withWidgetLogoAsset.cjs and runs on prebuild. + +const path = require("path"); +const fs = require("fs"); + +const xcodePath = require.resolve("xcode", { + paths: [ + require.resolve("@expo/config-plugins", { paths: [require.resolve("expo/package.json")] }), + ], +}); +const xcode = require(xcodePath); +const { addWidgetAssetCatalog } = require("../plugins/lib/addWidgetAssetCatalog.cjs"); + +const pbxprojPath = path.join(__dirname, "..", "ios", "T3CodeDev.xcodeproj", "project.pbxproj"); +const proj = xcode.project(pbxprojPath); +proj.parseSync(); + +const added = addWidgetAssetCatalog(proj, { targetName: "ExpoWidgetsTarget" }); + +if (added) { + fs.writeFileSync(pbxprojPath, proj.writeSync()); + console.log("Added widget asset-compile phase to ExpoWidgetsTarget."); +} else { + console.log("No change: phase already present."); +} diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx new file mode 100644 index 0000000000..835f54491f --- /dev/null +++ b/apps/mobile/src/App.tsx @@ -0,0 +1,88 @@ +import { BlurTargetView } from "expo-blur"; +import * as Linking from "expo-linking"; +import * as SplashScreen from "expo-splash-screen"; +import { useEffect } from "react"; +import { StatusBar, useColorScheme } from "react-native"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { KeyboardProvider } from "react-native-keyboard-controller"; +import { SafeAreaProvider } from "react-native-safe-area-context"; +import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigation/native"; + +import { RegistryContext } from "@effect/atom-react"; +import { ConfirmDialogHost } from "./components/ConfirmDialogHost"; +import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider"; +import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene"; +import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider"; +import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider"; +import { RootStack } from "./Stack"; +import { appAtomRegistry } from "./state/atom-registry"; +import { OverlayPortalHost } from "./components/OverlayPortal"; +import { appBlurTargetRef } from "./lib/appBlurTarget"; +import { useThemeColor } from "./lib/useThemeColor"; + +import "../global.css"; + +if (process.env.EXPO_PUBLIC_SHOWCASE === "1") { + prepareNativeShowcaseCapture(); +} + +const appLinking = { + prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"], + // The Expo dev client launches the app via + // ://expo-development-client/?url= — that URL addresses + // the launcher, not app navigation. Without this filter it falls through + // to the NotFound wildcard route on every dev launch. + // 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); + +export default function App() { + const colorScheme = useColorScheme(); + const statusBarBg = useThemeColor("--color-status-bar"); + + useEffect(() => { + SplashScreen.hide(); + }, []); + + return ( + + + + + + + + {/* The navigation theme drives the NATIVE header appearance: native-stack + forwards `dark` as the nav bar's overrideUserInterfaceStyle. Without + this, React Navigation defaults to its light theme and every native + header (glass buttons, title, materials) is forced light even when + the system is in dark mode. */} + {/* Blur target for Android dropdown backdrops — see appBlurTarget.ts. */} + + + + + + + {/* Anchored-menu overlays render here — in-window, so the + keyboard stays up while a dropdown is open. */} + + + + + + + + ); +} diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx new file mode 100644 index 0000000000..4cf787d9ce --- /dev/null +++ b/apps/mobile/src/Stack.tsx @@ -0,0 +1,567 @@ +import { + createPathConfigForStaticNavigation, + getPathFromState, + NavigationState, + StackActions, + useNavigation, +} from "@react-navigation/native"; +import { + createNativeStackNavigator, + 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"; + +import { AppText as Text } from "./components/AppText"; +import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen"; +import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation"; +import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent"; +import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen"; +import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation"; +import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen"; +import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout"; +import { HardwareKeyboardCommandProvider } from "./features/keyboard/HardwareKeyboardCommandProvider"; +import { ReviewCommentComposerSheet } from "./features/review/ReviewCommentComposerSheet"; +import { ReviewSheet } from "./features/review/ReviewSheet"; +import { ThreadTerminalRouteScreen } from "./features/terminal/ThreadTerminalRouteScreen"; +import { GitBranchesSheet } from "./features/threads/git/GitBranchesSheet"; +import { GitCommitSheet } from "./features/threads/git/GitCommitSheet"; +import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet"; +import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet"; +import { ThreadRouteScreen } from "./features/threads/ThreadRouteScreen"; +import { ConnectionsRouteScreen } from "./features/connection/ConnectionsRouteScreen"; +import { ConnectionsNewRouteScreen } from "./features/connection/ConnectionsNewRouteScreen"; +import { HomeRouteScreen } from "./features/home/HomeRouteScreen"; +import { AddProjectDestinationRoute } from "./features/projects/AddProjectDestinationRoute"; +import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute"; +import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute"; +import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute"; +import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen"; +import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider"; +import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen"; +import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen"; +import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsClientStorageRouteScreen"; +import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen"; +import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen"; +import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen"; +import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen"; +import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen"; +import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator"; +import { + SettingsLegalDocumentCloseHeaderButton, + 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"; + +const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version); + +// Matches --color-sheet in global.css (light/dark). DynamicColorIOS lets the header +// background stay STATIC config while still adapting to appearance changes. +const SHEET_BACKGROUND_COLOR = + Platform.OS === "ios" + ? DynamicColorIOS({ light: "rgba(242, 242, 247, 0.98)", dark: "rgba(14, 14, 14, 0.98)" }) + : undefined; + +type AppScreenOptions = NativeStackNavigationOptions & { + readonly unstable_navigationItemStyle?: "editor"; +}; + +// Shared header presets. Screens only override genuinely dynamic values (titles, +// subtitles, toolbar items, search callbacks) via NativeStackScreenOptions. +// +// GLASS: transparent header over the screen's primary scroll view on supported +// iOS versions. Pre-glass iOS gets the same solid material as internal-scroll +// surfaces so content is laid out below the bar instead of underlapping it. +const GLASS_HEADER_OPTIONS: AppScreenOptions = { + headerBackButtonDisplayMode: "minimal", + headerBackTitle: "", + headerLargeTitle: false, + headerShadowVisible: false, + headerShown: true, + headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED + ? { backgroundColor: "transparent" } + : SHEET_BACKGROUND_COLOR !== undefined + ? { backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string } + : undefined, + headerTitleStyle: { fontSize: 18, fontWeight: "800" }, + headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED, + scrollEdgeEffects: NATIVE_LIQUID_GLASS_SUPPORTED ? HEADER_SCROLL_EDGE_EFFECTS : undefined, + unstable_navigationItemStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? "editor" : undefined, +}; + +// SOLID: opaque sheet-colored header for surfaces whose content scrolls internally +// (file viewer, terminal, review) — there is nothing for glass to sample there. +const SOLID_HEADER_OPTIONS: AppScreenOptions = { + headerBackButtonDisplayMode: "minimal", + headerBackTitle: "", + headerLargeTitle: false, + headerShadowVisible: false, + headerShown: true, + headerStyle: + SHEET_BACKGROUND_COLOR !== undefined + ? // native-stack types this as `string`, but the native side accepts any + // ColorValue including DynamicColorIOS. + { backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string } + : undefined, + headerTitleStyle: { fontSize: 18, fontWeight: "800" }, + headerTransparent: false, + unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined, +}; + +// Solid header variant for screens inside sheets (centered title, no editor style). +const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = { + ...SOLID_HEADER_OPTIONS, + unstable_navigationItemStyle: undefined, +}; + +const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = { + ...SHEET_SOLID_HEADER_OPTIONS, + headerBackVisible: false, + headerLeft: SettingsLegalDocumentCloseHeaderButton, + headerRight: () => , + presentation: "fullScreenModal", +}; + +const SettingsSheetStack = createNativeStackNavigator({ + initialRouteName: "Settings", + screenOptions: { + ...GLASS_HEADER_OPTIONS, + // Sheets read better with the iOS-default centered title (no editor style). + unstable_navigationItemStyle: undefined, + }, + screens: { + Settings: createNativeStackScreen({ + screen: SettingsRouteScreen, + linking: "", + options: { + title: "Settings", + }, + }), + SettingsEnvironments: createNativeStackScreen({ + screen: SettingsEnvironmentsRouteScreen, + linking: "environments", + options: { + title: "Environments", + }, + }), + SettingsEnvironmentNew: createNativeStackScreen({ + screen: ConnectionsNewRouteScreen, + linking: "environment-new", + options: { + title: "Add Environment", + }, + }), + SettingsArchive: createNativeStackScreen({ + screen: ArchivedThreadsRouteScreen, + linking: "archive", + options: { + title: "Archived Threads", + }, + }), + SettingsAppearance: createNativeStackScreen({ + screen: SettingsAppearanceRouteScreen, + linking: "appearance", + options: { + title: "Appearance", + }, + }), + SettingsClientStorage: createNativeStackScreen({ + screen: SettingsClientStorageRouteScreen, + linking: "client-storage", + options: { + title: "Client Storage", + }, + }), + SettingsAuth: createNativeStackScreen({ + screen: SettingsAuthRouteScreen, + linking: "auth", + options: { + title: "Sign in", + }, + }), + SettingsWaitlist: createNativeStackScreen({ + screen: SettingsWaitlistRouteScreen, + linking: "waitlist", + options: { + title: "Join the waitlist", + }, + }), + }, +}); + +// Thread routes live FLAT in the root stack (not in a nested navigator). A nested +// stack means a second UINavigationController with its own UINavigationBar, which +// breaks iOS 26's shared-header morphing between Home and Thread (each pair inside +// one bar morphs; across two bars the whole screen slides). Flat linking paths keep +// the same deep-link URLs the nested config produced. +const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId"; + +// New-task / add-project flow: nested navigator inside the formSheet (Settings-sheet +// pattern — a plain formSheet screen cannot render a stack header; the header and +// in-sheet pushes come from this nested stack). +const NewTaskSheetStack = createNativeStackNavigator({ + initialRouteName: "NewTask", + screenOptions: { + ...GLASS_HEADER_OPTIONS, + // Sheets read better with the iOS-default centered title (no editor style). + unstable_navigationItemStyle: undefined, + }, + screens: { + NewTask: createNativeStackScreen({ + screen: NewTaskRouteScreen, + linking: "", + options: { + title: "Choose project", + }, + }), + NewTaskDraft: createNativeStackScreen({ + screen: NewTaskDraftRouteScreen, + linking: "draft", + // The draft composer has no scroll view for glass to sample; a solid + // header also lays the content out below the bar (no manual inset). + options: SHEET_SOLID_HEADER_OPTIONS, + }), + AddProject: createNativeStackScreen({ + screen: AddProjectSourceRoute, + linking: "add-project", + options: { + title: "Add Project", + }, + }), + AddProjectRepository: createNativeStackScreen({ + screen: AddProjectRepositoryRoute, + linking: "add-project/repository", + }), + AddProjectDestination: createNativeStackScreen({ + screen: AddProjectDestinationRoute, + linking: "add-project/destination", + }), + AddProjectLocal: createNativeStackScreen({ + screen: AddProjectLocalRoute, + linking: "add-project/local", + }), + }, +}); + +// Routes presented as sheets/overlays ON TOP of the workspace. They must not +// influence the adaptive workspace layout: opening Settings over Home should +// not flip the sidebar in or change the active thread. +const WORKSPACE_OVERLAY_ROUTES = new Set([ + "ConnectOnboarding", + "Connections", + "ConnectionsNew", + "GitBranches", + "GitCommit", + "GitConfirm", + "GitOverview", + "NewTaskSheet", + "SettingsLegal", + "SettingsSheet", + "ThreadReviewComment", +]); + +/** + * Pathname of the topmost NON-overlay route — the screen the workspace is + * actually "on", regardless of any sheets floating above it. + */ +function workspacePathFromState(state: NavigationState): string { + const routes = state.routes.filter((route) => !WORKSPACE_OVERLAY_ROUTES.has(route.name)); + const effectiveState = + routes.length > 0 && routes.length !== state.routes.length + ? ({ ...state, routes, index: routes.length - 1 } as NavigationState) + : state; + const path = getPathFromState(effectiveState, navigationPathConfig); + return path.startsWith("/") ? path : `/${path}`; +} + +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); + const pathname = path.startsWith("/") ? path : `/${path}`; + const workspacePathname = workspacePathFromState(props.state); + + return ( + + + + + {props.children} + + + + ); +} + +function NotFoundScreen() { + const navigation = useNavigation(); + const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen")); + const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary")); + const returnHomeButtonStyle = StyleSheet.flatten([ + { + borderRadius: 999, + paddingHorizontal: 20, + paddingVertical: 14, + }, + primaryBgStyle, + ]); + + return ( + + + Route not found + + navigation.dispatch(StackActions.replace("Home"))} + > + Return home + + + ); +} + +export const RootStack = createNativeStackNavigator({ + initialRouteName: "Home", + layout: RootStackLayout, + screenOptions: { + headerShown: false, + }, + screens: { + Home: createNativeStackScreen({ + screen: HomeRouteScreen, + linking: "", + options: { + ...GLASS_HEADER_OPTIONS, + contentStyle: { backgroundColor: "transparent" }, + headerBackVisible: false, + title: "Threads", + }, + }), + Thread: createNativeStackScreen({ + screen: ThreadRouteScreen, + linking: THREAD_LINKING_PREFIX, + options: GLASS_HEADER_OPTIONS, + }), + ThreadTerminal: createNativeStackScreen({ + screen: ThreadTerminalRouteScreen, + linking: `${THREAD_LINKING_PREFIX}/terminal`, + options: SOLID_HEADER_OPTIONS, + }), + ThreadReview: createNativeStackScreen({ + screen: ReviewSheet, + linking: `${THREAD_LINKING_PREFIX}/review`, + options: SOLID_HEADER_OPTIONS, + }), + ThreadReviewComment: createNativeStackScreen({ + screen: ReviewCommentComposerSheet, + linking: `${THREAD_LINKING_PREFIX}/review-comment`, + options: { + // Android cannot host the keyboard-driven comment composer inside a + // formSheet; use a full-screen modal there instead. + presentation: Platform.OS === "android" ? "fullScreenModal" : "formSheet", + sheetAllowedDetents: Platform.OS === "android" ? undefined : [0.55, 0.92], + sheetGrabberVisible: Platform.OS !== "android", + }, + }), + ThreadFiles: createNativeStackScreen({ + screen: ThreadFilesTreeScreen, + linking: `${THREAD_LINKING_PREFIX}/files`, + options: { + ...GLASS_HEADER_OPTIONS, + contentStyle: + SHEET_BACKGROUND_COLOR !== undefined + ? { backgroundColor: SHEET_BACKGROUND_COLOR } + : undefined, + title: "Files", + }, + }), + ThreadFile: createNativeStackScreen({ + screen: ThreadFileScreen, + linking: `${THREAD_LINKING_PREFIX}/files/:path*`, + options: SOLID_HEADER_OPTIONS, + }), + GitOverview: createNativeStackScreen({ + screen: GitOverviewSheet, + linking: `${THREAD_LINKING_PREFIX}/git`, + options: { + presentation: "formSheet", + sheetAllowedDetents: [0.55, 0.92], + sheetGrabberVisible: true, + }, + }), + GitCommit: createNativeStackScreen({ + screen: GitCommitSheet, + linking: `${THREAD_LINKING_PREFIX}/git/commit`, + options: { + presentation: "formSheet", + sheetAllowedDetents: [0.55, 0.92], + sheetGrabberVisible: true, + }, + }), + GitBranches: createNativeStackScreen({ + screen: GitBranchesSheet, + linking: `${THREAD_LINKING_PREFIX}/git/branches`, + options: { + presentation: "formSheet", + sheetAllowedDetents: [0.55, 0.92], + sheetGrabberVisible: true, + }, + }), + GitConfirm: createNativeStackScreen({ + screen: GitConfirmSheet, + linking: `${THREAD_LINKING_PREFIX}/git-confirm`, + options: { + presentation: "formSheet", + sheetAllowedDetents: [0.45, 0.7], + sheetGrabberVisible: true, + }, + }), + SettingsSheet: createNativeStackScreen({ + screen: SettingsSheetStack, + linking: "settings", + options: { + gestureEnabled: true, + headerShown: false, + // Android pushes settings as a regular full page with an in-screen + // back header; iOS keeps the detented form sheet. + ...(Platform.OS === "android" + ? { presentation: "card" as const } + : { + presentation: "formSheet" as const, + sheetAllowedDetents: [0.7, 0.92], + sheetGrabberVisible: true, + }), + }, + }), + SettingsLegal: createNativeStackScreen({ + screen: SettingsLegalRouteScreen, + linking: "settings/legal", + options: { + ...LEGAL_DOCUMENT_HEADER_OPTIONS, + title: "Legal", + }, + }), + ConnectOnboarding: createNativeStackScreen({ + screen: ConnectOnboardingRouteScreen, + linking: "connect-onboarding", + options: { + // A root-level Android formSheet does not host the native stack bar; + // the route renders an embedded AndroidSheetHeader instead. + ...(Platform.OS === "android" ? { headerShown: false } : SHEET_SOLID_HEADER_OPTIONS), + title: "Set up T3 Connect", + gestureEnabled: true, + presentation: "formSheet", + sheetAllowedDetents: [0.6, 0.95], + sheetGrabberVisible: true, + }, + }), + Connections: createNativeStackScreen({ + screen: ConnectionsRouteScreen, + linking: "connections", + options: { + title: "Environments", + // Android: full page; the screen renders its own AndroidScreenHeader, + // so the native bar stays hidden. iOS keeps the sheet. + ...(Platform.OS === "android" + ? { presentation: "card" as const, headerShown: false } + : { + presentation: "formSheet" as const, + sheetAllowedDetents: [0.55, 0.7], + sheetGrabberVisible: true, + }), + }, + }), + ConnectionsNew: createNativeStackScreen({ + screen: ConnectionsNewRouteScreen, + linking: "connections/new", + options: { + presentation: "formSheet", + sheetAllowedDetents: [0.55, 0.7], + sheetGrabberVisible: true, + }, + }), + NewTaskSheet: createNativeStackScreen({ + screen: NewTaskSheetStack, + linking: "new", + // The whole new-task flow (choose project → draft → add project) shares + // draft state via NewTaskFlowProvider. The expo-router era mounted it in + // app/new/_layout.tsx; this layout wrapper is the native-stack equivalent. + layout: ({ children }) => {children}, + options: { + gestureEnabled: true, + headerShown: false, + // Android pushes the flow as a regular full page — the draft should + // read like a thread that just doesn't exist yet; iOS keeps the sheet. + ...(Platform.OS === "android" + ? { presentation: "card" as const } + : { + presentation: "formSheet" as const, + sheetAllowedDetents: [0.92], + sheetGrabberVisible: true, + }), + }, + }), + NotFound: createNativeStackScreen({ + screen: NotFoundScreen, + linking: "*", + }), + }, +}); +type RootStackType = typeof RootStack; + +const navigationPathConfig = { + screens: createPathConfigForStaticNavigation(RootStack) ?? {}, +}; + +declare module "@react-navigation/native" { + interface RootNavigator extends RootStackType {} +} diff --git a/apps/mobile/src/app/+not-found.tsx b/apps/mobile/src/app/+not-found.tsx deleted file mode 100644 index d11155f860..0000000000 --- a/apps/mobile/src/app/+not-found.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import { Link } from "expo-router"; -import { Pressable, ScrollView, StyleSheet } from "react-native"; -import { useResolveClassNames } from "uniwind"; - -import { AppText as Text } from "../components/AppText"; - -export default function NotFoundRoute() { - const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen")); - const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary")); - - return ( - - - Route not found - - - - Return home - - - - ); -} diff --git a/apps/mobile/src/app/_layout.tsx b/apps/mobile/src/app/_layout.tsx deleted file mode 100644 index 968be6c14a..0000000000 --- a/apps/mobile/src/app/_layout.tsx +++ /dev/null @@ -1,149 +0,0 @@ -import "../../global.css"; -import { - DMSans_400Regular, - DMSans_500Medium, - DMSans_700Bold, - useFonts, -} from "@expo-google-fonts/dm-sans"; -import { usePathname } from "expo-router"; -import Stack from "expo-router/stack"; -import { useCallback } from "react"; -import { StatusBar, useColorScheme } from "react-native"; -import { GestureHandlerRootView } from "react-native-gesture-handler"; -import { KeyboardProvider } from "react-native-keyboard-controller"; -import { SafeAreaProvider } from "react-native-safe-area-context"; -import { useResolveClassNames } from "uniwind"; - -import { LoadingScreen } from "../components/LoadingScreen"; - -import { useWorkspaceState } from "../state/workspace"; -import { useThreadOutboxDrain } from "../state/use-thread-outbox-drain"; -import { RegistryContext } from "@effect/atom-react"; -import { appAtomRegistry } from "../state/atom-registry"; -import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider"; -import { - ClerkSettingsSheetDetentProvider, - useClerkSettingsSheetDetent, -} from "../features/cloud/ClerkSettingsSheetDetent"; -import { useAgentNotificationNavigation } from "../features/agent-awareness/notificationNavigation"; -import { useThemeColor } from "../lib/useThemeColor"; - -function AppNavigator() { - const pathname = usePathname(); - const expandedSettingsRouteIsActive = - pathname === "/settings/archive" || pathname === "/settings/auth"; - - return ( - - - - ); -} - -function AppNavigatorContent() { - const { state } = useWorkspaceState(); - const { collapse, isExpanded } = useClerkSettingsSheetDetent(); - const colorScheme = useColorScheme(); - const statusBarBg = useThemeColor("--color-status-bar"); - const sheetStyle = useResolveClassNames("bg-sheet"); - useAgentNotificationNavigation(); - useThreadOutboxDrain(); - - const handleSettingsTransitionEnd = useCallback( - (event: { data: { closing: boolean } }) => { - if (event.data.closing) { - collapse(); - } - }, - [collapse], - ); - - const newTaskScreenOptions = { - contentStyle: sheetStyle, - gestureEnabled: true, - headerShown: false, - presentation: "formSheet" as const, - sheetAllowedDetents: [0.92], - sheetGrabberVisible: true, - }; - - const connectionSheetScreenOptions = { - contentStyle: sheetStyle, - gestureEnabled: true, - headerShown: false, - presentation: "formSheet" as const, - sheetAllowedDetents: [0.55, 0.7], - sheetGrabberVisible: true, - }; - - const settingsSheetScreenOptions = { - ...connectionSheetScreenOptions, - sheetAllowedDetents: isExpanded ? [0.92] : [0.7], - }; - - if (state.isLoadingConnections) { - return ; - } - - return ( - <> - - - - - - - - - - ); -} - -export default function RootLayout() { - const [fontsLoaded] = useFonts({ - DMSans_400Regular, - DMSans_500Medium, - DMSans_700Bold, - }); - return ( - - - - - - {fontsLoaded ? ( - - ) : ( - - )} - - - - - - ); -} diff --git a/apps/mobile/src/app/connections/_layout.tsx b/apps/mobile/src/app/connections/_layout.tsx deleted file mode 100644 index 902b53cb15..0000000000 --- a/apps/mobile/src/app/connections/_layout.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import Stack from "expo-router/stack"; -import { useResolveClassNames } from "uniwind"; -import { useThemeColor } from "../../lib/useThemeColor"; - -export const unstable_settings = { - anchor: "index", -}; - -export default function ConnectionsLayout() { - const contentStyle = useResolveClassNames("bg-sheet"); - const connSheetBg = useThemeColor("--color-sheet"); - const headerTint = useThemeColor("--color-foreground"); - - return ( - - - - - ); -} diff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx deleted file mode 100644 index 7f9962efc9..0000000000 --- a/apps/mobile/src/app/index.tsx +++ /dev/null @@ -1,120 +0,0 @@ -import type { - EnvironmentId, - SidebarProjectGroupingMode, - SidebarThreadSortOrder, -} from "@t3tools/contracts"; -import { - DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE, - DEFAULT_SIDEBAR_PROJECT_SORT_ORDER, - DEFAULT_SIDEBAR_THREAD_SORT_ORDER, -} from "@t3tools/contracts"; -import * as Arr from "effect/Array"; -import * as Order from "effect/Order"; -import { useRouter } from "expo-router"; -import { useCallback, useMemo, useState } from "react"; - -import { useProjects, useThreadShells } from "../state/entities"; -import { useWorkspaceState } from "../state/workspace"; -import { buildThreadRoutePath } from "../lib/routes"; -import { useSavedRemoteConnections } from "../state/use-remote-environment-registry"; -import { HomeScreen } from "../features/home/HomeScreen"; -import { HomeHeader } from "../features/home/HomeHeader"; -import type { HomeProjectSortOrder } from "../features/home/homeThreadList"; -import { useThreadListActions } from "../features/home/useThreadListActions"; - -interface HomeListOptions { - readonly selectedEnvironmentId: EnvironmentId | null; - readonly projectSortOrder: HomeProjectSortOrder; - readonly threadSortOrder: SidebarThreadSortOrder; - readonly projectGroupingMode: SidebarProjectGroupingMode; -} - -/* ─── Route screen ───────────────────────────────────────────────────── */ - -export default function HomeRouteScreen() { - const projects = useProjects(); - const threads = useThreadShells(); - const { state: catalogState } = useWorkspaceState(); - const { savedConnectionsById } = useSavedRemoteConnections(); - const router = useRouter(); - const [searchQuery, setSearchQuery] = useState(""); - const [listOptions, setListOptions] = useState({ - selectedEnvironmentId: null, - projectSortOrder: - DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual" - ? "updated_at" - : DEFAULT_SIDEBAR_PROJECT_SORT_ORDER, - threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER, - projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE, - }); - const { archiveThread, confirmDeleteThread } = useThreadListActions(); - const environments = useMemo( - () => - Arr.sort( - Object.values(savedConnectionsById).map((connection) => ({ - environmentId: connection.environmentId, - label: connection.environmentLabel, - })), - Order.mapInput( - Order.String, - (environment: { readonly label: string }) => environment.label, - ), - ), - [savedConnectionsById], - ); - const selectedEnvironmentId = environments.some( - (environment) => environment.environmentId === listOptions.selectedEnvironmentId, - ) - ? listOptions.selectedEnvironmentId - : null; - const setSelectedEnvironmentId = useCallback((environmentId: EnvironmentId | null) => { - setListOptions((current) => ({ ...current, selectedEnvironmentId: environmentId })); - }, []); - const setProjectSortOrder = useCallback((projectSortOrder: HomeProjectSortOrder) => { - setListOptions((current) => ({ ...current, projectSortOrder })); - }, []); - const setThreadSortOrder = useCallback((threadSortOrder: SidebarThreadSortOrder) => { - setListOptions((current) => ({ ...current, threadSortOrder })); - }, []); - const setProjectGroupingMode = useCallback((projectGroupingMode: SidebarProjectGroupingMode) => { - setListOptions((current) => ({ ...current, projectGroupingMode })); - }, []); - - return ( - <> - router.push("/settings")} - onProjectGroupingModeChange={setProjectGroupingMode} - onProjectSortOrderChange={setProjectSortOrder} - onSearchQueryChange={setSearchQuery} - onStartNewTask={() => router.push("/new")} - onThreadSortOrderChange={setThreadSortOrder} - /> - - router.push("/connections/new")} - onArchiveThread={archiveThread} - onDeleteThread={confirmDeleteThread} - onOpenEnvironments={() => router.push("/settings/environments")} - onSelectThread={(thread) => { - router.push(buildThreadRoutePath(thread)); - }} - projectGroupingMode={listOptions.projectGroupingMode} - projects={projects} - projectSortOrder={listOptions.projectSortOrder} - savedConnectionsById={savedConnectionsById} - searchQuery={searchQuery} - selectedEnvironmentId={selectedEnvironmentId} - threads={threads} - threadSortOrder={listOptions.threadSortOrder} - /> - - ); -} diff --git a/apps/mobile/src/app/new/_layout.tsx b/apps/mobile/src/app/new/_layout.tsx deleted file mode 100644 index 2113b13311..0000000000 --- a/apps/mobile/src/app/new/_layout.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import Stack from "expo-router/stack"; -import { useResolveClassNames } from "uniwind"; - -import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider"; -import { useThemeColor } from "../../lib/useThemeColor"; - -export const unstable_settings = { - anchor: "index", -}; - -export default function NewTaskLayout() { - const sheetStyle = useResolveClassNames("bg-sheet"); - const sheetBg = useThemeColor("--color-sheet"); - const headerTint = useThemeColor("--color-foreground"); - - return ( - - - - - - - - - - - ); -} diff --git a/apps/mobile/src/app/new/add-project/destination.tsx b/apps/mobile/src/app/new/add-project/destination.tsx deleted file mode 100644 index 7c00aa28c6..0000000000 --- a/apps/mobile/src/app/new/add-project/destination.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { AddProjectDestinationScreen } from "../../../features/projects/AddProjectScreen"; - -export default function AddProjectDestinationRoute() { - return ; -} diff --git a/apps/mobile/src/app/new/add-project/index.tsx b/apps/mobile/src/app/new/add-project/index.tsx deleted file mode 100644 index e7d88b9c4f..0000000000 --- a/apps/mobile/src/app/new/add-project/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { AddProjectSourceScreen } from "../../../features/projects/AddProjectScreen"; - -export default function AddProjectRoute() { - return ; -} diff --git a/apps/mobile/src/app/new/add-project/local.tsx b/apps/mobile/src/app/new/add-project/local.tsx deleted file mode 100644 index db8e2f4d61..0000000000 --- a/apps/mobile/src/app/new/add-project/local.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { AddProjectLocalFolderScreen } from "../../../features/projects/AddProjectScreen"; - -export default function AddProjectLocalRoute() { - return ; -} diff --git a/apps/mobile/src/app/new/add-project/repository.tsx b/apps/mobile/src/app/new/add-project/repository.tsx deleted file mode 100644 index 7bf23a4955..0000000000 --- a/apps/mobile/src/app/new/add-project/repository.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { Stack, useLocalSearchParams } from "expo-router"; -import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime/operations/projects"; - -import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen"; - -export default function AddProjectRepositoryRoute() { - const params = useLocalSearchParams<{ source?: string | string[] }>(); - const source = Array.isArray(params.source) ? params.source[0] : params.source; - const title = - source === "github" || - source === "gitlab" || - source === "bitbucket" || - source === "azure-devops" - ? addProjectRemoteSourceLabel(source) - : "Git URL"; - - return ( - <> - - - - ); -} diff --git a/apps/mobile/src/app/new/draft.tsx b/apps/mobile/src/app/new/draft.tsx deleted file mode 100644 index 3adc7c53f9..0000000000 --- a/apps/mobile/src/app/new/draft.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Stack, useLocalSearchParams } from "expo-router"; - -import { NewTaskDraftScreen } from "../../features/threads/NewTaskDraftScreen"; - -export default function NewTaskDraftRoute() { - const params = useLocalSearchParams<{ - environmentId?: string | string[]; - projectId?: string | string[]; - title?: string | string[]; - }>(); - - return ( - <> - - - - ); -} diff --git a/apps/mobile/src/app/new/index.tsx b/apps/mobile/src/app/new/index.tsx deleted file mode 100644 index 6e2aa64ce1..0000000000 --- a/apps/mobile/src/app/new/index.tsx +++ /dev/null @@ -1,218 +0,0 @@ -import { Link, Stack, useRouter } from "expo-router"; -import { SymbolView } from "expo-symbols"; -import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; -import { useMemo } from "react"; -import { ActivityIndicator, Pressable, ScrollView, View } from "react-native"; -import { useSafeAreaInsets } from "react-native-safe-area-context"; -import { useThemeColor } from "../../lib/useThemeColor"; - -import { AppText as Text } from "../../components/AppText"; -import { ProjectFavicon } from "../../components/ProjectFavicon"; -import { useProjects, useThreadShells } from "../../state/entities"; -import type { WorkspaceState } from "../../state/workspaceModel"; -import { useWorkspaceState } from "../../state/workspace"; -import { groupProjectsByRepository } from "../../lib/repositoryGroups"; - -function deriveProjectEmptyState(catalogState: WorkspaceState): { - readonly title: string; - readonly detail: string; - readonly loading: boolean; -} { - if (catalogState.isLoadingConnections) { - return { - title: "Loading environments", - detail: "Checking saved environments on this device.", - loading: true, - }; - } - - if (!catalogState.hasConnections) { - return { - title: "No environments connected", - detail: "Add an environment before creating a task.", - loading: false, - }; - } - - if ( - (catalogState.connectionState === "available" || - catalogState.connectionState === "offline" || - catalogState.connectionState === "error") && - !catalogState.hasLoadedShellSnapshot - ) { - return { - title: "Environment unavailable", - detail: - catalogState.connectionError ?? - "The saved environment is offline. Check the URL or start the environment, then retry.", - loading: false, - }; - } - - if ( - catalogState.hasConnectingEnvironment && - !catalogState.hasLoadedShellSnapshot && - catalogState.connectionError === null - ) { - return { - title: "Connecting to environment", - detail: "Loading projects from the saved environment.", - loading: true, - }; - } - - return { - title: "No projects found", - detail: "The connected environment did not report any projects.", - loading: false, - }; -} - -export default function NewTaskRoute() { - const projects = useProjects(); - const threads = useThreadShells(); - const { state: catalogState } = useWorkspaceState(); - const router = useRouter(); - const insets = useSafeAreaInsets(); - const chevronColor = useThemeColor("--color-chevron"); - const accentColor = useThemeColor("--color-icon-muted"); - const borderSubtleColor = useThemeColor("--color-border-subtle"); - const repositoryGroups = useMemo( - () => groupProjectsByRepository({ projects, threads }), - [projects, threads], - ); - const items = useMemo(() => { - const nextItems: Array<{ - readonly environmentId: EnvironmentId; - readonly id: ProjectId; - readonly key: string; - readonly title: string; - readonly workspaceRoot: string; - }> = []; - for (const group of repositoryGroups) { - const project = group.projects[0]?.project; - if (!project) { - continue; - } - nextItems.push({ - environmentId: project.environmentId, - id: project.id, - key: group.key, - title: project.title, - workspaceRoot: project.workspaceRoot, - }); - } - return nextItems; - }, [repositoryGroups]); - const projectEmptyState = deriveProjectEmptyState(catalogState); - - return ( - - - - router.push("/new/add-project")} - separateBackground - /> - - - - {items.length === 0 ? ( - - {projectEmptyState.loading ? : null} - - {projectEmptyState.title} - - - {projectEmptyState.detail} - - {!catalogState.hasReadyEnvironment ? ( - router.push("/connections/new")} - > - - Add environment - - - ) : ( - router.push("/new/add-project")} - > - - Add new project - - - )} - - ) : ( - - {items.map((item, index) => { - const isFirst = index === 0; - const isLast = index === items.length - 1; - - return ( - - - - - - - - {item.title} - - - - - - ); - })} - - )} - - - ); -} diff --git a/apps/mobile/src/app/settings/_layout.tsx b/apps/mobile/src/app/settings/_layout.tsx deleted file mode 100644 index 2607c2cd1f..0000000000 --- a/apps/mobile/src/app/settings/_layout.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import Stack from "expo-router/stack"; -import { useCallback } from "react"; -import { useResolveClassNames } from "uniwind"; - -import { useClerkSettingsSheetDetent } from "../../features/cloud/ClerkSettingsSheetDetent"; -import { useThemeColor } from "../../lib/useThemeColor"; - -export const unstable_settings = { - anchor: "index", -}; - -export default function SettingsLayout() { - const { collapse } = useClerkSettingsSheetDetent(); - const contentStyle = useResolveClassNames("bg-sheet"); - const sheetBg = useThemeColor("--color-sheet"); - const headerTint = useThemeColor("--color-foreground"); - const handleExpandedRouteTransitionEnd = useCallback( - (event: { data: { closing: boolean } }) => { - if (event.data.closing) { - collapse(); - } - }, - [collapse], - ); - - return ( - - - - - - - - - ); -} diff --git a/apps/mobile/src/app/settings/archive.tsx b/apps/mobile/src/app/settings/archive.tsx deleted file mode 100644 index 2b900afbbc..0000000000 --- a/apps/mobile/src/app/settings/archive.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen"; - -export default ArchivedThreadsRouteScreen; diff --git a/apps/mobile/src/app/settings/auth.tsx b/apps/mobile/src/app/settings/auth.tsx deleted file mode 100644 index de33207ccd..0000000000 --- a/apps/mobile/src/app/settings/auth.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { useAuth } from "@clerk/expo"; -import { AuthView, UserProfileView } from "@clerk/expo/native"; -import { Redirect, Stack } from "expo-router"; -import { View } from "react-native"; - -import { hasCloudPublicConfig } from "../../features/cloud/publicConfig"; - -export default function SettingsAuthRouteScreen() { - return hasCloudPublicConfig() ? ( - - ) : ( - - ); -} - -function ConfiguredSettingsAuthRouteScreen() { - const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); - - return ( - <> - - - {isLoaded ? ( - isSignedIn ? ( - - ) : ( - - ) - ) : null} - - - ); -} diff --git a/apps/mobile/src/app/settings/environment-new.tsx b/apps/mobile/src/app/settings/environment-new.tsx deleted file mode 100644 index 3fb3e8d3a0..0000000000 --- a/apps/mobile/src/app/settings/environment-new.tsx +++ /dev/null @@ -1 +0,0 @@ -export { default } from "../connections/new"; diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx deleted file mode 100644 index 92e90920e2..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx +++ /dev/null @@ -1,107 +0,0 @@ -import Stack from "expo-router/stack"; -import { StyleSheet } from "react-native"; -import { useResolveClassNames } from "uniwind"; - -export default function ThreadLayout() { - const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet")); - const headerBg = { - backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor, - }; - - return ( - - - - - - - - - - - ); -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/[...path].tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/[...path].tsx deleted file mode 100644 index 225c39f2ec..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/[...path].tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen"; - -export default function ThreadFileRoute() { - return ; -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/index.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/index.tsx deleted file mode 100644 index b67630dbf0..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/files/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen"; - -export default function ThreadFilesIndexRoute() { - return ; -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git-confirm.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git-confirm.tsx deleted file mode 100644 index 3773ce55b2..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git-confirm.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { GitConfirmSheet } from "../../../../features/threads/git/GitConfirmSheet"; - -export default function GitConfirmRoute() { - return ; -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx deleted file mode 100644 index 15b10c295f..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import Stack from "expo-router/stack"; -import { StyleSheet } from "react-native"; -import { useResolveClassNames } from "uniwind"; - -export const unstable_settings = { - anchor: "index", -}; - -export default function GitSheetLayout() { - const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet")); - const headerBg = { - backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor, - }; - - return ( - - - - - - - ); -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/branches.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/branches.tsx deleted file mode 100644 index 955e4febd7..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/branches.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { GitBranchesSheet } from "../../../../../features/threads/git/GitBranchesSheet"; - -export default function GitBranchesRoute() { - return ; -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/commit.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/commit.tsx deleted file mode 100644 index 4510f81a8c..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/commit.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { GitCommitSheet } from "../../../../../features/threads/git/GitCommitSheet"; - -export default function GitCommitRoute() { - return ; -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/index.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/index.tsx deleted file mode 100644 index dd099d80d2..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { GitOverviewSheet } from "../../../../../features/threads/git/GitOverviewSheet"; - -export default function GitRoute() { - return ; -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/review.tsx deleted file mode 100644 index 8ca686c146..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/review.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { Redirect, useLocalSearchParams } from "expo-router"; -import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; - -export default function ReviewRoute() { - const { environmentId, threadId } = useLocalSearchParams<{ - environmentId: EnvironmentId; - threadId: ThreadId; - }>(); - - return ( - - ); -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/index.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/index.tsx deleted file mode 100644 index 4586ee93ca..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { ThreadRouteScreen } from "../../../../features/threads/ThreadRouteScreen"; - -export default function ThreadRoute() { - return ; -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review-comment.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review-comment.tsx deleted file mode 100644 index 281ec34107..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review-comment.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { ReviewCommentComposerSheet } from "../../../../features/review/ReviewCommentComposerSheet"; - -export default function ReviewCommentRoute() { - return ; -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx deleted file mode 100644 index ee993ee7c8..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider"; -import { ReviewSheet } from "../../../../features/review/ReviewSheet"; - -export default function ReviewRoute() { - return ( - - - - ); -} diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/terminal.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/terminal.tsx deleted file mode 100644 index e209a180a4..0000000000 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/terminal.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { ThreadTerminalRouteScreen } from "../../../../features/terminal/ThreadTerminalRouteScreen"; - -export default function ThreadTerminalRoute() { - return ; -} diff --git a/apps/mobile/src/components/AndroidAnchoredMenu.tsx b/apps/mobile/src/components/AndroidAnchoredMenu.tsx new file mode 100644 index 0000000000..c4a0045eef --- /dev/null +++ b/apps/mobile/src/components/AndroidAnchoredMenu.tsx @@ -0,0 +1,337 @@ +import type { MenuAction, MenuComponentProps } from "@react-native-menu/menu"; +import { BlurView } from "expo-blur"; +import type { ReactNode } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; +import type { StyleProp, ViewStyle } from "react-native"; +import { BackHandler, Pressable, ScrollView, useColorScheme, View } from "react-native"; +import { useKeyboardState } from "react-native-keyboard-controller"; +import Animated, { FadeIn } from "react-native-reanimated"; + +import { appBlurTargetRef } from "../lib/appBlurTarget"; +import { useThemeColor } from "../lib/useThemeColor"; +import { cn } from "../lib/cn"; +import { type AppSymbolName, SymbolView } from "./AppSymbol"; +import { AppText as Text } from "./AppText"; +import { OverlayPortal } from "./OverlayPortal"; + +const MENU_WIDTH = 250; +const SCREEN_MARGIN = 12; +const ANCHOR_GAP = 6; + +// Anchor position is snapshotted in window coordinates when the menu opens; +// the overlay root measures itself the same way, and the menu is placed from +// the delta. Both snapshots are taken at open time so later reflows (keyboard +// show/hide, screen transitions) can't flip an opens-up menu to opens-down +// mid-presentation. +type AnchorSnapshot = { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +}; + +type OverlayFrame = { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +}; + +export type AndroidAnchoredMenuProps = { + readonly actions: readonly MenuAction[]; + readonly title?: string; + readonly onPressAction?: MenuComponentProps["onPressAction"]; + /** Applied to the anchor wrapper — call sites flex these to fill toolbars. */ + readonly className?: string; + readonly style?: StyleProp; + /** + * Plain children open the menu on tap (the wrapper owns the press). A + * render function keeps the children interactive and hands them `open` to + * call from their own gesture — e.g. a row that selects on tap and opens + * this menu on long-press. + */ + readonly children: ReactNode | ((open: () => void) => ReactNode); +}; + +/** + * Token-styled anchored dropdown for Android, drop-in for the subset of the + * MenuView contract the app uses (actions with state/subtitle/image/ + * attributes, one level of subactions). The native AppCompat PopupMenu caps + * out on theming — stock animation, item metrics, and submenu chrome — so + * ControlPillMenu renders this instead on Android while iOS keeps the native + * UIMenu. Styling follows the themed native popup (12dp radius, plain rows, + * trailing check glyph); submenus drill in under a muted parent-title header. + */ +export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) { + const [anchor, setAnchor] = useState(null); + const [path, setPath] = useState([]); + // Height of the modal's root view, in the modal's own coordinate space. + // Menus that flip above their anchor are pinned by their BOTTOM edge + // (bottom = rootHeight - anchorTop), so drill-in height changes grow + // upward without any re-measurement — positioning them via `top` from the + // menu's measured height made every submenu transition settle over two + // frames and jitter. + const [rootHeight, setRootHeight] = useState(null); + // Window frame of the overlay root, measured on layout. Anchor coordinates + // are converted into this frame, so the menu lands correctly no matter + // where the portal host sits (status bar, keyboard resize, etc.). + const [overlay, setOverlay] = useState(null); + const anchorRef = useRef(null); + const overlayRef = useRef(null); + + const isDarkMode = useColorScheme() === "dark"; + const keyboardVisible = useKeyboardState((state) => state.isVisible); + const keyboardHeight = useKeyboardState((state) => state.height); + const rippleColor = useThemeColor("--color-subtle"); + const iconColor = useThemeColor("--color-icon"); + const iconSubtleColor = useThemeColor("--color-icon-subtle"); + const dangerColor = useThemeColor("--color-danger-foreground"); + + const close = useCallback(() => { + setAnchor(null); + setPath([]); + setOverlay(null); + setRootHeight(null); + }, []); + + const open = useCallback(() => { + anchorRef.current?.measureInWindow((x, y, width, height) => { + setAnchor({ x, y, width, height }); + }); + }, []); + + const measureOverlay = useCallback(() => { + overlayRef.current?.measureInWindow((x, y, width, height) => { + setOverlay({ x, y, width, height }); + setRootHeight(height); + }); + }, []); + + // The dropdown renders in-window (no Modal takes focus), so the hardware + // back gesture needs explicit handling while it is open. Back steps out of + // a drilled-in submenu one level at a time (mirroring the tappable parent + // header) before closing the menu. Under predictive back + // (enableOnBackInvokedCallback) this stays correct: back reaches JS + // through always-registered OnBackPressedDispatcher callbacks (react-native + // core on Android 16+, withAndroidPredictiveBackCompat on 13-15), which + // also keeps the system from playing a "leave app" preview while the menu + // merely closes. + const submenuDepth = path.length; + useEffect(() => { + if (anchor === null) { + return; + } + const subscription = BackHandler.addEventListener("hardwareBackPress", () => { + if (submenuDepth > 0) { + setPath((current) => current.slice(0, -1)); + } else { + close(); + } + return true; + }); + return () => subscription.remove(); + }, [anchor, close, submenuDepth]); + + const parent = path.length > 0 ? path[path.length - 1] : null; + const levelActions = (parent?.subactions ?? props.actions).filter( + (action) => !(action.attributes?.hidden ?? false), + ); + + // Anchor in overlay-local coordinates (both measured in window space). + const local = + anchor === null || overlay === null + ? null + : { + x: anchor.x - overlay.x, + y: anchor.y - overlay.y, + width: anchor.width, + height: anchor.height, + }; + const preferredLeft = + local === null || overlay === null + ? 0 + : local.x + local.width / 2 <= overlay.width / 2 + ? local.x + : local.x + local.width - MENU_WIDTH; + const left = + overlay === null + ? 0 + : Math.min( + Math.max(preferredLeft, SCREEN_MARGIN), + overlay.width - MENU_WIDTH - SCREEN_MARGIN, + ); + // The keyboard stays up while the menu is open (in-window overlay, no + // focus change), so the space it covers is not usable — without this the + // composer-pill menus "open down" into the IME and can't be tapped. + const usableBottom = + overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0); + const spaceBelow = + local === null || overlay === null + ? 0 + : usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN; + const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN; + const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove; + const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480); + // The menu needs the overlay frame before it can be placed; it stays + // unmounted for that first frame so the fade-in plays at the final position. + const placeable = local !== null && rootHeight !== null; + + const onPressItem = useCallback( + (action: MenuAction) => { + if ((action.subactions?.length ?? 0) > 0) { + setPath((current) => [...current, action]); + return; + } + close(); + if (action.id !== undefined) { + props.onPressAction?.({ + nativeEvent: { event: action.id }, + } as Parameters>[0]); + } + }, + [close, props.onPressAction], + ); + + return ( + <> + {typeof props.children === "function" ? ( + + {props.children(open)} + + ) : ( + + {props.children} + + )} + {anchor === null ? null : ( + + + + {!placeable || local === null ? null : ( + + {/* Frosted backdrop: blur of the app content behind the menu, + washed with the translucent card tone so rows keep contrast. */} + + + {/* keyboardShouldPersistTaps: the menu often opens over an + active editor; the first item tap must act, not just + dismiss the keyboard. */} + + {parent !== null ? ( + // Muted parent title as the submenu header; tapping it + // steps back, but it reads as a label, not a button. + setPath((current) => current.slice(0, -1))} + > + + {parent.title} + + + ) : props.title ? ( + <> + + + {props.title} + + + + + ) : null} + {levelActions.map((action, index) => { + const destructive = action.attributes?.destructive ?? false; + const disabled = action.attributes?.disabled ?? false; + const hasSubmenu = (action.subactions?.length ?? 0) > 0; + return ( + onPressItem(action)} + > + + + {action.title} + + {action.subtitle ? ( + + {action.subtitle} + + ) : null} + + {hasSubmenu ? ( + + ) : action.state === "on" ? ( + + ) : action.image ? ( + + ) : null} + + ); + })} + + + )} + + + )} + + ); +} diff --git a/apps/mobile/src/components/AndroidScreenHeader.tsx b/apps/mobile/src/components/AndroidScreenHeader.tsx new file mode 100644 index 0000000000..ef5319a1b6 --- /dev/null +++ b/apps/mobile/src/components/AndroidScreenHeader.tsx @@ -0,0 +1,117 @@ +import type { ReactNode } from "react"; +import { Pressable, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { SymbolView, type AppSymbolName } from "./AppSymbol"; +import { AppText as Text } from "./AppText"; +import { cn } from "../lib/cn"; +import { useThemeColor } from "../lib/useThemeColor"; + +export interface AndroidHeaderAction { + readonly accessibilityLabel: string; + readonly icon: AppSymbolName; + readonly onPress: () => void; + readonly disabled?: boolean; +} + +export function AndroidHeaderIconButton(props: { + readonly accessibilityLabel: string; + readonly icon: AppSymbolName; + readonly onPress?: () => void; + readonly disabled?: boolean; +}) { + const foregroundColor = useThemeColor("--color-foreground"); + const disabledColor = useThemeColor("--color-icon-subtle"); + + return ( + + + + ); +} + +export function AndroidScreenHeader(props: { + readonly title: string; + readonly subtitle?: string | null; + readonly actions?: ReadonlyArray; + readonly trailing?: ReactNode; + readonly onBack?: () => void; + readonly embedded?: boolean; +}) { + const insets = useSafeAreaInsets(); + const foregroundColor = useThemeColor("--color-foreground"); + + return ( + + + {props.onBack ? ( + + + + ) : null} + + + + {props.title} + + {props.subtitle ? ( + + {props.subtitle} + + ) : null} + + + {props.actions?.map((action) => ( + + ))} + {props.trailing} + + + ); +} + +export function AndroidSheetHeader( + props: Omit[0], "embedded">, +) { + return ; +} diff --git a/apps/mobile/src/components/AppSymbol.tsx b/apps/mobile/src/components/AppSymbol.tsx new file mode 100644 index 0000000000..ac813bdbe0 --- /dev/null +++ b/apps/mobile/src/components/AppSymbol.tsx @@ -0,0 +1,202 @@ +import { + IconAdjustmentsHorizontal, + IconAlertCircle, + IconAlertTriangle, + IconArchive, + IconArrowBackUp, + IconArrowDownCircle, + IconArrowRightCircle, + IconArrowUp, + IconArrowUpCircle, + IconArrowUpRight, + IconArrowUpRightCircle, + IconArrowsMaximize, + IconBellRinging, + IconBolt, + IconCamera, + IconCheck, + IconChevronDown, + IconCode, + IconChevronLeft, + IconChevronRight, + IconChevronUp, + IconCircleCheck, + IconCircleXFilled, + IconCopy, + IconDeviceDesktop, + IconDots, + IconDotsCircleHorizontal, + IconEdit, + IconExternalLink, + IconEye, + IconFileText, + IconFilter, + IconFolder, + IconFolderOpen, + IconFolderPlus, + IconGitBranch, + IconHammer, + IconGitMerge, + IconGitPullRequest, + IconInfoCircle, + IconKeyboard, + IconKeyboardHide, + IconLayoutColumns, + IconLayoutSidebar, + IconLetterSpacing, + IconLink, + IconMessage, + IconMinus, + IconNetwork, + IconPalette, + IconPlayerPlay, + IconPlayerStopFilled, + IconPlus, + IconQrcode, + IconRefresh, + IconSearch, + IconServer, + IconSettings, + IconSparkles, + IconLayoutSidebarRight, + IconTerminal2, + IconTextDecrease, + IconTextIncrease, + IconTool, + IconTrash, + IconTypography, + IconUserCircle, + IconWifiOff, + IconWorld, + IconX, + type Icon, +} from "@tabler/icons-react-native"; +import { Platform } from "react-native"; +import { SymbolView as ExpoSymbolView, type SFSymbol, type SymbolViewProps } from "expo-symbols"; + +const ANDROID_ICON_BY_SF_SYMBOL: Partial> = { + "arrow.branch": IconGitBranch, + "arrow.clockwise": IconRefresh, + "arrow.down.circle": IconArrowDownCircle, + "arrow.right.circle": IconArrowRightCircle, + "arrow.triangle.branch": IconGitBranch, + "arrow.triangle.pull": IconGitPullRequest, + "arrow.turn.left.up": IconArrowBackUp, + "arrow.up": IconArrowUp, + "arrow.up.circle": IconArrowUpCircle, + "arrow.up.left.and.arrow.down.right": IconArrowsMaximize, + "arrow.up.right": IconArrowUpRight, + "arrow.up.right.circle": IconArrowUpRightCircle, + "arrow.uturn.backward": IconArrowBackUp, + archivebox: IconArchive, + "archivebox.fill": IconArchive, + "bell.badge": IconBellRinging, + "bolt.circle": IconBolt, + "bolt.horizontal.circle": IconBolt, + camera: IconCamera, + checkmark: IconCheck, + "checkmark.circle": IconCircleCheck, + "chevron.down": IconChevronDown, + "chevron.left": IconChevronLeft, + "chevron.left.forwardslash.chevron.right": IconCode, + "chevron.right": IconChevronRight, + "chevron.up": IconChevronUp, + desktopcomputer: IconDeviceDesktop, + "doc.on.doc": IconCopy, + "doc.text": IconFileText, + ellipsis: IconDots, + "ellipsis.circle": IconDotsCircleHorizontal, + "exclamationmark.triangle": IconAlertTriangle, + eye: IconEye, + folder: IconFolder, + "folder.badge.plus": IconFolderPlus, + "folder.fill": IconFolder, + gearshape: IconSettings, + "info.circle": IconInfoCircle, + link: IconLink, + "line.3.horizontal.decrease.circle": IconFilter, + "line.3.horizontal.decrease.circle.fill": IconFilter, + magnifyingglass: IconSearch, + paintbrush: IconPalette, + "person.crop.circle": IconUserCircle, + play: IconPlayerPlay, + plus: IconPlus, + "qrcode.viewfinder": IconQrcode, + "point.3.connected.trianglepath.dotted": IconNetwork, + "point.topleft.down.curvedto.point.bottomright.up": IconGitMerge, + safari: IconExternalLink, + "server.rack": IconServer, + "sidebar.left": IconLayoutSidebar, + "sidebar.right": IconLayoutSidebarRight, + "slider.horizontal.3": IconAdjustmentsHorizontal, + "square.and.pencil": IconEdit, + "square.split.2x1": IconLayoutColumns, + "stop.fill": IconPlayerStopFilled, + terminal: IconTerminal2, + "text.bubble": IconMessage, + "text.word.spacing": IconLetterSpacing, + "textformat.size": IconTypography, + "textformat.size.larger": IconTextIncrease, + "textformat.size.smaller": IconTextDecrease, + trash: IconTrash, + "wifi.slash": IconWifiOff, + xmark: IconX, + "xmark.circle.fill": IconCircleXFilled, +}; + +// Callers can pass `{ ios, android }` names where `android` is a Material +// icon name (the raw expo-symbols contract). Resolve those here too so the +// android key keeps working through this wrapper — it wins over the SF map +// when both match (e.g. folder vs folder_open for expanded project groups). +const ANDROID_ICON_BY_MATERIAL_NAME: Record = { + auto_awesome: IconSparkles, + bolt: IconBolt, + build: IconTool, + chat_bubble: IconMessage, + check: IconCheck, + close: IconX, + construction: IconHammer, + content_copy: IconCopy, + edit: IconEdit, + error: IconAlertCircle, + folder: IconFolder, + folder_open: IconFolderOpen, + keyboard: IconKeyboard, + keyboard_arrow_down: IconChevronDown, + keyboard_arrow_up: IconChevronUp, + keyboard_hide: IconKeyboardHide, + public: IconWorld, + remove: IconMinus, + terminal: IconTerminal2, + visibility: IconEye, +}; + +export type { SFSymbol } from "expo-symbols"; +export type AppSymbolName = SymbolViewProps["name"]; + +export function SymbolView(props: SymbolViewProps) { + if (Platform.OS !== "android") { + return ; + } + + const materialName = typeof props.name === "string" ? undefined : props.name.android; + const sfSymbol = typeof props.name === "string" ? props.name : props.name.ios; + const AndroidIcon = + (materialName ? ANDROID_ICON_BY_MATERIAL_NAME[materialName] : undefined) ?? + (sfSymbol ? ANDROID_ICON_BY_SF_SYMBOL[sfSymbol] : undefined); + + if (!AndroidIcon) { + return props.fallback ?? null; + } + + return ( + + ); +} diff --git a/apps/mobile/src/components/AppText.tsx b/apps/mobile/src/components/AppText.tsx index d98a8573e6..39517f0e62 100644 --- a/apps/mobile/src/components/AppText.tsx +++ b/apps/mobile/src/components/AppText.tsx @@ -1,11 +1,9 @@ -import type { Ref } from "react"; import { Text as RNText, TextInput as RNTextInput, type TextInputProps as RNTextInputProps, type TextProps as RNTextProps, } from "react-native"; -import { useThemeColor } from "../lib/useThemeColor"; import { cn } from "../lib/cn"; @@ -19,31 +17,24 @@ export function AppText({ className, ...props }: AppTextProps) { return ; } -export type AppTextInputProps = RNTextInputProps & { +export type AppTextInputProps = Omit & { readonly className?: string; - readonly ref?: Ref; + readonly ref?: React.Ref; }; /** * Thin wrapper around RN TextInput with default input styling. * Uses Uniwind className — no manual style parsing. */ -export function AppTextInput({ - className, - placeholderTextColor, - ref, - ...props -}: AppTextInputProps) { - const placeholderColor = useThemeColor("--color-placeholder"); - +export function AppTextInput({ className, ref, ...props }: AppTextInputProps) { return ( ); diff --git a/apps/mobile/src/components/BrandMark.tsx b/apps/mobile/src/components/BrandMark.tsx index 78aaf6b0ce..c8f1d43855 100644 --- a/apps/mobile/src/components/BrandMark.tsx +++ b/apps/mobile/src/components/BrandMark.tsx @@ -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 ( @@ -22,14 +32,9 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab /> - - T3 Code - + T3 Code - + {stageLabel} diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index 5b4d3d626c..0621285c03 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -1,4 +1,4 @@ -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "../components/AppSymbol"; import { Image, Pressable, ScrollView, View } from "react-native"; import { useThemeColor } from "../lib/useThemeColor"; @@ -39,14 +39,14 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) { horizontal showsHorizontalScrollIndicator={false} keyboardShouldPersistTaps="always" - style={{ flexGrow: 0 }} + className="grow-0" > - + {props.attachments.map((image) => ( props.onRemove(image.id)} diff --git a/apps/mobile/src/components/ComposerToolbarTrigger.tsx b/apps/mobile/src/components/ComposerToolbarTrigger.tsx index e054a13f69..2018762496 100644 --- a/apps/mobile/src/components/ComposerToolbarTrigger.tsx +++ b/apps/mobile/src/components/ComposerToolbarTrigger.tsx @@ -1,4 +1,3 @@ -import { SymbolView } from "expo-symbols"; import type { ComponentProps, ReactNode } from "react"; import { useCallback, useMemo, useState } from "react"; import { @@ -16,6 +15,7 @@ import { import { useThemeColor } from "../lib/useThemeColor"; import { cn } from "../lib/cn"; import { AppText as Text } from "./AppText"; +import { SymbolView } from "./AppSymbol"; export const COMPOSER_TOOLBAR_CONTROL_HEIGHT = 44; export const COMPOSER_TOOLBAR_GAP = 8; @@ -31,11 +31,9 @@ export function ComposerToolbarRow(props: { }) { return ( + ; }) { const isDarkMode = useColorScheme() === "dark"; @@ -183,7 +182,11 @@ export function ComposerToolbarButton(props: { disabled={props.disabled} onPress={props.onPress} className={cn( - "h-11 flex-row items-center justify-center rounded-full active:opacity-70", + // Default width cap lives in the class chain (not the inline style) + // so callers can lift it with max-w-full — flex-filling pills in the + // thread composer stretch to the row's edge. The numeric maxWidth + // prop still wins via the inline style below. + "h-11 max-w-[172px] flex-row items-center justify-center rounded-full active:opacity-70", isCircle ? "w-11" : "gap-2 px-3.5", variant === "primary" ? props.disabled @@ -194,6 +197,7 @@ export function ComposerToolbarButton(props: { : props.active ? "bg-subtle-strong" : "bg-subtle", + props.className, )} style={({ pressed }) => [ { @@ -204,7 +208,7 @@ export function ComposerToolbarButton(props: { : defaultBorderColor : filledBorderColor, borderWidth: 1, - maxWidth: props.maxWidth ?? 172, + maxWidth: props.maxWidth, minWidth: props.minWidth, opacity: props.disabled ? 0.55 : pressed ? 0.72 : 1, shadowColor: "#000", diff --git a/apps/mobile/src/components/ConfirmDialogHost.tsx b/apps/mobile/src/components/ConfirmDialogHost.tsx new file mode 100644 index 0000000000..81daa3d6a2 --- /dev/null +++ b/apps/mobile/src/components/ConfirmDialogHost.tsx @@ -0,0 +1,111 @@ +import { useCallback, useEffect, useState } from "react"; +import { Modal, Pressable, View } from "react-native"; + +import { useThemeColor } from "../lib/useThemeColor"; +import { cn } from "../lib/cn"; +import { AppText } from "./AppText"; + +export type ConfirmDialogRequest = { + readonly title: string; + readonly message?: string; + readonly cancelText?: string; + readonly confirmText: string; + readonly destructive?: boolean; + readonly onConfirm: () => void; + readonly onCancel?: () => void; +}; + +let presentRequest: ((request: ConfirmDialogRequest) => void) | null = null; + +/** + * Imperative confirm dialog, Alert.alert-shaped. Native iOS alerts already + * match the app (and support per-button destructive red), so this is for + * Android, where the native dialog can only theme all confirm buttons at + * once. Requires ConfirmDialogHost to be mounted at the app root. + */ +export function showConfirmDialog(request: ConfirmDialogRequest): void { + presentRequest?.(request); +} + +/** + * Android-style alert dialog matching the native one themed by + * withAndroidModernAlertDialog — left-aligned text, right-aligned text + * buttons — with what the native theme can't do: a per-dialog destructive + * button color and a dimmer message than the title. + */ +export function ConfirmDialogHost() { + const [request, setRequest] = useState(null); + const pressedOverlay = useThemeColor("--color-subtle"); + + useEffect(() => { + presentRequest = setRequest; + return () => { + presentRequest = null; + }; + }, []); + + const handleCancel = useCallback(() => { + request?.onCancel?.(); + setRequest(null); + }, [request]); + + const handleConfirm = useCallback(() => { + request?.onConfirm(); + setRequest(null); + }, [request]); + + return ( + + {request === null ? null : ( + + + {request.title} + {request.message === undefined ? null : ( + + {request.message} + + )} + + + + + {request.cancelText ?? "Cancel"} + + + + + + + {request.confirmText} + + + + + + + )} + + ); +} diff --git a/apps/mobile/src/components/ControlPill.tsx b/apps/mobile/src/components/ControlPill.tsx index 62c1b06178..31e95cf9db 100644 --- a/apps/mobile/src/components/ControlPill.tsx +++ b/apps/mobile/src/components/ControlPill.tsx @@ -1,10 +1,18 @@ import { MenuView } from "@react-native-menu/menu"; -import type { ComponentProps, ReactNode } from "react"; -import { Pressable, useColorScheme, View } from "react-native"; -import { SymbolView } from "expo-symbols"; +import * as Haptics from "expo-haptics"; +import { + cloneElement, + isValidElement, + type ComponentProps, + type ReactElement, + type ReactNode, +} from "react"; +import { Platform, Pressable, useColorScheme, View } from "react-native"; import { useThemeColor } from "../lib/useThemeColor"; import { cn } from "../lib/cn"; +import { AndroidAnchoredMenu } from "./AndroidAnchoredMenu"; +import { SymbolView } from "./AppSymbol"; import { AppText as Text } from "./AppText"; export function ControlPill(props: { @@ -74,16 +82,60 @@ export function ControlPill(props: { ); } +// iOS renders the native UIMenu (standard checkmark for `state: "on"`); +// Android renders the token-styled AndroidAnchoredMenu, since the native +// AppCompat popup can't be themed past its stock animation, metrics, and +// submenu chrome. export function ControlPillMenu( - props: Omit, "children" | "style" | "themeVariant"> & { + props: Omit, "children" | "themeVariant"> & { readonly children: ReactNode; + readonly className?: string; }, ) { const isDarkMode = useColorScheme() === "dark"; + if (Platform.OS === "android") { + // Long-press menus keep their child interactive: the child element gets + // an injected onLongPress (mirroring the iOS context-menu interaction) + // so its own tap handling still works. + if (props.shouldOpenOnLongPress && isValidElement(props.children)) { + const child = props.children as ReactElement<{ onLongPress?: () => void }>; + return ( + + {(open) => + cloneElement(child, { + onLongPress: () => { + void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium); + open(); + }, + }) + } + + ); + } + return ( + + {props.children} + + ); + } + + const { className: _className, ...menuProps } = props; return ( - - {props.children} + + {menuProps.children} ); } diff --git a/apps/mobile/src/components/CopyTextButton.tsx b/apps/mobile/src/components/CopyTextButton.tsx index 712b272a90..7f4e060eda 100644 --- a/apps/mobile/src/components/CopyTextButton.tsx +++ b/apps/mobile/src/components/CopyTextButton.tsx @@ -1,4 +1,4 @@ -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "../components/AppSymbol"; import { memo, useEffect, useRef, useState } from "react"; import { Pressable, type ColorValue } from "react-native"; @@ -58,7 +58,11 @@ export const CopyTextButton = memo(function CopyTextButton(props: { })} > void; + readonly variant?: "card" | "plain"; }) { + if (props.variant === "plain") { + return ( + + {props.title} + + {props.detail} + + {props.actionLabel && props.onAction ? ( + + + {props.actionLabel} + + + ) : null} + + ); + } + return ( {props.title} - + {props.detail} {props.actionLabel && props.onAction ? ( diff --git a/apps/mobile/src/components/ErrorBanner.tsx b/apps/mobile/src/components/ErrorBanner.tsx index d47f924b39..76e06edcd1 100644 --- a/apps/mobile/src/components/ErrorBanner.tsx +++ b/apps/mobile/src/components/ErrorBanner.tsx @@ -4,7 +4,7 @@ import { AppText as Text } from "./AppText"; export function ErrorBanner(props: { readonly message: string }) { return ( - + {props.message} diff --git a/apps/mobile/src/components/GlassSafeAreaView.tsx b/apps/mobile/src/components/GlassSafeAreaView.tsx index 836a7cffbd..8f91d61031 100644 --- a/apps/mobile/src/components/GlassSafeAreaView.tsx +++ b/apps/mobile/src/components/GlassSafeAreaView.tsx @@ -39,22 +39,12 @@ export function GlassSafeAreaView({ style={{ borderRadius: 0, backgroundColor: "transparent" }} > - {leftSlot} - - {centerSlot} - - {rightSlot} + {leftSlot} + {centerSlot} + {rightSlot} diff --git a/apps/mobile/src/components/GlassSurface.tsx b/apps/mobile/src/components/GlassSurface.tsx index 03311e3b7e..f34bd4e283 100644 --- a/apps/mobile/src/components/GlassSurface.tsx +++ b/apps/mobile/src/components/GlassSurface.tsx @@ -10,7 +10,7 @@ import { } from "react-native"; import { useThemeColor } from "../lib/useThemeColor"; -export interface GlassSurfaceProps extends ViewProps { +export interface GlassSurfaceProps extends Omit { readonly children: ReactNode; readonly glassEffectStyle?: "clear" | "regular" | "none"; readonly tintColor?: ColorValue; diff --git a/apps/mobile/src/components/OverlayPortal.tsx b/apps/mobile/src/components/OverlayPortal.tsx new file mode 100644 index 0000000000..747595174f --- /dev/null +++ b/apps/mobile/src/components/OverlayPortal.tsx @@ -0,0 +1,69 @@ +import { type ReactNode, useEffect, useRef, useState } from "react"; +import { View } from "react-native"; + +// Minimal in-tree portal for Android overlays. AndroidAnchoredMenu projects +// its dropdown here instead of into an RN Modal: a Modal is a separate native +// window, so presenting one moves window focus and closes the soft keyboard — +// which matters for menus anchored to the keyboard-sticky composer pills. +type Entries = ReadonlyMap; +type Listener = (entries: Entries) => void; + +let nextKey = 0; +const entries = new Map(); +const listeners = new Set(); + +function emit() { + const snapshot = new Map(entries); + for (const listener of listeners) { + listener(snapshot); + } +} + +/** Projects children into the app-root OverlayPortalHost. */ +export function OverlayPortal(props: { readonly children: ReactNode }) { + const keyRef = useRef(null); + keyRef.current ??= nextKey++; + const key = keyRef.current; + + // No dependency array: re-project after every render so the host always + // shows the current content (menus re-render while open — drill-in, theme). + useEffect(() => { + entries.set(key, props.children); + emit(); + }); + + useEffect( + () => () => { + entries.delete(key); + emit(); + }, + [key], + ); + + return null; +} + +/** Mounted once at the app root, above the navigation container. */ +export function OverlayPortalHost() { + const [current, setCurrent] = useState(() => new Map()); + + useEffect(() => { + listeners.add(setCurrent); + return () => { + listeners.delete(setCurrent); + }; + }, []); + + if (current.size === 0) { + return null; + } + return ( + + {[...current.entries()].map(([key, node]) => ( + + {node} + + ))} + + ); +} diff --git a/apps/mobile/src/components/PierreEntryIcon.tsx b/apps/mobile/src/components/PierreEntryIcon.tsx index 15ea24331b..fa79c4f60e 100644 --- a/apps/mobile/src/components/PierreEntryIcon.tsx +++ b/apps/mobile/src/components/PierreEntryIcon.tsx @@ -1,4 +1,4 @@ -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "../components/AppSymbol"; import { Image, type ImageStyle, type StyleProp } from "react-native"; import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons"; diff --git a/apps/mobile/src/components/ProjectFavicon.tsx b/apps/mobile/src/components/ProjectFavicon.tsx index ba306c5a9f..772d5e8cc1 100644 --- a/apps/mobile/src/components/ProjectFavicon.tsx +++ b/apps/mobile/src/components/ProjectFavicon.tsx @@ -1,7 +1,9 @@ -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "./AppSymbol"; +import { Image } from "expo-image"; import { useState } from "react"; -import { Image, View } from "react-native"; +import { View } from "react-native"; import type { EnvironmentId } from "@t3tools/contracts"; +import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon"; import { useThemeColor } from "../lib/useThemeColor"; import { useAssetUrl } from "../state/assets"; @@ -11,6 +13,7 @@ const loadedFaviconUrls = new Set(); /* ─── Component ──────────────────────────────────────────────────────── */ export function ProjectFavicon(props: { readonly environmentId: EnvironmentId; + readonly open?: boolean; readonly size?: number; readonly projectTitle: string; readonly workspaceRoot?: string | null; @@ -22,11 +25,13 @@ export function ProjectFavicon(props: { ? null : { _tag: "project-favicon", cwd: props.workspaceRoot }, ); + const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl; return ( @@ -35,6 +40,7 @@ export function ProjectFavicon(props: { function ProjectFaviconImage(props: { readonly faviconUrl: string | null; + readonly open?: boolean; readonly projectTitle: string; readonly size: number; }) { @@ -58,7 +64,7 @@ function ProjectFaviconImage(props: { {/* Folder icon fallback (matches web's FolderIcon) */} {!showImage ? ( { if (props.faviconUrl) loadedFaviconUrls.add(props.faviconUrl); setStatus("loaded"); diff --git a/apps/mobile/src/components/T3Wordmark.tsx b/apps/mobile/src/components/T3Wordmark.tsx new file mode 100644 index 0000000000..81106557c6 --- /dev/null +++ b/apps/mobile/src/components/T3Wordmark.tsx @@ -0,0 +1,23 @@ +import type { ColorValue } from "react-native"; +import Svg, { Path } from "react-native-svg"; + +/** + * The "T3" brand mark, matching the desktop sidebar's T3Wordmark SVG + * (apps/web Sidebar.tsx). Width derives from the viewBox aspect ratio. + */ +export function T3Wordmark(props: { readonly height: number; readonly color: ColorValue }) { + const aspectRatio = 94.3941 / 56.96; + return ( + + + + ); +} diff --git a/apps/mobile/src/connection/catalog-store.ts b/apps/mobile/src/connection/catalog-store.ts index b5bda40067..6a4fcd35f6 100644 --- a/apps/mobile/src/connection/catalog-store.ts +++ b/apps/mobile/src/connection/catalog-store.ts @@ -10,6 +10,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; +import * as MobileSecureStorage from "../persistence/mobile-secure-storage"; import { migrateLegacyConnectionCatalog } from "./migration"; export const CONNECTION_CATALOG_KEY = "t3code.connection-catalog.v1"; @@ -22,23 +23,22 @@ function catalogError(operation: string, cause: unknown) { }); } +const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument); +const decodeConnectionCatalogDocument = Schema.decodeEffect(ConnectionCatalogDocumentJson); +const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson); + const decodeCatalog = Effect.fn("mobile.connectionStorage.decodeCatalog")(function* (raw: string) { - const parsed = yield* Effect.try({ - try: () => JSON.parse(raw) as unknown, - catch: (cause) => catalogError("decode", cause), - }); - return yield* Effect.fromResult( - Schema.decodeUnknownResult(ConnectionCatalogDocument)(parsed), - ).pipe(Effect.mapError((cause) => catalogError("decode", cause))); + return yield* decodeConnectionCatalogDocument(raw).pipe( + Effect.mapError((cause) => catalogError("decode", cause)), + ); }); const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(function* ( catalog: ConnectionCatalogDocumentType, ) { - const encoded = yield* Effect.fromResult( - Schema.encodeUnknownResult(ConnectionCatalogDocument)(catalog), - ).pipe(Effect.mapError((cause) => catalogError("encode", cause))); - return JSON.stringify(encoded); + return yield* encodeConnectionCatalogDocument(catalog).pipe( + Effect.mapError((cause) => catalogError("encode", cause)), + ); }); interface CatalogStore { @@ -48,20 +48,19 @@ interface CatalogStore { ) => Effect.Effect; } -export interface SecureCatalogStorage { - readonly getItem: (key: string) => Effect.Effect; - readonly setItem: (key: string, value: string) => Effect.Effect; - readonly deleteItem: (key: string) => Effect.Effect; -} - -export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogStore")(function* ( - storage: SecureCatalogStorage, -) { +export const make = Effect.fn("mobile.connectionStorage.makeCatalogStore")(function* () { + const storage = yield* MobileSecureStorage.MobileSecureStorage; + const getItem = (key: string) => + storage.getItem(key).pipe(Effect.mapError((cause) => catalogError("load", cause))); + const setItem = (key: string, value: string) => + storage.setItem(key, value).pipe(Effect.mapError((cause) => catalogError("save", cause))); + const deleteItem = (key: string) => + storage.removeItem(key).pipe(Effect.mapError((cause) => catalogError("delete", cause))); const state = yield* Ref.make>(Option.none()); const lock = yield* Semaphore.make(1); const loadLegacyCatalog = Effect.fn("mobile.connectionStorage.loadLegacyCatalog")(function* () { - const legacyRaw = yield* storage.getItem(LEGACY_CONNECTIONS_KEY); + const legacyRaw = yield* getItem(LEGACY_CONNECTIONS_KEY); const catalog = legacyRaw === null || legacyRaw.trim() === "" ? EMPTY_CONNECTION_CATALOG_DOCUMENT @@ -75,8 +74,8 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS ); if (legacyRaw !== null && legacyRaw.trim() !== "") { const encoded = yield* encodeCatalog(catalog); - yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded); - yield* storage.deleteItem(LEGACY_CONNECTIONS_KEY); + yield* setItem(CONNECTION_CATALOG_KEY, encoded); + yield* deleteItem(LEGACY_CONNECTIONS_KEY); } return catalog; }); @@ -86,13 +85,13 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS if (Option.isSome(cached)) { return cached.value; } - const raw = yield* storage.getItem(CONNECTION_CATALOG_KEY); + const raw = yield* getItem(CONNECTION_CATALOG_KEY); let catalog: ConnectionCatalogDocumentType; if (raw !== null && raw.trim() !== "") { catalog = yield* decodeCatalog(raw).pipe( Effect.catch((error) => Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe( - Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)), + Effect.andThen(deleteItem(CONNECTION_CATALOG_KEY)), Effect.andThen(loadLegacyCatalog()), ), ), @@ -111,7 +110,7 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS Effect.gen(function* () { const next = transform(yield* loadUnlocked()); const encoded = yield* encodeCatalog(next); - yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded); + yield* setItem(CONNECTION_CATALOG_KEY, encoded); yield* Ref.set(state, Option.some(next)); }), ); diff --git a/apps/mobile/src/connection/environment-cache-store.test.ts b/apps/mobile/src/connection/environment-cache-store.test.ts new file mode 100644 index 0000000000..0caf2b4159 --- /dev/null +++ b/apps/mobile/src/connection/environment-cache-store.test.ts @@ -0,0 +1,97 @@ +import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-database"; +import { make } from "./environment-cache-store"; + +const ENVIRONMENT_ID = EnvironmentId.make("environment-1"); +const REFS: VcsListRefsResult = { + refs: [ + { + name: "main", + current: true, + isDefault: true, + worktreePath: "/repo", + }, + ], + isRepo: true, + hasPrimaryRemote: true, + nextCursor: null, + totalCount: 1, +}; + +function cacheId(environmentId: EnvironmentId, kind: ClientCacheKind, cacheKey: string) { + return `${environmentId}:${kind}:${cacheKey}`; +} + +function makeDatabase() { + const values = new Map(); + const removed: Array = []; + const database = MobileDatabase.of({ + loadCache: (environmentId, kind, cacheKey) => + Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))), + saveCache: (environmentId, kind, cacheKey, _schemaVersion, payload) => + Effect.sync(() => { + values.set(cacheId(environmentId, kind, cacheKey), payload); + }), + removeCache: (environmentId, kind, cacheKey) => + Effect.sync(() => { + const id = cacheId(environmentId, kind, cacheKey); + removed.push(id); + values.delete(id); + }), + clearEnvironmentCache: (environmentId) => + Effect.sync(() => { + for (const key of values.keys()) { + if (key.startsWith(`${environmentId}:`)) values.delete(key); + } + }), + clearAllCaches: Effect.sync(() => values.clear()), + inspectCaches: Effect.succeed([]), + loadPreferencesJson: Effect.succeed(Option.none()), + savePreferencesJson: () => Effect.void, + }); + return { database, removed, values }; +} + +describe("mobile SQLite environment cache store", () => { + it.effect("round-trips schema-validated VCS refs", () => + Effect.gen(function* () { + const memory = makeDatabase(); + const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database)); + + yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS); + + expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.some(REFS)); + }), + ); + + it.effect("deletes a corrupt cache record and treats it as a miss", () => + Effect.gen(function* () { + const memory = makeDatabase(); + const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database)); + const id = cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo"); + memory.values.set(id, "{not-json"); + + expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none()); + expect(memory.removed).toEqual([id]); + }), + ); + + it.effect("clears one environment without touching another", () => + Effect.gen(function* () { + const memory = makeDatabase(); + const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database)); + const otherEnvironmentId = EnvironmentId.make("environment-2"); + yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS); + yield* store.saveVcsRefs(otherEnvironmentId, "/repo", REFS); + + yield* store.clear(ENVIRONMENT_ID); + + expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none()); + expect(yield* store.loadVcsRefs(otherEnvironmentId, "/repo")).toEqual(Option.some(REFS)); + }), + ); +}); diff --git a/apps/mobile/src/connection/environment-cache-store.ts b/apps/mobile/src/connection/environment-cache-store.ts new file mode 100644 index 0000000000..6808dd420d --- /dev/null +++ b/apps/mobile/src/connection/environment-cache-store.ts @@ -0,0 +1,234 @@ +import { + ConnectionPersistenceError, + EnvironmentCacheStore, +} from "@t3tools/client-runtime/platform"; +import { + type EnvironmentId, + OrchestrationV2ShellSnapshot, + OrchestrationV2ThreadDetailSnapshot, + ServerConfig, + VcsListRefsResult, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import * as MobileDatabase from "../persistence/mobile-database"; + +const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1; +const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2; +const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1; +const VCS_REFS_CACHE_SCHEMA_VERSION = 1; + +const StoredShellSnapshot = Schema.Struct({ + schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION), + environmentId: Schema.String, + snapshot: OrchestrationV2ShellSnapshot, +}); +const StoredThreadSnapshot = Schema.Struct({ + schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION), + environmentId: Schema.String, + threadId: Schema.String, + snapshot: OrchestrationV2ThreadDetailSnapshot, +}); +const StoredServerConfig = Schema.Struct({ + schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION), + environmentId: Schema.String, + config: ServerConfig, +}); +const StoredVcsRefs = Schema.Struct({ + schemaVersion: Schema.Literal(VCS_REFS_CACHE_SCHEMA_VERSION), + environmentId: Schema.String, + cwd: Schema.String, + refs: VcsListRefsResult, +}); + +const decodeStoredShellSnapshot = Schema.decodeUnknownEffect( + Schema.fromJsonString(StoredShellSnapshot), +); +const encodeStoredShellSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredShellSnapshot)); +const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect( + Schema.fromJsonString(StoredThreadSnapshot), +); +const encodeStoredThreadSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredThreadSnapshot)); +const decodeStoredServerConfig = Schema.decodeUnknownEffect( + Schema.fromJsonString(StoredServerConfig), +); +const encodeStoredServerConfig = Schema.encodeEffect(Schema.fromJsonString(StoredServerConfig)); +const decodeStoredVcsRefs = Schema.decodeUnknownEffect(Schema.fromJsonString(StoredVcsRefs)); +const encodeStoredVcsRefs = Schema.encodeEffect(Schema.fromJsonString(StoredVcsRefs)); + +type CacheOperation = ConnectionPersistenceError["operation"]; + +function persistenceError(operation: CacheOperation, cause: unknown) { + return new ConnectionPersistenceError({ + operation, + message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`, + }); +} + +function mapDatabaseError(operation: CacheOperation) { + return (error: MobileDatabase.MobileDatabaseError) => persistenceError(operation, error); +} + +function loadDecodedCache(input: { + readonly database: MobileDatabase.MobileDatabase["Service"]; + readonly environmentId: EnvironmentId; + readonly kind: MobileDatabase.ClientCacheKind; + readonly cacheKey: string; + readonly operation: CacheOperation; + readonly decode: (raw: string) => Effect.Effect; + readonly select: (value: A) => Option.Option; +}): Effect.Effect, ConnectionPersistenceError> { + return input.database.loadCache(input.environmentId, input.kind, input.cacheKey).pipe( + Effect.mapError(mapDatabaseError(input.operation)), + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(Option.none()), + onSome: (raw) => + input.decode(raw).pipe( + Effect.map(input.select), + Effect.catch((cause) => + Effect.logWarning("Discarding corrupt mobile client cache record.", { + environmentId: input.environmentId, + kind: input.kind, + cacheKey: input.cacheKey, + cause: String(cause), + }).pipe( + Effect.andThen( + input.database + .removeCache(input.environmentId, input.kind, input.cacheKey) + .pipe(Effect.catch(() => Effect.void)), + ), + Effect.as(Option.none()), + ), + ), + ), + }), + ), + ); +} + +export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () { + const database = yield* MobileDatabase.MobileDatabase; + return EnvironmentCacheStore.of({ + loadShell: Effect.fn("MobileEnvironmentCache.loadShell")((environmentId) => + loadDecodedCache({ + database, + environmentId, + kind: "shell", + cacheKey: "snapshot", + operation: "load-shell", + decode: decodeStoredShellSnapshot, + select: (stored) => + stored.environmentId === environmentId ? Option.some(stored.snapshot) : Option.none(), + }), + ), + saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) { + const payload = yield* encodeStoredShellSnapshot({ + schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, + environmentId, + snapshot, + }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause))); + yield* database + .saveCache(environmentId, "shell", "snapshot", SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, payload) + .pipe(Effect.mapError(mapDatabaseError("save-shell"))); + }), + loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) => + loadDecodedCache({ + database, + environmentId, + kind: "thread", + cacheKey: threadId, + operation: "load-thread", + decode: decodeStoredThreadSnapshot, + select: (stored) => + stored.environmentId === environmentId && stored.threadId === threadId + ? Option.some(stored.snapshot) + : Option.none(), + }), + ), + saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) { + const threadId = snapshot.projection.thread.id; + const payload = yield* encodeStoredThreadSnapshot({ + schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, + environmentId, + threadId, + snapshot, + }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause))); + yield* database + .saveCache(environmentId, "thread", threadId, THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, payload) + .pipe(Effect.mapError(mapDatabaseError("save-thread"))); + }), + removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) => + database + .removeCache(environmentId, "thread", threadId) + .pipe(Effect.mapError(mapDatabaseError("remove-thread"))), + ), + loadServerConfig: Effect.fn("MobileEnvironmentCache.loadServerConfig")((environmentId) => + loadDecodedCache({ + database, + environmentId, + kind: "server-config", + cacheKey: "config", + operation: "load-server-config", + decode: decodeStoredServerConfig, + select: (stored) => + stored.environmentId === environmentId ? Option.some(stored.config) : Option.none(), + }), + ), + saveServerConfig: Effect.fn("MobileEnvironmentCache.saveServerConfig")( + function* (environmentId, config) { + const payload = yield* encodeStoredServerConfig({ + schemaVersion: SERVER_CONFIG_CACHE_SCHEMA_VERSION, + environmentId, + config, + }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause))); + yield* database + .saveCache( + environmentId, + "server-config", + "config", + SERVER_CONFIG_CACHE_SCHEMA_VERSION, + payload, + ) + .pipe(Effect.mapError(mapDatabaseError("save-server-config"))); + }, + ), + loadVcsRefs: Effect.fn("MobileEnvironmentCache.loadVcsRefs")((environmentId, cwd) => + loadDecodedCache({ + database, + environmentId, + kind: "vcs-refs", + cacheKey: cwd, + operation: "load-vcs-refs", + decode: decodeStoredVcsRefs, + select: (stored) => + stored.environmentId === environmentId && stored.cwd === cwd + ? Option.some(stored.refs) + : Option.none(), + }), + ), + saveVcsRefs: Effect.fn("MobileEnvironmentCache.saveVcsRefs")( + function* (environmentId, cwd, refs) { + const payload = yield* encodeStoredVcsRefs({ + schemaVersion: VCS_REFS_CACHE_SCHEMA_VERSION, + environmentId, + cwd, + refs, + }).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause))); + yield* database + .saveCache(environmentId, "vcs-refs", cwd, VCS_REFS_CACHE_SCHEMA_VERSION, payload) + .pipe(Effect.mapError(mapDatabaseError("save-vcs-refs"))); + }, + ), + clear: Effect.fn("MobileEnvironmentCache.clear")((environmentId) => + database + .clearEnvironmentCache(environmentId) + .pipe(Effect.mapError(mapDatabaseError("clear-environment"))), + ), + }); +}); + +export const layer = Layer.effect(EnvironmentCacheStore, make()); diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts index 769632a8fc..cc51b56ee7 100644 --- a/apps/mobile/src/connection/platform.ts +++ b/apps/mobile/src/connection/platform.ts @@ -25,7 +25,8 @@ import * as Network from "expo-network"; import { AppState } from "react-native"; import { authClientMetadata } from "../lib/authClientMetadata"; -import { loadOrCreateAgentAwarenessDeviceId } from "../lib/storage"; +import * as Runtime from "../lib/runtime"; +import * as MobileStorage from "../persistence/mobile-storage"; import { appAtomRegistry } from "../state/atom-registry"; import { clearThreadOutboxEnvironment } from "../state/thread-outbox"; import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts"; @@ -83,82 +84,87 @@ const wakeupsLayer = Wakeups.layer({ ), }); -const capabilitiesLayer = Layer.succeedContext( - Context.make( - CloudSession, - CloudSession.of({ - clerkToken: Effect.gen(function* () { - const session = appAtomRegistry.get(managedRelaySessionAtom); - if (session === null) { - return yield* new ConnectionBlockedError({ - reason: "authentication", - detail: "Sign in to T3 Cloud to connect this environment.", - }); - } - const token = yield* session.readClerkToken().pipe( - Effect.mapError( - (error) => - new ConnectionTransientError({ - reason: "network", - detail: error.message, +const capabilitiesLayer = Layer.effectContext( + Effect.gen(function* () { + const storage = yield* MobileStorage.MobileStorage; + return Context.make( + CloudSession, + CloudSession.of({ + clerkToken: Effect.gen(function* () { + const session = appAtomRegistry.get(managedRelaySessionAtom); + if (session === null) { + return yield* new ConnectionBlockedError({ + reason: "authentication", + detail: "Sign in to T3 Connect to connect this environment.", + }); + } + const token = yield* session.readClerkToken().pipe( + Effect.mapError( + (error) => + new ConnectionTransientError({ + reason: "network", + detail: error.message, + }), + ), + ); + if (token === null) { + return yield* new ConnectionBlockedError({ + reason: "authentication", + detail: "The T3 Connect session is unavailable.", + }); + } + return token; + }), + }), + ).pipe( + Context.add( + PrimaryEnvironmentAuth, + PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }), + ), + Context.add( + RelayDeviceIdentity, + RelayDeviceIdentity.of({ + deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe( + Effect.mapError( + (cause) => + new ConnectionTransientError({ + reason: "remote-unavailable", + detail: `Could not load the mobile device identity: ${String(cause)}`, + }), + ), + Effect.map(Option.some), + ), + }), + ), + Context.add( + ClientPresentation, + ClientPresentation.of({ + metadata: authClientMetadata(), + scopes: AuthStandardClientScopes, + }), + ), + Context.add( + SshEnvironmentGateway, + SshEnvironmentGateway.of({ + provision: () => + Effect.fail( + new ConnectionBlockedError({ + reason: "unsupported", + detail: "SSH environments are only available in the desktop app.", }), - ), - ); - if (token === null) { - return yield* new ConnectionBlockedError({ - reason: "authentication", - detail: "The T3 Cloud session is unavailable.", - }); - } - return token; - }), - }), - ).pipe( - Context.add( - PrimaryEnvironmentAuth, - PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }), - ), - Context.add( - RelayDeviceIdentity, - RelayDeviceIdentity.of({ - deviceId: Effect.tryPromise({ - try: () => loadOrCreateAgentAwarenessDeviceId(), - catch: (cause) => - new ConnectionTransientError({ - reason: "remote-unavailable", - detail: `Could not load the mobile device identity: ${String(cause)}`, - }), - }).pipe(Effect.map(Option.some)), - }), - ), - Context.add( - ClientPresentation, - ClientPresentation.of({ - metadata: authClientMetadata(), - scopes: AuthStandardClientScopes, - }), - ), - Context.add( - SshEnvironmentGateway, - SshEnvironmentGateway.of({ - provision: () => - Effect.fail( - new ConnectionBlockedError({ - reason: "unsupported", - detail: "SSH environments are only available in the desktop app.", - }), - ), - prepare: () => - Effect.fail( - new ConnectionBlockedError({ - reason: "unsupported", - detail: "SSH environments are only available in the desktop app.", - }), - ), - disconnect: () => Effect.void, - }), - ), - ), + ), + prepare: () => + Effect.fail( + new ConnectionBlockedError({ + reason: "unsupported", + detail: "SSH environments are only available in the desktop app.", + }), + ), + disconnect: () => Effect.void, + }), + ), + ); + }), ); const platformConnectionSourceLayer = Layer.succeed( @@ -168,6 +174,13 @@ const platformConnectionSourceLayer = Layer.succeed( }), ); +const providedConnectionStorageLayer = connectionStorageLayer.pipe( + Layer.provide(Runtime.runtimeContextLayer), +); +const providedCapabilitiesLayer = capabilitiesLayer.pipe( + Layer.provide(Runtime.runtimeContextLayer), +); + const environmentOwnedDataCleanupLayer = Layer.succeed( EnvironmentOwnedDataCleanup, EnvironmentOwnedDataCleanup.of({ @@ -190,10 +203,11 @@ const environmentOwnedDataCleanupLayer = Layer.succeed( ); type ConnectionPlatformLayerSource = - | typeof connectionStorageLayer + | typeof providedConnectionStorageLayer + | typeof Runtime.runtimeContextLayer | typeof connectivityLayer | typeof wakeupsLayer - | typeof capabilitiesLayer + | typeof providedCapabilitiesLayer | typeof platformConnectionSourceLayer | typeof environmentOwnedDataCleanupLayer; @@ -202,10 +216,11 @@ export const connectionPlatformLayer: Layer.Layer< Layer.Error, Layer.Services > = Layer.mergeAll( - connectionStorageLayer, + providedConnectionStorageLayer, + Runtime.runtimeContextLayer, connectivityLayer, wakeupsLayer, - capabilitiesLayer, + providedCapabilitiesLayer, platformConnectionSourceLayer, environmentOwnedDataCleanupLayer, ); diff --git a/apps/mobile/src/connection/runtime.ts b/apps/mobile/src/connection/runtime.ts index 3698a0a5fc..3d4bf4944f 100644 --- a/apps/mobile/src/connection/runtime.ts +++ b/apps/mobile/src/connection/runtime.ts @@ -1,4 +1,6 @@ import { Connection } from "@t3tools/client-runtime/connection"; +import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell"; +import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads"; import * as Layer from "effect/Layer"; import { Atom } from "effect/unstable/reactivity"; @@ -9,12 +11,15 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe( Layer.provide(runtimeContextLayer), ); +const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer); + type ConnectionLayerSource = | typeof Connection.layer + | typeof snapshotLoaderLayer | typeof runtimeContextLayer | typeof connectionPlatformLayer; -const connectionLayer = Connection.layer.pipe( +const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe( Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)), ); diff --git a/apps/mobile/src/connection/storage.test.ts b/apps/mobile/src/connection/storage.test.ts index 031c152e65..34ba6ed850 100644 --- a/apps/mobile/src/connection/storage.test.ts +++ b/apps/mobile/src/connection/storage.test.ts @@ -1,28 +1,35 @@ import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import { vi } from "vite-plus/test"; -import { - CONNECTION_CATALOG_KEY, - LEGACY_CONNECTIONS_KEY, - makeCatalogStore, - type SecureCatalogStorage, -} from "./catalog-store"; +vi.mock("react-native", () => ({ + Platform: { OS: "ios" }, +})); + +vi.mock("expo-secure-store", () => ({ + deleteItemAsync: vi.fn(), + getItemAsync: vi.fn(), + setItemAsync: vi.fn(), +})); + +import { CONNECTION_CATALOG_KEY, LEGACY_CONNECTIONS_KEY, make } from "./catalog-store"; +import { MobileSecureStorage } from "../persistence/mobile-secure-storage"; function makeStorage(initial: Readonly>) { const values = new Map(Object.entries(initial)); const deleted: Array = []; - const storage: SecureCatalogStorage = { + const storage = MobileSecureStorage.of({ getItem: (key) => Effect.sync(() => values.get(key) ?? null), setItem: (key, value) => Effect.sync(() => { values.set(key, value); }), - deleteItem: (key) => + removeItem: (key) => Effect.sync(() => { deleted.push(key); values.delete(key); }), - }; + }); return { deleted, storage, values }; } @@ -32,7 +39,9 @@ describe("mobile connection catalog storage", () => { const memory = makeStorage({ [CONNECTION_CATALOG_KEY]: "{not-json", }); - const catalog = yield* makeCatalogStore(memory.storage); + const catalog = yield* make().pipe( + Effect.provideService(MobileSecureStorage, memory.storage), + ); expect((yield* catalog.read).targets).toEqual([]); expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY]); @@ -44,7 +53,9 @@ describe("mobile connection catalog storage", () => { const memory = makeStorage({ [LEGACY_CONNECTIONS_KEY]: JSON.stringify({ connections: [{ invalid: true }] }), }); - const catalog = yield* makeCatalogStore(memory.storage); + const catalog = yield* make().pipe( + Effect.provideService(MobileSecureStorage, memory.storage), + ); expect((yield* catalog.read).targets).toEqual([]); expect(memory.deleted).toEqual([LEGACY_CONNECTIONS_KEY]); @@ -71,7 +82,9 @@ describe("mobile connection catalog storage", () => { ], }), }); - const catalog = yield* makeCatalogStore(memory.storage); + const catalog = yield* make().pipe( + Effect.provideService(MobileSecureStorage, memory.storage), + ); expect((yield* catalog.read).targets).toHaveLength(1); expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY, LEGACY_CONNECTIONS_KEY]); diff --git a/apps/mobile/src/connection/storage.ts b/apps/mobile/src/connection/storage.ts index 1c3bead420..b043a3b414 100644 --- a/apps/mobile/src/connection/storage.ts +++ b/apps/mobile/src/connection/storage.ts @@ -2,11 +2,6 @@ import { ConnectionPersistenceError, ConnectionRegistrationStore, ConnectionTargetStore, - EnvironmentCacheStore, - ORCHESTRATION_CACHE_SCHEMA_VERSION, - StoredOrchestrationShellSnapshot, - StoredOrchestrationThreadSnapshot, - decodeOrDiscardOrchestrationCache, registerConnectionInCatalog, removeConnectionFromCatalog, removeCatalogValue, @@ -18,88 +13,12 @@ import { CredentialStore, ProfileStore, } from "@t3tools/client-runtime/connection"; -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; -import * as SecureStore from "expo-secure-store"; -import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store"; - -const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots"; -const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots"; -const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots"; - -const StoredShellSnapshot = StoredOrchestrationShellSnapshot; -const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot; -const decodeStoredShellSnapshot = Schema.decodeUnknownResult(StoredShellSnapshot); -const encodeStoredShellSnapshot = Schema.encodeUnknownResult(StoredShellSnapshot); -const decodeStoredThreadSnapshot = Schema.decodeUnknownResult(StoredThreadSnapshot); -const encodeStoredThreadSnapshot = Schema.encodeUnknownResult(StoredThreadSnapshot); - -function catalogError(operation: string, cause: unknown) { - return new ConnectionTransientError({ - reason: "remote-unavailable", - detail: `Could not ${operation} the local connection catalog: ${String(cause)}`, - }); -} - -function shellPersistenceError( - operation: - | "load-shell" - | "save-shell" - | "load-thread" - | "save-thread" - | "remove-thread" - | "clear-environment", - cause: unknown, -) { - return new ConnectionPersistenceError({ - operation, - message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`, - }); -} - -function threadSnapshotFileName(threadId: ThreadId): string { - return `${encodeURIComponent(threadId)}.json`; -} - -const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")( - function* ( - environmentId: EnvironmentId, - operation: "load-thread" | "save-thread" | "remove-thread" | "clear-environment", - ) { - return yield* Effect.tryPromise({ - try: async () => { - const { Directory, Paths } = await import("expo-file-system"); - const directory = new Directory( - Paths.document, - THREAD_SNAPSHOT_CACHE_DIRECTORY, - encodeURIComponent(environmentId), - ); - if (operation !== "clear-environment") { - directory.create({ idempotent: true, intermediates: true }); - } - return directory; - }, - catch: (cause) => shellPersistenceError(operation, cause), - }); - }, -); - -const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFile")(function* ( - environmentId: EnvironmentId, - threadId: ThreadId, - operation: "load-thread" | "save-thread" | "remove-thread", -) { - const { File } = yield* Effect.promise(() => import("expo-file-system")); - return new File( - yield* threadSnapshotDirectory(environmentId, operation), - threadSnapshotFileName(threadId), - ); -}); +import * as CatalogStore from "./catalog-store"; function targetPersistenceError( operation: "list-targets" | "register-connection" | "remove-connection", @@ -111,59 +30,9 @@ function targetPersistenceError( }); } -const secureCatalogStorage: SecureCatalogStorage = { - getItem: (key) => - Effect.tryPromise({ - try: () => SecureStore.getItemAsync(key), - catch: (cause) => catalogError("load", cause), - }), - setItem: (key, value) => - Effect.tryPromise({ - try: () => SecureStore.setItemAsync(key, value), - catch: (cause) => catalogError("save", cause), - }), - deleteItem: (key) => - Effect.tryPromise({ - try: () => SecureStore.deleteItemAsync(key), - catch: (cause) => catalogError("delete", cause), - }), -}; - -function shellSnapshotFileName(environmentId: EnvironmentId): string { - return `${encodeURIComponent(environmentId)}.json`; -} - -const shellSnapshotFileInDirectory = Effect.fn( - "mobile.connectionStorage.shellSnapshotFileInDirectory", -)(function* ( - environmentId: EnvironmentId, - operation: "load-shell" | "save-shell" | "clear-environment", - directoryName: string, -) { - return yield* Effect.tryPromise({ - try: async () => { - const { Directory, File, Paths } = await import("expo-file-system"); - const directory = new Directory(Paths.document, directoryName); - directory.create({ idempotent: true, intermediates: true }); - return new File(directory, shellSnapshotFileName(environmentId)); - }, - catch: (cause) => shellPersistenceError(operation, cause), - }); -}); - -const shellSnapshotFile = ( - environmentId: EnvironmentId, - operation: "load-shell" | "save-shell" | "clear-environment", -) => shellSnapshotFileInDirectory(environmentId, operation, SHELL_SNAPSHOT_CACHE_DIRECTORY); - -const legacyShellSnapshotFile = ( - environmentId: EnvironmentId, - operation: "load-shell" | "clear-environment", -) => shellSnapshotFileInDirectory(environmentId, operation, LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY); - export const connectionStorageLayer = Layer.effectContext( Effect.gen(function* () { - const catalog = yield* makeCatalogStore(secureCatalogStorage); + const catalog = yield* CatalogStore.make(); const targetStore = ConnectionTargetStore.of({ list: catalog.read.pipe( @@ -260,178 +129,11 @@ export const connectionStorageLayer = Layer.effectContext( ), })), }); - const cacheStore = EnvironmentCacheStore.of({ - loadShell: (environmentId) => - Effect.gen(function* () { - const file = yield* shellSnapshotFile(environmentId, "load-shell"); - if (file.exists) { - const raw = yield* Effect.tryPromise({ - try: () => file.text(), - catch: (cause) => shellPersistenceError("load-shell", cause), - }); - const parsed = yield* Effect.try({ - try: () => JSON.parse(raw) as unknown, - catch: (cause) => shellPersistenceError("load-shell", cause), - }); - const stored = yield* Effect.fromResult(decodeStoredShellSnapshot(parsed)).pipe( - Effect.mapError((cause) => shellPersistenceError("load-shell", cause)), - ); - return stored.environmentId === environmentId - ? Option.some(stored.snapshot) - : Option.none(); - } - - const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell"); - if (legacyFile.exists) { - yield* Effect.try({ - try: () => legacyFile.delete(), - catch: (cause) => shellPersistenceError("load-shell", cause), - }); - } - - return Option.none(); - }).pipe((decode) => - decodeOrDiscardOrchestrationCache( - decode, - shellSnapshotFile(environmentId, "load-shell").pipe( - Effect.flatMap((file) => - Effect.try({ - try: () => { - if (file.exists) file.delete(); - }, - catch: (cause) => shellPersistenceError("load-shell", cause), - }), - ), - Effect.catch(() => Effect.void), - ), - ), - ), - saveShell: (environmentId, snapshot) => - Effect.gen(function* () { - const file = yield* shellSnapshotFile(environmentId, "save-shell"); - const stored = { - schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION, - environmentId, - snapshot, - } as const; - const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe( - Effect.mapError((cause) => shellPersistenceError("save-shell", cause)), - ); - yield* Effect.try({ - try: () => { - if (!file.exists) { - file.create({ intermediates: true, overwrite: true }); - } - file.write(JSON.stringify(encoded)); - }, - catch: (cause) => shellPersistenceError("save-shell", cause), - }); - }), - loadThread: (environmentId, threadId) => - Effect.gen(function* () { - const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread"); - if (!file.exists) { - return Option.none(); - } - const raw = yield* Effect.tryPromise({ - try: () => file.text(), - catch: (cause) => shellPersistenceError("load-thread", cause), - }); - const parsed = yield* Effect.try({ - try: () => JSON.parse(raw) as unknown, - catch: (cause) => shellPersistenceError("load-thread", cause), - }); - const stored = yield* Effect.fromResult(decodeStoredThreadSnapshot(parsed)).pipe( - Effect.mapError((cause) => shellPersistenceError("load-thread", cause)), - ); - return stored.environmentId === environmentId && stored.threadId === threadId - ? Option.some(stored.thread) - : Option.none(); - }).pipe((decode) => - decodeOrDiscardOrchestrationCache( - decode, - threadSnapshotFile(environmentId, threadId, "load-thread").pipe( - Effect.flatMap((file) => - Effect.try({ - try: () => { - if (file.exists) file.delete(); - }, - catch: (cause) => shellPersistenceError("load-thread", cause), - }), - ), - Effect.catch(() => Effect.void), - ), - ), - ), - saveThread: (environmentId, thread) => - Effect.gen(function* () { - const file = yield* threadSnapshotFile(environmentId, thread.thread.id, "save-thread"); - const encoded = yield* Effect.fromResult( - encodeStoredThreadSnapshot({ - schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION, - environmentId, - threadId: thread.thread.id, - thread, - }), - ).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause))); - yield* Effect.try({ - try: () => { - if (!file.exists) { - file.create({ intermediates: true, overwrite: true }); - } - file.write(JSON.stringify(encoded)); - }, - catch: (cause) => shellPersistenceError("save-thread", cause), - }); - }), - removeThread: (environmentId, threadId) => - Effect.gen(function* () { - const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread"); - if (file.exists) { - file.delete(); - } - }).pipe( - Effect.mapError((cause) => - cause._tag === "ConnectionPersistenceError" - ? cause - : shellPersistenceError("remove-thread", cause), - ), - ), - clear: (environmentId) => - Effect.gen(function* () { - const file = yield* shellSnapshotFile(environmentId, "clear-environment"); - if (file.exists) { - yield* Effect.try({ - try: () => file.delete(), - catch: (cause) => shellPersistenceError("clear-environment", cause), - }); - } - const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment"); - if (legacyFile.exists) { - yield* Effect.try({ - try: () => legacyFile.delete(), - catch: (cause) => shellPersistenceError("clear-environment", cause), - }); - } - const threadDirectory = yield* threadSnapshotDirectory( - environmentId, - "clear-environment", - ); - if (threadDirectory.exists) { - yield* Effect.try({ - try: () => threadDirectory.delete(), - catch: (cause) => shellPersistenceError("clear-environment", cause), - }); - } - }), - }); - return Context.make(ConnectionTargetStore, targetStore).pipe( Context.add(ConnectionRegistrationStore, registrationStore), Context.add(ProfileStore.ConnectionProfileStore, profileStore), Context.add(CredentialStore.ConnectionCredentialStore, credentialStore), Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore), - Context.add(EnvironmentCacheStore, cacheStore), ); }), ); diff --git a/apps/mobile/src/features/agent-awareness/capabilities.ts b/apps/mobile/src/features/agent-awareness/capabilities.ts new file mode 100644 index 0000000000..d627f36575 --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/capabilities.ts @@ -0,0 +1,5 @@ +import Constants from "expo-constants"; + +export function supportsAgentAwarenessPush() { + return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true; +} diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts index 5de14ea76f..0ee3e59b98 100644 --- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts +++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts @@ -7,21 +7,30 @@ import * as Layer from "effect/Layer"; import { HttpClient } from "effect/unstable/http"; import type { SavedRemoteConnection } from "../../lib/connection"; -import { savePreferencesPatch } from "../../lib/storage"; -import { linkEnvironmentToCloud } from "../cloud/linkEnvironment"; +import { MobileStorage } from "../../persistence/mobile-storage"; +import { + CloudEnvironmentLinkError, + linkEnvironmentToCloudWithPreference, +} from "../cloud/linkEnvironment"; import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences"; -import { refreshAgentAwarenessRegistration } from "./remoteRegistration"; +import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration"; -vi.mock("../../lib/storage", () => ({ - savePreferencesPatch: vi.fn(() => Promise.resolve()), +vi.mock("expo-secure-store", () => ({ + deleteItemAsync: vi.fn(), + getItemAsync: vi.fn(), + setItemAsync: vi.fn(), +})); + +vi.mock("react-native", () => ({ + Platform: { OS: "ios" }, })); vi.mock("../cloud/linkEnvironment", () => ({ - linkEnvironmentToCloud: vi.fn(() => Effect.void), + linkEnvironmentToCloudWithPreference: vi.fn(() => Effect.void), })); vi.mock("./remoteRegistration", () => ({ - refreshAgentAwarenessRegistration: vi.fn(() => Effect.void), + updateAgentAwarenessRegistrationPreferences: vi.fn(() => Effect.void), })); const connection: SavedRemoteConnection = { @@ -40,6 +49,21 @@ const testLayer = Layer.mergeAll( HttpClient.HttpClient, HttpClient.make(() => Effect.die("unexpected HTTP request")), ), + Layer.succeed( + MobileStorage, + MobileStorage.of({ + loadSavedConnections: Effect.succeed([]), + saveConnection: () => Effect.void, + clearSavedConnection: () => Effect.void, + loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"), + loadAgentAwarenessDeviceId: Effect.succeed("device-1"), + loadAgentAwarenessRegistrationRecord: Effect.succeed(null), + saveAgentAwarenessRegistrationRecord: () => Effect.void, + clearAgentAwarenessRegistrationRecord: Effect.void, + loadRecentThreadShortcuts: Effect.succeed([]), + saveRecentThreadShortcuts: () => Effect.void, + }), + ), ); describe("liveActivityPreferences", () => { @@ -51,15 +75,18 @@ describe("liveActivityPreferences", () => { Effect.gen(function* () { yield* setLiveActivityUpdatesEnabled({ enabled: false, + previousEnabled: true, clerkToken: "clerk-token", connections: [connection], }); - expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false }); - expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1); - expect(linkEnvironmentToCloud).toHaveBeenCalledWith({ + expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({ + liveActivitiesEnabled: false, + }); + expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({ clerkToken: "clerk-token", connection, + liveActivitiesEnabled: false, }); }).pipe(Effect.provide(testLayer)), ); @@ -68,15 +95,18 @@ describe("liveActivityPreferences", () => { Effect.gen(function* () { yield* setLiveActivityUpdatesEnabled({ enabled: true, + previousEnabled: false, clerkToken: "clerk-token", connections: [connection], }); - expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true }); - expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1); - expect(linkEnvironmentToCloud).toHaveBeenCalledWith({ + expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({ + liveActivitiesEnabled: true, + }); + expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({ clerkToken: "clerk-token", connection, + liveActivitiesEnabled: true, }); }).pipe(Effect.provide(testLayer)), ); @@ -85,13 +115,15 @@ describe("liveActivityPreferences", () => { Effect.gen(function* () { yield* setLiveActivityUpdatesEnabled({ enabled: false, + previousEnabled: true, clerkToken: null, connections: [connection], }); - expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false }); - expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1); - expect(linkEnvironmentToCloud).not.toHaveBeenCalled(); + expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({ + liveActivitiesEnabled: false, + }); + expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled(); }).pipe(Effect.provide(testLayer)), ); @@ -104,14 +136,51 @@ describe("liveActivityPreferences", () => { return Effect.gen(function* () { yield* setLiveActivityUpdatesEnabled({ enabled: true, + previousEnabled: false, clerkToken: "clerk-token", connections: [connection, managedConnection], }); - expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1); - expect(linkEnvironmentToCloud).toHaveBeenCalledWith({ + expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledTimes(1); + expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({ clerkToken: "clerk-token", connection, + liveActivitiesEnabled: true, + }); + }).pipe(Effect.provide(testLayer)); + }); + + it.effect("restores relay preferences when an environment update fails", () => { + vi.mocked(linkEnvironmentToCloudWithPreference).mockImplementationOnce(() => + Effect.fail(new CloudEnvironmentLinkError({ message: "environment update failed" })), + ); + + return Effect.gen(function* () { + const exit = yield* Effect.exit( + setLiveActivityUpdatesEnabled({ + enabled: false, + previousEnabled: true, + clerkToken: "clerk-token", + connections: [connection], + }), + ); + + expect(exit._tag).toBe("Failure"); + expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(1, { + liveActivitiesEnabled: false, + }); + expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(2, { + liveActivitiesEnabled: true, + }); + expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(1, { + clerkToken: "clerk-token", + connection, + liveActivitiesEnabled: false, + }); + expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(2, { + clerkToken: "clerk-token", + connection, + liveActivitiesEnabled: true, }); }).pipe(Effect.provide(testLayer)); }); diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts index 932376e8bc..1b30769e7b 100644 --- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts +++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts @@ -1,47 +1,73 @@ import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; -import { HttpClient } from "effect/unstable/http"; -import { ManagedRelay } from "@t3tools/client-runtime/relay"; import type { SavedRemoteConnection } from "../../lib/connection"; -import { savePreferencesPatch } from "../../lib/storage"; -import { linkEnvironmentToCloud } from "../cloud/linkEnvironment"; -import { refreshAgentAwarenessRegistration } from "./remoteRegistration"; +import { linkEnvironmentToCloudWithPreference } from "../cloud/linkEnvironment"; +import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration"; -export class LiveActivityPreferenceSaveError extends Schema.TaggedErrorClass()( - "LiveActivityPreferenceSaveError", - { - enabled: Schema.Boolean, - cause: Schema.Defect(), - }, -) { - override get message(): string { - return `Failed to save the Live Activity updates setting (enabled: ${this.enabled}).`; - } -} +export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEnabled")( + function* (input: { + readonly enabled: boolean; + readonly previousEnabled: boolean; + readonly clerkToken: string | null; + readonly connections: ReadonlyArray; + }) { + const linkedConnections = input.connections.filter( + (connection) => connection.bearerToken !== null, + ); -export function setLiveActivityUpdatesEnabled(input: { - readonly enabled: boolean; - readonly clerkToken: string | null; - readonly connections: ReadonlyArray; -}): Effect.Effect { - return Effect.gen(function* () { - yield* Effect.tryPromise({ - try: () => savePreferencesPatch({ liveActivitiesEnabled: input.enabled }), - catch: (cause) => new LiveActivityPreferenceSaveError({ enabled: input.enabled, cause }), + const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) { + yield* updateAgentAwarenessRegistrationPreferences({ + liveActivitiesEnabled: enabled, + }); + + const clerkToken = input.clerkToken; + if (!clerkToken) return; + + yield* Effect.forEach( + linkedConnections, + (connection) => + linkEnvironmentToCloudWithPreference({ + clerkToken, + connection, + liveActivitiesEnabled: enabled, + }), + { concurrency: "unbounded" }, + ); }); - yield* refreshAgentAwarenessRegistration(); + const restoreRelayPreference = Effect.fn("restoreRelayPreference")(function* () { + yield* updateAgentAwarenessRegistrationPreferences({ + liveActivitiesEnabled: input.previousEnabled, + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not restore Live Activity device preference.", cause), + ), + ); - const clerkToken = input.clerkToken; - if (!clerkToken) { - return; - } + const clerkToken = input.clerkToken; + if (!clerkToken) return; - yield* Effect.forEach( - input.connections.filter((connection) => connection.bearerToken !== null), - (connection) => linkEnvironmentToCloud({ clerkToken, connection }), - { concurrency: "unbounded" }, + yield* Effect.forEach( + linkedConnections, + (connection) => + linkEnvironmentToCloudWithPreference({ + clerkToken, + connection, + liveActivitiesEnabled: input.previousEnabled, + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning( + `Could not restore Live Activity preference for environment ${connection.environmentId}.`, + cause, + ), + ), + ), + { concurrency: "unbounded" }, + ); + }); + + yield* updateRelayPreference(input.enabled).pipe( + Effect.onError(() => restoreRelayPreference()), ); - }); -} + }, +); diff --git a/apps/mobile/src/features/agent-awareness/notificationNavigation.ts b/apps/mobile/src/features/agent-awareness/notificationNavigation.ts index 18bb93d723..e9ca9246b9 100644 --- a/apps/mobile/src/features/agent-awareness/notificationNavigation.ts +++ b/apps/mobile/src/features/agent-awareness/notificationNavigation.ts @@ -1,12 +1,12 @@ import { useEffect, useRef } from "react"; import * as Notifications from "expo-notifications"; -import { useRouter } from "expo-router"; +import { useLinkTo } from "@react-navigation/native"; import { routeAgentNotificationResponseOnce } from "./notificationPayload"; import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer"; export function useAgentNotificationNavigation(): void { - const router = useRouter(); + const linkTo = useLinkTo(); const handledResponseIds = useRef(new Set()); useEffect(() => { @@ -14,7 +14,7 @@ export function useAgentNotificationNavigation(): void { routeAgentNotificationResponseOnce({ handledResponseIds: handledResponseIds.current, response, - navigate: (deepLink) => router.push(deepLink as never), + navigate: linkTo, }); }; @@ -28,5 +28,5 @@ export function useAgentNotificationNavigation(): void { return () => { subscription.remove(); }; - }, [router]); + }, [linkTo]); } diff --git a/apps/mobile/src/features/agent-awareness/registrationPayload.ts b/apps/mobile/src/features/agent-awareness/registrationPayload.ts index a4e6fc3d6d..8279a27fee 100644 --- a/apps/mobile/src/features/agent-awareness/registrationPayload.ts +++ b/apps/mobile/src/features/agent-awareness/registrationPayload.ts @@ -1,29 +1,42 @@ import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay"; -import type { Preferences } from "../../lib/storage"; +import type { Preferences } from "../../persistence/mobile-preferences"; +import { supportsAgentAwarenessPush } from "./capabilities"; + +// Development builds are Xcode-signed and receive sandbox APNs tokens; +// preview and production builds are distribution-signed and use production +// APNs. The relay routes each device's pushes accordingly. +export function resolveApsEnvironment(appVariant: unknown): "sandbox" | "production" { + return appVariant === "development" ? "sandbox" : "production"; +} export function makeRelayDeviceRegistrationRequest(input: { readonly deviceId: string; readonly label: string; readonly iosMajorVersion: number; readonly appVersion?: string; + readonly bundleId?: string; + readonly apsEnvironment?: "sandbox" | "production"; readonly pushToken?: string; readonly pushToStartToken?: string; readonly notificationsEnabled: boolean; readonly preferences: Preferences; }): RelayDeviceRegistrationRequest { - const liveActivitiesEnabled = input.preferences.liveActivitiesEnabled !== false; + const pushAvailable = supportsAgentAwarenessPush(); + const liveActivitiesEnabled = pushAvailable && input.preferences.liveActivitiesEnabled !== false; return { deviceId: input.deviceId, label: input.label, platform: "ios", iosMajorVersion: input.iosMajorVersion, appVersion: input.appVersion, + ...(input.bundleId ? { bundleId: input.bundleId } : {}), + ...(input.apsEnvironment ? { apsEnvironment: input.apsEnvironment } : {}), ...(input.pushToken ? { pushToken: input.pushToken } : {}), ...(input.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}), preferences: { liveActivitiesEnabled, - notificationsEnabled: input.notificationsEnabled, + notificationsEnabled: pushAvailable && input.notificationsEnabled, notifyOnApproval: true, notifyOnInput: true, notifyOnCompletion: true, diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts index 7f97d7c718..b1a48a35a0 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts @@ -16,15 +16,24 @@ import { verifyDpopProof } from "@t3tools/shared/dpop"; import type { SavedRemoteConnection } from "../../lib/connection"; import { cryptoLayer } from "../cloud/dpop"; import { managedRelayClientLayer } from "../cloud/managedRelayLayer"; -import { makeRelayDeviceRegistrationRequest } from "./registrationPayload"; +import { + clearAgentAwarenessRegistrationRecord, + loadAgentAwarenessRegistrationRecord, + loadOrCreateAgentAwarenessDeviceId, + saveAgentAwarenessRegistrationRecord, +} from "../../persistence/imperative"; +import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload"; import { AgentAwarenessOperationError, __resetAgentAwarenessRemoteRegistrationForTest, + getAgentAwarenessRegistrationStatus, + mergeAgentAwarenessRegistrationPreferences, refreshActiveLiveActivityRemoteRegistration, refreshAgentAwarenessRegistration, normalizeAgentAwarenessRelayBaseUrl, registerAgentAwarenessConnection, registerLiveActivityPushToken, + releaseAgentAwarenessRelayTokenProvider, setAgentAwarenessRelayTokenProvider, shouldRegisterAgentAwarenessDeviceForProvider, unregisterAgentAwarenessConnection, @@ -41,6 +50,16 @@ const backgroundRuntime = vi.hoisted(() => ({ readonly resolve: (exit: Exit.Exit) => void; }>, })); +const appStateMock = vi.hoisted(() => ({ + listeners: [] as Array<(state: string) => void>, +})); +const registrationRecordStore = vi.hoisted(() => ({ + current: null as { + readonly identity: string; + readonly signature: string; + readonly pushToStartToken?: string; + } | null, +})); vi.mock("expo-constants", () => ({ default: { @@ -100,6 +119,19 @@ vi.mock("react-native", () => ({ OS: "ios", Version: "18.0", }, + AppState: { + addEventListener: (_event: string, listener: (state: string) => void) => { + appStateMock.listeners.push(listener); + return { + remove: () => { + const index = appStateMock.listeners.indexOf(listener); + if (index >= 0) { + appStateMock.listeners.splice(index, 1); + } + }, + }; + }, + }, })); vi.mock("../../lib/runtime", () => ({ @@ -111,10 +143,21 @@ vi.mock("../../lib/runtime", () => ({ }, })); -vi.mock("../../lib/storage", () => ({ +vi.mock("../../persistence/imperative", () => ({ loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")), loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")), - loadPreferences: vi.fn(() => Promise.resolve({})), + loadPreferences: vi.fn(() => Promise.resolve({ liveActivitiesEnabled: false })), + loadAgentAwarenessRegistrationRecord: vi.fn(() => + Promise.resolve(registrationRecordStore.current), + ), + saveAgentAwarenessRegistrationRecord: vi.fn((record: { identity: string; signature: string }) => { + registrationRecordStore.current = record; + return Promise.resolve(); + }), + clearAgentAwarenessRegistrationRecord: vi.fn(() => { + registrationRecordStore.current = null; + return Promise.resolve(); + }), })); function proofIat(proof: string): number { @@ -176,6 +219,12 @@ describe("makeRelayDeviceRegistrationRequest", () => { backgroundRuntime.pending.length = 0; Constants.expoConfig!.extra = {}; __resetAgentAwarenessRemoteRegistrationForTest(); + appStateMock.listeners.length = 0; + registrationRecordStore.current = null; + vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear(); + vi.mocked(loadAgentAwarenessRegistrationRecord).mockClear(); + vi.mocked(clearAgentAwarenessRegistrationRecord).mockClear(); + vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1"); widgetMocks.getInstances.mockReset(); widgetMocks.getInstances.mockReturnValue([]); }); @@ -213,6 +262,51 @@ describe("makeRelayDeviceRegistrationRequest", () => { }); }); + it("registers the app's APNs routing so the relay targets the right bundle", () => { + expect( + makeRelayDeviceRegistrationRequest({ + deviceId: "device-1", + label: "Julius's iPhone", + iosMajorVersion: 18, + appVersion: "1.0.0", + bundleId: "com.t3tools.t3code.preview", + apsEnvironment: resolveApsEnvironment("preview"), + notificationsEnabled: true, + preferences: {}, + }), + ).toMatchObject({ + bundleId: "com.t3tools.t3code.preview", + apsEnvironment: "production", + }); + }); + + it("routes development builds to the APNs sandbox", () => { + expect(resolveApsEnvironment("development")).toBe("sandbox"); + expect(resolveApsEnvironment("preview")).toBe("production"); + expect(resolveApsEnvironment("production")).toBe("production"); + expect(resolveApsEnvironment(undefined)).toBe("production"); + }); + + it("disables push features in Personal Team relay registrations", () => { + Constants.expoConfig!.extra = { iosPersonalTeamBuild: true }; + + expect( + makeRelayDeviceRegistrationRequest({ + deviceId: "device-1", + label: "Julius's iPhone", + iosMajorVersion: 18, + appVersion: "1.0.0", + pushToken: "apns-token", + pushToStartToken: "push-to-start-token", + notificationsEnabled: true, + preferences: {}, + }).preferences, + ).toMatchObject({ + liveActivitiesEnabled: false, + notificationsEnabled: false, + }); + }); + it("marks notification delivery disabled when APNs permission is unavailable", () => { expect( makeRelayDeviceRegistrationRequest({ @@ -251,6 +345,15 @@ describe("makeRelayDeviceRegistrationRequest", () => { expect(normalizeAgentAwarenessRelayBaseUrl(" ")).toBeNull(); }); + it("overrides persisted preferences for an in-flight registration", () => { + expect( + mergeAgentAwarenessRegistrationPreferences( + { liveActivitiesEnabled: false, baseFontSize: 18 }, + { liveActivitiesEnabled: true }, + ), + ).toEqual({ liveActivitiesEnabled: true, baseFontSize: 18 }); + }); + it.effect("registers at most one listener while a Live Activity push token is pending", () => { registerAgentAwarenessConnection(savedConnection()); const addPushTokenListener = vi.fn(); @@ -329,6 +432,53 @@ describe("makeRelayDeviceRegistrationRequest", () => { }, ); + it.effect( + "re-registers active Live Activity tokens when the app returns to the foreground", + () => { + const activity = { + getPushToken: vi.fn(() => Promise.resolve("activity-token")), + addPushTokenListener: vi.fn(), + }; + widgetMocks.getInstances.mockReturnValue([activity] as never); + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + + return Effect.gen(function* () { + yield* runBackgroundOperations(); + activity.getPushToken.mockClear(); + + expect(appStateMock.listeners).toHaveLength(1); + for (const listener of appStateMock.listeners) { + listener("background"); + } + yield* runBackgroundOperations(); + expect(activity.getPushToken).not.toHaveBeenCalled(); + + for (const listener of appStateMock.listeners) { + listener("active"); + } + yield* runBackgroundOperations(); + expect(activity.getPushToken).toHaveBeenCalled(); + }).pipe(Effect.provide(relayTestLayer)); + }, + ); + + it("ends local Live Activities and stops foreground reconciliation on cloud sign-out", () => { + const end = vi.fn(() => Promise.resolve()); + const activity = { + getPushToken: vi.fn(() => Promise.resolve("activity-token")), + addPushTokenListener: vi.fn(), + end, + }; + widgetMocks.getInstances.mockReturnValue([activity] as never); + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + expect(appStateMock.listeners).toHaveLength(1); + + setAgentAwarenessRelayTokenProvider(null); + + expect(end).toHaveBeenCalledWith("immediate"); + expect(appStateMock.listeners).toHaveLength(0); + }); + it.effect("refreshes APNs registration for connected environments after settings changes", () => { registerAgentAwarenessConnection(savedConnection()); return Effect.gen(function* () { @@ -395,6 +545,174 @@ describe("makeRelayDeviceRegistrationRequest", () => { nowEpochSeconds: proofIat(dpop), }), ).toMatchObject({ ok: true }); + expect(getAgentAwarenessRegistrationStatus()).toBe("registered"); + }).pipe(Effect.provide(relayTestLayer)); + }); + + it.effect("marks registration failed when device registration cannot complete", () => { + Constants.expoConfig!.extra = { + relay: { + url: "https://relay.example.test/", + }, + }; + vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce( + new Error("registration failed"), + ); + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + + return Effect.gen(function* () { + // Drive the registration directly so the assertion does not depend on the + // background queue draining; refreshAgentAwarenessRegistration swallows the + // error but must record the failed status so the settings toggles cannot + // read as enabled. + yield* refreshAgentAwarenessRegistration(); + expect(getAgentAwarenessRegistrationStatus()).toBe("failed"); + }).pipe(Effect.provide(relayTestLayer)); + }); + + it("clears registration status on cloud sign-out", () => { + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + setAgentAwarenessRelayTokenProvider(null); + expect(getAgentAwarenessRegistrationStatus()).toBe("unknown"); + expect(clearAgentAwarenessRegistrationRecord).toHaveBeenCalled(); + }); + + it("releases the provider without ending activities or clearing the registration", () => { + const end = vi.fn(() => Promise.resolve()); + const activity = { + getPushToken: vi.fn(() => Promise.resolve("activity-token")), + addPushTokenListener: vi.fn(), + end, + }; + widgetMocks.getInstances.mockReturnValue([activity] as never); + registrationRecordStore.current = { identity: "", signature: "sig" }; + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + expect(appStateMock.listeners).toHaveLength(1); + + releaseAgentAwarenessRelayTokenProvider(); + + expect(appStateMock.listeners).toHaveLength(0); + expect(end).not.toHaveBeenCalled(); + expect(clearAgentAwarenessRegistrationRecord).not.toHaveBeenCalled(); + expect(registrationRecordStore.current).not.toBeNull(); + }); + + it.effect("resets a pending status to unknown when relay config is missing", () => { + // No relay url configured: registration can neither run nor ever succeed, + // so the status must not stick at "pending". + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + + return Effect.gen(function* () { + yield* runBackgroundOperations(); + expect(getAgentAwarenessRegistrationStatus()).toBe("unknown"); + }).pipe(Effect.provide(relayTestLayer)); + }); + + it.effect("keeps a registered status when a later refresh fails", () => { + Constants.expoConfig!.extra = { + relay: { + url: "https://relay.example.test/", + }, + }; + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + + return Effect.gen(function* () { + yield* runBackgroundOperations(); + expect(getAgentAwarenessRegistrationStatus()).toBe("registered"); + + // The relay still holds the accepted registration; a transient refresh + // failure must not flip the settings toggles off. + vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce( + new Error("transient failure"), + ); + yield* refreshAgentAwarenessRegistration(); + expect(getAgentAwarenessRegistrationStatus()).toBe("registered"); + }).pipe(Effect.provide(relayTestLayer)); + }); + + it.effect("does not re-register the same account when nothing has changed", () => { + Constants.expoConfig!.extra = { + relay: { + url: "https://relay.example.test/", + }, + }; + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + + return Effect.gen(function* () { + yield* refreshAgentAwarenessRegistration(); + expect(getAgentAwarenessRegistrationStatus()).toBe("registered"); + expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1); + expect(registrationRecordStore.current).not.toBeNull(); + + // Second attempt with an identical payload must skip the relay entirely, + // so no new registration record is written. + vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear(); + yield* refreshAgentAwarenessRegistration(); + expect(getAgentAwarenessRegistrationStatus()).toBe("registered"); + expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled(); + }).pipe(Effect.provide(relayTestLayer)); + }); + + it.effect("dedupes rapid activity-token re-registrations within the replay window", () => { + // Fetch counts are unreliable here (the module-level relay layer captures + // the first test's fetch), so assert on the flow's own seams: a real + // registration attempt loads the device id, a deduped one short-circuits + // before it. + const fetchMock = vi.fn((request: RequestInfo | URL) => { + const url = request instanceof Request ? request.url : String(request); + return Promise.resolve( + Response.json( + url.endsWith("/v1/client/dpop-token") + ? { + access_token: "relay-dpop-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 300, + scope: "mobile:registration", + } + : { ok: true }, + ), + ); + }); + vi.stubGlobal("fetch", fetchMock); + Constants.expoConfig!.extra = { + relay: { + url: "https://relay.example.test/", + }, + }; + const activity = { + getPushToken: vi.fn(() => Promise.resolve("activity-token")), + addPushTokenListener: vi.fn(), + }; + widgetMocks.getInstances.mockReturnValue([activity] as never); + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + + return Effect.gen(function* () { + // Drains the sign-in refresh, which registers the activity token. + yield* runBackgroundOperations(); + expect(activity.getPushToken).toHaveBeenCalled(); + + // A burst refresh (foreground / connection update seconds later) must + // dedupe: it reads the token but never proceeds to a registration + // attempt (which would load the device id first). + vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockClear(); + yield* refreshActiveLiveActivityRemoteRegistration(); + expect(loadOrCreateAgentAwarenessDeviceId).not.toHaveBeenCalled(); + }).pipe(Effect.provide(relayTestLayer)); + }); + + it.effect("re-registers when the stored account identity differs", () => { + Constants.expoConfig!.extra = { + relay: { + url: "https://relay.example.test/", + }, + }; + registrationRecordStore.current = { identity: "someone-else", signature: "stale" }; + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + + return Effect.gen(function* () { + yield* refreshAgentAwarenessRegistration(); + expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1); }).pipe(Effect.provide(relayTestLayer)); }); diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts index 3281381e0e..449f90886c 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts @@ -1,12 +1,13 @@ -import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets"; +import { type LiveActivity } from "expo-widgets"; import Constants from "expo-constants"; import * as Notifications from "expo-notifications"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import { Platform } from "react-native"; +import { AppState, Platform } from "react-native"; import type { EnvironmentId } from "@t3tools/contracts"; import { type RelayDeviceRegistrationRequest, + type RelayAgentActivitySnapshotResponse, type RelayLiveActivityRegistrationRequest, } from "@t3tools/contracts/relay"; import { findErrorTraceId } from "@t3tools/client-runtime/errors"; @@ -19,14 +20,19 @@ import { import type { SavedRemoteConnection } from "../../lib/connection"; import { runtime } from "../../lib/runtime"; +import type { Preferences } from "../../persistence/mobile-preferences"; import { + clearAgentAwarenessRegistrationRecord, loadAgentAwarenessDeviceId, + loadAgentAwarenessRegistrationRecord, loadOrCreateAgentAwarenessDeviceId, loadPreferences, -} from "../../lib/storage"; + saveAgentAwarenessRegistrationRecord, +} from "../../persistence/imperative"; import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity"; import { resolveCloudPublicConfig } from "../cloud/publicConfig"; -import { makeRelayDeviceRegistrationRequest } from "./registrationPayload"; +import { supportsAgentAwarenessPush } from "./capabilities"; +import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload"; const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000; @@ -42,6 +48,8 @@ const AgentAwarenessOperation = Schema.Literals([ "read-live-activity-push-token", "load-live-activity-registration-identifier", "list-active-live-activities", + "load-live-activity-prime-preferences", + "prime-live-activity", ]); export class AgentAwarenessOperationError extends Schema.TaggedErrorClass()( @@ -58,8 +66,49 @@ export class AgentAwarenessOperationError extends Schema.TaggedErrorClass(); const activityPushTokenListeners = new WeakSet>(); -let pushToStartSubscription: { remove: () => void } | null = null; +// Activity tokens the relay recently accepted, by acceptance time. The refresh +// runs on sign-in, every app foreground, and every environment-connection +// update, which arrive in bursts and spammed identical registrations. But the +// registration is not a pure no-op: the relay replays the current aggregate to +// this device on every accepted registration, and that replay is the +// foreground reconciliation that repairs drifted or orphaned activities. So +// dedupe only within a short window — bursts collapse to one request, while a +// foreground after real time away still triggers a replay. Cleared on +// sign-out/identity change alongside the device registration state. +const ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS = 60_000; +const registeredActivityPushTokens = new Map(); let pushTokenSubscription: { remove: () => void } | null = null; +let appStateSubscription: { remove: () => void } | null = null; + +// Whether the relay has actually accepted this device's registration. The +// notification/Live Activity settings toggles must reflect this rather than +// only local iOS permission or saved preferences: if the registration request +// never succeeded, the device cannot receive anything, so the switches must +// not read as enabled. +export type AgentAwarenessRegistrationStatus = "unknown" | "pending" | "registered" | "failed"; +let registrationStatus: AgentAwarenessRegistrationStatus = "unknown"; +const registrationStatusListeners = new Set<() => void>(); + +function setRegistrationStatus(next: AgentAwarenessRegistrationStatus): void { + if (registrationStatus === next) { + return; + } + registrationStatus = next; + for (const listener of registrationStatusListeners) { + listener(); + } +} + +export function getAgentAwarenessRegistrationStatus(): AgentAwarenessRegistrationStatus { + return registrationStatus; +} + +export function subscribeAgentAwarenessRegistrationStatus(listener: () => void): () => void { + registrationStatusListeners.add(listener); + return () => { + registrationStatusListeners.delete(listener); + }; +} let activeLiveActivityRegistrationRetry: ReturnType | null = null; let relayTokenProvider: (() => Promise) | null = null; let relayTokenProviderIdentity: string | null = null; @@ -74,10 +123,20 @@ let pendingDeviceRegistration: { } | null = null; interface DeviceRegistrationInput { - readonly pushToStartToken?: string; readonly observedPushToken?: string; } +interface RegisterDeviceInput extends DeviceRegistrationInput { + readonly preferencesOverride?: Partial; +} + +export function mergeAgentAwarenessRegistrationPreferences( + stored: Preferences, + override: Partial | undefined, +): Preferences { + return { ...stored, ...override }; +} + export function normalizeAgentAwarenessRelayBaseUrl( value: string | null | undefined, ): string | null { @@ -120,32 +179,66 @@ export function setAgentAwarenessRelayTokenProvider( deviceRegistrationGeneration++; activeDeviceRegistration = null; pendingDeviceRegistration = null; + registeredActivityPushTokens.clear(); } relayTokenProvider = provider; relayTokenProviderIdentity = provider ? (identity ?? null) : null; if (!provider) { - pushToStartSubscription?.remove(); - pushToStartSubscription = null; pushTokenSubscription?.remove(); pushTokenSubscription = null; + appStateSubscription?.remove(); + appStateSubscription = null; if (activeLiveActivityRegistrationRetry) { clearTimeout(activeLiveActivityRegistrationRetry); activeLiveActivityRegistrationRetry = null; } + // Without a signed-in user the relay can no longer update or end these + // activities, so they would sit orphaned on the lock screen. + endLocalLiveActivities("live activity cleanup after cloud sign-out failed"); + setRegistrationStatus("unknown"); + // Sign-out is the only thing that invalidates a stored registration, so the + // next sign-in re-registers. + void clearAgentAwarenessRegistrationRecord().catch((error: unknown) => { + logRegistrationError("clear registration record on sign-out failed", error); + }); return; } - ensurePushToStartListener(); ensurePushTokenListener(); + ensureAppStateListener(); runRegistrationInBackground( refreshActiveLiveActivityRemoteRegistration(), "active live activity registration after cloud sign-in failed", ); if (isExistingIdentity) { + // Same account re-activating (e.g. Clerk token refresh) normally needs no + // re-registration — but if the previous attempt never succeeded, this is + // the only trigger that will retry it before the next cold start. + if (registrationStatus !== "registered") { + enqueueDeviceRegistration({}, "device registration retry after cloud session refresh failed"); + } return; } enqueueDeviceRegistration({}, "device registration after cloud sign-in failed"); } +// Detach the provider and native listeners without the destructive sign-out +// cleanup. For provider teardown while the user is still signed in (e.g. the +// auth bridge unmounting/remounting), ending lock-screen activities and wiping +// the persisted registration would be wrong — the relay still holds a valid +// registration and the next mount reuses it. +export function releaseAgentAwarenessRelayTokenProvider(): void { + relayTokenProvider = null; + relayTokenProviderIdentity = null; + pushTokenSubscription?.remove(); + pushTokenSubscription = null; + appStateSubscription?.remove(); + appStateSubscription = null; + if (activeLiveActivityRegistrationRetry) { + clearTimeout(activeLiveActivityRegistrationRetry); + activeLiveActivityRegistrationRetry = null; + } +} + function iosMajorVersion(): number { const version = Platform.Version; if (typeof version === "number") { @@ -157,7 +250,7 @@ function iosMajorVersion(): number { function nativePushTokenRegistration(observedPushToken?: string) { return Effect.gen(function* () { - if (!canRegisterRemoteLiveActivities()) { + if (!canRegisterRemoteLiveActivities() || !supportsAgentAwarenessPush()) { return { notificationsEnabled: false, pushToken: null }; } if (observedPushToken) { @@ -211,6 +304,27 @@ const relayToken = ( }); }); +// Stable fingerprint of everything the relay stores for this device. When it +// matches the last accepted registration for the same account, re-registering +// is a no-op, so a launch that changed nothing skips the request entirely. +function registrationSignature(body: RelayDeviceRegistrationRequest): string { + return [ + body.deviceId, + body.pushToken ?? "", + body.bundleId ?? "", + body.apsEnvironment ?? "", + body.appVersion ?? "", + body.label, + body.iosMajorVersion, + body.preferences.notificationsEnabled, + body.preferences.liveActivitiesEnabled, + body.preferences.notifyOnApproval, + body.preferences.notifyOnInput, + body.preferences.notifyOnCompletion, + body.preferences.notifyOnFailure, + ].join("|"); +} + function registerDeviceWithRelay( body: RelayDeviceRegistrationRequest, expectedGeneration: number, @@ -223,7 +337,13 @@ function registerDeviceWithRelay( }); return; } - if (!readRelayConfig()) return; + const relayConfig = readRelayConfig(); + if (!relayConfig) { + // Nothing is in flight and nothing can succeed until configuration + // appears; "pending" would otherwise stick forever. + setRegistrationStatus("unknown"); + return; + } const token = yield* relayToken("read-device-registration-relay-token"); if (expectedGeneration !== deviceRegistrationGeneration) { logRegistrationDebug("device registration cancelled after auth lookup", { @@ -234,6 +354,37 @@ function registerDeviceWithRelay( } if (!token) { logRegistrationDebug("relay device registration skipped; user is not signed in"); + setRegistrationStatus("unknown"); + return; + } + + // Skip the request when this account already registered an identical + // payload; the relay upsert would be a no-op. The record is only cleared on + // sign-out, so a device stays registered across launches without re-hitting + // the relay every time the app opens. + const identity = relayTokenProviderIdentity ?? ""; + const persisted = yield* Effect.tryPromise({ + try: () => loadAgentAwarenessRegistrationRecord(), + catch: (cause) => cause, + }).pipe(Effect.orElseSucceed(() => null)); + if (expectedGeneration !== deviceRegistrationGeneration) { + // Signed out while the record loaded — do not resurrect the cleared + // record or report the previous account's registration as current. + logRegistrationDebug("device registration cancelled after record lookup", { + expectedGeneration, + currentGeneration: deviceRegistrationGeneration, + }); + return; + } + const payload = body; + // The relay URL participates so pointing the app at a different relay + // invalidates the record and re-registers there. + const signature = `${relayConfig.url}|${registrationSignature(payload)}`; + if (persisted && persisted.identity === identity && persisted.signature === signature) { + setRegistrationStatus("registered"); + logRegistrationDebug("relay device registration skipped; already registered for account", { + expectedGeneration, + }); return; } @@ -243,8 +394,27 @@ function registerDeviceWithRelay( }); yield* client.registerDevice({ clerkToken: token, - payload: body, + payload, }); + if (expectedGeneration !== deviceRegistrationGeneration) { + // Signed out while the request was in flight: the sign-out path already + // reset the status and cleared the record for the next account, so a + // stale success must not overwrite either. + logRegistrationDebug("device registration completed after sign-out; result discarded", { + expectedGeneration, + currentGeneration: deviceRegistrationGeneration, + }); + return; + } + setRegistrationStatus("registered"); + yield* Effect.promise(() => + saveAgentAwarenessRegistrationRecord({ + identity, + signature, + }).catch((error: unknown) => { + logRegistrationError("persist registration record failed", error); + }), + ); logRegistrationDebug("relay device registration request completed", { expectedGeneration, }); @@ -278,6 +448,91 @@ function unregisterDeviceWithRelay(input: { }); } +// Arms the lock-screen card the moment the user starts agent work from this +// phone, while the app is still foregrounded and the fresh activity's token +// can be registered immediately. The seeded row is a best-effort placeholder; +// the relay's registration replay repaints it with the authoritative +// aggregate within seconds. No-ops when a card is already armed. +export function armAgentAwarenessLiveActivityForLocalWork(input: { + readonly threadTitle: string; + readonly projectTitle: string; +}): void { + if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) { + return; + } + void loadPreferences() + .catch(() => null) + .then((preferences) => { + if (preferences?.liveActivitiesEnabled === false) { + return; + } + armAgentAwarenessLiveActivityForLocalWorkNow(input); + }); +} + +function armAgentAwarenessLiveActivityForLocalWorkNow(input: { + readonly threadTitle: string; + readonly projectTitle: string; +}): void { + try { + if (AgentActivity.getInstances().length > 0) { + return; + } + const nowIso = new Date(Date.now()).toISOString(); + const activity = AgentActivity.start({ + title: "T3 Code", + subtitle: "Agent work in progress", + activeCount: 1, + updatedAt: nowIso, + activities: [ + { + environmentId: "", + threadId: "", + projectTitle: input.projectTitle, + threadTitle: input.threadTitle, + modelTitle: "", + phase: "starting", + status: "Connecting", + updatedAt: nowIso, + deepLink: "/", + }, + ], + }); + logRegistrationDebug("live activity card armed for local work", { + threadTitle: input.threadTitle, + }); + runRegistrationInBackground( + registerLiveActivityPushToken({ activity }).pipe(Effect.asVoid), + "live activity arming after local task start failed", + ); + } catch (error) { + logRegistrationError("live activity arming failed", error); + } +} + +function readAgentActivitySnapshot(): Effect.Effect< + RelayAgentActivitySnapshotResponse | null, + never, + ManagedRelay.ManagedRelayClient +> { + return Effect.gen(function* () { + if (!readRelayConfig()) return null; + const token = yield* relayToken("read-live-activity-registration-relay-token"); + if (!token) { + return null; + } + const client = yield* ManagedRelay.ManagedRelayClient; + return yield* client.getAgentActivitySnapshot({ clerkToken: token }); + }).pipe( + Effect.catch((error) => + Effect.sync(() => { + logRegistrationError("agent activity snapshot read failed", error); + return null; + }), + ), + ); +} + function registerLiveActivityWithRelay( body: RelayLiveActivityRegistrationRequest, ): Effect.Effect { @@ -332,14 +587,8 @@ function mergeDeviceRegistrationInput( current: DeviceRegistrationInput, next: DeviceRegistrationInput, ): DeviceRegistrationInput { - return { - ...((next.pushToStartToken ?? current.pushToStartToken) - ? { pushToStartToken: next.pushToStartToken ?? current.pushToStartToken } - : {}), - ...((next.observedPushToken ?? current.observedPushToken) - ? { observedPushToken: next.observedPushToken ?? current.observedPushToken } - : {}), - }; + const observedPushToken = next.observedPushToken ?? current.observedPushToken; + return observedPushToken ? { observedPushToken } : {}; } function registrationAddsInformation( @@ -347,8 +596,7 @@ function registrationAddsInformation( next: DeviceRegistrationInput, ): boolean { return ( - (next.pushToStartToken !== undefined && next.pushToStartToken !== current.pushToStartToken) || - (next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken) + next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken ); } @@ -363,8 +611,10 @@ function startPendingDeviceRegistration(): void { logRegistrationDebug("device registration started", { generation, hasObservedPushToken: next.input.observedPushToken !== undefined, - hasPushToStartToken: next.input.pushToStartToken !== undefined, }); + if (registrationStatus !== "registered") { + setRegistrationStatus("pending"); + } const registration = { input: next.input, operation: Promise.resolve(), @@ -375,6 +625,13 @@ function startPendingDeviceRegistration(): void { runtime.runPromiseExit(registerDevice(next.input, generation)), ); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + // A transient failure on a later refresh (e.g. token rotation) leaves + // the prior accepted registration intact on the relay, so an already + // registered device stays "registered" rather than flipping the + // settings toggles off. + if (registrationStatus !== "registered") { + setRegistrationStatus("failed"); + } logRegistrationError(next.context, squashAtomCommandFailure(result)); } logRegistrationDebug("device registration finished", { generation }); @@ -411,7 +668,7 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stri } function registerDevice( - input: DeviceRegistrationInput = {}, + input: RegisterDeviceInput = {}, expectedGeneration = deviceRegistrationGeneration, ): Effect.Effect { return Effect.gen(function* () { @@ -421,7 +678,7 @@ function registerDevice( } logRegistrationDebug("device registration loading local state", { expectedGeneration }); - const [deviceId, preferences] = yield* Effect.all([ + const [deviceId, storedPreferences] = yield* Effect.all([ Effect.tryPromise({ try: () => loadOrCreateAgentAwarenessDeviceId(), catch: (cause) => @@ -439,19 +696,25 @@ function registerDevice( }), }), ]); + const preferences = mergeAgentAwarenessRegistrationPreferences( + storedPreferences, + input.preferencesOverride, + ); const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken); logRegistrationDebug("device registration local state ready", { expectedGeneration, notificationsEnabled: pushTokenRegistration.notificationsEnabled, }); + const bundleId = Constants.expoConfig?.ios?.bundleIdentifier?.trim(); yield* registerDeviceWithRelay( makeRelayDeviceRegistrationRequest({ deviceId, label: Constants.deviceName?.trim() || "iOS device", iosMajorVersion: iosMajorVersion(), appVersion: Constants.expoConfig?.version, + ...(bundleId ? { bundleId } : {}), + apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant), ...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}), - ...(input?.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}), notificationsEnabled: pushTokenRegistration.notificationsEnabled, preferences, }), @@ -460,27 +723,12 @@ function registerDevice( }); } -function registerDeviceForCurrentUser( - pushToStartToken?: string, -): Effect.Effect { - return registerDevice(pushToStartToken ? { pushToStartToken } : undefined); -} - -function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void { - enqueueDeviceRegistration({ pushToStartToken }, "push-to-start token registration failed"); -} - -function ensurePushToStartListener(): void { - if (pushToStartSubscription || !canRegisterRemoteLiveActivities()) { - return; - } - - pushToStartSubscription = addPushToStartTokenListener((event) => { - const token = event.activityPushToStartToken; - if (token) { - registerPushToStartTokenForCurrentUser(token); - } - }); +function registerDeviceForCurrentUser(): Effect.Effect< + void, + unknown, + ManagedRelay.ManagedRelayClient +> { + return registerDevice(undefined); } function ensurePushTokenListener(): void { @@ -498,14 +746,51 @@ function ensurePushTokenListener(): void { }); } +// Re-registering activity tokens on foreground makes the relay replay the +// current aggregate to this device, which updates content that drifted while +// pushes could not be delivered and ends orphaned activities whose end push +// never arrived. (Deduped by ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS: rapid +// foreground/sign-in bursts collapse to one registration, but returning after +// real time away still replays.) +function ensureAppStateListener(): void { + if (appStateSubscription || !canRegisterRemoteLiveActivities()) { + return; + } + + appStateSubscription = AppState.addEventListener("change", (state) => { + if (state !== "active") { + return; + } + runRegistrationInBackground( + refreshActiveLiveActivityRemoteRegistration(), + "active live activity reconciliation after app foreground failed", + ); + }); +} + +function endLocalLiveActivities(context: string): void { + if (!canRegisterRemoteLiveActivities()) { + return; + } + try { + for (const activity of AgentActivity.getInstances()) { + activity.end("immediate").catch((error: unknown) => { + logRegistrationError(context, error); + }); + } + } catch (error) { + logRegistrationError(context, error); + } +} + export function registerAgentAwarenessConnection(connection: SavedRemoteConnection): void { if (!canRegisterRemoteLiveActivities()) { return; } environmentConnections.set(connection.environmentId, connection); - ensurePushToStartListener(); ensurePushTokenListener(); + ensureAppStateListener(); enqueueDeviceRegistration({}, "device registration failed"); runRegistrationInBackground( refreshActiveLiveActivityRemoteRegistration(), @@ -523,10 +808,10 @@ export function unregisterAgentAwarenessConnection(environmentId: EnvironmentId) export function unregisterAllAgentAwarenessConnections(): void { environmentConnections.clear(); - pushToStartSubscription?.remove(); - pushToStartSubscription = null; pushTokenSubscription?.remove(); pushTokenSubscription = null; + appStateSubscription?.remove(); + appStateSubscription = null; if (activeLiveActivityRegistrationRetry) { clearTimeout(activeLiveActivityRegistrationRetry); activeLiveActivityRegistrationRetry = null; @@ -541,18 +826,38 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect< return registerDeviceForCurrentUser().pipe( Effect.catch((error) => Effect.sync(() => { + // Same rationale as the queued path: a failed refresh does not undo an + // already accepted registration. + if (registrationStatus !== "registered") { + setRegistrationStatus("failed"); + } logRegistrationError("device registration refresh failed", error); }), ), ); } +export function updateAgentAwarenessRegistrationPreferences( + preferencesOverride: Partial, +): Effect.Effect { + return registerDevice({ preferencesOverride }).pipe( + Effect.tapError((error) => + Effect.sync(() => { + if (registrationStatus !== "registered") { + setRegistrationStatus("failed"); + } + logRegistrationError("device preference registration refresh failed", error); + }), + ), + ); +} + export function __resetAgentAwarenessRemoteRegistrationForTest(): void { environmentConnections.clear(); - pushToStartSubscription?.remove(); - pushToStartSubscription = null; pushTokenSubscription?.remove(); pushTokenSubscription = null; + appStateSubscription?.remove(); + appStateSubscription = null; if (activeLiveActivityRegistrationRetry) { clearTimeout(activeLiveActivityRegistrationRetry); activeLiveActivityRegistrationRetry = null; @@ -562,6 +867,9 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void { deviceRegistrationGeneration++; activeDeviceRegistration = null; pendingDeviceRegistration = null; + registrationStatus = "unknown"; + registrationStatusListeners.clear(); + registeredActivityPushTokens.clear(); } export function unregisterAgentAwarenessDeviceForCurrentUser( @@ -649,6 +957,13 @@ function registerLiveActivityPushTokenValue(input: { readonly activityPushToken: string; }): Effect.Effect { return Effect.gen(function* () { + const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken); + if ( + acceptedAt !== undefined && + Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS + ) { + return true; + } const deviceId = yield* Effect.tryPromise({ try: () => loadOrCreateAgentAwarenessDeviceId(), catch: (cause) => @@ -662,6 +977,7 @@ function registerLiveActivityPushTokenValue(input: { activityPushToken: input.activityPushToken, }); if (registered) { + registeredActivityPushTokens.set(input.activityPushToken, Date.now()); logRegistrationDebug("live activity push token registered", { tokenSuffix: input.activityPushToken.slice(-8), }); @@ -694,7 +1010,7 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect< return; } - const activities = yield* Effect.try({ + let activities = yield* Effect.try({ try: () => AgentActivity.getInstances(), catch: (cause) => new AgentAwarenessOperationError({ @@ -710,6 +1026,79 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect< ), ); + // The relay tracks exactly one card per device; if concurrent arming ever + // produced extras, end them so only one keeps receiving updates. + if (activities.length > 1) { + for (const extra of activities.slice(1)) { + extra.end("immediate").catch((error: unknown) => { + logRegistrationError("duplicate live activity cleanup failed", error); + }); + } + activities = activities.slice(0, 1); + } + + // Activities are only ever created here, in the foreground, where the + // update token can be observed and registered immediately — the relay + // never remote-starts one (background push-to-start wakes proved too + // unreliable to hand the token over). Arming is conditional: the relay is + // asked what the card would show first, so an idle open never creates an + // empty lock-screen card, and an armed card is born with the real + // aggregate instead of a placeholder. + if (activities.length === 0) { + const preferences = yield* Effect.tryPromise({ + try: () => loadPreferences(), + catch: (cause) => + new AgentAwarenessOperationError({ + operation: "load-live-activity-prime-preferences", + cause, + }), + }).pipe(Effect.orElseSucceed(() => null)); + // The toggle defaults to on: an unset preference (fresh install) must + // prime, so only an explicit false blocks it. + if (preferences?.liveActivitiesEnabled !== false) { + const snapshot = yield* readAgentActivitySnapshot(); + // The snapshot request yields; an arm-on-send may have created the + // card in the meantime. Re-check so two cards are never started. + const armedMeanwhile = yield* Effect.try({ + try: () => AgentActivity.getInstances(), + catch: () => [] as ReadonlyArray>, + }).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray>)); + if (armedMeanwhile.length > 0) { + activities = [...armedMeanwhile]; + } else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) { + const aggregate = snapshot.aggregate; + const primed = yield* Effect.try({ + try: () => + AgentActivity.start({ + title: aggregate.title, + subtitle: aggregate.subtitle, + activeCount: aggregate.activeCount, + updatedAt: aggregate.updatedAt, + activities: aggregate.activities, + }), + catch: (cause) => + new AgentAwarenessOperationError({ + operation: "prime-live-activity", + cause, + }), + }).pipe( + Effect.catch((error) => + Effect.sync(() => { + logRegistrationError("live activity priming failed", error); + return null; + }), + ), + ); + if (primed) { + logRegistrationDebug("live activity card primed", { + activeCount: aggregate.activeCount, + }); + activities = [primed]; + } + } + } + } + const registrationResults = yield* Effect.forEach(activities, (activity) => registerLiveActivityPushToken({ activity }).pipe( Effect.map((registered) => !registered), diff --git a/apps/mobile/src/features/archive/ArchivedThreadsRouteScreen.tsx b/apps/mobile/src/features/archive/ArchivedThreadsRouteScreen.tsx index d560f8db9f..c2381ef258 100644 --- a/apps/mobile/src/features/archive/ArchivedThreadsRouteScreen.tsx +++ b/apps/mobile/src/features/archive/ArchivedThreadsRouteScreen.tsx @@ -1,7 +1,7 @@ import type { EnvironmentId } from "@t3tools/contracts"; import * as Arr from "effect/Array"; import * as Order from "effect/Order"; -import { useFocusEffect } from "expo-router"; +import { useFocusEffect } from "@react-navigation/native"; import { useCallback, useMemo, useState } from "react"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; diff --git a/apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx b/apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx index 3e1934100c..916802e9fa 100644 --- a/apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx +++ b/apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx @@ -2,35 +2,34 @@ import type { EnvironmentProject, EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; +import { LegendList } from "@legendapp/list/react-native"; import type { EnvironmentId } from "@t3tools/contracts"; import type { MenuAction } from "@react-native-menu/menu"; -import * as Haptics from "expo-haptics"; -import { Stack } from "expo-router"; -import { SymbolView } from "expo-symbols"; -import { useCallback, useRef } from "react"; +import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader"; +import { SymbolView } from "../../components/AppSymbol"; +import { useNavigation } from "@react-navigation/native"; +import { useCallback, useMemo, useRef, type ComponentProps } from "react"; import { + TextInput, ActivityIndicator, + Platform, Pressable, RefreshControl, - ScrollView, useWindowDimensions, View, } from "react-native"; -import ReanimatedSwipeable, { - type SwipeableMethods, -} from "react-native-gesture-handler/ReanimatedSwipeable"; +import { Gesture, GestureDetector } from "react-native-gesture-handler"; +import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable"; import { AppText as Text } from "../../components/AppText"; import { ControlPillMenu } from "../../components/ControlPill"; import { EmptyState } from "../../components/EmptyState"; import { ProjectFavicon } from "../../components/ProjectFavicon"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; import { relativeTime } from "../../lib/time"; import { useThemeColor } from "../../lib/useThemeColor"; -import { - THREAD_SWIPE_ACTIONS_WIDTH, - THREAD_SWIPE_SPRING, - ThreadSwipeActions, -} from "../home/thread-swipe-actions"; +import { ThreadSwipeable } from "../home/thread-swipe-actions"; +import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar"; import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList"; export interface ArchivedThreadsHeaderEnvironment { @@ -38,98 +37,317 @@ export interface ArchivedThreadsHeaderEnvironment { readonly label: string; } -const THREAD_ACTIONS: MenuAction[] = [ - { - id: "unarchive", - title: "Unarchive", - image: "arrow.uturn.backward", - }, - { - id: "delete", - title: "Delete", - image: "trash", - attributes: { destructive: true }, - }, -]; +type ArchivedThreadListItem = + | { + readonly kind: "project"; + readonly key: string; + readonly environmentLabel: string | null; + readonly project: EnvironmentProject; + } + | { + readonly kind: "thread"; + readonly key: string; + readonly environmentLabel: string | null; + readonly isFirst: boolean; + readonly isLast: boolean; + readonly thread: EnvironmentThreadShell; + }; function ArchivedThreadsHeader(props: { readonly environments: ReadonlyArray; + readonly searchQuery: string; readonly selectedEnvironmentId: EnvironmentId | null; readonly sortOrder: ArchivedThreadSortOrder; readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void; + readonly onRefresh: () => void; readonly onSearchQueryChange: (query: string) => void; readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void; }) { + const { width } = useWindowDimensions(); + const navigation = useNavigation(); + const insets = useSafeAreaInsets(); const hasCustomFilter = props.selectedEnvironmentId !== null || props.sortOrder !== "newest"; + const searchIconColor = useThemeColor("--color-icon"); + const searchTextColor = useThemeColor("--color-foreground"); + const usesNativeChrome = Platform.OS === "ios"; + const usesCompactMailToolbar = Platform.OS === "ios" && width < 700; + const androidFilterActions = useMemo( + () => [ + { + id: "environment", + title: "Environment", + subactions: [ + { + id: "environment:all", + title: "All environments", + state: props.selectedEnvironmentId === null ? ("on" as const) : undefined, + }, + ...props.environments.map((environment) => ({ + id: `environment:${environment.environmentId}`, + title: environment.label, + state: + props.selectedEnvironmentId === environment.environmentId + ? ("on" as const) + : undefined, + })), + ], + }, + { + id: "sort", + title: "Sort by archived date", + subactions: [ + { + id: "sort:newest", + title: "Newest first", + state: props.sortOrder === "newest" ? ("on" as const) : undefined, + }, + { + id: "sort:oldest", + title: "Oldest first", + state: props.sortOrder === "oldest" ? ("on" as const) : undefined, + }, + ], + }, + ], + [props.environments, props.selectedEnvironmentId, props.sortOrder], + ); + const handleAndroidFilterAction = useCallback( + (event: { nativeEvent: { event: string } }) => { + const action = event.nativeEvent.event; + if (action === "environment:all") { + props.onEnvironmentChange(null); + } else if (action.startsWith("environment:")) { + props.onEnvironmentChange(action.slice("environment:".length) as EnvironmentId); + } else if (action === "sort:newest") { + props.onSortOrderChange("newest"); + } else if (action === "sort:oldest") { + props.onSortOrderChange("oldest"); + } + }, + [props.onEnvironmentChange, props.onSortOrderChange], + ); + + if (Platform.OS === "android") { + // Single header row matching the app's Android chrome (AndroidScreenHeader + // palette): back chevron, inline search, filter menu. + return ( + <> + + + + navigation.goBack()} + className="size-11 items-center justify-center" + > + + + + + + + + + + + + + + + ); + } + const archiveFilterMenu = { + title: "Archived thread options", + items: [ + { + type: "submenu" as const, + title: "Environment", + items: [ + { + type: "action" as const, + title: "All environments", + state: props.selectedEnvironmentId === null ? ("on" as const) : ("off" as const), + onPress: () => props.onEnvironmentChange(null), + }, + ...props.environments.map((environment) => ({ + type: "action" as const, + title: environment.label, + state: + props.selectedEnvironmentId === environment.environmentId + ? ("on" as const) + : ("off" as const), + onPress: () => props.onEnvironmentChange(environment.environmentId), + })), + ], + }, + { + type: "submenu" as const, + title: "Sort by archived date", + items: [ + { + type: "action" as const, + title: "Newest first", + state: props.sortOrder === "newest" ? ("on" as const) : ("off" as const), + onPress: () => props.onSortOrderChange("newest"), + }, + { + type: "action" as const, + title: "Oldest first", + state: props.sortOrder === "oldest" ? ("on" as const) : ("off" as const), + onPress: () => props.onSortOrderChange("oldest"), + }, + ], + }, + ], + }; return ( <> - { - props.onSearchQueryChange(event.nativeEvent.text); - }, - onCancelButtonPress: () => { - props.onSearchQueryChange(""); - }, - }, + unstable_headerToolbarItems: usesCompactMailToolbar + ? () => [ + createNativeMailSearchToolbarItem({ + composeButtonId: "archived-refresh", + composeSystemImageName: "arrow.clockwise", + filterMenu: archiveFilterMenu, + filterButtonId: "archived-filter", + filterSystemImageName: hasCustomFilter + ? "line.3.horizontal.decrease.circle.fill" + : "line.3.horizontal.decrease", + onComposePress: props.onRefresh, + onSearchTextChange: props.onSearchQueryChange, + placeholder: "Search", + searchTextChangeId: "archived-search-text", + }), + ] + : undefined, + headerSearchBarOptions: usesCompactMailToolbar + ? undefined + : { + ...(usesNativeChrome + ? { + allowToolbarIntegration: true, + placement: "integratedButton" as const, + } + : { + placement: "stacked" as const, + }), + autoCapitalize: "none", + hideNavigationBar: false, + obscureBackground: false, + placeholder: "Search archived threads", + onChangeText: (event) => { + props.onSearchQueryChange(event.nativeEvent.text); + }, + onCancelButtonPress: () => { + props.onSearchQueryChange(""); + }, + }, }} /> - - - - Environment - props.onEnvironmentChange(null)} - > - All environments - - {props.environments.map((environment) => ( - props.onEnvironmentChange(environment.environmentId)} + {usesCompactMailToolbar ? null : ( + + {usesNativeChrome ? ( + + ) : null} + + + Environment + props.onEnvironmentChange(null)} > - {environment.label} - - ))} - + All environments + + {props.environments.map((environment) => ( + props.onEnvironmentChange(environment.environmentId)} + > + {environment.label} + + ))} + - - Sort by archived date - props.onSortOrderChange("newest")} - > - Newest first - - props.onSortOrderChange("oldest")} - > - Oldest first - - - - + + Sort by archived date + props.onSortOrderChange("newest")} + > + Newest first + + props.onSortOrderChange("oldest")} + > + Oldest first + + + + + )} ); } @@ -147,9 +365,8 @@ function ProjectGroupLabel(props: { workspaceRoot={props.project.workspaceRoot} /> {props.project.title} @@ -164,150 +381,94 @@ function ProjectGroupLabel(props: { function ArchivedThreadRow(props: { readonly environmentLabel: string | null; + readonly isFirst: boolean; readonly isLast: boolean; readonly onDelete: () => void; readonly onSwipeableClose: (methods: SwipeableMethods) => void; readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void; + readonly simultaneousSwipeGesture?: ComponentProps< + typeof ThreadSwipeable + >["simultaneousWithExternalGesture"]; readonly onUnarchive: () => void; readonly thread: EnvironmentThreadShell; }) { - const swipeableRef = useRef(null); - const fullSwipeArmedRef = useRef(false); const { width: windowWidth } = useWindowDimensions(); const cardColor = useThemeColor("--color-card"); const iconColor = useThemeColor("--color-icon-subtle"); const separatorColor = useThemeColor("--color-separator"); - const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58); const timestamp = relativeTime(props.thread.archivedAt ?? props.thread.updatedAt); const subtitle = [props.environmentLabel, props.thread.branch].filter((part): part is string => Boolean(part), ); - const handleFullSwipeArmedChange = useCallback((armed: boolean) => { - if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") { - void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium); - } - fullSwipeArmedRef.current = armed; - }, []); - const handleMenuAction = useCallback( - (event: { nativeEvent: { event: string } }) => { - if (event.nativeEvent.event === "unarchive") { - props.onUnarchive(); - } else if (event.nativeEvent.event === "delete") { - props.onDelete(); - } - }, - [props.onDelete, props.onUnarchive], - ); - return ( - { - fullSwipeArmedRef.current = false; - if (swipeableRef.current) { - props.onSwipeableClose(swipeableRef.current); - } + { - if (swipeableRef.current) { - props.onSwipeableWillOpen(swipeableRef.current); - } + fullSwipeWidth={windowWidth - 32} + onDelete={props.onDelete} + onSwipeableClose={props.onSwipeableClose} + onSwipeableWillOpen={props.onSwipeableWillOpen} + primaryAction={{ + accessibilityLabel: `Unarchive ${props.thread.title}`, + icon: "arrow.uturn.backward", + label: "Unarchive", + onPress: props.onUnarchive, }} - onSwipeableWillOpen={() => { - const methods = swipeableRef.current; - if (!methods) return; - - props.onSwipeableWillOpen(methods); - if (fullSwipeArmedRef.current) { - fullSwipeArmedRef.current = false; - methods.close(); - props.onDelete(); - } - }} - overshootFriction={1} - overshootRight - renderRightActions={(_progress, translation, methods) => ( - - )} - rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42} + simultaneousWithExternalGesture={props.simultaneousSwipeGesture} + threadTitle={props.thread.title} > - - - - - - - - - {props.thread.title} - - - {timestamp} - + {() => ( + + + - {subtitle.length > 0 ? ( - - + + + - {subtitle.join(" · ")} + {props.thread.title} + + + {timestamp} - ) : null} + {subtitle.length > 0 ? ( + + + + {subtitle.join(" · ")} + + + ) : null} + - - - - - - - - + )} + ); } @@ -317,7 +478,7 @@ function ArchiveError(props: { readonly message: string; readonly onRetry: () => Could not load every archive - {props.message} + {props.message} Try again @@ -340,8 +501,41 @@ export function ArchivedThreadsScreen(props: { readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void; readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void; }) { + const { onDeleteThread, onUnarchiveThread } = props; const openSwipeableRef = useRef(null); + const archiveScrollGesture = useMemo(() => Gesture.Native(), []); const refreshTint = useThemeColor("--color-icon"); + const environmentLabelsById = useMemo( + () => + new Map( + props.environments.map((environment) => [environment.environmentId, environment.label]), + ), + [props.environments], + ); + const listItems = useMemo>(() => { + const items: ArchivedThreadListItem[] = []; + for (const group of props.groups) { + const environmentLabel = environmentLabelsById.get(group.project.environmentId) ?? null; + items.push({ + kind: "project", + key: `${group.key}:project`, + environmentLabel, + project: group.project, + }); + + group.threads.forEach((thread, index) => { + items.push({ + kind: "thread", + key: `${thread.environmentId}:${thread.id}`, + environmentLabel, + isFirst: index === 0, + isLast: index === group.threads.length - 1, + thread, + }); + }); + } + return items; + }, [environmentLabelsById, props.groups]); const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => { if (openSwipeableRef.current && openSwipeableRef.current !== methods) { openSwipeableRef.current.close(); @@ -355,82 +549,104 @@ export function ArchivedThreadsScreen(props: { }, []); const isInitialLoad = props.isLoading && props.groups.length === 0 && props.error === null; const isFiltered = props.searchQuery.trim().length > 0 || props.selectedEnvironmentId !== null; + const renderListItem = useCallback( + ({ item }: { item: ArchivedThreadListItem }) => { + if (item.kind === "project") { + return ( + + + + ); + } + + return ( + onDeleteThread(item.thread)} + onSwipeableClose={handleSwipeableClose} + onSwipeableWillOpen={handleSwipeableWillOpen} + onUnarchive={() => onUnarchiveThread(item.thread)} + simultaneousSwipeGesture={archiveScrollGesture} + thread={item.thread} + /> + ); + }, + [ + archiveScrollGesture, + handleSwipeableClose, + handleSwipeableWillOpen, + onDeleteThread, + onUnarchiveThread, + ], + ); + const listEmptyComponent = useMemo(() => { + if (isInitialLoad) { + return ( + + + Loading archive... + + ); + } + + return ( + + ); + }, [isFiltered, isInitialLoad, refreshTint]); return ( - openSwipeableRef.current?.close()} - refreshControl={ - - } - showsVerticalScrollIndicator={false} - > - {props.error ? : null} - - {isInitialLoad ? ( - - - Loading archive… - - ) : props.groups.length === 0 ? ( - - ) : ( - props.groups.map((group) => { - const environmentLabel = - props.environments.find( - (environment) => environment.environmentId === group.project.environmentId, - )?.label ?? null; - - return ( - - - - {group.threads.map((thread, index) => ( - props.onDeleteThread(thread)} - onSwipeableClose={handleSwipeableClose} - onSwipeableWillOpen={handleSwipeableWillOpen} - onUnarchive={() => props.onUnarchiveThread(thread)} - thread={thread} - /> - ))} - - - ); - }) - )} - + + item.kind} + keyboardDismissMode="on-drag" + keyboardShouldPersistTaps="handled" + keyExtractor={(item) => item.key} + ListEmptyComponent={listEmptyComponent} + ListHeaderComponent={ + props.error ? : null + } + onScrollBeginDrag={() => openSwipeableRef.current?.close()} + refreshControl={ + + } + renderItem={renderListItem} + showsVerticalScrollIndicator={false} + /> + ); } diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx index c89aeb9249..f7ece97cba 100644 --- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx @@ -14,9 +14,11 @@ import { runtime } from "../../lib/runtime"; import { appAtomRegistry } from "../../state/atom-registry"; import { useAtomCommand } from "../../state/use-atom-command"; import { + releaseAgentAwarenessRelayTokenProvider, setAgentAwarenessRelayTokenProvider, unregisterAgentAwarenessDeviceForCurrentUser, } from "../agent-awareness/remoteRegistration"; +import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding"; import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig"; function resetManagedRelayTokenCache() { @@ -66,6 +68,19 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) { const nextAccount = isSignedIn && userId ? userId : null; observedAccountRef.current = nextAccount; + // Every sign-in or account switch that completes during this session (a + // cold start observes undefined → account and must not re-prompt) requests + // the T3 Connect onboarding sheet — account transitions clear the + // connected environments, so each new session starts with no devices to + // reach. The request itself is issued after the cleanup transition inside + // activateSession, so the sheet never lists the previous account's + // environments; sign-out drops any not-yet-presented request instead. + const isAccountTransition = + previousObservedAccount !== undefined && previousObservedAccount !== nextAccount; + if (isAccountTransition && nextAccount === null) { + clearConnectOnboardingRequest(); + } + const queueAccountCleanup = ( previous: { readonly userId: string; @@ -113,6 +128,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) { } previousTokenProviderRef.current = { userId, provider: tokenProvider }; activateCloudRelayAccount(userId, tokenProvider); + if (isAccountTransition) { + requestConnectOnboarding(userId); + } }; const activateAfterTransition = (transition: Promise) => { void (async () => { @@ -143,7 +161,11 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) { useEffect( () => () => { previousTokenProviderRef.current = null; - deactivateCloudRelayAccount(); + // Unmounting is not a sign-out: the user is usually still signed in, so + // detach the provider without ending lock-screen activities or wiping the + // persisted registration (a remount reuses both). + releaseAgentAwarenessRelayTokenProvider(); + setManagedRelaySession(appAtomRegistry, null); }, [], ); diff --git a/apps/mobile/src/features/cloud/CloudWaitlistEnrollment.tsx b/apps/mobile/src/features/cloud/CloudWaitlistEnrollment.tsx index 4d5b570332..1a7020fd0e 100644 --- a/apps/mobile/src/features/cloud/CloudWaitlistEnrollment.tsx +++ b/apps/mobile/src/features/cloud/CloudWaitlistEnrollment.tsx @@ -1,14 +1,12 @@ import { useWaitlist } from "@clerk/expo"; -import { ActivityIndicator, Pressable, StyleSheet, Text, TextInput, View } from "react-native"; +import { ActivityIndicator, Pressable, Text, TextInput, View } from "react-native"; import { useState } from "react"; -import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; -import { useThemeColor } from "../../lib/useThemeColor"; +import { cn } from "../../lib/cn"; import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin"; export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) { const { errors, fetchStatus, waitlist } = useWaitlist(); - const colors = useCloudWaitlistColors(); const [emailAddress, setEmailAddress] = useState(""); const [requestError, setRequestError] = useState(null); const isSubmitting = fetchStatus === "fetching"; @@ -35,10 +33,12 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void } if (waitlist.id) { return ( - - You are on the waitlist - - We will email you when your T3 Cloud access is ready. + + + You are on the waitlist + + + We will email you when your T3 Connect access is ready. @@ -46,18 +46,22 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void } } return ( - - + + Enter your email and we will let you know when access is ready. - - Email address + + Email address { setEmailAddress(value); @@ -65,24 +69,15 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void } }} onSubmitEditing={() => void joinWaitlist()} placeholder="Enter your email address" - placeholderTextColor={colors.placeholder} + placeholderTextColorClassName="accent-placeholder" returnKeyType="join" - style={[ - styles.input, - { - backgroundColor: colors.input, - borderColor: - fieldError || requestError ? colors.dangerForeground : colors.inputBorder, - color: colors.foreground, - }, - ]} textContentType="emailAddress" value={emailAddress} /> {fieldError || requestError ? ( {fieldError ?? requestError} @@ -98,16 +93,12 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void } }} disabled={isSubmitting || emailAddress.trim().length === 0} onPress={() => void joinWaitlist()} - style={[ - styles.primaryButton, - { - backgroundColor: colors.primary, - opacity: isSubmitting || emailAddress.trim().length === 0 ? 0.45 : 1, - }, - ]} + className="min-h-[54px] flex-row items-center justify-center gap-2 rounded-full bg-primary px-5 py-3 disabled:opacity-[0.45]" > - {isSubmitting ? : null} - + {isSubmitting ? ( + + ) : null} + {isSubmitting ? "Joining" : "Join the waitlist"} @@ -118,90 +109,12 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void } } function SignInAction(props: { readonly onPress: () => void }) { - const colors = useCloudWaitlistColors(); return ( - - Already have access? + + Already have access? - Sign in + Sign in ); } - -function useCloudWaitlistColors() { - return { - dangerForeground: String(useThemeColor("--color-danger-foreground")), - foreground: String(useThemeColor("--color-foreground")), - input: String(useThemeColor("--color-input")), - inputBorder: String(useThemeColor("--color-input-border")), - placeholder: String(useThemeColor("--color-placeholder")), - primary: String(useThemeColor("--color-primary")), - primaryForeground: String(useThemeColor("--color-primary-foreground")), - secondaryForeground: String(useThemeColor("--color-foreground-secondary")), - }; -} - -const styles = StyleSheet.create({ - body: { - fontFamily: "DMSans_400Regular", - ...MOBILE_TYPOGRAPHY.body, - }, - buttonText: { - fontFamily: "DMSans_700Bold", - fontSize: MOBILE_TYPOGRAPHY.body.fontSize, - }, - content: { - gap: 18, - }, - confirmationBody: { - textAlign: "center", - }, - error: { - fontFamily: "DMSans_400Regular", - ...MOBILE_TYPOGRAPHY.footnote, - }, - field: { - gap: 8, - }, - input: { - borderCurve: "continuous", - borderRadius: 16, - borderWidth: 1, - fontFamily: "DMSans_400Regular", - fontSize: MOBILE_TYPOGRAPHY.headline.fontSize, - minHeight: 54, - paddingHorizontal: 16, - paddingVertical: 14, - }, - label: { - fontFamily: "DMSans_700Bold", - ...MOBILE_TYPOGRAPHY.footnote, - }, - primaryButton: { - alignItems: "center", - borderRadius: 999, - flexDirection: "row", - gap: 8, - justifyContent: "center", - minHeight: 54, - paddingHorizontal: 20, - paddingVertical: 12, - }, - signInRow: { - alignItems: "center", - flexDirection: "row", - gap: 4, - justifyContent: "center", - paddingTop: 4, - }, - signInText: { - fontFamily: "DMSans_700Bold", - ...MOBILE_TYPOGRAPHY.body, - }, - title: { - fontFamily: "DMSans_700Bold", - ...MOBILE_TYPOGRAPHY.title, - textAlign: "center", - }, -}); diff --git a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx new file mode 100644 index 0000000000..952d1c3884 --- /dev/null +++ b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx @@ -0,0 +1,137 @@ +import { NativeHeaderToolbar } from "../../native/StackHeader"; +import { useAuth } from "@clerk/expo"; +import { StackActions, useNavigation } from "@react-navigation/native"; +import { useCallback, useEffect, useState } from "react"; +import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { reportAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime"; +import { AndroidSheetHeader } from "../../components/AndroidScreenHeader"; +import { AppText as Text } from "../../components/AppText"; +import { useRemoteConnections } from "../../state/use-remote-environment-registry"; +import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows"; +import { splitEnvironmentSections } from "../connection/environmentSections"; +import { useConnectionController } from "../connection/useConnectionController"; +import { optOutOfConnectOnboarding } from "./connectOnboardingOptOut"; +import { hasCloudPublicConfig } from "./publicConfig"; + +/** + * Post-sign-in onboarding sheet for T3 Connect. Mobile never publishes + * environments itself — it consumes ones published elsewhere — so this simply + * surfaces the account's T3 Connect environments right after sign-in so every + * device can be connected in one go. It shows on every sign-in: sign-out + * clears the connected environments, so each new session starts from zero. + */ +export function ConnectOnboardingRouteScreen() { + const navigation = useNavigation(); + + // The route is deep-linkable; without cloud config the sheet would present + // empty with no chrome to dismiss it, so bail back out instead. + useEffect(() => { + if (hasCloudPublicConfig()) { + return; + } + if (navigation.canGoBack()) { + navigation.goBack(); + } else { + navigation.dispatch(StackActions.replace("Home")); + } + }, [navigation]); + + return hasCloudPublicConfig() ? : null; +} + +function ConfiguredConnectOnboardingRouteScreen() { + const navigation = useNavigation(); + const insets = useSafeAreaInsets(); + const { isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false }); + const { connectedEnvironments, onReconnectEnvironment } = useRemoteConnections(); + const { refreshRelayEnvironments } = useConnectionController(); + const { connectedCloudEnvironments } = splitEnvironmentSections({ + connectedEnvironments, + cloudEnvironments: null, + }); + + // Pull-to-refresh tracks its own spinner instead of discovery's refreshing + // flag, so background refreshes (e.g. the sign-in one) don't yank the + // content down. + const [isPullRefreshing, setIsPullRefreshing] = useState(false); + const handlePullRefresh = useCallback(() => { + void (async () => { + setIsPullRefreshing(true); + await refreshRelayEnvironments(); + setIsPullRefreshing(false); + })(); + }, [refreshRelayEnvironments]); + + const handleClose = useCallback(() => { + navigation.goBack(); + }, [navigation]); + + // Persist before dismissing so a quick sign-out/sign-in cannot race ahead + // of the preference write; the write is a local secure-store update. + const handleDontShowAgain = useCallback(() => { + void (async () => { + if (userId) { + const result = await settlePromise(() => optOutOfConnectOnboarding(userId)); + reportAtomCommandResult(result, { label: "connect onboarding opt-out" }); + } + navigation.goBack(); + })(); + }, [navigation, userId]); + + return ( + + {Platform.OS === "android" ? ( + + ) : ( + + + + )} + + } + > + {isSignedIn ? ( + + ) : ( + + + Sign in to your T3 account to set up T3 Connect. + + + )} + + {userId ? ( + + {"Don't show this again"} + + ) : null} + + + ); +} diff --git a/apps/mobile/src/features/cloud/connectOnboarding.ts b/apps/mobile/src/features/cloud/connectOnboarding.ts new file mode 100644 index 0000000000..9d3944331a --- /dev/null +++ b/apps/mobile/src/features/cloud/connectOnboarding.ts @@ -0,0 +1,24 @@ +import { Atom } from "effect/unstable/reactivity"; + +import { appAtomRegistry } from "../../state/atom-registry"; + +// Signals RootStackLayout (inside the navigation tree) that an in-session +// sign-in just completed. Holds the account id so a sign-out between the +// request and the navigation cannot present the sheet for the wrong account. +export const connectOnboardingRequestAtom = Atom.make(null).pipe( + Atom.keepAlive, + Atom.withLabel("mobile:connect-onboarding-request"), +); + +/** + * Requests the onboarding sheet for the given account. Sign-out clears the + * connected environments, so onboarding runs on every in-session sign-in — + * each new session starts with no connected devices. + */ +export function requestConnectOnboarding(accountId: string): void { + appAtomRegistry.set(connectOnboardingRequestAtom, accountId); +} + +export function clearConnectOnboardingRequest(): void { + appAtomRegistry.set(connectOnboardingRequestAtom, null); +} diff --git a/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts b/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts new file mode 100644 index 0000000000..f937453e52 --- /dev/null +++ b/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts @@ -0,0 +1,49 @@ +import { useAtomValue } from "@effect/atom-react"; +import { useNavigation } from "@react-navigation/native"; +import { useEffect } from "react"; + +import { appAtomRegistry } from "../../state/atom-registry"; +import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding"; +import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut"; + +// Sign-in happens inside the Settings sheet; give its detent/session-state +// transitions a beat to settle before presenting another formSheet on top. +const PRESENT_ONBOARDING_DELAY_MS = 600; + +/** + * Consumes the onboarding request inside the navigation tree (RootStackLayout) + * and presents the onboarding formSheet. Lives apart from connectOnboarding.ts + * so non-navigation consumers (CloudAuthProvider) do not pull + * @react-navigation into their module graph. + */ +export function useConnectOnboardingNavigation(): void { + const navigation = useNavigation(); + const requestedAccountId = useAtomValue(connectOnboardingRequestAtom); + + useEffect(() => { + if (requestedAccountId === null) { + return; + } + let cancelled = false; + const timer = setTimeout(() => { + void (async () => { + // A failed preference read prefers showing the sheet. + const optedOut = await isConnectOnboardingOptedOut(requestedAccountId).catch(() => false); + // The cancelled flag covers effect re-runs, but a sign-out can clear + // the request atom moments before this render commits — re-check the + // atom so a stale request never presents the sheet. + if (cancelled || appAtomRegistry.get(connectOnboardingRequestAtom) !== requestedAccountId) { + return; + } + clearConnectOnboardingRequest(); + if (!optedOut) { + navigation.navigate("ConnectOnboarding"); + } + })(); + }, PRESENT_ONBOARDING_DELAY_MS); + return () => { + cancelled = true; + clearTimeout(timer); + }; + }, [navigation, requestedAccountId]); +} diff --git a/apps/mobile/src/features/cloud/connectOnboardingOptOut.ts b/apps/mobile/src/features/cloud/connectOnboardingOptOut.ts new file mode 100644 index 0000000000..ff74863b61 --- /dev/null +++ b/apps/mobile/src/features/cloud/connectOnboardingOptOut.ts @@ -0,0 +1,21 @@ +import { loadPreferences, updatePreferences } from "../../persistence/imperative"; + +// Lives apart from connectOnboarding.ts so CloudAuthProvider (which imports +// the request signal) never pulls the persistence adapter into its +// module graph; that breaks CloudAuthProvider.test.ts suite loading. + +/** Whether the account chose "Don't show this again". */ +export async function isConnectOnboardingOptedOut(accountId: string): Promise { + const preferences = await loadPreferences(); + return preferences.connectOnboardingOptOutAccounts?.includes(accountId) ?? false; +} + +/** Persists "Don't show this again" for the account. */ +export async function optOutOfConnectOnboarding(accountId: string): Promise { + await updatePreferences((current) => { + const optedOut = current.connectOnboardingOptOutAccounts ?? []; + return optedOut.includes(accountId) + ? {} + : { connectOnboardingOptOutAccounts: [...optedOut, accountId] }; + }); +} diff --git a/apps/mobile/src/features/cloud/dpop.ts b/apps/mobile/src/features/cloud/dpop.ts index 0bd4b7ff1b..eabf0dd79b 100644 --- a/apps/mobile/src/features/cloud/dpop.ts +++ b/apps/mobile/src/features/cloud/dpop.ts @@ -8,12 +8,7 @@ import * as Schema from "effect/Schema"; import * as ExpoCrypto from "expo-crypto"; import * as SecureStore from "expo-secure-store"; import { p256 } from "@noble/curves/nist"; -import { - computeDpopAccessTokenHash, - computeDpopJwkThumbprint, - DpopPublicJwk, - normalizeDpopHtu, -} from "@t3tools/shared/dpop"; +import { DpopPublicJwk, normalizeDpopHtu } from "@t3tools/shared/dpopCommon"; import * as Layer from "effect/Layer"; export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{ @@ -107,6 +102,40 @@ function sha256Digest( ); } +function base64UrlSha256( + data: Uint8Array, + message: string, +): Effect.Effect { + return sha256Digest(data, message).pipe(Effect.map(Encoding.encodeBase64Url)); +} + +function dpopThumbprintInput(jwk: DpopPublicJwk): string { + return JSON.stringify({ + crv: jwk.crv, + kty: jwk.kty, + x: jwk.x, + y: jwk.y, + }); +} + +function computeDpopJwkThumbprintEffect( + jwk: DpopPublicJwk, +): Effect.Effect { + return base64UrlSha256( + new TextEncoder().encode(dpopThumbprintInput(jwk)), + "Could not hash the DPoP public key thumbprint.", + ); +} + +function computeDpopAccessTokenHashEffect( + accessToken: string, +): Effect.Effect { + return base64UrlSha256( + new TextEncoder().encode(accessToken), + "Could not hash the DPoP access token.", + ); +} + function secureRandomBytes( byteCount: number, message: string, @@ -153,7 +182,7 @@ export function generateDpopProofKeyPair(): Effect.Effect< try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)), catch: cloudDpopError("Generated DPoP public key is invalid."), }); - const thumbprint = computeDpopJwkThumbprint(publicJwk); + const thumbprint = yield* computeDpopJwkThumbprintEffect(publicJwk); return { privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk), publicJwk, @@ -189,9 +218,10 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect< }, catch: cloudDpopError("Stored DPoP proof key is invalid."), }); + const thumbprint = yield* computeDpopJwkThumbprintEffect(restored.publicJwk); return { ...restored, - thumbprint: computeDpopJwkThumbprint(restored.publicJwk), + thumbprint, }; } const generated = yield* generateDpopProofKeyPair(); @@ -243,7 +273,9 @@ export function createDpopProof(input: { Effect.map(Encoding.encodeBase64Url), Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")), ); - const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null; + const ath = input.accessToken + ? yield* computeDpopAccessTokenHashEffect(input.accessToken) + : null; const payload = yield* encodeDpopJwtPayloadJson({ htm: input.method.toUpperCase(), htu, diff --git a/apps/mobile/src/features/cloud/linkEnvironment.test.ts b/apps/mobile/src/features/cloud/linkEnvironment.test.ts index b9ab3aeab0..c75d60d5fd 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.test.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.test.ts @@ -7,10 +7,13 @@ import { RelayMobileClientId } from "@t3tools/contracts/relay"; import { ManagedRelay } from "@t3tools/client-runtime/relay"; import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc"; import { HttpClient } from "effect/unstable/http"; +import { MobilePreferencesStore } from "../../persistence/mobile-preferences"; +import { MobileStorage } from "../../persistence/mobile-storage"; import { cloudEnvironmentsPendingStatus, linkEnvironmentToCloud, + linkEnvironmentToCloudWithPreference, connectCloudEnvironment, listCloudEnvironments, listCloudEnvironmentsWithStatus, @@ -36,11 +39,14 @@ vi.mock("react-native", () => ({ }, })); -vi.mock("../../lib/storage", () => ({ - loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")), - loadPreferences: vi.fn(() => Promise.resolve({})), +vi.mock("expo-secure-store", () => ({ + deleteItemAsync: vi.fn(), + getItemAsync: vi.fn(), + setItemAsync: vi.fn(), })); +const loadPreferences = vi.fn(() => Effect.succeed({})); + const savedConnection = { environmentId: EnvironmentId.make("env-1"), environmentLabel: "Desktop", @@ -69,6 +75,29 @@ function cloudClientLayer() { const httpClientLayer = remoteHttpClientLayer((input, init) => globalThis.fetch(input, init)); return Layer.mergeAll( httpClientLayer, + Layer.succeed( + MobilePreferencesStore, + MobilePreferencesStore.of({ + load: loadPreferences(), + savePatch: (patch) => Effect.succeed(patch), + update: () => Effect.succeed({}), + }), + ), + Layer.succeed( + MobileStorage, + MobileStorage.of({ + loadSavedConnections: Effect.succeed([]), + saveConnection: () => Effect.void, + clearSavedConnection: () => Effect.void, + loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"), + loadAgentAwarenessDeviceId: Effect.succeed("device-1"), + loadAgentAwarenessRegistrationRecord: Effect.succeed(null), + saveAgentAwarenessRegistrationRecord: () => Effect.void, + clearAgentAwarenessRegistrationRecord: Effect.void, + loadRecentThreadShortcuts: Effect.succeed([]), + saveRecentThreadShortcuts: () => Effect.void, + }), + ), ManagedRelay.layer({ relayUrl: "https://relay.example.test", clientId: RelayMobileClientId, @@ -80,7 +109,11 @@ const withCloudServices = ( effect: Effect.Effect< A, E, - HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner + | HttpClient.HttpClient + | ManagedRelay.ManagedRelayClient + | ManagedRelay.ManagedRelayDpopSigner + | MobilePreferencesStore + | MobileStorage >, ) => effect.pipe(Effect.provide(cloudClientLayer())); @@ -146,6 +179,7 @@ describe("mobile cloud link environment client", () => { beforeEach(() => { vi.restoreAllMocks(); createProofMock.mockClear(); + loadPreferences.mockClear(); }); it("normalizes configured relay base URLs before building DPoP-bound requests", () => { @@ -705,10 +739,7 @@ describe("mobile cloud link environment client", () => { it.effect("preserves disabled Live Activity preferences when linking an environment", () => Effect.gen(function* () { - const storage = yield* Effect.promise(() => import("../../lib/storage")); - vi.mocked(storage.loadPreferences).mockResolvedValueOnce({ - liveActivitiesEnabled: false, - }); + loadPreferences.mockReturnValueOnce(Effect.succeed({ liveActivitiesEnabled: false })); const bodies: Array = []; const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => { if (init?.body) { @@ -761,6 +792,45 @@ describe("mobile cloud link environment client", () => { }), ); + it.effect("uses an explicit Live Activity preference when persisted state is unavailable", () => + Effect.gen(function* () { + loadPreferences.mockReturnValueOnce(Effect.die("persisted preferences must not be read")); + const bodies: Array> = []; + const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => { + if (init?.body) { + // @effect-diagnostics-next-line preferSchemaOverJson:off + bodies.push(JSON.parse(requestBodyText(init.body)) as Record); + } + if (String(url).endsWith("/v1/client/environment-link-challenges")) { + return Promise.resolve(Response.json(validLinkChallengeResponse())); + } + if (String(url).endsWith("/api/connect/link-proof")) { + return Promise.resolve(Response.json(validLinkProof())); + } + if (String(url).endsWith("/v1/client/environment-links")) { + return Promise.resolve(Response.json(validLinkResponse())); + } + return Promise.resolve( + Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }), + ); + }); + vi.stubGlobal("fetch", fetchMock); + + yield* withCloudServices( + linkEnvironmentToCloudWithPreference({ + clerkToken: "clerk-token", + connection: savedConnection, + liveActivitiesEnabled: true, + }), + ); + + expect(bodies.filter((body) => "liveActivitiesEnabled" in body)).toEqual([ + expect.objectContaining({ liveActivitiesEnabled: true }), + expect.objectContaining({ liveActivitiesEnabled: true }), + ]); + }), + ); + it.effect( "does not persist cloud connect bootstrap credentials in saved connection records", () => diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts index a77ca62897..5423686e04 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.ts @@ -30,7 +30,8 @@ import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc"; import { authClientMetadata } from "../../lib/authClientMetadata"; import type { SavedRemoteConnection } from "../../lib/connection"; -import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage"; +import * as MobilePreferences from "../../persistence/mobile-preferences"; +import * as MobileStorage from "../../persistence/mobile-storage"; import { resolveCloudPublicConfig } from "./publicConfig"; const RELAY_STATUS_AND_CONNECT_SCOPES = [ @@ -256,14 +257,19 @@ function ensureConnectEndpointMatchesEnvironment(input: { return Effect.void; } -export function linkEnvironmentToCloud(input: { +interface LinkEnvironmentToCloudInput { readonly connection: SavedRemoteConnection; readonly clerkToken: string; -}): Effect.Effect< - void, - CloudEnvironmentLinkError, - HttpClient.HttpClient | ManagedRelay.ManagedRelayClient -> { +} + +type LinkEnvironmentToCloudRequirements = + | HttpClient.HttpClient + | ManagedRelay.ManagedRelayClient + | MobileStorage.MobileStorage; + +export function linkEnvironmentToCloudWithPreference( + input: LinkEnvironmentToCloudInput & { readonly liveActivitiesEnabled: boolean }, +): Effect.Effect { return Effect.gen(function* () { if (!input.connection.bearerToken) { return yield* new CloudEnvironmentLinkError({ @@ -273,15 +279,11 @@ export function linkEnvironmentToCloud(input: { const localBearerToken = input.connection.bearerToken; const relayUrl = yield* requireRelayUrl(); const relayClient = yield* ManagedRelay.ManagedRelayClient; - const deviceId = yield* Effect.tryPromise({ - try: () => loadOrCreateAgentAwarenessDeviceId(), - catch: cloudEnvironmentLinkError("Could not load the mobile device id."), - }); - const preferences = yield* Effect.tryPromise({ - try: () => loadPreferences(), - catch: cloudEnvironmentLinkError("Could not load mobile notification preferences."), - }); - const liveActivitiesEnabled = preferences.liveActivitiesEnabled !== false; + const storage = yield* MobileStorage.MobileStorage; + const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe( + Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")), + ); + const liveActivitiesEnabled = input.liveActivitiesEnabled; const challenge = yield* relayClient .createEnvironmentLinkChallenge({ clerkToken: input.clerkToken, @@ -350,6 +352,25 @@ export function linkEnvironmentToCloud(input: { }); } +export function linkEnvironmentToCloud( + input: LinkEnvironmentToCloudInput, +): Effect.Effect< + void, + CloudEnvironmentLinkError, + LinkEnvironmentToCloudRequirements | MobilePreferences.MobilePreferencesStore +> { + return MobilePreferences.MobilePreferencesStore.pipe( + Effect.flatMap((preferencesStore) => preferencesStore.load), + Effect.mapError(cloudEnvironmentLinkError("Could not load mobile notification preferences.")), + Effect.flatMap((preferences) => + linkEnvironmentToCloudWithPreference({ + ...input, + liveActivitiesEnabled: preferences.liveActivitiesEnabled !== false, + }), + ), + ); +} + export function listCloudEnvironments(input: { readonly clerkToken: string; }): Effect.Effect< @@ -460,10 +481,10 @@ export function listCloudEnvironmentsWithStatus(input: { const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")( function* () { - return yield* Effect.tryPromise({ - try: () => loadOrCreateAgentAwarenessDeviceId(), - catch: cloudEnvironmentLinkError("Could not load the mobile device id."), - }); + const storage = yield* MobileStorage.MobileStorage; + return yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe( + Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")), + ); }, ); @@ -557,7 +578,10 @@ export function connectCloudEnvironment(input: { }): Effect.Effect< SavedRemoteConnection, CloudEnvironmentLinkError, - HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner + | HttpClient.HttpClient + | ManagedRelay.ManagedRelayClient + | ManagedRelay.ManagedRelayDpopSigner + | MobileStorage.MobileStorage > { return connectRelayManagedEnvironment({ clerkToken: input.clerkToken, @@ -572,7 +596,10 @@ export function refreshCloudEnvironmentConnection(input: { }): Effect.Effect< SavedRemoteConnection, CloudEnvironmentLinkError, - HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner + | HttpClient.HttpClient + | ManagedRelay.ManagedRelayClient + | ManagedRelay.ManagedRelayDpopSigner + | MobileStorage.MobileStorage > { return connectRelayManagedEnvironment({ clerkToken: input.clerkToken, diff --git a/apps/mobile/src/app/settings/environments.tsx b/apps/mobile/src/features/connection/CloudEnvironmentRows.tsx similarity index 65% rename from apps/mobile/src/app/settings/environments.tsx rename to apps/mobile/src/features/connection/CloudEnvironmentRows.tsx index 8f65c630a5..608d43b2ac 100644 --- a/apps/mobile/src/app/settings/environments.tsx +++ b/apps/mobile/src/features/connection/CloudEnvironmentRows.tsx @@ -1,6 +1,5 @@ import { useAuth } from "@clerk/expo"; -import { Stack, useRouter } from "expo-router"; -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "../../components/AppSymbol"; import { connectionStatusText, type EnvironmentConnectionPhase, @@ -10,133 +9,44 @@ import { useCallback, useState } from "react"; import { ActivityIndicator, Pressable, - ScrollView, Switch, type NativeSyntheticEvent, type TextLayoutEventData, View, } from "react-native"; -import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/AppText"; -import { - type RelayEnvironmentView, - useConnectionController, -} from "../../features/connection/useConnectionController"; -import { hasCloudPublicConfig } from "../../features/cloud/publicConfig"; -import { availableCloudEnvironmentPresentation } from "../../features/cloud/cloudEnvironmentPresentation"; -import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow"; -import { ConnectionStatusDot } from "../../features/connection/ConnectionStatusDot"; -import { splitEnvironmentSections } from "../../features/connection/environmentSections"; import { cn } from "../../lib/cn"; import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { useThemeColor } from "../../lib/useThemeColor"; import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types"; -import { useRemoteConnections } from "../../state/use-remote-environment-registry"; +import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation"; +import { ConnectionStatusDot } from "./ConnectionStatusDot"; +import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController"; -export default function SettingsEnvironmentsRouteScreen() { - const { - connectedEnvironments, - onReconnectEnvironment, - onRemoveEnvironmentPress, - onUpdateEnvironment, - } = useRemoteConnections(); - const router = useRouter(); - const insets = useSafeAreaInsets(); - const { localEnvironments, connectedCloudEnvironments } = splitEnvironmentSections({ - connectedEnvironments, - cloudEnvironments: null, - }); - const hasLocalEnvironments = localEnvironments.length > 0; - const [expandedId, setExpandedId] = useState(null); - const accentColor = useThemeColor("--color-icon-muted"); - - const handleToggle = useCallback((environmentId: EnvironmentId) => { - setExpandedId((prev) => (prev === environmentId ? null : environmentId)); - }, []); - - return ( - - - - router.push("/settings/environment-new")} - separateBackground - /> - - - {hasLocalEnvironments ? ( - - {localEnvironments.map((environment, index) => ( - - handleToggle(environment.environmentId)} - onReconnect={onReconnectEnvironment} - onRemove={onRemoveEnvironmentPress} - onUpdate={onUpdateEnvironment} - /> - - ))} - - ) : ( - - - - - - No environments connected yet.{"\n"}Tap{" "} - + to add one. - - - )} - - {hasCloudPublicConfig() ? ( - - ) : null} - - - ); -} - -function ConfiguredCloudEnvironmentRows(props: { +/** + * "T3 Connect" section: every environment published to the signed-in account, + * with connect switches, availability status, refresh, and loading/error + * states. Shared between the Settings environments screen and the T3 Connect + * onboarding sheet. + */ +export function CloudEnvironmentRows(props: { readonly connectedCloudEnvironments: ReadonlyArray; readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void; + readonly showcaseAvailableEnvironments?: ReadonlyArray; + 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 + * pull-to-refresh). + */ + readonly showHeader?: boolean; }) { 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(null); const hasCloudRows = props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0; @@ -155,27 +65,36 @@ function ConfiguredCloudEnvironmentRows(props: { setExpandedErrorId((current) => (current === environmentId ? null : environmentId)); }, []); - if (!isSignedIn) return null; + const showHeader = props.showHeader ?? true; + + if (!(props.showcaseSignedIn ?? isSignedIn)) return null; return ( - - - T3 Cloud - { - void controller.refreshRelayEnvironments(); - }} - className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50" - > - {controller.relayDiscovery.isRefreshing ? ( - - ) : ( - - )} - - + + {showHeader ? ( + + T3 Connect + { + void controller.refreshRelayEnvironments(); + }} + className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50" + > + {controller.relayDiscovery.isRefreshing ? ( + + ) : ( + + )} + + + ) : null} {hasCloudRows ? ( @@ -204,29 +123,40 @@ function ConfiguredCloudEnvironmentRows(props: { ) : controller.relayDiscovery.isRefreshing ? ( - + Loading linked cloud environments. - ) : controller.relayDiscovery.error ? ( - - - Could not load T3 Cloud environments - - - {controller.relayDiscovery.error} - - {controller.relayDiscovery.errorTraceId ? ( - - ) : null} - - ) : ( + ) : controller.relayDiscovery.error ? null : ( - + No additional linked cloud environments. )} + + {/* Rendered alongside any connected rows — a failed discovery must not + hide behind an otherwise-healthy list. */} + {controller.relayDiscovery.error && !controller.relayDiscovery.isRefreshing ? ( + + + Could not load T3 Connect environments + + {controller.relayDiscovery.error} + {controller.relayDiscovery.errorTraceId ? ( + + ) : null} + { + void controller.refreshRelayEnvironments(); + }} + className="self-start rounded-full bg-subtle px-3.5 py-2 active:opacity-70" + > + Try again + + + ) : null} ); } @@ -361,7 +291,7 @@ function CloudEnvironmentRowShell(props: { {props.label} @@ -370,9 +300,8 @@ function CloudEnvironmentRowShell(props: { {props.connectionError ? ( {measuredErrorText} @@ -384,7 +313,7 @@ function CloudEnvironmentRowShell(props: { className="min-w-0 flex-row items-start gap-1" > {statusText} @@ -394,7 +323,7 @@ function CloudEnvironmentRowShell(props: { { event.stopPropagation(); copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" }); @@ -402,7 +331,6 @@ function CloudEnvironmentRowShell(props: { onPress={(event) => { event.stopPropagation(); }} - style={{ textDecorationStyle: "dotted" }} > {errorTraceId} diff --git a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx index 7b901ec4c6..03a0eb5025 100644 --- a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx +++ b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx @@ -1,4 +1,4 @@ -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "../../components/AppSymbol"; import { connectionStatusText } from "@t3tools/client-runtime/connection"; import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId } from "@t3tools/contracts"; @@ -38,7 +38,6 @@ export function ConnectionEnvironmentRow(props: { const [url, setUrl] = useState(props.environment.displayUrl); const mutedColor = useThemeColor("--color-icon-subtle"); - const placeholderColor = useThemeColor("--color-placeholder"); const primaryFg = useThemeColor("--color-primary-foreground"); const dangerFg = useThemeColor("--color-danger-foreground"); const statusLabel = connectionStatusLabel(props.environment); @@ -76,16 +75,16 @@ export function ConnectionEnvironmentRow(props: { /> - + {props.environment.environmentLabel} - + {props.environment.displayUrl} {statusLabel ? ( { event.stopPropagation(); copyTextWithHaptic(statusTraceId, { target: "connection-trace-id" }); @@ -106,7 +105,6 @@ export function ConnectionEnvironmentRow(props: { onPress={(event) => { event.stopPropagation(); }} - style={{ textDecorationStyle: "dotted" }} > {statusTraceId} @@ -134,23 +132,19 @@ export function ConnectionEnvironmentRow(props: { className="gap-3 px-4 pb-4" > {props.environment.isRelayManaged ? ( - - Managed by T3 Cloud. Tunnel details update automatically. + + Managed by T3 Connect. Tunnel details update automatically. ) : ( <> - + Label - + URL - + Save diff --git a/apps/mobile/src/features/connection/ConnectionSheetButton.tsx b/apps/mobile/src/features/connection/ConnectionSheetButton.tsx index 8a692d8072..f88e328744 100644 --- a/apps/mobile/src/features/connection/ConnectionSheetButton.tsx +++ b/apps/mobile/src/features/connection/ConnectionSheetButton.tsx @@ -1,4 +1,4 @@ -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "../../components/AppSymbol"; import { Platform, Pressable } from "react-native"; import { useThemeColor } from "../../lib/useThemeColor"; @@ -37,33 +37,11 @@ export function ConnectionSheetButton(props: { }) { const tone = props.tone ?? "secondary"; - const primaryBg = useThemeColor("--color-primary"); const primaryFg = useThemeColor("--color-primary-foreground"); - const dangerBg = useThemeColor("--color-danger"); - const dangerBorderColor = useThemeColor("--color-danger-border"); const dangerFg = useThemeColor("--color-danger-foreground"); - const secondaryBg = useThemeColor("--color-secondary"); const secondaryFg = useThemeColor("--color-secondary-foreground"); - const borderColor = useThemeColor("--color-border"); - const colors = - tone === "primary" - ? { - backgroundColor: primaryBg, - borderColor: "transparent", - textColor: primaryFg, - } - : tone === "danger" - ? { - backgroundColor: dangerBg, - borderColor: dangerBorderColor, - textColor: dangerFg, - } - : { - backgroundColor: secondaryBg, - borderColor: borderColor, - textColor: secondaryFg, - }; + const textColor = tone === "primary" ? primaryFg : tone === "danger" ? dangerFg : secondaryFg; const primaryShadow = tone === "primary" @@ -80,32 +58,39 @@ export function ConnectionSheetButton(props: { return ( {props.label} diff --git a/apps/mobile/src/app/connections/new.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx similarity index 69% rename from apps/mobile/src/app/connections/new.tsx rename to apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx index ca9693dbb1..de3799ac8a 100644 --- a/apps/mobile/src/app/connections/new.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx @@ -1,28 +1,35 @@ import { CameraView, useCameraPermissions } from "expo-camera"; -import { Stack, useLocalSearchParams, useRouter } from "expo-router"; +import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader"; +import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { AsyncResult } from "effect/unstable/reactivity"; import { useCallback, useEffect, useState } from "react"; -import { Alert, ScrollView, View } from "react-native"; +import { Alert, Platform, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useThemeColor } from "../../lib/useThemeColor"; +import { AndroidScreenHeader } from "../../components/AndroidScreenHeader"; import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; import { ErrorBanner } from "../../components/ErrorBanner"; -import { dismissRoute } from "../../lib/routes"; -import { ConnectionSheetButton } from "../../features/connection/ConnectionSheetButton"; -import { extractPairingUrlFromQrPayload } from "../../features/connection/pairing"; +import { ConnectionSheetButton } from "./ConnectionSheetButton"; +import { extractPairingUrlFromQrPayload } from "./pairing"; import { useRemoteConnections } from "../../state/use-remote-environment-registry"; -import { buildPairingUrl, parsePairingUrl } from "../../features/connection/pairing"; +import { buildPairingUrl, parsePairingUrl } from "./pairing"; -export default function ConnectionsNewRouteScreen() { +type ConnectionsNewRouteParams = { + readonly mode?: string; +}; + +export function ConnectionsNewRouteScreen({ + route, +}: StaticScreenProps) { const { connectionPairingUrl, onChangeConnectionPairingUrl, onConnectPress, pairingConnectionError, } = useRemoteConnections(); - const router = useRouter(); - const params = useLocalSearchParams<{ mode?: string }>(); + const navigation = useNavigation(); + const params = route.params ?? {}; const insets = useSafeAreaInsets(); const [hostInput, setHostInput] = useState(""); const [codeInput, setCodeInput] = useState(""); @@ -31,7 +38,7 @@ export default function ConnectionsNewRouteScreen() { const [cameraPermission, requestCameraPermission] = useCameraPermissions(); const [scannerLocked, setScannerLocked] = useState(false); - const placeholderColor = useThemeColor("--color-placeholder"); + const headerIconColor = useThemeColor("--color-icon"); const connectDisabled = isSubmitting || hostInput.trim().length === 0; @@ -116,37 +123,64 @@ export default function ConnectionsNewRouteScreen() { onChangeConnectionPairingUrl(pairingUrl); const result = await onConnectPress(pairingUrl); if (AsyncResult.isSuccess(result)) { - dismissRoute(router); + if (navigation.canGoBack()) { + navigation.goBack(); + } else { + navigation.dispatch(StackActions.replace("Home")); + } } else { setIsSubmitting(false); } - }, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]); + }, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, navigation]); return ( - - - { - if (showScanner) { - closeScanner(); - } else { - void openScanner(); - } - }} - separateBackground + {Platform.OS === "android" ? ( + navigation.goBack()} + actions={[ + { + accessibilityLabel: showScanner ? "Close scanner" : "Scan QR code", + icon: showScanner ? "xmark" : "camera", + onPress: () => { + if (showScanner) { + closeScanner(); + } else { + void openScanner(); + } + }, + }, + ]} /> - + ) : ( + + { + if (showScanner) { + closeScanner(); + } else { + void openScanner(); + } + }} + separateBackground + tintColor={headerIconColor} + /> + + )} {showScanner ? ( cameraPermission?.granted ? ( - + ) : ( - - + + Camera permission is required to scan a QR code. - + Host - + Pairing code 0; const [expandedId, setExpandedId] = useState(null); @@ -31,22 +33,31 @@ export default function ConnectionsRouteScreen() { return ( - - - router.push("/connections/new")} - separateBackground + {Platform.OS === "android" ? ( + navigation.goBack()} + actions={[ + { + accessibilityLabel: "Add environment", + icon: "plus", + onPress: () => navigation.navigate("ConnectionsNew"), + }, + ]} /> - + ) : ( + + navigation.navigate("ConnectionsNew")} + separateBackground + /> + + )} - + No environments connected yet.{"\n"}Tap{" "} + to add one. diff --git a/apps/mobile/src/features/connection/EnvironmentConnectionNotice.tsx b/apps/mobile/src/features/connection/EnvironmentConnectionNotice.tsx index 373b0d3ef0..ce7e7bec96 100644 --- a/apps/mobile/src/features/connection/EnvironmentConnectionNotice.tsx +++ b/apps/mobile/src/features/connection/EnvironmentConnectionNotice.tsx @@ -2,7 +2,7 @@ import { type EnvironmentConnectionPhase, type EnvironmentConnectionPresentation, } from "@t3tools/client-runtime/connection"; -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "../../components/AppSymbol"; import { ActivityIndicator, Pressable, View } from "react-native"; import { AppText as Text } from "../../components/AppText"; @@ -73,10 +73,10 @@ export function EnvironmentConnectionNotice(props: { /> )} - + {noticeTitle(props.connection.phase, props.environmentLabel)} - + {noticeDetail(props.connection.phase, props.resourceName, props.connection.error)} {props.connection.traceId ? ( <> diff --git a/apps/mobile/src/features/connection/environmentSections.test.ts b/apps/mobile/src/features/connection/environmentSections.test.ts index 497af4bfac..75f78738ad 100644 --- a/apps/mobile/src/features/connection/environmentSections.test.ts +++ b/apps/mobile/src/features/connection/environmentSections.test.ts @@ -35,7 +35,7 @@ function cloudEnvironment(environmentId: string): RelayClientEnvironmentRecord { } describe("mobile environment settings sections", () => { - it("keeps saved relay-managed connections under T3 Cloud", () => { + it("keeps saved relay-managed connections under T3 Connect", () => { const local = connectedEnvironment({ environmentId: "environment-local", isRelayManaged: false, diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts new file mode 100644 index 0000000000..9e1480d1de --- /dev/null +++ b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts @@ -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 { + 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, + alreadyHighlightedRowIds?: ReadonlySet, +) { + 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], + ); + }); +}); diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts index 6c8c957f54..14158e61c7 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts +++ b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts @@ -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, + 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, +): 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) { const rowsByFileId = new Map(); 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> = {}; - 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(); diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts index 975bf7be13..438b50a27e 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts @@ -33,11 +33,14 @@ describe("resolveNativeReviewDiffView", () => { expect(expoMocks.requireNativeView).not.toHaveBeenCalled(); }); - it("returns the native review diff view when the view config is installed", async () => { + it("returns the payload bridge when the native review diff view is installed", async () => { setExpoViewConfigAvailable(); expoMocks.requireNativeView.mockReturnValue(nativeView); const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface"); - expect(resolveNativeReviewDiffView()).toBe(nativeView); + const resolvedView = resolveNativeReviewDiffView(); + expect(resolvedView).not.toBeNull(); + expect(resolvedView).not.toBe(nativeView); + expect(resolveNativeReviewDiffView()).toBe(resolvedView); expect(expoMocks.requireNativeView).toHaveBeenCalledWith("T3ReviewDiffSurface"); }); @@ -78,3 +81,37 @@ describe("resolveNativeReviewDiffView", () => { expect(consoleError).toHaveBeenCalledTimes(1); }); }); + +describe("isPendingNativeViewRegistration", () => { + it("recognizes registration races for the installed native view name", async () => { + const { isPendingNativeViewRegistration } = await import("./nativeReviewDiffSurface"); + + expect( + isPendingNativeViewRegistration( + new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag"), + ), + ).toBe(true); + expect( + 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); + }); +}); diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts index 7660a04775..fda7341066 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts @@ -1,10 +1,18 @@ -import type { ComponentType } from "react"; +import { + createElement, + useEffect, + useImperativeHandle, + useRef, + type ComponentType, + type Ref, +} from "react"; import type { NativeSyntheticEvent, ViewProps } from "react-native"; import { requireNativeView } from "expo"; import { NativeViewResolutionError } from "../../native/nativeViewResolutionError"; const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface"; +const NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES = 60; interface ExpoGlobalWithViewConfig { readonly expo?: { @@ -103,6 +111,7 @@ export interface NativeReviewDiffViewProps extends ViewProps { readonly tokensJson?: string; readonly tokensPatchJson?: string; readonly tokensResetKey?: string; + readonly contentResetKey?: string; readonly collapsedFileIdsJson?: string; readonly viewedFileIdsJson?: string; readonly selectedRowIdsJson?: string; @@ -113,7 +122,13 @@ export interface NativeReviewDiffViewProps extends ViewProps { readonly rowHeight: number; readonly contentWidth: number; readonly initialRowIndex?: number; + readonly refreshing?: boolean; + readonly nativeViewRef?: Ref; + readonly onPullToRefresh?: (event: NativeSyntheticEvent>) => void; readonly onDebug?: (event: NativeSyntheticEvent>) => void; + readonly onVisibleFileChange?: ( + event: NativeSyntheticEvent<{ readonly fileId?: string | null }>, + ) => void; readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void; readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void; readonly onPressLine?: ( @@ -129,18 +144,136 @@ export interface NativeReviewDiffViewProps extends ViewProps { readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void; } -let cachedNativeReviewDiffView: ComponentType | undefined; +export interface NativeReviewDiffViewHandle { + readonly scrollToFile: (fileId: string, animated?: boolean) => Promise; + readonly scrollToTop: (animated?: boolean) => Promise; +} + +export function isNativeReviewDiffDrawEvent(payload: Readonly>): boolean { + return payload.message === "draw-metrics" || payload.message === "visible-range"; +} + +interface NativeReviewDiffViewRef { + readonly setRowsJson: (rowsJson: string) => Promise; + readonly setTokensJson: (tokensJson: string) => Promise; + readonly setTokensPatchJson: (tokensPatchJson: string) => Promise; + readonly scrollToFile: (fileId: string, animated: boolean) => Promise; + readonly scrollToTop: (animated: boolean) => Promise; +} + +type NativeReviewDiffRawViewProps = Omit< + NativeReviewDiffViewProps, + "nativeViewRef" | "rowsJson" | "tokensJson" | "tokensPatchJson" +> & { + readonly ref?: Ref; +}; + +let cachedNativeReviewDiffRawView: ComponentType | undefined; let nativeReviewDiffViewResolutionFailed = false; +type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson"; + +export function isPendingNativeViewRegistration(error: unknown): boolean { + if (!(error instanceof Error)) return false; + return ( + 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")) + ); +} + +function useNativeReviewDiffPayload( + nativeRef: React.RefObject, + method: NativeReviewDiffPayloadMethod, + payload: string | undefined, +) { + useEffect(() => { + if (payload === undefined) { + return; + } + + let cancelled = false; + let frame: number | null = null; + let attempts = 0; + + const dispatch = () => { + if (cancelled) { + return; + } + + const view = nativeRef.current; + const command = view?.[method]; + if (!view || !command) { + if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) { + attempts += 1; + frame = requestAnimationFrame(dispatch); + } + return; + } + + void command.call(view, payload).catch((error: unknown) => { + if ( + !cancelled && + attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES && + isPendingNativeViewRegistration(error) + ) { + attempts += 1; + frame = requestAnimationFrame(dispatch); + return; + } + console.error(`[native-review-diff] ${method} failed`, error); + }); + }; + + // Fabric attaches the React ref before Expo registers the native tag used by + // view functions. Starting on the next frame avoids racing that registration. + frame = requestAnimationFrame(dispatch); + + return () => { + cancelled = true; + if (frame !== null) { + cancelAnimationFrame(frame); + } + }; + }, [method, nativeRef, payload]); +} + function getExpoViewConfig(moduleName: string) { return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.( moduleName, ); } +function NativeReviewDiffView(props: NativeReviewDiffViewProps) { + const { nativeViewRef, rowsJson, tokensJson, tokensPatchJson, ...nativeProps } = props; + const nativeRef = useRef(null); + useNativeReviewDiffPayload(nativeRef, "setRowsJson", rowsJson); + useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson); + useNativeReviewDiffPayload(nativeRef, "setTokensPatchJson", tokensPatchJson); + useImperativeHandle( + nativeViewRef, + () => ({ + scrollToFile: async (fileId, animated = true) => { + await nativeRef.current?.scrollToFile(fileId, animated); + }, + scrollToTop: async (animated = true) => { + await nativeRef.current?.scrollToTop(animated); + }, + }), + [], + ); + + const RawNativeView = cachedNativeReviewDiffRawView; + if (!RawNativeView) { + return null; + } + + return createElement(RawNativeView, { ...nativeProps, ref: nativeRef }); +} + export function resolveNativeReviewDiffView(): ComponentType | null { - if (cachedNativeReviewDiffView) { - return cachedNativeReviewDiffView; + if (cachedNativeReviewDiffRawView) { + return NativeReviewDiffView; } if (nativeReviewDiffViewResolutionFailed) { @@ -152,7 +285,7 @@ export function resolveNativeReviewDiffView(): ComponentType( + cachedNativeReviewDiffRawView = requireNativeView( NATIVE_REVIEW_DIFF_MODULE_NAME, ); } catch (cause) { @@ -166,5 +299,5 @@ export function resolveNativeReviewDiffView(): ComponentType resolveMarkdownFontSizes(appearance.baseFontSize), + [appearance.baseFontSize], + ); + const nativeMarkdownTypography = useMemo( + () => resolveNativeMarkdownTypography(appearance.baseFontSize), + [appearance.baseFontSize], + ); const body = String(useThemeColor("--color-md-body")); const strong = String(useThemeColor("--color-md-strong")); const link = String(useThemeColor("--color-md-link")); @@ -32,11 +46,15 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles { const codeBackground = String(useThemeColor("--color-md-code-bg")); const codeText = String(useThemeColor("--color-md-code-text")); const horizontalRule = String(useThemeColor("--color-md-hr")); + const regularFontFamily = useFontFamily("regular"); + const mediumFontFamily = useFontFamily("medium"); + const boldFontFamily = useFontFamily("bold"); return useMemo(() => { const renderers: CustomRenderers = { link: ({ href, children }) => ( { if (href) { void tryOpenExternalUrl(href, "markdown-link"); @@ -44,7 +62,6 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles { }} style={{ color: link, - fontFamily: "DMSans_500Medium", textDecorationLine: "none", }} > @@ -61,11 +78,14 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles { link, blockquote: blockquoteBorder, border: horizontalRule, + surface: "transparent", surfaceLight: blockquoteBackground, accent: link, tableBorder: horizontalRule, tableHeader: blockquoteBackground, tableHeaderText: strong, + tableRowOdd: blockquoteBackground, + tableRowEven: "transparent", code: codeText, codeBackground, }, @@ -73,20 +93,21 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles { styles: { text: { color: body, - fontFamily: "DMSans_400Regular", - ...MOBILE_TYPOGRAPHY.body, + fontFamily: regularFontFamily, + fontSize: markdownFontSizes.m, + lineHeight: markdownFontSizes.bodyLineHeight, }, heading: { color: strong, - fontFamily: "DMSans_700Bold", + fontFamily: boldFontFamily, }, strong: { color: strong, - fontFamily: "DMSans_700Bold", + fontFamily: boldFontFamily, }, link: { color: link, - fontFamily: "DMSans_500Medium", + fontFamily: mediumFontFamily, }, blockquote: { backgroundColor: blockquoteBackground, @@ -124,10 +145,12 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles { skillTextColor: codeText, quoteMarkerColor: blockquoteBorder, dividerColor: horizontalRule, - ...MOBILE_TYPOGRAPHY.body, - fontFamily: "DMSans_400Regular", - headingFontFamily: "DMSans_700Bold", - boldFontFamily: "DMSans_700Bold", + fontSize: nativeMarkdownTypography.fontSize, + lineHeight: nativeMarkdownTypography.lineHeight, + headingFontSizes: nativeMarkdownTypography.headingFontSizes, + fontFamily: regularFontFamily, + headingFontFamily: boldFontFamily, + boldFontFamily, }, }; }, [ @@ -138,18 +161,49 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles { codeText, horizontalRule, link, + markdownFontSizes, + mediumFontFamily, + nativeMarkdownTypography, + regularFontFamily, strong, + boldFontFamily, ]); } -export function FileMarkdownPreview(props: { readonly markdown: string }) { +export function FileMarkdownPreview(props: { + readonly markdown: string; + readonly onRefresh?: () => Promise | void; +}) { + const [isPullRefreshing, setIsPullRefreshing] = useState(false); + const handlePullToRefresh = useCallback(async () => { + if (!props.onRefresh) { + return; + } + setIsPullRefreshing(true); + try { + await props.onRefresh(); + } finally { + setIsPullRefreshing(false); + } + }, [props.onRefresh]); const styles = useMarkdownPreviewStyles(); const onLinkPress = useCallback((href: string) => { void tryOpenExternalUrl(href, "markdown-link"); }, []); return ( - + void handlePullToRefresh()} + /> + ) : undefined + } + > {hasNativeSelectableMarkdownText() ? ( , ReadonlyArray>(); +const FILE_TREE_INITIAL_RENDER_COUNT = 20; +const FILE_TREE_RENDER_BATCH_SIZE = 12; +const OPTIMISTIC_SELECTION_TIMEOUT_MS = 1_000; + +function cachedFileTree(entries: ReadonlyArray): ReadonlyArray { + const cached = fileTreeCache.get(entries); + if (cached !== undefined) { + return cached; + } + const tree = buildFileTree(entries); + fileTreeCache.set(entries, tree); + return tree; +} + function ancestorPaths(path: string): ReadonlyArray { const parts = path.split("/").filter(Boolean); const ancestors: string[] = []; @@ -25,19 +43,24 @@ function ancestorPaths(path: string): ReadonlyArray { const FileTreeRow = memo(function FileTreeRow(props: { readonly item: VisibleFileTreeNode; - readonly selectedPath: string | null; + readonly selected: boolean; readonly expanded: boolean; readonly iconColor: string; readonly onPressDirectory: (path: string) => void; + readonly onPreviewFile?: (path: string) => void; readonly onPressFile: (path: string) => void; }) { const { node, depth } = props.item; - const selected = node.kind === "file" && node.path === props.selectedPath; return ( { + if (node.kind === "file") { + props.onPreviewFile?.(node.path); + } + }} onPress={() => { if (node.kind === "directory") { props.onPressDirectory(node.path); @@ -47,7 +70,7 @@ const FileTreeRow = memo(function FileTreeRow(props: { }} className={cn( "mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle", - selected && "bg-subtle-strong", + props.selected && "bg-subtle-strong", )} style={{ paddingLeft: 8 + depth * 18 }} > @@ -64,8 +87,10 @@ const FileTreeRow = memo(function FileTreeRow(props: { @@ -86,13 +111,30 @@ export function FileTreeBrowser(props: { readonly isPending: boolean; readonly searchQuery: string; readonly selectedPath: string | null; + readonly onPreviewFile?: (path: string) => void; readonly onRefresh: () => void; readonly onSelectFile: (path: string) => void; }) { const [expandedPaths, setExpandedPaths] = useState>(() => new Set()); + const [pendingSelection, setPendingSelection] = useState<{ + readonly path: string; + readonly selectedPathAtPress: string | null; + } | null>(null); + const insets = useSafeAreaInsets(); + // Native transparent-header height ≈ safe-area top + nav bar (~44). Matches the + // observed adjustedContentInset bottom (~102) seen in the native trace. + const headerInset = NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 44 : 0; const iconColor = String(useThemeColor("--color-icon-muted")); + const { onPreviewFile, onSelectFile, selectedPath: controlledSelectedPath } = props; + const controlledSelectedPathRef = useRef(controlledSelectedPath); + const pendingSelectionTimeoutRef = useRef | null>(null); + controlledSelectedPathRef.current = controlledSelectedPath; - const tree = useMemo(() => buildFileTree(props.entries), [props.entries]); + const selectedPath = + pendingSelection?.selectedPathAtPress === controlledSelectedPath + ? pendingSelection.path + : controlledSelectedPath; + const tree = useMemo(() => cachedFileTree(props.entries), [props.entries]); const defaultExpanded = useMemo(() => defaultExpandedTreePaths(tree), [tree]); const visibleNodes = useMemo( () => @@ -114,17 +156,30 @@ export function FileTreeBrowser(props: { }, [defaultExpanded]); useEffect(() => { - if (!props.selectedPath) { + if (!controlledSelectedPath) { return; } setExpandedPaths((current) => { + const ancestors = ancestorPaths(controlledSelectedPath); + if (ancestors.every((ancestor) => current.has(ancestor))) { + return current; + } const next = new Set(current); - for (const ancestor of ancestorPaths(props.selectedPath ?? "")) { + for (const ancestor of ancestors) { next.add(ancestor); } return next; }); - }, [props.selectedPath]); + }, [controlledSelectedPath]); + + useEffect( + () => () => { + if (pendingSelectionTimeoutRef.current !== null) { + clearTimeout(pendingSelectionTimeoutRef.current); + } + }, + [], + ); const toggleDirectory = useCallback((path: string) => { setExpandedPaths((current) => { @@ -137,53 +192,88 @@ export function FileTreeBrowser(props: { return next; }); }, []); + const handleSelectFile = useCallback( + (path: string) => { + if (pendingSelectionTimeoutRef.current !== null) { + clearTimeout(pendingSelectionTimeoutRef.current); + } + setPendingSelection({ + path, + selectedPathAtPress: controlledSelectedPathRef.current, + }); + pendingSelectionTimeoutRef.current = setTimeout(() => { + pendingSelectionTimeoutRef.current = null; + setPendingSelection((current) => (current?.path === path ? null : current)); + }, OPTIMISTIC_SELECTION_TIMEOUT_MS); + onSelectFile(path); + }, + [onSelectFile], + ); + const renderItem = useCallback( + ({ item }: { readonly item: VisibleFileTreeNode }) => ( + + ), + [expandedPaths, handleSelectFile, iconColor, onPreviewFile, selectedPath, toggleDirectory], + ); + if (props.error && props.entries.length === 0) { + return ( + + Files unavailable + {props.error} + + ); + } + + // SPIKE: render the FlatList as the screen's DIRECT content (no wrapping View), and + // mirror the Home ScrollView exactly — `contentInsetAdjustmentBehavior: "automatic"` + // with NO manual contentInset. iOS only applies the nav-bar top inset + scroll-edge + // blur to a scroll view in the screen's primary position; a scroll view buried in + // flex-1 Views is ignored, which is why the tree rendered under the header with no blur. return ( - - {props.error && props.entries.length === 0 ? ( + item.node.path} + contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"} + scrollIndicatorInsets={ + NATIVE_LIQUID_GLASS_SUPPORTED + ? { top: headerInset, left: 0, right: 0, bottom: 0 } + : undefined + } + keyboardDismissMode="on-drag" + keyboardShouldPersistTaps="handled" + initialNumToRender={FILE_TREE_INITIAL_RENDER_COUNT} + maxToRenderPerBatch={FILE_TREE_RENDER_BATCH_SIZE} + updateCellsBatchingPeriod={16} + windowSize={5} + contentContainerStyle={{ paddingTop: 8, paddingBottom: 8 }} + refreshControl={} + renderItem={renderItem} + ListEmptyComponent={ - Files unavailable - {props.error} - - ) : ( - item.node.path} - contentInsetAdjustmentBehavior="automatic" - keyboardDismissMode="on-drag" - keyboardShouldPersistTaps="handled" - contentContainerStyle={{ paddingVertical: 8 }} - refreshControl={ - - } - renderItem={({ item }) => ( - + {props.isPending ? ( + + ) : ( + <> + No files found + + {props.searchQuery.trim().length > 0 + ? "Try a different search." + : "The workspace file index is empty."} + + )} - ListEmptyComponent={ - - {props.isPending ? ( - - ) : ( - <> - No files found - - {props.searchQuery.trim().length > 0 - ? "Try a different search." - : "The workspace file index is empty."} - - - )} - - } - /> - )} - + + } + /> ); } diff --git a/apps/mobile/src/features/files/SourceFileSurface.tsx b/apps/mobile/src/features/files/SourceFileSurface.tsx index b96d651595..9774130eb2 100644 --- a/apps/mobile/src/features/files/SourceFileSurface.tsx +++ b/apps/mobile/src/features/files/SourceFileSurface.tsx @@ -1,8 +1,15 @@ import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/unstable/reactivity"; import type { ComponentType } from "react"; -import { memo, useCallback, useEffect, useMemo, useRef } from "react"; -import { FlatList, ScrollView, Text as NativeText, useColorScheme, View } from "react-native"; +import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + FlatList, + ScrollView, + Text as NativeText, + useColorScheme, + useWindowDimensions, + View, +} from "react-native"; import { AppText as Text } from "../../components/AppText"; import { LoadingStrip } from "../../components/LoadingStrip"; @@ -11,71 +18,62 @@ import { resolveNativeReviewDiffView, } from "../diffs/nativeReviewDiffSurface"; import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter"; -import { - REVIEW_DIFF_LINE_HEIGHT, - REVIEW_MONO_FONT_FAMILY, - renderVisibleWhitespace, -} from "../review/reviewDiffRendering"; +import { REVIEW_MONO_FONT_FAMILY, renderVisibleWhitespace } from "../review/reviewDiffRendering"; import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter"; import { cn } from "../../lib/cn"; -import { MOBILE_CODE_SURFACE } from "../../lib/typography"; +import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences"; +import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface"; import { - buildNativeSourceRows, buildNativeSourceTokens, NATIVE_SOURCE_CONTENT_WIDTH, - NATIVE_SOURCE_ROW_HEIGHT, - NATIVE_SOURCE_STYLE, nativeSourceRowId, } from "./nativeSourceFileAdapter"; +import { prepareSourceFileDocument } from "./source-file-document"; import { sourceHighlightAtom } from "./sourceHighlightingState"; -const SOURCE_LINE_HEIGHT = MOBILE_CODE_SURFACE.rowHeight; -const SOURCE_LINE_NUMBER_WIDTH = MOBILE_CODE_SURFACE.gutterWidth; -const NATIVE_SOURCE_STYLE_JSON = JSON.stringify(NATIVE_SOURCE_STYLE); - interface SourceFileSurfaceProps { readonly contents: string; readonly path: string; readonly initialLine?: number | null; + /** Enables native pull-to-refresh on the source surface. */ + readonly onRefresh?: () => Promise | void; } type SourceHighlightStatus = "highlighting" | "ready" | "error"; -function splitSourceLines(contents: string): ReadonlyArray { - return contents.replace(/\r\n?/g, "\n").split("\n"); -} - const HighlightedSourceLine = memo(function HighlightedSourceLine(props: { + readonly codeSurface: ResolvedMobileCodeSurface; readonly index: number; readonly line: string; readonly tokens: ReadonlyArray | null; readonly highlighted: boolean; + readonly wordBreak: boolean; }) { return ( {props.index + 1} {props.tokens && props.tokens.length > 0 @@ -119,11 +117,8 @@ const HighlightedSourceLine = memo(function HighlightedSourceLine(props: { function useSourceFileModel(props: SourceFileSurfaceProps) { const colorScheme = useColorScheme(); const theme: "dark" | "light" = colorScheme === "dark" ? "dark" : "light"; - const normalizedContents = useMemo( - () => props.contents.replace(/\r\n?/g, "\n"), - [props.contents], - ); - const lines = useMemo(() => splitSourceLines(normalizedContents), [normalizedContents]); + const document = useMemo(() => prepareSourceFileDocument(props.contents), [props.contents]); + const { contents: normalizedContents, lines, rowsJson } = document; const targetIndex = props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0 ? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1)) @@ -140,7 +135,7 @@ function useSourceFileModel(props: SourceFileSurfaceProps) { ? "ready" : "highlighting"; - return { lines, status, targetIndex, theme, tokens }; + return { lines, rowsJson, status, targetIndex, theme, tokens }; } function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) { @@ -162,39 +157,63 @@ function NativeSourceFileSurface( readonly NativeView: ComponentType; }, ) { - const { NativeView } = props; - const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props); - const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]); + const { NativeView, onRefresh } = props; + const { codeSurface, codeWordBreak, nativeSourceStyle } = useAppearanceCodeSurface(); + const { width: viewportWidth } = useWindowDimensions(); + const { rowsJson, status, targetIndex, theme, tokens } = useSourceFileModel(props); + const [isPullRefreshing, setIsPullRefreshing] = useState(false); + const handlePullToRefresh = useCallback(async () => { + if (!onRefresh) { + return; + } + setIsPullRefreshing(true); + try { + await onRefresh(); + } finally { + setIsPullRefreshing(false); + } + }, [onRefresh]); const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]); const selectedRowIdsJson = useMemo( () => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]), [targetIndex], ); const themeJson = useMemo(() => JSON.stringify(createNativeReviewDiffTheme(theme)), [theme]); + const styleJson = useMemo(() => JSON.stringify(nativeSourceStyle), [nativeSourceStyle]); + const contentWidth = codeWordBreak + ? Math.max(240, viewportWidth - codeSurface.gutterWidth - 24) + : NATIVE_SOURCE_CONTENT_WIDTH; return ( - + void handlePullToRefresh(), + } + : {})} /> ); } function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) { + const { codeSurface, codeWordBreak } = useAppearanceCodeSurface(); const { lines, status, targetIndex, tokens } = useSourceFileModel(props); const listRef = useRef>(null); @@ -211,39 +230,53 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) { const renderLine = useCallback( ({ item, index }: { item: string; index: number }) => ( ), - [targetIndex, tokens], + [codeSurface, codeWordBreak, targetIndex, tokens], + ); + + const list = ( + String(index)} + initialNumToRender={80} + maxToRenderPerBatch={80} + windowSize={12} + {...(codeWordBreak + ? {} + : { + getItemLayout: (_data, index) => ({ + length: codeSurface.rowHeight, + offset: codeSurface.rowHeight * index, + index, + }), + })} + contentContainerStyle={{ + minWidth: codeWordBreak ? undefined : "100%", + paddingBottom: codeSurface.rowHeight, + paddingTop: 8, + }} + renderItem={renderLine} + /> ); return ( - + - - String(index)} - initialNumToRender={80} - maxToRenderPerBatch={80} - windowSize={12} - getItemLayout={(_data, index) => ({ - length: SOURCE_LINE_HEIGHT, - offset: SOURCE_LINE_HEIGHT * index, - index, - })} - contentContainerStyle={{ - minWidth: "100%", - paddingBottom: REVIEW_DIFF_LINE_HEIGHT, - paddingTop: 8, - }} - renderItem={renderLine} - /> - + {codeWordBreak ? ( + list + ) : ( + + {list} + + )} ); } diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx index fba032c036..012f99536d 100644 --- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx +++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx @@ -1,8 +1,8 @@ -import Stack from "expo-router/stack"; -import { SymbolView } from "expo-symbols"; -import { useLocalSearchParams, useRouter } from "expo-router"; -import { useCallback, useMemo, useRef, useState } from "react"; -import { ActivityIndicator, Pressable, ScrollView, Text as RNText, View } from "react-native"; +import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader"; +import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { ActivityIndicator, Platform, useColorScheme, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"; import { EnvironmentId, @@ -11,28 +11,37 @@ import { ThreadId, } from "@t3tools/contracts"; -import { AppText as Text } from "../../components/AppText"; -import { CopyTextButton } from "../../components/CopyTextButton"; +import { AndroidScreenHeader } from "../../components/AndroidScreenHeader"; +import { SymbolView } from "../../components/AppSymbol"; +import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; import { EmptyState } from "../../components/EmptyState"; import { LoadingScreen } from "../../components/LoadingScreen"; -import { cn } from "../../lib/cn"; +import { resolveFileSelectionNavigationAction } from "../../lib/adaptive-navigation"; +import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; -import { buildThreadFilesNavigation } from "../../lib/routes"; -import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; import { useThemeColor } from "../../lib/useThemeColor"; import { useThreadSelection } from "../../state/use-thread-selection"; import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; import { useEnvironmentQuery } from "../../state/query"; import { projectEnvironment } from "../../state/projects"; +import { + useAdaptiveWorkspaceLayout, + useAdaptiveWorkspacePaneRole, + useRegisterWorkspaceInspector, +} from "../layout/AdaptiveWorkspaceLayout"; +import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar"; +import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar"; import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider"; +import { ThreadRouteScreen } from "../threads/ThreadRouteScreen"; import { FileMarkdownPreview } from "./FileMarkdownPreview"; import { FileTreeBrowser } from "./FileTreeBrowser"; +import { preloadWorkspaceFileContents } from "./preload-workspace-file"; import { SourceFileSurface } from "./SourceFileSurface"; +import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane"; import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview"; import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview"; import { basename, - fileBreadcrumbs, isBrowserPreviewFile, isImagePreviewFile, isMarkdownPreviewFile, @@ -72,196 +81,6 @@ function defaultViewMode(path: string | null): FileViewMode { : "source"; } -function ModeButton(props: { - readonly active: boolean; - readonly icon: "doc.text" | "eye"; - readonly label: string; - readonly onPress: () => void; -}) { - const iconColor = String( - useThemeColor(props.active ? "--color-primary-foreground" : "--color-icon-muted"), - ); - - return ( - - - - {props.label} - - - ); -} - -function BreadcrumbFade(props: { readonly color: string; readonly side: "left" | "right" }) { - const gradientId = `file-breadcrumb-${props.side}-fade`; - const isLeft = props.side === "left"; - - return ( - - - - - - - - - - - - ); -} - -function FileBreadcrumbs(props: { readonly projectName: string; readonly relativePath: string }) { - const iconColor = String(useThemeColor("--color-icon-muted")); - const cardColor = String(useThemeColor("--color-card")); - const scrollMetrics = useRef({ contentWidth: 0, offsetX: 0, viewportWidth: 0 }); - const [fadeVisibility, setFadeVisibility] = useState({ left: false, right: false }); - const breadcrumbs = useMemo( - () => fileBreadcrumbs(props.projectName, props.relativePath), - [props.projectName, props.relativePath], - ); - const updateFadeVisibility = useCallback( - (metrics: Partial<(typeof scrollMetrics)["current"]>) => { - Object.assign(scrollMetrics.current, metrics); - const { contentWidth, offsetX, viewportWidth } = scrollMetrics.current; - const maxOffset = Math.max(0, contentWidth - viewportWidth); - const next = { - left: maxOffset > 1 && offsetX > 1, - right: maxOffset > 1 && offsetX < maxOffset - 1, - }; - - setFadeVisibility((current) => - current.left === next.left && current.right === next.right ? current : next, - ); - }, - [], - ); - - return ( - - { - updateFadeVisibility({ contentWidth }); - }} - onLayout={(event) => { - updateFadeVisibility({ viewportWidth: event.nativeEvent.layout.width }); - }} - onScroll={(event) => { - updateFadeVisibility({ offsetX: event.nativeEvent.contentOffset.x }); - }} - scrollEventThrottle={16} - > - - {breadcrumbs.map((crumb, index) => ( - - {index > 0 ? ( - - ) : null} - - {crumb.label} - - - ))} - - - {fadeVisibility.left ? : null} - {fadeVisibility.right ? : null} - - ); -} - -function FilePreviewHeader(props: { - readonly activeMode: FileViewMode; - readonly showModeSelector: boolean; - readonly externalPreviewUri?: string | null; - readonly projectName: string; - readonly relativePath: string; - readonly onSetMode: (mode: FileViewMode) => void; -}) { - const iconColor = String(useThemeColor("--color-icon-muted")); - - return ( - - - - - - {props.showModeSelector ? ( - - props.onSetMode("preview")} - /> - props.onSetMode("source")} - /> - {props.externalPreviewUri !== undefined ? ( - { - if (typeof props.externalPreviewUri === "string") { - void tryOpenExternalUrl(props.externalPreviewUri, "file-preview"); - } - }} - > - - - ) : null} - - ) : null} - - ); -} - function FileContent(props: { readonly activeMode: FileViewMode; readonly previewUri: string | null; @@ -270,6 +89,7 @@ function FileContent(props: { readonly relativePath: string; readonly initialLine: number | null; readonly truncated: boolean; + readonly onRefresh?: () => Promise | void; }) { const isMarkdown = isMarkdownPreviewFile(props.relativePath); const isBrowserFile = isBrowserPreviewFile(props.relativePath); @@ -293,7 +113,7 @@ function FileContent(props: { if (props.fileError && props.fileContents === null) { return ( - + ); @@ -301,7 +121,7 @@ function FileContent(props: { if (props.fileContents === null) { return ( - + Loading file... @@ -309,35 +129,47 @@ function FileContent(props: { } return ( - + {props.truncated ? ( Partial file - + Preview limited to the first 1 MB of a truncated file. ) : null} {props.activeMode === "preview" && isMarkdown ? ( - + ) : ( )} ); } -function useThreadFilesWorkspace() { - const params = useLocalSearchParams<{ - environmentId?: string | string[]; - threadId?: string | string[]; - }>(); +type ThreadFilesRouteScreenProps = StaticScreenProps<{ + readonly environmentId: string; + readonly threadId: string; +}>; + +type ThreadFileRouteScreenProps = StaticScreenProps<{ + readonly environmentId: string; + readonly threadId: string; + readonly path: string[]; + readonly line?: string; +}>; + +function useThreadFilesWorkspace(params: { + readonly environmentId?: string | string[]; + readonly threadId?: string | string[]; +}) { const routeEnvironmentId = firstRouteParam(params.environmentId); const routeThreadId = firstRouteParam(params.threadId); const { selectedThread, selectedThreadProject } = useThreadSelection(); @@ -364,7 +196,7 @@ function useThreadFilesWorkspace() { function FilesUnavailable() { return ( - + - - Files - - - {props.projectName} - - - ); -} - function FilesToolbarBottomFade() { const sheetColor = String(useThemeColor("--color-sheet")); @@ -419,14 +217,7 @@ function FilesToolbarBottomFade() { pointerEvents="none" accessibilityElementsHidden importantForAccessibility="no-hide-descendants" - style={{ - bottom: 0, - height: 112, - left: 0, - position: "absolute", - right: 0, - zIndex: 1, - }} + className="absolute inset-x-0 bottom-0 z-[1] h-28" > @@ -442,12 +233,22 @@ function FilesToolbarBottomFade() { ); } -export function ThreadFilesTreeScreen() { - const router = useRouter(); +export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) { + useAdaptiveWorkspacePaneRole("inspector"); + const navigation = useNavigation(); + const { fileInspector, layout, panes, showAuxiliaryPane, togglePrimarySidebar } = + useAdaptiveWorkspaceLayout(); const [searchQuery, setSearchQuery] = useState(""); - const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(); + const colorScheme = useColorScheme(); + const isAndroid = Platform.OS === "android"; + const highlightTheme = colorScheme === "dark" ? "dark" : "light"; + const iconColor = String(useThemeColor("--color-icon-muted")); + const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace( + props.route.params, + ); + const revealedInspectorRef = useRef(false); const entriesQuery = useEnvironmentQuery( - environmentId !== null && cwd !== null + environmentId !== null && cwd !== null && !fileInspector.supported ? projectEnvironment.listEntries({ environmentId, input: { cwd }, @@ -455,18 +256,87 @@ export function ThreadFilesTreeScreen() { : null, ); const entriesData = entriesQuery.data as ProjectListEntriesResult | null; + const handleReturnToThread = useCallback(() => { + if (navigation.canGoBack()) { + navigation.goBack(); + return; + } + if (environmentId !== null && threadId !== null) { + navigation.dispatch( + StackActions.replace("Thread", { + environmentId: String(environmentId), + threadId: String(threadId), + }), + ); + } + }, [environmentId, navigation, threadId]); const handleSelectFile = useCallback( (path: string) => { if (environmentId === null || threadId === null) { return; } - router.push(buildThreadFilesNavigation({ environmentId, threadId }, path)); + const params = { + environmentId: String(environmentId), + threadId: String(threadId), + path: path.split("/").filter((segment) => segment.length > 0), + }; + const navigationAction = resolveFileSelectionNavigationAction({ + hasPersistentFileInspector: fileInspector.supported, + }); + if (navigationAction === "replace") { + navigation.dispatch(StackActions.replace("ThreadFile", params)); + return; + } + navigation.navigate("ThreadFile", params); }, - [environmentId, router, threadId], + [environmentId, fileInspector.supported, navigation, threadId], ); + const renderInspector = useCallback( + (headerInset: number) => + environmentId !== null && cwd !== null ? ( + + ) : null, + [cwd, environmentId, handleSelectFile, projectName], + ); + const handlePreviewFile = useCallback( + (relativePath: string) => { + if (environmentId === null || cwd === null) { + return; + } + preloadWorkspaceFileContents({ + cwd, + environmentId, + relativePath, + theme: highlightTheme, + }); + }, + [cwd, environmentId, highlightTheme], + ); + useEffect(() => { + if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) { + revealedInspectorRef.current = true; + showAuxiliaryPane("inspector"); + } + }, [cwd, fileInspector.supported, showAuxiliaryPane]); if (selectedThread === null || environmentId === null || threadId === null) { + if (fileInspector.supported) { + return ( + + ); + } return ; } @@ -474,62 +344,129 @@ export function ThreadFilesTreeScreen() { return ; } + if (fileInspector.supported) { + return ( + + ); + } + + const usesCompactMailToolbar = Platform.OS === "ios" && !layout.usesSplitView; + return ( - - + {/* Static header config (glass preset, title, contentStyle) lives in Stack.tsx. + Only genuinely dynamic options are set here. */} + , - headerSearchBarOptions: { - allowToolbarIntegration: true, - autoCapitalize: "none", - hideNavigationBar: false, - placeholder: "Search files", - onChangeText: (event) => { - setSearchQuery(event.nativeEvent.text); - }, - onCancelButtonPress: () => { - setSearchQuery(""); - }, - }, + headerShown: !isAndroid, + unstable_headerSubtitle: + Platform.OS === "ios" && projectName.length > 0 ? projectName : undefined, + // No refresh button: the list already supports pull-to-refresh. + unstable_headerToolbarItems: usesCompactMailToolbar + ? () => [ + createNativeMailSearchToolbarItem({ + onSearchTextChange: setSearchQuery, + placeholder: "Search files", + searchTextChangeId: "files-search-text", + }), + ] + : undefined, + headerSearchBarOptions: usesCompactMailToolbar + ? undefined + : { + allowToolbarIntegration: true, + autoCapitalize: "none", + hideNavigationBar: false, + placeholder: "Search files", + onChangeText: (event) => { + setSearchQuery(event.nativeEvent.text); + }, + onCancelButtonPress: () => { + setSearchQuery(""); + }, + }, }} /> - - - - - - + {isAndroid ? ( + <> + + + + + + + ) : ( + <> + {layout.usesSplitView ? ( + + + + ) : null} + {usesCompactMailToolbar ? null : ( + + + + )} + + )} - + ); } -export function ThreadFileScreen() { - const params = useLocalSearchParams<{ - line?: string | string[]; - path?: string | string[]; - }>(); +export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { + useAdaptiveWorkspacePaneRole("inspector"); + const navigation = useNavigation(); + const { fileInspector, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout(); + const iconColor = useThemeColor("--color-icon"); + const params = props.route.params; const relativePath = normalizeRoutePath(params.path); const targetLine = normalizeRouteLine(firstRouteParam(params.line)); - const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(); + const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace( + props.route.params, + ); const [modeOverride, setModeOverride] = useState<{ readonly path: string; readonly mode: FileViewMode; @@ -568,6 +505,43 @@ export function ThreadFileScreen() { ); const fileData = fileQuery.data as ProjectReadFileResult | null; + const handleSelectFile = useCallback( + (path: string) => { + navigation.navigate("ThreadFile", { + environmentId: String(environmentId), + threadId: String(threadId), + path: path.split("/").filter(Boolean), + }); + }, + [environmentId, navigation, threadId], + ); + const renderInspector = useCallback( + (headerInset: number) => + fileInspector.supported && environmentId !== null && cwd !== null ? ( + + ) : undefined, + [cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath], + ); + // The workspace inspector column spans the full window height. On iOS the + // pane brings its own nested native header; elsewhere it pads itself below + // the top inset. + const safeAreaInsets = useSafeAreaInsets(); + const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top; + // Hand the file navigator to the workspace so it renders beside the + // navigator, outside this screen's native header. + const renderWorkspaceInspector = useCallback( + () => renderInspector(inspectorHeaderInset), + [inspectorHeaderInset, renderInspector], + ); + useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined); + if (selectedThread === null || environmentId === null || threadId === null) { return ; } @@ -579,38 +553,104 @@ export function ThreadFileScreen() { if (relativePath === null) { return ( - + ); } + const parentDir = relativePath.split("/").slice(0, -1).join("/"); + const headerSubtitle = [projectName, parentDir].filter(Boolean).join(" · "); + return ( - - - { - if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) { - setPreviewRevision((current) => current + 1); - return; - } - fileQuery.refresh(); - }} - /> - - { - setModeOverride({ path: relativePath, mode }); + 0 ? headerSubtitle : undefined, }} /> + + {fileInspector.supported ? ( + { + navigation.dispatch( + StackActions.replace("Thread", { + environmentId: String(environmentId), + threadId: String(threadId), + }), + ); + }} + /> + ) : null} + + + {fileInspector.supported ? ( + + ) : null} + + {canPreview && !isImageFile ? ( + + setModeOverride({ path: relativePath, mode: "preview" })} + > + Preview + + setModeOverride({ path: relativePath, mode: "source" })} + > + Source + + + ) : null} + copyTextWithHaptic(relativePath)} + > + Copy path + + {isBrowserFile && typeof assetPreviewUri === "string" ? ( + { + void tryOpenExternalUrl(assetPreviewUri, "file-preview"); + }} + > + Open in Safari + + ) : null} + {resolvedActiveMode === "preview" && (isBrowserFile || isImageFile) ? ( + { + setPreviewRevision((current) => current + 1); + }} + > + Refresh + + ) : null} + + fileQuery.refresh()} /> diff --git a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx index 6d03a23d52..efa7ee88cb 100644 --- a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx +++ b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx @@ -24,7 +24,7 @@ export function WorkspaceFileWebPreview(props: { readonly uri: string | null }) {loadError ? ( Preview failed - {loadError} + {loadError} ) : null} >(); +const MAX_HIGHLIGHT_PRELOAD_CHARACTERS = 256 * 1024; + +function preloadKey(input: { + readonly cwd: string; + readonly environmentId: EnvironmentId; + readonly relativePath: string; +}): string { + return JSON.stringify([input.environmentId, input.cwd, input.relativePath]); +} + +export function preloadWorkspaceFileContents(input: { + readonly cwd: string; + readonly environmentId: EnvironmentId; + readonly relativePath: string; + readonly theme: ReviewDiffTheme; +}): void { + if (isBrowserPreviewFile(input.relativePath) || isImagePreviewFile(input.relativePath)) { + return; + } + + const key = preloadKey(input); + if (inFlightPreloads.has(key)) { + return; + } + + const preload = executeAtomQuery( + appAtomRegistry, + projectEnvironment.readFile({ + environmentId: input.environmentId, + input: { cwd: input.cwd, relativePath: input.relativePath }, + }), + { + label: "workspace file preload", + reportDefect: false, + reportFailure: false, + }, + ) + .then(async (result) => { + if (result._tag === "Success") { + const document = prepareSourceFileDocument(result.value.contents); + if (document.contents.length <= MAX_HIGHLIGHT_PRELOAD_CHARACTERS) { + await executeAtomQuery( + appAtomRegistry, + sourceHighlightAtom({ + path: input.relativePath, + contents: document.contents, + theme: input.theme, + }), + { + label: "workspace source highlight preload", + reportDefect: false, + reportFailure: false, + }, + ); + } + } + }) + .finally(() => { + inFlightPreloads.delete(key); + }); + + inFlightPreloads.set(key, preload); +} diff --git a/apps/mobile/src/features/files/source-file-document.test.ts b/apps/mobile/src/features/files/source-file-document.test.ts new file mode 100644 index 0000000000..04b3046994 --- /dev/null +++ b/apps/mobile/src/features/files/source-file-document.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { prepareSourceFileDocument } from "./source-file-document"; + +describe("prepareSourceFileDocument", () => { + it("normalizes and serializes source rows once for repeated consumers", () => { + const first = prepareSourceFileDocument("const value = 1;\r\n\tvalue;\r"); + const second = prepareSourceFileDocument("const value = 1;\r\n\tvalue;\r"); + const rows = JSON.parse(first.rowsJson) as ReadonlyArray<{ readonly content: string }>; + + expect(first.contents).toBe("const value = 1;\n\tvalue;\n"); + expect(first.lines).toEqual(["const value = 1;", "\tvalue;", ""]); + expect(rows.map((row) => row.content)).toEqual(["const value = 1;", " value;", ""]); + expect(second).toBe(first); + }); +}); diff --git a/apps/mobile/src/features/files/source-file-document.ts b/apps/mobile/src/features/files/source-file-document.ts new file mode 100644 index 0000000000..d78ead3288 --- /dev/null +++ b/apps/mobile/src/features/files/source-file-document.ts @@ -0,0 +1,54 @@ +import { buildNativeSourceRows } from "./nativeSourceFileAdapter"; + +const MAX_CACHED_DOCUMENTS = 8; +const MAX_CACHED_CHARACTERS = 4 * 1024 * 1024; + +export interface SourceFileDocument { + readonly contents: string; + readonly lines: ReadonlyArray; + readonly rowsJson: string; +} + +const documentCache = new Map(); +let cachedCharacterCount = 0; + +function removeOldestCachedDocument(): void { + const oldestKey = documentCache.keys().next().value; + if (typeof oldestKey !== "string") { + return; + } + const document = documentCache.get(oldestKey); + documentCache.delete(oldestKey); + cachedCharacterCount -= (document?.contents.length ?? 0) + (document?.rowsJson.length ?? 0); +} + +export function prepareSourceFileDocument(contents: string): SourceFileDocument { + const cached = documentCache.get(contents); + if (cached !== undefined) { + documentCache.delete(contents); + documentCache.set(contents, cached); + return cached; + } + + const normalizedContents = contents.replace(/\r\n?/g, "\n"); + const lines = normalizedContents.split("\n"); + const document = { + contents: normalizedContents, + lines, + rowsJson: JSON.stringify(buildNativeSourceRows(lines)), + } satisfies SourceFileDocument; + const characterCount = document.contents.length + document.rowsJson.length; + + if (characterCount <= MAX_CACHED_CHARACTERS) { + while ( + documentCache.size >= MAX_CACHED_DOCUMENTS || + cachedCharacterCount + characterCount > MAX_CACHED_CHARACTERS + ) { + removeOldestCachedDocument(); + } + documentCache.set(contents, document); + cachedCharacterCount += characterCount; + } + + return document; +} diff --git a/apps/mobile/src/features/files/sourceHighlightingState.test.ts b/apps/mobile/src/features/files/sourceHighlightingState.test.ts index 6c4c00e166..50b4eec41b 100644 --- a/apps/mobile/src/features/files/sourceHighlightingState.test.ts +++ b/apps/mobile/src/features/files/sourceHighlightingState.test.ts @@ -88,7 +88,7 @@ describe("sourceHighlightingState", () => { expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true); }); firstUnmount(); - await new Promise((resolve) => setTimeout(resolve, 25)); + await new Promise((resolve) => setTimeout(resolve, 100)); const secondUnmount = registry.mount(atom); await vi.waitFor(() => { diff --git a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx new file mode 100644 index 0000000000..c06f7cc969 --- /dev/null +++ b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx @@ -0,0 +1,175 @@ +import type { EnvironmentId, ProjectListEntriesResult } from "@t3tools/contracts"; +import { SymbolView } from "../../components/AppSymbol"; +import { useCallback, useMemo, useState, type ComponentProps } from "react"; +import { Platform, Pressable, useColorScheme, View, type NativeSyntheticEvent } from "react-native"; +import { + Screen, + ScreenStack, + ScreenStackHeaderConfig, + ScreenStackHeaderSearchBarView, + SearchBar, +} from "react-native-screens"; + +import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; +import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader"; +import { useThemeColor } from "../../lib/useThemeColor"; +import { projectEnvironment } from "../../state/projects"; +import { useEnvironmentQuery } from "../../state/query"; +import { FileTreeBrowser } from "./FileTreeBrowser"; +import { preloadWorkspaceFileContents } from "./preload-workspace-file"; + +export function ThreadFileNavigatorPane(props: { + readonly cwd: string; + readonly environmentId: EnvironmentId; + readonly headerInset: number; + readonly projectName: string; + readonly selectedPath: string | null; + readonly onSelectFile: (path: string) => void; +}) { + const [searchQuery, setSearchQuery] = useState(""); + const colorScheme = useColorScheme(); + const highlightTheme = colorScheme === "dark" ? "dark" : "light"; + const iconColor = String(useThemeColor("--color-icon-muted")); + const foregroundColor = String(useThemeColor("--color-foreground")); + const sheetColor = String(useThemeColor("--color-sheet")); + const headerScrollEdgeEffects = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version); + const entriesQuery = useEnvironmentQuery( + projectEnvironment.listEntries({ + environmentId: props.environmentId, + input: { cwd: props.cwd }, + }), + ); + const entriesData = entriesQuery.data as ProjectListEntriesResult | null; + const handlePreviewFile = useCallback( + (relativePath: string) => { + preloadWorkspaceFileContents({ + cwd: props.cwd, + environmentId: props.environmentId, + relativePath, + theme: highlightTheme, + }); + }, + [highlightTheme, props.cwd, props.environmentId], + ); + const nativeHeaderRightBarButtonItems = useMemo( + () => + [ + { + accessibilityLabel: "Refresh files", + icon: { name: "arrow.clockwise", type: "sfSymbol" as const }, + identifier: "thread-file-navigator-refresh", + onPress: entriesQuery.refresh, + sharesBackground: false, + tintColor: foregroundColor, + type: "button" as const, + width: 44, + }, + ] as ComponentProps["headerRightBarButtonItems"], + [entriesQuery.refresh, foregroundColor], + ); + + const fileTree = ( + + ); + + if (Platform.OS === "ios") { + return ( + + + + {fileTree} + + + { + setSearchQuery(""); + }} + onChangeText={(event: NativeSyntheticEvent<{ readonly text?: string }>) => { + setSearchQuery(event.nativeEvent.text ?? ""); + }} + placement="integratedButton" + placeholder="Search files" + textColor={foregroundColor} + tintColor={foregroundColor} + /> + + + + + + ); + } + + return ( + + + + + Files + + {props.projectName} + + + + + + + + + + + + {fileTree} + + ); +} diff --git a/apps/mobile/src/features/home/AndroidHomeFab.tsx b/apps/mobile/src/features/home/AndroidHomeFab.tsx new file mode 100644 index 0000000000..5c7d5a0b98 --- /dev/null +++ b/apps/mobile/src/features/home/AndroidHomeFab.tsx @@ -0,0 +1,51 @@ +import type { ReactNode } from "react"; +import { Platform, Pressable, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { SymbolView } from "../../components/AppSymbol"; +import { useThemeColor } from "../../lib/useThemeColor"; + +/** + * Android-only wrapper that overlays a bottom-right new-task FAB on the home + * screen. Other platforms render children unchanged. + */ +export function AndroidHomeFabLayout(props: { + readonly onStartNewTask: () => void; + readonly children: ReactNode; +}) { + if (Platform.OS !== "android") { + return <>{props.children}; + } + + return ; +} + +function AndroidHomeFab(props: { + readonly onStartNewTask: () => void; + readonly children: ReactNode; +}) { + const insets = useSafeAreaInsets(); + const primaryForegroundColor = useThemeColor("--color-primary-foreground"); + + return ( + + {props.children} + + + + + ); +} diff --git a/apps/mobile/src/features/home/HomeHeader.tsx b/apps/mobile/src/features/home/HomeHeader.tsx index 9757d5fbf9..3a0342a821 100644 --- a/apps/mobile/src/features/home/HomeHeader.tsx +++ b/apps/mobile/src/features/home/HomeHeader.tsx @@ -3,63 +3,37 @@ import type { SidebarProjectGroupingMode, SidebarThreadSortOrder, } from "@t3tools/contracts"; -import { - DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE, - DEFAULT_SIDEBAR_PROJECT_SORT_ORDER, - DEFAULT_SIDEBAR_THREAD_SORT_ORDER, -} from "@t3tools/contracts"; -import { Stack } from "expo-router"; -import { Text as RNText, View } from "react-native"; +import type { MenuAction } from "@react-native-menu/menu"; +import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader"; +import { useCallback, useMemo, useRef } from "react"; +import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native"; +import type { SearchBarCommands } from "react-native-screens"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { ControlPillMenu } from "../../components/ControlPill"; +import { SymbolView } from "../../components/AppSymbol"; +import { T3Wordmark } from "../../components/T3Wordmark"; import { useThemeColor } from "../../lib/useThemeColor"; -import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; +import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands"; +import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items"; +import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar"; import type { HomeProjectSortOrder } from "./homeThreadList"; +import { + buildHomeListFilterMenu, + type HomeListFilterMenuEnvironment, +} from "./home-list-filter-menu"; +import { + hasCustomHomeListOptions, + PROJECT_GROUPING_OPTIONS, + PROJECT_SORT_OPTIONS, + THREAD_SORT_OPTIONS, +} from "./home-list-options"; -export interface HomeHeaderEnvironment { - readonly environmentId: EnvironmentId; - readonly label: string; -} - -const PROJECT_SORT_OPTIONS: ReadonlyArray<{ - readonly value: HomeProjectSortOrder; - readonly label: string; -}> = [ - { value: "updated_at", label: "Last user message" }, - { value: "created_at", label: "Created at" }, -]; - -const THREAD_SORT_OPTIONS: ReadonlyArray<{ - readonly value: SidebarThreadSortOrder; - readonly label: string; -}> = [ - { value: "updated_at", label: "Last user message" }, - { value: "created_at", label: "Created at" }, -]; - -const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{ - readonly value: SidebarProjectGroupingMode; - readonly label: string; - readonly subtitle: string; -}> = [ - { - value: "repository", - label: "Group by repository", - subtitle: "Combine matching repositories across environments", - }, - { - value: "repository_path", - label: "Group by repository path", - subtitle: "Combine only matching paths within a repository", - }, - { - value: "separate", - label: "Keep separate", - subtitle: "Show every project path separately", - }, -]; +export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment; export function HomeHeader(props: { readonly environments: ReadonlyArray; + readonly searchQuery: string; readonly selectedEnvironmentId: EnvironmentId | null; readonly projectSortOrder: HomeProjectSortOrder; readonly threadSortOrder: SidebarThreadSortOrder; @@ -72,174 +46,377 @@ export function HomeHeader(props: { readonly onOpenSettings: () => void; readonly onStartNewTask: () => void; }) { + if (Platform.OS === "android") { + return ; + } + + return ; +} + +type HomeHeaderProps = Parameters[0]; + +function checkedMenuState(checked: boolean) { + return checked ? ("on" as const) : undefined; +} + +function AndroidHomeHeader(props: HomeHeaderProps) { + const insets = useSafeAreaInsets(); const iconColor = useThemeColor("--color-icon"); const mutedColor = useThemeColor("--color-foreground-muted"); - const subtleColor = useThemeColor("--color-subtle"); - const hasCustomListOptions = - props.selectedEnvironmentId !== null || - props.projectSortOrder !== DEFAULT_SIDEBAR_PROJECT_SORT_ORDER || - props.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER || - props.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE; + const hasCustomListOptions = hasCustomHomeListOptions(props); + const menuActions = useMemo( + () => [ + { + id: "environment", + title: "Environment", + subactions: [ + { + id: "environment:all", + title: "All environments", + state: checkedMenuState(props.selectedEnvironmentId === null), + }, + ...props.environments.map((environment) => ({ + id: `environment:${environment.environmentId}`, + title: environment.label, + state: checkedMenuState(props.selectedEnvironmentId === environment.environmentId), + })), + ], + }, + { + id: "project-sort", + title: "Sort projects", + subactions: PROJECT_SORT_OPTIONS.map((option) => ({ + id: `project-sort:${option.value}`, + title: option.label, + state: checkedMenuState(props.projectSortOrder === option.value), + })), + }, + { + id: "thread-sort", + title: "Sort threads", + subactions: THREAD_SORT_OPTIONS.map((option) => ({ + id: `thread-sort:${option.value}`, + title: option.label, + state: checkedMenuState(props.threadSortOrder === option.value), + })), + }, + { + id: "project-grouping", + title: "Group projects", + subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({ + id: `project-grouping:${option.value}`, + title: option.label, + state: checkedMenuState(props.projectGroupingMode === option.value), + })), + }, + ], + [ + props.environments, + props.projectGroupingMode, + props.projectSortOrder, + props.selectedEnvironmentId, + props.threadSortOrder, + ], + ); + const handleMenuAction = useCallback( + (event: { nativeEvent: { event: string } }) => { + const id = event.nativeEvent.event; + if (id === "environment:all") { + props.onEnvironmentChange(null); + return; + } + + if (id.startsWith("environment:")) { + const environmentId = id.slice("environment:".length); + const environment = props.environments.find( + (candidate) => candidate.environmentId === environmentId, + ); + if (environment) { + props.onEnvironmentChange(environment.environmentId); + } + return; + } + + const projectSort = PROJECT_SORT_OPTIONS.find( + (option) => id === `project-sort:${option.value}`, + ); + if (projectSort) { + props.onProjectSortOrderChange(projectSort.value); + return; + } + + const threadSort = THREAD_SORT_OPTIONS.find((option) => id === `thread-sort:${option.value}`); + if (threadSort) { + props.onThreadSortOrderChange(threadSort.value); + return; + } + + const grouping = PROJECT_GROUPING_OPTIONS.find( + (option) => id === `project-grouping:${option.value}`, + ); + if (grouping) { + props.onProjectGroupingModeChange(grouping.value); + } + }, + [props], + ); return ( <> - { - props.onSearchQueryChange(event.nativeEvent.text); - }, - onCancelButtonPress: () => { - props.onSearchQueryChange(""); - }, - allowToolbarIntegration: true, - }, + + - - - - - - T3 Code - - - - Alpha + > + + + + {/* Mirrors the desktop SidebarBrand: T3 mark + muted "Code". */} + + + Code + + + Alpha + + - - - - - - - Environment - props.onEnvironmentChange(null)} - subtitle="Show threads from every environment" + - All environments - - {props.environments.map((environment) => ( - props.onEnvironmentChange(environment.environmentId)} + - {environment.label} - - ))} - + + + + {/* Built identically to the filter button so the two circles + match exactly (ControlPill sizes via Tailwind classes and + resolves to a different box). */} + + + + - - Sort projects - {PROJECT_SORT_OPTIONS.map((option) => ( - props.onProjectSortOrderChange(option.value)} + + + + {props.searchQuery.length > 0 ? ( + props.onSearchQueryChange("")} > - {option.label} - - ))} - - - - Sort threads - {THREAD_SORT_OPTIONS.map((option) => ( - props.onThreadSortOrderChange(option.value)} - > - {option.label} - - ))} - - - - Group projects - {PROJECT_GROUPING_OPTIONS.map((option) => ( - props.onProjectGroupingModeChange(option.value)} - subtitle={option.subtitle} - > - {option.label} - - ))} - - - - - - - - - - - + + + ) : null} + + + + + ); +} + +function IosHomeHeader(props: HomeHeaderProps) { + const searchBarRef = useRef(null); + const iconColor = useThemeColor("--color-icon"); + const hasCustomListOptions = hasCustomHomeListOptions(props); + const focusSearch = useCallback(() => { + searchBarRef.current?.focus(); + return searchBarRef.current !== null; + }, []); + useHardwareKeyboardCommand("focusSearch", focusSearch); + const filterMenu = buildHomeListFilterMenu(props); + + return ( + <> + [ + withNativeGlassHeaderItem({ + accessibilityLabel: "Open settings", + icon: { name: "ellipsis", type: "sfSymbol" } as const, + identifier: "home-settings", + label: "", + onPress: props.onOpenSettings, + type: "button", + }), + ] + : undefined, + unstable_headerToolbarItems: + Platform.OS === "ios" + ? () => [ + createNativeMailSearchToolbarItem({ + composeButtonId: "home-new-task", + composeSystemImageName: "square.and.pencil", + filterMenu, + filterButtonId: "home-filter", + filterSystemImageName: hasCustomListOptions + ? "line.3.horizontal.decrease.circle.fill" + : "line.3.horizontal.decrease", + onComposePress: props.onStartNewTask, + onSearchTextChange: props.onSearchQueryChange, + placeholder: "Search", + searchTextChangeId: "home-search-text", + }), + ] + : undefined, + headerSearchBarOptions: + Platform.OS === "ios" + ? undefined + : { + ref: searchBarRef, + allowToolbarIntegration: true, + hideNavigationBar: false, + placeholder: "Search", + onCancelButtonPress: () => { + props.onSearchQueryChange(""); + }, + onChangeText: (event) => { + props.onSearchQueryChange(event.nativeEvent.text); + }, + }, + }} + /> + + {Platform.OS === "ios" ? null : ( + + + + )} + + {Platform.OS === "ios" ? null : ( + + + + Settings + + + + Environment + props.onEnvironmentChange(null)} + subtitle="Show threads from every environment" + > + All environments + + {props.environments.map((environment) => ( + props.onEnvironmentChange(environment.environmentId)} + > + {environment.label} + + ))} + + + + Sort projects + {PROJECT_SORT_OPTIONS.map((option) => ( + props.onProjectSortOrderChange(option.value)} + > + {option.label} + + ))} + + + + Sort threads + {THREAD_SORT_OPTIONS.map((option) => ( + props.onThreadSortOrderChange(option.value)} + > + {option.label} + + ))} + + + + Group projects + {PROJECT_GROUPING_OPTIONS.map((option) => ( + props.onProjectGroupingModeChange(option.value)} + subtitle={option.subtitle} + > + {option.label} + + ))} + + + + + + + + )} ); } diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx new file mode 100644 index 0000000000..49cf06d85e --- /dev/null +++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx @@ -0,0 +1,155 @@ +import * as Arr from "effect/Array"; +import * as Order from "effect/Order"; +import { useNavigation } from "@react-navigation/native"; +import { useMemo, useState } from "react"; + +import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader"; +import { useProjects, useThreadShells } from "../../state/entities"; +import { usePendingNewTasks } from "../../state/use-pending-new-tasks"; +import { useWorkspaceState } from "../../state/workspace"; +import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; +import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; +import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail"; +import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar"; +import { AndroidHomeFabLayout } from "./AndroidHomeFab"; +import { HomeScreen } from "./HomeScreen"; +import { HomeHeader } from "./HomeHeader"; +import { useHomeListOptions } from "./home-list-options"; +import { usePendingTaskListActions } from "./usePendingTaskListActions"; +import { useThreadListActions } from "./useThreadListActions"; + +/* ─── Route screen ───────────────────────────────────────────────────── */ + +export function HomeRouteScreen() { + const { layout } = useAdaptiveWorkspaceLayout(); + const projects = useProjects(); + const threads = useThreadShells(); + const { state: catalogState } = useWorkspaceState(); + const { savedConnectionsById } = useSavedRemoteConnections(); + const navigation = useNavigation(); + const [searchQuery, setSearchQuery] = useState(""); + const { archiveThread, confirmDeleteThread } = useThreadListActions(); + const pendingTasks = usePendingNewTasks(); + const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions(); + const environments = useMemo( + () => + Arr.sort( + Object.values(savedConnectionsById).map((connection) => ({ + environmentId: connection.environmentId, + label: connection.environmentLabel, + })), + Order.mapInput( + Order.String, + (environment: { readonly label: string }) => environment.label, + ), + ), + [savedConnectionsById], + ); + const availableEnvironmentIds = useMemo( + () => new Set(environments.map((environment) => environment.environmentId)), + [environments], + ); + const { + options: listOptions, + setSelectedEnvironmentId, + setProjectGroupingMode, + setProjectSortOrder, + setThreadSortOrder, + } = useHomeListOptions(availableEnvironmentIds); + const selectedEnvironmentId = listOptions.selectedEnvironmentId; + + // In split layouts the persistent sidebar IS the thread list — Home becomes + // an empty detail pane so selecting a thread never transitions layouts. + if (layout.usesSplitView) { + return ( + <> + + navigation.navigate("NewTaskSheet", { screen: "NewTask" })} + /> + } + /> + navigation.navigate("NewTaskSheet", { screen: "NewTask" })} + /> + + ); + } + + return ( + navigation.navigate("NewTaskSheet", { screen: "NewTask" })} + > + <> + {/* Restore the compact title in case the split branch blanked it. */} + + navigation.navigate("SettingsSheet", { screen: "Settings" })} + onProjectGroupingModeChange={setProjectGroupingMode} + onProjectSortOrderChange={setProjectSortOrder} + onSearchQueryChange={setSearchQuery} + onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })} + onThreadSortOrderChange={setThreadSortOrder} + /> + + + navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" }) + } + onArchiveThread={archiveThread} + onDeleteThread={confirmDeleteThread} + onEnvironmentChange={setSelectedEnvironmentId} + onOpenEnvironments={() => + navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }) + } + onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })} + onProjectGroupingModeChange={setProjectGroupingMode} + onProjectSortOrderChange={setProjectSortOrder} + onSearchQueryChange={setSearchQuery} + onSelectThread={(thread) => { + navigation.navigate("Thread", { + environmentId: thread.environmentId, + threadId: thread.id, + }); + }} + onSelectPendingTask={openPendingTask} + onDeletePendingTask={confirmDeletePendingTask} + onNewThreadInProject={(project) => { + navigation.navigate("NewTaskSheet", { + screen: "NewTaskDraft", + params: { + environmentId: String(project.environmentId), + projectId: String(project.id), + title: project.title, + }, + }); + }} + onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })} + onThreadSortOrderChange={setThreadSortOrder} + pendingTasks={pendingTasks} + projectGroupingMode={listOptions.projectGroupingMode} + projects={projects} + projectSortOrder={listOptions.projectSortOrder} + savedConnectionsById={savedConnectionsById} + searchQuery={searchQuery} + selectedEnvironmentId={selectedEnvironmentId} + threads={threads} + threadSortOrder={listOptions.threadSortOrder} + /> + + + ); +} diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index f1e120a38c..6360cdb6ed 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -1,3 +1,8 @@ +import { + LegendList, + type LegendListRef, + type LegendListRenderItemProps, +} from "@legendapp/list/react-native"; import { type EnvironmentProject, type EnvironmentThreadShell, @@ -7,103 +12,82 @@ import type { SidebarProjectGroupingMode, SidebarThreadSortOrder, } from "@t3tools/contracts"; -import * as Haptics from "expo-haptics"; -import { SymbolView } from "expo-symbols"; +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { AsyncResult } from "effect/unstable/reactivity"; import { useCallback, useMemo, useRef, useState } from "react"; -import { ActivityIndicator, Pressable, ScrollView, useWindowDimensions, View } from "react-native"; -import ReanimatedSwipeable, { - type SwipeableMethods, -} from "react-native-gesture-handler/ReanimatedSwipeable"; -import Animated, { - Easing, - LinearTransition, - type ExitAnimationsValues, - withDelay, - withTiming, -} from "react-native-reanimated"; +import { ActivityIndicator, Platform, View } from "react-native"; +import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useThemeColor } from "../../lib/useThemeColor"; -import { AppText as Text } from "../../components/AppText"; import { EmptyState } from "../../components/EmptyState"; -import { ProjectFavicon } from "../../components/ProjectFavicon"; import type { WorkspaceState } from "../../state/workspaceModel"; import type { SavedRemoteConnection } from "../../lib/connection"; -import { relativeTime } from "../../lib/time"; -import { threadStatusTone } from "../threads/threadPresentation"; -import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList"; +import { scopedProjectKey } from "../../lib/scopedEntities"; +import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import type { PendingNewTask } from "../../state/use-pending-new-tasks"; import { - THREAD_SWIPE_ACTIONS_WIDTH, - THREAD_SWIPE_SPRING, - ThreadSwipeActions, -} from "./thread-swipe-actions"; + PendingTaskListRow, + ThreadListGroupHeader, + ThreadListRow, + ThreadListShowMoreRow, +} from "../threads/thread-list-items"; +import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu"; +import { + buildHomeListLayout, + DEFAULT_GROUP_DISPLAY_STATE, + homeListItemsAreEqual, + nextGroupDisplayState, + type HomeGroupDisplayAction, + type HomeGroupDisplayState, + type HomeListItem, +} from "./homeListItems"; +import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList"; +import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions"; +import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus"; +import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status"; /* ─── Types ──────────────────────────────────────────────────────────── */ interface HomeScreenProps { readonly projects: ReadonlyArray; readonly threads: ReadonlyArray; + readonly pendingTasks: ReadonlyArray; readonly catalogState: WorkspaceState; readonly savedConnectionsById: Readonly>; + readonly environments: ReadonlyArray; readonly searchQuery: string; readonly selectedEnvironmentId: EnvironmentId | null; readonly projectSortOrder: HomeProjectSortOrder; readonly threadSortOrder: SidebarThreadSortOrder; readonly projectGroupingMode: SidebarProjectGroupingMode; + readonly onSearchQueryChange: (query: string) => void; + readonly onEnvironmentChange: (environmentId: EnvironmentId | 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; + readonly onStartNewTask: () => void; readonly onSelectThread: (thread: EnvironmentThreadShell) => void; readonly onArchiveThread: (thread: EnvironmentThreadShell) => void; readonly onDeleteThread: (thread: EnvironmentThreadShell) => void; + readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void; + readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void; + readonly onNewThreadInProject: (project: EnvironmentProject) => void; } -/* ─── Status indicator colors ────────────────────────────────────────── */ +/* ─── Layout constants ───────────────────────────────────────────────── */ -function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } { - switch (thread.runtime?.status) { - case "running": - case "waiting": - return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" }; - case "completed": - return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" }; - case "queued": - case "starting": - return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" }; - case "failed": - return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" }; - default: - return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" }; - } -} - -const COLLAPSED_THREAD_LIMIT = 6; -const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic)); - -function threadRowExit(values: ExitAnimationsValues) { - "worklet"; - - return { - initialValues: { - height: values.currentHeight, - opacity: 1, - originX: values.currentOriginX, - }, - animations: { - height: withDelay( - 90, - withTiming(0, { - duration: 170, - easing: Easing.inOut(Easing.cubic), - }), - ), - opacity: withDelay(80, withTiming(0, { duration: 100 })), - originX: withTiming(values.currentOriginX - values.windowWidth, { - duration: 190, - easing: Easing.out(Easing.cubic), - }), - }, - }; -} +const ESTIMATED_THREAD_ROW_HEIGHT = 72; +/** + * Top spacing between the list and the Android custom header. The Android + * header (AndroidHomeHeader) is rendered in-flow above this screen and + * already consumes the top safe-area inset, so the list only needs breathing + * room here. + */ function deriveEmptyState(props: { readonly catalogState: WorkspaceState; @@ -168,290 +152,57 @@ function deriveEmptyState(props: { }; } -/* ─── Project group header ───────────────────────────────────────────── */ - -function ProjectGroupLabel(props: { - readonly project: EnvironmentProject; - readonly title: string; - readonly totalThreadCount: number; - readonly isExpanded: boolean; - readonly onToggleExpand: () => void; -}) { - const hiddenCount = props.totalThreadCount - COLLAPSED_THREAD_LIMIT; - - return ( - - - - {props.title} - - - {hiddenCount > 0 ? ( - - - {props.isExpanded ? "Show less" : `${hiddenCount} more`} - - - ) : null} - - ); -} - -/* ─── Thread row ─────────────────────────────────────────────────────── */ - -function ThreadRow(props: { - readonly thread: EnvironmentThreadShell; - readonly environmentLabel: string | null; - readonly onPress: () => void; - readonly onArchive: () => void; - readonly onDelete: () => void; - readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void; - readonly onSwipeableClose: (methods: SwipeableMethods) => void; - readonly isLast: boolean; -}) { - const swipeableRef = useRef(null); - const fullSwipeArmedRef = useRef(false); - const { width: windowWidth } = useWindowDimensions(); - const separatorColor = useThemeColor("--color-separator"); - const iconSubtleColor = useThemeColor("--color-icon-subtle"); - const cardColor = useThemeColor("--color-card"); - const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58); - const { bg, fg } = statusColors(props.thread); - const tone = threadStatusTone(props.thread); - const timestamp = relativeTime( - props.thread.latestUserMessageAt ?? props.thread.updatedAt ?? props.thread.createdAt, - ); - const branch = props.thread.branch; - const subtitleParts = [props.environmentLabel, branch].filter((part): part is string => - Boolean(part), - ); - const handleFullSwipeArmedChange = useCallback((armed: boolean) => { - if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") { - void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium); - } - fullSwipeArmedRef.current = armed; - }, []); - - return ( - { - fullSwipeArmedRef.current = false; - if (swipeableRef.current) { - props.onSwipeableClose(swipeableRef.current); - } - }} - onSwipeableOpenStartDrag={() => { - if (swipeableRef.current) { - props.onSwipeableWillOpen(swipeableRef.current); - } - }} - onSwipeableWillOpen={() => { - const methods = swipeableRef.current; - if (!methods) { - return; - } - - props.onSwipeableWillOpen(methods); - if (fullSwipeArmedRef.current) { - fullSwipeArmedRef.current = false; - methods.close(); - props.onDelete(); - } - }} - overshootFriction={1} - overshootRight - renderRightActions={(_progress, translation, methods) => ( - - )} - rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42} - > - { - swipeableRef.current?.close(); - props.onPress(); - }} - style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })} - > - - - - - - - - - {props.thread.title} - - - - - {tone.label} - - - - {timestamp} - - - - - {subtitleParts.length > 0 ? ( - - - - {subtitleParts.join(" · ")} - - - ) : null} - - - - - ); +function HomeTopContentSpacer() { + return ; } /* ─── Main screen ────────────────────────────────────────────────────── */ -function staleCatalogPillLabel(props: { readonly catalogState: WorkspaceState }): string { - if (props.catalogState.networkStatus === "offline") { - return "You are offline"; - } - const connectingEnvironments = props.catalogState.connectingEnvironments; - if (connectingEnvironments.length === 1) { - return `Reconnecting to ${connectingEnvironments[0]!.environmentLabel}`; - } - if (connectingEnvironments.length > 1) { - return `Reconnecting ${connectingEnvironments.length} environments`; - } - return "Not connected"; -} - -function StaleCatalogStatusPill(props: { - readonly catalogState: WorkspaceState; - readonly onPress: () => void; -}) { - const iconColor = useThemeColor("--color-icon-muted"); - const label = staleCatalogPillLabel(props); - const isReconnecting = props.catalogState.connectingEnvironments.length > 0; - - return ( - - {isReconnecting ? ( - - ) : ( - - )} - - {label} - - - ); -} - export function HomeScreen(props: HomeScreenProps) { - const [expandedProjects, setExpandedProjects] = useState>(() => new Set()); + const [groupDisplayStates, setGroupDisplayStates] = useState< + ReadonlyMap + >(() => new Map()); + const preferencesResult = useAtomValue(mobilePreferencesAtom); + const savePreferences = useAtomSet(updateMobilePreferencesAtom); const openSwipeableRef = useRef(null); + const listRef = useRef(null); const insets = useSafeAreaInsets(); const accentColor = useThemeColor("--color-icon-muted"); - - const toggleExpanded = useCallback((key: string) => { - setExpandedProjects((prev) => { - const next = new Set(prev); - if (next.has(key)) next.delete(key); - else next.add(key); + const effectiveGroupDisplayStates = useMemo(() => { + const next = new Map(groupDisplayStates); + if (!AsyncResult.isSuccess(preferencesResult)) { return next; - }); - }, []); + } + for (const key of preferencesResult.value.collapsedProjectGroups ?? []) { + const existing = next.get(key); + next.set(key, { + ...(existing ?? DEFAULT_GROUP_DISPLAY_STATE), + collapsed: true, + }); + } + return next; + }, [groupDisplayStates, preferencesResult]); + const effectiveGroupDisplayStatesRef = useRef(effectiveGroupDisplayStates); + effectiveGroupDisplayStatesRef.current = effectiveGroupDisplayStates; + + const updateGroupDisplay = useCallback( + (key: string, action: HomeGroupDisplayAction) => { + const next = new Map(effectiveGroupDisplayStatesRef.current); + next.set(key, nextGroupDisplayState(next.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action)); + effectiveGroupDisplayStatesRef.current = next; + setGroupDisplayStates(next); + if (action === "toggle-collapsed") { + const collapsedProjectGroups: string[] = []; + for (const [groupKey, state] of next) { + if (state.collapsed) { + collapsedProjectGroups.push(groupKey); + } + } + savePreferences({ collapsedProjectGroups }); + } + }, + [savePreferences], + ); const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => { if (openSwipeableRef.current !== methods) { @@ -466,11 +217,19 @@ export function HomeScreen(props: HomeScreenProps) { } }, []); + const handleScrollBeginDrag = useCallback(() => { + openSwipeableRef.current?.close(); + }, []); + const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({ + onScrollBeginDrag: handleScrollBeginDrag, + }); + const projectGroups = useMemo( () => buildHomeThreadGroups({ projects: props.projects, threads: props.threads, + pendingTasks: props.pendingTasks, environmentId: props.selectedEnvironmentId, searchQuery: props.searchQuery, projectSortOrder: props.projectSortOrder, @@ -478,6 +237,7 @@ export function HomeScreen(props: HomeScreenProps) { projectGroupingMode: props.projectGroupingMode, }), [ + props.pendingTasks, props.projectGroupingMode, props.projects, props.projectSortOrder, @@ -488,135 +248,255 @@ export function HomeScreen(props: HomeScreenProps) { ], ); + const hasSearchQuery = props.searchQuery.trim().length > 0; + const listLayout = useMemo( + () => + buildHomeListLayout({ + groups: projectGroups, + displayStates: effectiveGroupDisplayStates, + showAllThreads: hasSearchQuery, + }), + [projectGroups, effectiveGroupDisplayStates, hasSearchQuery], + ); + + const projectCwdByKey = useMemo(() => { + const map = new Map(); + for (const project of props.projects) { + map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot); + } + return map; + }, [props.projects]); + + const extraData = useMemo( + () => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }), + [props.savedConnectionsById, projectCwdByKey], + ); + + const renderItem = useCallback( + ({ item }: LegendListRenderItemProps) => { + switch (item.type) { + case "header": + return ( + + ); + case "pending-task": + return ( + + ); + case "thread": { + const thread = item.thread; + return ( + + ); + } + case "show-more": + return ( + + ); + } + }, + [ + handleSwipeableClose, + handleSwipeableWillOpen, + projectCwdByKey, + props.onArchiveThread, + props.onDeletePendingTask, + props.onDeleteThread, + props.onNewThreadInProject, + props.onSelectPendingTask, + props.onSelectThread, + props.savedConnectionsById, + updateGroupDisplay, + ], + ); + + const keyExtractor = useCallback((item: HomeListItem) => item.key, []); + /* Empty states */ - const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null); + const hasAnyThreads = + props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0; const hasResults = projectGroups.length > 0; const selectedEnvironmentLabel = props.selectedEnvironmentId === null ? null : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ?? "this environment"); - const hasSearchQuery = props.searchQuery.trim().length > 0; - const shouldShowConnectionStatus = - props.catalogState.networkStatus === "offline" || - props.catalogState.hasConnectingEnvironment || - (props.catalogState.hasLoadedShellSnapshot && !props.catalogState.hasReadyEnvironment); + const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState); const emptyState = deriveEmptyState({ catalogState: props.catalogState, projectCount: props.projects.length, }); + const connectionStatus = + shouldShowConnectionStatus && Platform.OS !== "ios" ? ( + + + + ) : null; - return ( - - openSwipeableRef.current?.close()} - className="flex-1" - contentContainerStyle={{ - paddingHorizontal: 16, - paddingTop: 8, - paddingBottom: 24, - gap: 20, + if (!hasAnyThreads) { + return ( + - {!hasAnyThreads ? ( - - - {emptyState.loading ? ( - - - - ) : null} - - ) : !hasResults && hasSearchQuery ? ( - - ) : !hasResults && selectedEnvironmentLabel ? ( + - ) : !hasResults ? ( - - ) : ( - projectGroups.map((group) => { - const isExpanded = expandedProjects.has(group.key); - const visibleThreads = isExpanded - ? group.threads - : group.threads.slice(0, COLLAPSED_THREAD_LIMIT); + {emptyState.loading && !shouldShowConnectionStatus ? ( + + + + ) : null} + {shouldShowConnectionStatus && Platform.OS === "ios" ? ( + + + + ) : null} + + {connectionStatus} + + ); + } - return ( - - toggleExpanded(group.key)} - project={group.representative} - title={group.title} - totalThreadCount={group.threads.length} - /> - - {visibleThreads.map((thread, i) => { - const threadKey = `${thread.environmentId}:${thread.id}`; - return ( - - props.onArchiveThread(thread)} - onDelete={() => props.onDeleteThread(thread)} - onPress={() => props.onSelectThread(thread)} - onSwipeableClose={handleSwipeableClose} - onSwipeableWillOpen={handleSwipeableWillOpen} - /> - - ); - })} - - - ); - }) - )} - - {shouldShowConnectionStatus ? ( - - + {Platform.OS === "ios" ? null : } + + {shouldShowConnectionStatus && Platform.OS === "ios" ? ( + + ) : null} + + ); + + const listEmpty = !hasResults ? ( + hasSearchQuery ? ( + + ) : selectedEnvironmentLabel ? ( + + ) : ( + + ) + ) : null; + + return ( + + {/* Sticky headers are deliberately not wired up: LegendList's JS sticky + implementation mispositions pinned headers at mount under iOS + automatic content insets (headers render one nav-inset too low until + the first scroll event) and blanks non-pinned headers after + collapse/expand data changes. The flattened layout still exposes + `stickyHeaderIndices` if this gets revisited. */} + + + + {connectionStatus} ); } diff --git a/apps/mobile/src/features/home/WorkspaceConnectionStatus.test.ts b/apps/mobile/src/features/home/WorkspaceConnectionStatus.test.ts new file mode 100644 index 0000000000..8c3c873cc9 --- /dev/null +++ b/apps/mobile/src/features/home/WorkspaceConnectionStatus.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from "vite-plus/test"; + +import type { WorkspaceState } from "../../state/workspaceModel"; +import { + shouldShowWorkspaceConnectionStatus, + workspaceConnectionStatusLabel, +} from "./workspace-connection-status"; + +function workspaceState(overrides: Partial = {}): WorkspaceState { + return { + isLoadingConnections: false, + hasConnections: true, + hasLoadedShellSnapshot: true, + hasPendingShellSnapshot: false, + hasReadyEnvironment: true, + hasConnectingEnvironment: false, + connectingEnvironments: [], + connectionState: "connected", + connectionError: null, + shellSnapshotError: null, + latestCachedSnapshotReceivedAt: null, + networkStatus: "online", + ...overrides, + }; +} + +describe("workspace connection status", () => { + it("stays hidden while a ready environment is connected", () => { + expect(shouldShowWorkspaceConnectionStatus(workspaceState())).toBe(false); + }); + + it("surfaces offline snapshots", () => { + const state = workspaceState({ networkStatus: "offline", hasReadyEnvironment: false }); + + expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true); + expect(workspaceConnectionStatusLabel(state)).toBe("You are offline"); + }); + + it("names the environment while reconnecting", () => { + const state = workspaceState({ + hasConnectingEnvironment: true, + hasReadyEnvironment: false, + connectingEnvironments: [ + { + environmentId: "environment-1" as never, + environmentLabel: "Julius’s Mac mini", + displayUrl: "", + isRelayManaged: false, + connectionState: "reconnecting", + connectionError: null, + connectionErrorTraceId: null, + }, + ], + }); + + expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true); + expect(workspaceConnectionStatusLabel(state)).toBe("Reconnecting to Julius’s Mac mini"); + }); + + it("surfaces connection errors before the generic disconnected fallback", () => { + const state = workspaceState({ + connectionError: "Could not reach Julius’s Mac mini", + hasLoadedShellSnapshot: false, + hasReadyEnvironment: false, + }); + + 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..."); + }); +}); diff --git a/apps/mobile/src/features/home/WorkspaceConnectionStatus.tsx b/apps/mobile/src/features/home/WorkspaceConnectionStatus.tsx new file mode 100644 index 0000000000..1e986ad1a5 --- /dev/null +++ b/apps/mobile/src/features/home/WorkspaceConnectionStatus.tsx @@ -0,0 +1,56 @@ +import { SymbolView } from "../../components/AppSymbol"; +import { ActivityIndicator, Pressable } from "react-native"; + +import { AppText as Text } from "../../components/AppText"; +import { useThemeColor } from "../../lib/useThemeColor"; +import type { WorkspaceState } from "../../state/workspaceModel"; +import { workspaceConnectionStatusLabel } from "./workspace-connection-status"; + +export function WorkspaceConnectionStatus(props: { + readonly state: WorkspaceState; + readonly onPress: () => void; + readonly variant?: "floating" | "sidebar"; +}) { + const iconColor = useThemeColor("--color-icon-muted"); + const isSynchronizing = + props.state.networkStatus !== "offline" && + props.state.connectionError === null && + (props.state.connectingEnvironments.length > 0 || props.state.hasPendingShellSnapshot); + const variant = props.variant ?? "floating"; + + return ( + + {isSynchronizing ? ( + + ) : ( + + )} + + {workspaceConnectionStatusLabel(props.state)} + + {variant === "sidebar" ? ( + + ) : null} + + ); +} diff --git a/apps/mobile/src/features/home/home-list-filter-menu.ts b/apps/mobile/src/features/home/home-list-filter-menu.ts new file mode 100644 index 0000000000..46ea639677 --- /dev/null +++ b/apps/mobile/src/features/home/home-list-filter-menu.ts @@ -0,0 +1,120 @@ +import type { + EnvironmentId, + SidebarProjectGroupingMode, + SidebarThreadSortOrder, +} from "@t3tools/contracts"; + +import type { HomeProjectSortOrder } from "./homeThreadList"; +import { + PROJECT_GROUPING_OPTIONS, + PROJECT_SORT_OPTIONS, + THREAD_SORT_OPTIONS, +} from "./home-list-options"; + +export interface HomeListFilterMenuEnvironment { + readonly environmentId: EnvironmentId; + readonly label: string; +} + +type HomeListFilterMenuAction = { + readonly type: "action"; + readonly title: string; + readonly subtitle?: string; + readonly state?: "on" | "off"; + readonly onPress: () => void; +}; + +type HomeListFilterMenuSubmenu = { + readonly type: "submenu"; + readonly title: string; + readonly items: HomeListFilterMenuAction[]; +}; + +export interface HomeListFilterMenu { + readonly title: string; + readonly items: Array; +} + +export function buildHomeListFilterMenu(props: { + readonly environments: ReadonlyArray; + readonly selectedEnvironmentId: EnvironmentId | null; + readonly projectSortOrder: HomeProjectSortOrder; + readonly threadSortOrder: SidebarThreadSortOrder; + readonly projectGroupingMode: SidebarProjectGroupingMode; + readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void; + readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void; + readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void; + readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void; + readonly onOpenSettings?: () => void; +}): HomeListFilterMenu { + const items: Array = []; + + if (props.onOpenSettings) { + items.push({ + type: "action", + title: "Settings", + onPress: props.onOpenSettings, + }); + } + + items.push( + { + type: "submenu", + title: "Environment", + items: [ + { + type: "action", + title: "All environments", + subtitle: "Show threads from every environment", + state: props.selectedEnvironmentId === null ? "on" : "off", + onPress: () => props.onEnvironmentChange(null), + }, + ...props.environments.map((environment) => ({ + type: "action" as const, + title: environment.label, + state: + props.selectedEnvironmentId === environment.environmentId + ? ("on" as const) + : ("off" as const), + onPress: () => props.onEnvironmentChange(environment.environmentId), + })), + ], + }, + { + type: "submenu", + title: "Sort projects", + items: PROJECT_SORT_OPTIONS.map((option) => ({ + type: "action", + title: option.label, + state: props.projectSortOrder === option.value ? "on" : "off", + onPress: () => props.onProjectSortOrderChange(option.value), + })), + }, + { + type: "submenu", + title: "Sort threads", + items: THREAD_SORT_OPTIONS.map((option) => ({ + type: "action", + title: option.label, + state: props.threadSortOrder === option.value ? "on" : "off", + onPress: () => props.onThreadSortOrderChange(option.value), + })), + }, + { + type: "submenu", + title: "Group projects", + items: PROJECT_GROUPING_OPTIONS.map((option) => ({ + type: "action", + title: option.label, + subtitle: option.subtitle, + state: props.projectGroupingMode === option.value ? "on" : "off", + onPress: () => props.onProjectGroupingModeChange(option.value), + })), + }, + ); + + return { + title: "Thread list options", + items, + }; +} diff --git a/apps/mobile/src/features/home/home-list-options.test.ts b/apps/mobile/src/features/home/home-list-options.test.ts new file mode 100644 index 0000000000..788be25906 --- /dev/null +++ b/apps/mobile/src/features/home/home-list-options.test.ts @@ -0,0 +1,31 @@ +import { + DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE, + DEFAULT_SIDEBAR_PROJECT_SORT_ORDER, + DEFAULT_SIDEBAR_THREAD_SORT_ORDER, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { hasCustomHomeListOptions, type HomeListOptions } from "./home-list-options"; + +const defaults: HomeListOptions = { + selectedEnvironmentId: null, + projectSortOrder: + DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual" + ? "updated_at" + : DEFAULT_SIDEBAR_PROJECT_SORT_ORDER, + threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER, + projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE, +}; + +describe("home list options", () => { + it("recognizes default options", () => { + expect(hasCustomHomeListOptions(defaults)).toBe(false); + }); + + it("marks environment filters and grouping changes as customized", () => { + expect( + hasCustomHomeListOptions({ ...defaults, selectedEnvironmentId: "environment-1" as never }), + ).toBe(true); + expect(hasCustomHomeListOptions({ ...defaults, projectGroupingMode: "separate" })).toBe(true); + }); +}); diff --git a/apps/mobile/src/features/home/home-list-options.ts b/apps/mobile/src/features/home/home-list-options.ts new file mode 100644 index 0000000000..6488103430 --- /dev/null +++ b/apps/mobile/src/features/home/home-list-options.ts @@ -0,0 +1,144 @@ +import type { + EnvironmentId, + SidebarProjectGroupingMode, + SidebarThreadSortOrder, +} from "@t3tools/contracts"; +import { + DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE, + DEFAULT_SIDEBAR_PROJECT_SORT_ORDER, + DEFAULT_SIDEBAR_THREAD_SORT_ORDER, +} from "@t3tools/contracts"; +import { + createContext, + createElement, + useCallback, + useContext, + useMemo, + useState, + type PropsWithChildren, + type Dispatch, + type SetStateAction, +} from "react"; + +import type { HomeProjectSortOrder } from "./homeThreadList"; + +export interface HomeListOptions { + readonly selectedEnvironmentId: EnvironmentId | null; + readonly projectSortOrder: HomeProjectSortOrder; + readonly threadSortOrder: SidebarThreadSortOrder; + readonly projectGroupingMode: SidebarProjectGroupingMode; +} + +export const PROJECT_SORT_OPTIONS: ReadonlyArray<{ + readonly value: HomeProjectSortOrder; + readonly label: string; +}> = [ + { value: "updated_at", label: "Last user message" }, + { value: "created_at", label: "Created at" }, +]; + +export const THREAD_SORT_OPTIONS: ReadonlyArray<{ + readonly value: SidebarThreadSortOrder; + readonly label: string; +}> = [ + { value: "updated_at", label: "Last user message" }, + { value: "created_at", label: "Created at" }, +]; + +export const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{ + readonly value: SidebarProjectGroupingMode; + readonly label: string; + readonly subtitle: string; +}> = [ + { + value: "repository", + label: "Group by repository", + subtitle: "Combine matching repositories across environments", + }, + { + value: "repository_path", + label: "Group by repository path", + subtitle: "Combine only matching paths within a repository", + }, + { + value: "separate", + label: "Keep separate", + subtitle: "Show every project path separately", + }, +]; + +function defaultHomeListOptions(): HomeListOptions { + return { + selectedEnvironmentId: null, + projectSortOrder: + DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual" + ? "updated_at" + : DEFAULT_SIDEBAR_PROJECT_SORT_ORDER, + threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER, + projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE, + }; +} + +interface HomeListOptionsContextValue { + readonly options: HomeListOptions; + readonly setOptions: Dispatch>; +} + +const HomeListOptionsContext = createContext(null); + +/** Keeps list preferences stable while the app moves between compact and split shells. */ +export function HomeListOptionsProvider({ children }: PropsWithChildren) { + const [options, setOptions] = useState(defaultHomeListOptions); + const value = useMemo(() => ({ options, setOptions }), [options]); + return createElement(HomeListOptionsContext, { value }, children); +} + +export function hasCustomHomeListOptions(options: HomeListOptions): boolean { + const defaultProjectSortOrder = + DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual" + ? "updated_at" + : DEFAULT_SIDEBAR_PROJECT_SORT_ORDER; + return ( + options.selectedEnvironmentId !== null || + options.projectSortOrder !== defaultProjectSortOrder || + options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER || + options.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE + ); +} + +export function useHomeListOptions(availableEnvironmentIds: ReadonlySet) { + const shared = useContext(HomeListOptionsContext); + const [localOptions, setLocalOptions] = useState(defaultHomeListOptions); + const options = shared?.options ?? localOptions; + const setOptions = shared?.setOptions ?? setLocalOptions; + const selectedEnvironmentId = + options.selectedEnvironmentId !== null && + availableEnvironmentIds.has(options.selectedEnvironmentId) + ? options.selectedEnvironmentId + : null; + const resolvedOptions = + selectedEnvironmentId === options.selectedEnvironmentId + ? options + : { ...options, selectedEnvironmentId }; + + const setSelectedEnvironmentId = useCallback((value: EnvironmentId | null) => { + setOptions((current) => ({ ...current, selectedEnvironmentId: value })); + }, []); + const setProjectSortOrder = useCallback((value: HomeProjectSortOrder) => { + setOptions((current) => ({ ...current, projectSortOrder: value })); + }, []); + const setThreadSortOrder = useCallback((value: SidebarThreadSortOrder) => { + setOptions((current) => ({ ...current, threadSortOrder: value })); + }, []); + const setProjectGroupingMode = useCallback((value: SidebarProjectGroupingMode) => { + setOptions((current) => ({ ...current, projectGroupingMode: value })); + }, []); + + return { + options: resolvedOptions, + setSelectedEnvironmentId, + setProjectSortOrder, + setThreadSortOrder, + setProjectGroupingMode, + } as const; +} diff --git a/apps/mobile/src/features/home/homeListItems.test.ts b/apps/mobile/src/features/home/homeListItems.test.ts new file mode 100644 index 0000000000..86b996145a --- /dev/null +++ b/apps/mobile/src/features/home/homeListItems.test.ts @@ -0,0 +1,254 @@ +import { + presentThreadShell, + type EnvironmentProject, + type EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; +import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import { + buildHomeListLayout, + DEFAULT_GROUP_DISPLAY_STATE, + HOME_INITIAL_VISIBLE_THREADS, + HOME_SHOW_MORE_STEP, + nextGroupDisplayState, + type HomeGroupDisplayState, + type HomeListItem, +} from "./homeListItems"; +import type { HomeThreadGroup } from "./homeThreadList"; + +const environmentId = EnvironmentId.make("environment-1"); + +function makeProject(id: string, title: string): EnvironmentProject { + return { + environmentId, + id: ProjectId.make(id), + title, + workspaceRoot: `/workspaces/${id}`, + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-06-01T00:00:00.000Z", + updatedAt: "2026-06-01T00:00:00.000Z", + }; +} + +const threadTimestamp = DateTime.makeUnsafe("2026-06-01T00:00:00.000Z"); + +function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell { + const threadId = ThreadId.make(id); + return presentThreadShell(environmentId, { + id: threadId, + projectId, + title: `Thread ${id}`, + providerInstanceId: ProviderInstanceId.make("codex"), + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null }, + forkedFrom: null, + createdBy: "user", + creationSource: "mobile", + latestRunId: null, + activeRunId: null, + status: "idle", + pendingRuntimeRequest: null, + latestVisibleMessage: null, + latestUserMessageAt: null, + hasActionableProposedPlan: false, + itemCount: 0, + visibleItemCount: 0, + createdAt: threadTimestamp, + updatedAt: threadTimestamp, + archivedAt: null, + deletedAt: null, + }); +} + +function makeGroup(key: string, threadCount: number): HomeThreadGroup { + const project = makeProject(key, key); + const threads = Array.from({ length: threadCount }, (_, index) => + makeThread(`${key}-thread-${index}`, project.id), + ); + return { + key, + title: key, + representative: project, + projects: [project], + pendingTasks: [], + threads, + // All threads inside the recency window, so the baseline stays at the + // initial page size and the pagination expectations below hold. + recentThreads: threads, + newThreadTarget: project, + }; +} + +function itemTypes(items: ReadonlyArray): string[] { + return items.map((item) => item.type); +} + +function displayStates( + entries: Record, +): ReadonlyMap { + return new Map(Object.entries(entries)); +} + +describe("buildHomeListLayout", () => { + it("renders a header plus all threads for a small group without a show-more row", () => { + const layout = buildHomeListLayout({ + groups: [makeGroup("alpha", 3)], + displayStates: displayStates({}), + }); + + expect(itemTypes(layout.items)).toEqual(["header", "thread", "thread", "thread"]); + expect(layout.stickyHeaderIndices).toEqual([0]); + expect(layout.items.at(-1)).toMatchObject({ type: "thread", isLast: true }); + }); + + it("limits large groups to the initial visible count with a show-more row", () => { + const layout = buildHomeListLayout({ + groups: [makeGroup("alpha", 133)], + displayStates: displayStates({}), + }); + + const threadItems = layout.items.filter((item) => item.type === "thread"); + expect(threadItems).toHaveLength(HOME_INITIAL_VISIBLE_THREADS); + expect(layout.items.at(-1)).toMatchObject({ + type: "show-more", + groupKey: "alpha", + hiddenCount: 133 - HOME_INITIAL_VISIBLE_THREADS, + canShowLess: false, + }); + // The show-more row takes over the last slot, so no thread is marked last. + expect(threadItems.every((item) => item.type === "thread" && !item.isLast)).toBe(true); + }); + + it("reveals more threads per show-more step and offers show-less when exhausted", () => { + const group = makeGroup("alpha", 20); + + const expandedOnce = buildHomeListLayout({ + groups: [group], + displayStates: displayStates({ + alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"), + }), + }); + expect(expandedOnce.items.filter((item) => item.type === "thread")).toHaveLength( + HOME_INITIAL_VISIBLE_THREADS + HOME_SHOW_MORE_STEP, + ); + expect(expandedOnce.items.at(-1)).toMatchObject({ + type: "show-more", + hiddenCount: 4, + canShowLess: true, + }); + + const fullyExpanded = buildHomeListLayout({ + groups: [group], + displayStates: displayStates({ + alpha: nextGroupDisplayState( + nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"), + "show-more", + ), + }), + }); + expect(fullyExpanded.items.filter((item) => item.type === "thread")).toHaveLength(20); + expect(fullyExpanded.items.at(-1)).toMatchObject({ + type: "show-more", + hiddenCount: 0, + canShowLess: true, + }); + + const reset = nextGroupDisplayState( + nextGroupDisplayState( + nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"), + "show-more", + ), + "show-less", + ); + expect(reset.visibleCount).toBe(HOME_INITIAL_VISIBLE_THREADS); + }); + + it("offers show-less after expanding a stale group whose baseline is below the page size", () => { + // Stale project: 10 threads total but only 3 within the recency window. + const project = makeProject("stale", "stale"); + const threads = Array.from({ length: 10 }, (_, index) => + makeThread(`stale-thread-${index}`, project.id), + ); + const group: HomeThreadGroup = { + key: "stale", + title: "stale", + representative: project, + projects: [project], + pendingTasks: [], + threads, + recentThreads: threads.slice(0, 3), + newThreadTarget: project, + }; + + const collapsedToRecent = buildHomeListLayout({ + groups: [group], + displayStates: displayStates({}), + }); + expect(collapsedToRecent.items.filter((item) => item.type === "thread")).toHaveLength(3); + expect(collapsedToRecent.items.at(-1)).toMatchObject({ + type: "show-more", + hiddenCount: 7, + canShowLess: false, + }); + + const expanded = buildHomeListLayout({ + groups: [group], + displayStates: displayStates({ + stale: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"), + }), + }); + expect(expanded.items.filter((item) => item.type === "thread")).toHaveLength(10); + expect(expanded.items.at(-1)).toMatchObject({ + type: "show-more", + hiddenCount: 0, + canShowLess: true, + }); + }); + + it("hides threads and the show-more row for collapsed groups", () => { + const layout = buildHomeListLayout({ + groups: [makeGroup("alpha", 12), makeGroup("beta", 2)], + displayStates: displayStates({ + alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "toggle-collapsed"), + }), + }); + + expect(itemTypes(layout.items)).toEqual(["header", "header", "thread", "thread"]); + expect(layout.items[0]).toMatchObject({ type: "header", collapsed: true, isFirst: true }); + expect(layout.items[1]).toMatchObject({ type: "header", collapsed: false, isFirst: false }); + expect(layout.stickyHeaderIndices).toEqual([0, 1]); + }); + + it("suspends collapse and pagination while searching", () => { + const layout = buildHomeListLayout({ + groups: [makeGroup("alpha", 12)], + displayStates: displayStates({ + alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "toggle-collapsed"), + }), + showAllThreads: true, + }); + + expect(layout.items.filter((item) => item.type === "thread")).toHaveLength(12); + expect(layout.items.some((item) => item.type === "show-more")).toBe(false); + }); + + it("keeps sticky indices aligned across multiple expanded groups", () => { + const layout = buildHomeListLayout({ + groups: [makeGroup("alpha", 8), makeGroup("beta", 1)], + displayStates: displayStates({}), + }); + + // header + 6 threads + show-more = 8 items, so beta's header is index 8. + expect(layout.stickyHeaderIndices).toEqual([0, 8]); + expect(layout.items[8]).toMatchObject({ type: "header", isFirst: false }); + }); +}); diff --git a/apps/mobile/src/features/home/homeListItems.ts b/apps/mobile/src/features/home/homeListItems.ts new file mode 100644 index 0000000000..eb3f2a5de1 --- /dev/null +++ b/apps/mobile/src/features/home/homeListItems.ts @@ -0,0 +1,207 @@ +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; + +import type { PendingNewTask } from "../../state/use-pending-new-tasks"; +import type { HomeThreadGroup } from "./homeThreadList"; + +/** Threads shown per project before the "Show more" affordance appears. */ +export const HOME_INITIAL_VISIBLE_THREADS = 6; +/** Additional threads revealed per "Show more" tap. */ +export const HOME_SHOW_MORE_STEP = 10; + +export interface HomeGroupDisplayState { + readonly collapsed: boolean; + /** How many threads are currently revealed (clamped to the group size). */ + readonly visibleCount: number; +} + +export const DEFAULT_GROUP_DISPLAY_STATE: HomeGroupDisplayState = { + collapsed: false, + visibleCount: HOME_INITIAL_VISIBLE_THREADS, +}; + +export interface HomeHeaderListItem { + readonly type: "header"; + readonly key: string; + readonly group: HomeThreadGroup; + readonly collapsed: boolean; + readonly isFirst: boolean; +} + +export interface HomeThreadListItem { + readonly type: "thread"; + readonly key: string; + readonly thread: EnvironmentThreadShell; + readonly isLast: boolean; +} + +export interface HomePendingTaskListItem { + readonly type: "pending-task"; + readonly key: string; + readonly pendingTask: PendingNewTask; + readonly isLast: boolean; +} + +export interface HomeShowMoreListItem { + readonly type: "show-more"; + readonly key: string; + readonly groupKey: string; + /** Threads still hidden. 0 means the group is fully expanded. */ + readonly hiddenCount: number; + /** Whether more than the initial count is revealed, so "Show less" applies. */ + readonly canShowLess: boolean; +} + +export type HomeListItem = + | HomeHeaderListItem + | HomePendingTaskListItem + | HomeThreadListItem + | HomeShowMoreListItem; + +export interface HomeListLayout { + readonly items: ReadonlyArray; + readonly stickyHeaderIndices: ReadonlyArray; +} + +export type HomeGroupDisplayAction = "toggle-collapsed" | "show-more" | "show-less"; + +export function nextGroupDisplayState( + current: HomeGroupDisplayState, + action: HomeGroupDisplayAction, +): HomeGroupDisplayState { + switch (action) { + case "toggle-collapsed": + return { ...current, collapsed: !current.collapsed }; + case "show-more": + return { ...current, visibleCount: current.visibleCount + HOME_SHOW_MORE_STEP }; + case "show-less": + return { ...current, visibleCount: HOME_INITIAL_VISIBLE_THREADS }; + } +} + +/** + * Structural equality for list items. Item objects are rebuilt on every + * collapse/show-more toggle; without this the lists would consider every + * mounted row changed and re-render all of them (each carrying a swipeable + + * a vcs-status subscription). Group/thread references are stable across + * toggles. + */ +export function homeListItemsAreEqual(previous: HomeListItem, item: HomeListItem): boolean { + switch (item.type) { + case "header": + return ( + previous.type === "header" && + previous.group === item.group && + previous.collapsed === item.collapsed && + previous.isFirst === item.isFirst + ); + case "pending-task": + return ( + previous.type === "pending-task" && + previous.pendingTask === item.pendingTask && + previous.isLast === item.isLast + ); + case "thread": + return ( + previous.type === "thread" && + previous.thread === item.thread && + previous.isLast === item.isLast + ); + case "show-more": + return ( + previous.type === "show-more" && + previous.groupKey === item.groupKey && + previous.hiddenCount === item.hiddenCount && + previous.canShowLess === item.canShowLess + ); + } +} + +export function buildHomeListLayout(input: { + readonly groups: ReadonlyArray; + readonly displayStates: ReadonlyMap; + /** + * When searching, pagination is suspended so every match stays visible. + */ + readonly showAllThreads?: boolean; +}): HomeListLayout { + const items: HomeListItem[] = []; + const stickyHeaderIndices: number[] = []; + + for (const [groupIndex, group] of input.groups.entries()) { + const display = input.displayStates.get(group.key) ?? DEFAULT_GROUP_DISPLAY_STATE; + const collapsed = display.collapsed && input.showAllThreads !== true; + + stickyHeaderIndices.push(items.length); + items.push({ + type: "header", + key: `header:${group.key}`, + group, + collapsed, + isFirst: groupIndex === 0, + }); + + if (collapsed) { + continue; + } + + const totalCount = group.threads.length; + // Default to the group's recent-activity window (last few days, or a small + // fallback for stale projects), capped at the initial page size. Until the + // user taps "Show more", older threads stay hidden to save vertical space; + // "Show less" resets visibleCount to the initial constant, which lands back + // here at the recency baseline. + const baselineCount = Math.min( + group.recentThreads.length, + HOME_INITIAL_VISIBLE_THREADS, + totalCount, + ); + const visibleCount = input.showAllThreads + ? totalCount + : Math.min( + display.visibleCount > HOME_INITIAL_VISIBLE_THREADS + ? display.visibleCount + : baselineCount, + totalCount, + ); + const visibleThreads = group.threads.slice(0, visibleCount); + const hiddenCount = totalCount - visibleCount; + const hasShowMoreRow = !input.showAllThreads && totalCount > baselineCount; + + // Pending (unsent) tasks lead the group and are never paginated away. + for (const [pendingIndex, pendingTask] of group.pendingTasks.entries()) { + items.push({ + type: "pending-task", + key: `pending-task:${pendingTask.message.messageId}`, + pendingTask, + isLast: + pendingIndex === group.pendingTasks.length - 1 && + visibleThreads.length === 0 && + !hasShowMoreRow, + }); + } + + for (const [threadIndex, thread] of visibleThreads.entries()) { + items.push({ + type: "thread", + key: `thread:${thread.environmentId}:${thread.id}`, + thread, + isLast: threadIndex === visibleThreads.length - 1 && !hasShowMoreRow, + }); + } + + if (hasShowMoreRow) { + items.push({ + type: "show-more", + key: `show-more:${group.key}`, + groupKey: group.key, + hiddenCount, + // Compare against the group's own baseline, not the global page size: + // stale projects start below HOME_INITIAL_VISIBLE_THREADS, and "Show + // less" must be offered as soon as anything beyond the baseline shows. + canShowLess: visibleCount > baselineCount, + }); + } + } + + return { items, stickyHeaderIndices }; +} diff --git a/apps/mobile/src/features/home/homeThreadList.test.ts b/apps/mobile/src/features/home/homeThreadList.test.ts index 50be9a68a7..88686d1577 100644 --- a/apps/mobile/src/features/home/homeThreadList.test.ts +++ b/apps/mobile/src/features/home/homeThreadList.test.ts @@ -43,6 +43,8 @@ function makeThread( }); } +const NOW = Date.parse("2026-06-29T00:00:00.000Z"); + function buildGroups( projects: ReadonlyArray, threads: ReadonlyArray, @@ -56,6 +58,7 @@ function buildGroups( projectSortOrder: "updated_at", threadSortOrder: "updated_at", projectGroupingMode: "repository", + now: NOW, ...overrides, }); } @@ -219,4 +222,144 @@ describe("buildHomeThreadGroups", () => { ); expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2); }); + + it("default view shows only threads from the last 5 days", () => { + const environmentId = EnvironmentId.make("environment-1"); + const project = makeProject({ + environmentId, + id: ProjectId.make("project-1"), + title: "T3 Code", + }); + const threads = [ + makeThread({ + environmentId, + id: ThreadId.make("recent-1"), + projectId: project.id, + title: "Today", + updatedAt: "2026-06-28T00:00:00.000Z", + }), + makeThread({ + environmentId, + id: ThreadId.make("recent-2"), + projectId: project.id, + title: "Within window", + updatedAt: "2026-06-25T00:00:00.000Z", + }), + makeThread({ + environmentId, + id: ThreadId.make("old"), + projectId: project.id, + title: "Two weeks ago", + updatedAt: "2026-06-14T00:00:00.000Z", + }), + ]; + + const group = buildGroups([project], threads)[0]; + // Default view trims to recent threads... + expect(group?.recentThreads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2"]); + // ...while full history stays available for the expanded view. + expect(group?.threads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2", "old"]); + }); + + it("falls back to the most recent 3 threads when none are within 5 days", () => { + const environmentId = EnvironmentId.make("environment-1"); + const project = makeProject({ + environmentId, + id: ProjectId.make("project-1"), + title: "T3 Code", + }); + const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map( + (day, index) => + makeThread({ + environmentId, + id: ThreadId.make(`thread-${index}`), + projectId: project.id, + title: `Thread ${index}`, + updatedAt: `${day}T00:00:00.000Z`, + }), + ); + + const group = buildGroups([project], threads)[0]; + expect(group?.recentThreads.map((thread) => thread.id)).toEqual([ + "thread-4", + "thread-3", + "thread-2", + ]); + expect(group?.threads).toHaveLength(5); + }); + + it("does not apply the recency window while searching", () => { + const environmentId = EnvironmentId.make("environment-1"); + const project = makeProject({ + environmentId, + id: ProjectId.make("project-1"), + title: "T3 Code", + }); + const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map( + (day, index) => + makeThread({ + environmentId, + id: ThreadId.make(`thread-${index}`), + projectId: project.id, + title: `Thread ${index}`, + updatedAt: `${day}T00:00:00.000Z`, + }), + ); + + const group = buildGroups([project], threads, { searchQuery: "T3 Code" })[0]; + // Search reaches the full history rather than the 3-thread fallback. + expect(group?.recentThreads).toHaveLength(5); + expect(group?.recentThreads.map((thread) => thread.id)).toEqual( + group?.threads.map((thread) => thread.id), + ); + }); + + it("targets quick new threads at the group member with the newest thread", () => { + const laptopEnv = EnvironmentId.make("environment-laptop"); + const desktopEnv = EnvironmentId.make("environment-desktop"); + const repositoryIdentity = { + canonicalKey: "github.com/pingdotgg/t3code", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "git@github.com:pingdotgg/t3code.git", + }, + }; + const laptopProject = makeProject({ + environmentId: laptopEnv, + id: ProjectId.make("project-laptop"), + title: "t3code", + repositoryIdentity, + }); + const desktopProject = makeProject({ + environmentId: desktopEnv, + id: ProjectId.make("project-desktop"), + title: "t3code", + repositoryIdentity, + }); + const threads = [ + makeThread({ + environmentId: laptopEnv, + id: ThreadId.make("thread-laptop"), + projectId: laptopProject.id, + title: "Older laptop thread", + updatedAt: "2026-06-27T00:00:00.000Z", + }), + makeThread({ + environmentId: desktopEnv, + id: ThreadId.make("thread-desktop"), + projectId: desktopProject.id, + title: "Newest desktop thread", + updatedAt: "2026-06-28T00:00:00.000Z", + }), + ]; + + // Aggregated into one group by repository; the quick new-thread target + // must follow the newest thread (desktop), not the arbitrary first member. + const groups = buildGroups([laptopProject, desktopProject], threads); + expect(groups).toHaveLength(1); + expect(groups[0]?.projects).toHaveLength(2); + expect(groups[0]?.newThreadTarget?.environmentId).toBe(desktopEnv); + expect(groups[0]?.newThreadTarget?.id).toBe(desktopProject.id); + }); }); diff --git a/apps/mobile/src/features/home/homeThreadList.ts b/apps/mobile/src/features/home/homeThreadList.ts index 9f09e894c2..cada956d8b 100644 --- a/apps/mobile/src/features/home/homeThreadList.ts +++ b/apps/mobile/src/features/home/homeThreadList.ts @@ -14,42 +14,92 @@ import type { SidebarThreadSortOrder, } from "@t3tools/contracts"; import * as Arr from "effect/Array"; +import * as Option from "effect/Option"; import * as Order from "effect/Order"; import { scopedProjectKey } from "../../lib/scopedEntities"; +import type { PendingNewTask } from "../../state/use-pending-new-tasks"; export type HomeProjectSortOrder = Exclude; +/** + * Default home view only surfaces threads active within this window, to keep the + * screen compact while keeping recent work visible. + */ +const RECENT_THREAD_WINDOW_MS = 5 * 24 * 60 * 60 * 1000; +/** Fallback when a project has no threads inside the recency window. */ +const RECENT_THREAD_FALLBACK_COUNT = 3; + export interface HomeThreadGroup { readonly key: string; readonly title: string; readonly representative: EnvironmentProject; readonly projects: ReadonlyArray; + readonly pendingTasks: ReadonlyArray; + /** Full sorted thread history for the group (revealed when expanded / searching). */ readonly threads: ReadonlyArray; + /** Subset shown by default: threads from the last few days, or the most recent few. */ + readonly recentThreads: ReadonlyArray; + /** + * Where a quick "new thread in this project" should land. For aggregated + * groups (same repo on several machines) this is the member that owns the + * group's most recent thread — the machine the user last worked on — rather + * than the arbitrary first member; the draft's computer picker covers + * switching from there. Null only for synthetic pending-project groups, + * whose single "project" is a placeholder built from queued-task metadata. + */ + readonly newThreadTarget: EnvironmentProject | null; } interface MutableHomeThreadGroup { readonly key: string; readonly projects: EnvironmentProject[]; + readonly pendingTasks: PendingNewTask[]; readonly threads: EnvironmentThreadShell[]; } function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number { - return group.threads.reduce( + const latestThread = group.threads.reduce( (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)), Number.NEGATIVE_INFINITY, ); + return group.pendingTasks.reduce((latest, pendingTask) => { + const timestamp = Date.parse(pendingTask.message.createdAt); + return Number.isNaN(timestamp) ? latest : Math.max(latest, timestamp); + }, latestThread); +} + +/** + * Trims a group's threads to recent activity for the default home view. + * `sortedThreads` must already be ordered newest-first for `threadSortOrder`. + * Keeps threads within {@link RECENT_THREAD_WINDOW_MS}; when none qualify, keeps + * the most recent {@link RECENT_THREAD_FALLBACK_COUNT} so a project never vanishes. + */ +function selectRecentThreads( + sortedThreads: ReadonlyArray, + threadSortOrder: SidebarThreadSortOrder, + now: number, +): ReadonlyArray { + const cutoff = now - RECENT_THREAD_WINDOW_MS; + const recent = sortedThreads.filter( + (thread) => getThreadSortTimestamp(thread, threadSortOrder) >= cutoff, + ); + return recent.length > 0 ? recent : sortedThreads.slice(0, RECENT_THREAD_FALLBACK_COUNT); } export function buildHomeThreadGroups(input: { readonly projects: ReadonlyArray; readonly threads: ReadonlyArray; + readonly pendingTasks?: ReadonlyArray; readonly environmentId: EnvironmentId | null; readonly searchQuery: string; readonly projectSortOrder: HomeProjectSortOrder; readonly threadSortOrder: SidebarThreadSortOrder; readonly projectGroupingMode: SidebarProjectGroupingMode; + /** Current time used for the recency window; defaults to now. Injectable for tests. */ + readonly now?: number; }): ReadonlyArray { + const now = input.now ?? Date.now(); const groups = new Map(); const groupKeyByProjectKey = new Map(); @@ -68,10 +118,49 @@ export function buildHomeThreadGroups(input: { if (existing) { existing.projects.push(project); } else { - groups.set(groupKey, { key: groupKey, projects: [project], threads: [] }); + groups.set(groupKey, { key: groupKey, projects: [project], pendingTasks: [], threads: [] }); } } + for (const pendingTask of input.pendingTasks ?? []) { + if (input.environmentId !== null && pendingTask.message.environmentId !== input.environmentId) { + continue; + } + + const physicalKey = scopedProjectKey( + pendingTask.message.environmentId, + pendingTask.creation.projectId, + ); + let groupKey = groupKeyByProjectKey.get(physicalKey); + if (!groupKey) { + // The project shell is not loaded (environment offline / project gone). + // A queued task must stay visible and deletable regardless, so build a + // standalone group from the metadata snapshotted at enqueue time. + groupKey = `pending-project:${physicalKey}`; + groupKeyByProjectKey.set(physicalKey, groupKey); + groups.set(groupKey, { + key: groupKey, + projects: [ + { + environmentId: pendingTask.message.environmentId, + id: pendingTask.creation.projectId, + title: pendingTask.creation.projectTitle ?? "Unknown project", + workspaceRoot: + pendingTask.creation.projectCwd ?? String(pendingTask.creation.projectId), + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: pendingTask.message.createdAt, + updatedAt: pendingTask.message.createdAt, + }, + ], + pendingTasks: [], + threads: [], + }); + } + groups.get(groupKey)?.pendingTasks.push(pendingTask); + } + for (const thread of input.threads) { if (thread.archivedAt !== null) { continue; @@ -93,7 +182,7 @@ export function buildHomeThreadGroups(input: { for (const group of groups.values()) { const representative = group.projects[0]; - if (!representative || group.threads.length === 0) { + if (!representative || (group.threads.length === 0 && group.pendingTasks.length === 0)) { continue; } @@ -108,17 +197,53 @@ export function buildHomeThreadGroups(input: { const matchingThreads = groupMatches ? group.threads : group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query)); + const matchingPendingTasks = groupMatches + ? group.pendingTasks + : group.pendingTasks.filter((pendingTask) => + pendingTask.title.toLocaleLowerCase().includes(query), + ); - if (matchingThreads.length === 0) { + if (matchingThreads.length === 0 && matchingPendingTasks.length === 0) { continue; } + const sortedThreads = sortThreads(matchingThreads, input.threadSortOrder); + // An active search should reach the full history, so the recency window + // only trims the default (no-query) view. + const recentThreads = + query.length === 0 + ? selectRecentThreads(sortedThreads, input.threadSortOrder, now) + : sortedThreads; + + // Sorted newest-first, so the first thread whose project is a group member + // marks the machine the user last worked on. + const lastActiveProject = Arr.findFirst(sortedThreads, (thread) => + group.projects.some( + (project) => + project.environmentId === thread.environmentId && project.id === thread.projectId, + ), + ).pipe( + Option.flatMap((thread) => + Arr.findFirst( + group.projects, + (project) => + project.environmentId === thread.environmentId && project.id === thread.projectId, + ), + ), + Option.getOrNull, + ); + result.push({ key: group.key, title, representative, projects: group.projects, - threads: sortThreads(matchingThreads, input.threadSortOrder), + pendingTasks: matchingPendingTasks, + threads: sortedThreads, + recentThreads, + newThreadTarget: group.key.startsWith("pending-project:") + ? null + : (lastActiveProject ?? representative), }); } diff --git a/apps/mobile/src/features/home/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx index dd0e2901bb..84a9f32ee5 100644 --- a/apps/mobile/src/features/home/thread-swipe-actions.tsx +++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx @@ -1,8 +1,26 @@ -import { SymbolView } from "expo-symbols"; -import type { ComponentProps } from "react"; -import type { ColorValue } from "react-native"; +import { SymbolView } from "../../components/AppSymbol"; +import * as Haptics from "expo-haptics"; +import { + createContext, + use, + useCallback, + useEffect, + useRef, + useState, + type ComponentProps, + type ReactNode, +} from "react"; +import type { + ColorValue, + NativeScrollEvent, + NativeSyntheticEvent, + StyleProp, + ViewStyle, +} from "react-native"; import { Pressable, View } from "react-native"; -import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable"; +import ReanimatedSwipeable, { + type SwipeableMethods, +} from "react-native-gesture-handler/ReanimatedSwipeable"; import Animated, { Extrapolation, interpolate, @@ -14,7 +32,8 @@ import Animated, { import { AppText as Text } from "../../components/AppText"; -const ACTION_ITEM_WIDTH = 50; +// Wide enough for the longest action label ("Unarchive"). +const ACTION_ITEM_WIDTH = 58; const ACTION_CIRCLE_SIZE = 36; const ACTION_ICON_SIZE = 15; @@ -26,6 +45,231 @@ export const THREAD_SWIPE_SPRING = { stiffness: 330, }; +interface ThreadSwipePrimaryAction { + readonly accessibilityLabel: string; + readonly icon: ComponentProps["name"]; + readonly label: string; + readonly onPress: () => void; +} + +/** + * Delivers the scroll gate to swipeables via context so that flipping it does + * NOT re-render whole rows: putting the flag in list extraData/renderItem deps + * re-rendered every visible row (hooks, subscriptions and all) exactly at + * scroll start — peak frame pressure. As a context value only the + * ThreadSwipeable consumers re-render. + */ +const SwipeableScrollGateContext = createContext(true); + +export function SwipeableScrollGateProvider(props: { + readonly enabled: boolean; + readonly children: ReactNode; +}) { + return ( + + {props.children} + + ); +} + +/** + * Gates row swipes on list scroll activity, mirroring UIKit's own swipe + * actions (`!isDragging && !isDecelerating`). failOffsetY on the swipe pan + * covers the first pan of a scroll, but trackpad scroll sessions spawn fresh + * gesture sessions (momentum catch, direction changes) whose reset + * translation can re-activate a swipe mid-scroll — so while the list has + * moved vertically during an active drag/momentum phase, row swipes are + * disabled entirely. + * + * Spread the returned handlers onto the list and pass `swipeEnabled` to rows. + */ +export function useSwipeableScrollGate(options?: { + readonly onScroll?: (event: NativeSyntheticEvent) => void; + readonly onScrollBeginDrag?: (event: NativeSyntheticEvent) => void; +}) { + const [gateActive, setGateActive] = useState(false); + const gateActiveRef = useRef(false); + const draggingRef = useRef(false); + const dragStartYRef = useRef(0); + const settleTimerRef = useRef | null>(null); + const externalOnScroll = options?.onScroll; + const externalOnScrollBeginDrag = options?.onScrollBeginDrag; + + const update = useCallback((next: boolean) => { + if (gateActiveRef.current !== next) { + gateActiveRef.current = next; + setGateActive(next); + } + }, []); + const clearSettle = useCallback(() => { + if (settleTimerRef.current !== null) { + clearTimeout(settleTimerRef.current); + settleTimerRef.current = null; + } + }, []); + useEffect(() => clearSettle, [clearSettle]); + + const onScrollBeginDrag = useCallback( + (event: NativeSyntheticEvent) => { + draggingRef.current = true; + dragStartYRef.current = event.nativeEvent.contentOffset.y; + clearSettle(); + externalOnScrollBeginDrag?.(event); + }, + [clearSettle, externalOnScrollBeginDrag], + ); + const onScroll = useCallback( + (event: NativeSyntheticEvent) => { + // Only vertical movement during a user drag arms the gate — a purely + // horizontal row swipe never moves contentOffset.y, and inset-driven + // offset changes at mount happen outside a drag. + if ( + draggingRef.current && + !gateActiveRef.current && + Math.abs(event.nativeEvent.contentOffset.y - dragStartYRef.current) > 4 + ) { + update(true); + } + externalOnScroll?.(event); + }, + [externalOnScroll, update], + ); + const onScrollEndDrag = useCallback(() => { + draggingRef.current = false; + clearSettle(); + // If momentum follows, onMomentumScrollBegin cancels this and the gate + // stays armed until the deceleration finishes. + settleTimerRef.current = setTimeout(() => update(false), 160); + }, [clearSettle, update]); + const onMomentumScrollBegin = useCallback(() => { + clearSettle(); + }, [clearSettle]); + const onMomentumScrollEnd = useCallback(() => { + update(false); + }, [update]); + + return { + swipeEnabled: !gateActive, + scrollGateHandlers: { + onScroll, + onScrollBeginDrag, + onScrollEndDrag, + onMomentumScrollBegin, + onMomentumScrollEnd, + }, + }; +} + +export function ThreadSwipeable(props: { + readonly backgroundColor: ColorValue; + readonly children: (close: () => void) => ReactNode; + readonly containerStyle?: StyleProp; + /** Disables NEW swipe activations (e.g. while the list scrolls). */ + readonly enabled?: boolean; + readonly enableTrackpadSwipe?: boolean; + readonly fullSwipeWidth: number; + readonly onDelete: () => void; + readonly onSwipeableClose?: (methods: SwipeableMethods) => void; + readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void; + readonly primaryAction: ThreadSwipePrimaryAction; + /** + * Identity of the content being wrapped. When a recycled list reuses this + * component for a different item, the swipeable snaps back to closed so an + * open/mid-drag state can't leak onto another row. + */ + readonly resetKey?: string; + readonly simultaneousWithExternalGesture?: ComponentProps< + typeof ReanimatedSwipeable + >["simultaneousWithExternalGesture"]; + readonly threadTitle: string; +}) { + const swipeableRef = useRef(null); + const fullSwipeArmedRef = useRef(false); + const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, props.fullSwipeWidth * 0.58); + const close = useCallback(() => swipeableRef.current?.close(), []); + const gateEnabled = use(SwipeableScrollGateContext); + const resetKey = props.resetKey; + useEffect(() => { + if (resetKey === undefined) { + return; + } + fullSwipeArmedRef.current = false; + swipeableRef.current?.reset(); + }, [resetKey]); + const handleFullSwipeArmedChange = useCallback((armed: boolean) => { + if (armed && !fullSwipeArmedRef.current) { + void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium); + } + fullSwipeArmedRef.current = armed; + }, []); + + return ( + { + fullSwipeArmedRef.current = false; + if (swipeableRef.current) { + props.onSwipeableClose?.(swipeableRef.current); + } + }} + onSwipeableOpenStartDrag={() => { + if (swipeableRef.current) { + props.onSwipeableWillOpen?.(swipeableRef.current); + } + }} + onSwipeableWillOpen={() => { + const methods = swipeableRef.current; + if (!methods) { + return; + } + + props.onSwipeableWillOpen?.(methods); + if (fullSwipeArmedRef.current) { + fullSwipeArmedRef.current = false; + methods.close(); + props.onDelete(); + } + }} + overshootFriction={1} + overshootRight + renderRightActions={(_progress, translation, methods) => ( + { + methods.close(); + props.primaryAction.onPress(); + }, + }} + swipeableMethods={methods} + threadTitle={props.threadTitle} + translation={translation} + /> + )} + rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42} + simultaneousWithExternalGesture={props.simultaneousWithExternalGesture} + > + {props.children(close)} + + ); +} + function SwipeActionButton(props: { readonly accessibilityLabel: string; readonly backgroundColor: string; @@ -167,7 +411,9 @@ function SwipeActionButton(props: { - {props.label} + + {props.label} + @@ -179,12 +425,7 @@ export function ThreadSwipeActions(props: { readonly fullSwipeThreshold: number; readonly onDelete: () => void; readonly onFullSwipeArmedChange: (armed: boolean) => void; - readonly primaryAction: { - readonly accessibilityLabel: string; - readonly icon: ComponentProps["name"]; - readonly label: string; - readonly onPress: () => void; - }; + readonly primaryAction: ThreadSwipePrimaryAction; readonly swipeableMethods: SwipeableMethods; readonly threadTitle: string; readonly translation: SharedValue; diff --git a/apps/mobile/src/features/home/usePendingTaskListActions.ts b/apps/mobile/src/features/home/usePendingTaskListActions.ts new file mode 100644 index 0000000000..3f0867ba0e --- /dev/null +++ b/apps/mobile/src/features/home/usePendingTaskListActions.ts @@ -0,0 +1,57 @@ +import { useNavigation } from "@react-navigation/native"; +import { useCallback } from "react"; +import { Alert } from "react-native"; + +import { removeThreadOutboxMessage } from "../../state/thread-outbox"; +import type { PendingNewTask } from "../../state/use-pending-new-tasks"; +import { releaseEditingQueuedMessage } from "../../state/use-thread-outbox"; + +export function usePendingTaskListActions(): { + readonly openPendingTask: (pendingTask: PendingNewTask) => void; + readonly confirmDeletePendingTask: (pendingTask: PendingNewTask) => void; +} { + const navigation = useNavigation(); + + const openPendingTask = useCallback( + (pendingTask: PendingNewTask) => { + navigation.navigate("NewTaskSheet", { + screen: "NewTaskDraft", + params: { + environmentId: String(pendingTask.message.environmentId), + projectId: String(pendingTask.creation.projectId), + pendingTaskId: String(pendingTask.message.messageId), + }, + }); + }, + [navigation], + ); + + const confirmDeletePendingTask = useCallback((pendingTask: PendingNewTask) => { + Alert.alert( + "Delete pending task?", + `“${pendingTask.title}” has not been sent yet and will be removed from the outbox.`, + [ + { text: "Cancel", style: "cancel" }, + { + text: "Delete", + style: "destructive", + onPress: () => { + // Release the edit lock only after removal succeeds, and only if + // it is held for THIS task — clearing it up front (or for another + // task) would let the drain deliver a mid-edit payload. + void removeThreadOutboxMessage(pendingTask.message) + .then(() => releaseEditingQueuedMessage(pendingTask.message.messageId)) + .catch((error) => { + Alert.alert( + "Could not delete pending task", + error instanceof Error ? error.message : "The pending task could not be removed.", + ); + }); + }, + }, + ], + ); + }, []); + + return { openPendingTask, confirmDeletePendingTask }; +} diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index cc5d0dd047..8effdc942d 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -4,6 +4,7 @@ import * as Haptics from "expo-haptics"; import { useCallback, useRef } from "react"; import { Alert } from "react-native"; +import { showConfirmDialog } from "../../components/ConfirmDialogHost"; import { scopedThreadKey } from "../../lib/scopedEntities"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -21,9 +22,7 @@ function actionFailureMessage(action: ThreadListAction, cause: Cause.Cause { - Alert.alert( - "Delete thread?", - `“${thread.title}” will be permanently deleted, including its terminal history.`, - [ + const title = "Delete thread?"; + const message = `“${thread.title}” will be permanently deleted, including its terminal history.`; + if (process.env.EXPO_OS === "ios") { + Alert.alert(title, message, [ { text: "Cancel", style: "cancel" }, { text: "Delete", @@ -92,8 +91,18 @@ function useConfirmDeleteThread( void executeAction("delete", thread); }, }, - ], - ); + ]); + return; + } + showConfirmDialog({ + title, + message, + confirmText: "Delete", + destructive: true, + onConfirm: () => { + void executeAction("delete", thread); + }, + }); }, [executeAction], ); diff --git a/apps/mobile/src/features/home/workspace-connection-status.ts b/apps/mobile/src/features/home/workspace-connection-status.ts new file mode 100644 index 0000000000..d8eed4383b --- /dev/null +++ b/apps/mobile/src/features/home/workspace-connection-status.ts @@ -0,0 +1,26 @@ +import type { WorkspaceState } from "../../state/workspaceModel"; + +export function shouldShowWorkspaceConnectionStatus(state: WorkspaceState): boolean { + return ( + state.networkStatus === "offline" || + state.connectionError !== null || + state.hasConnectingEnvironment || + state.hasPendingShellSnapshot || + (state.hasLoadedShellSnapshot && !state.hasReadyEnvironment) + ); +} + +export function workspaceConnectionStatusLabel(state: WorkspaceState): string { + if (state.networkStatus === "offline") return "You are offline"; + if (state.connectingEnvironments.length === 1) { + return `Reconnecting to ${state.connectingEnvironments[0]!.environmentLabel}`; + } + if (state.connectingEnvironments.length > 1) { + return `Reconnecting ${state.connectingEnvironments.length} environments`; + } + if (state.connectionError !== null) return state.connectionError; + if (state.hasPendingShellSnapshot) { + return state.hasLoadedShellSnapshot ? "Syncing threads..." : "Loading threads..."; + } + return "Not connected"; +} diff --git a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx new file mode 100644 index 0000000000..96a4a63e90 --- /dev/null +++ b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx @@ -0,0 +1,73 @@ +import { StackActions, useNavigation } from "@react-navigation/native"; +import { useCallback, useMemo, useSyncExternalStore, type PropsWithChildren } from "react"; + +import { T3KeyboardCommands } from "../../native/T3KeyboardCommands"; +import { + dispatchHardwareKeyboardCommand, + getHardwareKeyboardCommandRegistrationVersion, + getRegisteredHardwareKeyboardCommands, + parseActiveThreadPath, + subscribeToHardwareKeyboardCommandRegistrations, + type HardwareKeyboardCommand, +} from "./hardwareKeyboardCommands"; + +export function HardwareKeyboardCommandProvider({ + children, + pathname, +}: PropsWithChildren<{ readonly pathname: string }>) { + const navigation = useNavigation(); + const registrationVersion = useSyncExternalStore( + subscribeToHardwareKeyboardCommandRegistrations, + getHardwareKeyboardCommandRegistrationVersion, + getHardwareKeyboardCommandRegistrationVersion, + ); + const enabledCommands = useMemo(() => { + const commands = new Set(getRegisteredHardwareKeyboardCommands()); + commands.add("newTask"); + if (pathname !== "/" || navigation.canGoBack()) commands.add("back"); + if (parseActiveThreadPath(pathname)) { + commands.add("files"); + commands.add("terminal"); + commands.add("review"); + } + return [...commands]; + }, [pathname, registrationVersion, navigation]); + + const onCommand = useCallback( + (command: HardwareKeyboardCommand) => { + if (dispatchHardwareKeyboardCommand(command)) return; + + if (command === "newTask") { + navigation.navigate("NewTaskSheet", { screen: "NewTask" }); + return; + } + if (command === "back") { + if (navigation.canGoBack()) { + navigation.goBack(); + } else { + navigation.dispatch(StackActions.replace("Home")); + } + return; + } + + const thread = parseActiveThreadPath(pathname); + if (!thread) return; + if (command === "files" && !/\/files(?:\/|$)/.test(pathname)) { + navigation.navigate("ThreadFiles", thread); + } + if (command === "terminal" && !/\/terminal(?:\/|$)/.test(pathname)) { + navigation.navigate("ThreadTerminal", thread); + } + if (command === "review" && !/\/review(?:\/|$)/.test(pathname)) { + navigation.navigate("ThreadReview", thread); + } + }, + [pathname, navigation], + ); + + return ( + + {children} + + ); +} diff --git a/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.test.ts b/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.test.ts new file mode 100644 index 0000000000..55f1037c01 --- /dev/null +++ b/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { parseActiveThreadPath } from "./hardwareKeyboardCommands"; + +describe("parseActiveThreadPath", () => { + it("extracts the active thread from thread subroutes", () => { + expect(parseActiveThreadPath("/threads/environment-1/thread-1/files/src/index.ts")).toEqual({ + environmentId: "environment-1", + threadId: "thread-1", + }); + }); + + it("decodes route components", () => { + expect(parseActiveThreadPath("/threads/local%20machine/thread%2Fone/review")).toEqual({ + environmentId: "local machine", + threadId: "thread/one", + }); + }); + + it("ignores non-thread routes", () => { + expect(parseActiveThreadPath("/settings")).toBeNull(); + expect(parseActiveThreadPath("/threads/environment-only")).toBeNull(); + }); + + it("ignores malformed encoded route components", () => { + expect(parseActiveThreadPath("/threads/%E0%A4%A/thread-1")).toBeNull(); + }); +}); diff --git a/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts b/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts new file mode 100644 index 0000000000..300434eb73 --- /dev/null +++ b/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts @@ -0,0 +1,78 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { useEffect } from "react"; + +export type HardwareKeyboardCommand = + | "newTask" + | "focusSearch" + | "back" + | "files" + | "terminal" + | "review" + | "toggleSidebar"; + +type CommandHandler = () => boolean | void; + +const handlers = new Map>(); +const registrationListeners = new Set<() => void>(); +let registrationVersion = 0; + +/** + * Registers a context-specific hardware-keyboard action. The most recently mounted handler gets + * the first chance to consume the command, allowing focused screens to override app defaults. + */ +export function useHardwareKeyboardCommand( + command: HardwareKeyboardCommand, + handler: CommandHandler, +): void { + useEffect(() => { + const commandHandlers = handlers.get(command) ?? new Set(); + commandHandlers.add(handler); + handlers.set(command, commandHandlers); + registrationVersion += 1; + registrationListeners.forEach((listener) => listener()); + return () => { + commandHandlers.delete(handler); + if (commandHandlers.size === 0) handlers.delete(command); + registrationVersion += 1; + registrationListeners.forEach((listener) => listener()); + }; + }, [command, handler]); +} + +export function getRegisteredHardwareKeyboardCommands(): ReadonlySet { + return new Set(handlers.keys()); +} + +export function getHardwareKeyboardCommandRegistrationVersion(): number { + return registrationVersion; +} + +export function subscribeToHardwareKeyboardCommandRegistrations(listener: () => void): () => void { + registrationListeners.add(listener); + return () => registrationListeners.delete(listener); +} + +export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand): boolean { + const commandHandlers = handlers.get(command); + if (!commandHandlers) return false; + for (const handler of [...commandHandlers].toReversed()) { + if (handler() !== false) return true; + } + return false; +} + +export function parseActiveThreadPath(pathname: string): { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; +} | null { + const match = /^\/threads\/([^/]+)\/([^/]+)(?:\/|$)/.exec(pathname); + if (!match?.[1] || !match[2]) return null; + try { + return { + environmentId: EnvironmentId.make(decodeURIComponent(match[1])), + threadId: ThreadId.make(decodeURIComponent(match[2])), + }; + } catch { + return null; + } +} diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx new file mode 100644 index 0000000000..d1327473b0 --- /dev/null +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -0,0 +1,526 @@ +import type { + EnvironmentProject, + EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { useFocusEffect } from "@react-navigation/native"; +import { + NavigationContext, + NavigationRouteContext, + StackActions, + useNavigation, +} from "@react-navigation/native"; +import { + createContext, + use, + useCallback, + useEffect, + useMemo, + useRef, + useState, + type ReactNode, +} from "react"; +import { useWindowDimensions, View } from "react-native"; +import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated"; + +import { + deriveFileInspectorPaneLayout, + deriveLayout, + deriveWorkspacePaneLayout, + type FileInspectorPaneLayout, + type Layout, + type WorkspaceAuxiliaryPaneRole, + type WorkspacePaneLayout, +} from "../../lib/layout"; +import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation"; +import { scopedThreadKey } from "../../lib/scopedEntities"; +import { + parseActiveThreadPath, + useHardwareKeyboardCommand, +} from "../keyboard/hardwareKeyboardCommands"; +import { HomeListOptionsProvider } from "../home/home-list-options"; +import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar"; +import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation"; +import { WorkspaceInspectorPane } from "./workspace-inspector-pane"; + +interface AdaptiveWorkspaceContextValue { + readonly layout: Layout; + readonly panes: WorkspacePaneLayout; + readonly fileInspector: FileInspectorPaneLayout; + readonly primarySidebarSearchQuery: string; + readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void; + /** + * Route screens hand their inspector pane content to the workspace so it + * renders BESIDE the navigator (outside the native stack header) instead of + * inside the route. Returns a deactivate callback: the pane animates closed + * (content kept mounted for the exit transition) unless a newer + * registration already took over — stale deactivates never clobber it. + * Prefer useRegisterWorkspaceInspector over calling this directly. + */ + readonly registerWorkspaceInspector: (render: () => ReactNode) => () => void; + readonly setPrimarySidebarSearchQuery: (query: string) => void; + readonly showAuxiliaryPane: (role: WorkspaceAuxiliaryPaneRole) => void; + readonly toggleAuxiliaryPane: () => void; + readonly togglePrimarySidebar: () => void; + readonly setAuxiliaryPaneWidth: (width: number) => void; +} + +const compactLayout = deriveLayout({ width: 0, height: 0 }); +const compactPanes = deriveWorkspacePaneLayout({ + layout: compactLayout, + viewportWidth: 0, + primarySidebarPreferredVisible: true, + auxiliaryPanePreferredVisible: true, +}); +const compactFileInspector = deriveFileInspectorPaneLayout({ + layout: compactLayout, + viewportWidth: 0, +}); +const AdaptiveWorkspaceContext = createContext({ + layout: compactLayout, + panes: compactPanes, + fileInspector: compactFileInspector, + primarySidebarSearchQuery: "", + activateAuxiliaryPaneRole: () => () => undefined, + registerWorkspaceInspector: () => () => undefined, + setPrimarySidebarSearchQuery: () => undefined, + showAuxiliaryPane: () => undefined, + toggleAuxiliaryPane: () => undefined, + togglePrimarySidebar: () => undefined, + setAuxiliaryPaneWidth: () => undefined, +}); + +export function useAdaptiveWorkspaceLayout(): AdaptiveWorkspaceContextValue { + return use(AdaptiveWorkspaceContext); +} + +export function useAdaptiveWorkspacePaneRole(role: WorkspaceAuxiliaryPaneRole) { + const { activateAuxiliaryPaneRole } = useAdaptiveWorkspaceLayout(); + + useFocusEffect( + useCallback(() => activateAuxiliaryPaneRole(role), [activateAuxiliaryPaneRole, role]), + ); +} + +/** + * Register this screen's inspector pane content with the workspace column. + * + * The column renders BESIDE the navigator — outside any screen — so the + * registering screen's navigation and route contexts are captured here and + * re-provided around the portal content. Without them, useNavigation/useRoute + * inside the pane (e.g. GitOverviewSheet via useThreadSelection) throw + * "Couldn't find a route object". + * + * Registration is FOCUS-scoped, driven by navigation events rather than the + * screen's own render cycle: react-native-screens freezes blurred screens, so + * a cleanup that depends on the blurred subtree re-rendering never runs and + * would leak the pane into the next route. Blur deactivates the pane (it + * animates closed, or is replaced seamlessly when the next route registers in + * the same commit); focus re-registers it. + */ +export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undefined) { + const { registerWorkspaceInspector } = useAdaptiveWorkspaceLayout(); + // Raw context values (not the useNavigation/useRoute wrappers) so the + // portal re-provides exactly what this screen sees. + const navigation = use(NavigationContext); + const route = use(NavigationRouteContext); + + const wrappedRender = useMemo(() => { + if (render === undefined) { + return undefined; + } + return () => ( + + {render()} + + ); + }, [navigation, render, route]); + + const wrappedRenderRef = useRef(wrappedRender); + wrappedRenderRef.current = wrappedRender; + const focusedRef = useRef(false); + const deactivateRef = useRef<(() => void) | null>(null); + + const syncRegistration = useCallback(() => { + if (!focusedRef.current || wrappedRenderRef.current === undefined) { + deactivateRef.current?.(); + return; + } + deactivateRef.current = registerWorkspaceInspector(wrappedRenderRef.current); + }, [registerWorkspaceInspector]); + + // Focus lifecycle. Blur/focus events fire even when the blurred subtree is + // frozen (events are navigation-driven, renders are not). + useFocusEffect( + useCallback(() => { + focusedRef.current = true; + syncRegistration(); + return () => { + focusedRef.current = false; + syncRegistration(); + }; + }, [syncRegistration]), + ); + + // Content changes while focused re-register in place. + useEffect(() => { + if (focusedRef.current) { + syncRegistration(); + } + }, [syncRegistration, wrappedRender]); + + // Unmount: hand the pane back (owner-guarded, so a route that already + // took over is unaffected). + useEffect( + () => () => { + deactivateRef.current?.(); + deactivateRef.current = null; + }, + [], + ); +} + +export function AdaptiveWorkspaceLayout(props: { + readonly children: ReactNode; + readonly pathname: string; +}) { + const { width, height } = useWindowDimensions(); + const pathname = props.pathname; + const navigation = useNavigation(); + const activeRoleOwner = useRef(null); + const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true); + const [supplementaryPanePreferredVisible, setSupplementaryPanePreferredVisible] = useState(true); + const [supplementaryPanePreferredWidth, setSupplementaryPanePreferredWidth] = useState< + number | null + >(null); + const [fileInspectorPreferredVisible, setFileInspectorPreferredVisible] = useState(true); + const [fileInspectorPreferredWidth, setFileInspectorPreferredWidth] = useState( + null, + ); + const [primarySidebarSearchQuery, setPrimarySidebarSearchQuery] = useState(""); + const [focusedAuxiliaryPaneRole, setFocusedAuxiliaryPaneRole] = + useState(null); + const baseLayout = useMemo(() => deriveLayout({ width, height }), [height, width]); + const layout = baseLayout; + // In split layouts the sidebar IS the thread list — it renders on every + // route, including Home (which shows an empty-detail pane instead of the + // compact list). + const shouldRenderPrimarySidebar = layout.usesSplitView; + const fileInspector = useMemo( + () => + deriveFileInspectorPaneLayout({ + layout, + viewportWidth: width, + preferredWidth: fileInspectorPreferredWidth ?? undefined, + reservedLeadingWidth: + shouldRenderPrimarySidebar && primarySidebarPreferredVisible + ? (layout.listPaneWidth ?? 0) + : 0, + }), + [ + fileInspectorPreferredWidth, + layout, + primarySidebarPreferredVisible, + shouldRenderPrimarySidebar, + width, + ], + ); + const auxiliaryPaneRole: WorkspaceAuxiliaryPaneRole = + focusedAuxiliaryPaneRole ?? (/\/files(?:\/|$)/.test(pathname) ? "inspector" : "supplementary"); + const auxiliaryPanePreferredVisible = + auxiliaryPaneRole === "inspector" + ? fileInspectorPreferredVisible + : supplementaryPanePreferredVisible; + const auxiliaryPanePreferredWidth = + auxiliaryPaneRole === "inspector" + ? fileInspectorPreferredWidth + : supplementaryPanePreferredWidth; + const panes = useMemo( + () => + deriveWorkspacePaneLayout({ + layout, + viewportWidth: width, + primarySidebarPreferredVisible, + auxiliaryPanePreferredVisible, + auxiliaryPaneRole, + auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined, + }), + [ + auxiliaryPanePreferredVisible, + auxiliaryPaneRole, + auxiliaryPanePreferredWidth, + layout, + primarySidebarPreferredVisible, + width, + ], + ); + const activeThread = parseActiveThreadPath(pathname); + const environmentId = activeThread?.environmentId ?? null; + const threadId = activeThread?.threadId ?? null; + const selectedThreadKey = useMemo(() => { + if (environmentId === null || threadId === null) { + return null; + } + try { + return scopedThreadKey(EnvironmentId.make(environmentId), ThreadId.make(threadId)); + } catch { + return null; + } + }, [environmentId, threadId]); + // Wrapped in an object: bare functions in useState would be treated as + // lazy initializers/updaters. `active: false` keeps the outgoing route's + // content mounted so the pane can animate closed (or be replaced + // seamlessly by the next route's registration in the same commit). + const [workspaceInspector, setWorkspaceInspector] = useState<{ + readonly render: () => ReactNode; + readonly active: boolean; + } | null>(null); + const workspaceInspectorOwner = useRef(null); + const registerWorkspaceInspector = useCallback((render: () => ReactNode) => { + const owner = Symbol("workspace-inspector"); + workspaceInspectorOwner.current = owner; + setWorkspaceInspector({ render, active: true }); + + return () => { + // During a push/replace the outgoing screen deactivates AFTER the + // incoming screen registered — only the current owner may deactivate. + if (workspaceInspectorOwner.current !== owner) { + return; + } + setWorkspaceInspector((current) => (current === null ? null : { ...current, active: false })); + }; + }, []); + // Once the close animation settles, drop the stale content entirely. + const handleWorkspaceInspectorClosed = useCallback(() => { + setWorkspaceInspector((current) => (current !== null && !current.active ? null : current)); + }, []); + const activateAuxiliaryPaneRole = useCallback((role: WorkspaceAuxiliaryPaneRole) => { + const owner = Symbol(role); + activeRoleOwner.current = owner; + setFocusedAuxiliaryPaneRole(role); + + return () => { + if (activeRoleOwner.current !== owner) { + return; + } + activeRoleOwner.current = null; + setFocusedAuxiliaryPaneRole(null); + }; + }, []); + const togglePrimarySidebar = useCallback(() => { + if (!panes.primarySidebarVisible && panes.primarySidebarSuppressedByAuxiliary) { + setFileInspectorPreferredVisible(false); + setPrimarySidebarPreferredVisible(true); + return; + } + setPrimarySidebarPreferredVisible((current) => !current); + }, [panes.primarySidebarSuppressedByAuxiliary, panes.primarySidebarVisible]); + const revealPrimarySidebar = useCallback(() => { + if (panes.primarySidebarSuppressedByAuxiliary) { + setFileInspectorPreferredVisible(false); + } + setPrimarySidebarPreferredVisible(true); + }, [panes.primarySidebarSuppressedByAuxiliary]); + const handleToggleSidebarCommand = useCallback(() => { + togglePrimarySidebar(); + return true; + }, [togglePrimarySidebar]); + useHardwareKeyboardCommand("toggleSidebar", handleToggleSidebarCommand); + const showAuxiliaryPane = useCallback((role: WorkspaceAuxiliaryPaneRole) => { + if (role === "inspector") { + setFocusedAuxiliaryPaneRole("inspector"); + setFileInspectorPreferredVisible(true); + return; + } + setFocusedAuxiliaryPaneRole("supplementary"); + setSupplementaryPanePreferredVisible(true); + }, []); + const handleOpenFilesCommand = useCallback(() => { + const activeThread = parseActiveThreadPath(pathname); + if (!layout.usesSplitView || !fileInspector.supported || activeThread === null) { + return false; + } + showAuxiliaryPane("inspector"); + if (/\/files(?:\/|$)/.test(pathname)) { + return true; + } + navigation.navigate("ThreadFiles", activeThread); + return true; + }, [fileInspector.supported, layout.usesSplitView, pathname, navigation, showAuxiliaryPane]); + useHardwareKeyboardCommand("files", handleOpenFilesCommand); + const toggleAuxiliaryPane = useCallback(() => { + if (auxiliaryPaneRole === "inspector") { + setFileInspectorPreferredVisible((current) => !current); + return; + } + setSupplementaryPanePreferredVisible((current) => !current); + }, [auxiliaryPaneRole]); + const setAuxiliaryPaneWidth = useCallback( + (nextWidth: number) => { + if (auxiliaryPaneRole === "inspector") { + setFileInspectorPreferredWidth(nextWidth); + return; + } + setSupplementaryPanePreferredWidth(nextWidth); + }, + [auxiliaryPaneRole], + ); + const contextValue = useMemo( + () => ({ + layout, + panes, + fileInspector, + primarySidebarSearchQuery, + activateAuxiliaryPaneRole, + registerWorkspaceInspector, + setPrimarySidebarSearchQuery, + showAuxiliaryPane, + toggleAuxiliaryPane, + togglePrimarySidebar, + setAuxiliaryPaneWidth, + }), + [ + activateAuxiliaryPaneRole, + fileInspector, + layout, + panes, + primarySidebarSearchQuery, + registerWorkspaceInspector, + showAuxiliaryPane, + setPrimarySidebarSearchQuery, + setAuxiliaryPaneWidth, + toggleAuxiliaryPane, + togglePrimarySidebar, + ], + ); + + const handleOpenSettings = useCallback(() => { + navigation.navigate("SettingsSheet", { screen: "Settings" }); + }, [navigation]); + + // Minted here (root stack navigation) so the sidebar pane stays free of + // navigation hooks — on iOS it renders inside an independent nav tree. + const handleOpenEnvironmentSettings = useCallback(() => { + navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }); + }, [navigation]); + + const handleNewThreadInProject = useCallback( + (project: EnvironmentProject) => { + navigation.navigate("NewTaskSheet", { + screen: "NewTaskDraft", + params: { + environmentId: String(project.environmentId), + projectId: String(project.id), + title: project.title, + }, + }); + }, + [navigation], + ); + + const renderedSidebarWidth = useSharedValue( + panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0, + ); + useEffect(() => { + const targetWidth = panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0; + renderedSidebarWidth.value = withTiming(targetWidth, WORKSPACE_PANE_TIMING); + }, [layout.listPaneWidth, panes.primarySidebarVisible, renderedSidebarWidth]); + const sidebarAnimatedStyle = useAnimatedStyle(() => ({ + opacity: Math.min(1, renderedSidebarWidth.value / 80), + width: renderedSidebarWidth.value, + })); + + // Freeze the content pane at its SETTLED width while the side panes + // animate. The navigator (native header + markdown feed) lays out ONCE per + // pane toggle instead of re-measuring on every animation frame — the + // animating columns merely clip/reveal it over a matching background. + // Continuously re-wrapping the chat feed was the main source of dropped + // frames during sidebar/inspector transitions. + const inspectorColumnTargetWidth = + workspaceInspector !== null && workspaceInspector.active && panes.auxiliaryPaneVisible + ? (panes.auxiliaryPaneWidth ?? 0) + : 0; + const contentSettledWidth = layout.usesSplitView + ? Math.max(0, panes.contentPaneWidth - inspectorColumnTargetWidth) + : null; + + const handleSelectThread = useCallback( + (thread: EnvironmentThreadShell) => { + const params = { + environmentId: String(thread.environmentId), + threadId: String(thread.id), + }; + const navigationAction = resolveThreadSelectionNavigationAction({ + usesSplitView: layout.usesSplitView, + pathname, + }); + if (navigationAction === "set-params") { + const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id); + if (nextThreadKey === selectedThreadKey) { + return; + } + setFileInspectorPreferredVisible(false); + navigation.navigate("Thread", params); + return; + } + if (navigationAction === "replace") { + setFileInspectorPreferredVisible(false); + navigation.dispatch(StackActions.replace("Thread", params)); + return; + } + navigation.navigate("Thread", params); + }, + [layout.usesSplitView, pathname, navigation, selectedThreadKey], + ); + + return ( + + + + {shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? ( + + + + ) : null} + + + {props.children} + + + + + + + ); +} diff --git a/apps/mobile/src/features/layout/WorkspaceEmptyDetail.tsx b/apps/mobile/src/features/layout/WorkspaceEmptyDetail.tsx new file mode 100644 index 0000000000..66ce2a0aaf --- /dev/null +++ b/apps/mobile/src/features/layout/WorkspaceEmptyDetail.tsx @@ -0,0 +1,30 @@ +import { SymbolView } from "../../components/AppSymbol"; +import { Pressable, View } from "react-native"; + +import { AppText as Text } from "../../components/AppText"; +import { useThemeColor } from "../../lib/useThemeColor"; + +export function WorkspaceEmptyDetail(props: { readonly onStartNewTask?: () => void }) { + const iconColor = useThemeColor("--color-icon-subtle"); + + return ( + + + + Select a thread + + Choose a thread from the sidebar or start a new task. + + {props.onStartNewTask ? ( + + New Task + + ) : null} + + + ); +} diff --git a/apps/mobile/src/features/layout/native-glass-header-items.ts b/apps/mobile/src/features/layout/native-glass-header-items.ts new file mode 100644 index 0000000000..a8019776c4 --- /dev/null +++ b/apps/mobile/src/features/layout/native-glass-header-items.ts @@ -0,0 +1,33 @@ +type NativeGlassHeaderItem = { + readonly type: "button" | "menu"; + readonly glassEffect?: boolean; + readonly hidesSharedBackground?: boolean; + readonly sharesBackground?: boolean; + readonly variant?: "plain" | "done" | "prominent"; + readonly width?: number; +}; + +/** + * iOS 26/27 Mail-style header controls need the native glass button + * shared background configuration when they are not part of a larger toolbar. + * Do not enable `glassEffect` for normal bar-button items: react-native-screens + * renders that as a custom UIButton, which creates a second skinny capsule. + */ +export function withNativeGlassHeaderItem( + item: T, + options: { + readonly hidesSharedBackground?: boolean; + readonly sharesBackground?: boolean; + readonly width?: number; + } = {}, +): T { + const sharesBackground = options.sharesBackground ?? item.sharesBackground ?? true; + return { + ...item, + glassEffect: item.glassEffect ?? false, + hidesSharedBackground: options.hidesSharedBackground ?? item.hidesSharedBackground ?? false, + sharesBackground, + variant: item.variant ?? "plain", + width: options.width ?? item.width, + } as T; +} diff --git a/apps/mobile/src/features/layout/native-mail-search-toolbar.ts b/apps/mobile/src/features/layout/native-mail-search-toolbar.ts new file mode 100644 index 0000000000..820e122224 --- /dev/null +++ b/apps/mobile/src/features/layout/native-mail-search-toolbar.ts @@ -0,0 +1,25 @@ +import type { HeaderBarButtonMailSearchToolbarItem } from "react-native-screens"; + +type NativeMailSearchToolbarInput = Omit< + HeaderBarButtonMailSearchToolbarItem, + "type" | "useFallbackSearchField" +>; + +/** + * Builds the patched react-native-screens Mail-style bottom search toolbar. + * + * Keeping this behind an app-level helper makes the iOS-only RNS patch an + * explicit layout primitive instead of a per-screen object literal. Android can + * keep using platform-specific header/search primitives without depending on + * this helper. + */ +export function createNativeMailSearchToolbarItem( + input: NativeMailSearchToolbarInput, +): HeaderBarButtonMailSearchToolbarItem { + return { + placeholder: "Search", + ...input, + type: "mailSearchToolbar", + useFallbackSearchField: true, + }; +} diff --git a/apps/mobile/src/features/layout/workspace-inspector-pane.tsx b/apps/mobile/src/features/layout/workspace-inspector-pane.tsx new file mode 100644 index 0000000000..9825ed7fdf --- /dev/null +++ b/apps/mobile/src/features/layout/workspace-inspector-pane.tsx @@ -0,0 +1,146 @@ +import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; +import Animated, { + runOnJS, + useAnimatedStyle, + useSharedValue, + withTiming, +} from "react-native-reanimated"; + +import { constrainAuxiliaryPaneWidth, type WorkspacePaneLayout } from "../../lib/layout"; +import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation"; +import { WorkspacePaneDivider } from "./workspace-pane-divider"; + +/** + * The trailing inspector column: resize divider + animated reveal. + * + * Rendered by AdaptiveWorkspaceLayout as a SIBLING of the navigator so the + * native stack header (and its trailing toolbar items) spans only the content + * pane — the inspector owns its own full-height column, mirroring how each + * column of a UISplitViewController has its own chrome. + * + * Receives the pane layout via props (not the workspace context hook) so this + * module stays import-cycle-free with AdaptiveWorkspaceLayout. + */ +export function WorkspaceInspectorPane(props: { + /** + * When false the pane animates closed but keeps its content mounted for the + * exit transition (a route that lost focus). `onClosed` fires once the + * close animation settles so the owner can drop the stale content. + */ + readonly active?: boolean; + readonly onClosed?: () => void; + readonly panes: WorkspacePaneLayout; + readonly renderInspector?: () => ReactNode; + readonly setAuxiliaryPaneWidth: (width: number) => void; +}) { + const { panes, setAuxiliaryPaneWidth } = props; + const inspectorWidth = panes.auxiliaryPaneWidth; + const inspectorSupported = props.renderInspector !== undefined && inspectorWidth !== null; + const inspectorVisible = + inspectorSupported && panes.auxiliaryPaneVisible && (props.active ?? true); + const resizeStartWidth = useRef(0); + const [resizing, setResizing] = useState(false); + + // A file-to-file replace remounts the route. Initialize an already-visible + // inspector at its final position so route replacement never replays an + // entering transition. Only visibility and explicit resizing change it. + const inspectorProgress = useSharedValue(inspectorVisible ? 1 : 0); + const renderedInspectorWidth = useSharedValue(inspectorVisible ? (inspectorWidth ?? 0) : 0); + // The content keeps its own width so the reveal (outer width) clips a + // fully-laid-out pane instead of reflowing text every frame. When the OPEN + // pane's target width changes (e.g. the sidebar toggles and reserves + // space), animate the content width in lockstep rather than snapping. + const renderedContentWidth = useSharedValue(inspectorWidth ?? 0); + + const onClosed = props.onClosed; + useEffect(() => { + inspectorProgress.value = withTiming( + inspectorVisible ? 1 : 0, + WORKSPACE_PANE_TIMING, + (finished) => { + if (finished === true && !inspectorVisible && onClosed !== undefined) { + runOnJS(onClosed)(); + } + }, + ); + const targetWidth = inspectorVisible ? (inspectorWidth ?? 0) : 0; + renderedInspectorWidth.value = resizing + ? targetWidth + : withTiming(targetWidth, WORKSPACE_PANE_TIMING); + }, [ + inspectorProgress, + inspectorVisible, + inspectorWidth, + onClosed, + renderedInspectorWidth, + resizing, + ]); + + useEffect(() => { + const targetWidth = inspectorWidth ?? 0; + if (!inspectorVisible || resizing) { + // Hidden panes re-measure silently; during a divider drag the content + // tracks the finger directly. + renderedContentWidth.value = targetWidth; + return; + } + renderedContentWidth.value = withTiming(targetWidth, WORKSPACE_PANE_TIMING); + }, [inspectorVisible, inspectorWidth, renderedContentWidth, resizing]); + + const inspectorStyle = useAnimatedStyle( + () => ({ + opacity: inspectorProgress.value, + transform: [{ translateX: (1 - inspectorProgress.value) * 24 }], + width: renderedInspectorWidth.value, + }), + [], + ); + const inspectorContentStyle = useAnimatedStyle(() => ({ width: renderedContentWidth.value }), []); + const beginResize = useCallback(() => { + resizeStartWidth.current = inspectorWidth ?? 0; + setResizing(true); + }, [inspectorWidth]); + const resizeBy = useCallback( + (delta: number) => { + setAuxiliaryPaneWidth( + constrainAuxiliaryPaneWidth({ + preferredWidth: resizeStartWidth.current + delta, + availableWidth: panes.contentPaneWidth, + }), + ); + }, + [panes.contentPaneWidth, setAuxiliaryPaneWidth], + ); + const endResize = useCallback(() => { + setResizing(false); + }, []); + + return ( + <> + {inspectorVisible ? ( + + ) : null} + {inspectorSupported ? ( + + + {props.renderInspector?.()} + + + ) : null} + + ); +} diff --git a/apps/mobile/src/features/layout/workspace-pane-animation.ts b/apps/mobile/src/features/layout/workspace-pane-animation.ts new file mode 100644 index 0000000000..5f037cbcc6 --- /dev/null +++ b/apps/mobile/src/features/layout/workspace-pane-animation.ts @@ -0,0 +1,16 @@ +import { Easing, ReduceMotion } from "react-native-reanimated"; + +/** + * One timing curve for every workspace pane (primary sidebar + inspector). + * + * Panes frequently animate together — opening the sidebar can auto-close the + * inspector when both no longer fit — so identical duration and easing on + * every pane keeps the center content pane from wobbling while both edges + * move. Asymmetric open/close timings (the previous 220ms out-cubic open vs + * 160ms in-cubic close) read as jank during those simultaneous swaps. + */ +export const WORKSPACE_PANE_TIMING = { + duration: 260, + easing: Easing.inOut(Easing.cubic), + reduceMotion: ReduceMotion.System, +} as const; diff --git a/apps/mobile/src/features/layout/workspace-pane-divider.tsx b/apps/mobile/src/features/layout/workspace-pane-divider.tsx new file mode 100644 index 0000000000..3be3cdf602 --- /dev/null +++ b/apps/mobile/src/features/layout/workspace-pane-divider.tsx @@ -0,0 +1,107 @@ +import { useCallback, useMemo, useRef, useState } from "react"; +import { + Platform, + PlatformColor, + Pressable, + StyleSheet, + View, + type AccessibilityActionEvent, +} from "react-native"; +import { Gesture, GestureDetector } from "react-native-gesture-handler"; +import { runOnJS } from "react-native-reanimated"; + +const ACCESSIBILITY_RESIZE_STEP = 24; + +interface WorkspacePaneDividerProps { + readonly accessibilityLabel: string; + readonly currentWidth: number; + /** 1 when dragging right grows the pane, -1 when dragging left grows it. */ + readonly resizeDirection: 1 | -1; + readonly onResizeStart?: () => void; + readonly onResizeBy: (delta: number) => void; + readonly onResizeEnd?: () => void; +} + +/** A forgiving divider target for touch, pointer, and VoiceOver users. */ +export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) { + const latestProps = useRef(props); + latestProps.current = props; + const [hovered, setHovered] = useState(false); + const [dragging, setDragging] = useState(false); + const handleResizeStart = useCallback(() => { + setDragging(true); + latestProps.current.onResizeStart?.(); + }, []); + const handleResize = useCallback((translationX: number) => { + latestProps.current.onResizeBy(translationX * latestProps.current.resizeDirection); + }, []); + const handleResizeEnd = useCallback(() => { + setDragging(false); + latestProps.current.onResizeEnd?.(); + }, []); + const resizeGesture = useMemo( + () => + Gesture.Pan() + .activeOffsetX([-4, 4]) + .failOffsetY([-24, 24]) + .onStart(() => { + runOnJS(handleResizeStart)(); + }) + .onUpdate((event) => { + runOnJS(handleResize)(event.translationX); + }) + .onFinalize(() => { + runOnJS(handleResizeEnd)(); + }), + [handleResize, handleResizeEnd, handleResizeStart], + ); + + const handleAccessibilityAction = (event: AccessibilityActionEvent) => { + props.onResizeStart?.(); + if (event.nativeEvent.actionName === "increment") { + props.onResizeBy(ACCESSIBILITY_RESIZE_STEP); + } else if (event.nativeEvent.actionName === "decrement") { + props.onResizeBy(-ACCESSIBILITY_RESIZE_STEP); + } + props.onResizeEnd?.(); + }; + + return ( + + setHovered(true)} + onHoverOut={() => setHovered(false)} + > + + + + ); +} + +const styles = StyleSheet.create({ + line: { + alignSelf: "center", + backgroundColor: + Platform.OS === "ios" ? PlatformColor("separator") : "rgba(120, 120, 128, 0.28)", + height: "100%", + opacity: 0.7, + width: StyleSheet.hairlineWidth, + }, + activeLine: { + backgroundColor: Platform.OS === "ios" ? PlatformColor("systemBlueColor") : "#0a84ff", + opacity: 1, + width: 2, + }, +}); diff --git a/apps/mobile/src/features/layout/workspace-sidebar-toolbar.tsx b/apps/mobile/src/features/layout/workspace-sidebar-toolbar.tsx new file mode 100644 index 0000000000..d07a003361 --- /dev/null +++ b/apps/mobile/src/features/layout/workspace-sidebar-toolbar.tsx @@ -0,0 +1,32 @@ +import { NativeHeaderToolbar } from "../../native/StackHeader"; +import type { ReactNode } from "react"; +import { Platform } from "react-native"; + +import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout"; + +export function WorkspaceSidebarToolbar( + props: { + readonly children?: ReactNode; + readonly afterSidebarButton?: ReactNode; + } = {}, +) { + const { layout, panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout(); + + if (Platform.OS === "android" || !layout.usesSplitView) { + return null; + } + + return ( + + {props.children} + + {props.afterSidebarButton} + + ); +} diff --git a/apps/mobile/src/features/projects/AddProjectDestinationRoute.tsx b/apps/mobile/src/features/projects/AddProjectDestinationRoute.tsx new file mode 100644 index 0000000000..04e2e236be --- /dev/null +++ b/apps/mobile/src/features/projects/AddProjectDestinationRoute.tsx @@ -0,0 +1,15 @@ +import type { StaticScreenProps } from "@react-navigation/native"; +import { AddProjectDestinationScreen } from "./AddProjectScreen"; + +type AddProjectDestinationRouteParams = { + readonly environmentId?: string | string[]; + readonly source?: string | string[]; + readonly remoteUrl?: string | string[]; + readonly repositoryTitle?: string | string[]; +}; + +export function AddProjectDestinationRoute({ + route, +}: StaticScreenProps) { + return ; +} diff --git a/apps/mobile/src/features/projects/AddProjectLocalRoute.tsx b/apps/mobile/src/features/projects/AddProjectLocalRoute.tsx new file mode 100644 index 0000000000..abe7fb6d6c --- /dev/null +++ b/apps/mobile/src/features/projects/AddProjectLocalRoute.tsx @@ -0,0 +1,12 @@ +import type { StaticScreenProps } from "@react-navigation/native"; +import { AddProjectLocalFolderScreen } from "./AddProjectScreen"; + +type AddProjectLocalRouteParams = { + readonly environmentId?: string | string[]; +}; + +export function AddProjectLocalRoute({ + route, +}: StaticScreenProps) { + return ; +} diff --git a/apps/mobile/src/features/projects/AddProjectRepositoryRoute.tsx b/apps/mobile/src/features/projects/AddProjectRepositoryRoute.tsx new file mode 100644 index 0000000000..cdf52022a4 --- /dev/null +++ b/apps/mobile/src/features/projects/AddProjectRepositoryRoute.tsx @@ -0,0 +1,31 @@ +import type { StaticScreenProps } from "@react-navigation/native"; +import { NativeStackScreenOptions } from "../../native/StackHeader"; +import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime/operations/projects"; + +import { AddProjectRepositoryScreen } from "./AddProjectScreen"; + +type AddProjectRepositoryRouteParams = { + readonly environmentId?: string | string[]; + readonly source?: string | string[]; +}; + +export function AddProjectRepositoryRoute({ + route, +}: StaticScreenProps) { + const params = route.params ?? {}; + const source = Array.isArray(params.source) ? params.source[0] : params.source; + const title = + source === "github" || + source === "gitlab" || + source === "bitbucket" || + source === "azure-devops" + ? addProjectRemoteSourceLabel(source) + : "Git URL"; + + return ( + <> + + + + ); +} diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx index 50a7336fa9..d56855e6df 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.tsx +++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx @@ -22,8 +22,8 @@ import { isFilesystemBrowseQuery, } from "@t3tools/client-runtime/state/projects"; import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts"; -import { useLocalSearchParams, useRouter } from "expo-router"; -import { SymbolView } from "expo-symbols"; +import { StackActions, useNavigation } from "@react-navigation/native"; +import { SymbolView } from "../../components/AppSymbol"; import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"; import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -31,6 +31,7 @@ import * as Arr from "effect/Array"; import * as Cause from "effect/Cause"; import * as Order from "effect/Order"; import { AsyncResult } from "effect/unstable/reactivity"; +import { cn } from "../../lib/cn"; import { useProjects, useServerConfigs } from "../../state/entities"; import { filesystemEnvironment } from "../../state/filesystem"; @@ -99,10 +100,7 @@ function sourceFromParam(value: string | string[] | undefined): AddProjectRemote function SectionTitle(props: { readonly children: string }) { return ( - + {props.children} ); @@ -112,7 +110,12 @@ function AddProjectShell(props: { readonly children: ReactNode }) { const insets = useSafeAreaInsets(); return ( - + // collapsable={false} is load-bearing: if this wrapper is flattened, the + // ScrollView lands directly under RNSSafeAreaView and RNS's formSheet + // scroll-view frame correction mistakes this full-height wrapper for a + // "header" sibling, coercing the ScrollView to zero height (blank sheet + // as soon as the sheet re-lays-out, e.g. when the keyboard opens). + void; }) { - const borderColor = useThemeColor("--color-border-subtle"); const chevronColor = useThemeColor("--color-chevron"); return ( - {props.title} + {props.title} {props.subtitle ? ( - + {props.subtitle} ) : null} @@ -215,7 +216,7 @@ function ProjectPathInput(props: { }) { return ( void; } { - const router = useRouter(); - const params = useLocalSearchParams<{ environmentId?: string }>(); + const [selectedEnvironmentId, setSelectedEnvironmentId] = useState(null); const environmentOptions = useEnvironmentOptions(); - const requestedEnvironmentId = stringParam(params.environmentId) as EnvironmentId | null; const selectedEnvironment = - environmentOptions.find( - (environment) => environment.environmentId === requestedEnvironmentId, - ) ?? + environmentOptions.find((environment) => environment.environmentId === selectedEnvironmentId) ?? environmentOptions[0] ?? null; return { environmentOptions, selectedEnvironment, - setSelectedEnvironmentId: (environmentId) => router.setParams({ environmentId }), + setSelectedEnvironmentId, }; } function EmptyEnvironmentState() { - const router = useRouter(); + const navigation = useNavigation(); return ( No environments connected - + Add an environment before adding a project. router.replace("/connections/new")} + onPress={() => navigation.dispatch(StackActions.replace("ConnectionsNew"))} className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70" > Add environment @@ -294,7 +291,7 @@ function SourceControlRow(props: { readonly hint: string; readonly isFirst: boolean; }) { - const router = useRouter(); + const navigation = useNavigation(); const iconColor = useThemeColor("--color-icon"); const title = props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`; @@ -322,8 +319,8 @@ function SourceControlRow(props: { icon={icon} isFirst={props.isFirst} onPress={() => - router.push({ - pathname: "/new/add-project/repository", + navigation.navigate("NewTaskSheet", { + screen: "AddProjectRepository", params: { environmentId: props.selectedEnvironmentId, source: props.source, @@ -335,7 +332,7 @@ function SourceControlRow(props: { } export function AddProjectSourceScreen() { - const router = useRouter(); + const navigation = useNavigation(); const accentColor = useThemeColor("--color-icon-muted"); const iconColor = useThemeColor("--color-icon"); const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } = @@ -409,9 +406,11 @@ export function AddProjectSourceScreen() { } isFirst onPress={() => - router.push({ - pathname: "/new/add-project/local", - params: { environmentId: selectedEnvironment.environmentId }, + navigation.navigate("NewTaskSheet", { + screen: "AddProjectLocal", + params: { + environmentId: selectedEnvironment.environmentId, + }, }) } /> @@ -440,7 +439,7 @@ export function AddProjectSourceScreen() { } function useCreateProject(environment: EnvironmentOption | null) { - const router = useRouter(); + const navigation = useNavigation(); const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); const projects = useProjects(); @@ -455,14 +454,13 @@ function useCreateProject(environment: EnvironmentOption | null) { }); if (existing) { Alert.alert("Project already exists", existing.title); - router.replace({ - pathname: "/new/draft", - params: { + navigation.dispatch( + StackActions.replace("NewTaskDraft", { environmentId: existing.environmentId, projectId: existing.id, title: existing.title, - }, - }); + }), + ); return; } @@ -479,24 +477,24 @@ function useCreateProject(environment: EnvironmentOption | null) { if (AsyncResult.isFailure(result)) { return result; } - router.replace({ - pathname: "/new/draft", - params: { + navigation.dispatch( + StackActions.replace("NewTaskDraft", { environmentId: environment.environmentId, projectId, title: inferProjectTitleFromPath(workspaceRoot), - }, - }); + }), + ); return result; }, - [createProject, environment, projects, router], + [createProject, environment, projects, navigation], ); } -function useEnvironmentFromParam(): EnvironmentOption | null { - const params = useLocalSearchParams<{ environmentId?: string }>(); +function useEnvironmentFromParam( + environmentIdParam: string | string[] | undefined, +): EnvironmentOption | null { const environmentOptions = useEnvironmentOptions(); - const environmentId = stringParam(params.environmentId) as EnvironmentId | null; + const environmentId = stringParam(environmentIdParam) as EnvironmentId | null; return ( environmentOptions.find((environment) => environment.environmentId === environmentId) ?? environmentOptions[0] ?? @@ -504,14 +502,16 @@ function useEnvironmentFromParam(): EnvironmentOption | null { ); } -export function AddProjectRepositoryScreen() { +export function AddProjectRepositoryScreen(props: { + readonly environmentId?: string | string[]; + readonly source?: string | string[]; +}) { const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, { reportFailure: false, }); - const router = useRouter(); - const params = useLocalSearchParams<{ environmentId?: string; source?: string }>(); - const environment = useEnvironmentFromParam(); - const source = sourceFromParam(params.source); + const navigation = useNavigation(); + const environment = useEnvironmentFromParam(props.environmentId); + const source = sourceFromParam(props.source); const [repositoryInput, setRepositoryInput] = useState(""); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); @@ -523,8 +523,8 @@ export function AddProjectRepositoryScreen() { const provider = addProjectRemoteSourceProvider(source); if (!provider) { const remoteUrl = repositoryInput.trim(); - router.push({ - pathname: "/new/add-project/destination", + navigation.navigate("NewTaskSheet", { + screen: "AddProjectDestination", params: { environmentId: environment.environmentId, source, @@ -547,8 +547,8 @@ export function AddProjectRepositoryScreen() { setError(errorMessage(Cause.squash(result.cause))); } else { const repository = result.value; - router.push({ - pathname: "/new/add-project/destination", + navigation.navigate("NewTaskSheet", { + screen: "AddProjectDestination", params: { environmentId: environment.environmentId, source, @@ -558,13 +558,13 @@ export function AddProjectRepositoryScreen() { }); } setIsSubmitting(false); - }, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, router, source]); + }, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]); return ( {error ? : null} getAddProjectInitialQuery(environment?.baseDirectory), @@ -744,19 +744,18 @@ export function AddProjectLocalFolderScreen() { ); } -export function AddProjectDestinationScreen() { +export function AddProjectDestinationScreen(props: { + readonly environmentId?: string | string[]; + readonly remoteUrl?: string | string[]; + readonly repositoryTitle?: string | string[]; +}) { const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, { reportFailure: false, }); - const params = useLocalSearchParams<{ - environmentId?: string; - remoteUrl?: string; - repositoryTitle?: string; - }>(); - const environment = useEnvironmentFromParam(); + const environment = useEnvironmentFromParam(props.environmentId); const createProject = useCreateProject(environment); - const remoteUrl = stringParam(params.remoteUrl); - const repositoryTitle = stringParam(params.repositoryTitle); + const remoteUrl = stringParam(props.remoteUrl); + const repositoryTitle = stringParam(props.repositoryTitle); const [pathInput, setPathInput] = useState(() => getAddProjectInitialQuery(environment?.baseDirectory), ); diff --git a/apps/mobile/src/features/projects/AddProjectSourceRoute.tsx b/apps/mobile/src/features/projects/AddProjectSourceRoute.tsx new file mode 100644 index 0000000000..2dc85606be --- /dev/null +++ b/apps/mobile/src/features/projects/AddProjectSourceRoute.tsx @@ -0,0 +1,5 @@ +import { AddProjectSourceScreen } from "./AddProjectScreen"; + +export function AddProjectSourceRoute() { + return ; +} diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx index d35c48e8a9..c6d678ddca 100644 --- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx @@ -1,14 +1,21 @@ -import { useLocalSearchParams, useRouter } from "expo-router"; -import { SymbolView } from "expo-symbols"; +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { TextInputWrapper } from "expo-paste-input"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { useCallback, useEffect, useMemo, useState } from "react"; -import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native"; -import { KeyboardAvoidingView } from "react-native-keyboard-controller"; +import { + Platform, + Pressable, + ScrollView, + View, + useColorScheme, + useWindowDimensions, +} from "react-native"; +import { KeyboardAvoidingView, KeyboardStickyView } from "react-native-keyboard-controller"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import ImageViewing from "react-native-image-viewing"; import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; +import { SymbolView } from "../../components/AppSymbol"; import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip"; import { ControlPill } from "../../components/ControlPill"; import { cn } from "../../lib/cn"; @@ -25,13 +32,8 @@ import { getSelectedReviewCommentLines, useReviewCommentTarget, } from "./reviewCommentSelection"; -import { - changeTone, - DiffTokenText, - REVIEW_DIFF_LINE_HEIGHT, - REVIEW_MONO_FONT_FAMILY, - ReviewChangeBar, -} from "./reviewDiffRendering"; +import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface"; +import { changeTone, DiffTokenText, ReviewChangeBar } from "./reviewDiffRendering"; import { highlightReviewSelectedLines, type ReviewDiffTheme, @@ -40,17 +42,21 @@ import { const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5; -export function ReviewCommentComposerSheet() { - const router = useRouter(); +type ReviewCommentComposerSheetProps = StaticScreenProps<{ + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; +}>; + +export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProps) { + const isAndroid = Platform.OS === "android"; + const navigation = useNavigation(); const insets = useSafeAreaInsets(); const { width } = useWindowDimensions(); const colorScheme = useColorScheme(); const iconTint = String(useThemeColor("--color-icon")); const target = useReviewCommentTarget(); - const { environmentId, threadId } = useLocalSearchParams<{ - environmentId: EnvironmentId; - threadId: ThreadId; - }>(); + const { codeSurface } = useAppearanceCodeSurface(); + const { environmentId, threadId } = props.route.params; const [commentText, setCommentText] = useState(""); const [highlightedLinesById, setHighlightedLinesById] = useState< Record> @@ -78,14 +84,14 @@ export function ReviewCommentComposerSheet() { ? `Lines ${firstNumber}-${lastNumber}` : `${selectedLines.length} lines selected`; const previewHeight = Math.max( - Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT, - REVIEW_DIFF_LINE_HEIGHT, + Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * codeSurface.rowHeight, + codeSurface.rowHeight, ); const previewViewportWidth = Math.max(width - 40, 280); const dismissComposer = useCallback(() => { clearReviewCommentTarget(); - router.dismiss(); - }, [router]); + navigation.goBack(); + }, [navigation]); const handleNativePaste = useNativePaste((uris) => { void (async () => { try { @@ -140,15 +146,29 @@ export function ReviewCommentComposerSheet() { } } + const handleSubmit = useCallback(() => { + if (!target || !environmentId || !threadId || commentText.trim().length === 0) { + return; + } + + appendReviewCommentToDraft({ + environmentId, + threadId, + text: formatReviewCommentContext(target, commentText), + attachments, + }); + setAttachments([]); + dismissComposer(); + }, [attachments, commentText, dismissComposer, environmentId, target, threadId]); + return ( - - + + @@ -167,7 +187,7 @@ export function ReviewCommentComposerSheet() { {!target ? ( No selection - + Select a diff line or range first. @@ -178,7 +198,7 @@ export function ReviewCommentComposerSheet() { {selectionLabel} @@ -211,13 +231,10 @@ export function ReviewCommentComposerSheet() { - - + + {lineNumber ?? ""} @@ -225,6 +242,8 @@ export function ReviewCommentComposerSheet() { fallback={line.content} tokens={highlightedLinesById[line.id] ?? null} change={line.change} + fontSize={codeSurface.fontSize} + lineHeight={codeSurface.rowHeight} /> @@ -248,8 +267,7 @@ export function ReviewCommentComposerSheet() { textAlignVertical="top" value={commentText} onChangeText={setCommentText} - className="h-full flex-1 border-0 bg-transparent px-0 py-0 font-sans text-base" - style={{ flex: 1, minHeight: 0 }} + className="h-full min-h-0 flex-1 border-0 bg-transparent px-0 py-0 font-sans text-base" /> @@ -274,7 +292,7 @@ export function ReviewCommentComposerSheet() { )} - {target ? ( + {!isAndroid && target ? ( { - if (!target || !environmentId || !threadId || commentText.trim().length === 0) { - return; - } - - appendReviewCommentToDraft({ - environmentId, - threadId, - text: formatReviewCommentContext(target, commentText), - attachments, - }); - setAttachments([]); - dismissComposer(); - }} + onPress={handleSubmit} /> ) : null} + {isAndroid && target ? ( + + + void handlePickImages()} + /> + + + + + ) : null} Partial diff - + {props.notice} @@ -110,36 +148,246 @@ function ReviewSelectionActionBar(props: { ); } -export function ReviewSheet() { +interface ReviewNavigatorFile { + readonly id: string; + readonly path: string; + readonly additions: number; + readonly deletions: number; +} + +const ReviewFileNavigatorRow = memo(function ReviewFileNavigatorRow(props: { + readonly file: ReviewNavigatorFile; + readonly selected: boolean; + readonly onSelectFile: (fileId: string | null) => void; +}) { + const { file, selected, onSelectFile } = props; + // Tapping the selected file again returns to the all-files diff. + const handlePress = useCallback(() => { + onSelectFile(selected ? null : file.id); + }, [file.id, onSelectFile, selected]); + + return ( + + + {file.path} + + + +{file.additions} + -{file.deletions} + + + ); +}); + +interface ReviewFileNavigatorHandle { + readonly setVisibleFile: (fileId: string | null) => void; +} + +interface ReviewFileNavigatorProps { + readonly files: ReadonlyArray; + readonly headerInset: number; + readonly sectionId: string | null; + readonly onSelectFile: (fileId: string | null) => void; + readonly ref?: Ref; +} + +function ReviewFileNavigator({ + files, + headerInset, + sectionId, + onSelectFile, + ref, +}: ReviewFileNavigatorProps) { + const insets = useSafeAreaInsets(); + const sheetColor = String(useThemeColor("--color-sheet")); + const foregroundColor = String(useThemeColor("--color-foreground")); + const headerScrollEdgeEffects = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version); + const [fileSelection, setFileSelection] = useState<{ + readonly sectionId: string | null; + readonly fileId: string | null; + }>({ sectionId: null, fileId: null }); + const availableFileIds = useMemo(() => files.map((file) => file.id), [files]); + const selectedFileId = resolveSelectedReviewFileId({ + selection: fileSelection, + sectionId, + availableFileIds, + }); + + useImperativeHandle( + ref, + () => ({ + setVisibleFile: (fileId) => { + if (fileId !== null && !availableFileIds.includes(fileId)) { + return; + } + setFileSelection((current) => { + if (current.sectionId === sectionId && current.fileId === fileId) { + return current; + } + return { sectionId, fileId }; + }); + }, + }), + [availableFileIds, sectionId], + ); + + const handleSelectFile = useCallback( + (fileId: string | null) => { + setFileSelection({ sectionId, fileId }); + onSelectFile(fileId); + }, + [onSelectFile, sectionId], + ); + + const renderFile = useCallback( + ({ item }: { readonly item: ReviewNavigatorFile }) => ( + + ), + [handleSelectFile, selectedFileId], + ); + + const fileList = ( + file.id} + contentContainerStyle={{ + paddingHorizontal: 8, + paddingBottom: 8, + // The nested native header is translucent; start the list below it so + // the scroll-edge effect can sample the content (same treatment as + // FileTreeBrowser in the Files pane). + paddingTop: Platform.OS === "ios" ? insets.top + 44 + 8 : 8, + }} + scrollIndicatorInsets={Platform.OS === "ios" ? { top: insets.top + 44 } : undefined} + renderItem={renderFile} + /> + ); + + if (Platform.OS === "ios") { + return ( + + + + {fileList} + + + + + ); + } + + return ( + + + + Changed files + + {files.length} {files.length === 1 ? "file" : "files"} + + + + {fileList} + + ); +} + +type ReviewSheetProps = StaticScreenProps<{ + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; +}>; + +export function ReviewSheet(props: ReviewSheetProps) { + const isAndroid = Platform.OS === "android"; + const { nativeReviewDiffStyle } = useAppearanceCodeSurface(); + useAdaptiveWorkspacePaneRole("inspector"); + const { panes, showAuxiliaryPane, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout(); + const navigation = useNavigation(); const insets = useSafeAreaInsets(); const colorScheme = useColorScheme(); - const headerForeground = String(useThemeColor("--color-foreground")); - const headerMuted = String(useThemeColor("--color-foreground-muted")); const headerIcon = String(useThemeColor("--color-icon")); - const { environmentId, threadId } = useLocalSearchParams<{ - environmentId: EnvironmentId; - threadId: ThreadId; - }>(); + const { environmentId, threadId } = props.route.params; const environment = useEnvironmentPresentation(environmentId); const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry"); const isEnvironmentReady = environment.presentation?.connection.phase === "connected"; const { draftMessage } = useThreadDraftForThread({ environmentId, threadId }); const reviewCache = useReviewCacheForThread({ environmentId, threadId }); + /* ─── Git actions for the toolbar menu (commit/push without leaving review) ── */ + const { selectedThread } = useThreadSelection(); + const { selectedThreadCwd } = useSelectedThreadWorktree(); + const gitState = useSelectedThreadGitState(); + const gitActions = useSelectedThreadGitActions(); + const gitStatusQuery = useEnvironmentQuery( + selectedThread !== null && selectedThreadCwd !== null + ? vcsEnvironment.status({ + environmentId: selectedThread.environmentId, + input: { cwd: selectedThreadCwd }, + }) + : null, + ); + // The selection-based git hooks only apply when this review belongs to the + // selected thread (it always does when reached from the thread's toolbar). + const gitMenuAvailable = + selectedThread !== null && String(selectedThread.id) === String(threadId); const selectedTheme = colorScheme === "dark" ? "dark" : "light"; - const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT; - const { - error, - loadingGitDiffs, - loadingTurnIds, - reviewSections, - selectedSection, - refreshSelectedSection, - selectSection, - } = useReviewSections({ - enabled: isEnvironmentReady, - environmentId, - threadId, - reviewCache, + // With a solid (non-overlay) header the content lays out below the header + // natively, so no manual top inset is needed. (Android renders its own + // in-flow AndroidScreenHeader, so it needs no inset either.) + const topContentInset = 0; + + useEffect(() => { + showAuxiliaryPane("inspector"); + }, [environmentId, showAuxiliaryPane, threadId]); + const { error, reviewSections, selectedSection, refreshSelectedSection, selectSection } = + useReviewSections({ + enabled: isEnvironmentReady, + environmentId, + threadId, + reviewCache, + }); + useReviewDiffPrewarming({ + threadKey: reviewCache.threadKey, + sections: reviewSections, + selectedSectionId: selectedSection?.id ?? null, }); const { headerDiffSummary, nativeReviewDiffData, parsedDiff, pendingReviewCommentCount } = useReviewDiffData({ @@ -148,6 +396,19 @@ export function ReviewSheet() { draftMessage, }); const NativeReviewDiffView = resolveNativeReviewDiffView()!; + const nativeReviewDiffViewRef = useRef(null); + const showcasedReviewDrawRef = useRef(null); + // Native pull-to-refresh on the diff surface (replaces the old Refresh menu item). + const [isPullRefreshing, setIsPullRefreshing] = useState(false); + const handlePullToRefresh = useCallback(async () => { + setIsPullRefreshing(true); + try { + await refreshSelectedSection(); + } finally { + setIsPullRefreshing(false); + } + }, [refreshSelectedSection]); + const reviewFileNavigatorRef = useRef(null); const reviewFiles = parsedDiff.kind === "files" ? parsedDiff.files : []; const fileVisibility = useReviewFileVisibility({ threadKey: reviewCache.threadKey, @@ -178,6 +439,62 @@ export function ReviewSheet() { selectedRowIds: commentSelection.selectedRowIds, canHighlight: parsedDiff.kind === "files", }); + const showcaseReviewKey = + SHOWCASE_ENABLED && parsedDiff.kind === "files" && selectedSection + ? `${reviewCache.threadKey}:${selectedSection.id}:${nativeBridge.tokensResetKey}` + : null; + const handleNativeDebug = useCallback( + (event: NativeSyntheticEvent>) => { + nativeBridge.onDebug(event); + if ( + showcaseReviewKey === null || + showcasedReviewDrawRef.current === showcaseReviewKey || + !isNativeReviewDiffDrawEvent(event.nativeEvent) + ) { + return; + } + showcasedReviewDrawRef.current = showcaseReviewKey; + markNativeShowcaseReady("review"); + }, + [nativeBridge.onDebug, showcaseReviewKey], + ); + + const handleSelectFile = useCallback( + (fileId: string | null) => { + commentSelection.clearSelection(); + if (fileId !== null && collapsedFileIds.includes(fileId)) { + toggleExpandedFile(fileId); + } + const navigation = + fileId === null + ? nativeReviewDiffViewRef.current?.scrollToTop(true) + : nativeReviewDiffViewRef.current?.scrollToFile(fileId, true); + void navigation?.catch((error: unknown) => { + console.error("[review] Failed to navigate to diff file", error); + }); + }, + [collapsedFileIds, commentSelection, toggleExpandedFile], + ); + const handleVisibleFileChange = useCallback( + (event: NativeSyntheticEvent<{ readonly fileId?: string | null }>) => { + reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null); + }, + [], + ); + const renderInspector = useCallback( + () => ( + + ), + [handleSelectFile, insets.top, nativeReviewDiffData.files, selectedSection?.id], + ); const handleNativeToggleFile = useCallback( (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => { @@ -203,15 +520,85 @@ export function ReviewSheet() { parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null; const hasCachedSelectedDiff = selectedSection?.diff != null; const hasAnyCachedDiff = reviewSections.some((section) => section.diff != null); + const sectionMenu = useMemo(() => buildReviewSectionMenu(reviewSections), [reviewSections]); const { showConnectionNotice, showSectionToolbar } = resolveReviewAvailability({ hasEnvironmentPresentation: environment.isReady, isEnvironmentConnected: isEnvironmentReady, hasCachedSelectedDiff, hasAnyCachedDiff, }); + const androidSectionMenuActions = useMemo(() => { + const sectionAction = (section: ReviewSectionItem | null, title: string): MenuAction => ({ + id: section ? `section:${section.id}` : `unavailable:${title}`, + title: section?.id === selectedSection?.id ? `${title} (selected)` : title, + attributes: section ? undefined : { disabled: true }, + }); + const actions: MenuAction[] = [ + sectionAction(sectionMenu.workingTree, "Working tree"), + sectionAction(sectionMenu.branchChanges, "Branch changes"), + sectionAction(sectionMenu.latestTurn, "Latest turn"), + ]; + + if (sectionMenu.turns.length > 0) { + actions.push({ + id: "turns", + title: "Turn", + subactions: sectionMenu.turns.map((section) => ({ + id: `section:${section.id}`, + title: section.id === selectedSection?.id ? `${section.title} (selected)` : section.title, + subtitle: section.subtitle ?? undefined, + })), + }); + } + + // The Android native diff surface has no pull-to-refresh, so refresh + // stays a menu action there (iOS refreshes via pull-to-refresh instead). + actions.push({ + id: "refresh", + title: "Refresh current diff", + attributes: { + disabled: !selectedSection || selectedSection.isLoading, + }, + }); + return actions; + }, [sectionMenu, selectedSection]); + const handleAndroidSectionMenuAction = useCallback( + (event: { nativeEvent: { event: string } }) => { + const id = event.nativeEvent.event; + if (id === "refresh") { + void refreshSelectedSection(); + } else if (id.startsWith("section:")) { + selectSection(id.slice("section:".length)); + } + }, + [refreshSelectedSection, selectSection], + ); const handleRetryEnvironment = useCallback(() => { void retryEnvironment(environmentId); }, [environmentId, retryEnvironment]); + const handleReturnToThread = useCallback(() => { + if (navigation.canGoBack()) { + navigation.goBack(); + return; + } + navigation.navigate("Thread", { + environmentId: String(environmentId), + threadId: String(threadId), + }); + }, [environmentId, navigation, threadId]); + const androidHeaderSubtitle = [ + selectedSection?.title, + headerDiffSummary.additions, + headerDiffSummary.deletions, + ] + .filter((part): part is string => Boolean(part)) + .join(" · "); + + // The changed-files navigator lives in the workspace inspector column — + // the single right-hand pane per route — instead of an in-screen panel. + const showChangedFilesPane = + !showConnectionNotice && selectedSection !== null && parsedDiff.kind === "files"; + useRegisterWorkspaceInspector(showChangedFilesPane ? renderInspector : undefined); const listHeader = useMemo(() => { const children: ReactElement[] = []; @@ -220,7 +607,7 @@ export function ReviewSheet() { children.push( Review unavailable - {error} + {error} , ); } @@ -235,139 +622,149 @@ export function ReviewSheet() { return <>{children}; }, [error, parsedDiffNotice]); + const headerSubtitle = [ + headerDiffSummary.additions, + headerDiffSummary.deletions, + pendingReviewCommentCount > 0 + ? `${pendingReviewCommentCount} comment${pendingReviewCommentCount === 1 ? "" : "s"}` + : null, + ] + .filter(Boolean) + .join(" · "); + const headerTitleText = selectedSection?.title ?? "Review changes"; return ( <> - ( - - - Files Changed - - - {headerDiffSummary.additions && headerDiffSummary.deletions ? ( - <> - - {headerDiffSummary.additions} - - - {headerDiffSummary.deletions} - - {pendingReviewCommentCount > 0 ? ( - - {pendingReviewCommentCount} pending - - ) : null} - - ) : ( - - - {selectedSection?.title ?? "Review changes"} - - {pendingReviewCommentCount > 0 ? ( - - {pendingReviewCommentCount} pending - - ) : null} - - )} - - - ), - }} + 0 ? headerSubtitle : undefined, + } + } /> - {showSectionToolbar ? ( - - - {reviewSections.map((section) => ( - selectSection(section.id)} - subtitle={section.subtitle ?? undefined} + {isAndroid ? ( + - {section.title} - - ))} - + + ) : null + } + /> + ) : null} + + + + + + {!isAndroid && (showSectionToolbar || panes.supportsAuxiliaryPane || gitMenuAvailable) ? ( + + {panes.supportsAuxiliaryPane ? ( + void refreshSelectedSection()} - subtitle="Reload current diff" - > - Refresh - - - + icon="sidebar.right" + onPress={toggleAuxiliaryPane} + separateBackground + /> + ) : null} + {gitMenuAvailable && selectedThread !== null ? ( + + ) : null} + {showSectionToolbar ? ( + + + { + if (sectionMenu.workingTree) { + selectSection(sectionMenu.workingTree.id); + } + }} + > + Working tree + + { + if (sectionMenu.branchChanges) { + selectSection(sectionMenu.branchChanges.id); + } + }} + > + Branch changes + + { + if (sectionMenu.latestTurn) { + selectSection(sectionMenu.latestTurn.id); + } + }} + > + Latest turn + + {sectionMenu.turns.length > 0 ? ( + + {sectionMenu.turns.map((section) => ( + selectSection(section.id)} + subtitle={section.subtitle ?? undefined} + > + {section.title} + + ))} + + ) : null} + + + ) : null} + ) : null} {showConnectionNotice ? ( - + - {listHeader} - - + + {listHeader} + + void handlePullToRefresh()} + style={StyleSheet.absoluteFill} + appearanceScheme={selectedTheme} + collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson} + collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson} + contentResetKey={`${reviewCache.threadKey}:${selectedSection.id}`} + contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH} + nativeViewRef={nativeReviewDiffViewRef} + rowHeight={nativeReviewDiffStyle.rowHeight} + rowsJson={nativeBridge.rowsJson} + selectedRowIdsJson={nativeBridge.selectedRowIdsJson} + styleJson={nativeBridge.styleJson} + themeJson={nativeBridge.themeJson} + tokensPatchJson={nativeBridge.tokensPatchJson} + tokensResetKey={nativeBridge.tokensResetKey} + viewedFileIdsJson={nativeBridge.viewedFileIdsJson} + onDebug={handleNativeDebug} + onPressLine={commentSelection.onPressLine} + onVisibleFileChange={handleVisibleFileChange} + onToggleComment={nativeBridge.onToggleComment} + onToggleFile={handleNativeToggleFile} + onToggleViewedFile={handleNativeToggleViewedFile} + /> + ) : ( @@ -426,13 +831,13 @@ export function ReviewSheet() { bottom: Math.max(insets.bottom, 18) + 18, }} showsVerticalScrollIndicator={false} - style={{ flex: 1 }} + className="flex-1" > {listHeader} {!selectedSection ? ( No review diffs - + This thread has no ready turn diffs and the worktree diff is empty. @@ -444,17 +849,17 @@ export function ReviewSheet() { ) : parsedDiff.kind === "empty" ? ( No changes - + {selectedSection.subtitle ?? "This diff is empty."} ) : parsedDiff.kind === "raw" ? ( - + {parsedDiff.reason} - + {parsedDiff.text} diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts new file mode 100644 index 0000000000..1722b06d6f --- /dev/null +++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + getCachedNativeReviewDiffData, + type BuildNativeReviewDiffDataInput, +} from "./nativeReviewDiffAdapter"; +import type { ReviewInlineComment } from "./reviewCommentSelection"; +import { buildReviewParsedDiff } from "./reviewModel"; + +const parsedDiff = buildReviewParsedDiff( + [ + "diff --git a/example.ts b/example.ts", + "--- a/example.ts", + "+++ b/example.ts", + "@@ -1 +1 @@", + "-const before = 1;", + "+const after = 2;", + ].join("\n"), + "native-review-cache-test", +); + +function makeComment(text: string): ReviewInlineComment { + return { + id: "comment-1", + sectionId: "git:working-tree", + sectionTitle: "Dirty worktree", + filePath: "example.ts", + startIndex: 0, + endIndex: 0, + rangeLabel: "-1", + text, + diff: "@@ -1,1 +1,0 @@\n-const before = 1;", + }; +} + +function buildInput(comments: BuildNativeReviewDiffDataInput["comments"]) { + return { parsedDiff, comments } satisfies BuildNativeReviewDiffDataInput; +} + +describe("getCachedNativeReviewDiffData", () => { + it("reuses the row model for equivalent empty comment arrays", () => { + const first = getCachedNativeReviewDiffData(buildInput([])); + const second = getCachedNativeReviewDiffData(buildInput([])); + + expect(second).toBe(first); + }); + + it("reuses equivalent comment contents and invalidates changed comments", () => { + const first = getCachedNativeReviewDiffData(buildInput([makeComment("First")])); + const equivalent = getCachedNativeReviewDiffData(buildInput([makeComment("First")])); + const changed = getCachedNativeReviewDiffData(buildInput([makeComment("Changed")])); + + expect(equivalent).toBe(first); + expect(changed).not.toBe(first); + }); +}); diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts index f60fdfe70e..6d82940bb0 100644 --- a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts +++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts @@ -5,6 +5,8 @@ import type { } from "../diffs/nativeReviewDiffTypes"; import * as Arr from "effect/Array"; import { pipe } from "effect/Function"; +import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences"; +import { resolveMobileCodeSurface } from "../../lib/appearancePreferences"; import { MOBILE_CODE_SURFACE } from "../../lib/typography"; import { getPierreTerminalTheme, type TerminalAppearanceScheme } from "../terminal/terminalTheme"; import { computeWordAltDiffRanges } from "./reviewWordDiffs"; @@ -22,38 +24,44 @@ const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45; export const NATIVE_REVIEW_DIFF_ROW_HEIGHT = MOBILE_CODE_SURFACE.rowHeight; export const NATIVE_REVIEW_DIFF_CONTENT_WIDTH = 2_800; -export const NATIVE_REVIEW_DIFF_STYLE = { - rowHeight: NATIVE_REVIEW_DIFF_ROW_HEIGHT, - contentWidth: NATIVE_REVIEW_DIFF_CONTENT_WIDTH, - changeBarWidth: 4, - gutterWidth: MOBILE_CODE_SURFACE.gutterWidth, - codePadding: MOBILE_CODE_SURFACE.codePadding, - textVerticalInset: MOBILE_CODE_SURFACE.textVerticalInset, - fileHeaderHeight: 56, - fileHeaderHorizontalMargin: 8, - fileHeaderVerticalMargin: 6, - fileHeaderCornerRadius: 10, - fileHeaderHorizontalPadding: 10, - fileHeaderPathRightPadding: 118, - fileHeaderCountColumnWidth: 38, - fileHeaderCountGap: 5, - codeFontSize: MOBILE_CODE_SURFACE.fontSize, - codeFontWeight: "regular", - lineNumberFontSize: MOBILE_CODE_SURFACE.lineNumberFontSize, - lineNumberFontWeight: "regular", - hunkFontSize: 11, - hunkFontWeight: "medium", - fileHeaderFontSize: 11, - fileHeaderFontWeight: "semibold", - fileHeaderMetaFontSize: 10, - fileHeaderMetaFontWeight: "semibold", - fileHeaderSubtextFontSize: 11, - fileHeaderSubtextFontWeight: "medium", - fileHeaderStatusFontSize: 9, - fileHeaderStatusFontWeight: "bold", - emptyStateFontSize: 12, - emptyStateFontWeight: "medium", -} as const; +export const NATIVE_REVIEW_DIFF_STYLE = createNativeReviewDiffStyle( + resolveMobileCodeSurface(MOBILE_CODE_SURFACE.fontSize), +); + +export function createNativeReviewDiffStyle(codeSurface: ResolvedMobileCodeSurface) { + return { + rowHeight: codeSurface.rowHeight, + contentWidth: NATIVE_REVIEW_DIFF_CONTENT_WIDTH, + changeBarWidth: 4, + gutterWidth: codeSurface.gutterWidth, + codePadding: codeSurface.codePadding, + textVerticalInset: codeSurface.textVerticalInset, + fileHeaderHeight: 56, + fileHeaderHorizontalMargin: 8, + fileHeaderVerticalMargin: 6, + fileHeaderCornerRadius: 10, + fileHeaderHorizontalPadding: 10, + fileHeaderPathRightPadding: 118, + fileHeaderCountColumnWidth: 38, + fileHeaderCountGap: 5, + codeFontSize: codeSurface.fontSize, + codeFontWeight: "regular", + lineNumberFontSize: codeSurface.lineNumberFontSize, + lineNumberFontWeight: "regular", + hunkFontSize: 11, + hunkFontWeight: "medium", + fileHeaderFontSize: 11, + fileHeaderFontWeight: "semibold", + fileHeaderMetaFontSize: 10, + fileHeaderMetaFontWeight: "semibold", + fileHeaderSubtextFontSize: 11, + fileHeaderSubtextFontWeight: "medium", + fileHeaderStatusFontSize: 9, + fileHeaderStatusFontWeight: "bold", + emptyStateFontSize: 12, + emptyStateFontWeight: "medium", + } as const; +} export interface NativeReviewDiffData { readonly rows: ReadonlyArray; @@ -75,6 +83,33 @@ export interface BuildNativeReviewDiffDataInput { readonly comments?: ReadonlyArray; } +interface CachedNativeReviewDiffData { + readonly commentsKey: string; + readonly data: NativeReviewDiffData; +} + +const nativeReviewDiffDataCache = new WeakMap(); + +function buildReviewCommentsCacheKey(comments: ReadonlyArray): string { + if (comments.length === 0) { + return "none"; + } + + return comments + .map((comment) => + [ + comment.id, + comment.sectionId, + comment.filePath, + comment.startIndex, + comment.endIndex, + comment.rangeLabel, + comment.text, + ].join("\u001f"), + ) + .join("\u001e"); +} + export function createNativeReviewDiffTheme( scheme: TerminalAppearanceScheme, ): NativeReviewDiffTheme { @@ -83,10 +118,12 @@ export function createNativeReviewDiffTheme( if (scheme === "dark") { return { - background: terminalTheme.background, + // Match the app surface (--color-sheet) so code views blend with the rest of + // the app instead of using a distinct code-editor background. + background: "#0e0e0e", text: terminalTheme.foreground, mutedText: terminalTheme.mutedForeground, - headerBackground: terminalTheme.background, + headerBackground: "#0e0e0e", border: terminalTheme.border, hunkBackground: "#071f28", hunkText: terminalBlue ?? "#009fff", @@ -100,10 +137,12 @@ export function createNativeReviewDiffTheme( } return { - background: "#ffffff", + // Match the app surface (--color-sheet) so code views blend with the rest of the + // app instead of using a distinct code-editor background. + background: "#f2f2f7", text: "#070707", mutedText: terminalTheme.mutedForeground, - headerBackground: "#ffffff", + headerBackground: "#f2f2f7", border: terminalTheme.border, hunkBackground: "#e0f2ff", hunkText: terminalBlue ?? "#009fff", @@ -430,3 +469,26 @@ export function buildNativeReviewDiffData( deletions: parsedDiff.deletions, }; } + +/** + * Reuses the expensive flattened native row model across React development + * render probes and unrelated draft updates. Only the latest comment version + * is retained for each parsed diff so editing a comment cannot grow the cache. + */ +export function getCachedNativeReviewDiffData( + input: BuildNativeReviewDiffDataInput, +): NativeReviewDiffData { + const comments = input.comments ?? []; + const commentsKey = buildReviewCommentsCacheKey(comments); + const cached = nativeReviewDiffDataCache.get(input.parsedDiff); + if (cached?.commentsKey === commentsKey) { + return cached.data; + } + + const data = buildNativeReviewDiffData({ + parsedDiff: input.parsedDiff, + comments, + }); + nativeReviewDiffDataCache.set(input.parsedDiff, { commentsKey, data }); + return data; +} diff --git a/apps/mobile/src/features/review/review-section-menu.test.ts b/apps/mobile/src/features/review/review-section-menu.test.ts new file mode 100644 index 0000000000..7eca4ce3b4 --- /dev/null +++ b/apps/mobile/src/features/review/review-section-menu.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vite-plus/test"; + +import type { ReviewSectionItem, ReviewSectionKind } from "./reviewModel"; +import { buildReviewSectionMenu } from "./review-section-menu"; + +function section(id: string, kind: ReviewSectionKind): ReviewSectionItem { + return { + id, + kind, + title: id, + subtitle: null, + diff: null, + isLoading: false, + }; +} + +describe("buildReviewSectionMenu", () => { + it("exposes git scopes and the latest turn at the top level", () => { + const turn28 = section("turn:28", "turn"); + const turn27 = section("turn:27", "turn"); + const workingTree = section("git:working-tree", "working-tree"); + const branchChanges = section("git:branch-range", "branch-range"); + + expect(buildReviewSectionMenu([turn28, turn27, workingTree, branchChanges])).toEqual({ + workingTree, + branchChanges, + latestTurn: turn28, + turns: [turn28, turn27], + }); + }); + + it("keeps unavailable scopes empty while data loads", () => { + expect(buildReviewSectionMenu([])).toEqual({ + workingTree: null, + branchChanges: null, + latestTurn: null, + turns: [], + }); + }); +}); diff --git a/apps/mobile/src/features/review/review-section-menu.ts b/apps/mobile/src/features/review/review-section-menu.ts new file mode 100644 index 0000000000..87d1026652 --- /dev/null +++ b/apps/mobile/src/features/review/review-section-menu.ts @@ -0,0 +1,21 @@ +import type { ReviewSectionItem } from "./reviewModel"; + +export interface ReviewSectionMenu { + readonly workingTree: ReviewSectionItem | null; + readonly branchChanges: ReviewSectionItem | null; + readonly latestTurn: ReviewSectionItem | null; + readonly turns: ReadonlyArray; +} + +export function buildReviewSectionMenu( + sections: ReadonlyArray, +): ReviewSectionMenu { + const turns = sections.filter((section) => section.kind === "turn"); + + return { + workingTree: sections.find((section) => section.kind === "working-tree") ?? null, + branchChanges: sections.find((section) => section.kind === "branch-range") ?? null, + latestTurn: turns[0] ?? null, + turns, + }; +} diff --git a/apps/mobile/src/features/review/useNativeReviewDiffBridge.test.ts b/apps/mobile/src/features/review/reviewDiffBridgeKeys.test.ts similarity index 96% rename from apps/mobile/src/features/review/useNativeReviewDiffBridge.test.ts rename to apps/mobile/src/features/review/reviewDiffBridgeKeys.test.ts index cb28a30d92..9b39a51dc9 100644 --- a/apps/mobile/src/features/review/useNativeReviewDiffBridge.test.ts +++ b/apps/mobile/src/features/review/reviewDiffBridgeKeys.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { buildNativeReviewTokensResetKey, hashReviewDiffKey } from "./useNativeReviewDiffBridge"; +import { buildNativeReviewTokensResetKey, hashReviewDiffKey } from "./reviewDiffBridgeKeys"; describe("native review diff bridge", () => { it("builds stable reset keys from the rendered diff identity", () => { diff --git a/apps/mobile/src/features/review/reviewDiffBridgeKeys.ts b/apps/mobile/src/features/review/reviewDiffBridgeKeys.ts new file mode 100644 index 0000000000..d04534003b --- /dev/null +++ b/apps/mobile/src/features/review/reviewDiffBridgeKeys.ts @@ -0,0 +1,35 @@ +import type { NativeReviewDiffHighlightScheme } from "../diffs/nativeReviewDiffHighlighter"; + +// Pure key-derivation helpers for the native review diff bridge. Kept free of +// react-native / hook imports so they stay unit-testable in node. + +export function hashReviewDiffKey(diff: string | null | undefined): string { + if (!diff) { + return "empty"; + } + + let hash = 5381; + for (let index = 0; index < diff.length; index += 1) { + hash = (hash * 33) ^ diff.charCodeAt(index); + } + + return `${diff.length}:${(hash >>> 0).toString(36)}`; +} + +export function buildNativeReviewTokensResetKey(input: { + readonly threadKey: string | null; + readonly sectionId: string | null; + readonly scheme: NativeReviewDiffHighlightScheme; + readonly diff: string | null | undefined; + readonly fileCount: number; + readonly rowCount: number; +}): string { + return [ + input.threadKey ?? "none", + input.sectionId ?? "none", + input.scheme, + hashReviewDiffKey(input.diff), + input.fileCount, + input.rowCount, + ].join(":"); +} diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx index 14ff027665..d00cf2be4d 100644 --- a/apps/mobile/src/features/review/reviewDiffRendering.tsx +++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx @@ -13,7 +13,6 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({ }); export const REVIEW_DIFF_LINE_HEIGHT = MOBILE_CODE_SURFACE.rowHeight; -const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2; export function renderVisibleWhitespace(value: string): string { const expandedTabs = value.replace(/\t/g, " "); @@ -38,15 +37,19 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string | return undefined; } -export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) { +export function ReviewChangeBar(props: { + readonly change: ReviewRenderableLineRow["change"]; + readonly height?: number; +}) { + const height = props.height ?? REVIEW_DIFF_LINE_HEIGHT; if (props.change === "delete") { return ( - + - {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => ( + {Array.from({ length: Math.ceil(height / 2) }, (_, index) => ( - - + + ))} @@ -55,7 +58,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo } return ( - + ); @@ -66,7 +69,11 @@ export function DiffTokenText(props: { readonly fallback: string; readonly change?: ReviewRenderableLineRow["change"]; readonly className?: string; + readonly fontSize?: number; + readonly lineHeight?: number; }) { + const fontSize = props.fontSize ?? MOBILE_CODE_SURFACE.fontSize; + const lineHeight = props.lineHeight ?? MOBILE_CODE_SURFACE.rowHeight; if (!props.tokens || props.tokens.length === 0) { return ( {renderVisibleWhitespace(props.fallback || " ")} @@ -91,8 +98,8 @@ export function DiffTokenText(props: { className={cn("font-normal text-foreground", props.className)} style={{ fontFamily: REVIEW_MONO_FONT_FAMILY, - fontSize: MOBILE_CODE_SURFACE.fontSize, - lineHeight: MOBILE_CODE_SURFACE.rowHeight, + fontSize, + lineHeight, }} > {(() => { diff --git a/apps/mobile/src/features/review/reviewPaneSelection.test.ts b/apps/mobile/src/features/review/reviewPaneSelection.test.ts new file mode 100644 index 0000000000..5b1574d8f4 --- /dev/null +++ b/apps/mobile/src/features/review/reviewPaneSelection.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveSelectedReviewFileId } from "./reviewPaneSelection"; + +describe("resolveSelectedReviewFileId", () => { + it("keeps a visible file selected within the active section", () => { + expect( + resolveSelectedReviewFileId({ + selection: { sectionId: "worktree", fileId: "second" }, + sectionId: "worktree", + availableFileIds: ["first", "second"], + }), + ).toBe("second"); + }); + + it("clears selection when the review section changes", () => { + expect( + resolveSelectedReviewFileId({ + selection: { sectionId: "turn-1", fileId: "first" }, + sectionId: "turn-2", + availableFileIds: ["first"], + }), + ).toBeNull(); + }); + + it("clears a file that no longer exists in the diff", () => { + expect( + resolveSelectedReviewFileId({ + selection: { sectionId: "worktree", fileId: "removed" }, + sectionId: "worktree", + availableFileIds: ["first", "second"], + }), + ).toBeNull(); + }); +}); diff --git a/apps/mobile/src/features/review/reviewPaneSelection.ts b/apps/mobile/src/features/review/reviewPaneSelection.ts new file mode 100644 index 0000000000..6f3b7e41c1 --- /dev/null +++ b/apps/mobile/src/features/review/reviewPaneSelection.ts @@ -0,0 +1,16 @@ +export interface ReviewPaneFileSelection { + readonly sectionId: string | null; + readonly fileId: string | null; +} + +export function resolveSelectedReviewFileId(input: { + readonly selection: ReviewPaneFileSelection; + readonly sectionId: string | null; + readonly availableFileIds: ReadonlyArray; +}): string | null { + if (input.selection.sectionId !== input.sectionId || input.selection.fileId === null) { + return null; + } + + return input.availableFileIds.includes(input.selection.fileId) ? input.selection.fileId : null; +} diff --git a/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts b/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts index d0030e51a4..d28e45844f 100644 --- a/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts +++ b/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts @@ -2,43 +2,12 @@ import { useCallback, useMemo, useState } from "react"; import type { NativeSyntheticEvent } from "react-native"; import { type NativeReviewDiffHighlightScheme } from "../diffs/nativeReviewDiffHighlighter"; -import { - createNativeReviewDiffTheme, - NATIVE_REVIEW_DIFF_STYLE, - type NativeReviewDiffData, -} from "./nativeReviewDiffAdapter"; +import { createNativeReviewDiffTheme, type NativeReviewDiffData } from "./nativeReviewDiffAdapter"; +import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface"; import { useNativeReviewDiffHighlighting } from "./useNativeReviewDiffHighlighting"; +import { buildNativeReviewTokensResetKey } from "./reviewDiffBridgeKeys"; -export function hashReviewDiffKey(diff: string | null | undefined): string { - if (!diff) { - return "empty"; - } - - let hash = 5381; - for (let index = 0; index < diff.length; index += 1) { - hash = (hash * 33) ^ diff.charCodeAt(index); - } - - return `${diff.length}:${(hash >>> 0).toString(36)}`; -} - -export function buildNativeReviewTokensResetKey(input: { - readonly threadKey: string | null; - readonly sectionId: string | null; - readonly scheme: NativeReviewDiffHighlightScheme; - readonly diff: string | null | undefined; - readonly fileCount: number; - readonly rowCount: number; -}): string { - return [ - input.threadKey ?? "none", - input.sectionId ?? "none", - input.scheme, - hashReviewDiffKey(input.diff), - input.fileCount, - input.rowCount, - ].join(":"); -} +export { buildNativeReviewTokensResetKey, hashReviewDiffKey } from "./reviewDiffBridgeKeys"; export function useNativeReviewDiffBridge(input: { readonly threadKey: string | null; @@ -62,6 +31,7 @@ export function useNativeReviewDiffBridge(input: { threadKey, viewedFileIds, } = input; + const { nativeReviewDiffStyle } = useAppearanceCodeSurface(); const [collapsedCommentIds, setCollapsedCommentIds] = useState>( () => new Set(), ); @@ -76,7 +46,7 @@ export function useNativeReviewDiffBridge(input: { [collapsedCommentIds], ); const themeJson = useMemo(() => JSON.stringify(theme), [theme]); - const styleJson = useMemo(() => JSON.stringify(NATIVE_REVIEW_DIFF_STYLE), []); + const styleJson = useMemo(() => JSON.stringify(nativeReviewDiffStyle), [nativeReviewDiffStyle]); const tokensResetKey = useMemo( () => buildNativeReviewTokensResetKey({ diff --git a/apps/mobile/src/features/review/useReviewCommentSelectionController.ts b/apps/mobile/src/features/review/useReviewCommentSelectionController.ts index ae1dc6a057..923369a5e9 100644 --- a/apps/mobile/src/features/review/useReviewCommentSelectionController.ts +++ b/apps/mobile/src/features/review/useReviewCommentSelectionController.ts @@ -1,12 +1,11 @@ import { useCallback, useEffect, useMemo, useState } from "react"; import type { NativeSyntheticEvent } from "react-native"; -import { useRouter } from "expo-router"; +import { useNavigation } from "@react-navigation/native"; import * as Arr from "effect/Array"; import { pipe } from "effect/Function"; import * as Result from "effect/Result"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; - import { buildReviewCommentTarget, clearReviewCommentTarget, @@ -34,7 +33,7 @@ export function useReviewCommentSelectionController(input: { readonly nativeReviewDiffData: NativeReviewDiffData; }) { const { environmentId, nativeReviewDiffData, selectedSection, threadId } = input; - const { push } = useRouter(); + const navigation = useNavigation(); const activeCommentTarget = useReviewCommentTarget(); const [pendingNativeCommentSelection, setPendingNativeCommentSelection] = useState(null); @@ -44,11 +43,11 @@ export function useReviewCommentSelectionController(input: { return; } - push({ - pathname: "/threads/[environmentId]/[threadId]/review-comment", - params: { environmentId, threadId }, + navigation.navigate("ThreadReviewComment", { + environmentId, + threadId, }); - }, [environmentId, push, threadId]); + }, [environmentId, navigation, threadId]); const selectedRowIds = useMemo(() => { if ( diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts index ee04673dfc..85aa6b032f 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -1,11 +1,13 @@ import { useEffect, useMemo } from "react"; import { countReviewCommentContexts, parseReviewInlineComments } from "./reviewCommentSelection"; -import { buildNativeReviewDiffData } from "./nativeReviewDiffAdapter"; +import { getCachedNativeReviewDiffData } from "./nativeReviewDiffAdapter"; import { markReviewEvent, measureReviewWork } from "./reviewPerf"; import { getCachedReviewParsedDiff } from "./reviewState"; import type { ReviewParsedDiff, ReviewSectionItem } from "./reviewModel"; +const EMPTY_INLINE_REVIEW_COMMENTS = Object.freeze([]); + function isReviewDiffDebugLoggingEnabled(): boolean { return typeof __DEV__ !== "undefined" ? __DEV__ : false; } @@ -43,6 +45,7 @@ export function useReviewDiffData(input: { readonly draftMessage: string; }) { const { draftMessage, selectedSection, threadKey } = input; + const selectedSectionId = selectedSection?.id ?? null; const parsedDiff = useMemo( () => measureReviewWork("parse-diff", () => @@ -59,17 +62,16 @@ export function useReviewDiffData(input: { () => parseReviewInlineComments(draftMessage), [draftMessage], ); - const selectedSectionInlineComments = useMemo( - () => - selectedSection - ? inlineReviewComments.filter((comment) => comment.sectionId === selectedSection.id) - : [], - [inlineReviewComments, selectedSection], - ); + const selectedSectionInlineComments = useMemo(() => { + if (!selectedSectionId || inlineReviewComments.length === 0) { + return EMPTY_INLINE_REVIEW_COMMENTS; + } + return inlineReviewComments.filter((comment) => comment.sectionId === selectedSectionId); + }, [inlineReviewComments, selectedSectionId]); const nativeReviewDiffData = useMemo( () => measureReviewWork("build-native-diff-data", () => - buildNativeReviewDiffData({ + getCachedNativeReviewDiffData({ parsedDiff, comments: selectedSectionInlineComments, }), diff --git a/apps/mobile/src/features/review/useReviewDiffPrewarming.ts b/apps/mobile/src/features/review/useReviewDiffPrewarming.ts new file mode 100644 index 0000000000..80a2a64dbf --- /dev/null +++ b/apps/mobile/src/features/review/useReviewDiffPrewarming.ts @@ -0,0 +1,101 @@ +import { useEffect } from "react"; + +import { getCachedNativeReviewDiffData } from "./nativeReviewDiffAdapter"; +import type { ReviewSectionItem } from "./reviewModel"; +import { getCachedReviewParsedDiff } from "./reviewState"; + +interface IdleDeadlineLike { + readonly didTimeout: boolean; + timeRemaining(): number; +} + +type IdleCallback = (deadline: IdleDeadlineLike) => void; + +function scheduleIdle(callback: IdleCallback): number { + if (typeof globalThis.requestIdleCallback === "function") { + return globalThis.requestIdleCallback(callback, { timeout: 2_000 }); + } + + return setTimeout( + () => callback({ didTimeout: true, timeRemaining: () => 0 }), + 100, + ) as unknown as number; +} + +function cancelIdle(handle: number): void { + if (typeof globalThis.cancelIdleCallback === "function") { + globalThis.cancelIdleCallback(handle); + return; + } + clearTimeout(handle); +} + +export function prewarmReviewDiffSection(input: { + readonly threadKey: string; + readonly section: ReviewSectionItem; +}): void { + const { section, threadKey } = input; + if (section.diff === null) { + return; + } + + const parsedDiff = getCachedReviewParsedDiff({ + threadKey, + sectionId: section.id, + diff: section.diff, + }); + getCachedNativeReviewDiffData({ parsedDiff, comments: [] }); +} + +/** Warms one cached section per idle period, after navigation animations finish. */ +export function useReviewDiffPrewarming(input: { + readonly threadKey: string | null; + readonly sections: ReadonlyArray; + readonly selectedSectionId: string | null; +}): void { + const { sections, selectedSectionId, threadKey } = input; + + useEffect(() => { + if (!threadKey) { + return; + } + + const pendingSections = sections.filter( + (section) => section.id !== selectedSectionId && section.diff !== null, + ); + if (pendingSections.length === 0) { + return; + } + + let cancelled = false; + let idleHandle: number | null = null; + let nextSectionIndex = 0; + + const scheduleNext = () => { + idleHandle = scheduleIdle(() => { + if (cancelled) { + return; + } + + const section = pendingSections[nextSectionIndex]; + if (!section) { + return; + } + nextSectionIndex += 1; + prewarmReviewDiffSection({ threadKey, section }); + + if (nextSectionIndex < pendingSections.length) { + scheduleNext(); + } + }); + }; + + scheduleNext(); + return () => { + cancelled = true; + if (idleHandle !== null) { + cancelIdle(idleHandle); + } + }; + }, [sections, selectedSectionId, threadKey]); +} diff --git a/apps/mobile/src/features/settings/SettingsAppearanceRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAppearanceRouteScreen.tsx new file mode 100644 index 0000000000..21bcad35e2 --- /dev/null +++ b/apps/mobile/src/features/settings/SettingsAppearanceRouteScreen.tsx @@ -0,0 +1,28 @@ +import { ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { CodeAppearanceSection } from "./appearance/sections/CodeAppearanceSection"; +import { TerminalAppearanceSection } from "./appearance/sections/TerminalAppearanceSection"; +import { TextAppearanceSection } from "./appearance/sections/TextAppearanceSection"; + +export function SettingsAppearanceRouteScreen() { + const insets = useSafeAreaInsets(); + + return ( + + + + + + + + ); +} diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx new file mode 100644 index 0000000000..f6f92f5fc8 --- /dev/null +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx @@ -0,0 +1,39 @@ +import { useAuth } from "@clerk/expo"; +import { AuthView, UserProfileView } from "@clerk/expo/native"; +import { StackActions, useNavigation } from "@react-navigation/native"; +import { NativeStackScreenOptions } from "../../native/StackHeader"; +import { useEffect } from "react"; +import { View } from "react-native"; + +import { hasCloudPublicConfig } from "../cloud/publicConfig"; + +export function SettingsAuthRouteScreen() { + const navigation = useNavigation(); + + useEffect(() => { + if (!hasCloudPublicConfig()) { + navigation.dispatch(StackActions.replace("Settings")); + } + }, [navigation]); + + return hasCloudPublicConfig() ? : null; +} + +function ConfiguredSettingsAuthRouteScreen() { + const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); + + return ( + <> + + + {isLoaded ? ( + isSignedIn ? ( + + ) : ( + + ) + ) : null} + + + ); +} diff --git a/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx new file mode 100644 index 0000000000..9e18d4675f --- /dev/null +++ b/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx @@ -0,0 +1,215 @@ +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { AsyncResult } from "effect/unstable/reactivity"; +import { SymbolView } from "expo-symbols"; +import { useMemo } from "react"; +import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppText as Text } from "../../components/AppText"; +import { useThemeColor } from "../../lib/useThemeColor"; +import { + clearClientCacheAtom, + clientCacheSummaryAtom, + type EnvironmentClientCacheSummary, +} from "../../state/client-cache-state"; +import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; +import { SettingsSection } from "./components/SettingsSection"; + +export function SettingsClientStorageRouteScreen() { + const insets = useSafeAreaInsets(); + const iconColor = useThemeColor("--color-icon"); + const dangerForegroundColor = useThemeColor("--color-danger-foreground"); + const summaryResult = useAtomValue(clientCacheSummaryAtom); + const clearResult = useAtomValue(clearClientCacheAtom); + const clearCache = useAtomSet(clearClientCacheAtom); + const { savedConnectionsById } = useSavedRemoteConnections(); + const isClearing = clearResult.waiting; + const summary = AsyncResult.isSuccess(summaryResult) ? summaryResult.value : null; + const environmentSummaries = useMemo( + () => + [...(summary?.environments ?? [])].sort((left, right) => { + const leftLabel = savedConnectionsById[left.environmentId]?.environmentLabel ?? ""; + const rightLabel = savedConnectionsById[right.environmentId]?.environmentLabel ?? ""; + return leftLabel.localeCompare(rightLabel); + }), + [savedConnectionsById, summary?.environments], + ); + + const confirmClearEnvironment = (environment: EnvironmentClientCacheSummary) => { + const label = + savedConnectionsById[environment.environmentId]?.environmentLabel ?? + environment.environmentId; + Alert.alert( + `Clear cache for ${label}?`, + "This removes offline threads, server metadata, and cached branches for this environment. The saved connection and credentials stay intact.", + [ + { text: "Cancel", style: "cancel" }, + { + text: "Clear Cache", + style: "destructive", + onPress: () => + clearCache({ type: "environment", environmentId: environment.environmentId }), + }, + ], + ); + }; + + const confirmClearAll = () => { + Alert.alert( + "Clear all client caches?", + "This removes offline data for every environment. Connections, credentials, account data, and app preferences stay intact.", + [ + { text: "Cancel", style: "cancel" }, + { + text: "Clear All Caches", + style: "destructive", + onPress: () => clearCache({ type: "all" }), + }, + ], + ); + }; + + return ( + + + + {AsyncResult.isFailure(summaryResult) ? ( + + + Storage unavailable + + Restart the app and try again. + + + ) : !summary ? ( + + + + Inspecting cached data… + + + ) : environmentSummaries.length > 0 ? ( + environmentSummaries.map((environment, index) => ( + confirmClearEnvironment(environment)} + /> + )) + ) : ( + + + No cached data + + Offline cache records will appear here after environments are used. + + + )} + + + + + + + + {summary ? `Clear ${formatBytes(summary.payloadBytes)}` : "Clear caches"} + + {isClearing ? : null} + + + + Clearing caches never removes environment connections, credentials, account data, or + appearance preferences. + + {AsyncResult.isFailure(summaryResult) || AsyncResult.isFailure(clearResult) ? ( + + Client storage is temporarily unavailable. Try again after restarting the app. + + ) : null} + + + + ); +} + +function CacheEnvironmentRow(props: { + readonly environment: EnvironmentClientCacheSummary; + readonly environmentLabel: string; + readonly disabled: boolean; + readonly first: boolean; + readonly onClear: () => void; +}) { + const iconColor = useThemeColor("--color-icon"); + return ( + + + + {props.environmentLabel} + + + + Clear {formatBytes(props.environment.payloadBytes)} + + + + ); +} + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`; +} diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx new file mode 100644 index 0000000000..93b806f648 --- /dev/null +++ b/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx @@ -0,0 +1,179 @@ +import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader"; +import { useNavigation } from "@react-navigation/native"; +import { SymbolView } from "../../components/AppSymbol"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { useCallback, useEffect, useState } from "react"; +import { Platform, ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppText as Text } from "../../components/AppText"; +import { AndroidScreenHeader } from "../../components/AndroidScreenHeader"; +import { hasCloudPublicConfig } from "../cloud/publicConfig"; +import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows"; +import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow"; +import { splitEnvironmentSections } from "../connection/environmentSections"; +import { cn } from "../../lib/cn"; +import { useThemeColor } from "../../lib/useThemeColor"; +import { useRemoteConnections } from "../../state/use-remote-environment-registry"; +import { + applyShowcaseLocalEnvironmentDisplayUrls, + resolveShowcaseEnvironmentUpdateDisplayUrl, + SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS, + SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS, +} from "../showcase/showcaseEnvironmentRows"; +import { markNativeShowcaseReady } from "../showcase/nativeShowcaseScene"; + +const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1"; + +export function SettingsEnvironmentsRouteScreen() { + const { + connectedEnvironments, + onReconnectEnvironment, + onRemoveEnvironmentPress, + onUpdateEnvironment, + } = useRemoteConnections(); + const navigation = useNavigation(); + const insets = useSafeAreaInsets(); + const environmentSections = splitEnvironmentSections({ + connectedEnvironments, + cloudEnvironments: null, + }); + const localEnvironments = SHOWCASE_ENABLED + ? applyShowcaseLocalEnvironmentDisplayUrls(environmentSections.localEnvironments) + : environmentSections.localEnvironments; + const connectedCloudEnvironments = SHOWCASE_ENABLED + ? SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS + : environmentSections.connectedCloudEnvironments; + const hasLocalEnvironments = localEnvironments.length > 0; + const [expandedId, setExpandedId] = useState(null); + const accentColor = useThemeColor("--color-icon-muted"); + const headerIconColor = useThemeColor("--color-icon"); + + useEffect(() => { + if (!SHOWCASE_ENABLED) return; + const timer = setTimeout(() => markNativeShowcaseReady("environments"), 500); + return () => clearTimeout(timer); + }, []); + + const handleToggle = useCallback((environmentId: EnvironmentId) => { + setExpandedId((prev) => (prev === environmentId ? null : environmentId)); + }, []); + const handleUpdateEnvironment = useCallback( + ( + environmentId: EnvironmentId, + updates: { readonly label: string; readonly displayUrl: string }, + ) => { + if (!SHOWCASE_ENABLED) return onUpdateEnvironment(environmentId, updates); + const actualEnvironment = environmentSections.localEnvironments.find( + (environment) => environment.environmentId === environmentId, + ); + const presentedEnvironment = localEnvironments.find( + (environment) => environment.environmentId === environmentId, + ); + return onUpdateEnvironment(environmentId, { + ...updates, + displayUrl: + actualEnvironment && presentedEnvironment + ? resolveShowcaseEnvironmentUpdateDisplayUrl({ + actualDisplayUrl: actualEnvironment.displayUrl, + presentedDisplayUrl: presentedEnvironment.displayUrl, + submittedDisplayUrl: updates.displayUrl, + }) + : updates.displayUrl, + }); + }, + [environmentSections.localEnvironments, localEnvironments, onUpdateEnvironment], + ); + + return ( + + {Platform.OS === "android" ? ( + <> + {/* Android renders its own in-screen header instead of the native bar. */} + + navigation.goBack()} + actions={[ + { + accessibilityLabel: "Add environment", + icon: "plus", + onPress: () => + navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" }), + }, + ]} + /> + + ) : ( + + + navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" }) + } + separateBackground + tintColor={headerIconColor} + /> + + )} + + {hasLocalEnvironments ? ( + + {localEnvironments.map((environment, index) => ( + + handleToggle(environment.environmentId)} + onReconnect={onReconnectEnvironment} + onRemove={onRemoveEnvironmentPress} + onUpdate={handleUpdateEnvironment} + /> + + ))} + + ) : ( + + + + + + No environments connected yet.{"\n"}Tap{" "} + + to add one. + + + )} + + {hasCloudPublicConfig() || SHOWCASE_ENABLED ? ( + + ) : null} + + + ); +} diff --git a/apps/mobile/src/features/settings/SettingsLegalRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsLegalRouteScreen.tsx new file mode 100644 index 0000000000..7254186cf4 --- /dev/null +++ b/apps/mobile/src/features/settings/SettingsLegalRouteScreen.tsx @@ -0,0 +1,6 @@ +import { SettingsLegalDocumentRouteScreen } from "./components/SettingsLegalDocumentRouteScreen"; +import { LEGAL_URL } from "./lib/legal-document-url"; + +export function SettingsLegalRouteScreen() { + return ; +} diff --git a/apps/mobile/src/app/settings/index.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx similarity index 51% rename from apps/mobile/src/app/settings/index.tsx rename to apps/mobile/src/features/settings/SettingsRouteScreen.tsx index 41799ae7b8..6c67a4d89e 100644 --- a/apps/mobile/src/app/settings/index.tsx +++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx @@ -1,11 +1,15 @@ import { useAuth, useUser } from "@clerk/expo"; +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import Constants from "expo-constants"; import * as Notifications from "expo-notifications"; -import { Link, Stack, useRouter } from "expo-router"; -import { SymbolView } from "expo-symbols"; +import * as Updates from "expo-updates"; +import { useNavigation } from "@react-navigation/native"; +import { NativeStackScreenOptions } from "../../native/StackHeader"; +import { SymbolView } from "../../components/AppSymbol"; import * as Effect from "effect/Effect"; -import { useCallback, useEffect, useMemo, useState } from "react"; -import type { ComponentProps, ReactNode } from "react"; -import { Alert, Linking, Pressable, ScrollView, Switch, View } from "react-native"; +import { AsyncResult } from "effect/unstable/reactivity"; +import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react"; +import { Alert, Linking, Platform, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { @@ -15,26 +19,79 @@ import { settlePromise, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; +import { AndroidScreenHeader } from "../../components/AndroidScreenHeader"; import { AppText as Text } from "../../components/AppText"; -import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/liveActivityPreferences"; -import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions"; -import { refreshAgentAwarenessRegistration } from "../../features/agent-awareness/remoteRegistration"; -import { refreshManagedRelayEnvironments } from "../../features/cloud/managedRelayState"; -import { useClerkSettingsSheetDetent } from "../../features/cloud/ClerkSettingsSheetDetent"; +import { supportsAgentAwarenessPush } from "../agent-awareness/capabilities"; +import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences"; +import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions"; import { - hasCloudPublicConfig, - resolveRelayClerkTokenOptions, -} from "../../features/cloud/publicConfig"; + getAgentAwarenessRegistrationStatus, + refreshAgentAwarenessRegistration, + subscribeAgentAwarenessRegistrationStatus, +} from "../agent-awareness/remoteRegistration"; +import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState"; +import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent"; +import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig"; +import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items"; +import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar"; import { runtime } from "../../lib/runtime"; -import { loadPreferences } from "../../lib/storage"; import { useThemeColor } from "../../lib/useThemeColor"; +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; +import { SettingsRow } from "./components/SettingsRow"; +import { SettingsSection } from "./components/SettingsSection"; +import { SettingsSwitchRow } from "./components/SettingsSwitchRow"; type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported"; type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking"; -export default function SettingsRouteScreen() { - return hasCloudPublicConfig() ? : ; +// Reflects whether the relay actually accepted this device's registration. +// The notification and Live Activity switches are gated on this so they can +// never read as enabled when the device cannot receive anything (e.g. the +// registration request timed out). +function useDeviceRegistered(): boolean { + const status = useSyncExternalStore( + subscribeAgentAwarenessRegistrationStatus, + getAgentAwarenessRegistrationStatus, + () => "unknown" as const, + ); + return status === "registered"; +} + +export function SettingsRouteScreen() { + const navigation = useNavigation(); + + return ( + <> + + {Platform.OS === "android" ? ( + <> + {/* Android renders its own in-screen header instead of the native bar. */} + + navigation.goBack()} /> + + ) : ( + [ + withNativeGlassHeaderItem({ + accessibilityLabel: "Close settings", + icon: { name: "xmark", type: "sfSymbol" } as const, + identifier: "settings-close", + label: "", + onPress: () => navigation.goBack(), + type: "button", + }), + ] + : undefined, + }} + /> + )} + {hasCloudPublicConfig() ? : } + + ); } function LocalSettingsRouteScreen() { @@ -44,16 +101,13 @@ function LocalSettingsRouteScreen() { return ( - @@ -61,10 +115,14 @@ function LocalSettingsRouteScreen() { icon="desktopcomputer" label="Environments" value={`${environmentCount}`} - href="/settings/environments" + target="SettingsEnvironments" /> + + + + @@ -74,14 +132,21 @@ function LocalSettingsRouteScreen() { } function ConfiguredSettingsRouteScreen() { + const preferencesResult = useAtomValue(mobilePreferencesAtom); + const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const agentAwarenessPushAvailable = supportsAgentAwarenessPush(); const insets = useSafeAreaInsets(); - const { push } = useRouter(); + const navigation = useNavigation(); const { expand: expandClerkSheet } = useClerkSettingsSheetDetent(); const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); const { user } = useUser(); const { savedConnectionsById } = useSavedRemoteConnections(); const [notificationStatus, setNotificationStatus] = useState("checking"); const [liveActivityStatus, setLiveActivityStatus] = useState("checking"); + const deviceRegistered = useDeviceRegistered(); + const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult) + ? preferencesResult.value.liveActivitiesEnabled !== false + : true; const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]); const environmentCount = connections.length; @@ -118,16 +183,19 @@ function ConfiguredSettingsRouteScreen() { setLiveActivityStatus("signed-out"); return; } - void (async () => { - const result = await settlePromise(() => loadPreferences()); - if (result._tag === "Failure") { - reportAtomCommandResult(result, { label: "live activity preference load" }); + if (!AsyncResult.isSuccess(preferencesResult)) { + if (AsyncResult.isFailure(preferencesResult)) { + reportAtomCommandResult(preferencesResult, { label: "live activity preference load" }); setLiveActivityStatus("enabled"); - return; + } else { + setLiveActivityStatus("checking"); } - setLiveActivityStatus(result.value.liveActivitiesEnabled === false ? "disabled" : "enabled"); - })(); - }, [isLoaded, isSignedIn]); + return; + } + setLiveActivityStatus( + preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled", + ); + }, [isLoaded, isSignedIn, preferencesResult]); const requestNotifications = useCallback(async () => { const result = await settleAsyncResult(() => @@ -151,10 +219,19 @@ function ConfiguredSettingsRouteScreen() { } if (result.value.type === "granted") { setNotificationStatus("enabled"); - Alert.alert( - "Notifications enabled", - "Live Activity notifications are enabled for this device.", - ); + // Permission alone is not enough: the switch stays off until the relay + // registration succeeds, so tell the user the truth about which happened. + if (getAgentAwarenessRegistrationStatus() === "registered") { + Alert.alert( + "Notifications enabled", + "Live Activity notifications are enabled for this device.", + ); + } else { + Alert.alert( + "Couldn't finish enabling notifications", + "Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.", + ); + } return; } if (result.value.type === "unsupported") { @@ -182,14 +259,17 @@ function ConfiguredSettingsRouteScreen() { const promptSignIn = useCallback(() => { Alert.alert( - "Request T3 Cloud access", - "Live Activity updates require approved T3 Cloud access so relay can deliver updates to this device.", + "Request T3 Connect access", + "Live Activity updates require approved T3 Connect access so relay can deliver updates to this device.", [ { text: "Cancel", style: "cancel" }, - { text: "Continue", onPress: () => push("/settings/waitlist") }, + { + text: "Continue", + onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsWaitlist" }), + }, ], ); - }, [push]); + }, [navigation]); const linkEnvironments = useCallback(async () => { if (!isSignedIn) { @@ -218,6 +298,7 @@ function ConfiguredSettingsRouteScreen() { runtime.runPromiseExit( setLiveActivityUpdatesEnabled({ enabled: true, + previousEnabled: liveActivitiesPreferenceEnabled, clerkToken: tokenResult.value, connections, }), @@ -235,15 +316,34 @@ function ConfiguredSettingsRouteScreen() { return; } + savePreferences({ liveActivitiesEnabled: true }); refreshManagedRelayEnvironments(); setLiveActivityStatus("enabled"); - Alert.alert( - "Live Activities enabled", - environmentCount > 0 - ? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.` - : "Live Activity updates are enabled. Add an environment to start receiving updates.", - ); - }, [connections, environmentCount, getToken, isSignedIn, promptSignIn]); + // The environment link can succeed while this device's own registration + // (the push-to-start token the relay needs) has not — don't claim Live + // Activities are live until the device is actually registered. + if (getAgentAwarenessRegistrationStatus() === "registered") { + Alert.alert( + "Live Activities enabled", + environmentCount > 0 + ? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.` + : "Live Activity updates are enabled. Add an environment to start receiving updates.", + ); + } else { + Alert.alert( + "Couldn't finish enabling Live Activities", + "This device could not be registered with T3 Connect, so Live Activities won't appear yet. They'll start once registration succeeds.", + ); + } + }, [ + connections, + environmentCount, + getToken, + isSignedIn, + liveActivitiesPreferenceEnabled, + promptSignIn, + savePreferences, + ]); const handleDeviceNotificationsChange = useCallback( (enabled: boolean) => { @@ -287,17 +387,20 @@ function ConfiguredSettingsRouteScreen() { runtime.runPromiseExit( setLiveActivityUpdatesEnabled({ enabled: false, + previousEnabled: liveActivitiesPreferenceEnabled, clerkToken: token, connections, }), ), ); if (updateResult._tag === "Failure") { + setLiveActivityStatus("enabled"); reportAtomCommandResult(updateResult, { label: "live activity disable", }); return; } + savePreferences({ liveActivitiesEnabled: false }); refreshManagedRelayEnvironments(); })(); return; @@ -310,31 +413,36 @@ function ConfiguredSettingsRouteScreen() { void linkEnvironments(); }, - [connections, getToken, isSignedIn, linkEnvironments, promptSignIn], + [ + connections, + getToken, + isSignedIn, + linkEnvironments, + liveActivitiesPreferenceEnabled, + promptSignIn, + savePreferences, + ], ); const openAccount = useCallback(() => { if (!isLoaded) return; if (!isSignedIn) { - push("/settings/waitlist"); + navigation.navigate("SettingsSheet", { screen: "SettingsWaitlist" }); return; } expandClerkSheet(); - push("/settings/auth"); - }, [expandClerkSheet, isLoaded, isSignedIn, push]); + navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }); + }, [expandClerkSheet, isLoaded, isSignedIn, navigation]); return ( - @@ -346,7 +454,7 @@ function ConfiguredSettingsRouteScreen() { onPress={openAccount} /> - + T3 Code works locally without signing in. Cloud features are optional. @@ -356,26 +464,48 @@ function ConfiguredSettingsRouteScreen() { icon="desktopcomputer" label="Environments" value={`${environmentCount}`} - href="/settings/environments" + target="SettingsEnvironments" /> + + + + @@ -384,27 +514,30 @@ function ConfiguredSettingsRouteScreen() { ); } -type SymbolName = ComponentProps["name"]; - -function SettingsSection(props: { readonly title: string; readonly children: ReactNode }) { - return ( - - {props.title} - - {props.children} - - - ); -} - function AppSettingsSection() { const icon = useThemeColor("--color-icon"); + const version = Constants.expoConfig?.version ?? "0.0.0"; + // Fall back to "production" to match resolveAppVariant in app.config.ts, so a + // missing variant never mislabels a production build as development. + const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production"; + const variantLabel = variant === "production" ? "" : capitalize(variant); + const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version; + // Which JS is actually running: the bundle shipped in the binary, or an OTA + // update downloaded on top of it. Surfacing this makes "am I even on the + // right build?" answerable at a glance. + const bundleLabel = Updates.isEnabled + ? Updates.isEmbeddedLaunch + ? "Embedded" + : Updates.updateId + ? `OTA ${Updates.updateId.slice(0, 7)}` + : null + : null; + return ( + + Version - Alpha + + {versionLabel} + {bundleLabel ? ( + {bundleLabel} + ) : null} + ); } +function capitalize(value: string): string { + return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value; +} + function ArchivedThreadsSettingsSection() { return ( - + ); } - -function SettingsRow(props: { - readonly disabled?: boolean; - readonly icon: SymbolName; - readonly label: string; - readonly value?: string; - readonly href?: "/settings/archive" | "/settings/environments"; - readonly onPress?: () => void; -}) { - const icon = useThemeColor("--color-icon"); - const chevron = useThemeColor("--color-chevron"); - const content = ( - - - - {props.label} - - - {props.value ? ( - - {props.value} - - ) : null} - - - - ); - - if (props.href) { - return ( - - - {content} - - - ); - } - - return ( - - {content} - - ); -} - -function SettingsSwitchRow(props: { - readonly disabled?: boolean; - readonly icon: SymbolName; - readonly label: string; - readonly value: boolean; - readonly onValueChange: (value: boolean) => void; -}) { - const icon = useThemeColor("--color-icon"); - const activeTrack = String(useThemeColor("--color-switch-active")); - const track = String(useThemeColor("--color-secondary-border")); - - return ( - - - {props.label} - - - ); -} diff --git a/apps/mobile/src/app/settings/waitlist.tsx b/apps/mobile/src/features/settings/SettingsWaitlistRouteScreen.tsx similarity index 52% rename from apps/mobile/src/app/settings/waitlist.tsx rename to apps/mobile/src/features/settings/SettingsWaitlistRouteScreen.tsx index 3fc2fad269..f5182307eb 100644 --- a/apps/mobile/src/app/settings/waitlist.tsx +++ b/apps/mobile/src/features/settings/SettingsWaitlistRouteScreen.tsx @@ -1,36 +1,41 @@ import { useAuth } from "@clerk/expo"; -import { Redirect, Stack, useFocusEffect, useRouter } from "expo-router"; +import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native"; import { useCallback } from "react"; import { ScrollView } from "react-native"; -import { CloudWaitlistEnrollment } from "../../features/cloud/CloudWaitlistEnrollment"; -import { useClerkSettingsSheetDetent } from "../../features/cloud/ClerkSettingsSheetDetent"; -import { hasCloudPublicConfig } from "../../features/cloud/publicConfig"; +import { CloudWaitlistEnrollment } from "../cloud/CloudWaitlistEnrollment"; +import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent"; +import { hasCloudPublicConfig } from "../cloud/publicConfig"; -export default function SettingsWaitlistRouteScreen() { - return hasCloudPublicConfig() ? ( - - ) : ( - +export function SettingsWaitlistRouteScreen() { + const navigation = useNavigation(); + + useFocusEffect( + useCallback(() => { + if (!hasCloudPublicConfig()) { + navigation.dispatch(StackActions.replace("Settings")); + } + }, [navigation]), ); + + return hasCloudPublicConfig() ? : null; } function ConfiguredSettingsWaitlistRouteScreen() { const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); const { expand } = useClerkSettingsSheetDetent(); - const router = useRouter(); + const navigation = useNavigation(); useFocusEffect( useCallback(() => { if (isLoaded && isSignedIn) { - router.replace("/settings"); + navigation.dispatch(StackActions.replace("Settings")); } - }, [isLoaded, isSignedIn, router]), + }, [isLoaded, isSignedIn, navigation]), ); return ( <> - { expand(); - router.push("/settings/auth"); + navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }); }} /> diff --git a/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx new file mode 100644 index 0000000000..7eaafc0e9e --- /dev/null +++ b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx @@ -0,0 +1,126 @@ +import { createContext, use, useCallback, useEffect, useMemo, type ReactNode } from "react"; + +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { AsyncResult } from "effect/unstable/reactivity"; + +import { Uniwind } from "uniwind"; + +import { + resolveAppearance, + resolveAppearancePreferences, + resolveTextScaleVariables, + type AppearancePreferences, + type ResolvedAppearance, +} from "../../../lib/appearancePreferences"; +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences"; +import { cacheTerminalFontSize } from "../../terminal/terminalUiState"; + +interface AppearancePreferencesContextValue { + /** Effective values with base-size derivation applied. Use this for rendering. */ + readonly appearance: ResolvedAppearance; + readonly isReady: boolean; + readonly setBaseFontSize: (value: number) => void; + /** Pass null to clear the override and follow the base font size. */ + readonly setTerminalFontSize: (value: number | null) => void; + /** Pass null to clear the override and follow the base font size. */ + readonly setCodeFontSize: (value: number | null) => void; + readonly setCodeWordBreak: (value: boolean) => void; +} + +const AppearancePreferencesContext = createContext(null); + +/** + * Injects the scaled `--text-*` variables into Uniwind so every + * className-based text size (`text-sm`, `text-base`, ...) re-resolves live. + * Updates the current theme last so the active stylesheet settles correctly. + */ +function applyTextScaleVariables(baseFontSize: number) { + const variables = resolveTextScaleVariables(baseFontSize); + const currentTheme = Uniwind.currentTheme; + + for (const theme of ["light", "dark"] as const) { + if (theme !== currentTheme) { + Uniwind.updateCSSVariables(theme, variables); + } + } + Uniwind.updateCSSVariables(currentTheme, variables); +} + +export function AppearancePreferencesProvider(props: { readonly children: ReactNode }) { + const preferencesResult = useAtomValue(mobilePreferencesAtom); + const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const preferences = useMemo( + () => + resolveAppearancePreferences( + AsyncResult.isSuccess(preferencesResult) ? preferencesResult.value : null, + ), + [preferencesResult], + ); + const isReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting; + + useEffect(() => { + applyTextScaleVariables(preferences.baseFontSize); + cacheTerminalFontSize(resolveAppearance(preferences).terminalFontSize); + }, [preferences]); + + const updatePreferences = useCallback( + (patch: Partial) => { + savePreferences(patch); + }, + [savePreferences], + ); + + const setBaseFontSize = useCallback( + (value: number) => { + updatePreferences({ baseFontSize: value }); + }, + [updatePreferences], + ); + + const setTerminalFontSize = useCallback( + (value: number | null) => { + updatePreferences({ terminalFontSize: value }); + }, + [updatePreferences], + ); + + const setCodeFontSize = useCallback( + (value: number | null) => { + updatePreferences({ codeFontSize: value }); + }, + [updatePreferences], + ); + + const setCodeWordBreak = useCallback( + (value: boolean) => { + updatePreferences({ codeWordBreak: value }); + }, + [updatePreferences], + ); + + const value = useMemo( + (): AppearancePreferencesContextValue => ({ + appearance: resolveAppearance(preferences), + isReady, + setBaseFontSize, + setTerminalFontSize, + setCodeFontSize, + setCodeWordBreak, + }), + [preferences, isReady, setBaseFontSize, setTerminalFontSize, setCodeFontSize, setCodeWordBreak], + ); + + return ( + + {props.children} + + ); +} + +export function useAppearancePreferences(): AppearancePreferencesContextValue { + const context = use(AppearancePreferencesContext); + if (!context) { + throw new Error("useAppearancePreferences must be used within AppearancePreferencesProvider"); + } + return context; +} diff --git a/apps/mobile/src/features/settings/appearance/components/AppearancePreviews.tsx b/apps/mobile/src/features/settings/appearance/components/AppearancePreviews.tsx new file mode 100644 index 0000000000..fe96010963 --- /dev/null +++ b/apps/mobile/src/features/settings/appearance/components/AppearancePreviews.tsx @@ -0,0 +1,177 @@ +import { Platform, ScrollView, View, useColorScheme } from "react-native"; + +import { AppText as Text } from "../../../../components/AppText"; +import { + resolveMarkdownFontSizes, + resolveMobileCodeSurface, +} from "../../../../lib/appearancePreferences"; +import { useThemeColor } from "../../../../lib/useThemeColor"; +import { getPierreTerminalTheme } from "../../../terminal/terminalTheme"; + +const CODE_FONT_FAMILY = Platform.select({ + ios: "ui-monospace", + android: "monospace", + default: "monospace", +}); + +/** Hairline between a section's preview surface and its control rows. */ +export function AppearancePreviewSeparator() { + return ; +} + +/** Live sample of body text rendered at the chosen base font size. */ +export function TextAppearancePreview(props: { readonly fontSize: number }) { + const sizes = resolveMarkdownFontSizes(props.fontSize); + + return ( + + + The quick brown fox jumps over the lazy dog. + + + Messages, labels, and headings scale with this size. + + + ); +} + +/** + * Live terminal sample using the real terminal theme's text colors and font, + * on the shared card background so it reads like the other previews. + */ +export function TerminalAppearancePreview(props: { readonly fontSize: number }) { + const scheme = useColorScheme() === "light" ? "light" : "dark"; + const theme = getPierreTerminalTheme(scheme); + const lineHeight = Math.round(props.fontSize * 1.6); + const lineStyle = { + fontFamily: "Menlo", + fontSize: props.fontSize, + lineHeight, + } as const; + + return ( + + $ npm run dev + ✓ Ready in 430ms + + Local: http://localhost:3000{" "} + ▏ + + + ); +} + +interface CodePreviewToken { + readonly text: string; + readonly keyword?: boolean; +} + +interface CodePreviewLine { + readonly id: string; + readonly tokens: ReadonlyArray; +} + +const CODE_PREVIEW_LINES: ReadonlyArray = [ + { + id: "signature", + tokens: [{ text: "function", keyword: true }, { text: " formatUser(user) {" }], + }, + { + id: "body", + tokens: [ + { text: " " }, + { text: "return", keyword: true }, + { text: " `${user.name} <${user.email}>` // demonstrates how long lines behave" }, + ], + }, + { id: "close", tokens: [{ text: "}" }] }, +]; + +/** + * Live code sample matching the code & diff surface metrics. Long lines wrap + * when word break is on and scroll horizontally when it is off, mirroring the + * real code surface. + */ +export function CodeAppearancePreview(props: { + readonly fontSize: number; + readonly wordBreak: boolean; +}) { + const surface = resolveMobileCodeSurface(props.fontSize); + const lineNumberColor = useThemeColor("--color-icon-subtle"); + const keywordColor = useThemeColor("--color-md-link"); + + const lineNumber = (line: CodePreviewLine, index: number) => ( + + {index + 1} + + ); + + const codeLine = (line: CodePreviewLine, wrap: boolean) => ( + + {line.tokens.map((token) => ( + + {token.text} + + ))} + + ); + + if (props.wordBreak) { + return ( + + {CODE_PREVIEW_LINES.map((line, index) => ( + + {lineNumber(line, index)} + {codeLine(line, true)} + + ))} + + ); + } + + return ( + + {CODE_PREVIEW_LINES.map((line, index) => lineNumber(line, index))} + + {CODE_PREVIEW_LINES.map((line) => codeLine(line, false))} + + + ); +} diff --git a/apps/mobile/src/features/settings/appearance/components/FontSizeSliderRow.tsx b/apps/mobile/src/features/settings/appearance/components/FontSizeSliderRow.tsx new file mode 100644 index 0000000000..c0e46d248e --- /dev/null +++ b/apps/mobile/src/features/settings/appearance/components/FontSizeSliderRow.tsx @@ -0,0 +1,214 @@ +import * as Haptics from "expo-haptics"; +import { SymbolView } from "../../../../components/AppSymbol"; +import { useCallback, useEffect, useMemo, useRef } from "react"; +import { View, type AccessibilityActionEvent } from "react-native"; +import { Gesture, GestureDetector } from "react-native-gesture-handler"; +import Animated, { + runOnJS, + useAnimatedStyle, + useSharedValue, + withTiming, +} from "react-native-reanimated"; +import type { ComponentProps } from "react"; + +import { AppText as Text } from "../../../../components/AppText"; +import { useThemeColor } from "../../../../lib/useThemeColor"; + +type SymbolName = ComponentProps["name"]; + +const THUMB_SIZE = 26; +const TRACK_HEIGHT = 4; +const SNAP_ANIMATION = { duration: 120 } as const; + +function clampFraction(value: number): number { + "worklet"; + return Math.min(1, Math.max(0, value)); +} + +export function FontSizeSliderRow(props: { + readonly disabled?: boolean; + readonly icon: SymbolName; + readonly label: string; + readonly valueLabel: string; + readonly min: number; + readonly max: number; + readonly step: number; + readonly value: number; + readonly onChange: (value: number) => void; +}) { + const icon = useThemeColor("--color-icon"); + const iconMuted = String(useThemeColor("--color-icon-muted")); + const trackColor = String(useThemeColor("--color-secondary-border")); + const fillColor = String(useThemeColor("--color-primary")); + + const latest = useRef(props); + latest.current = props; + + const { min, max, step, value, disabled } = props; + const fraction = (value - min) / (max - min); + + const progress = useSharedValue(clampFraction(fraction)); + const trackWidth = useSharedValue(0); + const dragging = useSharedValue(false); + + useEffect(() => { + if (!dragging.value) { + progress.value = withTiming(clampFraction(fraction), SNAP_ANIMATION); + } + }, [dragging, fraction, progress]); + + const commit = useCallback((next: number) => { + if (next === latest.current.value) { + return; + } + Haptics.selectionAsync().catch(() => undefined); + latest.current.onChange(next); + }, []); + + const gesture = useMemo(() => { + const snapValue = (raw: number): number => { + "worklet"; + const stepped = Math.round((raw - min) / step) * step + min; + return Math.min(max, Math.max(min, stepped)); + }; + const fractionAt = (x: number): number => { + "worklet"; + const usable = trackWidth.value - THUMB_SIZE; + if (usable <= 0) { + return 0; + } + return clampFraction((x - THUMB_SIZE / 2) / usable); + }; + const valueAtFraction = (f: number): number => { + "worklet"; + return snapValue(min + f * (max - min)); + }; + const fractionOfValue = (v: number): number => { + "worklet"; + return clampFraction((v - min) / (max - min)); + }; + + const pan = Gesture.Pan() + .enabled(!disabled) + .activeOffsetX([-8, 8]) + .failOffsetY([-12, 12]) + .onUpdate((event) => { + dragging.value = true; + const f = fractionAt(event.x); + progress.value = f; + runOnJS(commit)(valueAtFraction(f)); + }) + .onFinalize(() => { + if (!dragging.value) { + return; + } + dragging.value = false; + progress.value = withTiming( + fractionOfValue(valueAtFraction(progress.value)), + SNAP_ANIMATION, + ); + }); + + const tap = Gesture.Tap() + .enabled(!disabled) + .onEnd((event) => { + const next = valueAtFraction(fractionAt(event.x)); + progress.value = withTiming(fractionOfValue(next), SNAP_ANIMATION); + runOnJS(commit)(next); + }); + + return Gesture.Race(pan, tap); + }, [commit, disabled, dragging, max, min, progress, step, trackWidth]); + + const fillStyle = useAnimatedStyle(() => ({ + width: THUMB_SIZE / 2 + progress.value * Math.max(0, trackWidth.value - THUMB_SIZE), + })); + const thumbStyle = useAnimatedStyle(() => ({ + transform: [{ translateX: progress.value * Math.max(0, trackWidth.value - THUMB_SIZE) }], + })); + + const handleAccessibilityAction = (event: AccessibilityActionEvent) => { + if (event.nativeEvent.actionName === "increment") { + commit(Math.min(max, value + step)); + } else if (event.nativeEvent.actionName === "decrement") { + commit(Math.max(min, value - step)); + } + }; + + return ( + + + + {props.label} + {props.valueLabel} + + + + + { + trackWidth.value = event.nativeEvent.layout.width; + }} + > + + + + + + + + + + ); +} diff --git a/apps/mobile/src/features/settings/appearance/sections/CodeAppearanceSection.tsx b/apps/mobile/src/features/settings/appearance/sections/CodeAppearanceSection.tsx new file mode 100644 index 0000000000..bb4bb4d0a8 --- /dev/null +++ b/apps/mobile/src/features/settings/appearance/sections/CodeAppearanceSection.tsx @@ -0,0 +1,64 @@ +import { useCallback } from "react"; + +import { + CODE_FONT_SIZE_STEP, + MAX_CODE_FONT_SIZE, + MIN_CODE_FONT_SIZE, +} from "../../../../lib/appearancePreferences"; +import { SettingsSection } from "../../components/SettingsSection"; +import { SettingsSwitchRow } from "../../components/SettingsSwitchRow"; +import { useAppearancePreferences } from "../AppearancePreferencesProvider"; +import { + AppearancePreviewSeparator, + CodeAppearancePreview, +} from "../components/AppearancePreviews"; +import { FontSizeSliderRow } from "../components/FontSizeSliderRow"; + +export function CodeAppearanceSection() { + const { isReady, appearance, setCodeFontSize, setCodeWordBreak } = useAppearancePreferences(); + const custom = appearance.isCodeFontSizeCustom; + + const handleToggleCustom = useCallback( + (enabled: boolean) => { + setCodeFontSize(enabled ? appearance.codeFontSize : null); + }, + [appearance.codeFontSize, setCodeFontSize], + ); + + return ( + + + + + {custom ? ( + + ) : null} + + + ); +} diff --git a/apps/mobile/src/features/settings/appearance/sections/TerminalAppearanceSection.tsx b/apps/mobile/src/features/settings/appearance/sections/TerminalAppearanceSection.tsx new file mode 100644 index 0000000000..911e6c307e --- /dev/null +++ b/apps/mobile/src/features/settings/appearance/sections/TerminalAppearanceSection.tsx @@ -0,0 +1,54 @@ +import { useCallback } from "react"; + +import { + MAX_TERMINAL_FONT_SIZE, + MIN_TERMINAL_FONT_SIZE, + TERMINAL_FONT_SIZE_STEP, +} from "../../../../lib/appearancePreferences"; +import { SettingsSection } from "../../components/SettingsSection"; +import { SettingsSwitchRow } from "../../components/SettingsSwitchRow"; +import { useAppearancePreferences } from "../AppearancePreferencesProvider"; +import { + AppearancePreviewSeparator, + TerminalAppearancePreview, +} from "../components/AppearancePreviews"; +import { FontSizeSliderRow } from "../components/FontSizeSliderRow"; + +export function TerminalAppearanceSection() { + const { isReady, appearance, setTerminalFontSize } = useAppearancePreferences(); + const custom = appearance.isTerminalFontSizeCustom; + + const handleToggleCustom = useCallback( + (enabled: boolean) => { + setTerminalFontSize(enabled ? appearance.terminalFontSize : null); + }, + [appearance.terminalFontSize, setTerminalFontSize], + ); + + return ( + + + + + {custom ? ( + + ) : null} + + ); +} diff --git a/apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx b/apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx new file mode 100644 index 0000000000..6617a75720 --- /dev/null +++ b/apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx @@ -0,0 +1,34 @@ +import { + BASE_FONT_SIZE_STEP, + MAX_BASE_FONT_SIZE, + MIN_BASE_FONT_SIZE, +} from "../../../../lib/appearancePreferences"; +import { SettingsSection } from "../../components/SettingsSection"; +import { useAppearancePreferences } from "../AppearancePreferencesProvider"; +import { + AppearancePreviewSeparator, + TextAppearancePreview, +} from "../components/AppearancePreviews"; +import { FontSizeSliderRow } from "../components/FontSizeSliderRow"; + +export function TextAppearanceSection() { + const { isReady, appearance, setBaseFontSize } = useAppearancePreferences(); + + return ( + + + + + + ); +} diff --git a/apps/mobile/src/features/settings/appearance/useAppearanceCodeSurface.ts b/apps/mobile/src/features/settings/appearance/useAppearanceCodeSurface.ts new file mode 100644 index 0000000000..62760f1e43 --- /dev/null +++ b/apps/mobile/src/features/settings/appearance/useAppearanceCodeSurface.ts @@ -0,0 +1,34 @@ +import { useMemo } from "react"; + +import { + resolveMobileCodeSurface, + type ResolvedMobileCodeSurface, +} from "../../../lib/appearancePreferences"; +import { createNativeReviewDiffStyle } from "../../review/nativeReviewDiffAdapter"; +import { createNativeSourceStyle } from "../../files/nativeSourceFileAdapter"; +import { useAppearancePreferences } from "./AppearancePreferencesProvider"; + +export function useAppearanceCodeSurface(): { + readonly codeSurface: ResolvedMobileCodeSurface; + readonly codeWordBreak: boolean; + readonly nativeSourceStyle: ReturnType; + readonly nativeReviewDiffStyle: ReturnType; +} { + const { appearance } = useAppearancePreferences(); + const codeSurface = useMemo( + () => resolveMobileCodeSurface(appearance.codeFontSize), + [appearance.codeFontSize], + ); + const nativeSourceStyle = useMemo(() => createNativeSourceStyle(codeSurface), [codeSurface]); + const nativeReviewDiffStyle = useMemo( + () => createNativeReviewDiffStyle(codeSurface), + [codeSurface], + ); + + return { + codeSurface, + codeWordBreak: appearance.codeWordBreak, + nativeSourceStyle, + nativeReviewDiffStyle, + }; +} diff --git a/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts b/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts new file mode 100644 index 0000000000..4224740c26 --- /dev/null +++ b/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts @@ -0,0 +1,36 @@ +import { useCSSVariable } from "uniwind"; + +import { MOBILE_TYPOGRAPHY } from "../../../lib/typography"; + +const TEXT_ROLE_VARIABLES = { + micro: "--text-3xs", + caption: "--text-2xs", + label: "--text-xs", + footnote: "--text-sm", + body: "--text-base", + headline: "--text-lg", + title: "--text-xl", + largeTitle: "--text-2xl", + display: "--text-3xl", +} as const satisfies Record; + +export interface ScaledTextRole { + readonly fontSize: number; + readonly lineHeight: number; +} + +/** + * Reads a typography role's current size from the Uniwind `--text-*` CSS + * variables (scaled at runtime with the base font size). Use for style-prop + * consumers that can't express their size as a `text-*` className. Reactive: + * re-renders when the appearance provider re-injects the variables. + */ +export function useScaledTextRole(role: keyof typeof MOBILE_TYPOGRAPHY): ScaledTextRole { + const variable = TEXT_ROLE_VARIABLES[role]; + const [fontSize, lineHeight] = useCSSVariable([variable, `${variable}--line-height`]); + + return { + fontSize: typeof fontSize === "number" ? fontSize : MOBILE_TYPOGRAPHY[role].fontSize, + lineHeight: typeof lineHeight === "number" ? lineHeight : MOBILE_TYPOGRAPHY[role].lineHeight, + }; +} diff --git a/apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx b/apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx new file mode 100644 index 0000000000..aa5303b9a8 --- /dev/null +++ b/apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx @@ -0,0 +1,186 @@ +import { type NavigationProp, type ParamListBase, useNavigation } from "@react-navigation/native"; +import { useCallback, useLayoutEffect, useState } from "react"; +import { ActivityIndicator, Linking, Pressable, View } from "react-native"; +import { WebView } from "react-native-webview"; + +import { AppText as Text } from "../../../components/AppText"; +import { LoadingStrip } from "../../../components/LoadingStrip"; +import { SymbolView } from "../../../components/AppSymbol"; +import { useThemeColor } from "../../../lib/useThemeColor"; +import { isLegalDocumentUrl, LEGAL_URL } from "../lib/legal-document-url"; + +export function SettingsLegalDocumentCloseHeaderButton() { + const navigation = useNavigation(); + const iconColor = useThemeColor("--color-icon"); + + return ( + navigation.goBack()} + className="p-2 active:opacity-60" + > + + + ); +} + +export function SettingsLegalDocumentExternalHeaderButton({ + externalUrl = LEGAL_URL, +}: { + readonly externalUrl?: string; +}) { + const iconColor = useThemeColor("--color-icon"); + const safeExternalUrl = isLegalDocumentUrl(externalUrl) ? externalUrl : LEGAL_URL; + + return ( + void Linking.openURL(safeExternalUrl).catch(() => undefined)} + className="p-2 active:opacity-60" + > + + + ); +} + +interface SettingsLegalDocumentRouteScreenProps { + readonly documentName: string; + readonly documentUrl: string; +} + +export function SettingsLegalDocumentRouteScreen({ + documentName, + documentUrl, +}: SettingsLegalDocumentRouteScreenProps) { + const navigation = useNavigation>(); + const iconColor = useThemeColor("--color-icon"); + const [reloadKey, setReloadKey] = useState(0); + const [loadProgress, setLoadProgress] = useState(0); + const [loadError, setLoadError] = useState(null); + const [externalUrl, setExternalUrl] = useState(documentUrl); + const renderExternalHeaderButton = useCallback( + () => , + [externalUrl], + ); + + useLayoutEffect(() => { + navigation.setOptions({ + headerRight: renderExternalHeaderButton, + }); + }, [navigation, renderExternalHeaderButton]); + + const openExternalUrl = useCallback((url: string) => { + void Linking.openURL(url).catch(() => undefined); + }, []); + if (loadError) { + return ( + + + + + Couldn't load the {documentName.toLowerCase()} + + + {loadError} + + + + { + setLoadError(null); + setReloadKey((value) => value + 1); + }} + className="items-center rounded-xl bg-foreground px-4 py-3 active:opacity-80" + > + Try Again + + openExternalUrl(documentUrl)} + className="items-center rounded-xl px-4 py-3 active:bg-foreground/5" + > + Open in Browser + + + + ); + } + + return ( + + {loadProgress > 0 && loadProgress < 1 ? : null} + { + if (isLegalDocumentUrl(request.url)) return true; + + openExternalUrl(request.url); + return false; + }} + onLoadProgress={(event) => { + setLoadProgress(event.nativeEvent.progress); + }} + onLoadStart={() => { + setLoadProgress(0.05); + setLoadError(null); + }} + onLoadEnd={(event) => { + if (isLegalDocumentUrl(event.nativeEvent.url)) { + setExternalUrl(event.nativeEvent.url); + } + setLoadProgress(0); + }} + onError={(event) => { + setLoadProgress(0); + setLoadError(event.nativeEvent.description || "The page could not be loaded."); + }} + onHttpError={(event) => { + if (!isLegalDocumentUrl(event.nativeEvent.url)) return; + setLoadProgress(0); + setLoadError(`The server returned status ${event.nativeEvent.statusCode}.`); + }} + renderLoading={() => ( + + + + )} + style={{ flex: 1, backgroundColor: "transparent" }} + /> + + ); +} diff --git a/apps/mobile/src/features/settings/components/SettingsRow.tsx b/apps/mobile/src/features/settings/components/SettingsRow.tsx new file mode 100644 index 0000000000..2f435c3a47 --- /dev/null +++ b/apps/mobile/src/features/settings/components/SettingsRow.tsx @@ -0,0 +1,95 @@ +import { useNavigation } from "@react-navigation/native"; +import type { ComponentProps } from "react"; +import { Pressable, View } from "react-native"; + +import { SymbolView } from "../../../components/AppSymbol"; + +import { AppText as Text } from "../../../components/AppText"; +import { useThemeColor } from "../../../lib/useThemeColor"; +import type { SettingsLegalDocumentTarget, SettingsSheetTarget } from "./settings-sheet-targets"; + +type SymbolName = ComponentProps["name"]; + +export function SettingsRow(props: { + readonly disabled?: boolean; + readonly icon: SymbolName; + readonly label: string; + readonly value?: string; + readonly target?: SettingsSheetTarget; + readonly fullScreenTarget?: SettingsLegalDocumentTarget; + readonly onPress?: () => void; +}) { + const navigation = useNavigation(); + const icon = useThemeColor("--color-icon"); + const chevron = useThemeColor("--color-chevron"); + const content = ( + + + + {props.label} + + + {props.value ? ( + + {props.value} + + ) : null} + + + + ); + + const target = props.target; + if (target) { + return ( + + navigation.navigate("SettingsSheet", { + screen: target, + }) + } + > + {content} + + ); + } + + const fullScreenTarget = props.fullScreenTarget; + if (fullScreenTarget) { + return ( + navigation.navigate(fullScreenTarget)} + > + {content} + + ); + } + + return ( + + {content} + + ); +} diff --git a/apps/mobile/src/features/settings/components/SettingsSection.tsx b/apps/mobile/src/features/settings/components/SettingsSection.tsx new file mode 100644 index 0000000000..9c87561a8e --- /dev/null +++ b/apps/mobile/src/features/settings/components/SettingsSection.tsx @@ -0,0 +1,26 @@ +import type { ReactNode } from "react"; +import { View } from "react-native"; + +import { AppText as Text } from "../../../components/AppText"; + +export function SettingsSection(props: { + readonly title: string; + readonly children: ReactNode; + /** Force the grouped card background; Android otherwise lists options flat. */ + readonly card?: boolean; +}) { + return ( + + {props.title} + + {props.children} + + + ); +} diff --git a/apps/mobile/src/features/settings/components/SettingsSwitchRow.tsx b/apps/mobile/src/features/settings/components/SettingsSwitchRow.tsx new file mode 100644 index 0000000000..38d707e231 --- /dev/null +++ b/apps/mobile/src/features/settings/components/SettingsSwitchRow.tsx @@ -0,0 +1,40 @@ +import type { ComponentProps } from "react"; +import { Switch, View } from "react-native"; + +import { SymbolView } from "../../../components/AppSymbol"; +import { AppText as Text } from "../../../components/AppText"; +import { useThemeColor } from "../../../lib/useThemeColor"; + +type SymbolName = ComponentProps["name"]; + +export function SettingsSwitchRow(props: { + readonly disabled?: boolean; + readonly icon: SymbolName; + readonly label: string; + readonly value: boolean; + readonly onValueChange: (value: boolean) => void; +}) { + const icon = useThemeColor("--color-icon"); + const activeTrack = String(useThemeColor("--color-switch-active")); + const track = String(useThemeColor("--color-secondary-border")); + + return ( + + + {props.label} + + + ); +} diff --git a/apps/mobile/src/features/settings/components/settings-sheet-targets.ts b/apps/mobile/src/features/settings/components/settings-sheet-targets.ts new file mode 100644 index 0000000000..71c059bedb --- /dev/null +++ b/apps/mobile/src/features/settings/components/settings-sheet-targets.ts @@ -0,0 +1,7 @@ +export type SettingsSheetTarget = + | "SettingsEnvironments" + | "SettingsArchive" + | "SettingsAppearance" + | "SettingsClientStorage"; + +export type SettingsLegalDocumentTarget = "SettingsLegal"; diff --git a/apps/mobile/src/features/settings/lib/legal-document-url.test.ts b/apps/mobile/src/features/settings/lib/legal-document-url.test.ts new file mode 100644 index 0000000000..10ce4ca487 --- /dev/null +++ b/apps/mobile/src/features/settings/lib/legal-document-url.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { isLegalDocumentUrl } from "./legal-document-url"; + +describe("isLegalDocumentUrl", () => { + it.each([ + "https://t3.codes/legal", + "https://t3.codes/legal/", + "https://t3.codes/privacy-policy?source=app", + "https://t3.codes/terms-of-service#updates", + "https://t3.codes/security-policy", + ])("allows a configured legal document: %s", (url) => { + expect(isLegalDocumentUrl(url)).toBe(true); + }); + + it.each([ + "https://t3.codes/download", + "https://example.com/legal", + "javascript:alert(1)", + "not-a-url", + ])("rejects a URL outside the legal-document allowlist: %s", (url) => { + expect(isLegalDocumentUrl(url)).toBe(false); + }); +}); diff --git a/apps/mobile/src/features/settings/lib/legal-document-url.ts b/apps/mobile/src/features/settings/lib/legal-document-url.ts new file mode 100644 index 0000000000..4556375615 --- /dev/null +++ b/apps/mobile/src/features/settings/lib/legal-document-url.ts @@ -0,0 +1,58 @@ +const DEFAULT_MARKETING_SITE_URL = "https://t3.codes"; + +function resolveMarketingSiteUrl(override: string | undefined): URL { + try { + const url = new URL(override?.trim() || DEFAULT_MARKETING_SITE_URL); + if (url.protocol !== "https:" && url.protocol !== "http:") { + return new URL(DEFAULT_MARKETING_SITE_URL); + } + + url.search = ""; + url.hash = ""; + url.pathname = `${url.pathname.replace(/\/+$/, "")}/`; + return url; + } catch { + return new URL(DEFAULT_MARKETING_SITE_URL); + } +} + +const MARKETING_SITE_URL = resolveMarketingSiteUrl(process.env.EXPO_PUBLIC_MARKETING_SITE_URL); + +function marketingSiteDocumentUrl(path: string): string { + return new URL(path, MARKETING_SITE_URL).toString(); +} + +export const PRIVACY_POLICY_URL = marketingSiteDocumentUrl("privacy-policy"); +export const SECURITY_POLICY_URL = marketingSiteDocumentUrl("security-policy"); +export const TERMS_OF_SERVICE_URL = marketingSiteDocumentUrl("terms-of-service"); +export const LEGAL_URL = marketingSiteDocumentUrl("legal"); + +export const ALLOWED_LEGAL_DOCUMENT_URLS = [ + LEGAL_URL, + PRIVACY_POLICY_URL, + TERMS_OF_SERVICE_URL, + SECURITY_POLICY_URL, +] as const; + +function webDocumentIdentity(value: string): string | null { + try { + const url = new URL(value); + if (url.protocol !== "https:" && url.protocol !== "http:") return null; + + const pathname = url.pathname.replace(/\/+$/, "") || "/"; + return `${url.origin}${pathname}`; + } catch { + return null; + } +} + +const ALLOWED_LEGAL_DOCUMENT_IDENTITIES = new Set( + ALLOWED_LEGAL_DOCUMENT_URLS.map(webDocumentIdentity).filter( + (value): value is string => value !== null, + ), +); + +export function isLegalDocumentUrl(value: string): boolean { + const identity = webDocumentIdentity(value); + return identity !== null && ALLOWED_LEGAL_DOCUMENT_IDENTITIES.has(identity); +} diff --git a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx new file mode 100644 index 0000000000..04d371e5d2 --- /dev/null +++ b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx @@ -0,0 +1,310 @@ +import Constants from "expo-constants"; +import * as Crypto from "expo-crypto"; +import { + clearSharedPayloads, + getResolvedSharedPayloadsAsync, + getSharedPayloads, + type ResolvedSharePayload, + type SharePayload, +} from "expo-sharing"; +import React, { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react"; +import { Alert, AppState, Platform } from "react-native"; + +import { + buildIncomingShareDraft, + type IncomingShareDestination, + type IncomingShareDraft, +} from "./incoming-share-model"; +import { IncomingShareInbox } from "./incoming-share-inbox"; +import { + loadIncomingShareDrafts, + removeIncomingShareDraft, + writeIncomingShareDraft, +} from "./incoming-share-storage"; + +type IncomingShareContextValue = { + readonly pendingShare: IncomingShareDraft | null; + readonly isLoading: boolean; + readonly error: Error | null; + readonly getShare: (shareId: string) => IncomingShareDraft | null; + readonly reserveShare: (shareId: string, destination: IncomingShareDestination) => Promise; + readonly releaseShareReservation: ( + shareId: string, + expectedDestination: IncomingShareDestination, + ) => Promise; + readonly consumeShare: (shareId: string) => Promise; + readonly refresh: () => Promise; +}; + +const IncomingShareContext = React.createContext(null); + +function receiveSharingEnabled(): boolean { + if (Platform.OS === "android") { + return true; + } + if (Platform.OS !== "ios") { + return false; + } + return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true; +} + +async function resolvedPayloadsForImages(): Promise> { + try { + return await getResolvedSharedPayloadsAsync(); + } catch (error) { + // iOS already gives the containing app a copied file:// URL, so raw + // payloads remain usable. Android normally resolves content:// into a + // private cache file; its modern File API can still read the raw URI when + // resolution fails. + console.warn("[incoming-share] could not resolve shared file metadata", error); + return []; + } +} + +async function incomingShareIdForPayloads(payloads: ReadonlyArray): Promise { + const fingerprint = JSON.stringify( + payloads.map((payload) => ({ + shareType: payload.shareType, + mimeType: payload.mimeType ?? null, + value: payload.value, + })), + ); + const digest = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, fingerprint); + return `share-${digest}`; +} + +async function readBase64(uri: string): Promise { + const { File } = await import("expo-file-system"); + return new File(uri).base64(); +} + +async function removeOwnedFile(uri: string): Promise { + if (!uri.startsWith("file:")) { + return; + } + try { + const { File } = await import("expo-file-system"); + const file = new File(uri); + if (file.exists) { + file.delete(); + } + } catch (error) { + console.warn("[incoming-share] could not remove temporary shared file", error); + } +} + +async function removeReplayedImagePayloadFiles( + payloads: ReadonlyArray, +): Promise { + const uris = new Set(); + for (const payload of payloads) { + if (payload.shareType === "image") { + uris.add(payload.value); + } + } + if (uris.size === 0) { + return; + } + const resolvedPayloads = await resolvedPayloadsForImages(); + for (const payload of resolvedPayloads) { + if (payload.shareType === "image" && payload.contentUri) { + uris.add(payload.contentUri); + } + } + await Promise.all([...uris].map(removeOwnedFile)); +} + +// Keep one operation queue across provider remounts (including development +// Strict Mode remounts) so two app lifecycle notifications cannot ingest the +// same native handoff independently. +const incomingShareInbox = new IncomingShareInbox({ + loadDrafts: loadIncomingShareDrafts, + writeDraft: writeIncomingShareDraft, + removeDraft: removeIncomingShareDraft, + getPayloads: getSharedPayloads, + clearPayloads: clearSharedPayloads, + buildDraft: async ({ payloads, id, createdAt }) => { + const cleanupUris = new Set(); + const resolvedPayloads = payloads.some((payload) => payload.shareType === "image") + ? await resolvedPayloadsForImages() + : []; + const draft = await buildIncomingShareDraft({ + payloads, + resolvedPayloads, + fileReader: { + readBase64, + removeOwnedFile: (uri) => { + cleanupUris.add(uri); + }, + }, + id, + createdAt, + }); + return { + draft, + cleanup: async () => { + await Promise.all([...cleanupUris].map(removeOwnedFile)); + }, + }; + }, + cleanupReplayedPayloads: removeReplayedImagePayloadFiles, + idForPayloads: incomingShareIdForPayloads, + now: () => new Date().toISOString(), + onClearError: (error) => { + console.warn("[incoming-share] could not acknowledge native payload", error); + }, + onCleanupError: (error) => { + console.warn("[incoming-share] could not remove temporary shared file", error); + }, +}); + +export function IncomingShareProvider(props: React.PropsWithChildren) { + const enabled = receiveSharingEnabled(); + const [drafts, setDrafts] = useState>([]); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + const refreshPromiseRef = useRef | null>(null); + const mountedRef = useRef(false); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; + }, []); + + const refresh = useCallback(async () => { + if (refreshPromiseRef.current) { + return refreshPromiseRef.current; + } + + const operation = (async () => { + try { + const snapshot = await incomingShareInbox.refresh({ ingestNative: enabled }); + if (mountedRef.current) { + setDrafts(snapshot); + setError(null); + } + } catch (cause) { + const persisted = await incomingShareInbox + .refresh({ ingestNative: false }) + .catch(() => null); + if (mountedRef.current) { + if (persisted) { + setDrafts(persisted); + } + setError(cause instanceof Error ? cause : new Error("Could not import shared content.")); + } + } + })().finally(() => { + refreshPromiseRef.current = null; + }); + + refreshPromiseRef.current = operation; + return operation; + }, [enabled]); + + useEffect(() => { + void refresh().finally(() => { + if (mountedRef.current) { + setIsLoading(false); + } + }); + }, [refresh]); + + const refreshOnAppActive = useEffectEvent(() => { + void refresh(); + }); + + useEffect(() => { + if (!enabled) { + return; + } + const subscription = AppState.addEventListener("change", (state) => { + if (state === "active") { + refreshOnAppActive(); + } + }); + return () => subscription.remove(); + }, [enabled]); + + useEffect(() => { + if (!error) { + return; + } + Alert.alert("Could not import shared content", error.message, [ + { text: "Dismiss", style: "cancel", onPress: () => setError(null) }, + { + text: "Retry", + onPress: () => { + setError(null); + void refresh(); + }, + }, + ]); + }, [error, refresh]); + + const consumeShare = useCallback(async (shareId: string) => { + const snapshot = await incomingShareInbox.consume(shareId); + if (mountedRef.current) { + setDrafts(snapshot); + } + }, []); + const reserveShare = useCallback( + async (shareId: string, destination: IncomingShareDestination) => { + const snapshot = await incomingShareInbox.reserve(shareId, destination); + if (mountedRef.current) { + setDrafts(snapshot); + } + }, + [], + ); + const releaseShareReservation = useCallback( + async (shareId: string, expectedDestination: IncomingShareDestination) => { + const snapshot = await incomingShareInbox.releaseReservation(shareId, expectedDestination); + if (mountedRef.current) { + setDrafts(snapshot); + } + }, + [], + ); + const getShare = useCallback( + (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null, + [drafts], + ); + + const value = useMemo( + () => ({ + pendingShare: drafts[0] ?? null, + isLoading, + error, + getShare, + releaseShareReservation, + reserveShare, + consumeShare, + refresh, + }), + [ + consumeShare, + drafts, + error, + getShare, + isLoading, + refresh, + releaseShareReservation, + reserveShare, + ], + ); + + return ( + {props.children} + ); +} + +export function useIncomingShare(): IncomingShareContextValue { + const value = React.use(IncomingShareContext); + if (value === null) { + throw new Error("useIncomingShare must be used within IncomingShareProvider."); + } + return value; +} diff --git a/apps/mobile/src/features/sharing/incoming-share-inbox.test.ts b/apps/mobile/src/features/sharing/incoming-share-inbox.test.ts new file mode 100644 index 0000000000..ff50c6a917 --- /dev/null +++ b/apps/mobile/src/features/sharing/incoming-share-inbox.test.ts @@ -0,0 +1,236 @@ +import { describe, expect, it, vi } from "@effect/vitest"; +import type { SharePayload } from "expo-sharing"; + +import type { IncomingShareDraft } from "./incoming-share-model"; +import { IncomingShareInbox, type IncomingShareInboxDependencies } from "./incoming-share-inbox"; + +const PAYLOAD: SharePayload = { + shareType: "text", + mimeType: "text/plain", + value: "Fix this", +}; + +function draft(id: string, createdAt = "2026-07-16T08:00:00.000Z"): IncomingShareDraft { + return { + schemaVersion: 1, + id, + createdAt, + text: PAYLOAD.value, + attachments: [], + warnings: [], + }; +} + +function deferred() { + let resolve!: () => void; + const promise = new Promise((next) => { + resolve = next; + }); + return { promise, resolve }; +} + +function createHarness(overrides: Partial = {}) { + const persisted = new Map(); + let payloads: ReadonlyArray = [PAYLOAD]; + const dependencies: IncomingShareInboxDependencies = { + loadDrafts: async () => [...persisted.values()], + writeDraft: async (value) => { + persisted.set(value.id, value); + }, + removeDraft: async (shareId) => { + persisted.delete(shareId); + }, + getPayloads: () => payloads, + clearPayloads: () => { + payloads = []; + }, + buildDraft: async ({ id, createdAt }) => ({ + draft: draft(id, createdAt), + cleanup: async () => undefined, + }), + idForPayloads: async () => "share-stable", + now: () => "2026-07-16T08:00:00.000Z", + ...overrides, + }; + return { inbox: new IncomingShareInbox(dependencies), persisted }; +} + +describe("IncomingShareInbox", () => { + it("coalesces a replay of an already-persisted native handoff", async () => { + const buildDraft = vi.fn(async ({ id, createdAt }) => ({ + draft: draft(id, createdAt), + cleanup: async () => undefined, + })); + const cleanupReplayedPayloads = vi.fn(async () => undefined); + const { inbox, persisted } = createHarness({ buildDraft, cleanupReplayedPayloads }); + persisted.set("share-stable", draft("share-stable")); + + await expect(inbox.refresh({ ingestNative: true })).resolves.toEqual([draft("share-stable")]); + expect(buildDraft).not.toHaveBeenCalled(); + expect(cleanupReplayedPayloads).toHaveBeenCalledWith([PAYLOAD]); + }); + + it("serializes concurrent refreshes so one native payload creates one inbox item", async () => { + const building = deferred(); + const buildDraft = vi.fn(async ({ id, createdAt }) => { + await building.promise; + return { draft: draft(id, createdAt), cleanup: async () => undefined }; + }); + const { inbox } = createHarness({ buildDraft }); + + const first = inbox.refresh({ ingestNative: true }); + const second = inbox.refresh({ ingestNative: true }); + building.resolve(); + + await expect(Promise.all([first, second])).resolves.toEqual([ + [draft("share-stable")], + [draft("share-stable")], + ]); + expect(buildDraft).toHaveBeenCalledTimes(1); + }); + + it("orders consumption after an in-flight refresh without restoring stale state", async () => { + const building = deferred(); + const { inbox, persisted } = createHarness({ + buildDraft: async ({ id, createdAt }) => { + await building.promise; + return { draft: draft(id, createdAt), cleanup: async () => undefined }; + }, + }); + + const refresh = inbox.refresh({ ingestNative: true }); + const consume = inbox.consume("share-stable"); + building.resolve(); + + await expect(refresh).resolves.toEqual([draft("share-stable")]); + await expect(consume).resolves.toEqual([]); + expect([...persisted.values()]).toEqual([]); + }); + + it("consumes only the addressed share when another share has identical content", async () => { + const { inbox, persisted } = createHarness(); + persisted.set("share-first", draft("share-first", "2026-07-16T07:59:00.000Z")); + persisted.set("share-second", draft("share-second")); + + await expect(inbox.refresh({ ingestNative: false })).resolves.toEqual([ + draft("share-second"), + draft("share-first", "2026-07-16T07:59:00.000Z"), + ]); + await expect(inbox.consume("share-second")).resolves.toEqual([ + draft("share-first", "2026-07-16T07:59:00.000Z"), + ]); + expect([...persisted.values()]).toEqual([draft("share-first", "2026-07-16T07:59:00.000Z")]); + }); + + it("keeps content-identical shares addressable by their own ids", async () => { + const { inbox, persisted } = createHarness(); + persisted.set("share-open-flow", draft("share-open-flow", "2026-07-16T07:59:00.000Z")); + persisted.set("share-newer", draft("share-newer")); + + await expect(inbox.refresh({ ingestNative: false })).resolves.toEqual([ + draft("share-newer"), + draft("share-open-flow", "2026-07-16T07:59:00.000Z"), + ]); + }); + + it("does not acknowledge a supported payload when its durable write fails", async () => { + const clearPayloads = vi.fn(); + const cleanup = vi.fn(async () => undefined); + const { inbox } = createHarness({ + clearPayloads, + buildDraft: async ({ id, createdAt }) => ({ + draft: draft(id, createdAt), + cleanup, + }), + writeDraft: async () => { + throw new Error("disk full"); + }, + }); + + await expect(inbox.refresh({ ingestNative: true })).rejects.toThrow("disk full"); + expect(clearPayloads).not.toHaveBeenCalled(); + expect(cleanup).not.toHaveBeenCalled(); + }); + + it("durably reserves a share for one project before draft import", async () => { + const { inbox, persisted } = createHarness(); + persisted.set("share-stable", draft("share-stable")); + const destination = { environmentId: "environment-1", projectId: "project-1" }; + + await expect(inbox.reserve("share-stable", destination)).resolves.toEqual([ + { ...draft("share-stable"), destination }, + ]); + expect(persisted.get("share-stable")?.destination).toEqual(destination); + await expect(inbox.reserve("share-stable", destination)).resolves.toEqual([ + { ...draft("share-stable"), destination }, + ]); + }); + + it("rejects moving a reserved share to another project", async () => { + const { inbox, persisted } = createHarness(); + persisted.set("share-stable", { + ...draft("share-stable"), + destination: { environmentId: "environment-1", projectId: "project-1" }, + }); + + await expect( + inbox.reserve("share-stable", { + environmentId: "environment-1", + projectId: "project-2", + }), + ).rejects.toThrow("already reserved"); + expect(persisted.get("share-stable")?.destination?.projectId).toBe("project-1"); + }); + + it("conditionally releases a reservation when its project is unavailable", async () => { + const { inbox, persisted } = createHarness(); + const destination = { environmentId: "environment-1", projectId: "project-1" }; + persisted.set("share-stable", { ...draft("share-stable"), destination }); + + await expect(inbox.releaseReservation("share-stable", destination)).resolves.toEqual([ + draft("share-stable"), + ]); + expect(persisted.get("share-stable")?.destination).toBeUndefined(); + + await expect( + inbox.reserve("share-stable", { + environmentId: "environment-2", + projectId: "project-2", + }), + ).resolves.toEqual([ + { + ...draft("share-stable"), + destination: { environmentId: "environment-2", projectId: "project-2" }, + }, + ]); + }); + + it("does not release a reservation that changed concurrently", async () => { + const { inbox, persisted } = createHarness(); + persisted.set("share-stable", { + ...draft("share-stable"), + destination: { environmentId: "environment-2", projectId: "project-2" }, + }); + + await expect( + inbox.releaseReservation("share-stable", { + environmentId: "environment-1", + projectId: "project-1", + }), + ).rejects.toThrow("reservation changed"); + expect(persisted.get("share-stable")?.destination?.projectId).toBe("project-2"); + }); + + it("treats an already-removed share as an already-released reservation", async () => { + const { inbox, persisted } = createHarness(); + persisted.set("share-other", draft("share-other")); + + await expect( + inbox.releaseReservation("share-stable", { + environmentId: "environment-1", + projectId: "project-1", + }), + ).resolves.toEqual([draft("share-other")]); + expect([...persisted.values()]).toEqual([draft("share-other")]); + }); +}); diff --git a/apps/mobile/src/features/sharing/incoming-share-inbox.ts b/apps/mobile/src/features/sharing/incoming-share-inbox.ts new file mode 100644 index 0000000000..1f61ea710b --- /dev/null +++ b/apps/mobile/src/features/sharing/incoming-share-inbox.ts @@ -0,0 +1,193 @@ +import type { SharePayload } from "expo-sharing"; + +import { SerializedAsyncQueue } from "../../lib/serialized-async-queue"; +import { + hasIncomingShareContent, + type IncomingShareDestination, + type IncomingShareDraft, +} from "./incoming-share-model"; + +export interface IncomingShareInboxDependencies { + readonly loadDrafts: () => Promise>; + readonly writeDraft: (draft: IncomingShareDraft) => Promise; + readonly removeDraft: (shareId: string) => Promise; + readonly getPayloads: () => ReadonlyArray; + readonly clearPayloads: () => void; + readonly buildDraft: (input: { + readonly payloads: ReadonlyArray; + readonly id: string; + readonly createdAt: string; + }) => Promise<{ + readonly draft: IncomingShareDraft; + readonly cleanup: () => Promise; + }>; + readonly cleanupReplayedPayloads?: (payloads: ReadonlyArray) => Promise; + readonly idForPayloads: (payloads: ReadonlyArray) => Promise; + readonly now: () => string; + readonly onClearError?: (error: unknown) => void; + readonly onCleanupError?: (error: unknown) => void; +} + +export function sortAndDedupeIncomingShares( + drafts: ReadonlyArray, +): ReadonlyArray { + const ids = new Set(); + return [...drafts] + .sort((left, right) => right.createdAt.localeCompare(left.createdAt)) + .filter((draft) => { + if (ids.has(draft.id)) { + return false; + } + ids.add(draft.id); + return true; + }); +} + +/** + * Serializes every durable inbox mutation. This prevents a stale storage load + * or a foreground refresh from restoring an item after it has been consumed. + */ +export class IncomingShareInbox { + private readonly operations = new SerializedAsyncQueue(); + + constructor(private readonly dependencies: IncomingShareInboxDependencies) {} + + private runExclusive(operation: () => Promise): Promise { + return this.operations.run(operation); + } + + private clearNativePayloads(): void { + try { + this.dependencies.clearPayloads(); + } catch (error) { + this.dependencies.onClearError?.(error); + } + } + + private async cleanup(operation: () => Promise): Promise { + try { + await operation(); + } catch (error) { + this.dependencies.onCleanupError?.(error); + } + } + + refresh(options: { readonly ingestNative: boolean }): Promise> { + return this.runExclusive(async () => { + const loaded = await this.dependencies.loadDrafts(); + const persisted = sortAndDedupeIncomingShares(loaded); + if (!options.ingestNative) { + return persisted; + } + + const payloads = this.dependencies.getPayloads(); + if (payloads.length === 0) { + return persisted; + } + + // A share extension payload remains available until the containing app + // acknowledges it. Use a content-derived id so a crash after the durable + // write but before acknowledgement reuses the same inbox item. + const shareId = await this.dependencies.idForPayloads(payloads); + if (loaded.some((draft) => draft.id === shareId)) { + if (this.dependencies.cleanupReplayedPayloads) { + await this.cleanup(() => this.dependencies.cleanupReplayedPayloads!(payloads)); + } + this.clearNativePayloads(); + return persisted; + } + + const built = await this.dependencies.buildDraft({ + payloads, + id: shareId, + createdAt: this.dependencies.now(), + }); + const { draft } = built; + if (!hasIncomingShareContent(draft)) { + // Unsupported native payloads cannot become actionable on retry and + // would otherwise reopen the project picker on every foreground. + await this.cleanup(built.cleanup); + this.clearNativePayloads(); + throw new Error( + draft.warnings[0] ?? "The shared content is not supported by the composer.", + ); + } + + // The durable inbox write is the transaction boundary. Never clear the + // native handoff first: a process termination must leave one recoverable + // copy on one side of the boundary. + await this.dependencies.writeDraft(draft); + await this.cleanup(built.cleanup); + this.clearNativePayloads(); + return sortAndDedupeIncomingShares([draft, ...persisted]); + }); + } + + consume(shareId: string): Promise> { + return this.runExclusive(async () => { + // The stable payload-derived id already coalesces retries of the same + // native handoff. Payload equality cannot identify duplicate handoffs: + // users may intentionally share identical content more than once. + await this.dependencies.removeDraft(shareId); + return sortAndDedupeIncomingShares(await this.dependencies.loadDrafts()); + }); + } + + reserve( + shareId: string, + destination: IncomingShareDestination, + ): Promise> { + return this.runExclusive(async () => { + const persisted = await this.dependencies.loadDrafts(); + const target = persisted.find((draft) => draft.id === shareId); + if (!target) { + throw new Error("The shared content is no longer available."); + } + if (target.destination) { + if ( + target.destination.environmentId !== destination.environmentId || + target.destination.projectId !== destination.projectId + ) { + throw new Error("The shared content is already reserved for another project draft."); + } + return sortAndDedupeIncomingShares(persisted); + } + + const reserved = { ...target, destination }; + await this.dependencies.writeDraft(reserved); + return sortAndDedupeIncomingShares( + persisted.map((draft) => (draft.id === shareId ? reserved : draft)), + ); + }); + } + + releaseReservation( + shareId: string, + expectedDestination: IncomingShareDestination, + ): Promise> { + return this.runExclusive(async () => { + const persisted = await this.dependencies.loadDrafts(); + const target = persisted.find((draft) => draft.id === shareId); + if (!target) { + // Conditional release is idempotent: if another operation already + // consumed the share, no reservation remains to clean up. + return sortAndDedupeIncomingShares(persisted); + } + if (!target.destination) { + return sortAndDedupeIncomingShares(persisted); + } + if ( + target.destination.environmentId !== expectedDestination.environmentId || + target.destination.projectId !== expectedDestination.projectId + ) { + throw new Error("The shared content reservation changed before it could be released."); + } + + const { destination: _destination, ...unreserved } = target; + await this.dependencies.writeDraft(unreserved); + return sortAndDedupeIncomingShares( + persisted.map((draft) => (draft.id === shareId ? unreserved : draft)), + ); + }); + } +} diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts new file mode 100644 index 0000000000..07ede18b8e --- /dev/null +++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts @@ -0,0 +1,196 @@ +import { describe, expect, it, vi } from "@effect/vitest"; +import { + PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, +} from "@t3tools/contracts"; +import type { ResolvedSharePayload, SharePayload } from "expo-sharing"; + +import { buildIncomingShareDraft, hasIncomingShareContent } from "./incoming-share-model"; + +describe("incoming native shares", () => { + it("converts shared text, URLs, and images into a durable composer draft", async () => { + const image: SharePayload = { + shareType: "image", + value: "file:///shared/Screenshot.png", + mimeType: "image/png", + }; + const payloads: SharePayload[] = [ + { shareType: "text", value: "Please explain this error" }, + { shareType: "url", value: "https://example.com/issue/1" }, + { shareType: "text", value: "Please explain this error" }, + image, + ]; + const resolvedImage: ResolvedSharePayload = { + ...image, + contentUri: image.value, + contentType: "image", + contentMimeType: "image/png", + contentSize: 3, + originalName: "Screenshot.png", + }; + const removeOwnedFile = vi.fn(() => Promise.resolve()); + + const result = await buildIncomingShareDraft({ + id: "share-1", + createdAt: "2026-07-15T10:00:00.000Z", + payloads, + resolvedPayloads: [resolvedImage], + fileReader: { + readBase64: async () => "YWJj", + removeOwnedFile, + }, + }); + + expect(result).toEqual({ + schemaVersion: 1, + id: "share-1", + createdAt: "2026-07-15T10:00:00.000Z", + text: "Please explain this error\n\nhttps://example.com/issue/1", + attachments: [ + { + id: "share-1:image:3", + type: "image", + name: "Screenshot.png", + mimeType: "image/png", + sizeBytes: 3, + dataUrl: "data:image/png;base64,YWJj", + previewUri: "data:image/png;base64,YWJj", + }, + ], + warnings: [], + }); + expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + expect(hasIncomingShareContent(result)).toBe(true); + }); + + it("skips oversized images and releases the temporary native file", async () => { + const image: SharePayload = { + shareType: "image", + value: "file:///shared/huge.png", + mimeType: "image/png", + }; + const readBase64 = vi.fn(async () => "unused"); + const removeOwnedFile = vi.fn(() => Promise.resolve()); + + const result = await buildIncomingShareDraft({ + id: "share-2", + createdAt: "2026-07-15T10:00:00.000Z", + payloads: [image], + resolvedPayloads: [ + { + ...image, + contentUri: image.value, + contentType: "image", + contentMimeType: "image/png", + contentSize: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, + originalName: "huge.png", + }, + ], + fileReader: { readBase64, removeOwnedFile }, + }); + + expect(result.attachments).toEqual([]); + expect(result.warnings).toEqual(["'huge.png' exceeds the 10 MB attachment limit."]); + expect(readBase64).not.toHaveBeenCalled(); + expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + expect(hasIncomingShareContent(result)).toBe(false); + }); + + it("releases every temporary file when a share exceeds the attachment limit", async () => { + const payloads = Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS + 1 }, (_, index) => ({ + shareType: "image" as const, + value: `file:///shared/${index}.png`, + mimeType: "image/png", + })); + const removeOwnedFile = vi.fn(() => Promise.resolve()); + const readBase64 = vi.fn(async () => "YWJj"); + + const result = await buildIncomingShareDraft({ + id: "share-3", + createdAt: "2026-07-15T10:00:00.000Z", + payloads, + resolvedPayloads: [], + fileReader: { readBase64, removeOwnedFile }, + }); + + expect(result.attachments).toHaveLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS); + expect(result.warnings).toEqual([ + `Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared images were attached.`, + ]); + expect(readBase64).toHaveBeenCalledTimes(PROVIDER_SEND_TURN_MAX_ATTACHMENTS); + expect(removeOwnedFile).toHaveBeenCalledTimes(payloads.length); + }); + + it("maps duplicate image payloads to distinct resolved files", async () => { + const duplicate: SharePayload = { + shareType: "image", + value: "content://shared/screenshot", + mimeType: "image/png", + }; + const resolvedPayloads: ResolvedSharePayload[] = [ + { + ...duplicate, + contentUri: "file:///cache/first.png", + contentType: "image", + contentMimeType: "image/png", + contentSize: 3, + originalName: "first.png", + }, + { + ...duplicate, + contentUri: "file:///cache/second.png", + contentType: "image", + contentMimeType: "image/png", + contentSize: 3, + originalName: "second.png", + }, + ]; + const readBase64 = vi.fn(async (uri: string) => + uri.includes("first") ? "Zmlyc3Q=" : "c2Vjb25k", + ); + const removeOwnedFile = vi.fn(async () => undefined); + + const result = await buildIncomingShareDraft({ + id: "share-duplicates", + createdAt: "2026-07-16T08:00:00.000Z", + payloads: [duplicate, duplicate], + resolvedPayloads, + fileReader: { readBase64, removeOwnedFile }, + }); + + expect(readBase64.mock.calls.map(([uri]) => uri)).toEqual([ + "file:///cache/first.png", + "file:///cache/second.png", + ]); + expect(result.attachments.map((attachment) => attachment.name)).toEqual([ + "first.png", + "second.png", + ]); + expect(removeOwnedFile).toHaveBeenCalledWith("file:///cache/first.png"); + expect(removeOwnedFile).toHaveBeenCalledWith("file:///cache/second.png"); + }); + + it("keeps imported content when temporary-file cleanup fails", async () => { + const image: SharePayload = { + shareType: "image", + value: "file:///shared/screenshot.png", + mimeType: "image/png", + }; + + const result = await buildIncomingShareDraft({ + id: "share-cleanup-failure", + createdAt: "2026-07-16T08:00:00.000Z", + payloads: [image], + resolvedPayloads: [], + fileReader: { + readBase64: async () => "YWJj", + removeOwnedFile: async () => { + throw new Error("file is busy"); + }, + }, + }); + + expect(result.attachments).toHaveLength(1); + expect(result.warnings).toEqual([]); + }); +}); diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts new file mode 100644 index 0000000000..873574209f --- /dev/null +++ b/apps/mobile/src/features/sharing/incoming-share-model.ts @@ -0,0 +1,217 @@ +import { + PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, +} from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import type { ResolvedSharePayload, SharePayload } from "expo-sharing"; + +import { DraftComposerImageAttachmentSchema } from "../../lib/composer-image-schema"; +import type { DraftComposerImageAttachment } from "../../lib/composerImages"; +import { estimateBase64ByteSize } from "../../lib/base64"; + +export interface IncomingShareDraft { + readonly schemaVersion: 1; + readonly id: string; + readonly createdAt: string; + readonly destination?: IncomingShareDestination; + readonly text: string; + readonly attachments: ReadonlyArray; + readonly warnings: ReadonlyArray; +} + +export interface IncomingShareDestination { + readonly environmentId: string; + readonly projectId: string; +} + +const IncomingShareDestinationSchema = Schema.Struct({ + environmentId: Schema.String, + projectId: Schema.String, +}); + +export const IncomingShareDraftSchema = Schema.Struct({ + schemaVersion: Schema.Literal(1), + id: Schema.String, + createdAt: Schema.String, + destination: Schema.optional(IncomingShareDestinationSchema), + text: Schema.String, + attachments: Schema.Array(DraftComposerImageAttachmentSchema), + warnings: Schema.Array(Schema.String), +}); + +const decodeIncomingShareDraftSync = Schema.decodeUnknownSync(IncomingShareDraftSchema); + +export function decodeIncomingShareDraft(value: unknown): IncomingShareDraft { + return decodeIncomingShareDraftSync(value); +} + +export interface IncomingShareFileReader { + readonly readBase64: (uri: string) => Promise; + readonly removeOwnedFile: (uri: string) => Promise | void; +} + +function sharedText(payloads: ReadonlyArray): string { + const seen = new Set(); + const values: string[] = []; + for (const payload of payloads) { + if (payload.shareType !== "text" && payload.shareType !== "url") { + continue; + } + const value = payload.value.trim(); + if (!value || seen.has(value)) { + continue; + } + seen.add(value); + values.push(value); + } + return values.join("\n\n"); +} + +function resolvedImageFor( + payload: SharePayload, + index: number, + resolvedPayloads: ReadonlyArray, + consumedIndexes: Set, +): ResolvedSharePayload | undefined { + const sameIndex = resolvedPayloads[index]; + if ( + !consumedIndexes.has(index) && + sameIndex?.shareType === payload.shareType && + sameIndex.value === payload.value + ) { + consumedIndexes.add(index); + return sameIndex; + } + const matchingIndex = resolvedPayloads.findIndex( + (candidate, candidateIndex) => + !consumedIndexes.has(candidateIndex) && + candidate.shareType === payload.shareType && + candidate.value === payload.value, + ); + if (matchingIndex < 0) { + return undefined; + } + consumedIndexes.add(matchingIndex); + return resolvedPayloads[matchingIndex]; +} + +async function releaseOwnedFiles( + fileReader: IncomingShareFileReader, + uris: ReadonlyArray, +): Promise { + for (const uri of new Set(uris.filter((candidate): candidate is string => Boolean(candidate)))) { + try { + await fileReader.removeOwnedFile(uri); + } catch { + // Temporary-file cleanup is best-effort and must never discard content + // that was successfully converted into a durable composer attachment. + } + } +} + +function fallbackName(uri: string, index: number, mimeType: string): string { + try { + const pathName = new URL(uri).pathname.split("/").findLast((segment) => segment.length > 0); + if (pathName) { + return decodeURIComponent(pathName); + } + } catch { + // Fall through to a deterministic attachment name. + } + const extension = mimeType.split("/")[1]?.replace(/[^a-z0-9.+-]/gi, "") || "png"; + return `shared-image-${index + 1}.${extension}`; +} + +export async function buildIncomingShareDraft(input: { + readonly payloads: ReadonlyArray; + readonly resolvedPayloads: ReadonlyArray; + readonly fileReader: IncomingShareFileReader; + readonly id: string; + readonly createdAt: string; +}): Promise { + const attachments: DraftComposerImageAttachment[] = []; + const warnings: string[] = []; + const consumedResolvedPayloadIndexes = new Set(); + let warnedAttachmentLimit = false; + + for (const [index, payload] of input.payloads.entries()) { + if (payload.shareType !== "image") { + continue; + } + const resolved = resolvedImageFor( + payload, + index, + input.resolvedPayloads, + consumedResolvedPayloadIndexes, + ); + const uri = resolved?.contentUri ?? payload.value; + if (attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { + if (!warnedAttachmentLimit) { + warnings.push( + `Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared images were attached.`, + ); + warnedAttachmentLimit = true; + } + await releaseOwnedFiles(input.fileReader, [uri, payload.value]); + continue; + } + + const mimeType = (resolved?.contentMimeType ?? payload.mimeType ?? "image/png").toLowerCase(); + if (!uri || !mimeType.startsWith("image/")) { + warnings.push("One shared item was not a supported image."); + await releaseOwnedFiles(input.fileReader, [uri, payload.value]); + continue; + } + if ( + resolved?.contentSize !== null && + resolved?.contentSize !== undefined && + resolved.contentSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + ) { + warnings.push( + `'${resolved.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`, + ); + await releaseOwnedFiles(input.fileReader, [uri, payload.value]); + continue; + } + + try { + const base64 = await input.fileReader.readBase64(uri); + const sizeBytes = resolved?.contentSize ?? estimateBase64ByteSize(base64); + if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + warnings.push( + `'${resolved?.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`, + ); + continue; + } + const dataUrl = `data:${mimeType};base64,${base64}`; + attachments.push({ + id: `${input.id}:image:${index}`, + type: "image", + name: resolved?.originalName ?? fallbackName(uri, index, mimeType), + mimeType, + sizeBytes, + dataUrl, + // The share provider's file is temporary. A data-backed preview keeps + // the composer valid after its source file and App Group entry are gone. + previewUri: dataUrl, + }); + } catch { + warnings.push(`Could not read '${fallbackName(uri, index, mimeType)}'.`); + } finally { + await releaseOwnedFiles(input.fileReader, [uri, payload.value]); + } + } + + return { + schemaVersion: 1, + id: input.id, + createdAt: input.createdAt, + text: sharedText(input.payloads), + attachments, + warnings, + }; +} + +export function hasIncomingShareContent(draft: IncomingShareDraft): boolean { + return draft.text.trim().length > 0 || draft.attachments.length > 0; +} diff --git a/apps/mobile/src/features/sharing/incoming-share-presentation.test.ts b/apps/mobile/src/features/sharing/incoming-share-presentation.test.ts new file mode 100644 index 0000000000..c46ee6eb30 --- /dev/null +++ b/apps/mobile/src/features/sharing/incoming-share-presentation.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { + EMPTY_INCOMING_SHARE_PRESENTATION_STATE, + transitionIncomingSharePresentation, +} from "./incoming-share-presentation"; + +describe("incoming share presentation", () => { + it("does not reopen a dismissed share when refresh returns a new object for the same id", () => { + const presented = transitionIncomingSharePresentation(EMPTY_INCOMING_SHARE_PRESENTATION_STATE, { + isShareSheetPresented: false, + pendingShareId: "share-1", + }); + expect(presented.shareIdToPresent).toBe("share-1"); + + const whilePresented = transitionIncomingSharePresentation(presented.state, { + isShareSheetPresented: true, + pendingShareId: "share-1", + }); + expect(whilePresented).toEqual({ state: presented.state, shareIdToPresent: null }); + + const dismissed = transitionIncomingSharePresentation(whilePresented.state, { + isShareSheetPresented: false, + pendingShareId: "share-1", + }); + expect(dismissed.state.dismissedShareId).toBe("share-1"); + + expect( + transitionIncomingSharePresentation(dismissed.state, { + isShareSheetPresented: false, + pendingShareId: "share-1", + }), + ).toEqual({ state: dismissed.state, shareIdToPresent: null }); + }); + + it("presents the next queued share immediately after the previous sheet closes", () => { + const first = transitionIncomingSharePresentation(EMPTY_INCOMING_SHARE_PRESENTATION_STATE, { + isShareSheetPresented: false, + pendingShareId: "share-1", + }); + + const next = transitionIncomingSharePresentation(first.state, { + isShareSheetPresented: false, + pendingShareId: "share-2", + }); + expect(next.shareIdToPresent).toBe("share-2"); + expect(next.state).toEqual({ presentedShareId: "share-2", dismissedShareId: null }); + }); + + it("forgets dismissal after consumption so a later handoff may reuse the id", () => { + const dismissed = { + presentedShareId: null, + dismissedShareId: "share-1", + }; + const consumed = transitionIncomingSharePresentation(dismissed, { + isShareSheetPresented: false, + pendingShareId: null, + }); + expect(consumed.state).toEqual(EMPTY_INCOMING_SHARE_PRESENTATION_STATE); + + expect( + transitionIncomingSharePresentation(consumed.state, { + isShareSheetPresented: false, + pendingShareId: "share-1", + }).shareIdToPresent, + ).toBe("share-1"); + }); + + it("forgets a consumed presentation while its sheet is still mounted", () => { + const presented = { + presentedShareId: "share-1", + dismissedShareId: null, + }; + const consumed = transitionIncomingSharePresentation(presented, { + isShareSheetPresented: true, + pendingShareId: null, + }); + expect(consumed.state).toEqual(EMPTY_INCOMING_SHARE_PRESENTATION_STATE); + + const replacementWhileOpen = transitionIncomingSharePresentation(consumed.state, { + isShareSheetPresented: true, + pendingShareId: "share-1", + }); + expect(replacementWhileOpen.shareIdToPresent).toBeNull(); + expect( + transitionIncomingSharePresentation(replacementWhileOpen.state, { + isShareSheetPresented: false, + pendingShareId: "share-1", + }).shareIdToPresent, + ).toBe("share-1"); + }); +}); diff --git a/apps/mobile/src/features/sharing/incoming-share-presentation.ts b/apps/mobile/src/features/sharing/incoming-share-presentation.ts new file mode 100644 index 0000000000..663d9dc17d --- /dev/null +++ b/apps/mobile/src/features/sharing/incoming-share-presentation.ts @@ -0,0 +1,71 @@ +export interface IncomingSharePresentationState { + readonly presentedShareId: string | null; + readonly dismissedShareId: string | null; +} + +export interface IncomingSharePresentationTransition { + readonly state: IncomingSharePresentationState; + readonly shareIdToPresent: string | null; +} + +export const EMPTY_INCOMING_SHARE_PRESENTATION_STATE: IncomingSharePresentationState = { + presentedShareId: null, + dismissedShareId: null, +}; + +/** + * Tracks presentation by durable share id rather than object identity. A user + * dismissal suppresses only that inbox item until it is consumed or replaced. + */ +export function transitionIncomingSharePresentation( + state: IncomingSharePresentationState, + input: { + readonly isShareSheetPresented: boolean; + readonly pendingShareId: string | null; + }, +): IncomingSharePresentationTransition { + if (input.isShareSheetPresented) { + if (state.presentedShareId !== null && input.pendingShareId !== state.presentedShareId) { + // Consumption may happen while the sheet remains mounted. Forget the + // old presentation immediately so a later handoff may reuse its id. + return { + state: EMPTY_INCOMING_SHARE_PRESENTATION_STATE, + shareIdToPresent: null, + }; + } + return { state, shareIdToPresent: null }; + } + + let nextState = state; + if (state.presentedShareId !== null) { + if (input.pendingShareId === state.presentedShareId) { + return { + state: { + presentedShareId: null, + dismissedShareId: state.presentedShareId, + }, + shareIdToPresent: null, + }; + } + nextState = { ...state, presentedShareId: null }; + } + + if (input.pendingShareId === null) { + return { + state: EMPTY_INCOMING_SHARE_PRESENTATION_STATE, + shareIdToPresent: null, + }; + } + + if (nextState.dismissedShareId === input.pendingShareId) { + return { state: nextState, shareIdToPresent: null }; + } + + return { + state: { + presentedShareId: input.pendingShareId, + dismissedShareId: null, + }, + shareIdToPresent: input.pendingShareId, + }; +} diff --git a/apps/mobile/src/features/sharing/incoming-share-storage.ts b/apps/mobile/src/features/sharing/incoming-share-storage.ts new file mode 100644 index 0000000000..8364b4c98a --- /dev/null +++ b/apps/mobile/src/features/sharing/incoming-share-storage.ts @@ -0,0 +1,80 @@ +import * as Schema from "effect/Schema"; + +import { decodeIncomingShareDraft, type IncomingShareDraft } from "./incoming-share-model"; + +const INCOMING_SHARE_DIRECTORY = "incoming-shares"; + +export class IncomingShareStorageError extends Schema.TaggedErrorClass()( + "IncomingShareStorageError", + { + operation: Schema.Literals(["load", "write", "remove"]), + shareId: Schema.NullOr(Schema.String), + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Incoming share storage operation ${this.operation} failed for ${this.shareId ?? "unknown"}.`; + } +} + +function fileName(shareId: string): string { + return `${encodeURIComponent(shareId)}.json`; +} + +async function getDirectory() { + const { Directory, Paths } = await import("expo-file-system"); + const directory = new Directory(Paths.document, INCOMING_SHARE_DIRECTORY); + directory.create({ idempotent: true, intermediates: true }); + return directory; +} + +async function getFile(shareId: string) { + const { File } = await import("expo-file-system"); + return new File(await getDirectory(), fileName(shareId)); +} + +export async function loadIncomingShareDrafts(): Promise> { + try { + const { File } = await import("expo-file-system"); + const drafts: IncomingShareDraft[] = []; + for (const entry of (await getDirectory()).list()) { + if (!(entry instanceof File) || !entry.name.endsWith(".json")) { + continue; + } + try { + drafts.push(decodeIncomingShareDraft(JSON.parse(await entry.text()) as unknown)); + } catch (cause) { + console.warn( + "[incoming-share] ignored invalid persisted share", + new IncomingShareStorageError({ operation: "load", shareId: null, cause }), + ); + } + } + return drafts.sort((left, right) => right.createdAt.localeCompare(left.createdAt)); + } catch (cause) { + throw new IncomingShareStorageError({ operation: "load", shareId: null, cause }); + } +} + +export async function writeIncomingShareDraft(draft: IncomingShareDraft): Promise { + try { + const file = await getFile(draft.id); + if (!file.exists) { + file.create({ intermediates: true, overwrite: true }); + } + file.write(JSON.stringify(draft)); + } catch (cause) { + throw new IncomingShareStorageError({ operation: "write", shareId: draft.id, cause }); + } +} + +export async function removeIncomingShareDraft(shareId: string): Promise { + try { + const file = await getFile(shareId); + if (file.exists) { + file.delete(); + } + } catch (cause) { + throw new IncomingShareStorageError({ operation: "remove", shareId, cause }); + } +} diff --git a/apps/mobile/src/features/shortcuts/appShortcuts.test.ts b/apps/mobile/src/features/shortcuts/appShortcuts.test.ts new file mode 100644 index 0000000000..17b63bb78f --- /dev/null +++ b/apps/mobile/src/features/shortcuts/appShortcuts.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, it } from "vite-plus/test"; +import type { NavigationState } from "@react-navigation/native"; + +import type { RecentThreadShortcut } from "../../persistence/imperative"; +import { + activeThreadRef, + buildShortcutActions, + MAX_RECENT_THREAD_SHORTCUTS, + NEW_TASK_SHORTCUT_ID, + shortcutHref, + withRecentThreadShortcut, +} from "./appShortcuts"; + +function navState(route: { name: string; params?: unknown }): NavigationState { + return { index: 0, routes: [route] } as unknown as NavigationState; +} + +function thread(suffix: string, title = `Thread ${suffix}`): RecentThreadShortcut { + return { environmentId: `env-${suffix}`, threadId: `thread-${suffix}`, title }; +} + +describe("withRecentThreadShortcut", () => { + it("prepends a newly opened thread", () => { + const next = withRecentThreadShortcut([thread("a")], thread("b")); + expect(next.map((entry) => entry.threadId)).toEqual(["thread-b", "thread-a"]); + }); + + it("moves a reopened thread to the front without duplicating it", () => { + const next = withRecentThreadShortcut([thread("a"), thread("b")], thread("b")); + expect(next.map((entry) => entry.threadId)).toEqual(["thread-b", "thread-a"]); + }); + + it("caps the list at the shortcut budget", () => { + const current = [thread("a"), thread("b"), thread("c")]; + const next = withRecentThreadShortcut(current, thread("d")); + expect(next).toHaveLength(MAX_RECENT_THREAD_SHORTCUTS); + expect(next[0]?.threadId).toBe("thread-d"); + expect(next.map((entry) => entry.threadId)).not.toContain("thread-c"); + }); + + it("returns the same array when the thread already leads with the same title", () => { + const current = [thread("a"), thread("b")]; + expect(withRecentThreadShortcut(current, thread("a"))).toBe(current); + }); + + it("keeps the known title when a reopen records an empty one", () => { + const current = [thread("a", "Fix the build")]; + const next = withRecentThreadShortcut(current, thread("a", "")); + expect(next).toBe(current); + }); + + it("updates the title once the shell provides one", () => { + const current = [thread("a", "")]; + const next = withRecentThreadShortcut(current, thread("a", "Fix the build")); + expect(next[0]?.title).toBe("Fix the build"); + expect(next).toHaveLength(1); + }); +}); + +describe("buildShortcutActions", () => { + it("leads with the static new-task action", () => { + const actions = buildShortcutActions([thread("a")]); + expect(actions[0]?.id).toBe(NEW_TASK_SHORTCUT_ID); + expect(actions[0]?.params?.href).toBe("/new"); + expect(actions).toHaveLength(2); + }); + + it("deep-links threads with encoded route params", () => { + const actions = buildShortcutActions([ + { environmentId: "env 1", threadId: "thread/2", title: "Spaced out" }, + ]); + expect(actions[1]?.params?.href).toBe("/threads/env%201/thread%2F2"); + expect(actions[1]?.title).toBe("Spaced out"); + }); + + it("falls back to a generic label for missing titles", () => { + const actions = buildShortcutActions([thread("a", " ")]); + expect(actions[1]?.title).toBe("Thread"); + }); +}); + +describe("shortcutHref", () => { + it("accepts exactly the destinations shortcuts can produce", () => { + expect(shortcutHref({ id: "x", title: "x", params: { href: "/new" } })).toBe("/new"); + expect(shortcutHref({ id: "x", title: "x", params: { href: "/threads/env-1/thread-2" } })).toBe( + "/threads/env-1/thread-2", + ); + expect( + shortcutHref({ id: "x", title: "x", params: { href: "/threads/env%201/thread%2F2" } }), + ).toBe("/threads/env%201/thread%2F2"); + }); + + it("rejects everything else", () => { + for (const href of [ + "https://evil.example", + "//evil.example", + "/settings", + "/threads/only-one-segment", + "/threads/a/b/c", + "/threads//x", + "/threads/a/b?x=1", + "/threads/a/b#frag", + "/new/extra", + ]) { + expect(shortcutHref({ id: "x", title: "x", params: { href } })).toBe(null); + } + expect(shortcutHref({ id: "x", title: "x", params: { href: 3 } })).toBe(null); + expect(shortcutHref({ id: "x", title: "x" })).toBe(null); + }); +}); + +describe("activeThreadRef", () => { + it("resolves the active Thread route's params", () => { + const ref = activeThreadRef( + navState({ name: "Thread", params: { environmentId: "env-1", threadId: "thread-2" } }), + ); + expect(ref).toEqual({ environmentId: "env-1", threadId: "thread-2" }); + }); + + it("takes the first value of array params", () => { + const ref = activeThreadRef( + navState({ name: "Thread", params: { environmentId: ["env-1"], threadId: ["thread-2"] } }), + ); + expect(ref).toEqual({ environmentId: "env-1", threadId: "thread-2" }); + }); + + it("returns null for non-thread routes", () => { + expect(activeThreadRef(navState({ name: "Home" }))).toBe(null); + }); + + it("returns null instead of throwing for malformed params", () => { + const malformed: unknown[] = [ + undefined, + {}, + { environmentId: "env-1" }, + { environmentId: "", threadId: "thread-2" }, + { environmentId: " ", threadId: "thread-2" }, + { environmentId: "env-1", threadId: " " }, + { environmentId: 42, threadId: "thread-2" }, + { environmentId: { nested: true }, threadId: "thread-2" }, + { environmentId: [], threadId: [] }, + ]; + for (const params of malformed) { + expect(activeThreadRef(navState({ name: "Thread", params }))).toBe(null); + } + }); +}); + +describe("launcher shortcut ids", () => { + it("cannot collide across different env/thread pairs", () => { + const a = buildShortcutActions([{ environmentId: "a-b", threadId: "c", title: "x" }]); + const b = buildShortcutActions([{ environmentId: "a", threadId: "b-c", title: "x" }]); + expect(a[1]?.id).not.toBe(b[1]?.id); + }); +}); diff --git a/apps/mobile/src/features/shortcuts/appShortcuts.ts b/apps/mobile/src/features/shortcuts/appShortcuts.ts new file mode 100644 index 0000000000..49e9d0999a --- /dev/null +++ b/apps/mobile/src/features/shortcuts/appShortcuts.ts @@ -0,0 +1,137 @@ +import type { Action } from "expo-quick-actions"; +import type { NavigationState } from "@react-navigation/native"; +import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; + +import type { RecentThreadShortcut } from "../../persistence/imperative"; + +// Launchers cap visible shortcuts around 4; one slot is the static +// "New task" entry, the rest rotate through recently opened threads. +export const MAX_RECENT_THREAD_SHORTCUTS = 3; + +export const NEW_TASK_SHORTCUT_ID = "new-task"; +const NEW_TASK_SHORTCUT_HREF = "/new"; + +// Adaptive icon resource generated by the expo-quick-actions config plugin +// (androidIcons key in app.config.ts). +const SHORTCUT_ICON = "shortcut_icon"; + +// Matches only the thread deep-link shape shortcuts are allowed to carry: +// exactly two non-empty segments, no nested paths, queries, or fragments. +const THREAD_SHORTCUT_HREF_PATTERN = /^\/threads\/[^/?#]+\/[^/?#]+$/; + +function threadShortcutHref(thread: RecentThreadShortcut): string { + return `/threads/${encodeURIComponent(thread.environmentId)}/${encodeURIComponent(thread.threadId)}`; +} + +function firstRouteParam(value: string | string[] | undefined): string | null { + if (Array.isArray(value)) { + return value[0] ?? null; + } + + return value ?? null; +} + +/** + * Thread ref of the navigation state's ACTIVE route, or null. Never throws: + * route params can arrive malformed from external deep links or restored + * state, the branded id constructors throw on values failing their schema, + * and this runs during render of the root stack layout — an uncaught throw + * here would take down the whole navigation tree. + */ +export function activeThreadRef(state: NavigationState): ScopedThreadRef | null { + const route = state.routes[state.index]; + if (route?.name !== "Thread") { + return null; + } + + try { + const params = route.params as + | { + readonly environmentId?: string | string[]; + readonly threadId?: string | string[]; + } + | undefined; + const environmentId = firstRouteParam(params?.environmentId)?.trim(); + const threadId = firstRouteParam(params?.threadId)?.trim(); + if (!environmentId || !threadId) { + return null; + } + + return { + environmentId: EnvironmentId.make(environmentId), + threadId: ThreadId.make(threadId), + }; + } catch { + return null; + } +} + +function threadShortcutLabel(thread: RecentThreadShortcut): string { + const title = thread.title.trim(); + return title.length > 0 ? title : "Thread"; +} + +/** + * In-app navigation path carried by a shortcut, or null for anything + * malformed — shortcuts persist in the launcher across app updates, so this + * allowlists the exact destinations shortcuts can produce rather than + * trusting any path-shaped string (`//host`, arbitrary routes, stale + * persisted junk all navigate nowhere). + */ +export function shortcutHref(action: Action): string | null { + const href = action.params?.href; + if (typeof href !== "string") { + return null; + } + + return href === NEW_TASK_SHORTCUT_HREF || THREAD_SHORTCUT_HREF_PATTERN.test(href) ? href : null; +} + +/** + * Records an opened thread as the most recent shortcut entry. Returns the + * SAME array when nothing changed so effect chains keyed on identity skip + * redundant launcher/storage writes. An empty title never clobbers a known + * one — shells load after navigation, so the first record of a thread often + * predates its title. + */ +export function withRecentThreadShortcut( + current: ReadonlyArray, + opened: RecentThreadShortcut, +): ReadonlyArray { + const existing = current.find( + (thread) => + thread.environmentId === opened.environmentId && thread.threadId === opened.threadId, + ); + const title = opened.title.trim().length > 0 ? opened.title : (existing?.title ?? opened.title); + if (current[0] === existing && existing !== undefined && existing.title === title) { + return current; + } + + return [ + { environmentId: opened.environmentId, threadId: opened.threadId, title }, + ...current.filter((thread) => thread !== existing), + ].slice(0, MAX_RECENT_THREAD_SHORTCUTS); +} + +/** Full launcher shortcut list: static "New task" first, then recents. */ +export function buildShortcutActions(recents: ReadonlyArray): Action[] { + return [ + { + id: NEW_TASK_SHORTCUT_ID, + title: "New task", + icon: SHORTCUT_ICON, + params: { href: NEW_TASK_SHORTCUT_HREF }, + }, + ...recents.slice(0, MAX_RECENT_THREAD_SHORTCUTS).map( + (thread): Action => ({ + // The encoded href doubles as the launcher id: URI-encoding makes the + // env/thread join unambiguous (a plain `-` join lets different pairs + // collide and overwrite each other's launcher slots). + id: `thread:${threadShortcutHref(thread)}`, + title: threadShortcutLabel(thread), + icon: SHORTCUT_ICON, + params: { href: threadShortcutHref(thread) }, + }), + ), + ]; +} diff --git a/apps/mobile/src/features/shortcuts/useAppShortcuts.ts b/apps/mobile/src/features/shortcuts/useAppShortcuts.ts new file mode 100644 index 0000000000..3070a1d54e --- /dev/null +++ b/apps/mobile/src/features/shortcuts/useAppShortcuts.ts @@ -0,0 +1,136 @@ +import * as QuickActions from "expo-quick-actions"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { Platform } from "react-native"; +import { useLinkTo, type NavigationState } from "@react-navigation/native"; + +import { + loadRecentThreadShortcuts, + saveRecentThreadShortcuts, + type RecentThreadShortcut, +} from "../../persistence/imperative"; +import { useThreadShell } from "../../state/entities"; +import { + activeThreadRef, + buildShortcutActions, + shortcutHref, + withRecentThreadShortcut, +} from "./appShortcuts"; + +/** + * Owns the launcher app shortcuts (Android long-press menu): keeps the + * static "New task" entry plus the recently opened threads in sync, and + * routes shortcut taps — cold start included — to their in-app screens. + * Mounted once in the root stack layout. + */ +export function useAppShortcuts(state: NavigationState): void { + useShortcutNavigation(); + useRecentThreadShortcutSync(state); +} + +function useShortcutNavigation(): void { + const linkTo = useLinkTo(); + const handledInitialAction = useRef(false); + + useEffect(() => { + // Cold start: the tapped shortcut arrives as the launch action, before + // any listener can fire. Navigating from here pushes the target over the + // initial Home route, so back returns home instead of exiting the app. + if (!handledInitialAction.current) { + handledInitialAction.current = true; + const initialHref = QuickActions.initial ? shortcutHref(QuickActions.initial) : null; + if (initialHref !== null) { + linkTo(initialHref); + } + } + + const subscription = QuickActions.addListener((action) => { + const href = shortcutHref(action); + if (href !== null) { + linkTo(href); + } + }); + return () => subscription.remove(); + }, [linkTo]); +} + +function useRecentThreadShortcutSync(state: NavigationState): void { + const threadRef = useMemo(() => activeThreadRef(state), [state]); + const threadShell = useThreadShell(threadRef); + // null until the persisted list loads; recording waits on it so the first + // thread opened after a cold start cannot clobber older entries. + const [recents, setRecents] = useState | null>(null); + // Gates storage writes: a failed load falls back to an empty in-memory + // list (so the launcher still gets the "New task" item), but persisting + // that fallback would erase valid history over a transient read error. + // Real thread opens flip this on — by then the list is the new truth. + const persistableRef = useRef(false); + // Saves are fire-and-forget; chaining them keeps an older list from + // finishing after (and overwriting) a newer one. + const saveQueueRef = useRef>(Promise.resolve()); + + useEffect(() => { + if (Platform.OS !== "android") { + return; + } + + let cancelled = false; + void loadRecentThreadShortcuts() + .then((threads) => { + if (!cancelled) { + persistableRef.current = true; + setRecents(threads); + } + }) + .catch((error) => { + console.warn("[app-shortcuts] failed to load recent threads", error); + if (!cancelled) { + setRecents([]); + } + }); + return () => { + cancelled = true; + }; + }, []); + + const loaded = recents !== null; + const environmentId = threadRef?.environmentId ?? null; + const threadId = threadRef?.threadId ?? null; + const title = threadShell?.title ?? ""; + useEffect(() => { + if (!loaded || environmentId === null || threadId === null) { + return; + } + + // withRecentThreadShortcut returns the same array when nothing changed, + // so React bails out and the persist effect below does not re-fire. + setRecents((current) => { + if (current === null) { + return current; + } + const next = withRecentThreadShortcut(current, { environmentId, threadId, title }); + if (next !== current) { + persistableRef.current = true; + } + return next; + }); + }, [loaded, environmentId, threadId, title]); + + useEffect(() => { + if (recents === null) { + return; + } + + if (persistableRef.current) { + saveQueueRef.current = saveQueueRef.current.then( + () => + saveRecentThreadShortcuts(recents).catch((error) => { + console.warn("[app-shortcuts] failed to persist recent threads", error); + }), + () => undefined, + ); + } + void QuickActions.setItems(buildShortcutActions(recents)).catch((error) => { + console.warn("[app-shortcuts] failed to update launcher shortcuts", error); + }); + }, [recents]); +} diff --git a/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx b/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx new file mode 100644 index 0000000000..9a4272824b --- /dev/null +++ b/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx @@ -0,0 +1,224 @@ +import { useEffect, useRef, useState } from "react"; +import { Keyboard, View } from "react-native"; +import { CommonActions, StackActions, useNavigation } from "@react-navigation/native"; +import { AsyncResult } from "effect/unstable/reactivity"; + +import { useConnectionController } from "../connection/useConnectionController"; +import { useProjects, useThreadShells } from "../../state/entities"; +import { enqueueThreadOutboxMessage } from "../../state/thread-outbox"; +import { holdEditingQueuedMessage } from "../../state/use-thread-outbox"; +import { useWorkspaceState } from "../../state/workspace"; +import { + getNativeShowcasePairingUrls, + getNativeShowcaseScene, + markNativeShowcaseReady, + type ShowcaseScene, +} from "./nativeShowcaseScene"; +import { + buildShowcasePendingTasks, + SHOWCASE_PENDING_TASK_DEFINITIONS, +} from "./showcasePendingTasks"; +import { retryShowcaseOperation } from "./showcaseRetry"; + +const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1"; +const SHOWCASE_THREAD_ID = "remote-command-center"; + +function sceneFromPathname(pathname: string): ShowcaseScene | null { + const routePath = pathname.split(/[?#]/u, 1)[0] ?? pathname; + if (routePath === "/settings" || routePath.endsWith("/settings/environments")) { + return "environments"; + } + if (routePath.endsWith("/terminal")) return "terminal"; + if (routePath.endsWith("/review")) return "review"; + if (routePath.startsWith("/threads/")) return "thread"; + if (routePath === "/") return "threads"; + return null; +} + +export function ShowcaseCaptureCoordinator(props: { readonly pathname: string }) { + const navigation = useNavigation(); + const { connectPairingUrl } = useConnectionController(); + const workspace = useWorkspaceState(); + const projects = useProjects(); + const threads = useThreadShells(); + const attemptedPairingRef = useRef(new Set()); + const seededPendingTaskIdsRef = useRef(new Set()); + const [pairingUrls, setPairingUrls] = useState>([]); + const [pendingTasksReady, setPendingTasksReady] = useState(false); + const [requestedScene, setRequestedScene] = useState(null); + const [readyScene, setReadyScene] = useState(null); + + useEffect(() => { + if (!SHOWCASE_ENABLED || pairingUrls.length > 0) return; + + const readPairingUrls = () => { + const values = getNativeShowcasePairingUrls(); + if (values.length > 0) setPairingUrls(values); + }; + readPairingUrls(); + const interval = setInterval(readPairingUrls, 250); + return () => clearInterval(interval); + }, [pairingUrls.length]); + + useEffect(() => { + if (!SHOWCASE_ENABLED) return; + + const readRequestedScene = () => { + const value = getNativeShowcaseScene(); + if (value) setRequestedScene(value); + }; + readRequestedScene(); + const interval = setInterval(readRequestedScene, 250); + return () => clearInterval(interval); + }, []); + + useEffect(() => { + if (!SHOWCASE_ENABLED || pairingUrls.length === 0) return; + let cancelled = false; + void (async () => { + await Promise.all( + pairingUrls.map(async (pairingUrl) => { + if (cancelled || attemptedPairingRef.current.has(pairingUrl)) return; + const paired = await retryShowcaseOperation( + async () => AsyncResult.isSuccess(await connectPairingUrl(pairingUrl)), + { isCancelled: () => cancelled }, + ); + if (paired) attemptedPairingRef.current.add(pairingUrl); + }), + ); + })(); + return () => { + cancelled = true; + }; + }, [connectPairingUrl, pairingUrls]); + + const scene = sceneFromPathname(props.pathname); + const hasServerFixture = + workspace.state.hasReadyEnvironment && + workspace.environments.length >= 3 && + projects.length >= 3 && + threads.some((thread) => String(thread.id) === SHOWCASE_THREAD_ID); + const hasFixture = hasServerFixture && pendingTasksReady; + const showcaseThread = threads.find((thread) => String(thread.id) === SHOWCASE_THREAD_ID); + + useEffect(() => { + if (!SHOWCASE_ENABLED || !hasServerFixture || pendingTasksReady) return; + + const pendingTasks = buildShowcasePendingTasks(projects, Date.now()); + if (pendingTasks.length !== SHOWCASE_PENDING_TASK_DEFINITIONS.length) return; + + let cancelled = false; + for (const task of pendingTasks) holdEditingQueuedMessage(task.messageId); + void (async () => { + const results = await Promise.all( + pendingTasks.map(async (task) => { + const messageId = String(task.messageId); + if (seededPendingTaskIdsRef.current.has(messageId)) return true; + const seeded = await retryShowcaseOperation( + async () => { + await enqueueThreadOutboxMessage(task); + return true; + }, + { isCancelled: () => cancelled }, + ); + if (seeded) seededPendingTaskIdsRef.current.add(messageId); + return seeded; + }), + ); + if (!cancelled && results.every(Boolean)) setPendingTasksReady(true); + })(); + return () => { + cancelled = true; + }; + }, [hasServerFixture, pendingTasksReady, projects]); + + useEffect(() => { + if (!SHOWCASE_ENABLED || requestedScene === null || !hasFixture || !showcaseThread) return; + if (scene === requestedScene) return; + + const params = { + environmentId: String(showcaseThread.environmentId), + threadId: SHOWCASE_THREAD_ID, + }; + if (requestedScene === "threads") { + navigation.dispatch(StackActions.popToTop()); + return; + } + const routes: Array<{ + name: string; + params?: Record; + state?: { index: number; routes: Array<{ name: string }> }; + }> = [{ name: "Home" }]; + if (requestedScene === "environments") { + routes.push({ + name: "SettingsSheet", + state: { + index: 1, + routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }], + }, + }); + } else { + routes.push({ name: "Thread", params }); + if (requestedScene === "terminal") { + routes.push({ + name: "ThreadTerminal", + params: { ...params, terminalId: "term-1" }, + }); + } else if (requestedScene === "review") { + routes.push({ name: "ThreadReview", params }); + } + } + navigation.dispatch( + CommonActions.reset({ + index: routes.length - 1, + routes, + }), + ); + }, [hasFixture, navigation, requestedScene, scene, showcaseThread]); + + useEffect(() => { + if ( + !SHOWCASE_ENABLED || + scene === null || + requestedScene === null || + scene !== requestedScene || + !hasFixture + ) { + setReadyScene(null); + return; + } + // Review owns its readiness marker because route activation happens before + // the VCS request is parsed and the native diff surface is mounted. + if (scene === "review") { + setReadyScene(null); + return; + } + if (scene === "terminal") Keyboard.dismiss(); + + let renderFrame: number | null = null; + let readyFrame: number | null = null; + const settleTimer = setTimeout(() => { + renderFrame = requestAnimationFrame(() => { + readyFrame = requestAnimationFrame(() => { + markNativeShowcaseReady(scene); + setReadyScene(scene); + }); + }); + }, 500); + return () => { + clearTimeout(settleTimer); + if (renderFrame !== null) cancelAnimationFrame(renderFrame); + if (readyFrame !== null) cancelAnimationFrame(readyFrame); + }; + }, [hasFixture, requestedScene, scene]); + + if (!SHOWCASE_ENABLED || readyScene === null) return null; + + return ( + + ); +} diff --git a/apps/mobile/src/features/showcase/nativeShowcaseScene.ts b/apps/mobile/src/features/showcase/nativeShowcaseScene.ts new file mode 100644 index 0000000000..1f2e263ebf --- /dev/null +++ b/apps/mobile/src/features/showcase/nativeShowcaseScene.ts @@ -0,0 +1,68 @@ +import { requireOptionalNativeModule } from "expo"; + +export const SHOWCASE_SCENES = ["threads", "thread", "terminal", "review", "environments"] as const; +export type ShowcaseScene = (typeof SHOWCASE_SCENES)[number]; + +interface NativeShowcaseControls { + readonly getShowcasePairingUrl?: () => string | null; + readonly getShowcaseScene?: () => string | null; + readonly prepareShowcaseCapture?: () => void; + readonly markShowcaseReady?: (scene: ShowcaseScene) => void; +} + +function nativeShowcaseControls(): NativeShowcaseControls | null { + return requireOptionalNativeModule("T3NativeControls"); +} + +export function getNativeShowcasePairingUrls(): ReadonlyArray { + try { + let raw = nativeShowcaseControls()?.getShowcasePairingUrl?.()?.trim(); + if (!raw) return []; + if (raw.startsWith("json-uri:")) { + try { + raw = decodeURIComponent(raw.slice("json-uri:".length)); + } catch { + return []; + } + } + try { + const parsed: unknown = JSON.parse(raw); + if (Array.isArray(parsed)) { + return parsed.filter( + (candidate): candidate is string => + typeof candidate === "string" && candidate.trim().length > 0, + ); + } + } catch { + // Older runners pass a single URL rather than a JSON array. + } + return [raw]; + } catch { + return []; + } +} + +export function getNativeShowcaseScene(): ShowcaseScene | null { + try { + const scene = nativeShowcaseControls()?.getShowcaseScene?.()?.trim(); + return SHOWCASE_SCENES.find((candidate) => candidate === scene) ?? null; + } catch { + return null; + } +} + +export function prepareNativeShowcaseCapture(): void { + try { + nativeShowcaseControls()?.prepareShowcaseCapture?.(); + } catch { + // The harness still works when a development build predates this helper. + } +} + +export function markNativeShowcaseReady(scene: ShowcaseScene): void { + try { + nativeShowcaseControls()?.markShowcaseReady?.(scene); + } catch { + // The readiness marker is capture-runner metadata, never app functionality. + } +} diff --git a/apps/mobile/src/features/showcase/showcaseEnvironmentRows.test.ts b/apps/mobile/src/features/showcase/showcaseEnvironmentRows.test.ts new file mode 100644 index 0000000000..a459cbe1db --- /dev/null +++ b/apps/mobile/src/features/showcase/showcaseEnvironmentRows.test.ts @@ -0,0 +1,70 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; + +import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types"; +import { + applyShowcaseLocalEnvironmentDisplayUrls, + resolveShowcaseEnvironmentUpdateDisplayUrl, +} from "./showcaseEnvironmentRows"; + +function environment( + environmentId: string, + environmentLabel: string, + displayUrl = "http://127.0.0.1:3773/", +): ConnectedEnvironmentSummary { + return { + environmentId: EnvironmentId.make(environmentId), + environmentLabel, + displayUrl, + isRelayManaged: false, + connectionState: "connected", + connectionError: null, + connectionErrorTraceId: null, + }; +} + +it("presents showcase transports as remote endpoints", () => { + const environments = applyShowcaseLocalEnvironmentDisplayUrls([ + environment("runtime-id-1", "Moonbase Terminal"), + environment("runtime-id-2", "Suspense Station"), + environment("runtime-id-3", "Kernel Cabin"), + ]); + + assert.deepStrictEqual( + environments.map(({ displayUrl }) => displayUrl), + [ + "https://moonbase.tail9f3a.ts.net/", + "https://suspense-vps.hel1.t3.sh/", + "http://100.82.16.5:3773/", + ], + ); +}); + +it("leaves environments outside the showcase fixture unchanged", () => { + const original = environment( + "runtime-id-4", + "My Workstation", + "https://workstation.example.test/", + ); + + assert.deepStrictEqual(applyShowcaseLocalEnvironmentDisplayUrls([original]), [original]); +}); + +it("does not persist a cosmetic showcase URL when only the label is saved", () => { + assert.equal( + resolveShowcaseEnvironmentUpdateDisplayUrl({ + actualDisplayUrl: "http://127.0.0.1:3773/", + presentedDisplayUrl: "https://moonbase.tail9f3a.ts.net/", + submittedDisplayUrl: "https://moonbase.tail9f3a.ts.net/", + }), + "http://127.0.0.1:3773/", + ); + assert.equal( + resolveShowcaseEnvironmentUpdateDisplayUrl({ + actualDisplayUrl: "http://127.0.0.1:3773/", + presentedDisplayUrl: "https://moonbase.tail9f3a.ts.net/", + submittedDisplayUrl: "https://new-host.example.com/", + }), + "https://new-host.example.com/", + ); +}); diff --git a/apps/mobile/src/features/showcase/showcaseEnvironmentRows.ts b/apps/mobile/src/features/showcase/showcaseEnvironmentRows.ts new file mode 100644 index 0000000000..66ec3046c6 --- /dev/null +++ b/apps/mobile/src/features/showcase/showcaseEnvironmentRows.ts @@ -0,0 +1,70 @@ +import { EnvironmentId } from "@t3tools/contracts"; + +import type { RelayEnvironmentView } from "../connection/useConnectionController"; +import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types"; + +const SHOWCASE_LOCAL_ENVIRONMENT_DISPLAY_URLS: Readonly> = { + "Moonbase Terminal": "https://moonbase.tail9f3a.ts.net/", + "Suspense Station": "https://suspense-vps.hel1.t3.sh/", + "Kernel Cabin": "http://100.82.16.5:3773/", +}; + +export function applyShowcaseLocalEnvironmentDisplayUrls( + environments: ReadonlyArray, +): ReadonlyArray { + return environments.map((environment) => ({ + ...environment, + displayUrl: + SHOWCASE_LOCAL_ENVIRONMENT_DISPLAY_URLS[environment.environmentLabel] ?? + environment.displayUrl, + })); +} + +export function resolveShowcaseEnvironmentUpdateDisplayUrl(input: { + readonly actualDisplayUrl: string; + readonly presentedDisplayUrl: string; + readonly submittedDisplayUrl: string; +}): string { + return input.submittedDisplayUrl === input.presentedDisplayUrl + ? input.actualDisplayUrl + : input.submittedDisplayUrl; +} + +const pocketPiId = EnvironmentId.make("showcase-pocket-pi"); +const pocketPiEndpoint = { + httpBaseUrl: "https://pocket-pi.t3.sh", + wsBaseUrl: "wss://pocket-pi.t3.sh", + providerKind: "t3_relay" as const, +}; + +export const SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS: ReadonlyArray = [ + { + environmentId: EnvironmentId.make("showcase-aurora-gpu"), + environmentLabel: "Aurora GPU Pod", + displayUrl: "https://aurora-gpu.t3.sh", + isRelayManaged: true, + connectionState: "connected", + connectionError: null, + connectionErrorTraceId: null, + }, +]; + +export const SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS: ReadonlyArray = [ + { + environment: { + environmentId: pocketPiId, + label: "Pocket Pi", + endpoint: pocketPiEndpoint, + linkedAt: "2026-07-16T08:00:00.000Z", + }, + availability: "online", + status: { + environmentId: pocketPiId, + endpoint: pocketPiEndpoint, + status: "online", + checkedAt: "2026-07-16T08:41:00.000Z", + }, + error: null, + traceId: null, + }, +]; diff --git a/apps/mobile/src/features/showcase/showcasePendingTasks.test.ts b/apps/mobile/src/features/showcase/showcasePendingTasks.test.ts new file mode 100644 index 0000000000..8ab043d7cd --- /dev/null +++ b/apps/mobile/src/features/showcase/showcasePendingTasks.test.ts @@ -0,0 +1,72 @@ +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { EnvironmentId, ProjectId, ProviderInstanceId } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; + +import { + buildShowcasePendingTasks, + SHOWCASE_PENDING_TASK_DEFINITIONS, +} from "./showcasePendingTasks"; + +const projects: ReadonlyArray = [ + { + environmentId: EnvironmentId.make("moonbase-terminal"), + id: ProjectId.make("t3code"), + title: "T3 Code", + workspaceRoot: "/workspace/t3code", + repositoryIdentity: null, + defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + scripts: [], + createdAt: "2026-07-16T08:00:00.000Z", + updatedAt: "2026-07-16T08:00:00.000Z", + }, + { + environmentId: EnvironmentId.make("suspense-station"), + id: ProjectId.make("react"), + title: "React", + workspaceRoot: "/workspace/react", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-07-16T08:00:00.000Z", + updatedAt: "2026-07-16T08:00:00.000Z", + }, +]; + +it("builds sendable-looking pending tasks against real showcase projects", () => { + const tasks = buildShowcasePendingTasks(projects, Date.parse("2026-07-16T09:00:00.000Z")); + + assert.equal(tasks.length, SHOWCASE_PENDING_TASK_DEFINITIONS.length); + assert.deepStrictEqual( + tasks.map((task) => ({ + environmentId: String(task.environmentId), + projectId: task.creation ? String(task.creation.projectId) : undefined, + title: task.creation?.projectTitle, + branch: task.creation?.branch, + createdAt: task.createdAt, + })), + [ + { + environmentId: "moonbase-terminal", + projectId: "t3code", + title: "T3 Code", + branch: "feat/offline-launchpad", + createdAt: "2026-07-16T08:52:00.000Z", + }, + { + environmentId: "suspense-station", + projectId: "react", + title: "React", + branch: "perf/tunnel-handoff", + createdAt: "2026-07-16T08:33:00.000Z", + }, + ], + ); + assert.equal( + tasks.every((task) => task.modelSelection !== undefined), + true, + ); +}); + +it("waits until every referenced project has hydrated", () => { + assert.equal(buildShowcasePendingTasks(projects.slice(0, 1), Date.now()).length, 1); +}); diff --git a/apps/mobile/src/features/showcase/showcasePendingTasks.ts b/apps/mobile/src/features/showcase/showcasePendingTasks.ts new file mode 100644 index 0000000000..1b0b5ed22f --- /dev/null +++ b/apps/mobile/src/features/showcase/showcasePendingTasks.ts @@ -0,0 +1,66 @@ +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + DEFAULT_RUNTIME_MODE, + MessageId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; + +import type { QueuedThreadMessage } from "../../state/thread-outbox-model"; + +export const SHOWCASE_PENDING_TASK_DEFINITIONS = [ + { + projectId: "t3code", + id: "offline-launch-checklist", + text: "Ship the offline launch checklist before touchdown ✈️", + branch: "feat/offline-launchpad", + minutesAgo: 8, + }, + { + projectId: "react", + id: "train-tunnel-suspense", + text: "Polish the Suspense handoff for the train tunnel 🚇", + branch: "perf/tunnel-handoff", + minutesAgo: 27, + }, +] as const; + +const FALLBACK_MODEL_SELECTION = { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", +} as const; + +export function buildShowcasePendingTasks( + projects: ReadonlyArray, + now: number, +): ReadonlyArray { + return SHOWCASE_PENDING_TASK_DEFINITIONS.flatMap((definition) => { + const project = projects.find((candidate) => String(candidate.id) === definition.projectId); + if (!project) return []; + + return [ + { + environmentId: project.environmentId, + threadId: ThreadId.make(`showcase-pending-${definition.id}`), + messageId: MessageId.make(`showcase-pending-message-${definition.id}`), + commandId: CommandId.make(`showcase-pending-command-${definition.id}`), + text: definition.text, + attachments: [], + modelSelection: project.defaultModelSelection ?? FALLBACK_MODEL_SELECTION, + runtimeMode: DEFAULT_RUNTIME_MODE, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + creation: { + projectId: project.id, + projectTitle: project.title, + projectCwd: project.workspaceRoot, + workspaceMode: "local" as const, + branch: definition.branch, + worktreePath: project.workspaceRoot, + }, + createdAt: new Date(now - definition.minutesAgo * 60_000).toISOString(), + }, + ]; + }); +} diff --git a/apps/mobile/src/features/showcase/showcaseRetry.test.ts b/apps/mobile/src/features/showcase/showcaseRetry.test.ts new file mode 100644 index 0000000000..86c2890366 --- /dev/null +++ b/apps/mobile/src/features/showcase/showcaseRetry.test.ts @@ -0,0 +1,44 @@ +import { assert, it } from "@effect/vitest"; + +import { retryShowcaseOperation } from "./showcaseRetry"; + +it("retries a failed showcase operation until it succeeds", async () => { + let attempts = 0; + const succeeded = await retryShowcaseOperation( + async () => { + attempts += 1; + return attempts === 3; + }, + { isCancelled: () => false, retryDelayMs: 0 }, + ); + + assert.equal(succeeded, true); + assert.equal(attempts, 3); +}); + +it("recovers when a showcase operation attempt hangs", async () => { + let attempts = 0; + const succeeded = await retryShowcaseOperation( + () => { + attempts += 1; + return attempts === 1 ? new Promise(() => undefined) : Promise.resolve(true); + }, + { isCancelled: () => false, attemptTimeoutMs: 1, retryDelayMs: 0 }, + ); + + assert.equal(succeeded, true); + assert.equal(attempts, 2); +}); + +it("stops retrying when the owning showcase effect is cancelled", async () => { + let cancelled = false; + const succeeded = await retryShowcaseOperation( + async () => { + cancelled = true; + return false; + }, + { isCancelled: () => cancelled, retryDelayMs: 0 }, + ); + + assert.equal(succeeded, false); +}); diff --git a/apps/mobile/src/features/showcase/showcaseRetry.ts b/apps/mobile/src/features/showcase/showcaseRetry.ts new file mode 100644 index 0000000000..0c7aeb1201 --- /dev/null +++ b/apps/mobile/src/features/showcase/showcaseRetry.ts @@ -0,0 +1,46 @@ +export interface ShowcaseRetryOptions { + readonly isCancelled: () => boolean; + readonly attemptTimeoutMs?: number; + readonly retryDelayMs?: number; +} + +const DEFAULT_ATTEMPT_TIMEOUT_MS = 10_000; +const DEFAULT_RETRY_DELAY_MS = 500; + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function runAttemptWithTimeout( + operation: () => Promise, + timeoutMs: number, +): Promise { + let timeout: ReturnType | null = null; + try { + return await Promise.race([ + operation(), + new Promise((resolve) => { + timeout = setTimeout(() => resolve(false), timeoutMs); + }), + ]); + } catch { + return false; + } finally { + if (timeout !== null) clearTimeout(timeout); + } +} + +/** Retry transient showcase setup work until it succeeds or the owning effect unmounts. */ +export async function retryShowcaseOperation( + operation: () => Promise, + options: ShowcaseRetryOptions, +): Promise { + const attemptTimeoutMs = options.attemptTimeoutMs ?? DEFAULT_ATTEMPT_TIMEOUT_MS; + const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS; + + while (!options.isCancelled()) { + if (await runAttemptWithTimeout(operation, attemptTimeoutMs)) return true; + if (!options.isCancelled()) await delay(retryDelayMs); + } + return false; +} diff --git a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx index ad693dcb44..b205b4df72 100644 --- a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx +++ b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx @@ -12,7 +12,10 @@ import { import { AppText as Text } from "../../components/AppText"; import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; -import { resolveNativeTerminalSurfaceView } from "./nativeTerminalModule"; +import { + getNativeTerminalHardwareKeyRevision, + resolveNativeTerminalSurfaceView, +} from "./nativeTerminalModule"; import { buildGhosttyThemeConfig, getPierreTerminalTheme, @@ -34,6 +37,7 @@ interface TerminalSurfaceProps extends ViewProps { readonly buffer: string; readonly fontSize?: number; readonly isRunning: boolean; + readonly autoFocus?: boolean; readonly keyboardFocusRequest?: number; readonly theme?: TerminalTheme; readonly onInput: (data: string) => void; @@ -79,9 +83,9 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter return ( - + {statusLabel} { const text = event.nativeEvent.text; if (text.length > 0) { - props.onInput(`${text}\n`); + // Terminal Enter is CR. LF is Ctrl+J and raw-mode TUIs can treat it as J. + props.onInput(`${text}\r`); } }} /> @@ -162,13 +162,7 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter })} onPress={() => props.onInput("\u0003")} > - + Ctrl-C @@ -179,7 +173,6 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) { const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize; - const keyboardInputRef = useRef(null); const appearanceScheme = useColorScheme() === "light" ? "light" : "dark"; const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme); const { onInput, onResize } = props; @@ -190,15 +183,23 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf terminalDebugLog("native:surface", { terminalKey: props.terminalKey, native: hasNativeSurface, + // null = installed binary predates native hardware-key handling (rebuild needed). + hardwareKeyRevision: getNativeTerminalHardwareKeyRevision(), bufferLen: props.buffer.length, isRunning: props.isRunning, }); }, [hasNativeSurface, props.buffer.length, props.isRunning, props.terminalKey]); const handleNativeInput = useCallback( (event: NativeSyntheticEvent) => { + if (!props.isRunning) { + return; + } + terminalDebugLog("native:onInput", { + codes: Array.from(event.nativeEvent.data, (char) => char.codePointAt(0)), + }); onInput(event.nativeEvent.data); }, - [onInput], + [onInput, props.isRunning], ); const handleNativeResize = useCallback( (event: NativeSyntheticEvent) => { @@ -210,33 +211,14 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf [onResize], ); - // Reopen focus through React and forward input normally; this avoids a native focus-command bridge. - useEffect(() => { - if (!NativeTerminalSurfaceView || (props.keyboardFocusRequest ?? 0) <= 0) { - return undefined; - } - - keyboardInputRef.current?.blur(); - const focusFrame = requestAnimationFrame(() => keyboardInputRef.current?.focus()); - return () => cancelAnimationFrame(focusFrame); - }, [NativeTerminalSurfaceView, props.keyboardFocusRequest]); - - const handleKeyboardInput = useCallback( - (data: string) => { - if (data.length > 0) { - onInput(data); - keyboardInputRef.current?.clear(); - } - }, - [onInput], - ); - if (NativeTerminalSurfaceView) { return ( - { - if (event.nativeEvent.key === "Backspace") { - onInput("\u007f"); - } - }} - onSubmitEditing={() => onInput("\n")} - /> ); } diff --git a/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx b/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx index 5d0b0547e6..1c7adb6834 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx @@ -1,5 +1,5 @@ import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts"; -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "../../components/AppSymbol"; import { memo, useCallback, useEffect, useMemo, useRef } from "react"; import { Pressable, View } from "react-native"; @@ -32,6 +32,8 @@ export const ThreadTerminalPanel = memo(function ThreadTerminalPanel( ) { const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write"); const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize"); + const closeTerminal = useAtomCommand(terminalEnvironment.close, "terminal close"); + const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open"); const nativeTerminalAvailable = hasNativeTerminalSurface(); const terminalId = DEFAULT_TERMINAL_ID; const lastGridSizeRef = useRef({ @@ -63,6 +65,94 @@ export const ThreadTerminalPanel = memo(function ThreadTerminalPanel( const terminalKey = `${props.environmentId}:${props.threadId}:${terminalId}`; const isRunning = terminal.status === "running" || terminal.status === "starting"; + // Close the session and dismiss the panel when the process ends while + // attached (e.g. typing `exit`), mirroring the web drawer's + // onSessionExited flow. + const runningTerminalKeyRef = useRef(null); + const reopenedStaleTerminalKeyRef = useRef(null); + + // Attach subscriptions are cached with an idle TTL; reopening the panel + // after its session ended reuses the stale stream without a new attach + // RPC. Issue an explicit open so the server respawns the session and its + // snapshot flows into the live subscription. + useEffect(() => { + if (isRunning) { + reopenedStaleTerminalKeyRef.current = null; + return; + } + if ( + attachInput === null || + (terminal.status !== "closed" && terminal.status !== "exited") || + terminal.version === 0 || + runningTerminalKeyRef.current === terminalKey || + reopenedStaleTerminalKeyRef.current === terminalKey + ) { + return; + } + reopenedStaleTerminalKeyRef.current = terminalKey; + void openTerminal({ + environmentId: props.environmentId, + input: { + threadId: props.threadId, + terminalId, + cwd: props.cwd, + worktreePath: props.worktreePath, + cols: lastGridSizeRef.current.cols, + rows: lastGridSizeRef.current.rows, + }, + }).then((result) => { + // Release the guard on failure so a later render can retry the respawn. + if (result._tag === "Failure" && reopenedStaleTerminalKeyRef.current === terminalKey) { + reopenedStaleTerminalKeyRef.current = null; + } + }); + }, [ + attachInput, + isRunning, + openTerminal, + props.cwd, + props.environmentId, + props.threadId, + props.worktreePath, + terminal.status, + terminal.version, + terminalId, + terminalKey, + ]); + + useEffect(() => { + // Forget both markers while hidden: if the process ends while the panel + // is unobserved (or was just auto-closed), the next show must take the + // stale-reopen path instead of treating it as a live exit or skipping + // the respawn. + if (attachInput === null) { + runningTerminalKeyRef.current = null; + reopenedStaleTerminalKeyRef.current = null; + return; + } + if (isRunning) { + runningTerminalKeyRef.current = terminalKey; + return; + } + // The web drawer treats both exited and closed as session end. + const sessionEnded = terminal.status === "exited" || terminal.status === "closed"; + if (!sessionEnded || runningTerminalKeyRef.current !== terminalKey) { + return; + } + runningTerminalKeyRef.current = null; + // Mark this key handled so the stale-attach effect doesn't respawn the + // session the user just ended. + reopenedStaleTerminalKeyRef.current = terminalKey; + void closeTerminal({ + environmentId: props.environmentId, + input: { + threadId: props.threadId, + terminalId, + }, + }); + props.onClose(); + }, [attachInput, closeTerminal, isRunning, props, terminal.status, terminalId, terminalKey]); + const sendResize = useCallback( (size: TerminalGridSize) => { void resizeTerminal({ diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx index 771c2afbb4..072aec2c04 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx @@ -1,9 +1,11 @@ import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts"; import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal"; -import { SymbolView } from "expo-symbols"; -import { Stack, useLocalSearchParams, useRouter } from "expo-router"; +import type { MenuAction } from "@react-native-menu/menu"; +import { SymbolView } from "../../components/AppSymbol"; +import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader"; +import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { Pressable, Text as RNText, View, useColorScheme } from "react-native"; +import { Platform, Pressable, View, useColorScheme } from "react-native"; import { KeyboardController, KeyboardEvents, @@ -11,11 +13,13 @@ import { useKeyboardState, } from "react-native-keyboard-controller"; +import { AndroidHeaderIconButton, AndroidScreenHeader } from "../../components/AndroidScreenHeader"; import { ComposerToolbarButton, ComposerToolbarRow, ComposerToolbarScroller, } from "../../components/ComposerToolbarTrigger"; +import { ControlPillMenu } from "../../components/ControlPill"; import { EmptyState } from "../../components/EmptyState"; import { GlassSurface } from "../../components/GlassSurface"; import { LoadingScreen } from "../../components/LoadingScreen"; @@ -24,8 +28,13 @@ import { useEnvironmentPresentation } from "../../state/presentation"; import { terminalEnvironment } from "../../state/terminal"; import { useAtomCommand } from "../../state/use-atom-command"; import { useWorkspaceState } from "../../state/workspace"; -import { buildThreadTerminalNavigation } from "../../lib/routes"; -import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; +import { + MAX_TERMINAL_FONT_SIZE, + MIN_TERMINAL_FONT_SIZE, + TERMINAL_FONT_SIZE_STEP, + stepTerminalFontSize, +} from "../../lib/appearancePreferences"; +import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { useAttachedTerminalSession, useKnownTerminalSessions, @@ -33,9 +42,9 @@ import { import { useThreadSelection } from "../../state/use-thread-selection"; import { useSelectedThreadProjection } from "../../state/use-thread-detail"; import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice"; +import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; import { TerminalSurface } from "./NativeTerminalSurface"; import { getPierreTerminalTheme } from "./terminalTheme"; -import { loadPreferences, savePreferencesPatch } from "../../lib/storage"; import { terminalDebugLog } from "./terminalDebugLog"; import { getTerminalBufferReplayKey, @@ -52,26 +61,16 @@ import { buildTerminalMenuSessions, getTerminalStatusLabel, nextOpenTerminalId, + previousLiveTerminalId, resolveTerminalSessionLabel, type TerminalMenuSession, } from "./terminalMenu"; -import { - DEFAULT_TERMINAL_FONT_SIZE, - MAX_TERMINAL_FONT_SIZE, - MIN_TERMINAL_FONT_SIZE, - TERMINAL_FONT_SIZE_STEP, - normalizeTerminalFontSize, -} from "./terminalPreferences"; -import { - cacheTerminalFontSize, - cacheTerminalGridSize, - getCachedTerminalFontSize, - getCachedTerminalGridSize, -} from "./terminalUiState"; +import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiState"; const DEFAULT_TERMINAL_COLS = 80; const DEFAULT_TERMINAL_ROWS = 24; const TERMINAL_ACCESSORY_HEIGHT = 52; +const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1"; type PendingModifier = "ctrl" | "meta"; type HostPlatform = "mac" | "linux" | "windows" | "unknown"; @@ -153,19 +152,24 @@ function pickRunningTerminalSessionForBootstrap( ); } -export function ThreadTerminalRouteScreen() { - const router = useRouter(); +type ThreadTerminalRouteScreenProps = StaticScreenProps<{ + readonly environmentId: string; + readonly threadId: string; + readonly terminalId?: string; +}>; + +export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps) { + const navigation = useNavigation(); const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write"); const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize"); const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear"); + const closeTerminal = useAtomCommand(terminalEnvironment.close, "terminal close"); + const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open"); const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry"); const appearanceScheme = useColorScheme() === "light" ? "light" : "dark"; const { state: workspaceState } = useWorkspaceState(); - const params = useLocalSearchParams<{ - environmentId?: string | string[]; - threadId?: string | string[]; - terminalId?: string | string[]; - }>(); + const { layout, panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout(); + const params = props.route.params; const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } = useThreadSelection(); const selectedThreadDetail = useSelectedThreadProjection(); @@ -181,7 +185,12 @@ export function ThreadTerminalRouteScreen() { const isEnvironmentReady = environment.presentation?.connection.phase === "connected"; const requestedTerminalId = firstRouteParam(params.terminalId); const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID; - const cachedFontSize = getCachedTerminalFontSize(); + const { + isReady: hasResolvedFontPreference, + appearance, + setTerminalFontSize, + } = useAppearancePreferences(); + const fontSize = appearance.terminalFontSize; const cachedRouteGridSize = routeEnvironmentId && routeThreadId ? getCachedTerminalGridSize({ @@ -241,7 +250,6 @@ export function ThreadTerminalRouteScreen() { rows: DEFAULT_TERMINAL_ROWS, }, ); - const [fontSize, setFontSize] = useState(cachedFontSize ?? DEFAULT_TERMINAL_FONT_SIZE); const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0); const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false); const bufferReplayTimerRef = useRef | null>(null); @@ -249,9 +257,6 @@ export function ThreadTerminalRouteScreen() { const lastBufferReplayKeyRef = useRef(null); const sentInitialInputKeyRef = useRef(null); const [readyBufferReplayKey, setReadyBufferReplayKey] = useState(null); - const [hasResolvedFontPreference, setHasResolvedFontPreference] = useState( - cachedFontSize !== null, - ); /** Default grid is always valid for attach; onResize refines cols/rows. Requiring a cached size blocked bootstrap for new terminal routes. */ const [hasMeasuredSurface, setHasMeasuredSurface] = useState(true); const [pendingModifierState, setPendingModifierState] = useState<{ @@ -350,6 +355,64 @@ export function ThreadTerminalRouteScreen() { }); const isRunning = terminal.status === "running" || terminal.status === "starting"; + // When the process ends while this screen is attached (e.g. typing `exit`), + // close the session and leave the screen, mirroring the web drawer's + // onSessionExited flow. Only react to a running -> exited transition + // observed on this screen so already-exited sessions can still be opened + // (they restart on attach). + const runningTerminalKeyRef = useRef(null); + const reopenedStaleTerminalKeyRef = useRef(null); + const pendingExitNavigationRef = useRef(null); + + // Attach subscriptions are cached with an idle TTL, so revisiting a + // terminal whose session ended while unobserved reuses the stale stream + // without a new attach RPC — the server never respawns anything. Detect + // that (dead status with processed events, never seen running here) and + // issue an explicit open; its snapshot flows into the live subscription. + useEffect(() => { + if (isRunning) { + reopenedStaleTerminalKeyRef.current = null; + return; + } + if ( + terminalAttachInput === null || + !selectedThread || + (terminal.status !== "closed" && terminal.status !== "exited") || + terminal.version === 0 || + runningTerminalKeyRef.current === terminalKey || + reopenedStaleTerminalKeyRef.current === terminalKey + ) { + return; + } + reopenedStaleTerminalKeyRef.current = terminalKey; + void openTerminal({ + environmentId: selectedThread.environmentId, + input: { + threadId: selectedThread.id, + terminalId, + cwd: terminalAttachInput.cwd, + worktreePath: terminalAttachInput.worktreePath, + cols: terminalAttachInput.cols, + rows: terminalAttachInput.rows, + ...(terminalAttachInput.env ? { env: terminalAttachInput.env } : {}), + }, + }).then((result) => { + // Release the guard on failure so a later render can retry the respawn. + if (result._tag === "Failure" && reopenedStaleTerminalKeyRef.current === terminalKey) { + reopenedStaleTerminalKeyRef.current = null; + } + }); + }, [ + isRunning, + openTerminal, + selectedThread, + terminal.status, + terminal.version, + terminalAttachInput, + terminalId, + terminalKey, + ]); + useEffect(() => { terminalDebugLog("surface:props", { terminalKey, @@ -406,24 +469,10 @@ export function ThreadTerminalRouteScreen() { ); const terminalTheme = getPierreTerminalTheme(appearanceScheme); + const usesNativeHeaderGlass = Platform.OS === "ios"; const pendingModifier = pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null; - const headerTitle = useMemo(() => { - const topLineParts = [ - selectedEnvironmentConnection?.environmentLabel ?? null, - selectedThreadProject?.title ?? null, - ].filter((value): value is string => Boolean(value)); - - return { - topLine: topLineParts.join(" \u00b7 "), - bottomLine: cwd ?? selectedThreadProject?.workspaceRoot ?? "", - }; - }, [ - cwd, - selectedEnvironmentConnection?.environmentLabel, - selectedThreadProject?.title, - selectedThreadProject?.workspaceRoot, - ]); + const headerSubtitle = selectedThreadProject?.title ?? ""; const terminalToolbarActions = useMemo>(() => { const modifierActions: ReadonlyArray = hostPlatform === "mac" @@ -548,8 +597,14 @@ export function ThreadTerminalRouteScreen() { if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) { return; } - router.replace(buildThreadTerminalNavigation(selectedThread, runningSession.target.terminalId)); - }, [router, runningSession, selectedThread, shouldRedirectToRunningTerminal]); + navigation.dispatch( + StackActions.replace("ThreadTerminal", { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + terminalId: runningSession.target.terminalId, + }), + ); + }, [navigation, runningSession, selectedThread, shouldRedirectToRunningTerminal]); useEffect(() => { const initialInput = pendingLaunch?.initialInput; @@ -639,42 +694,6 @@ export function ThreadTerminalRouteScreen() { setHasMeasuredSurface(true); }, [routeEnvironmentId, routeThreadId, terminalId]); - useEffect(() => { - let cancelled = false; - - void loadPreferences() - .then((preferences) => { - if (cancelled) { - return; - } - - setFontSize(cacheTerminalFontSize(preferences.terminalFontSize)); - setHasResolvedFontPreference(true); - }) - .catch(() => { - if (cancelled) { - return; - } - - setHasResolvedFontPreference(true); - }); - - return () => { - cancelled = true; - }; - }, []); - - useEffect(() => { - if (!hasResolvedFontPreference) { - return; - } - - cacheTerminalFontSize(fontSize); - void savePreferencesPatch({ - terminalFontSize: normalizeTerminalFontSize(fontSize), - }); - }, [fontSize, hasResolvedFontPreference]); - const writeInput = useCallback( (data: string) => { if (!selectedThread || !isRunning) { @@ -774,9 +793,114 @@ export function ThreadTerminalRouteScreen() { return; } - router.replace(buildThreadTerminalNavigation(selectedThread, nextTerminalId)); + navigation.dispatch( + StackActions.replace("ThreadTerminal", { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + terminalId: nextTerminalId, + }), + ); }, - [router, selectedThread, terminalId], + [navigation, selectedThread, terminalId], + ); + + const navigateAwayAfterExit = useCallback(() => { + // With other shells still live, fall through to the previous one instead + // of dropping the user back on the thread. + const fallbackTerminalId = previousLiveTerminalId({ + sessions: terminalMenuSessions, + exitedTerminalId: terminalId, + }); + if (fallbackTerminalId !== null && selectedThread) { + navigation.dispatch( + StackActions.replace("ThreadTerminal", { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + terminalId: fallbackTerminalId, + }), + ); + return; + } + if (navigation.canGoBack()) { + navigation.goBack(); + return; + } + // Deep-linked/root mounts have nothing to pop; land on the thread + // instead of stranding the user on a dead terminal. + if (selectedThread) { + navigation.dispatch( + StackActions.replace("Thread", { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + }), + ); + } + }, [navigation, selectedThread, terminalId, terminalMenuSessions]); + + useEffect(() => { + // Detached (hidden surface or environment drop): forget the running + // marker so a reattach takes the stale-reopen path instead of misreading + // the dead snapshot as an exit observed on this screen. A pending exit + // navigation stays armed — it only clears once the session runs again — + // so refocusing a dead screen still leaves it. + if (terminalAttachInput === null) { + runningTerminalKeyRef.current = null; + return; + } + if (isRunning) { + runningTerminalKeyRef.current = terminalKey; + // The session came back (e.g. respawned elsewhere) before the user + // returned; a stale pending exit must not eject a live terminal. + pendingExitNavigationRef.current = null; + return; + } + // The web drawer treats both exited and closed as session end. + const sessionEnded = terminal.status === "exited" || terminal.status === "closed"; + if (!sessionEnded || runningTerminalKeyRef.current !== terminalKey) { + return; + } + runningTerminalKeyRef.current = null; + // Mark this key handled so the stale-attach effect doesn't respawn the + // session the user just ended. + reopenedStaleTerminalKeyRef.current = terminalKey; + if (selectedThread) { + void closeTerminal({ + environmentId: selectedThread.environmentId, + input: { + threadId: selectedThread.id, + terminalId, + }, + }); + } + if (navigation.isFocused()) { + navigateAwayAfterExit(); + return; + } + // An unfocused screen can't navigate; leave when the user returns so + // they never land on the dead session. + pendingExitNavigationRef.current = terminalKey; + }, [ + closeTerminal, + isRunning, + navigateAwayAfterExit, + navigation, + selectedThread, + terminal.status, + terminalAttachInput, + terminalId, + terminalKey, + ]); + + useEffect( + () => + navigation.addListener("focus", () => { + if (pendingExitNavigationRef.current !== terminalKey) { + return; + } + pendingExitNavigationRef.current = null; + navigateAwayAfterExit(); + }), + [navigateAwayAfterExit, navigation, terminalKey], ); const handleOpenNewTerminal = useCallback(() => { @@ -784,30 +908,88 @@ export function ThreadTerminalRouteScreen() { return; } - router.replace( - buildThreadTerminalNavigation( - selectedThread, - nextOpenTerminalId({ + navigation.dispatch( + StackActions.replace("ThreadTerminal", { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + terminalId: nextOpenTerminalId({ listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), activeRouteTerminalId: terminalId, }), - ), + }), ); - }, [router, selectedThread, terminalId, terminalMenuSessions]); - - const adjustFontSize = useCallback((delta: number) => { - setTimeout(() => { - setFontSize((current) => cacheTerminalFontSize(current + delta)); - }, 0); - }, []); + }, [navigation, selectedThread, terminalId, terminalMenuSessions]); const handleDecreaseFontSize = useCallback(() => { - adjustFontSize(-TERMINAL_FONT_SIZE_STEP); - }, [adjustFontSize]); + setTerminalFontSize(stepTerminalFontSize(fontSize, -1)); + }, [fontSize, setTerminalFontSize]); const handleIncreaseFontSize = useCallback(() => { - adjustFontSize(TERMINAL_FONT_SIZE_STEP); - }, [adjustFontSize]); + setTerminalFontSize(stepTerminalFontSize(fontSize, 1)); + }, [fontSize, setTerminalFontSize]); + + // Android mirror of the iOS NativeHeaderToolbar terminal menu below: text + // size, session switching, and "Open new terminal", rendered through the + // token-styled anchored menu (the native header items are iOS-only). + const androidTerminalMenuActions = useMemo( + () => [ + { + id: "text-size", + title: "Text size", + subactions: [ + { + id: "font-decrease", + title: `A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`, + attributes: fontSize <= MIN_TERMINAL_FONT_SIZE ? { disabled: true } : undefined, + }, + { + id: "font-increase", + title: `A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`, + attributes: fontSize >= MAX_TERMINAL_FONT_SIZE ? { disabled: true } : undefined, + }, + ], + }, + ...terminalMenuSessions.map( + (session): MenuAction => ({ + id: `terminal-session:${session.terminalId}`, + title: session.displayLabel, + subtitle: [getTerminalStatusLabel({ status: session.status }), basename(session.cwd)] + .filter(Boolean) + .join(" · "), + state: session.terminalId === terminalId ? ("on" as const) : undefined, + }), + ), + { + id: "terminal-new", + title: "Open new terminal", + image: "plus", + subtitle: `Start another shell in ${basename(selectedThreadProject?.workspaceRoot ?? null) ?? "this workspace"}`, + }, + ], + [fontSize, selectedThreadProject?.workspaceRoot, terminalId, terminalMenuSessions], + ); + + const handleAndroidTerminalMenuAction = useCallback( + (event: { nativeEvent: { event: string } }) => { + const id = event.nativeEvent.event; + if (id === "font-decrease") { + handleDecreaseFontSize(); + return; + } + if (id === "font-increase") { + handleIncreaseFontSize(); + return; + } + if (id === "terminal-new") { + handleOpenNewTerminal(); + return; + } + if (id.startsWith("terminal-session:")) { + handleSelectTerminal(id.slice("terminal-session:".length)); + } + }, + [handleDecreaseFontSize, handleIncreaseFontSize, handleOpenNewTerminal, handleSelectTerminal], + ); const handleClearTerminal = useCallback(() => { if (!selectedThread) { @@ -900,80 +1082,99 @@ export function ThreadTerminalRouteScreen() { return ( <> - ( - - - {headerTitle.topLine} - - - {headerTitle.bottomLine} - - - ), + // Static header config lives in Stack.tsx (SOLID_HEADER_OPTIONS — the pty + // scrolls internally, nothing for glass to sample). Default title/subtitle + // styling, like every other page. + // Android draws its own in-flow header (AndroidScreenHeader below); + // the native stack header stays iOS-only. + headerShown: Platform.OS !== "android", + title: "Terminal", + unstable_headerSubtitle: + usesNativeHeaderGlass && headerSubtitle.length > 0 ? headerSubtitle : undefined, }} /> + {Platform.OS === "android" ? ( + navigation.goBack() : undefined} + trailing={ + <> + {layout.usesSplitView ? ( + + ) : null} + {isEnvironmentReady ? ( + + + + ) : null} + + } + /> + ) : null} + + {layout.usesSplitView ? ( + + + + ) : null} + {isEnvironmentReady ? ( - - - + + + {getTerminalStatusLabel({ status: terminal.status, hasRunningSubprocess: terminal.hasRunningSubprocess, })} - - - Text size - + + Text size + - {`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`} - - {`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`} + + = MAX_TERMINAL_FONT_SIZE} discoverabilityLabel="Increase terminal text size" onPress={handleIncreaseFontSize} > - {`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`} - - + {`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`} + + {terminalMenuSessions.map((session) => ( - handleSelectTerminal(session.terminalId)} @@ -984,21 +1185,21 @@ export function ThreadTerminalRouteScreen() { .filter(Boolean) .join(" · ")} > - {session.displayLabel} - + {session.displayLabel} + ))} - - Open new terminal - - - + Open new terminal + + + ) : null} - + {!isEnvironmentReady ? ( ) : ( <> - + diff --git a/apps/mobile/src/features/terminal/nativeTerminalModule.ts b/apps/mobile/src/features/terminal/nativeTerminalModule.ts index e5b1f63007..f6a74595c8 100644 --- a/apps/mobile/src/features/terminal/nativeTerminalModule.ts +++ b/apps/mobile/src/features/terminal/nativeTerminalModule.ts @@ -1,6 +1,6 @@ import type { ComponentType } from "react"; import type { NativeSyntheticEvent, ViewProps } from "react-native"; -import { requireNativeView } from "expo"; +import { requireNativeView, requireOptionalNativeModule } from "expo"; import { NativeViewResolutionError } from "../../native/nativeViewResolutionError"; @@ -23,6 +23,8 @@ interface TerminalResizeEvent { export interface NativeTerminalSurfaceProps extends ViewProps { readonly appearanceScheme?: "light" | "dark"; + readonly autoFocus?: boolean; + readonly focusRequest?: number; readonly themeConfig?: string; readonly backgroundColor?: string; readonly foregroundColor?: string; @@ -74,6 +76,25 @@ export function resolveNativeTerminalSurfaceView(): ComponentType( + NATIVE_TERMINAL_MODULE_NAME, + ); + return module?.hardwareKeyRevision ?? null; + } catch { + return null; + } +} + export function hasNativeTerminalSurface() { return resolveNativeTerminalSurfaceView() !== null; } diff --git a/apps/mobile/src/features/terminal/terminalMenu.test.ts b/apps/mobile/src/features/terminal/terminalMenu.test.ts index 48c87e18dd..1f176263ca 100644 --- a/apps/mobile/src/features/terminal/terminalMenu.test.ts +++ b/apps/mobile/src/features/terminal/terminalMenu.test.ts @@ -9,9 +9,25 @@ import { buildTerminalMenuSessions, nextOpenTerminalId, nextTerminalId, + previousLiveTerminalId, resolveProjectScriptTerminalId, + type TerminalMenuSession, } from "./terminalMenu"; +function makeMenuSession(input: { + readonly terminalId: string; + readonly status: TerminalMenuSession["status"]; +}): TerminalMenuSession { + return { + terminalId: input.terminalId, + cwd: null, + status: input.status, + hasRunningSubprocess: false, + displayLabel: getTerminalLabel(input.terminalId), + updatedAt: null, + }; +} + function makeKnownSession(input: { readonly terminalId: string; readonly status: KnownTerminalSession["state"]["status"]; @@ -144,6 +160,60 @@ describe("nextOpenTerminalId", () => { }); }); +describe("previousLiveTerminalId", () => { + it("returns null when no other live session remains", () => { + expect( + previousLiveTerminalId({ + sessions: [ + makeMenuSession({ terminalId: "term-2", status: "exited" }), + makeMenuSession({ terminalId: "term-3", status: "closed" }), + ], + exitedTerminalId: "term-2", + }), + ).toBe(null); + }); + + it("prefers the nearest live session below the exited id", () => { + expect( + previousLiveTerminalId({ + sessions: [ + makeMenuSession({ terminalId: DEFAULT_TERMINAL_ID, status: "running" }), + makeMenuSession({ terminalId: "term-2", status: "running" }), + makeMenuSession({ terminalId: "term-3", status: "exited" }), + makeMenuSession({ terminalId: "term-4", status: "running" }), + ], + exitedTerminalId: "term-3", + }), + ).toBe("term-2"); + }); + + it("falls back to the nearest live session above when the exited id was lowest", () => { + expect( + previousLiveTerminalId({ + sessions: [ + makeMenuSession({ terminalId: DEFAULT_TERMINAL_ID, status: "exited" }), + makeMenuSession({ terminalId: "term-2", status: "starting" }), + makeMenuSession({ terminalId: "term-4", status: "running" }), + ], + exitedTerminalId: DEFAULT_TERMINAL_ID, + }), + ).toBe("term-2"); + }); + + it("ignores dead sessions when picking the fallback", () => { + expect( + previousLiveTerminalId({ + sessions: [ + makeMenuSession({ terminalId: DEFAULT_TERMINAL_ID, status: "running" }), + makeMenuSession({ terminalId: "term-2", status: "exited" }), + makeMenuSession({ terminalId: "term-3", status: "exited" }), + ], + exitedTerminalId: "term-3", + }), + ).toBe(DEFAULT_TERMINAL_ID); + }); +}); + describe("resolveProjectScriptTerminalId", () => { it("reuses the default shell when no terminal is running", () => { expect( diff --git a/apps/mobile/src/features/terminal/terminalMenu.ts b/apps/mobile/src/features/terminal/terminalMenu.ts index 29374bdda6..06cb74e946 100644 --- a/apps/mobile/src/features/terminal/terminalMenu.ts +++ b/apps/mobile/src/features/terminal/terminalMenu.ts @@ -114,6 +114,35 @@ export function buildTerminalMenuSessions(input: { return Arr.sort(sessionsById.values(), terminalMenuSessionOrder); } +/** + * Picks the session to show after a terminal exits: the nearest live session + * below the exited id (terminal n-1), falling back to the nearest one above. + * Returns null when no other live session remains and the terminal UI should + * be dismissed instead. + */ +export function previousLiveTerminalId(input: { + readonly sessions: ReadonlyArray; + readonly exitedTerminalId: string; +}): string | null { + const live = Arr.sort( + input.sessions.filter( + (session) => + session.terminalId !== input.exitedTerminalId && + (session.status === "running" || session.status === "starting"), + ), + terminalMenuSessionOrder, + ); + if (live.length === 0) { + return null; + } + + const below = live.filter( + (session) => + session.terminalId.localeCompare(input.exitedTerminalId, undefined, { numeric: true }) < 0, + ); + return (below[below.length - 1] ?? live[0])?.terminalId ?? null; +} + export function resolveProjectScriptTerminalId(input: { readonly existingTerminalIds: ReadonlyArray; readonly hasRunningTerminal: boolean; diff --git a/apps/mobile/src/features/terminal/terminalPreferences.ts b/apps/mobile/src/features/terminal/terminalPreferences.ts index 095876fa2a..330a31d5f2 100644 --- a/apps/mobile/src/features/terminal/terminalPreferences.ts +++ b/apps/mobile/src/features/terminal/terminalPreferences.ts @@ -1,4 +1,4 @@ -export const DEFAULT_TERMINAL_FONT_SIZE = 10; +export const DEFAULT_TERMINAL_FONT_SIZE = 10.5; export const TERMINAL_FONT_SIZE_STEP = 0.5; export const MIN_TERMINAL_FONT_SIZE = 6; export const MAX_TERMINAL_FONT_SIZE = 14; diff --git a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx index 8b6fe07808..ccf6a30712 100644 --- a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx +++ b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx @@ -1,14 +1,12 @@ import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass"; import type { ComposerTriggerKind } from "@t3tools/shared/composerTrigger"; import type { ServerProviderSkill, ServerProviderSlashCommand } from "@t3tools/contracts"; -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "../../components/AppSymbol"; import { memo } from "react"; import { Pressable, ScrollView, useColorScheme, View, type ViewStyle } from "react-native"; import { AppText as Text } from "../../components/AppText"; import { PierreEntryIcon } from "../../components/PierreEntryIcon"; -import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; - export type ComposerCommandItem = | { readonly id: string; @@ -156,23 +154,11 @@ const CommandRow = memo(function CommandRow(props: { ) : iconName ? ( ) : null} - + {props.item.label} {props.item.description ? ( - + {props.item.description} ) : null} @@ -189,18 +175,15 @@ export const ComposerCommandPopover = memo(function ComposerCommandPopover( return ( {label ? ( - - + + {label} ) : null} {props.items.length > 0 ? ( @@ -214,7 +197,7 @@ export const ComposerCommandPopover = memo(function ComposerCommandPopover( ))} ) : ( - + {emptyText(props.triggerKind, props.isLoading)} diff --git a/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx b/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx index 93d929e596..4c99c2c866 100644 --- a/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx +++ b/apps/mobile/src/features/threads/GitActionProgressOverlay.tsx @@ -1,5 +1,5 @@ import * as Haptics from "expo-haptics"; -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "../../components/AppSymbol"; import { useCallback, useEffect, useRef } from "react"; import { ActivityIndicator, Pressable, View } from "react-native"; import Animated, { FadeIn, FadeOut } from "react-native-reanimated"; @@ -47,7 +47,8 @@ export function GitActionProgressOverlay(props: { diff --git a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx new file mode 100644 index 0000000000..8e6819378a --- /dev/null +++ b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx @@ -0,0 +1,49 @@ +import type { StaticScreenProps } from "@react-navigation/native"; +import { useMemo } from "react"; +import { NativeStackScreenOptions } from "../../native/StackHeader"; + +import { NewTaskDraftScreen } from "./NewTaskDraftScreen"; + +type NewTaskDraftRouteParams = { + readonly environmentId?: string | string[]; + readonly projectId?: string | string[]; + readonly title?: string | string[]; + readonly pendingTaskId?: string | string[]; + readonly incomingShareId?: string | string[]; +}; + +export function NewTaskDraftRouteScreen({ route }: StaticScreenProps) { + const params = route.params ?? {}; + + // Keyed on the params object so a fresh navigation to this (already + // mounted) screen produces a new reference, letting the draft screen + // re-apply the requested project. + const initialProjectRef = useMemo( + () => ({ + environmentId: Array.isArray(params.environmentId) + ? params.environmentId[0] + : params.environmentId, + projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId, + }), + [route.params], + ); + + return ( + <> + + + + ); +} diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index ce24198f5e..ce81db8c48 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -1,9 +1,11 @@ -import { Stack, useRouter } from "expo-router"; -import { useCallback, useEffect, useMemo, useRef } from "react"; -import { Alert, InteractionManager, View, useColorScheme } from "react-native"; +import { NativeStackScreenOptions } from "../../native/StackHeader"; +import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native"; import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useThemeColor } from "../../lib/useThemeColor"; +import { useFontFamily } from "../../lib/useFontFamily"; import { EnvironmentId } from "@t3tools/contracts"; import { @@ -18,10 +20,13 @@ import { ComposerToolbarScroller, ComposerToolbarTrigger, } from "../../components/ComposerToolbarTrigger"; +import { AndroidScreenHeader } from "../../components/AndroidScreenHeader"; import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip"; -import { ControlPillMenu } from "../../components/ControlPill"; +import { ControlPill, ControlPillMenu } from "../../components/ControlPill"; import { ProviderIcon } from "../../components/ProviderIcon"; +import { ComposerSurface } from "./ThreadComposer"; +import { makeTurnCommandMetadata } from "../../lib/commandMetadata"; import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages"; import { applyProviderOptionMenuEvent, @@ -29,13 +34,22 @@ import { providerOptionsConfigurationLabel, resolveProviderOptionDescriptors, } from "../../lib/providerOptions"; -import { buildThreadRoutePath } from "../../lib/routes"; -import { scopedProjectKey } from "../../lib/scopedEntities"; -import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; -import { getComposerDraftSnapshot } from "../../state/use-composer-drafts"; +import { useScaledTextRole } from "../settings/appearance/useScaledTextRole"; +import { + clearComposerDraftContent, + getComposerDraftSnapshot, + mergeComposerDraftContent, + restoreComposerDraftSnapshot, + type ComposerDraft, +} from "../../state/use-composer-drafts"; import { useProjects } from "../../state/entities"; +import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn"; +import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration"; +import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox"; +import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry"; import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider"; import { useCreateProjectThread } from "./use-project-actions"; +import { useIncomingShare } from "../sharing/IncomingShareProvider"; function formatWorkspaceLabel(input: { readonly workspaceMode: string; @@ -54,33 +68,192 @@ export function NewTaskDraftScreen(props: { readonly environmentId?: string; readonly projectId?: string; }; + /** Queued outbox message id when editing an existing pending task. */ + readonly pendingTaskId?: string; + /** Durable native share inbox item to merge into this project draft. */ + readonly incomingShareId?: string; }) { const projects = useProjects(); const createProjectThread = useCreateProjectThread(); const flow = useNewTaskFlow(); - const router = useRouter(); + const navigation = useNavigation(); + const { + consumeShare, + getShare, + isLoading: isIncomingShareInboxLoading, + releaseShareReservation, + reserveShare, + } = useIncomingShare(); const insets = useSafeAreaInsets(); const colorScheme = useColorScheme(); const isKeyboardVisible = useKeyboardState((state) => state.isVisible); const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10); const { logicalProjects, selectedProject, setProject } = flow; + const { connectedEnvironments } = useRemoteConnectionStatus(); + const environmentConnected = + selectedProject !== null && + connectedEnvironments.find( + (environment) => environment.environmentId === selectedProject.environmentId, + )?.connectionState === "connected"; const promptInputRef = useRef(null); const loadedBranchesProjectKeyRef = useRef(null); + const [isComposerFocused, setIsComposerFocused] = useState(false); + const [importingShareKey, setImportingShareKey] = useState(null); + const [isCancellingShareImport, setIsCancellingShareImport] = useState(false); + const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState(null); + const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false); + const [shareImportAttempt, setShareImportAttempt] = useState(0); + const startedShareImportKeyRef = useRef(null); + const cancellingShareImportKeyRef = useRef(null); + const shareImportDraftBackupRef = useRef(new Map()); + const activeShareImportTokenRef = useRef(null); + const shareImportMountedRef = useRef(true); + const latestDraftKeyRef = useRef(flow.draftKey); + const latestIncomingShareIdRef = useRef(props.incomingShareId); + latestDraftKeyRef.current = flow.draftKey; + latestIncomingShareIdRef.current = props.incomingShareId; + const isImportingShare = importingShareKey !== null; + const alertedUnavailableIncomingShareIdRef = useRef(null); + const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null; + const requestedInitialProjectAvailable = Boolean( + props.initialProjectRef?.environmentId && + props.initialProjectRef.projectId && + projects.some( + (project) => + project.environmentId === props.initialProjectRef?.environmentId && + project.id === props.initialProjectRef?.projectId, + ), + ); + const isProjectPickerReturnActive = + isReturningToProjectPicker && !requestedInitialProjectAvailable; + const isIncomingShareTransferPending = Boolean( + incomingShare && cancelledIncomingShareId !== props.incomingShareId, + ); + usePreventRemove( + (isIncomingShareTransferPending && !isProjectPickerReturnActive) || isCancellingShareImport, + () => undefined, + ); + const hasImportedIncomingShare = Boolean( + props.incomingShareId && + flow.draftKey && + getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId), + ); + const isIncomingShareUnavailable = Boolean( + props.incomingShareId && + !isIncomingShareInboxLoading && + !incomingShare && + !hasImportedIncomingShare, + ); + const isIncomingShareReady = + !props.incomingShareId || + (hasImportedIncomingShare && !incomingShare) || + isIncomingShareUnavailable; + const appliedInitialProjectKeyRef = useRef(null); + useEffect(() => { + if (cancelledIncomingShareId === props.incomingShareId) { + navigation.goBack(); + } + }, [cancelledIncomingShareId, navigation, props.incomingShareId]); + useEffect(() => { + if (!isReturningToProjectPicker) { + return; + } + if (requestedInitialProjectAvailable) { + setIsReturningToProjectPicker(false); + return; + } + // Let usePreventRemove commit its disabled state before replacing this + // route, otherwise the transfer guard can swallow the fallback action. + const frame = requestAnimationFrame(() => { + navigation.dispatch( + StackActions.replace("NewTask", { incomingShareId: props.incomingShareId }), + ); + }); + return () => cancelAnimationFrame(frame); + }, [ + isReturningToProjectPicker, + navigation, + props.incomingShareId, + requestedInitialProjectAvailable, + ]); + useEffect(() => { + if (!shareImportMountedRef.current) { + startedShareImportKeyRef.current = null; + } + shareImportMountedRef.current = true; + return () => { + appliedInitialProjectKeyRef.current = null; + shareImportMountedRef.current = false; + activeShareImportTokenRef.current = null; + cancellingShareImportKeyRef.current = null; + }; + }, []); - const borderColor = useThemeColor("--color-border"); + const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask } = flow; + const attemptedPendingTaskIdRef = useRef(null); + useEffect(() => { + if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) { + return; + } + // Attempt each pending task once: after it is delivered or deleted the + // editing session legitimately ends, and re-running must not navigate. + if (attemptedPendingTaskIdRef.current === props.pendingTaskId) { + return; + } + attemptedPendingTaskIdRef.current = props.pendingTaskId; + if (!beginEditingPendingTask(props.pendingTaskId)) { + // The queued task no longer exists (sent or deleted before opening). + navigation.dispatch(StackActions.replace("NewTask")); + } + }, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]); + + useEffect(() => { + if (!props.pendingTaskId) return; + return () => { + // Allow a later navigation for the same pending task to re-hydrate it. + attemptedPendingTaskIdRef.current = null; + cancelEditingPendingTask(); + }; + }, [props.pendingTaskId, cancelEditingPendingTask]); + + const foregroundColor = useThemeColor("--color-foreground"); + const regularFontFamily = useFontFamily("regular"); + const bodyText = useScaledTextRole("body"); + const headlineText = useScaledTextRole("headline"); const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)"; const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)"; + // A new navigation to this mounted screen delivers a fresh initialProjectRef + // reference — treat it as a new request and let it apply again. + const lastInitialProjectRefRef = useRef(props.initialProjectRef); + useEffect(() => { - if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) { + // Pending-task editing owns project selection (and must not fall through + // to the replace("NewTask") fallback while its hydration is in flight). + if (props.pendingTaskId) { + return; + } + if (lastInitialProjectRefRef.current !== props.initialProjectRef) { + lastInitialProjectRefRef.current = props.initialProjectRef; + appliedInitialProjectKeyRef.current = null; + } + const initialEnvironmentId = props.initialProjectRef?.environmentId; + const initialProjectId = props.initialProjectRef?.projectId; + if (initialEnvironmentId && initialProjectId) { const directProject = projects.find( (project) => - project.environmentId === props.initialProjectRef?.environmentId && - project.id === props.initialProjectRef?.projectId, + project.environmentId === initialEnvironmentId && project.id === initialProjectId, ) ?? null; if (directProject) { + // Apply the route's project once. Re-applying on every change would + // instantly revert environment/project switches made in the picker. + const directProjectKey = `${directProject.environmentId}:${directProject.id}`; + if (appliedInitialProjectKeyRef.current === directProjectKey) { + return; + } + appliedInitialProjectKeyRef.current = directProjectKey; if ( selectedProject?.environmentId === directProject.environmentId && selectedProject.id === directProject.id @@ -90,6 +263,14 @@ export function NewTaskDraftScreen(props: { setProject(directProject); return; } + + if (projects.length > 0) { + // Never fall through to the flow provider's temporary first-project + // default. Return to the picker with the share id intact so the user + // can choose an available destination. + setIsReturningToProjectPicker(true); + } + return; } if (selectedProject) { @@ -101,13 +282,14 @@ export function NewTaskDraftScreen(props: { return; } - router.replace("/new"); + navigation.dispatch(StackActions.replace("NewTask")); }, [ logicalProjects, projects, - props.initialProjectRef?.environmentId, - props.initialProjectRef?.projectId, - router, + props.initialProjectRef, + props.incomingShareId, + props.pendingTaskId, + navigation, selectedProject, setProject, ]); @@ -126,7 +308,208 @@ export function NewTaskDraftScreen(props: { }, [flow.loadBranches, selectedProject]); useEffect(() => { - if (!selectedProject) { + const shareId = props.incomingShareId; + const draftKey = flow.draftKey; + const destinationProject = selectedProject; + const initialEnvironmentId = props.initialProjectRef?.environmentId; + const initialProjectId = props.initialProjectRef?.projectId; + const selectedProjectMatchesRoute = + !initialEnvironmentId || + !initialProjectId || + (destinationProject?.environmentId === initialEnvironmentId && + destinationProject.id === initialProjectId); + if ( + !shareId || + !draftKey || + !destinationProject || + !selectedProjectMatchesRoute || + cancelledIncomingShareId === shareId + ) { + return; + } + const importKey = `${shareId}:${draftKey}`; + if ( + startedShareImportKeyRef.current === importKey || + cancellingShareImportKeyRef.current === importKey + ) { + return; + } + + if (!incomingShare) { + if (isIncomingShareUnavailable && alertedUnavailableIncomingShareIdRef.current !== shareId) { + alertedUnavailableIncomingShareIdRef.current = shareId; + Alert.alert( + "Shared content unavailable", + "The shared content is no longer in the inbox. You can continue editing this task draft.", + ); + } + return; + } + + if (alertedUnavailableIncomingShareIdRef.current === shareId) { + alertedUnavailableIncomingShareIdRef.current = null; + } + startedShareImportKeyRef.current = importKey; + const draftBackup = + shareImportDraftBackupRef.current.get(importKey) ?? getComposerDraftSnapshot(draftKey); + shareImportDraftBackupRef.current.set(importKey, draftBackup); + const importToken = Symbol(importKey); + let didReserveShare = false; + let needsDraftRestore = false; + activeShareImportTokenRef.current = importToken; + setImportingShareKey(importKey); + void (async () => { + await reserveShare(shareId, { + environmentId: String(destinationProject.environmentId), + projectId: String(destinationProject.id), + }); + didReserveShare = true; + if ( + !shareImportMountedRef.current || + activeShareImportTokenRef.current !== importToken || + latestDraftKeyRef.current !== draftKey || + latestIncomingShareIdRef.current !== shareId + ) { + return; + } + needsDraftRestore = true; + const { skippedAttachmentCount } = await mergeComposerDraftContent(draftKey, { + text: incomingShare.text, + attachments: incomingShare.attachments, + sourceShareId: shareId, + }); + if ( + !shareImportMountedRef.current || + activeShareImportTokenRef.current !== importToken || + latestDraftKeyRef.current !== draftKey || + latestIncomingShareIdRef.current !== shareId + ) { + // The durable reservation makes an interrupted transfer resume only + // in this project instead of copying into a second project draft. + return; + } + await consumeShare(shareId); + if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) { + return; + } + const warnings = [...incomingShare.warnings]; + if (skippedAttachmentCount > 0) { + warnings.push( + `${skippedAttachmentCount} shared image${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`, + ); + } + if (warnings.length > 0) { + Alert.alert("Some shared content was skipped", warnings.join("\n")); + } + shareImportDraftBackupRef.current.delete(importKey); + })() + .catch((error) => { + if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) { + return; + } + Alert.alert( + "Could not import shared content", + error instanceof Error ? error.message : "The shared content could not be saved.", + [ + { + text: "Cancel import", + style: "cancel", + onPress: () => { + const cancelImport = async (): Promise => { + if (!shareImportMountedRef.current) { + return; + } + // Latch synchronously before restoring the draft. The + // restore publishes atom state and can re-run the import + // effect before React commits the cancelling state update. + cancellingShareImportKeyRef.current = importKey; + setIsCancellingShareImport(true); + try { + if (needsDraftRestore) { + await restoreComposerDraftSnapshot(draftKey, draftBackup); + needsDraftRestore = false; + } + if (didReserveShare) { + await releaseShareReservation(shareId, { + environmentId: String(destinationProject.environmentId), + projectId: String(destinationProject.id), + }); + } + shareImportDraftBackupRef.current.delete(importKey); + if (shareImportMountedRef.current) { + setIsCancellingShareImport(false); + setCancelledIncomingShareId(shareId); + } + } catch (cancelError) { + if (!shareImportMountedRef.current) { + return; + } + Alert.alert( + "Could not cancel import", + cancelError instanceof Error + ? cancelError.message + : "The shared content could not be restored safely.", + [ + { + text: "Retry import", + onPress: () => { + cancellingShareImportKeyRef.current = null; + setIsCancellingShareImport(false); + setShareImportAttempt((attempt) => attempt + 1); + }, + }, + { + text: "Retry cancel", + onPress: () => void cancelImport(), + }, + ], + { cancelable: false }, + ); + } + }; + void cancelImport(); + }, + }, + { + text: "Retry", + onPress: () => setShareImportAttempt((attempt) => attempt + 1), + }, + ], + { cancelable: false }, + ); + }) + .finally(() => { + if (startedShareImportKeyRef.current === importKey) { + // Every terminal path, including an invalidated operation, must + // release the synchronous start latch so this transfer can retry. + startedShareImportKeyRef.current = null; + } + if (shareImportMountedRef.current && activeShareImportTokenRef.current === importToken) { + activeShareImportTokenRef.current = null; + setImportingShareKey(null); + } + }); + }, [ + consumeShare, + cancelledIncomingShareId, + flow.draftKey, + hasImportedIncomingShare, + incomingShare, + isIncomingShareInboxLoading, + isIncomingShareUnavailable, + props.incomingShareId, + props.initialProjectRef?.environmentId, + props.initialProjectRef?.projectId, + releaseShareReservation, + reserveShare, + selectedProject, + shareImportAttempt, + ]); + + useEffect(() => { + // Android starts with the collapsed composer pill (like an open thread) + // and only expands/focuses when tapped. + if (!selectedProject || Platform.OS === "android") { return; } @@ -148,10 +531,11 @@ export function NewTaskDraftScreen(props: { flow.environments.map((environment) => ({ id: `environment:${environment.environmentId}`, title: environment.environmentLabel, + attributes: isIncomingShareTransferPending ? { disabled: true } : undefined, state: flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined, })), - [flow.environments, flow.selectedEnvironmentId], + [flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending], ); const modelMenuActions = useMemo( @@ -273,12 +657,24 @@ export function NewTaskDraftScreen(props: { subtitle: flow.selectedBranchName ?? "Choose branch", subactions: branchActions, }, + ...(flow.workspaceMode === "worktree" + ? [ + { + id: "workspace:start-from-origin", + title: "Start from origin", + subtitle: "Base the worktree on the latest origin branch", + image: "arrow.triangle.pull", + state: flow.startFromOrigin ? ("on" as const) : undefined, + }, + ] + : []), ]; }, [ flow.availableBranches, flow.branchesLoading, flow.selectedBranchName, flow.selectedProject, + flow.startFromOrigin, flow.workspaceMode, ]); @@ -304,20 +700,23 @@ export function NewTaskDraftScreen(props: { [currentBranchName, flow.selectedBranchName, flow.workspaceMode], ); function handleModelMenuAction(event: string) { - if (!event.startsWith("model:")) { + if (isIncomingShareTransferPending || !event.startsWith("model:")) { return; } flow.setSelectedModelKey(event.slice("model:".length)); } function handleEnvironmentMenuAction(event: string) { - if (!event.startsWith("environment:")) { + if (isIncomingShareTransferPending || !event.startsWith("environment:")) { return; } flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length))); } function handleOptionsMenuAction(event: string) { + if (isIncomingShareTransferPending) { + return; + } const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event); if (providerOptions) { flow.setSelectedModelOptions(providerOptions); @@ -337,12 +736,19 @@ export function NewTaskDraftScreen(props: { } function handleWorkspaceMenuAction(event: string) { + if (isIncomingShareTransferPending) { + return; + } if (event.startsWith("workspace:mode:")) { flow.setWorkspaceMode( event.slice("workspace:mode:".length) as Parameters[0], ); return; } + if (event === "workspace:start-from-origin") { + flow.setStartFromOrigin(!flow.startFromOrigin); + return; + } if (event.startsWith("workspace:branch:")) { const branchName = event.slice("workspace:branch:".length); const branch = flow.availableBranches.find((candidate) => candidate.name === branchName); @@ -353,6 +759,9 @@ export function NewTaskDraftScreen(props: { } async function handlePickImages(): Promise { + if (isIncomingShareTransferPending) { + return; + } const result = await pickComposerImages({ existingCount: flow.attachments.length }); if (result.images.length > 0) { flow.appendAttachments(result.images); @@ -378,17 +787,17 @@ export function NewTaskDraftScreen(props: { async function handleStart(): Promise { const selectedProject = flow.selectedProject; - if (!selectedProject) { + const draftKey = flow.draftKey; + if (!selectedProject || !draftKey) { return; } - const draft = getComposerDraftSnapshot( - `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`, - ); + const draft = getComposerDraftSnapshot(draftKey); const modelSelection = draft.modelSelection ?? flow.selectedModel; const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode; const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName; const selectedWorktreePath = draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath; + const startFromOrigin = draft.workspaceSelection?.startFromOrigin ?? flow.startFromOrigin; const runtimeMode = draft.runtimeMode ?? flow.runtimeMode; const interactionMode = draft.interactionMode ?? flow.interactionMode; const initialMessageText = draft.text.trim(); @@ -402,17 +811,75 @@ export function NewTaskDraftScreen(props: { return; } + const editingPendingTask = flow.editingPendingTask; + + if (!environmentConnected) { + // Offline: park the task in the outbox; the drain sends it when the + // environment reconnects. Editing an existing pending task re-queues it + // under its original identifiers. + const metadata = editingPendingTask + ? { + threadId: editingPendingTask.threadId, + commandId: editingPendingTask.commandId, + messageId: editingPendingTask.messageId, + createdAt: editingPendingTask.createdAt, + } + : makeTurnCommandMetadata(); + const message = flow.buildPendingTaskMessage(metadata); + if (!message) { + return; + } + flow.setSubmitting(true); + try { + await enqueueThreadOutboxMessage(message); + } catch (error) { + Alert.alert( + "Could not queue task", + error instanceof Error ? error.message : "The task could not be saved to the outbox.", + ); + return; + } finally { + flow.setSubmitting(false); + } + if (editingPendingTask) { + flow.finishEditingPendingTask(); + } else { + clearComposerDraftContent(draftKey); + } + navigation.getParent()?.goBack(); + return; + } + flow.setSubmitting(true); + // Arm the lock-screen card before the async thread creation: backgrounding + // the app right after tapping submit would otherwise reject the foreground + // -only Activity start. If creation fails, the token registration's replay + // finds no work and ends the card within seconds. + armAgentAwarenessLiveActivityForLocalWork({ + threadTitle: deriveThreadTitleFromPrompt(initialMessageText), + projectTitle: selectedProject.title, + }); const result = await createProjectThread({ project: selectedProject, modelSelection, envMode: workspaceMode, branch: selectedBranchName, worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath, + startFromOrigin, runtimeMode, interactionMode, initialMessageText, initialAttachments: draft.attachments, + ...(editingPendingTask + ? { + turnMetadata: { + threadId: editingPendingTask.threadId, + commandId: editingPendingTask.commandId, + messageId: editingPendingTask.messageId, + createdAt: editingPendingTask.createdAt, + }, + } + : {}), }); flow.setSubmitting(false); @@ -427,52 +894,246 @@ export function NewTaskDraftScreen(props: { return; } - flow.setPrompt(""); - flow.clearAttachments(); - router.replace(buildThreadRoutePath(result.value)); + if (editingPendingTask) { + try { + await removeThreadOutboxMessage(editingPendingTask); + } catch (error) { + console.warn("[new-task] failed to remove delivered pending task", error); + } + flow.finishEditingPendingTask(); + } else { + clearComposerDraftContent(draftKey); + } + navigation.dispatch( + StackActions.replace("Thread", { + environmentId: String(result.value.environmentId), + threadId: String(result.value.threadId), + }), + ); } if (!selectedProject) { return ( - + {Platform.OS === "android" ? ( + <> + + navigation.goBack()} /> + + ) : ( + + )} + + ); + } + + const isAndroid = Platform.OS === "android"; + const isDarkMode = colorScheme === "dark"; + // Android expansion follows native editor focus so relayout cannot race + // the touch gesture that opens the keyboard. + const isExpanded = !isAndroid || isComposerFocused; + const canStart = + Boolean(flow.selectedProject) && + Boolean(flow.selectedModel) && + flow.prompt.trim().length > 0 && + isIncomingShareReady && + !isImportingShare && + !flow.submitting && + !(flow.workspaceMode === "worktree" && !flow.selectedBranchName); + const promptEditor = ( + setIsComposerFocused(true)} + onBlur={() => setIsComposerFocused(false)} + onPasteImages={(uris) => void handleNativePasteImages(uris)} + placeholder={`Describe a coding task in ${selectedProject.title}`} + // Same collapsed centering as ThreadComposer: native vertical gravity + // in a pill-height box. + singleLineCentered={!isExpanded} + contentInsetVertical={isAndroid ? 0 : undefined} + style={ + isAndroid + ? isExpanded + ? { minHeight: 80, maxHeight: 160, paddingHorizontal: 4, paddingVertical: 4 } + : { height: 36 } + : { flex: 1, minHeight: 0 } + } + textStyle={ + isAndroid + ? { ...bodyText, color: foregroundColor, fontFamily: regularFontFamily } + : headlineText + } + /> + ); + + const toolbarPills = ( + <> + void handlePickImages()} + showChevron={false} + disabled={isIncomingShareTransferPending} + /> + handleModelMenuAction(nativeEvent.event)} + > + } + label={flow.selectedModelOption?.label ?? "Model"} + /> + + handleOptionsMenuAction(nativeEvent.event)} + > + + + handleEnvironmentMenuAction(nativeEvent.event)} + > + + + handleWorkspaceMenuAction(nativeEvent.event)} + > + + + + ); + + const startButton = ( + void handleStart()} + variant="primary" + showChevron={false} + disabled={!canStart} + /> + ); + + if (isAndroid) { + // The draft is a thread that doesn't exist yet, so it mirrors the thread + // page: in-screen header, empty feed canvas above, and the same floating + // composer chrome as ThreadComposer (collapsed pill → expanded card). + return ( + + + navigation.goBack()} /> + + + + + + + {isExpanded && flow.attachments.length > 0 ? ( + + undefined : flow.removeAttachment + } + /> + + ) : null} + {promptEditor} + {!isExpanded ? ( + void handleStart()} + /> + ) : null} + + + {isExpanded ? ( + + + {toolbarPills} + + {startButton} + + ) : null} + + ); } return ( - + - - - void handleNativePasteImages(uris)} - placeholder={`Describe a coding task in ${selectedProject.title}`} - style={{ flex: 1, minHeight: 0 }} - textStyle={MOBILE_TYPOGRAPHY.composer} - /> - + + {promptEditor} - + {flow.attachments.length > 0 ? ( - + undefined : flow.removeAttachment} imageSize={88} imageBorderRadius={20} /> @@ -483,68 +1144,9 @@ export function NewTaskDraftScreen(props: { fadeOpaque={sheetFadeOpaque} fadeTransparent={sheetFadeTransparent} > - void handlePickImages()} - showChevron={false} - /> - handleModelMenuAction(nativeEvent.event)} - > - - } - label={flow.selectedModelOption?.label ?? "Model"} - /> - - handleOptionsMenuAction(nativeEvent.event)} - > - - - handleEnvironmentMenuAction(nativeEvent.event)} - > - - - handleWorkspaceMenuAction(nativeEvent.event)} - > - - + {toolbarPills} - void handleStart()} - variant="primary" - showChevron={false} - disabled={ - !flow.selectedProject || - !flow.selectedModel || - flow.prompt.trim().length === 0 || - flow.submitting || - (flow.workspaceMode === "worktree" && !flow.selectedBranchName) - } - /> + {startButton} diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx new file mode 100644 index 0000000000..99985385ea --- /dev/null +++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx @@ -0,0 +1,326 @@ +import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader"; +import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { SymbolView } from "../../components/AppSymbol"; +import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { useEffect, useMemo, useRef } from "react"; +import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { useThemeColor } from "../../lib/useThemeColor"; +import { cn } from "../../lib/cn"; + +import { AndroidScreenHeader } from "../../components/AndroidScreenHeader"; +import { AppText as Text } from "../../components/AppText"; +import { ProjectFavicon } from "../../components/ProjectFavicon"; +import { useProjects, useThreadShells } from "../../state/entities"; +import type { WorkspaceState } from "../../state/workspaceModel"; +import { useWorkspaceState } from "../../state/workspace"; +import { groupProjectsByRepository } from "../../lib/repositoryGroups"; +import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; +import { useIncomingShare } from "../sharing/IncomingShareProvider"; + +type NewTaskRouteParams = { + readonly incomingShareId?: string | string[]; +}; + +function deriveProjectEmptyState(catalogState: WorkspaceState): { + readonly title: string; + readonly detail: string; + readonly loading: boolean; +} { + if (catalogState.isLoadingConnections) { + return { + title: "Loading environments", + detail: "Checking saved environments on this device.", + loading: true, + }; + } + + if (!catalogState.hasConnections) { + return { + title: "No environments connected", + detail: "Add an environment before creating a task.", + loading: false, + }; + } + + if ( + (catalogState.connectionState === "available" || + catalogState.connectionState === "offline" || + catalogState.connectionState === "error") && + !catalogState.hasLoadedShellSnapshot + ) { + return { + title: "Environment unavailable", + detail: + catalogState.connectionError ?? + "The saved environment is offline. Check the URL or start the environment, then retry.", + loading: false, + }; + } + + if ( + catalogState.hasConnectingEnvironment && + !catalogState.hasLoadedShellSnapshot && + catalogState.connectionError === null + ) { + return { + title: "Connecting to environment", + detail: "Loading projects from the saved environment.", + loading: true, + }; + } + + return { + title: "No projects found", + detail: "The connected environment did not report any projects.", + loading: false, + }; +} + +export function NewTaskRouteScreen({ route }: StaticScreenProps) { + const projects = useProjects(); + const threads = useThreadShells(); + const { state: catalogState } = useWorkspaceState(); + const navigation = useNavigation(); + const isFocused = useIsFocused(); + const { layout } = useAdaptiveWorkspaceLayout(); + const insets = useSafeAreaInsets(); + const chevronColor = useThemeColor("--color-chevron"); + const accentColor = useThemeColor("--color-icon-muted"); + const { getShare, releaseShareReservation } = useIncomingShare(); + const routeShareId = Array.isArray(route.params?.incomingShareId) + ? route.params.incomingShareId[0] + : route.params?.incomingShareId; + const incomingShare = routeShareId ? getShare(routeShareId) : null; + const incomingShareSubtitle = incomingShare + ? incomingShare.attachments.length === 0 + ? "Choose a project for what you shared" + : incomingShare.attachments.length === 1 + ? "Choose a project for the image you shared" + : `Choose a project for the ${incomingShare.attachments.length} images you shared` + : null; + const screenTitle = incomingShare ? "Start a task" : "Choose project"; + const repositoryGroups = useMemo( + () => groupProjectsByRepository({ projects, threads }), + [projects, threads], + ); + const items = useMemo(() => { + const nextItems: Array<{ + readonly environmentId: EnvironmentId; + readonly id: ProjectId; + readonly key: string; + readonly title: string; + readonly workspaceRoot: string; + }> = []; + for (const group of repositoryGroups) { + const project = group.projects[0]?.project; + if (!project) { + continue; + } + nextItems.push({ + environmentId: project.environmentId, + id: project.id, + key: group.key, + title: project.title, + workspaceRoot: project.workspaceRoot, + }); + } + return nextItems; + }, [repositoryGroups]); + const projectEmptyState = deriveProjectEmptyState(catalogState); + const resumedDestinationKeyRef = useRef(null); + const reservedDestinationProject = incomingShare?.destination + ? (projects.find( + (project) => + project.environmentId === incomingShare.destination?.environmentId && + project.id === incomingShare.destination?.projectId, + ) ?? null) + : null; + + async function selectProject(item: (typeof items)[number]): Promise { + if (incomingShare?.destination && !reservedDestinationProject) { + try { + await releaseShareReservation(incomingShare.id, incomingShare.destination); + } catch (error) { + Alert.alert( + "Could not change project", + error instanceof Error + ? error.message + : "The shared content reservation could not be updated.", + ); + return; + } + } + navigation.navigate("NewTaskSheet", { + screen: "NewTaskDraft", + params: { + environmentId: item.environmentId, + projectId: item.id, + title: item.title, + incomingShareId: incomingShare?.id, + }, + }); + } + + useEffect(() => { + const destination = incomingShare?.destination; + if (!destination) { + resumedDestinationKeyRef.current = null; + return; + } + if (!isFocused) { + // Returning from the reserved draft is a fresh resume attempt. Keeping + // this latch set would leave every project row disabled with no route. + resumedDestinationKeyRef.current = null; + return; + } + const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`; + if (resumedDestinationKeyRef.current === destinationKey) { + return; + } + if (!reservedDestinationProject) { + return; + } + resumedDestinationKeyRef.current = destinationKey; + navigation.navigate("NewTaskSheet", { + screen: "NewTaskDraft", + params: { + environmentId: reservedDestinationProject.environmentId, + projectId: reservedDestinationProject.id, + title: reservedDestinationProject.title, + incomingShareId: incomingShare.id, + }, + }); + }, [incomingShare, isFocused, navigation, reservedDestinationProject]); + + return ( + + {Platform.OS === "android" ? ( + <> + {/* Android renders its own in-screen header instead of the native bar. */} + + navigation.goBack() : undefined} + actions={[ + { + accessibilityLabel: "Add project", + icon: "plus", + onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }), + }, + ]} + /> + + ) : ( + <> + + + {layout.usesSplitView ? ( + navigation.goBack()} + separateBackground + /> + ) : null} + navigation.navigate("NewTaskSheet", { screen: "AddProject" })} + separateBackground + /> + + + )} + + + {items.length === 0 ? ( + + {projectEmptyState.loading ? : null} + + {projectEmptyState.title} + + + {projectEmptyState.detail} + + {!catalogState.hasReadyEnvironment ? ( + navigation.navigate("ConnectionsNew")} + > + + Add environment + + + ) : ( + navigation.navigate("NewTaskSheet", { screen: "AddProject" })} + > + + Add new project + + + )} + + ) : ( + + {items.map((item, index) => { + const isFirst = index === 0; + const isLast = index === items.length - 1; + + return ( + void selectProject(item)} + className={cn( + "bg-card px-4 py-3.5", + !isFirst && "border-t border-border-subtle", + isFirst && "rounded-t-[24px]", + isLast && "rounded-b-[24px]", + )} + > + + + + + + {item.title} + + + + + ); + })} + + )} + + + ); +} diff --git a/apps/mobile/src/features/threads/PendingApprovalCard.tsx b/apps/mobile/src/features/threads/PendingApprovalCard.tsx index 2906bcd7d1..5b1cef76a5 100644 --- a/apps/mobile/src/features/threads/PendingApprovalCard.tsx +++ b/apps/mobile/src/features/threads/PendingApprovalCard.tsx @@ -25,7 +25,7 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) { {props.approval.requestKind} {props.approval.detail ? ( - + {props.approval.detail} ) : null} diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsx index cdff7a3b96..8bcdd80451 100644 --- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx +++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx @@ -42,7 +42,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) { {question.header} - + {question.question} diff --git a/apps/mobile/src/features/threads/ThreadActivityInspector.tsx b/apps/mobile/src/features/threads/ThreadActivityInspector.tsx index 2fe661319b..9313ad4a0a 100644 --- a/apps/mobile/src/features/threads/ThreadActivityInspector.tsx +++ b/apps/mobile/src/features/threads/ThreadActivityInspector.tsx @@ -1,26 +1,41 @@ import * as Haptics from "expo-haptics"; import { SymbolView } from "expo-symbols"; -import type { EnvironmentId } from "@t3tools/contracts"; -import { useRouter } from "expo-router"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { useNavigation } from "@react-navigation/native"; import { useMemo, useState } from "react"; import { Linking, Pressable, ScrollView, type ColorValue, View } from "react-native"; import { AppText as Text } from "../../components/AppText"; import type { ThreadFeedActivity } from "../../lib/threadActivity"; import { buildThreadActivityInspector } from "../../lib/threadActivityInspector"; -import { buildThreadFilesNavigation } from "../../lib/routes"; import { resolveWorkspaceRelativeFilePath } from "../files/filePath"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; import { useV2ItemSupport } from "../../state/v2-item-support"; +function buildThreadFileParams( + environmentId: EnvironmentId, + threadId: ThreadId, + relativePath: string, + line?: number | null, +) { + return { + environmentId: String(environmentId), + threadId: String(threadId), + path: relativePath.split("/").filter((segment) => segment.length > 0), + ...(Number.isFinite(line) && Number(line) > 0 + ? { line: String(Math.floor(Number(line))) } + : {}), + }; +} + export function ThreadActivityInspector(props: { readonly activity: ThreadFeedActivity; readonly environmentId: EnvironmentId; readonly iconColor: ColorValue; readonly workspaceRoot?: string | null; }) { - const router = useRouter(); + const navigation = useNavigation(); const row = props.activity.projectedItem; const support = useV2ItemSupport({ environmentId: props.environmentId, @@ -92,9 +107,11 @@ export function ThreadActivityInspector(props: { onPress={() => { if (!relativePath) return; void Haptics.selectionAsync(); - router.push( - buildThreadFilesNavigation( - { environmentId: props.environmentId, threadId: row.sourceThreadId }, + navigation.navigate( + "ThreadFile", + buildThreadFileParams( + props.environmentId, + row.sourceThreadId, relativePath, link.line, ), diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 3381e609ae..b8fa86623a 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -22,13 +22,17 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject import { ActivityIndicator, Image, + Platform, Pressable, useColorScheme, View, type ViewStyle, } from "react-native"; import ImageViewing from "react-native-image-viewing"; +import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated"; import { useThemeColor } from "../../lib/useThemeColor"; +import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration"; +import { scopedThreadKey } from "../../lib/scopedEntities"; import { AppText as Text } from "../../components/AppText"; import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip"; @@ -47,7 +51,7 @@ import { ControlPill, ControlPillMenu } from "../../components/ControlPill"; import { ProviderIcon } from "../../components/ProviderIcon"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { buildModelOptions, groupByProvider } from "../../lib/modelOptions"; -import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; +import { useScaledTextRole } from "../settings/appearance/useScaledTextRole"; import type { RemoteClientConnectionState } from "../../lib/connection"; import { insertRankedSearchResult, @@ -79,10 +83,17 @@ export interface ThreadComposerProps { readonly draftMessage: string; readonly draftAttachments: ReadonlyArray; readonly placeholder: string; + readonly contentMaxWidth?: number; readonly bottomInset?: number; readonly connectionState: RemoteClientConnectionState; readonly connectionError: string | null; readonly environmentLabel: string | null; + /** + * Message sync phase for the selected thread (drives the status pill): + * "loading" = first fetch, nothing to show yet; "syncing" = cached messages + * are on screen while they reconcile with the server. + */ + readonly threadSyncPhase?: "loading" | "syncing" | null; readonly selectedThread: EnvironmentThreadShell; readonly serverConfig: T3ServerConfig | null; readonly queueCount: number; @@ -106,47 +117,77 @@ export interface ThreadComposerProps { /** * The pill / card container — renders as LiquidGlassView on supported * iOS 26+ devices (progressive blur, native morph), opaque View otherwise. + * Exported so NewTaskDraftScreen can render the same composer chrome. */ -function ComposerSurface(props: { +// One timing for every piece of the expanded↔compact morph so the surface, +// toolbar, and siblings move together instead of popping between layouts. +// Android gets NO layout transition: the composer rides the keyboard via +// KeyboardStickyView (frame-synced to the IME), and a time-based morph +// running alongside that translate reads as jitter. Snapping the layout and +// letting the keyboard-synced slide be the only motion looks native there. +const COMPOSER_LAYOUT_TRANSITION = + Platform.OS === "android" ? undefined : LinearTransition.duration(220); + +export function ComposerSurface(props: { readonly children: ReactNode; readonly style: ViewStyle; readonly isDarkMode: boolean; }) { + // Drop shadow lives on a wrapper: `overflow: "hidden"` on the surface itself + // (needed to clip content to the pill shape) would clip the shadow on iOS. + const shadowStyle: ViewStyle = { + borderRadius: props.style.borderRadius, + shadowColor: "#000000", + shadowOpacity: props.isDarkMode ? 0.35 : 0.12, + shadowRadius: 14, + shadowOffset: { width: 0, height: 6 }, + elevation: 10, + }; + if (isLiquidGlassSupported) { return ( - - {props.children} - + + + {props.children} + + ); } return ( - - {props.children} - + + + {props.children} + + ); } +type ComposerStatusPillState = { + readonly kind: "unavailable" | "reconnecting" | "syncing"; + readonly label: string; +}; + function composerConnectionStatus(input: { readonly connectionError: string | null; readonly connectionState: RemoteClientConnectionState; readonly environmentLabel: string | null; -}): { readonly kind: "unavailable" | "reconnecting"; readonly label: string } | null { + readonly threadSyncPhase?: "loading" | "syncing" | null; +}): ComposerStatusPillState | null { const environmentLabel = input.environmentLabel ?? "Environment"; switch (input.connectionState) { @@ -171,15 +212,27 @@ function composerConnectionStatus(input: { case "available": return { kind: "unavailable", label: `${environmentLabel} is not connected` }; case "connected": + break; + } + + // Connected: the pill is the single loading/sync indicator. One stable + // label per open — "Loading" when starting from scratch, "Syncing" when + // cached messages are already visible. + switch (input.threadSyncPhase) { + case "loading": + return { kind: "syncing", label: "Loading messages..." }; + case "syncing": + return { kind: "syncing", label: "Syncing messages..." }; + default: return null; } } const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(props: { readonly onPress: () => void; - readonly status: { readonly kind: "unavailable" | "reconnecting"; readonly label: string }; + readonly status: ComposerStatusPillState; }) { - const isReconnecting = props.status.kind === "reconnecting"; + const isReconnecting = props.status.kind !== "unavailable"; return ( @@ -194,7 +247,7 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill( )} {props.status.label} @@ -207,10 +260,12 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill( export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) { const isDarkMode = useColorScheme() === "dark"; const foregroundColor = useThemeColor("--color-foreground"); + const bodyText = useScaledTextRole("body"); const fallbackInputRef = useRef(null); const inputRef = props.editorRef ?? fallbackInputRef; const [isFocused, setIsFocused] = useState(false); const wasExpandedBeforePreviewRef = useRef(false); + const inFlightThreadIdsRef = useRef(new Set()); const { onExpandedChange } = props; const [previewImageUri, setPreviewImageUri] = useState(null); @@ -255,6 +310,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer connectionError: props.connectionError, connectionState: props.connectionState, environmentLabel: props.environmentLabel, + threadSyncPhase: props.threadSyncPhase, }); const toolbarFadeOpaque = isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)"; const toolbarFadeTransparent = isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)"; @@ -448,9 +504,28 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer // ── Handle command selection ────────────────────────────── const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props; - const handleSend = useCallback(() => { - void onSendMessage(); - }, [onSendMessage]); + const handleSend = useCallback(async () => { + const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id); + if (inFlightThreadIdsRef.current.has(threadKey)) return; + inFlightThreadIdsRef.current.add(threadKey); + // Sending a prompt starts agent work: arm the lock-screen card now, while + // the app is foregrounded and the activity token can be registered. + armAgentAwarenessLiveActivityForLocalWork({ + threadTitle: props.selectedThread.title, + projectTitle: props.environmentLabel ?? "T3 Code", + }); + try { + await onSendMessage(); + } finally { + inFlightThreadIdsRef.current.delete(threadKey); + } + }, [ + onSendMessage, + props.environmentId, + props.environmentLabel, + props.selectedThread.id, + props.selectedThread.title, + ]); const handleCommandSelect = useCallback( (item: ComposerCommandItem) => { if (!composerTrigger) return; @@ -620,28 +695,24 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer } return ( - - + {composerTrigger && composerMenuItems.length > 0 ? ( - + {/* Attachment strip — inside the card, above the text input */} {isExpanded ? ( - 0 ? 10 : 0 }}> + 0 ? "pb-2.5" : undefined} + entering={FadeIn.duration(160)} + exiting={FadeOut.duration(120)} + > - + ) : null} - + {!isExpanded && props.draftAttachments.length > 0 ? ( - + {props.draftAttachments.slice(0, 3).map((image) => ( onPressImage(image.previewUri)}> ))} {props.draftAttachments.length > 3 ? ( - + +{props.draftAttachments.length - 3} @@ -759,87 +823,89 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer ) : null} {!isExpanded ? ( - showStopAction ? ( - - ) : ( - + {showStopAction ? ( + + ) : ( + + )} + + ) : null} + + + {isExpanded ? ( + // Toolbar row — matches draft page layout (expanded only) + + + + void props.onPickDraftImages()} + showChevron={false} + /> + handleModelMenuAction(nativeEvent.event)} + > + + } + label={currentModelOption?.label ?? currentModelSelection.model} + /> + + handleOptionsMenuAction(nativeEvent.event)} + > + + + {showStopAction ? ( + + ) : null} + + - ) - ) : null} - - - {/* Toolbar row — matches draft page layout (expanded only) */} - {isExpanded ? ( - - - void props.onPickDraftImages()} showChevron={false} /> - handleModelMenuAction(nativeEvent.event)} - > - - } - label={currentModelOption?.label ?? currentModelSelection.model} - /> - - handleOptionsMenuAction(nativeEvent.event)} - > - - - {showStopAction ? ( - - ) : null} - - - + + ) : null} {/* Queue count */} {props.queueCount > 0 ? ( - - {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send - automatically. - + + + {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send + automatically. + + ) : null} - + - + ); }); diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 1949020667..677ef0d3ff 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1,5 +1,6 @@ import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads"; import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard"; import type { LegendListRef } from "@legendapp/list/react-native"; import type { @@ -15,20 +16,19 @@ import type { } from "@t3tools/contracts"; import { formatElapsed } from "@t3tools/shared/orchestrationTiming"; import * as Haptics from "expo-haptics"; -import { useHeaderHeight } from "expo-router/build/react-navigation/elements"; import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; -import { View, type GestureResponderEvent } from "react-native"; -import { Gesture, GestureDetector } from "react-native-gesture-handler"; -import { KeyboardStickyView } from "react-native-keyboard-controller"; +import { Platform, View, type GestureResponderEvent } from "react-native"; +import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller"; +import Animated, { FadeInDown, FadeOut, LinearTransition } from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; -import { runOnJS } from "react-native-reanimated"; import { AppText as Text } from "../../components/AppText"; import type { ComposerEditorHandle } from "../../components/ComposerEditor"; import type { StatusTone } from "../../components/StatusPill"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; -import type { LayoutVariant } from "../../lib/layout"; +import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout"; import { scopedThreadKey } from "../../lib/scopedEntities"; +import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; import type { PendingApproval, PendingUserInput, @@ -64,6 +64,8 @@ export interface ThreadDetailScreenProps { readonly draftMessage: string; readonly draftAttachments: ReadonlyArray; readonly connectionStateLabel: EnvironmentConnectionPhase; + /** Message sync status for the selected thread (drives the composer status pill). */ + readonly threadSyncStatus?: EnvironmentThreadStatus; readonly activeThreadBusy: boolean; readonly environmentId: EnvironmentId; readonly projectWorkspaceRoot: string | null; @@ -71,7 +73,8 @@ export interface ThreadDetailScreenProps { readonly selectedThreadQueueCount: number; readonly serverConfig: T3ServerConfig | null; readonly layoutVariant?: LayoutVariant; - readonly onOpenDrawer: () => void; + readonly usesAutomaticContentInsets?: boolean; + readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void; readonly onOpenConnectionEditor: () => void; readonly onChangeDraftMessage: (value: string) => void; readonly onPickDraftImages: () => Promise; @@ -171,7 +174,11 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray - + + @@ -201,15 +218,12 @@ const WorkingDurationPill = memo(function WorkingDurationPill(props: { - + ); }); export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) { - const { onOpenDrawer } = props; - const insets = useSafeAreaInsets(); - const headerHeight = useHeaderHeight(); const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`; const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id); const composerEditorRef = useRef(null); @@ -222,20 +236,47 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread const [anchorMessageId, setAnchorMessageId] = useState(null); const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12); const contentPresentationKind = props.contentPresentation.kind; + // The raw sync status enters "synchronizing" on every full fetch, cached or + // not. Whether messages are already on screen decides the pill label: no + // data yet → "Loading messages", cached data reconciling → "Syncing". + const threadSyncPhase = (() => { + switch (props.threadSyncStatus) { + case "empty": + case "cached": + case "synchronizing": + if (contentPresentationKind === "ready") { + return "syncing" as const; + } + return contentPresentationKind === "loading" ? ("loading" as const) : null; + default: + return null; + } + })(); const selectedThreadFeed = props.selectedThreadFeed; const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME; const composerOverlapHeight = composerChrome + composerBottomInset; const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0; - const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8; + const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight; + // The overlay's measured height includes the home-indicator inset (the + // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes + // UIKit add the safe-area bottom to the content inset AGAIN — leaving a + // dead strip between the resting content and the composer. Report the + // overlay height minus the safe area; UIKit adds it back, and ThreadFeed + // hands LegendList the same delta via contentInsetEndStaticAdjustment so + // its end-scroll math matches the real resting position. + const nativeInsetOvercount = + props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0; const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset( listRef, composerOverlayRef, - estimatedOverlayHeight, + Math.max(0, estimatedOverlayHeight - nativeInsetOvercount), + -nativeInsetOvercount, ); const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef }); const showContent = props.showContent ?? true; const layoutVariant = props.layoutVariant ?? "compact"; const isSplitLayout = layoutVariant === "split"; + const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined; const selectedInstanceId = props.selectedThread.modelSelection.instanceId; useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed); const selectedProviderSkills = useMemo( @@ -245,28 +286,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread [props.serverConfig, selectedInstanceId], ); - const completeDrawerGesture = useCallback(() => { - void Haptics.selectionAsync(); - onOpenDrawer(); - }, [onOpenDrawer]); - - const drawerGestureThreshold = 80; - const headerDrawerGesture = useMemo( - () => - Gesture.Pan() - .enabled(!isSplitLayout) - .hitSlop({ left: 0, width: 40 }) - .activeOffsetX([10, 999]) - .failOffsetY([-24, 24]) - .onEnd((event) => { - const translationX = Math.max(event.translationX, 0); - if (event.y < drawerGestureThreshold && translationX > 56) { - runOnJS(completeDrawerGesture)(); - } - }), - [completeDrawerGesture, isSplitLayout], - ); - useLayoutEffect(() => { selectedThreadKeyRef.current = selectedThreadKey; }, [selectedThreadKey]); @@ -293,16 +312,31 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread return; } lastScrolledAnchorMessageIdRef.current = anchorMessageId; - void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => { - if ( - selectedThreadKeyRef.current !== targetThreadKey || - lastScrolledAnchorMessageIdRef.current !== anchorMessageId - ) { - return; - } - lastScrolledAnchorMessageIdRef.current = null; - freeze.set(false); - }); + // Wait for the keyboard dismissal (started by blur() on send) to finish + // before scrolling: scrollMessageToEnd freezes keyboard-driven inset + // updates while it runs, and a close event swallowed by that freeze + // leaves the keyboard padding permanently applied — overshooting the + // anchor and leaving a phantom bottom inset once the reply streams in. + void KeyboardController.dismiss() + .then(() => { + if ( + selectedThreadKeyRef.current !== targetThreadKey || + lastScrolledAnchorMessageIdRef.current !== anchorMessageId + ) { + return; + } + return scrollMessageToEnd({ animated: true, closeKeyboard: false }); + }) + .catch(() => { + if ( + selectedThreadKeyRef.current !== targetThreadKey || + lastScrolledAnchorMessageIdRef.current !== anchorMessageId + ) { + return; + } + lastScrolledAnchorMessageIdRef.current = null; + freeze.set(false); + }); }); return () => cancelAnimationFrame(frame); }, [ @@ -361,53 +395,63 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread }, []); return ( - - - {showContent ? ( - - - } - layoutVariant={layoutVariant} - skills={selectedProviderSkills} - /> - - ) : ( - - )} + + {showContent ? ( + + + } + layoutVariant={layoutVariant} + usesAutomaticContentInsets={props.usesAutomaticContentInsets} + onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange} + skills={selectedProviderSkills} + /> + + ) : ( + + )} - {/* Floating composer — sticks to keyboard via KeyboardStickyView */} - {showContent ? ( - - + {/* Floating composer — sticks to keyboard via KeyboardStickyView */} + {showContent ? ( + + {/* No paddingTop here: the overlay's measured height becomes the + list's bottom inset, so any padding above the pill/composer + pushes the resting content floor up by the same amount. */} + + {props.activeWorkStartedAt ? ( ) : null} @@ -418,7 +462,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread /> {props.activePendingApproval || props.activePendingUserInput ? ( - + {props.activePendingApproval ? ( ) : null} - + ) : null} + - - - - ) : null} - - + + + + ) : null} + ); }); diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 3646d8f9bd..7054625904 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -11,12 +11,15 @@ import { type RunId, } from "@t3tools/contracts"; import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList"; -import { SymbolView } from "expo-symbols"; -import { useRouter } from "expo-router"; +import { SymbolView } from "../../components/AppSymbol"; +import { HeaderHeightContext } from "@react-navigation/elements"; +import { useNavigation } from "@react-navigation/native"; import { memo, useCallback, + useContext, useEffect, + useLayoutEffect, useMemo, useRef, useState, @@ -33,6 +36,10 @@ import { ActivityIndicator, Image, Linking, + Platform, + type LayoutChangeEvent, + type NativeScrollEvent, + type NativeSyntheticEvent, Pressable, ScrollView, StyleSheet, @@ -45,8 +52,14 @@ import { import { TouchableOpacity } from "react-native-gesture-handler"; import ImageViewing from "react-native-image-viewing"; import { useSafeAreaInsets } from "react-native-safe-area-context"; -import type { SharedValue } from "react-native-reanimated"; +import Animated, { + FadeIn, + FadeInUp, + LinearTransition, + type SharedValue, +} from "react-native-reanimated"; import { useThemeColor } from "../../lib/useThemeColor"; +import { useFontFamily } from "../../lib/useFontFamily"; import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { hasNativeSelectableMarkdownText, @@ -61,21 +74,23 @@ import { parseReviewCommentMessageSegments, type ReviewInlineComment, } from "../review/reviewCommentSelection"; +import type { ReviewDiffTheme } from "../review/shikiReviewHighlighter"; import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface"; import { buildNativeReviewDiffData, createNativeReviewDiffTheme, NATIVE_REVIEW_DIFF_CONTENT_WIDTH, - NATIVE_REVIEW_DIFF_ROW_HEIGHT, - NATIVE_REVIEW_DIFF_STYLE, } from "../review/nativeReviewDiffAdapter"; import { buildReviewParsedDiff } from "../review/reviewModel"; import { cn } from "../../lib/cn"; -import type { LayoutVariant } from "../../lib/layout"; -import { buildThreadFilesNavigation } from "../../lib/routes"; -import { buildThreadRoutePath } from "../../lib/routes"; +import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../../lib/layout"; import { uuidv4 } from "../../lib/uuid"; -import { MOBILE_CODE_SURFACE, MOBILE_TYPOGRAPHY } from "../../lib/typography"; +import { + resolveMarkdownFontSizes, + resolveNativeMarkdownTypography, +} from "../../lib/appearancePreferences"; +import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; +import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface"; import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons"; import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links"; import { @@ -85,6 +100,7 @@ import { } from "../../lib/threadActivity"; import type { ThreadContentPresentation } from "./threadContentPresentation"; import { ThreadWorkLog } from "./thread-work-log"; +import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState"; import { useAssetUrl } from "../../state/assets"; import { appAtomRegistry } from "../../state/atom-registry"; import { environmentThreadShells, threadEnvironment } from "../../state/threads"; @@ -96,7 +112,6 @@ const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit", }); - function formatMessageTime(input: string): string { const timestamp = Date.parse(input); if (Number.isNaN(timestamp)) { @@ -105,6 +120,19 @@ function formatMessageTime(input: string): string { return MESSAGE_TIME_FORMATTER.format(timestamp); } +// Rows shift when content above them grows (streaming text, work-log folds); +// animating the container position turns those jumps into slides. +const FEED_ITEM_LAYOUT_TRANSITION = LinearTransition.duration(180); + +// Entering animations must only play for rows born just now — LegendList +// remounts rows when they scroll back into view, and replaying an entrance for +// old content would be its own kind of jank. +const FRESH_ENTRY_WINDOW_MS = 3_000; +function isFreshTimestamp(input: string): boolean { + const timestamp = Date.parse(input); + return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ENTRY_WINDOW_MS; +} + export interface ThreadFeedProps { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; @@ -121,7 +149,10 @@ export interface ThreadFeedProps { readonly contentTopInset?: number; readonly contentBottomInset?: number; readonly topAccessory?: ReactNode; + readonly contentMaxWidth?: number; readonly layoutVariant?: LayoutVariant; + readonly usesAutomaticContentInsets?: boolean; + readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void; readonly skills?: ReadonlyArray; } @@ -145,7 +176,7 @@ function AssistantForkButton(props: { sourceItemId: props.projectedItem.sourceItemId, }); const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response"); - const router = useRouter(); + const navigation = useNavigation(); const [busy, setBusy] = useState(false); const canFork = canForkProjectedAssistantItem({ projectedItem: props.projectedItem, @@ -176,12 +207,10 @@ function AssistantForkButton(props: { .then(async (result) => { if (result._tag !== "Success") return; await waitForThreadShell(props.environmentId, targetThreadId); - router.push( - buildThreadRoutePath({ - environmentId: props.environmentId, - threadId: targetThreadId, - }), - ); + navigation.navigate("Thread", { + environmentId: props.environmentId, + threadId: targetThreadId, + }); }) .finally(() => setBusy(false)); }} @@ -264,6 +293,12 @@ const MARKDOWN_COLORS = { }, } as const; +const MARKDOWN_MONO_FONT = Platform.select({ + ios: "ui-monospace", + android: "monospace", + default: "monospace", +}); + interface MarkdownStyleSets { readonly user: MarkdownStyleSet; readonly assistant: MarkdownStyleSet; @@ -296,10 +331,6 @@ const markdownLinkStyles = StyleSheet.create({ favicon: { borderRadius: 3, }, - file: { - fontFamily: "DMSans_700Bold", - fontWeight: "700", - }, }); const MarkdownExternalLink = memo(function MarkdownExternalLink(props: { @@ -312,12 +343,12 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: { return ( { void Linking.openURL(props.href); }} style={{ color: props.color, - fontFamily: "DMSans_400Regular", textDecorationLine: "none", }} > @@ -340,6 +371,122 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: { ); }); +function MarkdownCodeBlock(props: { + readonly backgroundColor: string; + readonly borderColor: string; + readonly content: string; + readonly copyTintColor: ColorValue; + readonly headerTextColor: string; + readonly fontSize: number; + readonly highlightCode: boolean; + readonly language?: string | null; + readonly lineHeight: number; + readonly textColor: string; + readonly theme: ReviewDiffTheme; +}) { + const content = props.content.replace(/\n$/, ""); + const languageLabel = props.language?.trim() || "text"; + const highlighted = useMarkdownCodeHighlight({ + code: content, + enabled: props.highlightCode && Boolean(props.language?.trim()), + language: props.language, + theme: props.theme, + }); + let tokenOffset = 0; + + return ( + + + + {languageLabel} + + + + + + {highlighted + ? highlighted.map((line, lineIndex) => { + const lineStartOffset = tokenOffset; + const lineText = line.map((token) => token.content).join(""); + const renderedLine = ( + + {line.map((token) => { + const startOffset = tokenOffset; + tokenOffset += token.content.length; + const fontStyle = + token.fontStyle !== null && (token.fontStyle & 1) === 1 + ? ("italic" as const) + : ("normal" as const); + const fontWeight = + token.fontStyle !== null && (token.fontStyle & 2) === 2 + ? ("700" as const) + : ("400" as const); + + return ( + + {token.content} + + ); + })} + {lineIndex + 1 < highlighted.length ? "\n" : ""} + + ); + if (lineIndex + 1 < highlighted.length) { + tokenOffset += 1; + } + return renderedLine; + }) + : content} + + + + ); +} + function useReviewCommentColors(): ReviewCommentColors { const colorScheme = useColorScheme(); const isDark = colorScheme === "dark"; @@ -365,8 +512,22 @@ function useReviewCommentColors(): ReviewCommentColors { function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSets { const colorScheme = useColorScheme(); - const colors = MARKDOWN_COLORS[colorScheme === "dark" ? "dark" : "light"]; + const { appearance } = useAppearancePreferences(); + const markdownFontSizes = useMemo( + () => resolveMarkdownFontSizes(appearance.baseFontSize), + [appearance.baseFontSize], + ); + const nativeMarkdownTypography = useMemo( + () => resolveNativeMarkdownTypography(appearance.baseFontSize), + [appearance.baseFontSize], + ); + const themeMode = colorScheme === "dark" ? "dark" : "light"; + const colors = MARKDOWN_COLORS[themeMode]; + const iconSubtleColor = String(useThemeColor("--color-icon-subtle")); const inlineSkillForeground = String(useThemeColor("--color-inline-skill-foreground")); + const userBubbleForegroundMuted = String(useThemeColor("--color-user-bubble-foreground-muted")); + const regularFontFamily = useFontFamily("regular"); + const boldFontFamily = useFontFamily("bold"); return useMemo(() => { const markdownBodyColor = colors.body; @@ -392,6 +553,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe link: markdownLinkColor, blockquote: markdownBlockquoteBorder, border: markdownHrColor, + surface: "transparent", surfaceLight: markdownBlockquoteBg, accent: markdownLinkColor, tableBorder: markdownHrColor, @@ -408,19 +570,19 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe xl: 16, }, fontSizes: { - s: 13, - m: 15, - h1: 20, - h2: 18, - h3: 16, - h4: 14, - h5: 14, - h6: 14, + s: markdownFontSizes.s, + m: markdownFontSizes.m, + h1: markdownFontSizes.h1, + h2: markdownFontSizes.h2, + h3: markdownFontSizes.h3, + h4: markdownFontSizes.h4, + h5: markdownFontSizes.h5, + h6: markdownFontSizes.h6, }, fontFamilies: { - regular: "DMSans_400Regular", - heading: "DMSans_700Bold", - mono: "ui-monospace", + regular: regularFontFamily, + heading: boldFontFamily, + mono: MARKDOWN_MONO_FONT, }, headingWeight: "700", borderRadius: { @@ -437,11 +599,11 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe list: { marginTop: 4, marginBottom: 8 }, list_item: { marginTop: 0, marginBottom: 4 }, task_list_item: { marginTop: 0, marginBottom: 4 }, - text: { lineHeight: 22 }, + text: { lineHeight: markdownFontSizes.bodyLineHeight }, bold: { fontWeight: "700", color: markdownStrongColor, - fontFamily: "DMSans_700Bold", + fontFamily: boldFontFamily, }, italic: { fontStyle: "italic" }, link: { @@ -457,7 +619,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe marginVertical: 10, }, heading: { - fontFamily: "DMSans_700Bold", + fontFamily: boldFontFamily, color: markdownStrongColor, marginTop: 18, marginBottom: 8, @@ -474,15 +636,18 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe inlineCodeTextColor: string, blockBackgroundColor: string, blockTextColor: string, + copyTintColor: ColorValue, preserveSoftBreaks: boolean, + highlightCode: boolean, ): CustomRenderers => ({ link: ({ children, href = "" }) => { const presentation = resolveMarkdownLinkPresentation(href); if (presentation.kind === "file") { return ( onLinkPress(href)} - style={[markdownLinkStyles.file, { color: inlineTextColor }]} + style={{ color: inlineTextColor }} > void): MarkdownStyleSe const linkHref = presentation.href; return ( { @@ -513,17 +679,14 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe } : undefined } - style={{ - color: markdownLinkColor, - textDecorationLine: "underline", - }} + style={{ color: markdownLinkColor }} > {children} ); }, list: ({ node, Renderer, ordered = false, start = 1 }) => ( - + {node.children?.map((child, index) => { const childKey = `${child.type}:${child.beg ?? "unknown"}:${child.end ?? "unknown"}`; if (child.type === "task_list_item") { @@ -532,27 +695,21 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe ); } return ( - + {ordered ? `${start + index}.` : "•"} - + @@ -564,11 +721,11 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe const value = content ?? ""; return ( {value} @@ -580,58 +737,20 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe soft_break: () => {"\n"}, } : {}), - code_block: ({ content, language }) => ( - - {language ? ( - - - {language} - - - ) : null} - - - {content} - - - + code_block: ({ content = "", language }) => ( + ), }); @@ -653,7 +772,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe bold: { fontWeight: "700", color: markdownUserBodyColor, - fontFamily: "DMSans_700Bold", + fontFamily: boldFontFamily, }, heading: { ...baseStyles.heading, @@ -689,7 +808,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe markdownUserInlineCodeText, markdownUserFenceBg, markdownUserFenceText, + userBubbleForegroundMuted, true, + false, ), nativeTextStyle: { color: markdownUserBodyColor, @@ -704,10 +825,12 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe skillTextColor: "#f0abfc", quoteMarkerColor: markdownUserBodyColor, dividerColor: markdownUserBodyColor, - ...MOBILE_TYPOGRAPHY.body, - fontFamily: "DMSans_400Regular", - headingFontFamily: "DMSans_700Bold", - boldFontFamily: "DMSans_700Bold", + fontSize: nativeMarkdownTypography.fontSize, + lineHeight: nativeMarkdownTypography.lineHeight, + headingFontSizes: nativeMarkdownTypography.headingFontSizes, + fontFamily: regularFontFamily, + headingFontFamily: boldFontFamily, + boldFontFamily, }, }, assistant: { @@ -718,7 +841,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe markdownInlineCodeText, markdownCodeBg, markdownCodeText, + iconSubtleColor, false, + true, ), nativeTextStyle: { color: markdownBodyColor, @@ -733,14 +858,27 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe skillTextColor: inlineSkillForeground, quoteMarkerColor: markdownBlockquoteBorder, dividerColor: markdownHrColor, - ...MOBILE_TYPOGRAPHY.body, - fontFamily: "DMSans_400Regular", - headingFontFamily: "DMSans_700Bold", - boldFontFamily: "DMSans_700Bold", + fontSize: nativeMarkdownTypography.fontSize, + lineHeight: nativeMarkdownTypography.lineHeight, + headingFontSizes: nativeMarkdownTypography.headingFontSizes, + fontFamily: regularFontFamily, + headingFontFamily: boldFontFamily, + boldFontFamily, }, }, }; - }, [colors, inlineSkillForeground, onLinkPress]); + }, [ + boldFontFamily, + colors, + iconSubtleColor, + inlineSkillForeground, + markdownFontSizes, + nativeMarkdownTypography, + onLinkPress, + regularFontFamily, + themeMode, + userBubbleForegroundMuted, + ]); } function renderFeedEntry( @@ -809,8 +947,12 @@ function renderFeedEntry( !message.streaming; if (isUser) { + const enterAnimated = isFreshTimestamp(message.createdAt); return ( - + {message.createdBy === "agent" ? ( Sent by another agent @@ -859,7 +1001,7 @@ function renderFeedEntry( /> ) : null} - + ); } @@ -869,8 +1011,12 @@ function renderFeedEntry( return null; } + const enterAnimated = isFreshTimestamp(message.createdAt); return ( - + {message.text.trim().length > 0 ? ( hasNativeSelectableMarkdownText() ? ( ) : null} - + ); } @@ -1021,6 +1167,7 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: { readonly comment: ReviewInlineComment; readonly colors: ReviewCommentColors; }) { + const { codeSurface, nativeReviewDiffStyle } = useAppearanceCodeSurface(); const colorScheme = useColorScheme(); const appearanceScheme = colorScheme === "light" ? "light" : "dark"; const NativeReviewDiffView = resolveNativeReviewDiffView(); @@ -1043,28 +1190,30 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: { () => JSON.stringify(nativeReviewDiffTheme), [nativeReviewDiffTheme], ); - const nativeStyleJson = useMemo(() => JSON.stringify(NATIVE_REVIEW_DIFF_STYLE), []); + const nativeStyleJson = useMemo( + () => JSON.stringify(nativeReviewDiffStyle), + [nativeReviewDiffStyle], + ); const nativeDiffHeight = useMemo( () => Math.min( 360, Math.max( 112, - compactNativeRows.length * NATIVE_REVIEW_DIFF_ROW_HEIGHT + - NATIVE_REVIEW_DIFF_STYLE.fileHeaderVerticalMargin, + compactNativeRows.length * nativeReviewDiffStyle.rowHeight + + nativeReviewDiffStyle.fileHeaderVerticalMargin, ), ), - [compactNativeRows.length], + [compactNativeRows.length, nativeReviewDiffStyle], ); const shouldRenderNativeDiff = NativeReviewDiffView != null && compactNativeRows.length > 0; return ( @@ -1107,7 +1256,7 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: { style={StyleSheet.absoluteFill} appearanceScheme={appearanceScheme} contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH} - rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT} + rowHeight={nativeReviewDiffStyle.rowHeight} rowsJson={nativeRowsJson} styleJson={nativeStyleJson} themeJson={nativeThemeJson} @@ -1126,11 +1275,11 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: { > {props.comment.diff.trim()} @@ -1139,11 +1288,7 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: { ) : null} {props.comment.text.length > 0 ? ( - + {props.comment.text} @@ -1184,7 +1329,6 @@ function ThreadFeedPlaceholder(props: { readonly bottomInset: number; readonly detail: string; readonly horizontalPadding: number; - readonly loading?: boolean; readonly title: string; readonly topInset: number; }) { @@ -1201,9 +1345,8 @@ function ThreadFeedPlaceholder(props: { }} > - {props.loading ? : null} {props.title} - + {props.detail} @@ -1212,13 +1355,18 @@ function ThreadFeedPlaceholder(props: { } export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { - const router = useRouter(); + const navigation = useNavigation(); const copyFeedbackTimeoutRef = useRef | null>(null); const foldSettleFrameRef = useRef(null); const foldSettleSecondFrameRef = useRef(null); const previousLatestTurnRef = useRef(props.latestRun); const disclosureAnchorKeyRef = useRef(null); - const { width: viewportWidth } = useWindowDimensions(); + const headerMaterialVisibleRef = useRef(false); + const { width: windowWidth } = useWindowDimensions(); + const [viewportWidth, setViewportWidth] = useState(() => + props.layoutVariant === "split" ? 0 : windowWidth, + ); + const [viewportHeight, setViewportHeight] = useState(0); const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false); const [interactionState, setInteractionState] = useState<{ readonly copiedRowId: string | null; @@ -1237,12 +1385,30 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { headers?: Record; } | null>(null); const horizontalPadding = props.layoutVariant === "split" ? 20 : 16; - const contentWidth = Math.max(0, viewportWidth - horizontalPadding * 2); + const contentHorizontalPadding = deriveCenteredContentHorizontalPadding({ + viewportWidth, + maxContentWidth: props.contentMaxWidth ?? null, + minimumPadding: horizontalPadding, + }); + const contentWidth = Math.max(0, viewportWidth - contentHorizontalPadding * 2); const userBubbleMaxWidth = contentWidth * 0.85; const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth); const insets = useSafeAreaInsets(); const topContentInset = props.contentTopInset ?? insets.top + 44; const bottomContentInset = props.contentBottomInset ?? 18; + const usesNativeAutomaticInsets = + props.usesAutomaticContentInsets === true && Platform.OS === "ios"; + // With automatic insets the header inset lives in UIKit's adjustedContentInset, + // which LegendList's JS anchoring math cannot see — it measures the anchored + // end space from the scroll view's frame top. Fold the header height back into + // the anchor offset or a just-sent message anchors underneath the header and + // the oversized end space keeps maintainScrollAtEnd snapping away from earlier + // messages. Read the context directly (useHeaderHeight throws outside a + // header-providing screen) and fall back to the standard iOS bar height. + const navigationHeaderHeight = useContext(HeaderHeightContext); + const anchorTopInset = usesNativeAutomaticInsets + ? navigationHeaderHeight || insets.top + 44 + : topContentInset; const iconSubtleColor = useThemeColor("--color-icon-subtle"); const userBubbleColor = useThemeColor("--color-user-bubble"); @@ -1256,13 +1422,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ); if (relativePath) { void Haptics.selectionAsync(); - router.push( - buildThreadFilesNavigation( - { environmentId: props.environmentId, threadId: props.threadId }, - relativePath, - presentation.line, - ), - ); + navigation.navigate("ThreadFile", { + environmentId: String(props.environmentId), + threadId: String(props.threadId), + path: relativePath.split("/").filter((segment) => segment.length > 0), + ...(presentation.line ? { line: String(presentation.line) } : {}), + }); } return; } @@ -1271,7 +1436,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { void Linking.openURL(presentation.href); } }, - [props.environmentId, props.threadId, props.workspaceRoot, router], + [props.environmentId, props.threadId, props.workspaceRoot, navigation], ); const markdownStyles = useMarkdownStyles(onMarkdownLinkPress); const reviewCommentColors = useReviewCommentColors(); @@ -1286,6 +1451,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { markdownStyles, reviewCommentColors, userBubbleColor, + viewportWidth, }), [ copiedRowId, @@ -1295,21 +1461,69 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { markdownStyles, reviewCommentColors, userBubbleColor, + viewportWidth, ], ); + const reportHeaderMaterialVisibility = useCallback( + (visible: boolean) => { + if (headerMaterialVisibleRef.current === visible) { + return; + } + headerMaterialVisibleRef.current = visible; + props.onHeaderMaterialVisibilityChange?.(visible); + }, + [props.onHeaderMaterialVisibilityChange], + ); + const handleScroll = useCallback( + (event: NativeSyntheticEvent) => { + // anchorTopInset, not topContentInset: under automatic insets the list + // rests at contentOffset.y = -headerHeight (the inset lives only in + // UIKit's adjustedContentInset, so topContentInset is 0 here). Add the + // header height back or the material toggles a full header too late. + reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6); + }, + [reportHeaderMaterialVisibility, anchorTopInset], + ); + const handleViewportLayout = useCallback((event: LayoutChangeEvent) => { + const nextWidth = Math.round(event.nativeEvent.layout.width); + const nextHeight = Math.round(event.nativeEvent.layout.height); + setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current)); + setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current)); + }, []); + + useEffect(() => { + reportHeaderMaterialVisibility(false); + }, [props.threadId, reportHeaderMaterialVisibility]); + const presentedFeed = useMemo( () => deriveThreadFeedPresentation(props.feed, props.latestRun, expandedTurnIds), [expandedTurnIds, props.feed, props.latestRun], ); + + // The empty↔filled key below remounts the list, which resets its imperative + // content-inset override — and useKeyboardChatComposerInset (mounted above + // the remount boundary) deduplicates by height, so it never re-reports the + // composer inset to the fresh instance. Without this, the remounted list's + // initial scroll-to-end computes with a zero end inset and rests one + // composer-height short of the end. Layout effect: it must land before the + // list's first positioning tick or the one-shot initial scroll misses it. + const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`; + useLayoutEffect(() => { + const bottom = props.contentInsetEndAdjustment.value; + if (bottom > 0) { + props.listRef.current?.reportContentInset({ bottom }); + } + }, [listMountKey, props.contentInsetEndAdjustment, props.listRef]); + const anchoredEndSpace = useMemo( () => resolveChatListAnchoredEndSpace( presentedFeed, props.anchorMessageId, (entry) => (entry.type === "message" ? entry.id : null), - { anchorOffset: topContentInset + CHAT_LIST_ANCHOR_OFFSET }, + { anchorOffset: anchorTopInset + CHAT_LIST_ANCHOR_OFFSET }, ), - [presentedFeed, props.anchorMessageId, topContentInset], + [presentedFeed, props.anchorMessageId, anchorTopInset], ); const terminalAssistantMessageIds = useMemo(() => { const terminalIdsByTurn = new Map(); @@ -1514,19 +1728,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ], ); - if (props.contentPresentation.kind === "loading") { - return ( - - ); - } - if (props.contentPresentation.kind === "unavailable") { return ( - - + + entry.id} - getItemType={(entry) => - entry.type === "message" ? `message:${entry.message.role}` : entry.type - } - keyboardShouldPersistTaps="always" - keyboardDismissMode="none" - keyboardLiftBehavior="whenAtEnd" - estimatedItemSize={180} - initialScrollAtEnd - ListHeaderComponent={ - <> - - {props.topAccessory} - - } - contentContainerStyle={{ - paddingTop: 12, - paddingHorizontal: horizontalPadding, - }} - /> - {props.feed.length === 0 ? ( + : { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })} + {...(anchoredEndSpace ? { anchoredEndSpace } : {})} + itemLayoutAnimation={FEED_ITEM_LAYOUT_TRANSITION} + // Patched LegendList prop (patches/@legendapp__list@3.2.0.patch): + // lets its scroll math clamp programmatic scrolls to -headerInset + // instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short + // content rest below the transparent header rather than at frame top. + contentInsetStartAdjustment={usesNativeAutomaticInsets ? anchorTopInset : 0} + contentInsetEndAdjustment={props.contentInsetEndAdjustment} + // UIKit's automatic behavior adds the safe-area bottom on top of the + // raw contentInset the keyboard integration writes. The detail screen + // under-reports the composer inset by this amount (see + // ThreadDetailScreen); this tells LegendList's scroll math about the + // extra so programmatic end scrolls land at the true resting offset. + contentInsetEndStaticAdjustment={usesNativeAutomaticInsets ? insets.bottom : 0} + // The keyboard integration's offset math (end pinning, max scroll) + // must add the same UIKit-added extra, or its keyboard-open end + // targets land one safe-area short of the true resting offset. + adjustedInsetCompensation={usesNativeAutomaticInsets ? insets.bottom : 0} + freeze={props.freeze} + // Animated: on send, the optimistic message's dataChange fires + // maintainScrollAtEnd before any render-cycle suppression could + // engage — an instant snap there teleports the feed to the anchor + // instead of scrolling to it. Keeping it enabled (animated) during + // anchor scrolls also lets it correct a scroll that landed on a + // stale end target once the anchor row finishes measuring. + maintainScrollAtEnd={ + disclosureToggleSettling + ? false + : { + animated: true, + on: { + dataChange: true, + itemLayout: true, + layout: true, + }, + } + } + maintainVisibleContentPosition={maintainVisibleContentPosition} + data={presentedFeed} + extraData={listAppearanceData} + renderItem={renderItem} + keyExtractor={(entry) => entry.id} + getItemType={(entry) => + entry.type === "message" ? `message:${entry.message.role}` : entry.type + } + keyboardShouldPersistTaps="always" + keyboardDismissMode="none" + keyboardLiftBehavior="whenAtEnd" + // Seed the list's scroll math with the real viewport before its own + // onLayout: the empty→filled remount can then tell at mount that + // short content underflows the viewport and skip programmatic + // positioning entirely (any offset write during screen attach races + // UIKit's adjustedContentInset application and lands high or low). + {...(viewportHeight > 0 && viewportWidth > 0 + ? { estimatedListSize: { height: viewportHeight, width: viewportWidth } } + : {})} + // RN's native scrollTo command clamps targets to a floor of + // -contentInset.top using the RAW inset — under automatic insets the + // header inset only exists in adjustedContentInset, so scrolls to + // negative offsets (content top below the transparent header) get + // clamped to 0. This prop disables that clamp; UIKit still bounces + // user overscroll back to the adjusted rest position. + scrollToOverflowEnabled + estimatedItemSize={180} + initialScrollAtEnd + onScroll={handleScroll} + scrollEventThrottle={16} + ListHeaderComponent={ + <> + {usesNativeAutomaticInsets ? null : } + {props.topAccessory} + + } + contentContainerStyle={{ + paddingTop: 12, + paddingHorizontal: contentHorizontalPadding, + }} + /> + + {props.feed.length === 0 && props.contentPresentation.kind === "ready" ? ( ; +type HeaderItems = HeaderItem[]; +type ThreadGitHeaderActionItems = { + readonly terminal: HeaderItem; + readonly files: HeaderItem; + readonly git: HeaderItem; +}; +type QuickActionIcon = + | "arrow.down.circle" + | "arrow.up.right.circle" + | "checkmark.circle" + | "arrow.up.circle"; + +/** The subset of git-control wiring the standalone git menu needs. */ +export type ThreadGitMenuProps = { + readonly environmentId: EnvironmentId | string; + readonly threadId: ThreadId | string; readonly currentBranch: string | null; readonly gitStatus: VcsStatusResult | null; readonly gitOperationLabel: string | null; + readonly onOpenFilesInspector?: () => void; + readonly onOpenGitInspector?: () => void; + readonly onPull: () => Promise; + readonly onRunAction: (input: GitActionRequestInput) => Promise; +}; + +type ThreadGitControlsProps = ThreadGitMenuProps & { + readonly auxiliaryPaneControl?: { + readonly accessibilityLabel: string; + readonly onPress: () => void; + }; readonly canOpenTerminal: boolean; readonly canOpenFiles: boolean; readonly projectScripts: ReadonlyArray; readonly terminalSessions: ReadonlyArray; + readonly showActionControls?: boolean; + readonly showDirectFileControl?: boolean; readonly onOpenTerminal: (terminalId?: string | null) => void; readonly onOpenNewTerminal: () => void; readonly onRunProjectScript: (script: ProjectScript) => Promise; - readonly onPull: () => Promise; - readonly onRunAction: (input: GitActionRequestInput) => Promise; -}) { - const router = useRouter(); - const { environmentId, threadId } = useLocalSearchParams<{ - environmentId: EnvironmentId; - threadId: ThreadId; - }>(); +}; + +function useThreadGitControlModel(props: ThreadGitMenuProps) { + const navigation = useNavigation(); + const environmentId = props.environmentId; + const threadId = props.threadId; const { gitStatus, gitOperationLabel, onPull, onRunAction } = props; const currentBranchLabel = gitStatus?.refName ?? props.currentBranch ?? "Detached HEAD"; @@ -109,7 +135,7 @@ export function ThreadGitControls(props: { ? (quickAction.hint ?? "This action is unavailable.") : null; - const quickActionIcon = (() => { + const quickActionIcon: QuickActionIcon = (() => { if (quickAction.kind === "run_pull") return "arrow.down.circle"; if (quickAction.kind === "open_pr") return "arrow.up.right.circle"; if (quickAction.kind === "run_action") { @@ -147,24 +173,21 @@ export function ThreadGitControls(props: { !input.featureBranch && requiresDefaultBranchConfirmation(input.action, isDefaultRef) ) { - router.push({ - pathname: "/threads/[environmentId]/[threadId]/git-confirm", - params: { - environmentId, - threadId, - confirmAction: confirmableAction, - branchName, - includesCommit: String( - input.action === "commit_push" || input.action === "commit_push_pr", - ), - }, + navigation.navigate("GitConfirm", { + environmentId: String(environmentId), + threadId: String(threadId), + confirmAction: confirmableAction, + branchName, + includesCommit: String( + input.action === "commit_push" || input.action === "commit_push_pr", + ), }); return; } await onRunAction(input); }, - [environmentId, gitStatus, isDefaultRef, onRunAction, router, threadId], + [environmentId, gitStatus, isDefaultRef, onRunAction, navigation, threadId], ); const runQuickAction = useCallback(async () => { @@ -181,102 +204,339 @@ export function ThreadGitControls(props: { } }, [onPull, openExistingPr, quickAction, runActionWithPrompt]); - return ( - - - {props.projectScripts.length > 0 ? ( - props.projectScripts.map((script) => ( - void props.onRunProjectScript(script)} - subtitle={script.command} - > - {projectScriptMenuLabel(script)} - - )) - ) : ( - {}} - subtitle="This project has no saved scripts yet" - > - No project scripts - - )} - {props.terminalSessions.map((session) => ( - props.onOpenTerminal(session.terminalId)} - subtitle={[ - getTerminalStatusLabel({ - status: session.status, - hasRunningSubprocess: session.hasRunningSubprocess, - }), - basename(session.cwd), - ] - .filter(Boolean) - .join(" · ")} - > - {session.displayLabel} - - ))} - - Open new terminal - - - - {}} - subtitle={compactMenuStatus(gitStatus)} - > - {compactMenuBranchLabel(currentBranchLabel)} - - void runQuickAction()} - subtitle={quickActionHint ?? undefined} - > - {quickAction.label} - - router.push(buildThreadReviewRoutePath({ environmentId, threadId }))} - subtitle="Turn diffs and worktree changes" - > - Review changes - - router.push(buildThreadFilesNavigation({ environmentId, threadId }))} - subtitle="Browse this workspace" - > - Files - - - router.push({ - pathname: "/threads/[environmentId]/[threadId]/git", - params: { environmentId, threadId }, - }) - } - subtitle="Commit, files, branches" - > - More - - - + const openFiles = useCallback(() => { + if (props.onOpenFilesInspector) { + props.onOpenFilesInspector(); + return; + } + navigation.navigate("ThreadFiles", { + environmentId: String(environmentId), + threadId: String(threadId), + }); + }, [environmentId, props.onOpenFilesInspector, navigation, threadId]); + + const openReview = useCallback(() => { + navigation.navigate("ThreadReview", { + environmentId: EnvironmentId.make(String(environmentId)), + threadId: ThreadId.make(String(threadId)), + }); + }, [environmentId, navigation, threadId]); + + const openGitInspector = useCallback(() => { + if (props.onOpenGitInspector) { + props.onOpenGitInspector(); + return; + } + navigation.navigate("GitOverview", { + environmentId: String(environmentId), + threadId: String(threadId), + }); + }, [environmentId, props.onOpenGitInspector, navigation, threadId]); + + return { + currentBranchLabel, + isRepo, + openFiles, + openGitInspector, + openReview, + quickAction, + quickActionHint, + quickActionIcon, + runQuickAction, + }; +} + +function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGitHeaderActionItems { + const model = useThreadGitControlModel(props); + + return useMemo( + () => ({ + terminal: { + accessibilityLabel: "Open terminal", + disabled: !props.canOpenTerminal, + icon: { name: "terminal", type: "sfSymbol" }, + identifier: "thread-right-terminal", + label: "Terminal", + menu: { + items: [ + ...props.projectScripts.map((script) => ({ + description: script.command, + icon: { name: projectScriptMenuIcon(script.icon), type: "sfSymbol" as const }, + label: projectScriptMenuLabel(script), + onPress: () => void props.onRunProjectScript(script), + type: "action" as const, + })), + ...(props.projectScripts.length === 0 + ? [ + { + description: "This project has no saved scripts yet", + disabled: true, + icon: { name: "play", type: "sfSymbol" as const }, + label: "No project scripts", + onPress: () => {}, + type: "action" as const, + }, + ] + : []), + ...props.terminalSessions.map((session) => ({ + description: [ + getTerminalStatusLabel({ + status: session.status, + hasRunningSubprocess: session.hasRunningSubprocess, + }), + basename(session.cwd), + ] + .filter(Boolean) + .join(" · "), + icon: { name: "terminal", type: "sfSymbol" as const }, + label: session.displayLabel, + onPress: () => props.onOpenTerminal(session.terminalId), + type: "action" as const, + })), + { + description: "Start another shell for this thread", + icon: { name: "plus", type: "sfSymbol" }, + label: "Open new terminal", + onPress: props.onOpenNewTerminal, + type: "action", + }, + ], + title: "Terminal", + }, + sharesBackground: true, + type: "menu", + variant: "plain", + }, + files: { + accessibilityLabel: "Open files", + disabled: !props.canOpenFiles, + icon: { name: "folder", type: "sfSymbol" }, + identifier: "thread-right-files", + label: "Files", + onPress: model.openFiles, + sharesBackground: true, + type: "button", + variant: "plain", + }, + git: { + accessibilityLabel: "Git actions", + icon: { name: "point.topleft.down.curvedto.point.bottomright.up", type: "sfSymbol" }, + identifier: "thread-right-git", + label: "Git", + menu: { + items: [ + { + description: compactMenuStatus(props.gitStatus), + disabled: true, + icon: { + name: "point.topleft.down.curvedto.point.bottomright.up", + type: "sfSymbol", + }, + label: compactMenuBranchLabel(model.currentBranchLabel), + onPress: (): void => {}, + type: "action", + }, + { + description: model.quickActionHint ?? undefined, + disabled: model.quickAction.disabled, + icon: { name: model.quickActionIcon, type: "sfSymbol" }, + label: model.quickAction.label, + onPress: (): void => void model.runQuickAction(), + type: "action", + }, + { + description: "Turn diffs and worktree changes", + disabled: !model.isRepo, + icon: { name: "text.bubble", type: "sfSymbol" }, + label: "Review changes", + onPress: model.openReview, + type: "action", + }, + { + description: "Commit, files, branches", + icon: { name: "ellipsis", type: "sfSymbol" }, + label: "More", + onPress: model.openGitInspector, + type: "action", + }, + ], + title: "Git", + }, + sharesBackground: true, + type: "menu", + variant: "plain", + }, + }), + [ + model.currentBranchLabel, + model.isRepo, + model.openFiles, + model.openGitInspector, + model.openReview, + model.quickAction.disabled, + model.quickAction.label, + model.quickActionHint, + model.quickActionIcon, + model.runQuickAction, + props.canOpenFiles, + props.canOpenTerminal, + props.gitStatus, + props.onOpenNewTerminal, + props.onOpenTerminal, + props.onRunProjectScript, + props.projectScripts, + props.terminalSessions, + ], + ); +} + +export function useThreadGitRightHeaderItems(props: ThreadGitControlsProps): HeaderItems { + const actionItems = useThreadGitHeaderActionItems(props); + return useMemo( + () => [actionItems.git, actionItems.files, actionItems.terminal] as HeaderItems, + [actionItems], + ); +} + +export function useThreadGitCenterHeaderItems(props: ThreadGitControlsProps): HeaderItems { + const actionItems = useThreadGitHeaderActionItems(props); + return useMemo( + () => [actionItems.files, actionItems.git, actionItems.terminal] as HeaderItems, + [actionItems], + ); +} + +export function ThreadGitControls(props: ThreadGitControlsProps) { + const model = useThreadGitControlModel(props); + const showActionControls = props.showActionControls ?? true; + + if (!showActionControls) { + return null; + } + + return ( + + {showActionControls && props.auxiliaryPaneControl ? ( + + ) : null} + {showActionControls ? ( + + {props.projectScripts.length > 0 ? ( + props.projectScripts.map((script) => ( + void props.onRunProjectScript(script)} + subtitle={script.command} + > + + {projectScriptMenuLabel(script)} + + + )) + ) : ( + {}} + subtitle="This project has no saved scripts yet" + > + No project scripts + + )} + {props.terminalSessions.map((session) => ( + props.onOpenTerminal(session.terminalId)} + subtitle={[ + getTerminalStatusLabel({ + status: session.status, + hasRunningSubprocess: session.hasRunningSubprocess, + }), + basename(session.cwd), + ] + .filter(Boolean) + .join(" · ")} + > + {session.displayLabel} + + ))} + + Open new terminal + + + ) : null} + {showActionControls && props.showDirectFileControl ? ( + + ) : null} + {showActionControls ? : null} + + ); +} + +/** + * The standalone git actions menu (branch status, quick commit/push action, + * review, more). Rendered inside a NativeHeaderToolbar by both the thread + * chat header and the review screen's toolbar. + */ +export function ThreadGitMenu(props: ThreadGitMenuProps) { + const model = useThreadGitControlModel(props); + + return ( + + {}} + subtitle={compactMenuStatus(props.gitStatus)} + > + + {compactMenuBranchLabel(model.currentBranchLabel)} + + + void model.runQuickAction()} + subtitle={model.quickActionHint ?? undefined} + > + {model.quickAction.label} + + + Review changes + + + More + + ); } diff --git a/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx b/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx deleted file mode 100644 index 9318fb7601..0000000000 --- a/apps/mobile/src/features/threads/ThreadNavigationDrawer.tsx +++ /dev/null @@ -1,282 +0,0 @@ -import { SymbolView } from "expo-symbols"; -import { useCallback, useEffect, useMemo, useState } from "react"; -import { - type ColorValue, - Modal, - Pressable, - ScrollView, - useWindowDimensions, - View, -} from "react-native"; -import * as Arr from "effect/Array"; -import * as Order from "effect/Order"; -import { Gesture, GestureDetector } from "react-native-gesture-handler"; -import { useSafeAreaInsets } from "react-native-safe-area-context"; -import Animated, { - runOnJS, - useAnimatedStyle, - useSharedValue, - withTiming, -} from "react-native-reanimated"; -import { useThemeColor } from "../../lib/useThemeColor"; - -import { AppText as Text } from "../../components/AppText"; -import { StatusPill } from "../../components/StatusPill"; -import { useProjects, useThreadShells } from "../../state/entities"; -import { groupProjectsByRepository } from "../../lib/repositoryGroups"; -import { scopedThreadKey } from "../../lib/scopedEntities"; -import { relativeTime } from "../../lib/time"; -import { threadStatusTone } from "./threadPresentation"; -import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; - -const threadActivityOrder = Order.mapInput( - Order.Struct({ - activityAt: Order.flip(Order.Number), - title: Order.String, - }), - (thread: EnvironmentThreadShell) => ({ - activityAt: new Date(thread.updatedAt ?? thread.createdAt).getTime(), - title: thread.title, - }), -); - -export function ThreadNavigationDrawer(props: { - readonly visible: boolean; - readonly selectedThreadKey: string | null; - readonly onClose: () => void; - readonly onSelectThread: (thread: EnvironmentThreadShell) => void; - readonly onStartNewTask: () => void; -}) { - const insets = useSafeAreaInsets(); - const { width } = useWindowDimensions(); - const drawerWidth = Math.min(width * 0.84, 360); - const [mounted, setMounted] = useState(props.visible); - const translateX = useSharedValue(-drawerWidth); - const overlayOpacity = useSharedValue(0); - - const backdropColor = useThemeColor("--color-backdrop"); - const drawerBg = useThemeColor("--color-drawer"); - const drawerShadow = useThemeColor("--color-drawer-shadow"); - const primaryForeground = useThemeColor("--color-primary-foreground"); - const borderSubtleColor = useThemeColor("--color-border-subtle"); - - useEffect(() => { - if (props.visible) { - setMounted(true); - translateX.value = withTiming(0, { duration: 240 }); - overlayOpacity.value = withTiming(1, { duration: 220 }); - return; - } - - overlayOpacity.value = withTiming(0, { duration: 180 }); - translateX.value = withTiming(-drawerWidth, { duration: 220 }, (finished) => { - if (finished) { - runOnJS(setMounted)(false); - } - }); - }, [drawerWidth, overlayOpacity, props.visible, translateX]); - - const closeDrawer = useCallback(() => { - props.onClose(); - }, [props]); - - const panGesture = useMemo( - () => - Gesture.Pan() - .activeOffsetX([-12, 12]) - .failOffsetY([-24, 24]) - .onUpdate((event) => { - translateX.value = Math.min(0, event.translationX); - }) - .onEnd((event) => { - const shouldClose = event.translationX < -drawerWidth * 0.2 || event.velocityX < -500; - if (shouldClose) { - runOnJS(closeDrawer)(); - return; - } - - translateX.value = withTiming(0, { duration: 180 }); - }), - [closeDrawer, drawerWidth, translateX], - ); - - const drawerStyle = useAnimatedStyle(() => ({ - transform: [{ translateX: translateX.value }], - })); - - const backdropStyle = useAnimatedStyle(() => ({ - opacity: overlayOpacity.value, - })); - - if (!mounted) { - return null; - } - - return ( - - - - - - - - - Threads - { - props.onClose(); - props.onStartNewTask(); - }} - className="h-11 w-11 items-center justify-center rounded-full bg-primary" - > - - - - - - - - - - ); -} - -function ThreadNavigationDrawerContent(props: { - readonly bottomInset: number; - readonly borderSubtleColor: ColorValue; - readonly selectedThreadKey: string | null; - readonly onClose: () => void; - readonly onSelectThread: (thread: EnvironmentThreadShell) => void; -}) { - const projects = useProjects(); - const threads = useThreadShells(); - const repositoryGroups = useMemo( - () => groupProjectsByRepository({ projects, threads }), - [projects, threads], - ); - const groupedThreads = useMemo( - () => - repositoryGroups.map((group) => { - const threads: EnvironmentThreadShell[] = []; - for (const projectGroup of group.projects) { - threads.push(...projectGroup.threads); - } - return { - key: group.key, - title: group.projects[0]?.project.title ?? group.title, - threads: Arr.sort(threads, threadActivityOrder), - }; - }), - [repositoryGroups], - ); - - return ( - - {groupedThreads.map((group) => ( - - - {group.title} - - - - {group.threads.length === 0 ? ( - - No threads yet - - ) : ( - group.threads.map((thread, index) => { - const threadKey = scopedThreadKey(thread.environmentId, thread.id); - const selected = props.selectedThreadKey === threadKey; - - return ( - { - props.onSelectThread(thread); - props.onClose(); - }} - style={{ - paddingHorizontal: 16, - paddingVertical: 15, - borderTopWidth: index === 0 ? 0 : 1, - borderTopColor: props.borderSubtleColor, - backgroundColor: selected ? undefined : "transparent", - }} - className={selected ? "bg-subtle" : undefined} - > - - - - {thread.title} - - - {relativeTime(thread.updatedAt ?? thread.createdAt)} - - - - - - ); - }) - )} - - - ))} - - ); -} diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx new file mode 100644 index 0000000000..f7ee4eaa74 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -0,0 +1,753 @@ +import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass"; +import type { + EnvironmentProject, + EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; +import { LegendList } from "@legendapp/list/react-native"; +import type { MenuAction } from "@react-native-menu/menu"; +import { useCallback, useMemo, useRef, useState, type ReactNode } from "react"; +import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native"; +import { Platform, StyleSheet, TextInput, View, useColorScheme } from "react-native"; +import { Gesture, GestureDetector } from "react-native-gesture-handler"; +import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import type { SearchBarCommands } from "react-native-screens"; +import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"; + +import { AppText as Text } from "../../components/AppText"; +import { ControlPillMenu } from "../../components/ControlPill"; +import { SymbolView } from "../../components/AppSymbol"; +import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; +import { NativeStackScreenOptions } from "../../native/StackHeader"; +import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities"; +import { useThemeColor } from "../../lib/useThemeColor"; +import { useProjects, useThreadShells } from "../../state/entities"; +import { usePendingNewTasks } from "../../state/use-pending-new-tasks"; +import { useWorkspaceState } from "../../state/workspace"; +import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; +import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands"; +import { + hasCustomHomeListOptions, + PROJECT_GROUPING_OPTIONS, + PROJECT_SORT_OPTIONS, + THREAD_SORT_OPTIONS, + useHomeListOptions, +} from "../home/home-list-options"; +import { buildHomeListFilterMenu } from "../home/home-list-filter-menu"; +import { + buildHomeListLayout, + DEFAULT_GROUP_DISPLAY_STATE, + homeListItemsAreEqual, + nextGroupDisplayState, + type HomeGroupDisplayAction, + type HomeGroupDisplayState, + type HomeListItem, +} from "../home/homeListItems"; +import { buildHomeThreadGroups } from "../home/homeThreadList"; +import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions"; +import { usePendingTaskListActions } from "../home/usePendingTaskListActions"; +import { useThreadListActions } from "../home/useThreadListActions"; +import { WorkspaceConnectionStatus } from "../home/WorkspaceConnectionStatus"; +import { shouldShowWorkspaceConnectionStatus } from "../home/workspace-connection-status"; +import { SidebarHeaderActions } from "./sidebar-header-actions"; +import { SidebarFilterButton } from "./sidebar-filter-button"; +import { createSidebarHeaderItems } from "./sidebar-native-header-items"; +import { SidebarNavigationShell } from "./sidebar-navigation-shell"; +import { + PendingTaskListRow, + ThreadListGroupHeader, + ThreadListRow, + ThreadListShowMoreRow, +} from "./thread-list-items"; + +/** + * Shared capsule behind the sidebar header buttons — a native liquid-glass + * surface on iOS 26+, a tinted pill everywhere else. + */ +function SidebarHeaderButtonGroup(props: { + readonly children: ReactNode; + readonly colorScheme: "light" | "dark"; +}) { + if (isLiquidGlassSupported) { + return ( + + {props.children} + + ); + } + + return ( + + {props.children} + + ); +} + +const SIDEBAR_STICKY_HEADER_HEIGHT = 106; +const SIDEBAR_STICKY_HEADER_FADE_HEIGHT = 44; +const SIDEBAR_HEADER_WASH_OPACITY = { + dark: [0.22, 0.14, 0.04], + light: [0.46, 0.3, 0.08], +} as const; + +interface ThreadNavigationSidebarProps { + readonly width: number; + readonly visible: boolean; + readonly selectedThreadKey: string | null; + readonly onOpenSettings: () => void; + readonly onOpenEnvironmentSettings: () => void; + readonly onNewThreadInProject: (project: EnvironmentProject) => void; + readonly onSearchQueryChange: (query: string) => void; + readonly onSelectThread: (thread: EnvironmentThreadShell) => void; + readonly onRequestVisibility: () => void; + readonly searchQuery: string; +} + +/** + * iPad/large-width sidebar column. + * + * On iOS the pane is hosted inside its own navigation-inert single-screen + * native stack (SidebarNavigationShell) so the header is a real + * UINavigationBar: large title, native bar-button items, and a + * UISearchController search field — the same chrome a UISplitViewController + * column gets. Other platforms keep the custom header chrome. + */ +export function ThreadNavigationSidebar(props: ThreadNavigationSidebarProps) { + if (Platform.OS !== "ios") { + return ; + } + return ; +} + +function NativeSidebarContainer(props: ThreadNavigationSidebarProps) { + const backgroundColor = useThemeColor("--color-drawer"); + const borderColor = useThemeColor("--color-border"); + + return ( + + + + + + ); +} + +function ThreadNavigationSidebarPane( + props: ThreadNavigationSidebarProps & { readonly nativeChrome: boolean }, +) { + const insets = useSafeAreaInsets(); + const colorScheme = useColorScheme() === "dark" ? "dark" : "light"; + const projects = useProjects(); + const threads = useThreadShells(); + const { state: catalogState } = useWorkspaceState(); + const { savedConnectionsById } = useSavedRemoteConnections(); + const [headerIsOverContent, setHeaderIsOverContent] = useState(false); + const searchInputRef = useRef(null); + const searchBarRef = useRef(null); + const openSwipeableRef = useRef(null); + const headerIsOverContentRef = useRef(false); + const sidebarScrollGesture = useMemo(() => Gesture.Native(), []); + const { archiveThread, confirmDeleteThread } = useThreadListActions(); + const pendingTasks = usePendingNewTasks(); + const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions(); + const environments = useMemo( + () => + Object.values(savedConnectionsById) + .map((connection) => ({ + environmentId: connection.environmentId, + label: connection.environmentLabel, + })) + .sort((left, right) => left.label.localeCompare(right.label)), + [savedConnectionsById], + ); + const availableEnvironmentIds = useMemo( + () => new Set(environments.map((environment) => environment.environmentId)), + [environments], + ); + const { + options, + setSelectedEnvironmentId, + setProjectGroupingMode, + setProjectSortOrder, + setThreadSortOrder, + } = useHomeListOptions(availableEnvironmentIds); + const groups = useMemo( + () => + buildHomeThreadGroups({ + projects, + threads, + pendingTasks, + environmentId: options.selectedEnvironmentId, + searchQuery: props.searchQuery, + projectSortOrder: options.projectSortOrder, + threadSortOrder: options.threadSortOrder, + projectGroupingMode: options.projectGroupingMode, + }), + [options, pendingTasks, projects, props.searchQuery, threads], + ); + const [groupDisplayStates, setGroupDisplayStates] = useState< + ReadonlyMap + >(() => new Map()); + const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => { + setGroupDisplayStates((previous) => { + const next = new Map(previous); + next.set( + key, + nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action), + ); + return next; + }); + }, []); + const hasSearchQuery = props.searchQuery.trim().length > 0; + const listLayout = useMemo( + () => + buildHomeListLayout({ + groups, + displayStates: groupDisplayStates, + showAllThreads: hasSearchQuery, + }), + [groups, groupDisplayStates, hasSearchQuery], + ); + const projectCwdByKey = useMemo(() => { + const map = new Map(); + for (const project of projects) { + map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot); + } + return map; + }, [projects]); + const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState); + const listMenuActions = useMemo( + () => [ + { + id: "environment", + title: "Environment", + subactions: [ + { + id: "environment:all", + title: "All environments", + subtitle: "Show threads from every environment", + state: options.selectedEnvironmentId === null ? "on" : "off", + }, + ...environments.map((environment) => ({ + id: `environment:${environment.environmentId}`, + title: environment.label, + state: + options.selectedEnvironmentId === environment.environmentId + ? ("on" as const) + : ("off" as const), + })), + ], + }, + { + id: "project-sort", + title: "Sort projects", + subactions: PROJECT_SORT_OPTIONS.map((option) => ({ + id: `project-sort:${option.value}`, + title: option.label, + state: options.projectSortOrder === option.value ? "on" : "off", + })), + }, + { + id: "thread-sort", + title: "Sort threads", + subactions: THREAD_SORT_OPTIONS.map((option) => ({ + id: `thread-sort:${option.value}`, + title: option.label, + state: options.threadSortOrder === option.value ? "on" : "off", + })), + }, + { + id: "project-grouping", + title: "Group projects", + subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({ + id: `project-grouping:${option.value}`, + title: option.label, + subtitle: option.subtitle, + state: options.projectGroupingMode === option.value ? "on" : "off", + })), + }, + ], + [environments, options], + ); + const handleListMenuAction = useCallback( + ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => { + const event = nativeEvent.event; + if (event === "environment:all") { + setSelectedEnvironmentId(null); + return; + } + if (event.startsWith("environment:")) { + const environment = environments.find( + (candidate) => String(candidate.environmentId) === event.slice("environment:".length), + ); + if (environment) setSelectedEnvironmentId(environment.environmentId); + return; + } + const projectSort = PROJECT_SORT_OPTIONS.find( + (option) => `project-sort:${option.value}` === event, + ); + if (projectSort) { + setProjectSortOrder(projectSort.value); + return; + } + const threadSort = THREAD_SORT_OPTIONS.find( + (option) => `thread-sort:${option.value}` === event, + ); + if (threadSort) { + setThreadSortOrder(threadSort.value); + return; + } + const grouping = PROJECT_GROUPING_OPTIONS.find( + (option) => `project-grouping:${option.value}` === event, + ); + if (grouping) setProjectGroupingMode(grouping.value); + }, + [ + environments, + setProjectGroupingMode, + setProjectSortOrder, + setSelectedEnvironmentId, + setThreadSortOrder, + ], + ); + + const backgroundColor = useThemeColor("--color-drawer"); + const borderColor = useThemeColor("--color-border"); + const mutedColor = useThemeColor("--color-foreground-muted"); + const placeholderColor = useThemeColor("--color-placeholder"); + const headerFadeColor = String(backgroundColor); + const headerWashOpacity = SIDEBAR_HEADER_WASH_OPACITY[colorScheme]; + const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState(null); + // The sticky header (title row, search field, optional connection status) + // is measured so the list inset always matches its real height — no + // hardcoded per-variant constants. + const stickyHeaderHeight = measuredHeaderHeight ?? insets.top + SIDEBAR_STICKY_HEADER_HEIGHT; + const topListInset = stickyHeaderHeight + 6; + const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => { + const nextHeight = Math.round(event.nativeEvent.layout.height); + setMeasuredHeaderHeight((current) => (current === nextHeight ? current : nextHeight)); + }, []); + const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => { + if (openSwipeableRef.current !== methods) { + openSwipeableRef.current?.close(); + openSwipeableRef.current = methods; + } + }, []); + const handleSwipeableClose = useCallback((methods: SwipeableMethods) => { + if (openSwipeableRef.current === methods) { + openSwipeableRef.current = null; + } + }, []); + const handleSelectThread = useCallback( + (thread: EnvironmentThreadShell) => { + props.onSelectThread(thread); + openSwipeableRef.current?.close(); + }, + [props.onSelectThread], + ); + const handleScroll = useCallback((event: NativeSyntheticEvent) => { + const next = event.nativeEvent.contentOffset.y > 6; + if (headerIsOverContentRef.current === next) { + return; + } + headerIsOverContentRef.current = next; + setHeaderIsOverContent(next); + }, []); + const handleScrollBeginDrag = useCallback(() => { + openSwipeableRef.current?.close(); + }, []); + const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({ + onScroll: handleScroll, + onScrollBeginDrag: handleScrollBeginDrag, + }); + const listExtraData = props.selectedThreadKey ?? ""; + const focusSearch = useCallback(() => { + const focus = () => { + if (props.nativeChrome) { + searchBarRef.current?.focus(); + return; + } + searchInputRef.current?.focus(); + }; + if (!props.visible) { + props.onRequestVisibility(); + setTimeout(focus, 240); + } else { + focus(); + } + return true; + }, [props.nativeChrome, props.onRequestVisibility, props.visible]); + useHardwareKeyboardCommand("focusSearch", focusSearch); + const renderListItem = useCallback( + ({ item }: { readonly item: HomeListItem }) => { + switch (item.type) { + case "header": + return ( + + ); + case "pending-task": + return ( + + ); + case "thread": { + const thread = item.thread; + return ( + + ); + } + case "show-more": + return ( + + ); + } + }, + [ + archiveThread, + confirmDeletePendingTask, + confirmDeleteThread, + handleSelectThread, + handleSwipeableClose, + handleSwipeableWillOpen, + openPendingTask, + projectCwdByKey, + props.onNewThreadInProject, + props.selectedThreadKey, + props.width, + savedConnectionsById, + sidebarScrollGesture, + updateGroupDisplay, + ], + ); + const filterIcon = hasCustomHomeListOptions(options) + ? "line.3.horizontal.decrease.circle.fill" + : "line.3.horizontal.decrease.circle"; + const filterMenu = useMemo( + () => + buildHomeListFilterMenu({ + environments, + selectedEnvironmentId: options.selectedEnvironmentId, + projectSortOrder: options.projectSortOrder, + threadSortOrder: options.threadSortOrder, + projectGroupingMode: options.projectGroupingMode, + onEnvironmentChange: setSelectedEnvironmentId, + onProjectSortOrderChange: setProjectSortOrder, + onThreadSortOrderChange: setThreadSortOrder, + onProjectGroupingModeChange: setProjectGroupingMode, + }), + [ + environments, + options, + setProjectGroupingMode, + setProjectSortOrder, + setSelectedEnvironmentId, + setThreadSortOrder, + ], + ); + const nativeHeaderItems = useMemo( + () => + createSidebarHeaderItems({ + filterIcon, + filterMenu, + onOpenSettings: props.onOpenSettings, + }), + [filterIcon, filterMenu, props.onOpenSettings], + ); + const listEmpty = ( + + {catalogState.isLoadingConnections + ? "Loading threads…" + : props.searchQuery.trim().length > 0 + ? "No matching threads" + : "No threads yet"} + + ); + + if (props.nativeChrome) { + return ( + <> + { + props.onSearchQueryChange(""); + }, + onChangeText: (event) => { + props.onSearchQueryChange(event.nativeEvent.text); + }, + }, + unstable_headerRightItems: () => nativeHeaderItems, + }} + /> + + + + item.type} + itemsAreEqual={homeListItemsAreEqual} + keyExtractor={(item) => item.key} + renderItem={renderListItem} + automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED} + contentInsetAdjustmentBehavior={ + NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never" + } + contentContainerStyle={[ + styles.threadListContent, + { + paddingBottom: Math.max(insets.bottom, 16) + 16, + paddingTop: 6, + }, + ]} + keyboardDismissMode="on-drag" + keyboardShouldPersistTaps="handled" + {...scrollGateHandlers} + recycleItems + scrollEventThrottle={16} + showsVerticalScrollIndicator={false} + style={styles.threadList} + ListHeaderComponent={ + showsConnectionStatus ? ( + + + + ) : null + } + ListEmptyComponent={listEmpty} + /> + + + + + ); + } + + return ( + + + + + item.type} + itemsAreEqual={homeListItemsAreEqual} + keyExtractor={(item) => item.key} + renderItem={renderListItem} + contentContainerStyle={[ + styles.threadListContent, + { + paddingBottom: 16 + insets.bottom, + paddingTop: topListInset, + }, + ]} + keyboardDismissMode="on-drag" + keyboardShouldPersistTaps="handled" + {...scrollGateHandlers} + recycleItems + scrollEventThrottle={16} + showsVerticalScrollIndicator={false} + style={styles.threadList} + ListEmptyComponent={listEmpty} + /> + + + + + + + + + + + + + + + + + + + + + Threads + + + + + + + + + + + + + + + {showsConnectionStatus ? ( + + + + ) : null} + + + ); +} + +const styles = StyleSheet.create({ + headerButtonGroup: { + alignItems: "center", + borderRadius: 22, + flexDirection: "row", + overflow: "hidden", + }, + threadList: { + flex: 1, + }, + threadListContent: { + paddingHorizontal: 8, + }, +}); diff --git a/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx b/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx index bf970456b6..91091a1132 100644 --- a/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx +++ b/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx @@ -8,13 +8,12 @@ import { } from "@t3tools/client-runtime/state/thread-relationships"; import { canDetachThreadProviderSession } from "@t3tools/client-runtime/state/thread-workflows"; import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts"; -import { useRouter } from "expo-router"; +import { useNavigation } from "@react-navigation/native"; import { useMemo, useState } from "react"; import { ActivityIndicator, Modal, Pressable, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/AppText"; -import { buildThreadRoutePath } from "../../lib/routes"; import { useThemeColor } from "../../lib/useThemeColor"; import { useThreadShells } from "../../state/entities"; import { threadEnvironment } from "../../state/threads"; @@ -91,7 +90,7 @@ export function ThreadRelationshipsBanner(props: { const canDetach = projection ? canDetachThreadProviderSession(projection) : false; const [visible, setVisible] = useState(false); const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null); - const router = useRouter(); + const navigation = useNavigation(); const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back"); const stopSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop"); const insets = useSafeAreaInsets(); @@ -110,11 +109,14 @@ export function ThreadRelationshipsBanner(props: { const openThread = (threadId: ThreadId, archivedThread: boolean) => { setVisible(false); void Haptics.selectionAsync(); - router.push( - archivedThread - ? "/settings/archive" - : buildThreadRoutePath({ environmentId: props.environmentId, threadId }), - ); + if (archivedThread) { + navigation.navigate("SettingsSheet", { screen: "SettingsArchive" }); + return; + } + navigation.navigate("Thread", { + environmentId: props.environmentId, + threadId, + }); }; const merge = async () => { diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 79a8161056..07cb3d13ff 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -1,21 +1,30 @@ -import { Stack, useLocalSearchParams, useRouter } from "expo-router"; +import { NativeStackScreenOptions } from "../../native/StackHeader"; +import { + StackActions, + useFocusEffect, + useNavigation, + type StaticScreenProps, +} from "@react-navigation/native"; import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; -import { useCallback, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import * as Option from "effect/Option"; -import { EnvironmentId, type ProjectScript } from "@t3tools/contracts"; +import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts"; import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts"; -import { Pressable, ScrollView, Text as RNText, View } from "react-native"; +import { Platform, ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useWorkspaceState } from "../../state/workspace"; -import { useThemeColor } from "../../lib/useThemeColor"; import { useEnvironmentQuery } from "../../state/query"; import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state"; import { vcsEnvironment } from "../../state/vcs"; import { EmptyState } from "../../components/EmptyState"; +import { + AndroidScreenHeader, + type AndroidHeaderAction, +} from "../../components/AndroidScreenHeader"; import { LoadingScreen } from "../../components/LoadingScreen"; -import { buildThreadRoutePath, buildThreadTerminalNavigation } from "../../lib/routes"; import { scopedThreadKey } from "../../lib/scopedEntities"; -import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; +import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; import { connectionTone } from "../connection/connectionTone"; import { @@ -38,8 +47,12 @@ import { } from "../terminal/terminalLaunchContext"; import { terminalDebugLog } from "../terminal/terminalDebugLog"; import { ThreadDetailScreen } from "./ThreadDetailScreen"; -import { ThreadGitControls } from "./ThreadGitControls"; -import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer"; +import { + ThreadGitControls, + useThreadGitCenterHeaderItems, + useThreadGitRightHeaderItems, +} from "./ThreadGitControls"; +import { GitOverviewSheet } from "./git/GitOverviewSheet"; import { useAtomCommand } from "../../state/use-atom-command"; import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions"; import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state"; @@ -48,6 +61,29 @@ import { useSelectedThreadWorktree } from "../../state/use-selected-thread-workt import { useThreadComposerState } from "../../state/use-thread-composer-state"; import { threadEnvironment } from "../../state/threads"; import { projectThreadContentPresentation } from "./threadContentPresentation"; +import { + useAdaptiveWorkspaceLayout, + useAdaptiveWorkspacePaneRole, + useRegisterWorkspaceInspector, +} from "../layout/AdaptiveWorkspaceLayout"; +import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items"; +import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane"; +import { + ThreadInspectorContentStack, + type ThreadInspectorMode, +} from "./thread-inspector-content-stack"; + +interface ThreadInspectorSelection { + readonly routeThreadIdentity: string | null; + readonly mode: ThreadInspectorMode; +} + +type NativeHeaderItems = ReadonlyArray>; + +function InspectorPaneRoleActivation() { + useAdaptiveWorkspacePaneRole("inspector"); + return null; +} function firstRouteParam(value: string | string[] | undefined): string | null { if (Array.isArray(value)) { @@ -61,13 +97,99 @@ function OpeningThreadLoadingScreen() { return ; } -export function ThreadRouteScreen() { +type ThreadRouteScreenRouteProps = StaticScreenProps<{ + readonly environmentId: string; + readonly threadId: string; +}>; + +interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps { + readonly onReturnToThread?: () => void; + readonly renderInspector?: (headerInset: number) => ReactNode; +} + +function ThreadUnavailableScreen() { + return ( + + + + ); +} + +export function ThreadRouteScreen(props: ThreadRouteScreenProps) { const { state: workspaceState } = useWorkspaceState(); const { connectionState } = useRemoteConnectionStatus(); + const { selectedThread } = useThreadSelection(); + const params = props.route.params; + const environmentIdRaw = firstRouteParam(params.environmentId); + const threadIdRaw = firstRouteParam(params.threadId); + const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null; + const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId); + const routeConnectionState = + routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState); + const routeThreadKey = + environmentId !== null && threadIdRaw !== null + ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw)) + : null; + const selectedThreadKey = + selectedThread === null + ? null + : scopedThreadKey(selectedThread.environmentId, selectedThread.id); + const selectedThreadDetailState = useSelectedThreadDetailState(); + + if (environmentId === null || threadIdRaw === null) { + return ; + } + + // Render the full thread chrome (header, feed, composer) as soon as the + // thread SHELL is known — no blocking on message detail. The feed shows a + // loading placeholder while messages fetch, and the composer's connection + // pill reports connecting/reconnecting/syncing status. + if (selectedThread !== null && selectedThreadKey === routeThreadKey) { + return ; + } + + const stillHydrating = + workspaceState.isLoadingConnections || + routeConnectionState === "connecting" || + routeConnectionState === "reconnecting"; + + if (stillHydrating) { + return ; + } + + return ; +} + +function ThreadRouteContent( + props: ThreadRouteScreenProps & { + readonly selectedThreadDetailState: ReturnType; + }, +) { + const { + fileInspector, + layout, + panes, + showAuxiliaryPane, + toggleAuxiliaryPane, + togglePrimarySidebar, + } = useAdaptiveWorkspaceLayout(); + const { connectionState } = useRemoteConnectionStatus(); const { onReconnectEnvironment } = useRemoteConnections(); const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } = useThreadSelection(); - const selectedThreadDetailState = useSelectedThreadDetailState(); + const selectedThreadDetailState = props.selectedThreadDetailState; const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data); const { selectedThreadCwd } = useSelectedThreadWorktree(); const composer = useThreadComposerState(); @@ -75,15 +197,71 @@ export function ThreadRouteScreen() { const gitActions = useSelectedThreadGitActions(); const requests = useSelectedThreadRequests(); const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt"); - const router = useRouter(); - const params = useLocalSearchParams<{ - environmentId?: string | string[]; - threadId?: string | string[]; - }>(); - const [drawerVisible, setDrawerVisible] = useState(false); + const navigation = useNavigation(); + const params = props.route.params; const environmentIdRaw = firstRouteParam(params.environmentId); const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null; const threadId = firstRouteParam(params.threadId); + const routeThreadIdentity = + environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null; + const [inspectorSelection, setInspectorSelection] = useState( + () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null), + ); + const inspectorMode = (() => { + if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) { + if (inspectorSelection.mode === "files" && selectedThreadCwd === null) { + return null; + } + return inspectorSelection.mode; + } + return null; + })(); + useEffect(() => { + if ( + fileInspector.supported && + selectedThreadCwd === null && + inspectorMode === null && + panes.auxiliaryPaneVisible + ) { + toggleAuxiliaryPane(); + } + }, [ + fileInspector.supported, + inspectorMode, + panes.auxiliaryPaneVisible, + selectedThreadCwd, + toggleAuxiliaryPane, + ]); + + useEffect(() => { + setInspectorSelection((current) => { + if (props.renderInspector === undefined) { + if (current === null || current.mode === "route") { + return null; + } + return { ...current, routeThreadIdentity }; + } + + if (current === null || current.mode === "route") { + return { routeThreadIdentity, mode: "route" }; + } + + return { ...current, routeThreadIdentity }; + }); + }, [props.renderInspector, routeThreadIdentity]); + + useFocusEffect( + useCallback(() => { + return () => { + if (props.renderInspector === undefined) { + // Inspectors are contextual to this chat destination. Clear the + // hidden chat copy after a native push so returning from Files, + // Review, or Terminal cannot reserve an empty trailing pane. + setInspectorSelection(null); + } + }; + }, [props.renderInspector]), + ); const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId); const routeConnectionState = routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState); @@ -102,10 +280,13 @@ export function ThreadRouteScreen() { ); /* ─── Native header theming ──────────────────────────────────────── */ - const iconColor = String(useThemeColor("--color-icon")); - const foregroundColor = String(useThemeColor("--color-foreground")); - const secondaryFg = String(useThemeColor("--color-foreground-secondary")); - + const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED; + const headerSubtitle = [ + selectedThreadProject?.title ?? null, + selectedEnvironmentConnection?.environmentLabel ?? null, + ] + .filter(Boolean) + .join(" · "); /* ─── Git status for native header trigger ───────────────────────── */ const gitStatus = useEnvironmentQuery( selectedThread !== null && selectedThreadCwd !== null @@ -145,13 +326,141 @@ export function ThreadRouteScreen() { ); const gitActionProgress = useGitActionProgress(gitActionProgressTarget); - const handleOpenDrawer = useCallback(() => { - setDrawerVisible(true); + const handleOpenGitInspector = useCallback(() => { + if (!fileInspector.supported) { + if (selectedThread === null) { + return; + } + navigation.navigate("GitOverview", { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + }); + return; + } + setInspectorSelection({ routeThreadIdentity, mode: "git" }); + showAuxiliaryPane("inspector"); + }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]); + const handleOpenFilesInspector = useCallback(() => { + if (selectedThread === null || selectedThreadCwd === null) { + return; + } + if (!fileInspector.supported) { + navigation.navigate("ThreadFiles", { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + }); + return; + } + setInspectorSelection({ + routeThreadIdentity, + mode: props.renderInspector === undefined ? "files" : "route", + }); + showAuxiliaryPane("inspector"); + }, [ + fileInspector.supported, + navigation, + props.renderInspector, + routeThreadIdentity, + selectedThread, + selectedThreadCwd, + showAuxiliaryPane, + ]); + const inspectorToggleActionRef = useRef({ + inspectorMode, + openFilesInspector: handleOpenFilesInspector, + toggleAuxiliaryPane, + }); + inspectorToggleActionRef.current = { + inspectorMode, + openFilesInspector: handleOpenFilesInspector, + toggleAuxiliaryPane, + }; + const handleToggleInspector = useCallback(() => { + const action = inspectorToggleActionRef.current; + if (action.inspectorMode === null) { + action.openFilesInspector(); + return; + } + action.toggleAuxiliaryPane(); }, []); + const handleSelectInspectorFile = useCallback( + (path: string) => { + if (selectedThread === null) { + return; + } + const params = { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + path: path.split("/").filter((segment) => segment.length > 0), + }; + if (fileInspector.supported) { + navigation.navigate("ThreadFile", params); + return; + } + navigation.navigate("ThreadFile", params); + }, + [fileInspector.supported, navigation, selectedThread], + ); + // The workspace inspector column spans the full window height. On iOS the + // panes bring their own nested native headers (which underlap the status + // bar); elsewhere the pane content pads itself below the top inset. + const safeAreaInsets = useSafeAreaInsets(); + const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top; + const GitInspector = useCallback( + () => ( + + ), + [inspectorHeaderInset, props.route.params], + ); + const FilesInspector = useCallback( + () => + selectedThread !== null && selectedThreadCwd !== null ? ( + + ) : null, + [ + handleSelectInspectorFile, + inspectorHeaderInset, + selectedThread, + selectedThreadCwd, + selectedThreadProject?.title, + ], + ); + const RouteInspector = useCallback( + () => props.renderInspector?.(inspectorHeaderInset), + [inspectorHeaderInset, props.renderInspector], + ); + const renderInspectorStack = useCallback( + () => + inspectorMode === null ? null : ( + + ), + [FilesInspector, GitInspector, RouteInspector, inspectorMode, props.renderInspector], + ); + const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack; + // Hand the inspector to the workspace so it renders beside the navigator, + // outside this screen's native header — the terminal/git/files toolbar + // stays anchored to the chat pane instead of floating above the inspector. + useRegisterWorkspaceInspector(activeInspectorRenderer); const handleOpenConnectionEditor = useCallback(() => { - void router.push("/connections"); - }, [router]); + void navigation.navigate("Connections"); + }, [navigation]); const handleStopThread = useCallback(() => { const runtime = selectedThread?.runtime; if (!selectedThread || !runtime || !threadRuntimeIsActive(runtime)) { @@ -178,16 +487,20 @@ export function ThreadRouteScreen() { return; } - void router.push(buildThreadTerminalNavigation(selectedThread, nextTerminalId)); + void navigation.navigate("ThreadTerminal", { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + ...(nextTerminalId ? { terminalId: nextTerminalId } : {}), + }); }, - [router, selectedThread, selectedThreadProject?.workspaceRoot], + [navigation, selectedThread, selectedThreadProject?.workspaceRoot], ); const handleOpenNewTerminal = useCallback(() => { terminalDebugLog("terminal-menu:open-new", { hasThread: Boolean(selectedThread), hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot), - listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId), + listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), }); if (!selectedThread || !selectedThreadProject?.workspaceRoot) { @@ -195,10 +508,14 @@ export function ThreadRouteScreen() { } const nextId = nextOpenTerminalId({ - listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId), + listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), }); - void router.push(buildThreadTerminalNavigation(selectedThread, nextId)); - }, [router, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]); + void navigation.navigate("ThreadTerminal", { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + terminalId: nextId, + }); + }, [navigation, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]); const handleRunProjectScript = useCallback( async (script: ProjectScript) => { @@ -218,9 +535,9 @@ export function ThreadRouteScreen() { } const targetTerminalId = resolveProjectScriptTerminalId({ - existingTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId), + existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId), hasRunningTerminal: terminalMenuSessions.some( - (runtime) => runtime.status === "running" || runtime.status === "starting", + (session) => session.status === "running" || session.status === "starting", ), }); const preferredWorktreePath = resolvePreferredThreadWorktreePath({ @@ -255,51 +572,164 @@ export function ThreadRouteScreen() { worktreePath: preferredWorktreePath, }); - void router.push(buildThreadTerminalNavigation(selectedThread, targetTerminalId)); + void navigation.navigate("ThreadTerminal", { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + terminalId: targetTerminalId, + }); }, [ - router, + navigation, selectedThread, selectedThreadDetailWorktreePath, selectedThreadProject, terminalMenuSessions, ], ); + const threadGitControlProps = { + environmentId: environmentIdRaw ?? "", + threadId: threadId ?? "", + auxiliaryPaneControl: + !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null + ? { + accessibilityLabel: "Toggle inspector", + onPress: handleToggleInspector, + } + : undefined, + onOpenFilesInspector: + fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined, + onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined, + currentBranch: selectedThread?.branch ?? null, + gitStatus: gitStatus.data, + gitOperationLabel: gitState.gitOperationLabel, + canOpenTerminal: Boolean(selectedThreadProject?.workspaceRoot), + canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot), + projectScripts: selectedThreadProject?.scripts ?? [], + terminalSessions: terminalMenuSessions, + showDirectFileControl: layout.usesSplitView, + onOpenTerminal: handleOpenTerminal, + onOpenNewTerminal: handleOpenNewTerminal, + onRunProjectScript: handleRunProjectScript, + onPull: gitActions.onPullSelectedThreadBranch, + onRunAction: gitActions.onRunSelectedThreadGitAction, + }; + const threadCenterHeaderItems = useThreadGitCenterHeaderItems(threadGitControlProps); + const compactRightHeaderItems = useThreadGitRightHeaderItems(threadGitControlProps); + const splitLeftHeaderItems = useMemo( + () => [ + { + // Match Mail's split-view detail toolbar: the first detail action sits + // inside the content pane, not flush against the sidebar divider. + spacing: 18, + type: "spacing" as const, + }, + ...(props.onReturnToThread + ? [ + withNativeGlassHeaderItem({ + accessibilityLabel: "Return to chat", + icon: { name: "chevron.left", type: "sfSymbol" as const }, + identifier: "thread-left-return", + onPress: props.onReturnToThread, + type: "button" as const, + }), + ] + : []), + withNativeGlassHeaderItem({ + accessibilityLabel: panes.primarySidebarVisible + ? "Maximize content" + : "Show thread sidebar", + icon: { + name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left", + type: "sfSymbol" as const, + }, + identifier: "thread-left-sidebar", + onPress: togglePrimarySidebar, + type: "button" as const, + }), + withNativeGlassHeaderItem({ + accessibilityLabel: "New task", + icon: { name: "square.and.pencil", type: "sfSymbol" as const }, + identifier: "thread-left-new-task", + onPress: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }), + type: "button" as const, + }), + ], + [panes.primarySidebarVisible, props.onReturnToThread, navigation, togglePrimarySidebar], + ); + const androidHeaderActions = useMemo>(() => { + if (Platform.OS !== "android") return []; + + const actions: AndroidHeaderAction[] = []; + if (props.onReturnToThread) { + actions.push({ + accessibilityLabel: "Return to chat", + icon: "chevron.left", + onPress: props.onReturnToThread, + }); + } + if (selectedThreadCwd !== null) { + actions.push({ + accessibilityLabel: "Open files", + icon: "folder", + onPress: handleOpenFilesInspector, + }); + } + if (selectedThreadProject?.workspaceRoot) { + actions.push({ + accessibilityLabel: "Open terminal", + icon: "terminal", + onPress: () => handleOpenTerminal(null), + }); + } + actions.push({ + accessibilityLabel: "Open git controls", + icon: "point.topleft.down.curvedto.point.bottomright.up", + onPress: handleOpenGitInspector, + }); + if (fileInspector.supported && selectedThreadCwd !== null) { + actions.push({ + accessibilityLabel: "Toggle inspector", + icon: "sidebar.right", + onPress: handleToggleInspector, + }); + } + return actions; + }, [ + fileInspector.supported, + handleOpenFilesInspector, + handleOpenTerminal, + handleOpenGitInspector, + handleToggleInspector, + props.onReturnToThread, + selectedThreadCwd, + selectedThreadProject?.workspaceRoot, + ]); + + // Deep links / cold starts land with Thread as the ONLY route, where the + // native back button does not render. Provide an explicit Home escape for + // that case; when history exists the native back button is used instead. + const canGoBack = navigation.canGoBack(); + const compactHomeHeaderItems = useMemo( + () => [ + withNativeGlassHeaderItem({ + accessibilityLabel: "Go to threads list", + icon: { name: "list.bullet", type: "sfSymbol" as const }, + identifier: "thread-left-home", + onPress: () => navigation.dispatch(StackActions.replace("Home")), + type: "button" as const, + }), + ], + [navigation], + ); if (!environmentId || !threadId) { return ; } if (!selectedThread) { - const stillHydrating = - workspaceState.isLoadingConnections || - routeConnectionState === "connecting" || - routeConnectionState === "reconnecting"; - - if (stillHydrating) { - return ; - } - - return ( - - - - ); + return ; } - const selectedThreadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id); const contentPresentation = projectThreadContentPresentation({ hasDetail: selectedThreadDetail !== null, detailError: Option.getOrNull(selectedThreadDetailState.error), @@ -307,74 +737,9 @@ export function ThreadRouteScreen() { connectionState: routeConnectionState, }); const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null; - - const headerSubtitle = [ - selectedThreadProject?.title ?? null, - selectedEnvironmentConnection?.environmentLabel ?? null, - ] - .filter(Boolean) - .join(" · "); - - return ( + const renderThreadRouteBody = (showActionControls: boolean) => ( <> - ( - { - // TODO: trigger rename modal - }} - > - - {selectedThread.title} - - - {headerSubtitle} - - - ), - }} - /> - - + @@ -396,12 +761,14 @@ export function ThreadRouteScreen() { draftMessage={composer.draftMessage} draftAttachments={composer.draftAttachments} connectionStateLabel={routeConnectionState} + threadSyncStatus={selectedThreadDetailState.status} activeThreadBusy={composer.activeThreadBusy} environmentId={selectedThread.environmentId} projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null} threadCwd={selectedThreadCwd} selectedThreadQueueCount={composer.selectedThreadQueueCount} - onOpenDrawer={handleOpenDrawer} + layoutVariant={layout.variant} + usesAutomaticContentInsets={usesNativeHeaderGlass} onOpenConnectionEditor={handleOpenConnectionEditor} onChangeDraftMessage={composer.onChangeDraftMessage} onPickDraftImages={composer.onPickDraftImages} @@ -419,17 +786,63 @@ export function ThreadRouteScreen() { onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer} onSubmitUserInput={requests.onSubmitUserInput} /> - - setDrawerVisible(false)} - onSelectThread={(thread) => { - router.replace(buildThreadRoutePath(thread)); - }} - onStartNewTask={() => router.push("/new")} - /> ); + + return ( + <> + {activeInspectorRenderer ? : null} + splitLeftHeaderItems + : canGoBack + ? undefined + : () => compactHomeHeaderItems + : undefined, + // Search lives in the persistent sidebar, so the split header keeps + // the git controls on the RIGHT (no center items — center space is + // reserved for future breadcrumbs/status). + unstable_headerRightItems: + Platform.OS === "ios" + ? () => (layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems) + : undefined, + unstable_headerSubtitle: usesNativeHeaderGlass ? headerSubtitle : undefined, + }} + /> + + {Platform.OS === "android" ? ( + navigation.goBack()} + actions={androidHeaderActions} + /> + ) : null} + + {/* Android surfaces the git/files/inspector actions in its in-flow + header above, so the fallback action toolbar stays iOS-only. */} + {renderThreadRouteBody( + Platform.OS !== "android" && !layout.usesSplitView && !usesNativeHeaderGlass, + )} + + ); } diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx index e27136702f..c66fc78876 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx @@ -1,11 +1,12 @@ import { sanitizeFeatureBranchName } from "@t3tools/shared/git"; -import { useRouter } from "expo-router"; +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useState } from "react"; -import { Pressable, ScrollView, View } from "react-native"; +import { Platform, Pressable, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; -import { useThemeColor } from "../../../lib/useThemeColor"; +import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader"; import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText"; +import { cn } from "../../../lib/cn"; import { useEnvironmentQuery } from "../../../state/query"; import { useThreadSelection } from "../../../state/use-thread-selection"; import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; @@ -14,20 +15,19 @@ import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-wo import { vcsEnvironment } from "../../../state/vcs"; import { SheetActionButton } from "./gitSheetComponents"; -export function GitBranchesSheet() { - const router = useRouter(); +type GitBranchesSheetProps = StaticScreenProps<{ + readonly environmentId: string; + readonly threadId: string; +}>; + +export function GitBranchesSheet(_props: GitBranchesSheetProps) { + const navigation = useNavigation(); const insets = useSafeAreaInsets(); const { selectedThread } = useThreadSelection(); const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree(); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); - const borderColor = useThemeColor("--color-border"); - const inputBorderColor = useThemeColor("--color-input-border"); - const inputBg = useThemeColor("--color-input"); - const foregroundColor = useThemeColor("--color-foreground"); - const subtleStrongColor = useThemeColor("--color-subtle-strong"); - const gitStatus = useEnvironmentQuery( selectedThread !== null && selectedThreadCwd !== null ? vcsEnvironment.status({ @@ -58,147 +58,125 @@ export function GitBranchesSheet() { const disabledExistingBranches = new Set(disabledExistingBranchNames); return ( - - - - New branch - - - { - const branch = sanitizeFeatureBranchName(newBranchName.trim()); - if (branch.length === 0) return; - void gitActions.onCreateSelectedThreadBranch(branch).then(() => { - setNewBranchName(""); - router.dismiss(); - }); - }} - /> - - - - - New worktree - - - - { - const baseBranch = worktreeBaseBranch.trim(); - const newBranch = worktreeBranchName.trim(); - if (baseBranch.length === 0 || newBranch.length === 0) return; - void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => { - setWorktreeBranchName(""); - router.dismiss(); - }); - }} - /> - - - - - Existing branches - - {branchesLoading ? ( - Loading branches... - ) : null} - {!branchesLoading && availableBranches.length === 0 ? ( - - No local branches found. + + {Platform.OS === "android" ? ( + navigation.goBack()} /> + ) : null} + + + + New branch - ) : null} - {availableBranches.map((branch) => { - const disabled = disabledExistingBranches.has(branch.name); - const subtitle = branch.worktreePath - ? branch.worktreePath === currentWorktreePath - ? "Checked out in this thread" - : "Checked out in another worktree" - : branch.isDefault - ? "Default branch" - : "Local branch"; + + { + const branch = sanitizeFeatureBranchName(newBranchName.trim()); + if (branch.length === 0) return; + void gitActions.onCreateSelectedThreadBranch(branch).then(() => { + setNewBranchName(""); + navigation.goBack(); + }); + }} + /> + - return ( - { - void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => { - router.dismiss(); - }); - }} - > - - {branch.name} - {subtitle} - - ); - })} - - + + + New worktree + + + + { + const baseBranch = worktreeBaseBranch.trim(); + const newBranch = worktreeBranchName.trim(); + if (baseBranch.length === 0 || newBranch.length === 0) return; + void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => { + setWorktreeBranchName(""); + navigation.goBack(); + }); + }} + /> + + + + + Existing branches + + {branchesLoading ? ( + + Loading branches... + + ) : null} + {!branchesLoading && availableBranches.length === 0 ? ( + + No local branches found. + + ) : null} + {availableBranches.map((branch) => { + const disabled = disabledExistingBranches.has(branch.name); + const subtitle = branch.worktreePath + ? branch.worktreePath === currentWorktreePath + ? "Checked out in this thread" + : "Checked out in another worktree" + : branch.isDefault + ? "Default branch" + : "Local branch"; + + return ( + { + void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => { + navigation.goBack(); + }); + }} + > + + {branch.name} + {subtitle} + + ); + })} + + + ); } diff --git a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx index 76e0daf5f0..cdc7f1a64a 100644 --- a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx @@ -1,10 +1,11 @@ -import { useRouter } from "expo-router"; +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useCallback, useState } from "react"; -import { Pressable, ScrollView, View, useColorScheme } from "react-native"; +import { Platform, Pressable, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; -import { useThemeColor } from "../../../lib/useThemeColor"; +import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader"; import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText"; +import { cn } from "../../../lib/cn"; import { useEnvironmentQuery } from "../../../state/query"; import { useThreadSelection } from "../../../state/use-thread-selection"; import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; @@ -13,21 +14,19 @@ import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-wo import { vcsEnvironment } from "../../../state/vcs"; import { SheetActionButton } from "./gitSheetComponents"; -export function GitCommitSheet() { - const router = useRouter(); +type GitCommitSheetProps = StaticScreenProps<{ + readonly environmentId: string; + readonly threadId: string; +}>; + +export function GitCommitSheet(_props: GitCommitSheetProps) { + const navigation = useNavigation(); const insets = useSafeAreaInsets(); - const isDarkMode = useColorScheme() === "dark"; const { selectedThread } = useThreadSelection(); const { selectedThreadCwd } = useSelectedThreadWorktree(); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); - const borderColor = useThemeColor("--color-border"); - const borderSubtleColor = useThemeColor("--color-border-subtle"); - const inputBorderColor = useThemeColor("--color-input-border"); - const inputBg = useThemeColor("--color-input"); - const foregroundColor = useThemeColor("--color-foreground"); - const gitStatus = useEnvironmentQuery( selectedThread !== null && selectedThreadCwd !== null ? vcsEnvironment.status({ @@ -55,7 +54,7 @@ export function GitCommitSheet() { const runCommitAction = useCallback( async (featureBranch: boolean) => { const commitMessage = dialogCommitMessage.trim(); - router.dismiss(); + navigation.goBack(); await gitActions.onRunSelectedThreadGitAction({ action: "commit", featureBranch, @@ -63,184 +62,172 @@ export function GitCommitSheet() { ...(!allSelected ? { filePaths: selectedFiles.map((file) => file.path) } : {}), }); }, - [allSelected, dialogCommitMessage, gitActions, router, selectedFiles], + [allSelected, dialogCommitMessage, gitActions, navigation, selectedFiles], ); return ( - - - - Branch - - {gitStatus.data?.refName ?? "(detached HEAD)"} - - - {isDefaultRef ? ( - - Warning: this is the default branch. - - ) : null} - - - - - - Files - - {selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions} + + {Platform.OS === "android" ? ( + navigation.goBack()} /> + ) : null} + + + + Branch + + {gitStatus.data?.refName ?? "(detached HEAD)"} - - {!allSelected && isEditingFiles ? ( + {isDefaultRef ? ( + + Warning: this is the default branch. + + ) : null} + + + + + + Files + + {selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions} + + + + {!allSelected && isEditingFiles ? ( + setExcludedFiles(new Set())} + > + Reset + + ) : null} setExcludedFiles(new Set())} + onPress={() => setIsEditingFiles((current) => !current)} > - Reset + + {isEditingFiles ? "Done" : "Edit"} + - ) : null} - setIsEditingFiles((current) => !current)} - > - - {isEditingFiles ? "Done" : "Edit"} - - + - - {allFiles.length === 0 ? ( - - No changed files are available to commit. - - ) : !isEditingFiles ? ( - - {selectedFilePreview.map((file) => ( - - - {file.path} + {allFiles.length === 0 ? ( + + No changed files are available to commit. + + ) : !isEditingFiles ? ( + + {selectedFilePreview.map((file) => ( + + + {file.path} + + +{file.insertions} + -{file.deletions} + + ))} + {selectedFiles.length > selectedFilePreview.length ? ( + + +{selectedFiles.length - selectedFilePreview.length} more files - - +{file.insertions} - - - -{file.deletions} - - - ))} - {selectedFiles.length > selectedFilePreview.length ? ( - - +{selectedFiles.length - selectedFilePreview.length} more files - - ) : null} - - ) : ( - - {allFiles.map((file) => { - const included = !excludedFiles.has(file.path); - return ( - { - setExcludedFiles((current) => { - const next = new Set(current); - if (next.has(file.path)) { - next.delete(file.path); - } else { - next.add(file.path); - } - return next; - }); - }} - > - - - - - {file.path} - - {!included ? ( - - Excluded from this commit + ) : null} + + ) : ( + + {allFiles.map((file) => { + const included = !excludedFiles.has(file.path); + return ( + { + setExcludedFiles((current) => { + const next = new Set(current); + if (next.has(file.path)) { + next.delete(file.path); + } else { + next.add(file.path); + } + return next; + }); + }} + > + + + + + {file.path} - ) : null} + {!included ? ( + + Excluded from this commit + + ) : null} + + + + +{file.insertions} + + + -{file.deletions} + + - - - +{file.insertions} - - - -{file.deletions} - - - - - ); - })} + + ); + })} + + )} + + + + Commit message + + + + + + void runCommitAction(true)} + /> + + + void runCommitAction(false)} + /> - )} - - - - Commit message - - - - - - void runCommitAction(true)} - /> - - void runCommitAction(false)} - /> - - - + + ); } diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx index 4272c31d2c..cddf1c614b 100644 --- a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx @@ -2,29 +2,35 @@ import { resolveDefaultBranchActionDialogCopy } from "@t3tools/client-runtime/st import { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; import * as Arr from "effect/Array"; import * as Result from "effect/Result"; -import { useLocalSearchParams, useRouter } from "expo-router"; +import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useCallback, useMemo } from "react"; -import { View } from "react-native"; +import { Platform, View } from "react-native"; + import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader"; import { AppText as Text } from "../../../components/AppText"; import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; import { SheetActionButton } from "./gitSheetComponents"; -export function GitConfirmSheet() { - const router = useRouter(); +type GitConfirmSheetProps = StaticScreenProps<{ + readonly environmentId: string; + readonly threadId: string; + readonly confirmAction?: string; + readonly branchName?: string; + readonly includesCommit?: string; + readonly commitMessage?: string; + readonly filePaths?: string; +}>; + +export function GitConfirmSheet(props: GitConfirmSheetProps) { + const navigation = useNavigation(); const insets = useSafeAreaInsets(); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); - const params = useLocalSearchParams<{ - confirmAction?: string; - branchName?: string; - includesCommit?: string; - commitMessage?: string; - filePaths?: string; - }>(); + const params = props.route.params; const confirmAction = params.confirmAction as | "push" @@ -34,6 +40,8 @@ export function GitConfirmSheet() { | undefined; const branchName = params.branchName ?? ""; const includesCommit = params.includesCommit === "true"; + const environmentId = params.environmentId ?? ""; + const threadId = params.threadId ?? ""; const copy = useMemo( () => @@ -49,17 +57,17 @@ export function GitConfirmSheet() { const continuePendingAction = useCallback(async () => { if (!confirmAction) return; - router.dismissAll(); + navigation.dispatch(StackActions.replace("Thread", { environmentId, threadId })); await gitActions.onRunSelectedThreadGitAction({ action: confirmAction, ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), ...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}), }); - }, [confirmAction, gitActions, params, router]); + }, [confirmAction, environmentId, gitActions, params, navigation, threadId]); const movePendingActionToFeatureBranch = useCallback(async () => { if (!confirmAction) return; - router.dismissAll(); + navigation.dispatch(StackActions.replace("Thread", { environmentId, threadId })); if (includesCommit) { await gitActions.onRunSelectedThreadGitAction({ @@ -82,31 +90,38 @@ export function GitConfirmSheet() { ); await gitActions.onCreateSelectedThreadBranch(newBranchName); await gitActions.onRunSelectedThreadGitAction({ action: confirmAction }); - }, [confirmAction, gitActions, gitState.selectedThreadBranches, includesCommit, params, router]); + }, [ + confirmAction, + gitActions, + gitState.selectedThreadBranches, + includesCommit, + params, + navigation, + environmentId, + threadId, + ]); return ( - + {Platform.OS === "android" ? ( + navigation.goBack()} /> + ) : ( + + )} - + Confirm {copy?.title ?? "Run action on default branch?"} - + {copy?.description ?? "Choose how to continue."} - + & { + readonly headerInset?: number; + readonly presentation?: "sheet" | "inspector"; +}; + +export function GitOverviewSheet(props: GitOverviewSheetProps) { + const navigation = useNavigation(); const insets = useSafeAreaInsets(); - const { environmentId, threadId } = useLocalSearchParams<{ - environmentId: EnvironmentId; - threadId: ThreadId; - }>(); + const presentation = props.presentation ?? "sheet"; + const isInspector = presentation === "inspector"; + const environmentId = EnvironmentId.make(props.route.params.environmentId); + const threadId = ThreadId.make(props.route.params.threadId); const { selectedThread } = useThreadSelection(); const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree(); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); const iconColor = useThemeColor("--color-icon"); - const borderColor = useThemeColor("--color-border"); + const foregroundColor = String(useThemeColor("--color-foreground")); + const sheetColor = String(useThemeColor("--color-sheet")); const gitStatus = useEnvironmentQuery( selectedThread !== null && selectedThreadCwd !== null @@ -48,6 +68,7 @@ export function GitOverviewSheet() { ); const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD"; + const currentStatusSummary = statusSummary(gitStatus.data); const currentWorktreePath = selectedThreadWorktreePath; const gitOperationLabel = gitState.gitOperationLabel; const busy = gitOperationLabel !== null; @@ -105,25 +126,24 @@ export function GitOverviewSheet() { !input.featureBranch && requiresDefaultBranchConfirmation(input.action, isDefaultRef) ) { - router.push({ - pathname: "/threads/[environmentId]/[threadId]/git-confirm", - params: { - environmentId, - threadId, - confirmAction: confirmableAction, - branchName, - includesCommit: String( - input.action === "commit_push" || input.action === "commit_push_pr", - ), - }, + navigation.navigate("GitConfirm", { + environmentId: String(environmentId), + threadId: String(threadId), + confirmAction: confirmableAction, + branchName, + includesCommit: String( + input.action === "commit_push" || input.action === "commit_push_pr", + ), }); return; } - router.dismiss(); + if (!isInspector) { + navigation.goBack(); + } await gitActions.onRunSelectedThreadGitAction(input); }, - [environmentId, gitActions, gitStatus.data, isDefaultRef, router, threadId], + [environmentId, gitActions, gitStatus.data, isDefaultRef, isInspector, navigation, threadId], ); const onPressMenuItem = useCallback( @@ -134,9 +154,9 @@ export function GitOverviewSheet() { return; } if (item.dialogAction === "commit") { - router.push({ - pathname: "/threads/[environmentId]/[threadId]/git/commit", - params: { environmentId, threadId }, + navigation.navigate("GitCommit", { + environmentId: String(environmentId), + threadId: String(threadId), }); return; } @@ -148,102 +168,253 @@ export function GitOverviewSheet() { await runActionWithPrompt({ action: "create_pr" }); } }, - [environmentId, openExistingPr, router, runActionWithPrompt, threadId], + [environmentId, openExistingPr, navigation, runActionWithPrompt, threadId], ); - return ( - - + // Status facts live on the relevant rows instead of crowding the header + // subtitle: files changed → Commit, ahead → Push, PR → View PR, behind → Pull. + const rowStatusDetail = useCallback( + (item: (typeof menuItems)[number]): string | undefined => { + const status = gitStatus.data; + if (status == null) { + return undefined; + } + if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) { + const fileCount = status.workingTree?.files.length ?? 0; + return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`; + } + if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) { + const ahead = status.aheadCount ?? 0; + return `${ahead} commit${ahead === 1 ? "" : "s"} ahead`; + } + if (item.kind === "open_pr" && status.pr?.number != null) { + return `PR #${status.pr.number} ${status.pr.state ?? "open"}`; + } + return undefined; + }, + [gitStatus.data, menuItems], + ); - - void gitActions.refreshSelectedThreadGitStatus()} - > - - - - Branch - - {currentBranchLabel} - - {statusSummary(gitStatus.data)} - + const behindCount = gitStatus.data?.behindCount ?? 0; + + // Deterministic pull-to-refresh state. Tying RefreshControl to the query's + // isPending flag left the spinner stuck (the status query reports pending + // during quiet background refreshes too). + const [isPullRefreshing, setIsPullRefreshing] = useState(false); + const handlePullRefresh = useCallback(async () => { + setIsPullRefreshing(true); + try { + await gitActions.refreshSelectedThreadGitStatus(); + } finally { + setIsPullRefreshing(false); + } + }, [gitActions]); + + const content = ( + void handlePullRefresh()} /> + } + > + + {sheetMenuItems.map(({ item, disabledReason }, index) => ( + + {index > 0 ? : null} + void onPressMenuItem(item)} + /> + + ))} + {behindCount > 0 ? ( + <> + + void gitActions.onPullSelectedThreadBranch()} + /> + + ) : null} + + { + const params = { environmentId, threadId }; + navigation.dispatch( + resolveGitOverviewReviewNavigationAction(presentation) === "replace" + ? StackActions.replace("ThreadReview", params) + : CommonActions.navigate("ThreadReview", params), + ); + }} + /> + + + navigation.navigate("GitBranches", { + environmentId: String(environmentId), + threadId: String(threadId), + }) + } + /> - - - {sheetMenuItems.map(({ item, disabledReason }, index) => ( - - {index > 0 ? ( - - ) : null} - void onPressMenuItem(item)} - /> - - ))} - {(gitStatus.data?.behindCount ?? 0) > 0 ? ( - <> - - void gitActions.onPullSelectedThreadBranch()} - /> - - ) : null} - - router.push(buildThreadReviewRoutePath({ environmentId, threadId }))} - /> - - - router.push({ - pathname: "/threads/[environmentId]/[threadId]/git/branches", - params: { environmentId, threadId }, - }) - } - /> - + {currentWorktreePath ? : null} + + ); - {currentWorktreePath ? : null} - + if (isInspector && Platform.OS === "ios") { + return ( + + + + {content} + + + + + ); + } + + if (Platform.OS === "ios") { + // Compact form sheet: a plain screen presented as formSheet never renders a + // stack header, so — like the Settings sheet — the header must come from a + // nested native stack INSIDE the sheet. This reuses the exact structure of the + // inspector branch below: branch as the title, status summary as the native + // subtitle, refresh as a header button. + return ( + + + + {content} + + + + + ); + } + + return ( + + {isInspector ? ( + + ) : null} + + {isInspector ? ( + + void gitActions.refreshSelectedThreadGitStatus()} + > + + + + Repository + + {currentBranchLabel} + + {currentStatusSummary} + + + ) : ( + navigation.goBack()} + actions={[ + { + accessibilityLabel: "Refresh repository status", + disabled: busy, + icon: "arrow.clockwise", + onPress: () => void gitActions.refreshSelectedThreadGitStatus(), + }, + ]} + /> + )} + + {content} ); } diff --git a/apps/mobile/src/features/threads/git/git-overview-navigation.test.ts b/apps/mobile/src/features/threads/git/git-overview-navigation.test.ts new file mode 100644 index 0000000000..b50bc42a9b --- /dev/null +++ b/apps/mobile/src/features/threads/git/git-overview-navigation.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveGitOverviewReviewNavigationAction } from "./git-overview-navigation"; + +describe("resolveGitOverviewReviewNavigationAction", () => { + it("replaces the sheet so Back returns directly to the thread", () => { + expect(resolveGitOverviewReviewNavigationAction("sheet")).toBe("replace"); + }); + + it("pushes Review normally when Git is a persistent inspector", () => { + expect(resolveGitOverviewReviewNavigationAction("inspector")).toBe("navigate"); + }); +}); diff --git a/apps/mobile/src/features/threads/git/git-overview-navigation.ts b/apps/mobile/src/features/threads/git/git-overview-navigation.ts new file mode 100644 index 0000000000..53927356c6 --- /dev/null +++ b/apps/mobile/src/features/threads/git/git-overview-navigation.ts @@ -0,0 +1,5 @@ +export function resolveGitOverviewReviewNavigationAction( + presentation: "sheet" | "inspector", +): "replace" | "navigate" { + return presentation === "sheet" ? "replace" : "navigate"; +} diff --git a/apps/mobile/src/features/threads/git/gitSheetComponents.tsx b/apps/mobile/src/features/threads/git/gitSheetComponents.tsx index 16c311bff5..61346fcef0 100644 --- a/apps/mobile/src/features/threads/git/gitSheetComponents.tsx +++ b/apps/mobile/src/features/threads/git/gitSheetComponents.tsx @@ -1,8 +1,9 @@ -import { SymbolView } from "expo-symbols"; +import { SymbolView } from "../../../components/AppSymbol"; import type { ComponentProps } from "react"; import { Pressable, View } from "react-native"; import { useThemeColor } from "../../../lib/useThemeColor"; import { AppText as Text } from "../../../components/AppText"; +import { cn } from "../../../lib/cn"; /* ─── Shared sheet components ──────────────────────────────────────── */ @@ -13,51 +14,36 @@ export function SheetActionButton(props: { readonly tone?: "primary" | "secondary" | "danger"; readonly onPress: () => void; }) { - const primaryBg = useThemeColor("--color-primary"); const primaryFg = useThemeColor("--color-primary-foreground"); - const dangerBg = useThemeColor("--color-danger"); - const dangerBorder = useThemeColor("--color-danger-border"); const dangerFg = useThemeColor("--color-danger-foreground"); - const secondaryBg = useThemeColor("--color-secondary"); - const secondaryBorder = useThemeColor("--color-secondary-border"); const secondaryFg = useThemeColor("--color-secondary-foreground"); const tone = props.tone ?? "secondary"; - const colors = - tone === "primary" - ? { - backgroundColor: primaryBg, - borderColor: "transparent", - textColor: primaryFg, - } - : tone === "danger" - ? { - backgroundColor: dangerBg, - borderColor: dangerBorder, - textColor: dangerFg, - } - : { - backgroundColor: secondaryBg, - borderColor: secondaryBorder, - textColor: secondaryFg, - }; + const textColor = tone === "primary" ? primaryFg : tone === "danger" ? dangerFg : secondaryFg; return ( - + {props.label} @@ -68,10 +54,7 @@ export function SheetActionButton(props: { export function MetaCard(props: { readonly label: string; readonly value: string }) { return ( - + {props.label} @@ -93,9 +76,8 @@ export function SheetListRow(props: { return ( @@ -104,7 +86,7 @@ export function SheetListRow(props: { {props.title} {props.subtitle ? ( - {props.subtitle} + {props.subtitle} ) : null} diff --git a/apps/mobile/src/features/threads/markdownCodeHighlightState.ts b/apps/mobile/src/features/threads/markdownCodeHighlightState.ts new file mode 100644 index 0000000000..c415cf7398 --- /dev/null +++ b/apps/mobile/src/features/threads/markdownCodeHighlightState.ts @@ -0,0 +1,87 @@ +import { useAtomValue } from "@effect/atom-react"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import { AsyncResult, Atom } from "effect/unstable/reactivity"; +import { useMemo } from "react"; + +import { + highlightCodeSnippet, + type ReviewDiffTheme, + type ReviewHighlightedToken, +} from "../review/shikiReviewHighlighter"; + +const MARKDOWN_CODE_HIGHLIGHT_IDLE_TTL_MS = 5 * 60_000; + +export type MarkdownHighlightedCode = ReadonlyArray>; + +export interface MarkdownCodeHighlightInput { + readonly code: string; + readonly enabled: boolean; + readonly language: string; + readonly theme: ReviewDiffTheme; +} + +type MarkdownCodeHighlighter = ( + input: MarkdownCodeHighlightInput, +) => Promise; + +class MarkdownCodeHighlightCacheKey extends Data.Class {} + +class MarkdownCodeHighlightError extends Data.TaggedError("MarkdownCodeHighlightError")<{ + readonly cause: unknown; +}> {} + +export function createMarkdownCodeHighlightAtomFamily(options?: { + readonly highlight?: MarkdownCodeHighlighter; + readonly idleTtlMs?: number; +}) { + const highlight = + options?.highlight ?? + ((input: MarkdownCodeHighlightInput) => + input.enabled + ? highlightCodeSnippet({ + code: input.code, + language: input.language, + theme: input.theme, + }) + : Promise.resolve(null)); + const idleTtlMs = options?.idleTtlMs ?? MARKDOWN_CODE_HIGHLIGHT_IDLE_TTL_MS; + const family = Atom.family((request: MarkdownCodeHighlightCacheKey) => + Atom.make( + Effect.tryPromise({ + try: () => highlight(request), + catch: (cause) => new MarkdownCodeHighlightError({ cause }), + }), + ).pipe( + Atom.setIdleTTL(idleTtlMs), + Atom.withLabel(`mobile:thread-markdown-code-highlight:${request.theme}:${request.language}`), + ), + ); + + return (input: MarkdownCodeHighlightInput) => family(new MarkdownCodeHighlightCacheKey(input)); +} + +export const markdownCodeHighlightAtom = createMarkdownCodeHighlightAtomFamily(); + +export function useMarkdownCodeHighlight(input: { + readonly code: string; + readonly enabled: boolean; + readonly language: string | null | undefined; + readonly theme: ReviewDiffTheme; +}): MarkdownHighlightedCode | null { + const normalizedLanguage = input.language?.trim() || "text"; + const enabled = input.enabled && Boolean(input.language?.trim()); + const atomLanguage = enabled ? normalizedLanguage : "text"; + const highlightAtom = useMemo( + () => + markdownCodeHighlightAtom({ + code: enabled ? input.code : "", + enabled, + language: atomLanguage, + theme: input.theme, + }), + [atomLanguage, enabled, input.code, input.theme], + ); + const result = useAtomValue(highlightAtom); + return AsyncResult.isSuccess(result) ? result.value : null; +} diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index 9a8dde3429..ee2bde9d97 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useMemo, useState } from "react"; +import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { EnvironmentId, @@ -8,18 +8,29 @@ import type { RuntimeMode, ServerProviderSkill, } from "@t3tools/contracts"; -import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "@t3tools/contracts"; +import { + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + DEFAULT_RUNTIME_MODE, + MessageId, + ThreadId, +} from "@t3tools/contracts"; import * as Arr from "effect/Array"; import { pipe } from "effect/Function"; import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities"; +import type { TurnCommandMetadata } from "../../lib/commandMetadata"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import type { ModelOption, ProviderGroup } from "../../lib/modelOptions"; import { buildModelOptions, groupByProvider } from "../../lib/modelOptions"; import { groupProjectsByRepository } from "../../lib/repositoryGroups"; import { scopedProjectKey } from "../../lib/scopedEntities"; +import { appAtomRegistry } from "../../state/atom-registry"; import { appendComposerDraftAttachments, + clearComposerDraft, + getComposerDraftSnapshot, + isComposerDraftEmpty, removeComposerDraftAttachment, replaceComposerDraftAttachments, setComposerDraftText, @@ -27,6 +38,17 @@ import { useComposerDraft, } from "../../state/use-composer-drafts"; import { useBranches } from "../../state/queries"; +import { + flattenQueuedThreadMessages, + threadOutboxManager, + updateThreadOutboxMessage, + type QueuedThreadMessage, +} from "../../state/thread-outbox"; +import { + holdEditingQueuedMessage, + releaseEditingQueuedMessage, + useThreadOutboxMessages, +} from "../../state/use-thread-outbox"; import { setPendingConnectionError, useSavedRemoteConnections, @@ -36,6 +58,23 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs"; type WorkspaceMode = "local" | "worktree"; +function pendingTaskDraftKey(messageId: string): string { + return `pending-task:${messageId}`; +} + +// The message id owned by the currently active editing session, tracked +// across provider instances. An in-flight flush from a dismissed session +// consults it so it never drops the draft or releases the drain lock out from +// under a newer session editing the same task. +let activeEditingMessageId: string | null = null; + +function findQueuedPendingTask(messageId: string): QueuedThreadMessage | null { + const message = flattenQueuedThreadMessages( + appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + ).find((candidate) => candidate.messageId === messageId); + return message?.creation !== undefined ? message : null; +} + function normalizeSelectedWorktreePath(project: EnvironmentProject, branch: VcsRef): string | null { if (!branch.worktreePath) { return null; @@ -74,6 +113,9 @@ type NewTaskFlowContextValue = { readonly workspaceMode: WorkspaceMode; readonly selectedBranchName: string | null; readonly selectedWorktreePath: string | null; + readonly startFromOrigin: boolean; + readonly draftKey: string | null; + readonly editingPendingTask: QueuedThreadMessage | null; readonly prompt: string; readonly attachments: ReadonlyArray; readonly submitting: boolean; @@ -100,6 +142,11 @@ type NewTaskFlowContextValue = { readonly setSelectedModelKey: (key: string | null) => void; readonly setWorkspaceMode: (mode: WorkspaceMode) => void; readonly selectBranch: (branch: VcsRef) => void; + readonly setStartFromOrigin: (value: boolean) => void; + readonly beginEditingPendingTask: (messageId: string) => boolean; + readonly finishEditingPendingTask: () => void; + readonly cancelEditingPendingTask: () => void; + readonly buildPendingTaskMessage: (metadata: TurnCommandMetadata) => QueuedThreadMessage | null; readonly setPrompt: (value: string) => void; readonly replaceAttachments: (attachments: ReadonlyArray) => void; readonly appendAttachments: (attachments: ReadonlyArray) => void; @@ -162,6 +209,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { const [submitting, setSubmitting] = useState(false); const [branchQuery, setBranchQuery] = useState(""); const [expandedProvider, setExpandedProvider] = useState(null); + const [editingPendingTask, setEditingPendingTask] = useState(null); + // Mirrors `editingPendingTask` synchronously so the unmount flush cannot act + // on a task whose editing session already ended this render. + const editingPendingTaskRef = useRef(null); const reset = useCallback(() => { setSelectedEnvironmentId(null); @@ -169,42 +220,17 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { setSubmitting(false); setBranchQuery(""); setExpandedProvider(null); + const editing = editingPendingTaskRef.current; + editingPendingTaskRef.current = null; + setEditingPendingTask(null); + if (editing) { + if (activeEditingMessageId === editing.messageId) { + activeEditingMessageId = null; + } + releaseEditingQueuedMessage(editing.messageId); + } }, []); - const environments = useMemo( - () => - pipe( - [ - ...new Set( - pipe( - projects, - Arr.map((project) => project.environmentId), - ), - ), - ], - Arr.map((environmentId) => { - const environment = savedConnectionsById[environmentId]; - if (!environment) { - return null; - } - - return { - environmentId, - environmentLabel: environment.environmentLabel, - }; - }), - Arr.filter( - ( - entry, - ): entry is { - readonly environmentId: EnvironmentId; - readonly environmentLabel: string; - } => entry !== null, - ), - ), - [projects, savedConnectionsById], - ); - const projectsForEnvironment = useMemo( () => pipe( @@ -214,24 +240,115 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { [projects, selectedEnvironmentId], ); + // Stand-in for the edited task's project while its shell is not loaded + // (environment offline / still synchronizing), built from the metadata + // snapshotted at enqueue time. + const editingPendingProject = useMemo(() => { + const creation = editingPendingTask?.creation; + if (!editingPendingTask || !creation) { + return null; + } + return { + environmentId: editingPendingTask.environmentId, + id: creation.projectId, + title: creation.projectTitle ?? "Unknown project", + // Deliberately empty when the snapshot has no cwd — downstream consumers + // (branch queries, worktree bootstrap) must skip it, not receive a + // fabricated path. + workspaceRoot: creation.projectCwd ?? "", + repositoryIdentity: null, + defaultModelSelection: editingPendingTask.modelSelection ?? null, + scripts: [], + createdAt: editingPendingTask.createdAt, + updatedAt: editingPendingTask.createdAt, + }; + }, [editingPendingTask]); + const selectedProject = projectsForEnvironment.find( (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey, ) ?? - projectsForEnvironment[0] ?? - null; + // While editing a queued task whose project shell is absent, keep the task + // pinned to its own project — falling through to an arbitrary first + // project would silently retarget it (and its reused turn identifiers). + (editingPendingProject !== null && + selectedProjectKey === + scopedProjectKey(editingPendingProject.environmentId, editingPendingProject.id) + ? editingPendingProject + : (projectsForEnvironment[0] ?? null)); + + // Only offer machines that actually host the currently selected repository, so + // switching computers moves the same repo across machines instead of jumping to + // whatever unrelated project happens to be first on the other machine. Repository + // identity is the primary signal; projects that haven't reported one yet (still + // indexing) fall back to workspace basename / title so a valid host isn't hidden. + const selectedRepositoryKey = selectedProject?.repositoryIdentity?.canonicalKey ?? null; + // `|| null` (not `??`): a pending-task placeholder project can have an empty + // workspaceRoot, and an "" basename would reject every real host below. + const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null; + const selectedProjectTitle = selectedProject?.title ?? null; + const environments = useMemo(() => { + const seen = new Set(); + const result: Array<{ + readonly environmentId: EnvironmentId; + readonly environmentLabel: string; + }> = []; + const hostsSelectedRepository = (project: EnvironmentProject) => { + if (selectedRepositoryKey === null && selectedWorkspaceBasename === null) { + return true; + } + const projectKey = project.repositoryIdentity?.canonicalKey ?? null; + if (selectedRepositoryKey !== null && projectKey !== null) { + return projectKey === selectedRepositoryKey; + } + return ( + project.workspaceRoot.split("/").at(-1) === selectedWorkspaceBasename || + (selectedProjectTitle !== null && project.title === selectedProjectTitle) + ); + }; + for (const project of projects) { + if (!hostsSelectedRepository(project)) { + continue; + } + if (seen.has(project.environmentId)) { + continue; + } + const environment = savedConnectionsById[project.environmentId]; + if (!environment) { + continue; + } + seen.add(project.environmentId); + result.push({ + environmentId: project.environmentId, + environmentLabel: environment.environmentLabel, + }); + } + return result; + }, [ + projects, + savedConnectionsById, + selectedRepositoryKey, + selectedWorkspaceBasename, + selectedProjectTitle, + ]); + const selectedEnvironmentServerConfig = useEnvironmentServerConfig( selectedProject?.environmentId ?? null, ); - const selectedProjectDraftKey = selectedProject - ? `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}` - : null; + // While a queued pending task is being edited its draft lives under a key + // scoped to the queued message, so per-project new-task drafts stay intact. + const selectedProjectDraftKey = editingPendingTask + ? pendingTaskDraftKey(editingPendingTask.messageId) + : selectedProject + ? `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}` + : null; const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey); const prompt = selectedProjectDraft.text; const attachments = selectedProjectDraft.attachments; const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local"; const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null; const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null; + const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false; const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE; const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE; @@ -350,7 +467,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { const branchTarget = useMemo( () => ({ environmentId: selectedProject?.environmentId ?? null, - cwd: selectedProject?.workspaceRoot ?? null, + // `|| null` also skips the stand-in project's empty workspaceRoot. + cwd: selectedProject?.workspaceRoot || null, query: null, }), [selectedProject?.environmentId, selectedProject?.workspaceRoot], @@ -384,10 +502,36 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { setSelectedProjectKey(nextProjectKey); }, []); - const selectEnvironment = useCallback((environmentId: EnvironmentId) => { - setSelectedEnvironmentId(environmentId); - setSelectedProjectKey(null); - }, []); + const selectEnvironment = useCallback( + (environmentId: EnvironmentId) => { + const projectsOnTarget = projects.filter( + (project) => project.environmentId === environmentId, + ); + const repositoryKey = selectedProject?.repositoryIdentity?.canonicalKey ?? null; + // Prefer the repository identity; projects without one (e.g. not yet + // indexed) fall back to workspace basename, then title, so switching + // computers still follows the same repo instead of resetting to + // whatever project is first on the target machine. + const workspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null; + const match = + (repositoryKey !== null + ? projectsOnTarget.find( + (project) => (project.repositoryIdentity?.canonicalKey ?? null) === repositoryKey, + ) + : undefined) ?? + (workspaceBasename !== null + ? projectsOnTarget.find( + (project) => project.workspaceRoot.split("/").at(-1) === workspaceBasename, + ) + : undefined) ?? + (selectedProject !== null + ? projectsOnTarget.find((project) => project.title === selectedProject.title) + : undefined); + setSelectedEnvironmentId(environmentId); + setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null); + }, + [projects, selectedProject], + ); const setWorkspaceMode = useCallback( (mode: WorkspaceMode) => { @@ -399,10 +543,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { mode, branch: selectedBranchName, worktreePath: selectedWorktreePath, + startFromOrigin, }, }); }, - [selectedBranchName, selectedProjectDraftKey, selectedWorktreePath], + [selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin], ); const selectBranch = useCallback( @@ -415,10 +560,28 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { mode: workspaceMode, branch: branch.name, worktreePath: normalizeSelectedWorktreePath(selectedProject, branch), + startFromOrigin, }, }); }, - [selectedProject, selectedProjectDraftKey, workspaceMode], + [selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode], + ); + + const setStartFromOrigin = useCallback( + (value: boolean) => { + if (!selectedProjectDraftKey) { + return; + } + updateComposerDraftSettings(selectedProjectDraftKey, { + workspaceSelection: { + mode: workspaceMode, + branch: selectedBranchName, + worktreePath: selectedWorktreePath, + startFromOrigin: value, + }, + }); + }, + [selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, workspaceMode], ); const refreshBranches = branchState.refresh; @@ -460,6 +623,183 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { [selectedProjectDraftKey], ); + const beginEditingPendingTask = useCallback((messageId: string): boolean => { + const message = findQueuedPendingTask(messageId); + if (!message?.creation) { + return false; + } + const draftKey = pendingTaskDraftKey(message.messageId); + // Only hydrate a fresh editing draft; reopening mid-edit keeps newer edits. + if (isComposerDraftEmpty(getComposerDraftSnapshot(draftKey))) { + setComposerDraftText(draftKey, message.text); + replaceComposerDraftAttachments(draftKey, message.attachments); + updateComposerDraftSettings(draftKey, { + modelSelection: message.modelSelection, + runtimeMode: message.runtimeMode, + interactionMode: message.interactionMode, + workspaceSelection: { + mode: message.creation.workspaceMode, + branch: message.creation.branch, + worktreePath: message.creation.worktreePath, + startFromOrigin: message.creation.startFromOrigin ?? false, + }, + }); + } + setSelectedEnvironmentId(message.environmentId); + setSelectedProjectKey(scopedProjectKey(message.environmentId, message.creation.projectId)); + activeEditingMessageId = message.messageId; + editingPendingTaskRef.current = message; + setEditingPendingTask(message); + // Hold the outbox drain off this task while it is open in the editor. + holdEditingQueuedMessage(message.messageId); + return true; + }, []); + + const buildPendingTaskMessage = useCallback( + (metadata: TurnCommandMetadata): QueuedThreadMessage | null => { + if (!selectedProject || !selectedProjectDraftKey) { + return null; + } + const draft = getComposerDraftSnapshot(selectedProjectDraftKey); + const text = draft.text.trim(); + const draftModelSelection = draft.modelSelection ?? selectedModel; + if (text.length === 0 || !draftModelSelection) { + return null; + } + const workspaceSelection = draft.workspaceSelection; + const mode = workspaceSelection?.mode ?? "local"; + // When the selection is the stand-in built from the queued snapshot, + // persist the original (possibly absent) snapshot values — the + // stand-in's placeholder title/workspaceRoot must never be written back + // as if they were real project metadata. + const usingPendingSnapshot = selectedProject === editingPendingProject; + const projectTitle = usingPendingSnapshot + ? editingPendingTask?.creation?.projectTitle + : selectedProject.title; + const projectCwd = usingPendingSnapshot + ? editingPendingTask?.creation?.projectCwd + : selectedProject.workspaceRoot; + return { + environmentId: selectedProject.environmentId, + threadId: ThreadId.make(metadata.threadId), + messageId: MessageId.make(metadata.messageId), + commandId: CommandId.make(metadata.commandId), + text, + attachments: draft.attachments, + modelSelection: draftModelSelection, + runtimeMode: draft.runtimeMode ?? DEFAULT_RUNTIME_MODE, + interactionMode: draft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE, + creation: { + projectId: selectedProject.id, + ...(projectTitle !== undefined ? { projectTitle } : {}), + ...(projectCwd !== undefined ? { projectCwd } : {}), + workspaceMode: mode, + branch: workspaceSelection?.branch ?? null, + worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null), + ...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}), + }, + createdAt: metadata.createdAt, + }; + }, + [ + editingPendingProject, + editingPendingTask, + selectedModel, + selectedProject, + selectedProjectDraftKey, + ], + ); + + const finishEditingPendingTask = useCallback(() => { + const editing = editingPendingTaskRef.current; + editingPendingTaskRef.current = null; + if (editing) { + if (activeEditingMessageId === editing.messageId) { + activeEditingMessageId = null; + } + clearComposerDraft(pendingTaskDraftKey(editing.messageId)); + releaseEditingQueuedMessage(editing.messageId); + } + setEditingPendingTask(null); + }, []); + + // If the queued task disappears mid-edit (deleted from the list, or + // delivered), end the editing session immediately without saving — a later + // flush must not resurrect it, and the composer should fall back to the + // regular per-project draft. + const queuedMessagesByThreadKey = useThreadOutboxMessages(); + useEffect(() => { + const editing = editingPendingTaskRef.current; + if (!editing) { + return; + } + const stillQueued = flattenQueuedThreadMessages(queuedMessagesByThreadKey).some( + (candidate) => candidate.messageId === editing.messageId, + ); + if (!stillQueued) { + finishEditingPendingTask(); + } + }, [finishEditingPendingTask, queuedMessagesByThreadKey]); + + // Leaving the flow mid-edit (sheet dismissed or draft screen popped) saves + // the current edits back into the queued task so nothing typed here is lost. + const editingFlushRef = useRef<(() => void) | null>(null); + useEffect(() => { + editingFlushRef.current = () => { + const editing = editingPendingTaskRef.current; + if (!editing) { + return; + } + editingPendingTaskRef.current = null; + setEditingPendingTask(null); + if (activeEditingMessageId === editing.messageId) { + activeEditingMessageId = null; + } + + const message = buildPendingTaskMessage({ + threadId: editing.threadId, + commandId: editing.commandId, + messageId: editing.messageId, + createdAt: editing.createdAt, + }); + + if (!message) { + // The edits are currently unsendable (e.g. the prompt was cleared). + // Keep both the draft and the drain lock: the stale queued payload + // must not auto-send content the user just removed, and reopening the + // task resumes from the saved draft. + return; + } + + // update() rewrites the task only if it is still queued — a concurrent + // delete or delivery wins, so the flush cannot resurrect it. + void updateThreadOutboxMessage(message) + .then(() => { + // If this task was reopened (possibly in a fresh provider) while + // the save was in flight, that session owns the draft and the lock. + if (activeEditingMessageId === editing.messageId) { + return; + } + clearComposerDraft(pendingTaskDraftKey(editing.messageId)); + releaseEditingQueuedMessage(editing.messageId); + }) + .catch((error) => { + // Keep the drain lock and the draft: delivering the stale payload + // would silently drop the newer edits. Reopening the task retries. + console.warn("[new-task] failed to save edited pending task", error); + }); + }; + }, [buildPendingTaskMessage]); + const cancelEditingPendingTask = useCallback(() => { + editingFlushRef.current?.(); + }, []); + useEffect( + () => () => { + editingFlushRef.current?.(); + }, + [], + ); + const value = useMemo( () => ({ logicalProjects, @@ -469,6 +809,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { workspaceMode, selectedBranchName, selectedWorktreePath, + startFromOrigin, + draftKey: selectedProjectDraftKey, + editingPendingTask, prompt, attachments, submitting, @@ -492,6 +835,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { setSelectedModelKey, setWorkspaceMode, selectBranch, + setStartFromOrigin, + beginEditingPendingTask, + finishEditingPendingTask, + cancelEditingPendingTask, + buildPendingTaskMessage, setPrompt, replaceAttachments, appendAttachments, @@ -508,11 +856,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { [ attachments, availableBranches, + beginEditingPendingTask, branchQuery, branchesLoading, + buildPendingTaskMessage, + cancelEditingPendingTask, + editingPendingTask, environments, expandedProvider, filteredBranches, + finishEditingPendingTask, interactionMode, loadBranches, logicalProjects, @@ -527,6 +880,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { selectedModel, selectedModelKey, selectedModelOption, + selectedProjectDraftKey, selectedProviderSkills, setSelectedModelOptions, selectedProject, @@ -539,7 +893,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { setPrompt, setRuntimeMode, setSelectedModelKey, + setStartFromOrigin, setWorkspaceMode, + startFromOrigin, submitting, workspaceMode, appendAttachments, diff --git a/apps/mobile/src/features/threads/sidebar-filter-button.tsx b/apps/mobile/src/features/threads/sidebar-filter-button.tsx new file mode 100644 index 0000000000..b1afe594f9 --- /dev/null +++ b/apps/mobile/src/features/threads/sidebar-filter-button.tsx @@ -0,0 +1,42 @@ +import { SymbolView } from "../../components/AppSymbol"; +import { Pressable, StyleSheet, useColorScheme } from "react-native"; + +import { useThemeColor } from "../../lib/useThemeColor"; + +export type SidebarFilterButtonIcon = + | "line.3.horizontal.decrease.circle" + | "line.3.horizontal.decrease.circle.fill"; + +export function SidebarFilterButton(props: { + readonly accessibilityLabel: string; + readonly icon: SidebarFilterButtonIcon; + /** Rendered inside a shared capsule group — no own background/border. */ + readonly grouped?: boolean; +}) { + const iconColor = useThemeColor("--color-foreground"); + const pressedBackgroundColor = useThemeColor("--color-subtle"); + const colorScheme = useColorScheme() === "dark" ? "dark" : "light"; + const idleBackgroundColor = + colorScheme === "dark" ? "rgba(118,118,128,0.24)" : "rgba(255,255,255,0.72)"; + const borderColor = colorScheme === "dark" ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.08)"; + + return ( + [ + props.grouped + ? { backgroundColor: pressed ? pressedBackgroundColor : "transparent", borderWidth: 0 } + : { + backgroundColor: pressed ? pressedBackgroundColor : idleBackgroundColor, + borderColor, + borderWidth: StyleSheet.hairlineWidth, + }, + ]} + > + + + ); +} diff --git a/apps/mobile/src/features/threads/sidebar-header-actions.android.tsx b/apps/mobile/src/features/threads/sidebar-header-actions.android.tsx new file mode 100644 index 0000000000..1321c82c0d --- /dev/null +++ b/apps/mobile/src/features/threads/sidebar-header-actions.android.tsx @@ -0,0 +1,16 @@ +import { View } from "react-native"; + +import { T3HeaderButton } from "../../native/T3HeaderButton.android"; +import type { SidebarHeaderActionsProps } from "./sidebar-header-actions"; + +export function SidebarHeaderActions(props: SidebarHeaderActionsProps) { + return ( + + + + ); +} diff --git a/apps/mobile/src/features/threads/sidebar-header-actions.tsx b/apps/mobile/src/features/threads/sidebar-header-actions.tsx new file mode 100644 index 0000000000..b8c8525b0a --- /dev/null +++ b/apps/mobile/src/features/threads/sidebar-header-actions.tsx @@ -0,0 +1,58 @@ +import { SymbolView } from "../../components/AppSymbol"; +import { Pressable, StyleSheet, View, useColorScheme } from "react-native"; + +import { useThemeColor } from "../../lib/useThemeColor"; + +export interface SidebarHeaderActionsProps { + readonly onOpenSettings: () => void; + /** Rendered inside a shared capsule group — buttons drop their own chrome. */ + readonly grouped?: boolean; +} + +function FallbackHeaderButton(props: { + readonly accessibilityLabel: string; + readonly icon: "gearshape" | "square.and.pencil"; + readonly grouped?: boolean; + readonly onPress: () => void; +}) { + const iconColor = useThemeColor("--color-foreground"); + const pressedBackgroundColor = useThemeColor("--color-subtle"); + const colorScheme = useColorScheme() === "dark" ? "dark" : "light"; + const idleBackgroundColor = + colorScheme === "dark" ? "rgba(118,118,128,0.24)" : "rgba(255,255,255,0.72)"; + const borderColor = colorScheme === "dark" ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.08)"; + + return ( + [ + props.grouped + ? { backgroundColor: pressed ? pressedBackgroundColor : "transparent", borderWidth: 0 } + : { + backgroundColor: pressed ? pressedBackgroundColor : idleBackgroundColor, + borderColor, + borderWidth: StyleSheet.hairlineWidth, + }, + ]} + > + + + ); +} + +export function SidebarHeaderActions(props: SidebarHeaderActionsProps) { + return ( + + + + ); +} diff --git a/apps/mobile/src/features/threads/sidebar-native-header-items.ts b/apps/mobile/src/features/threads/sidebar-native-header-items.ts new file mode 100644 index 0000000000..b80fffda05 --- /dev/null +++ b/apps/mobile/src/features/threads/sidebar-native-header-items.ts @@ -0,0 +1,63 @@ +import type { + NativeStackHeaderItem, + NativeStackHeaderItemMenu, +} from "@react-navigation/native-stack"; + +import type { HomeListFilterMenu } from "../home/home-list-filter-menu"; +import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items"; + +type NativeHeaderMenuItems = NativeStackHeaderItemMenu["menu"]["items"]; +type NativeHeaderIcon = NonNullable["icon"]>; + +function sfSymbolIcon(name: string): NativeHeaderIcon { + return { type: "sfSymbol", name: name as never }; +} + +function toNativeHeaderMenuItems(items: HomeListFilterMenu["items"]): NativeHeaderMenuItems { + return items.map((item) => + item.type === "action" + ? { + type: "action" as const, + label: item.title, + description: item.subtitle, + onPress: item.onPress, + state: item.state === "on" ? ("on" as const) : undefined, + } + : { + type: "submenu" as const, + label: item.title, + items: toNativeHeaderMenuItems(item.items), + }, + ); +} + +/** + * Right-side UINavigationBar items for the sidebar column: the thread list + * filter/sort menu plus the settings button, sharing one glass capsule — + * the Messages-style grouped header buttons. + */ +export function createSidebarHeaderItems(input: { + readonly filterIcon: string; + readonly filterMenu: HomeListFilterMenu; + readonly onOpenSettings: () => void; +}): NativeStackHeaderItem[] { + return [ + withNativeGlassHeaderItem({ + type: "menu", + label: "", + accessibilityLabel: "Filter and sort threads", + icon: sfSymbolIcon(input.filterIcon), + menu: { + title: input.filterMenu.title, + items: toNativeHeaderMenuItems(input.filterMenu.items), + }, + }), + withNativeGlassHeaderItem({ + type: "button", + label: "", + accessibilityLabel: "Open settings", + icon: sfSymbolIcon("gearshape"), + onPress: input.onOpenSettings, + }), + ]; +} diff --git a/apps/mobile/src/features/threads/sidebar-navigation-shell.tsx b/apps/mobile/src/features/threads/sidebar-navigation-shell.tsx new file mode 100644 index 0000000000..f0e3f89c07 --- /dev/null +++ b/apps/mobile/src/features/threads/sidebar-navigation-shell.tsx @@ -0,0 +1,73 @@ +import { + DarkTheme, + DefaultTheme, + NavigationContainer, + NavigationIndependentTree, +} from "@react-navigation/native"; +import { + createNativeStackNavigator, + type NativeStackNavigationOptions, +} from "@react-navigation/native-stack"; +import type { ReactNode } from "react"; +import { Platform, useColorScheme } from "react-native"; + +import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; +import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader"; + +const SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version); + +type SidebarScreenOptions = NativeStackNavigationOptions & { + // Same patched RNS option the GLASS/SOLID presets in Stack.tsx use — the + // iOS 26 "editor" navigation-item style leading-aligns the inline title. + readonly unstable_navigationItemStyle?: "editor"; +}; + +/** + * Static chrome for the sidebar column: a real UINavigationBar with a fixed + * inline title (no large title — saves vertical space, left-aligned via the + * editor item style) and the search bar pinned below it, scroll-edge blur + * sampling the list. Only genuinely dynamic values (search callbacks, header + * items) are set by the screen content via NativeStackScreenOptions. + */ +const SIDEBAR_SCREEN_OPTIONS: SidebarScreenOptions = { + contentStyle: { backgroundColor: "transparent" }, + headerLargeTitle: false, + headerShadowVisible: false, + headerShown: true, + headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? { backgroundColor: "transparent" } : undefined, + headerTitleStyle: { fontSize: 18, fontWeight: "800" }, + headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED, + scrollEdgeEffects: NATIVE_LIQUID_GLASS_SUPPORTED ? SCROLL_EDGE_EFFECTS : undefined, + title: "Threads", + unstable_navigationItemStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? "editor" : undefined, +}; + +const SidebarStack = createNativeStackNavigator(); + +/** + * Hosts the iPad sidebar pane inside its own single-screen native stack. + * + * The stack is navigation-inert — nothing is ever pushed onto it. It exists so + * the sidebar column owns a real UINavigationBar (large title, native bar + * button items, UISearchController), mirroring how each column of a + * UISplitViewController has its own UINavigationController. All real + * navigation still flows through the root stack via callbacks minted in + * AdaptiveWorkspaceLayout; NavigationIndependentTree only isolates the + * navigation hooks used for header configuration inside the pane. + */ +export function SidebarNavigationShell(props: { readonly children: ReactNode }) { + const colorScheme = useColorScheme(); + + return ( + + + + {() => props.children} + + + + ); +} diff --git a/apps/mobile/src/features/threads/thread-inspector-content-stack.tsx b/apps/mobile/src/features/threads/thread-inspector-content-stack.tsx new file mode 100644 index 0000000000..9b41ed4e36 --- /dev/null +++ b/apps/mobile/src/features/threads/thread-inspector-content-stack.tsx @@ -0,0 +1,101 @@ +import { useEffect, useState, type ComponentType, type ReactNode } from "react"; +import { View } from "react-native"; + +export type ThreadInspectorMode = "route" | "git" | "files"; + +const INSPECTOR_PREWARM_DELAY_MS = 350; + +function InspectorContentPane(props: { + readonly children: ReactNode; + readonly mounted: boolean; + readonly visible: boolean; +}) { + if (!props.mounted) { + return null; + } + + return ( + + {props.children} + + ); +} + +export function ThreadInspectorContentStack(props: { + readonly Files: ComponentType; + readonly Git: ComponentType; + readonly mode: ThreadInspectorMode; + readonly Route?: ComponentType; +}) { + const [mountedModes, setMountedModes] = useState>( + () => new Set([props.mode]), + ); + + useEffect(() => { + setMountedModes((current) => { + if (current.has(props.mode)) { + return current; + } + return new Set([...current, props.mode]); + }); + + if (props.mode === "route") { + return; + } + + // The file tree is expensive to detach because UIKit rebuilds its focus + // graph. Keep both chat inspectors alive after the opening animation so a + // later Files/Git switch only changes visibility. + const alternateMode = props.mode === "files" ? "git" : "files"; + const timeout = setTimeout(() => { + setMountedModes((current) => { + if (current.has(alternateMode)) { + return current; + } + return new Set([...current, alternateMode]); + }); + }, INSPECTOR_PREWARM_DELAY_MS); + + return () => clearTimeout(timeout); + }, [props.mode]); + + const Files = props.Files; + const Git = props.Git; + const Route = props.Route; + + return ( + + + + + + + + {Route ? ( + + + + ) : null} + + ); +} diff --git a/apps/mobile/src/features/threads/thread-list-items.tsx b/apps/mobile/src/features/threads/thread-list-items.tsx new file mode 100644 index 0000000000..c2eccc725a --- /dev/null +++ b/apps/mobile/src/features/threads/thread-list-items.tsx @@ -0,0 +1,666 @@ +import { useRecyclingState } from "@legendapp/list/react-native"; +import type { + EnvironmentProject, + EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; +import type { MenuAction } from "@react-native-menu/menu"; +import { SymbolView } from "../../components/AppSymbol"; +import { memo, useCallback, useMemo, type ComponentProps } from "react"; +import { Pressable, useColorScheme, useWindowDimensions, View } from "react-native"; +import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable"; +import Svg, { Circle, Path } from "react-native-svg"; + +import { AppText as Text } from "../../components/AppText"; +import { ControlPillMenu } from "../../components/ControlPill"; +import { ProjectFavicon } from "../../components/ProjectFavicon"; +import { cn } from "../../lib/cn"; +import { relativeTime } from "../../lib/time"; +import { useThemeColor } from "../../lib/useThemeColor"; +import type { PendingNewTask } from "../../state/use-pending-new-tasks"; +import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr"; +import type { HomeGroupDisplayAction } from "../home/homeListItems"; +import { ThreadSwipeable } from "../home/thread-swipe-actions"; +import { resolveThreadStatus } from "./threadPresentation"; + +/** + * Shared presentation for the thread lists: the compact (phone) Home list and + * the iPad sidebar render the SAME items — group headers with collapse, + * thread rows with status/PR/subtitle, and show-more rows — differing only in + * metrics and chrome via `variant`. + */ +export type ThreadListVariant = "compact" | "sidebar"; + +/** Left inset that aligns compact secondary rows with the title column. */ +export const THREAD_LIST_COMPACT_INSET = 20; +const SIDEBAR_ROW_RADIUS = 12; + +function pullRequestTintColor( + state: ThreadPr["state"], + colorScheme: ReturnType, +) { + const dark = colorScheme === "dark"; + switch (state) { + case "open": + return dark ? "#34d399" : "#059669"; + case "merged": + return dark ? "#a78bfa" : "#7c3aed"; + case "closed": + return dark ? "#a1a1aa" : "#71717a"; + } +} + +function PullRequestIcon(props: { readonly size: number; readonly color: string }) { + return ( + + + + + + + ); +} + +/* ─── Project group header ───────────────────────────────────────────── */ + +export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props: { + readonly variant: ThreadListVariant; + readonly project: EnvironmentProject; + readonly title: string; + readonly threadCount: number; + readonly collapsed: boolean; + readonly isFirst: boolean; + readonly groupKey: string; + readonly onGroupAction: (key: string, action: HomeGroupDisplayAction) => void; + /** Project a quick new thread should target; null hides the button. */ + readonly newThreadTarget?: EnvironmentProject | null; + readonly onNewThread?: (project: EnvironmentProject) => void; +}) { + const iconMutedColor = useThemeColor("--color-icon-muted"); + const { groupKey, onGroupAction, onNewThread } = props; + const newThreadTarget = props.newThreadTarget ?? null; + const compact = props.variant === "compact"; + const handleToggle = useCallback( + () => onGroupAction(groupKey, "toggle-collapsed"), + [groupKey, onGroupAction], + ); + const handleNewThread = useCallback(() => { + if (newThreadTarget) { + onNewThread?.(newThreadTarget); + } + }, [newThreadTarget, onNewThread]); + const showNewThreadButton = onNewThread !== undefined && newThreadTarget !== null; + + // The new-thread button is a SIBLING of the collapse toggle, not a child: + // nested touchables are unreachable to VoiceOver/TalkBack (the parent + // swallows focus). Row padding lives on the container (explicit styles — + // dynamic padding classes on Pressable did not apply reliably) so both + // children share one centerline; hitSlop restores the padded tap area. + const verticalHitSlop = { top: props.isFirst ? 8 : 24, bottom: 12 }; + return ( + + + + + {props.title} + + + {props.threadCount} + + + {showNewThreadButton ? ( + ({ opacity: pressed ? 0.5 : 1, paddingLeft: 12 })} + > + + + ) : null} + + ); +}); + +/* ─── Show more / show less row ──────────────────────────────────────── */ + +export const ThreadListShowMoreRow = memo(function ThreadListShowMoreRow(props: { + readonly variant: ThreadListVariant; + readonly hiddenCount: number; + readonly canShowLess: boolean; + readonly groupKey: string; + readonly onGroupAction: (key: string, action: HomeGroupDisplayAction) => void; +}) { + const iconSubtleColor = useThemeColor("--color-icon-subtle"); + const showsMore = props.hiddenCount > 0; + const compact = props.variant === "compact"; + const { groupKey, onGroupAction } = props; + const handleShowMore = useCallback( + () => onGroupAction(groupKey, "show-more"), + [groupKey, onGroupAction], + ); + const handleShowLess = useCallback( + () => onGroupAction(groupKey, "show-less"), + [groupKey, onGroupAction], + ); + + const button = (label: string, icon: "chevron.down" | "chevron.up", onPress: () => void) => ( + ({ + opacity: pressed ? 0.6 : 1, + paddingHorizontal: compact ? 14 : 12, + paddingVertical: compact ? 7 : 6, + borderCurve: "continuous", + })} + > + + + + {label} + + + + ); + + return ( + + {showsMore ? button("Show more", "chevron.down", handleShowMore) : null} + {props.canShowLess ? button("Show less", "chevron.up", handleShowLess) : null} + + ); +}); + +/* ─── Pending task row ───────────────────────────────────────────────── */ + +const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [ + { id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } }, +]; + +/** + * A queued new task waiting in the outbox for its environment to reconnect. + * Tapping reopens the new-task composer with everything prefilled; the row + * disappears once the task is delivered and the real thread arrives. + */ +export const PendingTaskListRow = memo(function PendingTaskListRow(props: { + readonly variant: ThreadListVariant; + readonly pendingTask: PendingNewTask; + readonly environmentLabel: string | null; + readonly isLast: boolean; + readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void; + readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void; +}) { + const compact = props.variant === "compact"; + const separatorColor = useThemeColor("--color-separator"); + const iconSubtleColor = useThemeColor("--color-icon-subtle"); + const mutedColor = useThemeColor("--color-foreground-muted"); + const pressedBackgroundColor = useThemeColor("--color-subtle"); + + const { pendingTask, onSelectPendingTask, onDeletePendingTask } = props; + const timestamp = relativeTime(pendingTask.message.createdAt); + const subtitleParts = [props.environmentLabel, pendingTask.creation.branch].filter( + (part): part is string => Boolean(part), + ); + + const handleMenuAction = useCallback( + ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => { + if (nativeEvent.event === "delete") onDeletePendingTask(pendingTask); + }, + [onDeletePendingTask, pendingTask], + ); + + const statusPill = ( + + Pending + + ); + + const subtitleRow = + subtitleParts.length > 0 ? ( + + + + {subtitleParts.join(" · ")} + + + ) : null; + + const rowContent = compact ? ( + onSelectPendingTask(pendingTask)} + style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })} + > + + + + + {pendingTask.title} + + + {statusPill} + {timestamp} + + + + {subtitleRow} + + + + ) : ( + onSelectPendingTask(pendingTask)} + style={({ pressed }) => ({ + backgroundColor: pressed ? pressedBackgroundColor : "transparent", + borderRadius: SIDEBAR_ROW_RADIUS, + cursor: "pointer", + minHeight: 64, + justifyContent: "center", + paddingHorizontal: 12, + paddingVertical: 10, + })} + > + + + + {pendingTask.title} + + + {statusPill} + + {timestamp} + + + + {subtitleRow} + + + ); + + return ( + + {rowContent} + + ); +}); + +/* ─── Thread row ─────────────────────────────────────────────────────── */ + +const THREAD_ROW_MENU_ACTIONS: MenuAction[] = [ + { id: "archive", title: "Archive", image: "archivebox" }, + { id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } }, +]; + +export const ThreadListRow = memo(function ThreadListRow(props: { + readonly variant: ThreadListVariant; + readonly thread: EnvironmentThreadShell; + readonly environmentLabel: string | null; + readonly projectCwd: string | null; + readonly isLast: boolean; + /** Sidebar only: the thread currently open in the detail pane. */ + readonly selected?: boolean; + /** Defaults to window width minus compact margins. */ + readonly fullSwipeWidth?: number; + readonly onSelectThread: (thread: EnvironmentThreadShell) => void; + readonly onArchiveThread: (thread: EnvironmentThreadShell) => void; + readonly onDeleteThread: (thread: EnvironmentThreadShell) => void; + readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void; + readonly onSwipeableClose: (methods: SwipeableMethods) => void; + readonly simultaneousSwipeGesture?: ComponentProps< + typeof ThreadSwipeable + >["simultaneousWithExternalGesture"]; +}) { + const { width: windowWidth } = useWindowDimensions(); + const colorScheme = useColorScheme(); + const compact = props.variant === "compact"; + const selected = props.selected === true; + // Recycling-safe: resets when the list container is reused for another + // thread, so a hover highlight can't leak across rows. + const [hovered, setHovered] = useRecyclingState(false); + + const separatorColor = useThemeColor("--color-separator"); + const iconSubtleColor = useThemeColor("--color-icon-subtle"); + const screenColor = useThemeColor("--color-screen"); + const drawerColor = useThemeColor("--color-drawer"); + const pressedBackgroundColor = useThemeColor("--color-subtle"); + const selectedBackgroundColor = useThemeColor("--color-user-bubble"); + + const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props; + const status = resolveThreadStatus(thread); + const pr = useThreadPr(thread, props.projectCwd); + const timestamp = relativeTime( + thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt, + ); + const threadAccessibilityLabel = pr ? `${thread.title}, ${pr.accessibilityLabel}` : thread.title; + const subtitleParts = [props.environmentLabel, thread.branch].filter((part): part is string => + Boolean(part), + ); + + const backgroundColor = compact ? screenColor : drawerColor; + const effectivePressedBackground = selected ? "rgba(255,255,255,0.16)" : pressedBackgroundColor; + const effectiveStatus = + selected && status + ? { ...status, pillClassName: "bg-white/20", textClassName: "text-white" } + : status; + + const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]); + const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]); + const primaryAction = useMemo( + () => ({ + accessibilityLabel: `Archive ${thread.title}`, + icon: "archivebox" as const, + label: "Archive", + onPress: handleArchive, + }), + [handleArchive, thread.title], + ); + const handleMenuAction = useCallback( + ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => { + if (nativeEvent.event === "archive") handleArchive(); + if (nativeEvent.event === "delete") handleDelete(); + }, + [handleArchive, handleDelete], + ); + + const statusPill = effectiveStatus ? ( + + + {effectiveStatus.label} + + + ) : null; + + const subtitleRow = + subtitleParts.length > 0 || pr !== null ? ( + + {subtitleParts.length > 0 ? ( + <> + + {subtitleParts.join(" · ")} + + + ) : null} + {pr !== null ? ( + + + + {pr.label} + + + ) : null} + + ) : null; + + const rowContent = (close: () => void) => + compact ? ( + { + close(); + onSelectThread(thread); + }} + style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })} + > + + + + + {thread.title} + + + {statusPill} + {timestamp} + + + + {subtitleRow} + + + + ) : ( + setHovered(true)} + onHoverOut={() => setHovered(false)} + onPress={() => { + close(); + onSelectThread(thread); + }} + style={({ pressed }) => ({ + backgroundColor: selected + ? selectedBackgroundColor + : pressed || hovered + ? effectivePressedBackground + : backgroundColor, + borderRadius: SIDEBAR_ROW_RADIUS, + cursor: "pointer", + minHeight: 64, + justifyContent: "center", + paddingHorizontal: 12, + paddingVertical: 10, + })} + > + + + + {thread.title} + + + {statusPill} + + {timestamp} + + + + {subtitleRow} + + + ); + + return ( + + {(close) => ( + // Messages-style row actions on long-press. iOS: a real + // UIContextMenuInteraction with the row as the zoom preview (needs the + // patched @react-native-menu, see + // patches/@react-native-menu__menu@2.0.0.patch — in long-press mode the + // interaction is hosted by the component view and the underlying + // UIButton passes touches through, so row taps keep working). Android: + // ControlPillMenu injects onLongPress into the row and anchors the + // token-styled dropdown to it; taps and swipes are untouched. + + {rowContent(close)} + + )} + + ); +}); diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index 1ce2c4cddc..66a3c049ea 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -1,13 +1,13 @@ import * as Haptics from "expo-haptics"; -import { SymbolView, type SFSymbol } from "expo-symbols"; +import { type AppSymbolName, SymbolView } from "../../components/AppSymbol"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { useRouter } from "expo-router"; +import { useNavigation } from "@react-navigation/native"; import { LayoutAnimation, Pressable, useColorScheme, View } from "react-native"; import { AppText as Text } from "../../components/AppText"; import { cn } from "../../lib/cn"; -import { buildThreadRoutePath } from "../../lib/routes"; import type { ThreadFeedActivity } from "../../lib/threadActivity"; +import Animated, { FadeIn } from "react-native-reanimated"; import { useV2ItemSupport } from "../../state/v2-item-support"; import { ThreadActivityInspector } from "./ThreadActivityInspector"; @@ -45,32 +45,32 @@ function compactActivityDetail(detail: string | null): string | null { return cleaned.length > 0 ? cleaned : null; } -function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol { +function workRowSymbolName(icon: ThreadFeedActivity["icon"]): AppSymbolName { switch (icon) { case "agent": - return "sparkles"; + return { ios: "sparkles", android: "auto_awesome" }; case "alert": - return "exclamationmark.triangle"; + return { ios: "exclamationmark.triangle", android: "error" }; case "check": - return "checkmark"; + return { ios: "checkmark", android: "check" }; case "command": - return "terminal"; + return { ios: "terminal", android: "terminal" }; case "edit": - return "square.and.pencil"; + return { ios: "square.and.pencil", android: "edit" }; case "eye": - return "eye"; + return { ios: "eye", android: "visibility" }; case "globe": - return "globe"; + return { ios: "globe", android: "public" }; case "hammer": - return "hammer"; + return { ios: "hammer", android: "construction" }; case "message": - return "bubble.left"; + return { ios: "bubble.left", android: "chat_bubble" }; case "warning": - return "xmark"; + return { ios: "xmark", android: "close" }; case "wrench": - return "wrench"; + return { ios: "wrench", android: "build" }; case "zap": - return "bolt"; + return { ios: "bolt", android: "bolt" }; } } @@ -85,7 +85,7 @@ function ThreadActivityThreadLink(props: { sourceThreadId: row.sourceThreadId, sourceItemId: row.sourceItemId, }); - const router = useRouter(); + const navigation = useNavigation(); const item = row.item; let targetThreadId: ThreadId | null = null; let label = "Open related thread"; @@ -112,12 +112,10 @@ function ThreadActivityThreadLink(props: { accessibilityLabel={label} onPress={() => { void Haptics.selectionAsync(); - router.push( - buildThreadRoutePath({ - environmentId: props.environmentId, - threadId: targetThreadId, - }), - ); + navigation.navigate("Thread", { + environmentId: props.environmentId, + threadId: targetThreadId, + }); }} className="mx-2 mb-2 min-h-9 flex-row items-center justify-center gap-1.5 rounded-lg border border-neutral-300/50 px-2 dark:border-white/[0.08]" > @@ -127,6 +125,14 @@ function ThreadActivityThreadLink(props: { ); } +// Entering fades only for rows created moments ago: rows remount whenever the +// list scrolls them back into view, and old rows must not replay an entrance. +const FRESH_ROW_WINDOW_MS = 3_000; +function isFreshRow(createdAt: string): boolean { + const timestamp = Date.parse(createdAt); + return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS; +} + export function ThreadWorkLog(props: { readonly activities: ReadonlyArray; readonly copiedRowId: string | null; @@ -170,8 +176,9 @@ export function ThreadWorkLog(props: { const iconIsDestructive = row.icon === "alert" || row.icon === "warning"; return ( - - + {canExpand ? ( ) : null} - + ); })} diff --git a/apps/mobile/src/features/threads/threadContentPresentation.ts b/apps/mobile/src/features/threads/threadContentPresentation.ts index c806e6dfc4..8b67815a64 100644 --- a/apps/mobile/src/features/threads/threadContentPresentation.ts +++ b/apps/mobile/src/features/threads/threadContentPresentation.ts @@ -32,7 +32,13 @@ export function projectThreadContentPresentation(input: { detail: input.detailError, }; } - if (input.connectionState === "connected") { + if ( + input.connectionState === "connected" || + input.connectionState === "connecting" || + input.connectionState === "reconnecting" + ) { + // Messages will arrive once the (re)connection completes — present as + // loading; the composer's connection pill reports the connection phase. return { kind: "loading" }; } return { diff --git a/apps/mobile/src/features/threads/threadPresentation.ts b/apps/mobile/src/features/threads/threadPresentation.ts index 0ef2bee691..531b9bd7fa 100644 --- a/apps/mobile/src/features/threads/threadPresentation.ts +++ b/apps/mobile/src/features/threads/threadPresentation.ts @@ -1,44 +1,129 @@ import type { StatusTone } from "../../components/StatusPill"; -import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { + threadRuntimeIsActive, + type EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; export function threadSortValue(thread: EnvironmentThreadShell): number { const candidate = Date.parse(thread.updatedAt ?? thread.createdAt); return Number.isNaN(candidate) ? 0 : candidate; } -export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone { - const status = thread.runtime?.status; - if (status === "running" || status === "waiting") { +export type ThreadStatusKind = + | "pending-approval" + | "awaiting-input" + | "working" + | "connecting" + | "error" + | "plan-ready"; + +export interface ThreadStatusPresentation extends StatusTone { + readonly kind: ThreadStatusKind; + /** Foreground color for the leading status icon. */ + readonly iconColor: string; + /** Background color for the leading status icon circle. */ + readonly iconBackground: string; + /** Whether the indicator represents in-flight activity. */ + readonly pulse: boolean; +} + +/** Neutral icon colors for threads with no actionable status. */ +export const THREAD_STATUS_NEUTRAL_ICON = { + iconColor: "#8e8e93", + iconBackground: "rgba(142,142,147,0.22)", +} as const; + +function isLatestRunSettled(thread: EnvironmentThreadShell): boolean { + if (!thread.latestRun?.startedAt) return false; + if (!thread.latestRun.completedAt) return false; + return !threadRuntimeIsActive(thread.runtime); +} + +/** + * Resolves the user-facing status of a thread, in priority order. Returns + * `null` for quiescent threads so rows stay free of "Idle"-style noise. + * Mirrors `resolveThreadStatusPill` in apps/web/src/components/Sidebar.logic.ts. + */ +export function resolveThreadStatus( + thread: EnvironmentThreadShell, +): ThreadStatusPresentation | null { + if (thread.hasPendingApprovals) { return { - label: "Running", - pillClassName: "bg-orange-500/12 dark:bg-orange-500/16", - textClassName: "text-orange-700 dark:text-orange-300", + kind: "pending-approval", + label: "Needs Approval", + pillClassName: "bg-amber-500/12 dark:bg-amber-500/16", + textClassName: "text-amber-700 dark:text-amber-300", + iconColor: "#ff9f0a", + iconBackground: "rgba(255,159,10,0.22)", + pulse: false, }; } - if (status === "completed") { + + if (thread.hasPendingUserInput) { return { - label: "Ready", - pillClassName: "bg-emerald-500/12 dark:bg-emerald-500/16", - textClassName: "text-emerald-700 dark:text-emerald-300", + kind: "awaiting-input", + label: "Awaiting Input", + pillClassName: "bg-indigo-500/12 dark:bg-indigo-500/16", + textClassName: "text-indigo-700 dark:text-indigo-300", + iconColor: "#5e5ce6", + iconBackground: "rgba(94,92,230,0.22)", + pulse: false, }; } - if (status === "preparing" || status === "queued" || status === "starting") { + + const runtimeStatus = thread.runtime?.status; + + if (runtimeStatus === "running" || runtimeStatus === "waiting") { return { - label: "Starting", + kind: "working", + label: "Working", pillClassName: "bg-sky-500/12 dark:bg-sky-500/16", textClassName: "text-sky-700 dark:text-sky-300", + iconColor: "#0a84ff", + iconBackground: "rgba(10,132,255,0.22)", + pulse: true, }; } - if (status === "failed") { + + if (runtimeStatus === "preparing" || runtimeStatus === "queued" || runtimeStatus === "starting") { return { + kind: "connecting", + label: "Connecting", + pillClassName: "bg-sky-500/12 dark:bg-sky-500/16", + textClassName: "text-sky-700 dark:text-sky-300", + iconColor: "#0a84ff", + iconBackground: "rgba(10,132,255,0.22)", + pulse: true, + }; + } + + if (runtimeStatus === "failed" || thread.latestRun?.status === "failed") { + return { + kind: "error", label: "Error", pillClassName: "bg-rose-500/12 dark:bg-rose-500/16", textClassName: "text-rose-700 dark:text-rose-300", + iconColor: "#ff453a", + iconBackground: "rgba(255,69,58,0.22)", + pulse: false, }; } - return { - label: "Idle", - pillClassName: "bg-neutral-500/10 dark:bg-neutral-500/16", - textClassName: "text-neutral-600 dark:text-neutral-300", - }; + + const hasPlanReadyPrompt = + thread.interactionMode === "plan" && + isLatestRunSettled(thread) && + thread.hasActionableProposedPlan; + if (hasPlanReadyPrompt) { + return { + kind: "plan-ready", + label: "Plan Ready", + pillClassName: "bg-violet-500/12 dark:bg-violet-500/16", + textClassName: "text-violet-700 dark:text-violet-300", + iconColor: "#bf5af2", + iconBackground: "rgba(191,90,242,0.22)", + pulse: false, + }; + } + + return null; } diff --git a/apps/mobile/src/features/threads/use-project-actions.ts b/apps/mobile/src/features/threads/use-project-actions.ts index 96008e4d6d..9d03dde59a 100644 --- a/apps/mobile/src/features/threads/use-project-actions.ts +++ b/apps/mobile/src/features/threads/use-project-actions.ts @@ -4,8 +4,6 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { mapAtomCommandResult } from "@t3tools/client-runtime/state/runtime"; import { - CommandId, - MessageId, ThreadId, type ModelSelection, type ProviderInteractionMode, @@ -17,22 +15,13 @@ import { AsyncResult } from "effect/unstable/reactivity"; import { threadEnvironment } from "../../state/threads"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; -import { makeTurnCommandMetadata } from "../../lib/commandMetadata"; -import { uuidv4 } from "../../lib/uuid"; +import { makeTurnCommandMetadata, type TurnCommandMetadata } from "../../lib/commandMetadata"; +import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn"; +import { randomHex } from "../../lib/uuid"; import { useAtomCommand } from "../../state/use-atom-command"; import { setPendingConnectionError } from "../../state/use-remote-environment-registry"; import { validateProjectThreadCreation } from "./projectThreadCreationValidation"; -function deriveThreadTitleFromPrompt(value: string): string { - const trimmed = value.trim(); - if (trimmed.length === 0) { - return "New thread"; - } - - const compact = trimmed.replace(/\s+/g, " "); - return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`; -} - export function useCreateProjectThread() { const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false }); @@ -43,15 +32,17 @@ export function useCreateProjectThread() { readonly envMode: "local" | "worktree"; readonly branch: string | null; readonly worktreePath: string | null; + readonly startFromOrigin?: boolean; readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode; readonly initialMessageText: string; readonly initialAttachments: ReadonlyArray; + /** Reuse identifiers from a queued pending task instead of minting new ones. */ + readonly turnMetadata?: TurnCommandMetadata; }) => { - const metadata = makeTurnCommandMetadata(); + const metadata = input.turnMetadata ?? makeTurnCommandMetadata(); const threadId = ThreadId.make(metadata.threadId); const initialMessageText = input.initialMessageText.trim(); - const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText); const validationError = validateProjectThreadCreation({ environmentId: input.project.environmentId, @@ -65,47 +56,26 @@ export function useCreateProjectThread() { return AsyncResult.failure(Cause.fail(validationError)); } - const isWorktree = input.envMode === "worktree"; const result = await startTurn({ environmentId: input.project.environmentId, - input: { - commandId: CommandId.make(metadata.commandId), - creationSource: "mobile", - threadId, - message: { - messageId: MessageId.make(metadata.messageId), - role: "user", - text: initialMessageText, - attachments: input.initialAttachments, - }, + input: buildProjectThreadStartTurnInput({ + projectId: input.project.id, + projectCwd: input.project.workspaceRoot, + threadId: metadata.threadId, + commandId: metadata.commandId, + messageId: metadata.messageId, + createdAt: metadata.createdAt, + text: initialMessageText, + attachments: input.initialAttachments, modelSelection: input.modelSelection, - titleSeed: nextTitle, runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, - bootstrap: { - createThread: { - projectId: input.project.id, - title: nextTitle, - modelSelection: input.modelSelection, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - branch: input.branch, - worktreePath: isWorktree ? null : input.worktreePath, - createdAt: metadata.createdAt, - }, - ...(isWorktree - ? { - prepareWorktree: { - projectCwd: input.project.workspaceRoot, - baseBranch: input.branch!, - branch: buildTemporaryWorktreeBranchName(uuidv4), - }, - runSetupScript: true, - } - : {}), - }, - createdAt: metadata.createdAt, - }, + workspaceMode: input.envMode, + branch: input.branch, + worktreePath: input.worktreePath, + startFromOrigin: input.startFromOrigin ?? false, + worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex), + }), }); if (AsyncResult.isFailure(result)) { const error = Cause.squash(result.cause); diff --git a/apps/mobile/src/lib/adaptive-navigation.test.ts b/apps/mobile/src/lib/adaptive-navigation.test.ts new file mode 100644 index 0000000000..324881eb4b --- /dev/null +++ b/apps/mobile/src/lib/adaptive-navigation.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + isBaseThreadRoute, + resolveFileSelectionNavigationAction, + resolveThreadSelectionNavigationAction, +} from "./adaptive-navigation"; + +describe("isBaseThreadRoute", () => { + it("recognizes only the thread detail route", () => { + expect(isBaseThreadRoute("/threads/environment/thread")).toBe(true); + expect(isBaseThreadRoute("/threads/environment/thread/")).toBe(true); + expect(isBaseThreadRoute("/threads/environment/thread/files")).toBe(false); + expect(isBaseThreadRoute("/threads/environment/thread/review")).toBe(false); + }); +}); + +describe("resolveThreadSelectionNavigationAction", () => { + it("updates params when a persistent sidebar selects a peer thread", () => { + expect( + resolveThreadSelectionNavigationAction({ + usesSplitView: true, + pathname: "/threads/environment/thread", + }), + ).toBe("set-params"); + }); + + it("replaces nested thread content when a persistent sidebar selects a peer", () => { + expect( + resolveThreadSelectionNavigationAction({ + usesSplitView: true, + pathname: "/threads/environment/thread/files/path", + }), + ).toBe("replace"); + }); + + it("pushes from Home so the back stack survives collapsing to compact", () => { + expect( + resolveThreadSelectionNavigationAction({ + usesSplitView: true, + pathname: "/", + }), + ).toBe("push"); + }); + + it("pushes compact list selections onto the native stack", () => { + expect( + resolveThreadSelectionNavigationAction({ + usesSplitView: false, + pathname: "/threads/environment/thread", + }), + ).toBe("push"); + }); +}); + +describe("resolveFileSelectionNavigationAction", () => { + it("replaces the wide file browser with the selected preview", () => { + expect(resolveFileSelectionNavigationAction({ hasPersistentFileInspector: true })).toBe( + "replace", + ); + }); + + it("pushes a preview above the compact file browser", () => { + expect(resolveFileSelectionNavigationAction({ hasPersistentFileInspector: false })).toBe( + "push", + ); + }); +}); diff --git a/apps/mobile/src/lib/adaptive-navigation.ts b/apps/mobile/src/lib/adaptive-navigation.ts new file mode 100644 index 0000000000..7eb6f658dc --- /dev/null +++ b/apps/mobile/src/lib/adaptive-navigation.ts @@ -0,0 +1,35 @@ +export type AdaptiveNavigationAction = "push" | "replace" | "set-params"; + +const BASE_THREAD_ROUTE_PATTERN = /^\/threads\/[^/]+\/[^/]+\/?$/; + +export function isBaseThreadRoute(pathname: string): boolean { + return BASE_THREAD_ROUTE_PATTERN.test(pathname); +} + +/** + * A persistent sidebar selects a peer destination in place. A compact list + * drills into a new destination so the native back stack remains available. + * From Home the selection pushes (never replaces) so Home stays beneath the + * thread — collapsing back to a compact width keeps a sane back stack. + */ +export function resolveThreadSelectionNavigationAction(input: { + readonly usesSplitView: boolean; + readonly pathname: string; +}): AdaptiveNavigationAction { + if (!input.usesSplitView || input.pathname === "/") { + return "push"; + } + + return isBaseThreadRoute(input.pathname) ? "set-params" : "replace"; +} + +/** + * On regular-width layouts, the file browser and preview occupy one workspace + * destination. Replacing the browser route keeps a single back step to chat. + * Compact layouts retain the browser as the previous stack screen. + */ +export function resolveFileSelectionNavigationAction(input: { + readonly hasPersistentFileInspector: boolean; +}): AdaptiveNavigationAction { + return input.hasPersistentFileInspector ? "replace" : "push"; +} diff --git a/apps/mobile/src/lib/appBlurTarget.ts b/apps/mobile/src/lib/appBlurTarget.ts new file mode 100644 index 0000000000..5c892adc68 --- /dev/null +++ b/apps/mobile/src/lib/appBlurTarget.ts @@ -0,0 +1,8 @@ +import { createRef } from "react"; +import type { View } from "react-native"; + +// Android BlurViews can't sample their real backdrop like iOS does — they +// need an explicit BlurTargetView to snapshot. App.tsx wraps the app content +// in one and binds this ref so overlays hosted in separate windows (the +// anchored dropdown's Modal) can still blur what's on screen behind them. +export const appBlurTargetRef = createRef(); diff --git a/apps/mobile/src/lib/appearancePreferences.test.ts b/apps/mobile/src/lib/appearancePreferences.test.ts new file mode 100644 index 0000000000..3458f0120f --- /dev/null +++ b/apps/mobile/src/lib/appearancePreferences.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + DEFAULT_BASE_FONT_SIZE, + deriveCodeFontSize, + deriveTerminalFontSize, + normalizeBaseFontSize, + normalizeCodeFontSize, + normalizeCodeWordBreak, + resolveAppearance, + resolveAppearancePreferences, + resolveMarkdownFontSizes, + resolveMobileCodeSurface, + resolveNativeMarkdownTypography, + resolveTextScaleVariables, + stepBaseFontSize, + stepCodeFontSize, + stepTerminalFontSize, +} from "./appearancePreferences"; + +describe("appearancePreferences", () => { + it("resolves defaults for empty stored preferences", () => { + expect(resolveAppearancePreferences({})).toEqual({ + baseFontSize: DEFAULT_BASE_FONT_SIZE, + terminalFontSize: null, + codeFontSize: null, + codeWordBreak: false, + }); + }); + + it("migrates the legacy markdownFontSize key to baseFontSize", () => { + expect(resolveAppearancePreferences({ markdownFontSize: 18 }).baseFontSize).toBe(18); + expect( + resolveAppearancePreferences({ baseFontSize: 16, markdownFontSize: 18 }).baseFontSize, + ).toBe(16); + }); + + it("keeps explicit overrides and treats missing values as automatic", () => { + const preferences = resolveAppearancePreferences({ terminalFontSize: 12, codeFontSize: 14 }); + expect(preferences.terminalFontSize).toBe(12); + expect(preferences.codeFontSize).toBe(14); + expect(resolveAppearancePreferences({ terminalFontSize: null }).terminalFontSize).toBe(null); + }); + + it("derives terminal and code sizes from the base size when not overridden", () => { + const appearance = resolveAppearance(resolveAppearancePreferences({ baseFontSize: 15 })); + expect(appearance.terminalFontSize).toBe(10); + expect(appearance.codeFontSize).toBe(11); + expect(appearance.isTerminalFontSizeCustom).toBe(false); + expect(appearance.isCodeFontSizeCustom).toBe(false); + + const scaled = resolveAppearance(resolveAppearancePreferences({ baseFontSize: 22 })); + expect(scaled.terminalFontSize).toBe(deriveTerminalFontSize(22)); + expect(scaled.codeFontSize).toBe(deriveCodeFontSize(22)); + expect(scaled.terminalFontSize).toBeGreaterThan(10); + expect(scaled.codeFontSize).toBeGreaterThan(11); + }); + + it("applies explicit overrides over derived values", () => { + const appearance = resolveAppearance( + resolveAppearancePreferences({ baseFontSize: 22, terminalFontSize: 8, codeFontSize: 9 }), + ); + expect(appearance.terminalFontSize).toBe(8); + expect(appearance.codeFontSize).toBe(9); + expect(appearance.isTerminalFontSizeCustom).toBe(true); + expect(appearance.isCodeFontSizeCustom).toBe(true); + }); + + it("clamps base and code font sizes", () => { + expect(normalizeBaseFontSize(4)).toBe(11); + expect(normalizeBaseFontSize(30)).toBe(22); + expect(normalizeCodeFontSize(4)).toBe(8); + expect(normalizeCodeFontSize(30)).toBe(18); + }); + + it("steps font sizes within bounds", () => { + expect(stepTerminalFontSize(6, -1)).toBe(6); + expect(stepBaseFontSize(11, -1)).toBe(11); + expect(stepCodeFontSize(8, -1)).toBe(8); + expect(stepBaseFontSize(15, 1)).toBe(16); + }); + + it("scales markdown typography from the base size", () => { + expect(resolveMarkdownFontSizes(15)).toMatchObject({ + m: 15, + h1: 20, + bodyLineHeight: 22, + codeBlockFontSize: 12, + codeBlockLineHeight: 18, + }); + }); + + it("scales code surface geometry from the code font size", () => { + expect(resolveMobileCodeSurface(11)).toMatchObject({ + fontSize: 11, + rowHeight: 20, + }); + }); + + it("defaults code word break to false", () => { + expect(normalizeCodeWordBreak(undefined)).toBe(false); + expect(normalizeCodeWordBreak(true)).toBe(true); + }); + + it("returns the authored text scale at the 16pt default", () => { + expect(DEFAULT_BASE_FONT_SIZE).toBe(16); + + const variables = resolveTextScaleVariables(DEFAULT_BASE_FONT_SIZE); + expect(variables["--text-base"]).toBe(16); + expect(variables["--text-base--line-height"]).toBe(23); + expect(variables["--text-sm"]).toBe(14); + expect(variables["--text-sm--line-height"]).toBe(19); + expect(variables["--text-lg"]).toBe(18); + expect(variables["--text-3xl"]).toBe(30); + }); + + it("scales every text variable proportionally with the base size", () => { + const smallerVariables = resolveTextScaleVariables(15); + expect(smallerVariables["--text-base"]).toBe(15); + expect(smallerVariables["--text-sm"]).toBe(13); + + const variables = resolveTextScaleVariables(20); + expect(variables["--text-base"]).toBe(20); + expect(variables["--text-base--line-height"]).toBe(29); + expect(variables["--text-sm"]).toBe(18); + expect(variables["--text-xs"]).toBe(16); + expect(variables["--text-lg"]).toBe(23); + + const smaller = resolveTextScaleVariables(11); + expect(smaller["--text-base"]).toBe(11); + expect(smaller["--text-3xs"]).toBeGreaterThanOrEqual(8); + expect(smaller["--text-3xs--line-height"]).toBeGreaterThanOrEqual(10); + }); + + it("derives native markdown typography from the base size", () => { + expect(resolveNativeMarkdownTypography(22)).toEqual({ + fontSize: 22, + lineHeight: 32, + headingFontSizes: [29, 26, 23, 21, 21, 21], + }); + }); +}); diff --git a/apps/mobile/src/lib/appearancePreferences.ts b/apps/mobile/src/lib/appearancePreferences.ts new file mode 100644 index 0000000000..7287eabba7 --- /dev/null +++ b/apps/mobile/src/lib/appearancePreferences.ts @@ -0,0 +1,245 @@ +import { MOBILE_CODE_SURFACE, MOBILE_TYPOGRAPHY } from "./typography"; +import { + DEFAULT_TERMINAL_FONT_SIZE, + MAX_TERMINAL_FONT_SIZE, + MIN_TERMINAL_FONT_SIZE, + TERMINAL_FONT_SIZE_STEP, + normalizeTerminalFontSize, +} from "../features/terminal/terminalPreferences"; + +export const DEFAULT_BASE_FONT_SIZE = MOBILE_TYPOGRAPHY.body.fontSize; +export const MIN_BASE_FONT_SIZE = 11; +export const MAX_BASE_FONT_SIZE = 22; +export const BASE_FONT_SIZE_STEP = 1; + +export const DEFAULT_CODE_FONT_SIZE = MOBILE_CODE_SURFACE.fontSize; +export const MIN_CODE_FONT_SIZE = 8; +export const MAX_CODE_FONT_SIZE = 18; +export const CODE_FONT_SIZE_STEP = 1; + +/** + * User-configurable appearance preferences as stored. `null` overrides mean + * "automatic": the value is derived from the base font size. + */ +export interface AppearancePreferences { + readonly baseFontSize: number; + readonly terminalFontSize: number | null; + readonly codeFontSize: number | null; + readonly codeWordBreak: boolean; +} + +/** Effective appearance values after applying base-size derivation. */ +export interface ResolvedAppearance { + readonly baseFontSize: number; + readonly terminalFontSize: number; + readonly codeFontSize: number; + readonly codeWordBreak: boolean; + readonly isTerminalFontSizeCustom: boolean; + readonly isCodeFontSizeCustom: boolean; +} + +export interface ResolvedMobileCodeSurface { + readonly fontSize: number; + readonly lineNumberFontSize: number; + readonly rowHeight: number; + readonly gutterWidth: number; + readonly codePadding: number; + readonly textVerticalInset: number; +} + +export interface ResolvedMarkdownFontSizes { + readonly s: number; + readonly m: number; + readonly h1: number; + readonly h2: number; + readonly h3: number; + readonly h4: number; + readonly h5: number; + readonly h6: number; + readonly bodyLineHeight: number; + readonly codeBlockFontSize: number; + readonly codeBlockLineHeight: number; +} + +export interface NativeMarkdownTypography { + readonly fontSize: number; + readonly lineHeight: number; + readonly headingFontSizes: readonly [number, number, number, number, number, number]; +} + +export function normalizeBaseFontSize(value: number | null | undefined): number { + if (typeof value !== "number" || !Number.isFinite(value)) { + return DEFAULT_BASE_FONT_SIZE; + } + + return Math.min(MAX_BASE_FONT_SIZE, Math.max(MIN_BASE_FONT_SIZE, Math.round(value))); +} + +export function normalizeCodeFontSize(value: number | null | undefined): number { + if (typeof value !== "number" || !Number.isFinite(value)) { + return DEFAULT_CODE_FONT_SIZE; + } + + return Math.min(MAX_CODE_FONT_SIZE, Math.max(MIN_CODE_FONT_SIZE, Math.round(value))); +} + +export function normalizeCodeWordBreak(value: boolean | null | undefined): boolean { + return value === true; +} + +/** Terminal size derived from base: 10.5pt at base 16, snapped to 0.5pt steps. */ +export function deriveTerminalFontSize(baseFontSize: number): number { + const scale = normalizeBaseFontSize(baseFontSize) / DEFAULT_BASE_FONT_SIZE; + return normalizeTerminalFontSize(Math.round(DEFAULT_TERMINAL_FONT_SIZE * scale * 2) / 2); +} + +/** Code/diff size derived from base: 12pt at base 16. */ +export function deriveCodeFontSize(baseFontSize: number): number { + const scale = normalizeBaseFontSize(baseFontSize) / DEFAULT_BASE_FONT_SIZE; + return normalizeCodeFontSize(Math.round(DEFAULT_CODE_FONT_SIZE * scale)); +} + +interface StoredAppearancePreferences { + readonly baseFontSize?: number | null | undefined; + /** Legacy key from before base font size existed; migrated to baseFontSize. */ + readonly markdownFontSize?: number | null | undefined; + readonly terminalFontSize?: number | null | undefined; + readonly codeFontSize?: number | null | undefined; + readonly codeWordBreak?: boolean | null | undefined; +} + +export function resolveAppearancePreferences( + stored: StoredAppearancePreferences | null | undefined, +): AppearancePreferences { + return { + baseFontSize: normalizeBaseFontSize(stored?.baseFontSize ?? stored?.markdownFontSize), + terminalFontSize: + typeof stored?.terminalFontSize === "number" && Number.isFinite(stored.terminalFontSize) + ? normalizeTerminalFontSize(stored.terminalFontSize) + : null, + codeFontSize: + typeof stored?.codeFontSize === "number" && Number.isFinite(stored.codeFontSize) + ? normalizeCodeFontSize(stored.codeFontSize) + : null, + codeWordBreak: normalizeCodeWordBreak(stored?.codeWordBreak), + }; +} + +export function resolveAppearance(preferences: AppearancePreferences): ResolvedAppearance { + return { + baseFontSize: preferences.baseFontSize, + terminalFontSize: + preferences.terminalFontSize ?? deriveTerminalFontSize(preferences.baseFontSize), + codeFontSize: preferences.codeFontSize ?? deriveCodeFontSize(preferences.baseFontSize), + codeWordBreak: preferences.codeWordBreak, + isTerminalFontSizeCustom: preferences.terminalFontSize !== null, + isCodeFontSizeCustom: preferences.codeFontSize !== null, + }; +} + +export function resolveMobileCodeSurface(codeFontSize: number): ResolvedMobileCodeSurface { + const fontSize = normalizeCodeFontSize(codeFontSize); + const scale = fontSize / DEFAULT_CODE_FONT_SIZE; + + return { + fontSize, + lineNumberFontSize: Math.max(8, Math.round(MOBILE_CODE_SURFACE.lineNumberFontSize * scale)), + rowHeight: Math.max(14, Math.round(MOBILE_CODE_SURFACE.rowHeight * scale)), + gutterWidth: MOBILE_CODE_SURFACE.gutterWidth, + codePadding: MOBILE_CODE_SURFACE.codePadding, + textVerticalInset: MOBILE_CODE_SURFACE.textVerticalInset, + }; +} + +export function resolveMarkdownFontSizes(baseFontSize: number): ResolvedMarkdownFontSizes { + const m = normalizeBaseFontSize(baseFontSize); + const scale = m / DEFAULT_BASE_FONT_SIZE; + const codeBlockFontSize = Math.max(10, Math.round(13 * scale)); + + return { + s: Math.max(10, Math.round(14 * scale)), + m, + h1: Math.max(16, Math.round(21 * scale)), + h2: Math.max(14, Math.round(19 * scale)), + h3: Math.max(13, Math.round(17 * scale)), + h4: Math.max(12, Math.round(15 * scale)), + h5: Math.max(12, Math.round(15 * scale)), + h6: Math.max(12, Math.round(15 * scale)), + bodyLineHeight: Math.max(18, Math.round(MOBILE_TYPOGRAPHY.body.lineHeight * scale)), + codeBlockFontSize, + codeBlockLineHeight: codeBlockFontSize + 6, + }; +} + +/** + * Maps the Uniwind `--text-*` theme variables (see global.css) to the + * MOBILE_TYPOGRAPHY roles they were authored from. Keep in sync with both. + */ +const TEXT_SCALE_VARIABLE_ROLES = { + "--text-3xs": MOBILE_TYPOGRAPHY.micro, + "--text-2xs": MOBILE_TYPOGRAPHY.caption, + "--text-xs": MOBILE_TYPOGRAPHY.label, + "--text-sm": MOBILE_TYPOGRAPHY.footnote, + "--text-base": MOBILE_TYPOGRAPHY.body, + "--text-lg": MOBILE_TYPOGRAPHY.headline, + "--text-xl": MOBILE_TYPOGRAPHY.title, + "--text-2xl": MOBILE_TYPOGRAPHY.largeTitle, + "--text-3xl": MOBILE_TYPOGRAPHY.display, +} as const; + +/** + * Scaled values for every `--text-*` size and line-height variable, ready to + * pass to `Uniwind.updateCSSVariables`. All className-based text (`text-sm`, + * `text-base`, ...) re-resolves live when these are injected. + */ +export function resolveTextScaleVariables(baseFontSize: number): Record { + const scale = normalizeBaseFontSize(baseFontSize) / DEFAULT_BASE_FONT_SIZE; + const variables: Record = {}; + + for (const [name, role] of Object.entries(TEXT_SCALE_VARIABLE_ROLES)) { + variables[name] = Math.max(8, Math.round(role.fontSize * scale)); + variables[`${name}--line-height`] = Math.max(10, Math.round(role.lineHeight * scale)); + } + + return variables; +} + +export function resolveNativeMarkdownTypography(baseFontSize: number): NativeMarkdownTypography { + const fontSizes = resolveMarkdownFontSizes(baseFontSize); + return { + fontSize: fontSizes.m, + lineHeight: fontSizes.bodyLineHeight, + headingFontSizes: [ + fontSizes.h1, + fontSizes.h2, + fontSizes.h3, + fontSizes.h4, + fontSizes.h5, + fontSizes.h6, + ], + }; +} + +export function stepBaseFontSize(current: number, direction: -1 | 1): number { + const next = direction === -1 ? current - BASE_FONT_SIZE_STEP : current + BASE_FONT_SIZE_STEP; + return normalizeBaseFontSize(next); +} + +export function stepTerminalFontSize(current: number, direction: -1 | 1): number { + const next = + direction === -1 ? current - TERMINAL_FONT_SIZE_STEP : current + TERMINAL_FONT_SIZE_STEP; + return normalizeTerminalFontSize(next); +} + +export function stepCodeFontSize(current: number, direction: -1 | 1): number { + const next = direction === -1 ? current - CODE_FONT_SIZE_STEP : current + CODE_FONT_SIZE_STEP; + return normalizeCodeFontSize(next); +} + +export { + DEFAULT_TERMINAL_FONT_SIZE, + MAX_TERMINAL_FONT_SIZE, + MIN_TERMINAL_FONT_SIZE, + TERMINAL_FONT_SIZE_STEP, + normalizeTerminalFontSize, +}; diff --git a/apps/mobile/src/lib/base64.ts b/apps/mobile/src/lib/base64.ts new file mode 100644 index 0000000000..640e2260be --- /dev/null +++ b/apps/mobile/src/lib/base64.ts @@ -0,0 +1,4 @@ +export function estimateBase64ByteSize(base64: string): number { + const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0; + return Math.floor((base64.length * 3) / 4) - padding; +} diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts index 40e00a271f..21f2edaf52 100644 --- a/apps/mobile/src/lib/composerImages.test.ts +++ b/apps/mobile/src/lib/composerImages.test.ts @@ -36,7 +36,37 @@ vi.mock("./uuid", () => ({ uuidv4: () => "attachment-id", })); -import { convertPastedImagesToAttachments, isOwnedPastedImageUri } from "./composerImages"; +import { + convertPastedImagesToAttachments, + isOwnedPastedImageUri, + toUploadChatImageAttachments, +} from "./composerImages"; + +describe("toUploadChatImageAttachments", () => { + it("strips client draft id and previewUri for the startTurn wire shape", () => { + expect( + toUploadChatImageAttachments([ + { + id: "client-draft-id", + type: "image", + name: "pasted-image.png", + mimeType: "image/png", + sizeBytes: 12, + dataUrl: "data:image/png;base64,AA==", + previewUri: "file:///tmp/preview.png", + }, + ]), + ).toEqual([ + { + type: "image", + name: "pasted-image.png", + mimeType: "image/png", + sizeBytes: 12, + dataUrl: "data:image/png;base64,AA==", + }, + ]); + }); +}); describe("native pasted image cleanup", () => { beforeEach(() => { diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index 13b53af724..5c79b5b5eb 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -3,6 +3,7 @@ import { PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, type UploadChatImageAttachment, } from "@t3tools/contracts"; +import { estimateBase64ByteSize } from "./base64"; import { uuidv4 } from "./uuid"; export interface DraftComposerImageAttachment extends UploadChatImageAttachment { @@ -10,13 +11,21 @@ export interface DraftComposerImageAttachment extends UploadChatImageAttachment readonly previewUri: string; } -const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste"; - -function estimateBase64ByteSize(base64: string): number { - const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0; - return Math.floor((base64.length * 3) / 4) - padding; +/** Wire shape for startTurn: pure uploads without client draft id / previewUri. */ +export function toUploadChatImageAttachments( + attachments: ReadonlyArray, +): ReadonlyArray { + return attachments.map((attachment) => ({ + type: attachment.type, + name: attachment.name, + mimeType: attachment.mimeType, + sizeBytes: attachment.sizeBytes, + dataUrl: attachment.dataUrl, + })); } +const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste"; + async function loadImagePicker() { try { return await import("expo-image-picker"); diff --git a/apps/mobile/src/lib/layout.test.ts b/apps/mobile/src/lib/layout.test.ts new file mode 100644 index 0000000000..6dea0beafb --- /dev/null +++ b/apps/mobile/src/lib/layout.test.ts @@ -0,0 +1,343 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + constrainAuxiliaryPaneWidth, + constrainPrimarySidebarWidth, + deriveCenteredContentHorizontalPadding, + deriveFileInspectorPaneLayout, + deriveLayout, + deriveStableFormSheetDetent, + deriveWorkspacePaneLayout, + SPLIT_LAYOUT_MIN_HEIGHT, + SPLIT_LAYOUT_MIN_WIDTH, +} from "./layout"; + +describe("resizable pane constraints", () => { + it("keeps a preferred sidebar width across large windows and clamps it in a narrow split view", () => { + expect(constrainPrimarySidebarWidth(430, 1_366)).toBe(430); + expect(constrainPrimarySidebarWidth(430, 744)).toBe(384); + expect(constrainPrimarySidebarWidth(100, 1_366)).toBe(280); + }); + + it("preserves a useful main pane while constraining a trailing pane", () => { + expect(constrainAuxiliaryPaneWidth({ preferredWidth: 440, availableWidth: 1_100 })).toBe(440); + expect(constrainAuxiliaryPaneWidth({ preferredWidth: 440, availableWidth: 900 })).toBe(340); + expect(constrainAuxiliaryPaneWidth({ preferredWidth: 100, availableWidth: 1_100 })).toBe(260); + }); +}); + +describe("deriveCenteredContentHorizontalPadding", () => { + it("keeps the minimum padding while the viewport fits the reading width", () => { + expect( + deriveCenteredContentHorizontalPadding({ + viewportWidth: 744, + maxContentWidth: 960, + minimumPadding: 20, + }), + ).toBe(20); + }); + + it("centers only the content inside a wider full-width scroll host", () => { + expect( + deriveCenteredContentHorizontalPadding({ + viewportWidth: 1_032, + maxContentWidth: 960, + minimumPadding: 20, + }), + ).toBe(56); + }); + + it("supports unconstrained compact content", () => { + expect( + deriveCenteredContentHorizontalPadding({ + viewportWidth: 430, + maxContentWidth: null, + minimumPadding: 16, + }), + ).toBe(16); + }); +}); + +describe("deriveLayout", () => { + it.each([ + { name: "small iPhone portrait", width: 375, height: 667 }, + { name: "large iPhone portrait", width: 430, height: 932 }, + { name: "small iPhone landscape", width: 667, height: 375 }, + { name: "large iPhone landscape", width: 932, height: 430 }, + { name: "short wide window", width: 1_024, height: 599 }, + { name: "narrow tall window", width: 719, height: 1_024 }, + ])("keeps a $name in the compact shell", ({ width, height }) => { + expect(deriveLayout({ width, height })).toEqual({ + variant: "compact", + usesSplitView: false, + listPaneWidth: null, + shellPadding: 0, + }); + }); + + it.each([ + { name: "small tablet portrait", width: 744, height: 1_133 }, + { name: "tablet landscape", width: 1_024, height: 768 }, + { name: "large resizable window", width: 1_366, height: 1_024 }, + { name: "foldable-sized window", width: 800, height: 700 }, + ])("uses the split shell for a $name", ({ width, height }) => { + expect(deriveLayout({ width, height })).toMatchObject({ + variant: "split", + usesSplitView: true, + }); + }); + + it("switches only after both space requirements are met", () => { + expect( + deriveLayout({ width: SPLIT_LAYOUT_MIN_WIDTH, height: SPLIT_LAYOUT_MIN_HEIGHT }).variant, + ).toBe("split"); + expect( + deriveLayout({ width: SPLIT_LAYOUT_MIN_WIDTH - 1, height: SPLIT_LAYOUT_MIN_HEIGHT }).variant, + ).toBe("compact"); + expect( + deriveLayout({ width: SPLIT_LAYOUT_MIN_WIDTH, height: SPLIT_LAYOUT_MIN_HEIGHT - 1 }).variant, + ).toBe("compact"); + }); + + it("keeps the sidebar within usable native-column bounds", () => { + expect(deriveLayout({ width: 720, height: 1_000 }).listPaneWidth).toBe(280); + expect(deriveLayout({ width: 1_024, height: 768 }).listPaneWidth).toBe(328); + expect(deriveLayout({ width: 1_600, height: 1_000 }).listPaneWidth).toBe(380); + }); +}); + +describe("deriveWorkspacePaneLayout", () => { + it("keeps the auxiliary pane out of a standard iPad detail column", () => { + const layout = deriveLayout({ width: 1_194, height: 834 }); + + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 1_194, + primarySidebarPreferredVisible: true, + auxiliaryPanePreferredVisible: true, + }), + ).toEqual({ + primarySidebarVisible: true, + primarySidebarSuppressedByAuxiliary: false, + contentPaneWidth: 814, + supportsAuxiliaryPane: false, + auxiliaryPaneVisible: false, + auxiliaryPaneWidth: null, + }); + }); + + it("offers an auxiliary pane when maximizing a standard iPad landscape window", () => { + const layout = deriveLayout({ width: 1_194, height: 834 }); + + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 1_194, + primarySidebarPreferredVisible: false, + auxiliaryPanePreferredVisible: true, + }), + ).toEqual({ + primarySidebarVisible: false, + primarySidebarSuppressedByAuxiliary: false, + contentPaneWidth: 1_194, + supportsAuxiliaryPane: true, + auxiliaryPaneVisible: true, + auxiliaryPaneWidth: 320, + }); + }); + + it("prioritizes a trailing file inspector over the thread sidebar at medium widths", () => { + const layout = deriveLayout({ width: 1_024, height: 1_366 }); + + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 1_024, + primarySidebarPreferredVisible: true, + auxiliaryPanePreferredVisible: true, + auxiliaryPaneRole: "inspector", + }), + ).toEqual({ + primarySidebarVisible: false, + primarySidebarSuppressedByAuxiliary: true, + contentPaneWidth: 1_024, + supportsAuxiliaryPane: true, + auxiliaryPaneVisible: true, + auxiliaryPaneWidth: 260, + }); + }); + + it("keeps threads, content, and the file inspector visible in a large landscape window", () => { + const layout = deriveLayout({ width: 1_366, height: 1_024 }); + + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 1_366, + primarySidebarPreferredVisible: true, + auxiliaryPanePreferredVisible: true, + auxiliaryPaneRole: "inspector", + }), + ).toEqual({ + primarySidebarVisible: true, + primarySidebarSuppressedByAuxiliary: false, + contentPaneWidth: 986, + supportsAuxiliaryPane: true, + auxiliaryPaneVisible: true, + auxiliaryPaneWidth: 276, + }); + }); + + it("keeps an explicitly hidden thread sidebar hidden when the file inspector is visible", () => { + const layout = deriveLayout({ width: 1_024, height: 1_366 }); + + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 1_024, + primarySidebarPreferredVisible: false, + auxiliaryPanePreferredVisible: true, + auxiliaryPaneRole: "inspector", + }), + ).toMatchObject({ + primarySidebarVisible: false, + primarySidebarSuppressedByAuxiliary: false, + auxiliaryPaneVisible: true, + }); + }); + + it("restores the thread sidebar when the file inspector is hidden", () => { + const layout = deriveLayout({ width: 1_024, height: 1_366 }); + + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 1_024, + primarySidebarPreferredVisible: true, + auxiliaryPanePreferredVisible: false, + auxiliaryPaneRole: "inspector", + }), + ).toMatchObject({ + primarySidebarVisible: true, + primarySidebarSuppressedByAuxiliary: false, + auxiliaryPaneVisible: false, + }); + }); + + it("keeps file navigation on the native stack below the inspector breakpoint", () => { + const layout = deriveLayout({ width: 744, height: 1_133 }); + + expect(deriveFileInspectorPaneLayout({ layout, viewportWidth: 744 })).toEqual({ + supported: false, + width: null, + }); + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 744, + primarySidebarPreferredVisible: true, + auxiliaryPanePreferredVisible: true, + auxiliaryPaneRole: "inspector", + }), + ).toMatchObject({ + primarySidebarVisible: true, + supportsAuxiliaryPane: false, + auxiliaryPaneVisible: false, + }); + }); + + it("supports three visible columns in a sufficiently large window", () => { + const layout = deriveLayout({ width: 1_366, height: 1_024 }); + + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 1_366, + primarySidebarPreferredVisible: true, + auxiliaryPanePreferredVisible: true, + }), + ).toMatchObject({ + primarySidebarVisible: true, + contentPaneWidth: 986, + supportsAuxiliaryPane: true, + auxiliaryPaneVisible: true, + auxiliaryPaneWidth: 276, + }); + }); + + it("uses a preferred inspector width when all three panes still fit", () => { + const layout = deriveLayout({ width: 1_366, height: 1_024 }); + + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 1_366, + primarySidebarPreferredVisible: true, + auxiliaryPanePreferredVisible: true, + auxiliaryPaneRole: "inspector", + auxiliaryPanePreferredWidth: 420, + }), + ).toMatchObject({ + primarySidebarVisible: true, + auxiliaryPaneVisible: true, + auxiliaryPaneWidth: 420, + }); + }); + + it("clamps a preferred supplementary width before squeezing the main pane", () => { + const layout = deriveLayout({ width: 1_366, height: 1_024 }); + + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 1_366, + primarySidebarPreferredVisible: true, + auxiliaryPanePreferredVisible: true, + auxiliaryPanePreferredWidth: 460, + }).auxiliaryPaneWidth, + ).toBe(426); + }); + + it("respects a hidden auxiliary-pane preference", () => { + const layout = deriveLayout({ width: 1_366, height: 1_024 }); + + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 1_366, + primarySidebarPreferredVisible: true, + auxiliaryPanePreferredVisible: false, + }).auxiliaryPaneVisible, + ).toBe(false); + }); + + it("never exposes workspace panes in compact layouts", () => { + const layout = deriveLayout({ width: 430, height: 932 }); + + expect( + deriveWorkspacePaneLayout({ + layout, + viewportWidth: 430, + primarySidebarPreferredVisible: true, + auxiliaryPanePreferredVisible: true, + }), + ).toMatchObject({ + primarySidebarVisible: false, + supportsAuxiliaryPane: false, + auxiliaryPaneVisible: false, + auxiliaryPaneWidth: null, + }); + }); +}); + +describe("deriveStableFormSheetDetent", () => { + it.each([ + { height: 1_194, expected: 0.62 }, + { height: 834, expected: 0.863 }, + { height: 600, expected: 0.893 }, + { height: 0, expected: 0.92 }, + ])("derives a stable sheet detent for height $height", ({ height, expected }) => { + expect(deriveStableFormSheetDetent(height)).toBe(expected); + }); +}); diff --git a/apps/mobile/src/lib/layout.ts b/apps/mobile/src/lib/layout.ts index 2ae4314fdb..eb0c45e060 100644 --- a/apps/mobile/src/lib/layout.ts +++ b/apps/mobile/src/lib/layout.ts @@ -2,6 +2,33 @@ function clamp(value: number, min: number, max: number): number { return Math.min(Math.max(value, min), max); } +/** + * Use available space, not device or orientation labels, to choose the shell. + * + * The height floor deliberately keeps every current iPhone in the compact shell + * when it rotates to landscape, while still allowing iPad and foldable-sized + * windows to adopt the persistent sidebar as they resize. + */ +export const SPLIT_LAYOUT_MIN_WIDTH = 720; +export const SPLIT_LAYOUT_MIN_HEIGHT = 600; + +export const SPLIT_SIDEBAR_MIN_WIDTH = 280; +export const SPLIT_SIDEBAR_MAX_WIDTH = 460; +const SPLIT_SIDEBAR_DEFAULT_MAX_WIDTH = 380; + +export const AUXILIARY_PANE_MIN_CONTENT_WIDTH = 960; +export const CHAT_CONTENT_MAX_WIDTH = 960; + +export const AUXILIARY_PANE_MIN_WIDTH = 260; +export const AUXILIARY_PANE_MAX_WIDTH = 480; +const AUXILIARY_PANE_DEFAULT_MAX_WIDTH = 320; +const FILE_INSPECTOR_MIN_VIEWPORT_WIDTH = 820; +const FILE_INSPECTOR_MIN_MAIN_WIDTH = 560; +const STABLE_FORM_SHEET_MAX_HEIGHT = 720; +const STABLE_FORM_SHEET_VERTICAL_MARGIN = 64; +const STABLE_FORM_SHEET_MIN_DETENT = 0.62; +const STABLE_FORM_SHEET_MAX_DETENT = 0.92; + export type LayoutVariant = "compact" | "split"; export interface Layout { @@ -11,10 +38,25 @@ export interface Layout { readonly shellPadding: number; } +export interface WorkspacePaneLayout { + readonly primarySidebarVisible: boolean; + readonly primarySidebarSuppressedByAuxiliary: boolean; + readonly contentPaneWidth: number; + readonly supportsAuxiliaryPane: boolean; + readonly auxiliaryPaneVisible: boolean; + readonly auxiliaryPaneWidth: number | null; +} + +export interface FileInspectorPaneLayout { + readonly supported: boolean; + readonly width: number | null; +} + +export type WorkspaceAuxiliaryPaneRole = "supplementary" | "inspector"; + export function deriveLayout(input: { readonly width: number; readonly height: number }): Layout { const { width, height } = input; - const shortestEdge = Math.min(width, height); - const wideEnoughForSplit = width >= 900 || (width >= 700 && shortestEdge >= 700); + const wideEnoughForSplit = width >= SPLIT_LAYOUT_MIN_WIDTH && height >= SPLIT_LAYOUT_MIN_HEIGHT; if (!wideEnoughForSplit) { return { @@ -28,7 +70,187 @@ export function deriveLayout(input: { readonly width: number; readonly height: n return { variant: "split", usesSplitView: true, - listPaneWidth: clamp(Math.round(width * 0.34), 320, 420), - shellPadding: width >= 1180 ? 20 : 14, + listPaneWidth: clamp( + Math.round(width * 0.32), + SPLIT_SIDEBAR_MIN_WIDTH, + SPLIT_SIDEBAR_DEFAULT_MAX_WIDTH, + ), + shellPadding: 0, }; } + +export function deriveWorkspacePaneLayout(input: { + readonly layout: Layout; + readonly viewportWidth: number; + readonly primarySidebarPreferredVisible: boolean; + readonly auxiliaryPanePreferredVisible: boolean; + readonly auxiliaryPaneRole?: WorkspaceAuxiliaryPaneRole; + readonly auxiliaryPanePreferredWidth?: number; +}): WorkspacePaneLayout { + const viewportWidth = Math.max(0, input.viewportWidth); + const auxiliaryPaneRole = input.auxiliaryPaneRole ?? "supplementary"; + const preferredPrimarySidebarVisible = + input.layout.usesSplitView && input.primarySidebarPreferredVisible; + const preferredPrimarySidebarWidth = preferredPrimarySidebarVisible + ? (input.layout.listPaneWidth ?? 0) + : 0; + + if (auxiliaryPaneRole === "inspector") { + const fileInspector = deriveFileInspectorPaneLayout({ + layout: input.layout, + viewportWidth, + preferredWidth: input.auxiliaryPanePreferredWidth, + reservedLeadingWidth: preferredPrimarySidebarWidth, + }); + const auxiliaryPaneVisible = fileInspector.supported && input.auxiliaryPanePreferredVisible; + const primarySidebarSuppressedByAuxiliary = + preferredPrimarySidebarVisible && + auxiliaryPaneVisible && + fileInspector.width !== null && + input.layout.listPaneWidth !== null && + viewportWidth - input.layout.listPaneWidth - fileInspector.width < + FILE_INSPECTOR_MIN_MAIN_WIDTH; + const primarySidebarVisible = + preferredPrimarySidebarVisible && !primarySidebarSuppressedByAuxiliary; + const primarySidebarWidth = primarySidebarVisible ? (input.layout.listPaneWidth ?? 0) : 0; + + return { + primarySidebarVisible, + primarySidebarSuppressedByAuxiliary, + contentPaneWidth: Math.max(0, viewportWidth - primarySidebarWidth), + supportsAuxiliaryPane: fileInspector.supported, + auxiliaryPaneVisible, + auxiliaryPaneWidth: fileInspector.width, + }; + } + + const contentPaneWidth = Math.max(0, viewportWidth - preferredPrimarySidebarWidth); + const supportsAuxiliaryPane = + input.layout.usesSplitView && contentPaneWidth >= AUXILIARY_PANE_MIN_CONTENT_WIDTH; + const auxiliaryPaneVisible = supportsAuxiliaryPane && input.auxiliaryPanePreferredVisible; + const defaultAuxiliaryPaneWidth = clamp( + Math.round(contentPaneWidth * 0.28), + AUXILIARY_PANE_MIN_WIDTH, + AUXILIARY_PANE_DEFAULT_MAX_WIDTH, + ); + + return { + primarySidebarVisible: preferredPrimarySidebarVisible, + primarySidebarSuppressedByAuxiliary: false, + contentPaneWidth, + supportsAuxiliaryPane, + auxiliaryPaneVisible, + auxiliaryPaneWidth: supportsAuxiliaryPane + ? constrainAuxiliaryPaneWidth({ + preferredWidth: input.auxiliaryPanePreferredWidth ?? defaultAuxiliaryPaneWidth, + availableWidth: contentPaneWidth, + }) + : null, + }; +} + +export function deriveFileInspectorPaneLayout(input: { + readonly layout: Layout; + readonly viewportWidth: number; + readonly preferredWidth?: number; + readonly reservedLeadingWidth?: number; +}): FileInspectorPaneLayout { + const viewportWidth = Math.max(0, input.viewportWidth); + const reservedLeadingWidth = Number.isFinite(input.reservedLeadingWidth) + ? Math.max(0, input.reservedLeadingWidth ?? 0) + : 0; + const availableContentWidth = Math.max(0, viewportWidth - reservedLeadingWidth); + const supported = + input.layout.usesSplitView && viewportWidth >= FILE_INSPECTOR_MIN_VIEWPORT_WIDTH; + + return { + supported, + width: supported + ? constrainAuxiliaryPaneWidth({ + preferredWidth: + input.preferredWidth ?? + clamp( + Math.round(availableContentWidth * 0.28), + AUXILIARY_PANE_MIN_WIDTH, + AUXILIARY_PANE_DEFAULT_MAX_WIDTH, + ), + availableWidth: availableContentWidth, + }) + : null, + }; +} + +/** Keep a user-selected sidebar width useful as a window is resized. */ +export function constrainPrimarySidebarWidth( + preferredWidth: number, + viewportWidth = Number.POSITIVE_INFINITY, +): number { + const safeWidth = Number.isFinite(preferredWidth) ? preferredWidth : SPLIT_SIDEBAR_MIN_WIDTH; + const viewportMax = Number.isFinite(viewportWidth) + ? Math.max(SPLIT_SIDEBAR_MIN_WIDTH, viewportWidth - 360) + : SPLIT_SIDEBAR_MAX_WIDTH; + return clamp( + Math.round(safeWidth), + SPLIT_SIDEBAR_MIN_WIDTH, + Math.min(SPLIT_SIDEBAR_MAX_WIDTH, viewportMax), + ); +} + +/** + * Keep an auxiliary pane within native-feeling bounds without squeezing its + * neighboring content below a usable reading/editor width. + */ +export function constrainAuxiliaryPaneWidth(input: { + readonly preferredWidth: number; + readonly availableWidth: number; +}): number { + const safePreferredWidth = Number.isFinite(input.preferredWidth) + ? input.preferredWidth + : AUXILIARY_PANE_MIN_WIDTH; + const availableWidth = Number.isFinite(input.availableWidth) + ? Math.max(0, input.availableWidth) + : 0; + const maxWidth = Math.max( + AUXILIARY_PANE_MIN_WIDTH, + Math.min(AUXILIARY_PANE_MAX_WIDTH, availableWidth - FILE_INSPECTOR_MIN_MAIN_WIDTH), + ); + return clamp(Math.round(safePreferredWidth), AUXILIARY_PANE_MIN_WIDTH, maxWidth); +} + +export function deriveCenteredContentHorizontalPadding(input: { + readonly viewportWidth: number; + readonly maxContentWidth: number | null; + readonly minimumPadding: number; +}): number { + const viewportWidth = Number.isFinite(input.viewportWidth) ? Math.max(0, input.viewportWidth) : 0; + const minimumPadding = Number.isFinite(input.minimumPadding) + ? Math.max(0, input.minimumPadding) + : 0; + + if ( + input.maxContentWidth === null || + !Number.isFinite(input.maxContentWidth) || + input.maxContentWidth <= 0 + ) { + return minimumPadding; + } + + return minimumPadding + Math.max(0, (viewportWidth - input.maxContentWidth) / 2); +} + +export function deriveStableFormSheetDetent(containerHeight: number): number { + if (!Number.isFinite(containerHeight) || containerHeight <= 0) { + return STABLE_FORM_SHEET_MAX_DETENT; + } + + const targetHeight = Math.min( + STABLE_FORM_SHEET_MAX_HEIGHT, + Math.max(0, containerHeight - STABLE_FORM_SHEET_VERTICAL_MARGIN), + ); + const detent = clamp( + targetHeight / containerHeight, + STABLE_FORM_SHEET_MIN_DETENT, + STABLE_FORM_SHEET_MAX_DETENT, + ); + return Math.round(detent * 1_000) / 1_000; +} diff --git a/apps/mobile/src/lib/native-glass-capability.test.ts b/apps/mobile/src/lib/native-glass-capability.test.ts new file mode 100644 index 0000000000..43f865c77c --- /dev/null +++ b/apps/mobile/src/lib/native-glass-capability.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { supportsNativeLiquidGlass } from "./native-glass-capability"; + +describe("supportsNativeLiquidGlass", () => { + it("uses native liquid glass when iOS reports the capability", () => { + expect(supportsNativeLiquidGlass("ios", true)).toBe(true); + }); + + it("keeps pre-glass iOS on the solid fallback", () => { + expect(supportsNativeLiquidGlass("ios", false)).toBe(false); + }); + + it("does not enable iOS liquid-glass layout behavior on other platforms", () => { + expect(supportsNativeLiquidGlass("android", true)).toBe(false); + expect(supportsNativeLiquidGlass("web", true)).toBe(false); + }); +}); diff --git a/apps/mobile/src/lib/native-glass-capability.ts b/apps/mobile/src/lib/native-glass-capability.ts new file mode 100644 index 0000000000..61c8547b50 --- /dev/null +++ b/apps/mobile/src/lib/native-glass-capability.ts @@ -0,0 +1,6 @@ +export function supportsNativeLiquidGlass( + platform: string, + nativeCapabilityAvailable: boolean, +): boolean { + return platform === "ios" && nativeCapabilityAvailable; +} diff --git a/apps/mobile/src/lib/projectThreadStartTurn.ts b/apps/mobile/src/lib/projectThreadStartTurn.ts new file mode 100644 index 0000000000..310f181859 --- /dev/null +++ b/apps/mobile/src/lib/projectThreadStartTurn.ts @@ -0,0 +1,90 @@ +import { + CommandId, + MessageId, + ThreadId, + type ModelSelection, + type ProjectId, + type ProviderInteractionMode, + type RuntimeMode, +} from "@t3tools/contracts"; + +import { toUploadChatImageAttachments, type DraftComposerImageAttachment } from "./composerImages"; + +export function deriveThreadTitleFromPrompt(value: string): string { + const trimmed = value.trim(); + if (trimmed.length === 0) { + return "New thread"; + } + + const compact = trimmed.replace(/\s+/g, " "); + return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`; +} + +export interface ProjectThreadStartTurnSpec { + readonly projectId: ProjectId; + readonly projectCwd: string; + readonly threadId: string; + readonly commandId: string; + readonly messageId: string; + readonly createdAt: string; + readonly text: string; + readonly attachments: ReadonlyArray; + readonly modelSelection: ModelSelection; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + readonly workspaceMode: "local" | "worktree"; + readonly branch: string | null; + readonly worktreePath: string | null; + readonly startFromOrigin: boolean; + /** Generated temp branch for worktree mode; unused for local mode. */ + readonly worktreeBranchName: string; +} + +/** + * Single source of the `thread.turn.start` bootstrap payload used to create a + * thread from a project draft — shared by the immediate send path and the + * offline outbox drain so both deliver identical commands. + */ +export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpec) { + const title = deriveThreadTitleFromPrompt(spec.text); + const isWorktree = spec.workspaceMode === "worktree"; + return { + commandId: CommandId.make(spec.commandId), + creationSource: "mobile" as const, + threadId: ThreadId.make(spec.threadId), + message: { + messageId: MessageId.make(spec.messageId), + role: "user" as const, + text: spec.text, + attachments: toUploadChatImageAttachments(spec.attachments), + }, + modelSelection: spec.modelSelection, + titleSeed: title, + runtimeMode: spec.runtimeMode, + interactionMode: spec.interactionMode, + bootstrap: { + createThread: { + projectId: spec.projectId, + title, + modelSelection: spec.modelSelection, + runtimeMode: spec.runtimeMode, + interactionMode: spec.interactionMode, + branch: spec.branch, + worktreePath: isWorktree ? null : spec.worktreePath, + createdAt: spec.createdAt, + }, + ...(isWorktree + ? { + prepareWorktree: { + projectCwd: spec.projectCwd, + baseBranch: spec.branch!, + branch: spec.worktreeBranchName, + ...(spec.startFromOrigin ? { startFromOrigin: true } : {}), + }, + runSetupScript: true, + } + : {}), + }, + createdAt: spec.createdAt, + }; +} diff --git a/apps/mobile/src/lib/routes.test.ts b/apps/mobile/src/lib/routes.test.ts deleted file mode 100644 index 773de9d84f..0000000000 --- a/apps/mobile/src/lib/routes.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; - -import { buildThreadFilesNavigation, buildThreadFilesRoutePath } from "./routes"; - -const thread = { - environmentId: EnvironmentId.make("environment-1"), - threadId: ThreadId.make("thread-1"), -}; - -describe("thread file routes", () => { - it("includes an optional source line in string routes", () => { - expect(buildThreadFilesRoutePath(thread, "src/main.ts", 42)).toBe( - "/threads/environment-1/thread-1/files/src/main.ts?line=42", - ); - }); - - it("encodes each file path segment without encoding separators", () => { - expect(buildThreadFilesRoutePath(thread, "docs/My File#1.md")).toBe( - "/threads/environment-1/thread-1/files/docs/My%20File%231.md", - ); - }); - - it("builds typed navigation params for a file and source line", () => { - expect(buildThreadFilesNavigation(thread, "src/main.ts", 42)).toEqual({ - pathname: "/threads/[environmentId]/[threadId]/files/[...path]", - params: { - environmentId: "environment-1", - threadId: "thread-1", - path: ["src", "main.ts"], - line: "42", - }, - }); - }); - - it("targets the files index when no file path is provided", () => { - expect(buildThreadFilesNavigation(thread)).toEqual({ - pathname: "/threads/[environmentId]/[threadId]/files", - params: { - environmentId: "environment-1", - threadId: "thread-1", - }, - }); - }); -}); diff --git a/apps/mobile/src/lib/routes.ts b/apps/mobile/src/lib/routes.ts deleted file mode 100644 index 3a33e2ee0f..0000000000 --- a/apps/mobile/src/lib/routes.ts +++ /dev/null @@ -1,134 +0,0 @@ -import type { Href, useRouter } from "expo-router"; -import { type EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; -import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; - -import type { SelectedThreadRef } from "../state/remote-runtime-types"; - -type Router = ReturnType; - -type ThreadRouteInput = - | Pick - | Pick; -type PlainThreadRouteInput = - | { - environmentId: EnvironmentId; - threadId: ThreadId; - } - | { - environmentId: EnvironmentId; - id: ThreadId; - }; - -export function buildThreadRoutePath(input: ThreadRouteInput | PlainThreadRouteInput): string { - const environmentId = input.environmentId; - const threadId = "threadId" in input ? input.threadId : input.id; - - return `/threads/${encodeURIComponent(environmentId)}/${encodeURIComponent(threadId)}`; -} - -export function buildThreadReviewRoutePath( - input: ThreadRouteInput | PlainThreadRouteInput, -): string { - return `${buildThreadRoutePath(input)}/review`; -} - -export function buildThreadFilesRoutePath( - input: ThreadRouteInput | PlainThreadRouteInput, - relativePath?: string | null, - line?: number | null, -): string { - const basePath = `${buildThreadRoutePath(input)}/files`; - if (!relativePath) { - return basePath; - } - - const pathSegments = relativePath.split("/").filter((segment) => segment.length > 0); - if (pathSegments.length === 0) { - return basePath; - } - - const encodedPath = pathSegments.map(encodeURIComponent).join("/"); - const lineParam = - Number.isFinite(line) && Number(line) > 0 ? `?line=${Math.floor(Number(line))}` : ""; - return `${basePath}/${encodedPath}${lineParam}`; -} - -export function buildThreadTerminalRoutePath( - input: ThreadRouteInput | PlainThreadRouteInput, - terminalId?: string | null, -): string { - const basePath = `${buildThreadRoutePath(input)}/terminal`; - if (!terminalId) { - return basePath; - } - - return `${basePath}?terminalId=${encodeURIComponent(terminalId)}`; -} - -/** - * Prefer this over {@link buildThreadTerminalRoutePath} with `router.push(string)` — Expo Router - * often does not merge query strings into `useLocalSearchParams`, which breaks terminal bootstrap - * (`requestedTerminalId` stays null while the UI assumes `default`). - */ -export function buildThreadTerminalNavigation( - input: ThreadRouteInput | PlainThreadRouteInput, - terminalId?: string | null, -): Href { - const environmentId = String(input.environmentId); - const threadId = String("threadId" in input ? input.threadId : input.id); - - const params: { environmentId: string; threadId: string; terminalId?: string } = { - environmentId, - threadId, - }; - - if (terminalId != null && terminalId !== "") { - params.terminalId = terminalId; - } - - return { - pathname: "/threads/[environmentId]/[threadId]/terminal", - params, - }; -} - -export function buildThreadFilesNavigation( - input: ThreadRouteInput | PlainThreadRouteInput, - relativePath?: string | null, - line?: number | null, -): Href { - const environmentId = String(input.environmentId); - const threadId = String("threadId" in input ? input.threadId : input.id); - const path = relativePath?.split("/").filter((segment) => segment.length > 0) ?? []; - - if (path.length === 0) { - return { - pathname: "/threads/[environmentId]/[threadId]/files", - params: { environmentId, threadId }, - }; - } - - const params: { - environmentId: string; - threadId: string; - path: string[]; - line?: string; - } = { environmentId, threadId, path }; - if (Number.isFinite(line) && Number(line) > 0) { - params.line = String(Math.floor(Number(line))); - } - - return { - pathname: "/threads/[environmentId]/[threadId]/files/[...path]", - params, - }; -} - -export function dismissRoute(router: Router) { - if (router.canGoBack()) { - router.back(); - return; - } - - router.replace("/"); -} diff --git a/apps/mobile/src/lib/runtime.ts b/apps/mobile/src/lib/runtime.ts index 51a4885562..98730edfbf 100644 --- a/apps/mobile/src/lib/runtime.ts +++ b/apps/mobile/src/lib/runtime.ts @@ -8,6 +8,7 @@ import { cryptoLayer } from "../features/cloud/dpop"; import { managedRelayClientLayer } from "../features/cloud/managedRelayLayer"; import { resolveCloudPublicConfig } from "../features/cloud/publicConfig"; import { tracingLayer } from "../features/observability/tracing"; +import * as Persistence from "../persistence/layer"; function configuredRelayUrl(): string { return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid"; @@ -20,6 +21,7 @@ type RuntimeLayerSource = | typeof Socket.layerWebSocketConstructorGlobal | typeof cryptoLayer | typeof httpClientLayer + | typeof Persistence.layer | typeof tracingLayer; const runtimeLayer = Layer.merge( @@ -29,6 +31,7 @@ const runtimeLayer = Layer.merge( Layer.provideMerge(cryptoLayer), Layer.provideMerge(httpClientLayer), Layer.provideMerge(tracingLayer.pipe(Layer.provide(httpClientLayer))), + Layer.provideMerge(Persistence.layer), ); export const runtime: ManagedRuntime.ManagedRuntime< diff --git a/apps/mobile/src/lib/serialized-async-queue.test.ts b/apps/mobile/src/lib/serialized-async-queue.test.ts new file mode 100644 index 0000000000..71dc9aa765 --- /dev/null +++ b/apps/mobile/src/lib/serialized-async-queue.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { SerializedAsyncQueue } from "./serialized-async-queue"; + +function deferred() { + let resolve!: () => void; + const promise = new Promise((next) => { + resolve = next; + }); + return { promise, resolve }; +} + +describe("SerializedAsyncQueue", () => { + it("does not let a newer operation overtake an in-flight operation", async () => { + const queue = new SerializedAsyncQueue(); + const firstGate = deferred(); + const events: string[] = []; + + const first = queue.run(async () => { + events.push("first:start"); + await firstGate.promise; + events.push("first:end"); + }); + const second = queue.run(async () => { + events.push("second"); + }); + + await Promise.resolve(); + expect(events).toEqual(["first:start"]); + firstGate.resolve(); + await Promise.all([first, second]); + expect(events).toEqual(["first:start", "first:end", "second"]); + }); + + it("continues after a rejected operation", async () => { + const queue = new SerializedAsyncQueue(); + const first = queue.run(async () => { + throw new Error("failed"); + }); + const second = queue.run(async () => "recovered"); + + await expect(first).rejects.toThrow("failed"); + await expect(second).resolves.toBe("recovered"); + }); +}); diff --git a/apps/mobile/src/lib/serialized-async-queue.ts b/apps/mobile/src/lib/serialized-async-queue.ts new file mode 100644 index 0000000000..e989eb7da6 --- /dev/null +++ b/apps/mobile/src/lib/serialized-async-queue.ts @@ -0,0 +1,16 @@ +/** + * Runs asynchronous operations in call order while keeping the queue usable + * after an individual operation rejects. + */ +export class SerializedAsyncQueue { + private tail: Promise = Promise.resolve(); + + run(operation: () => Promise): Promise { + const result = this.tail.then(operation, operation); + this.tail = result.then( + () => undefined, + () => undefined, + ); + return result; + } +} diff --git a/apps/mobile/src/lib/storage.test.ts b/apps/mobile/src/lib/storage.test.ts index 084f9430d0..a97252c7b7 100644 --- a/apps/mobile/src/lib/storage.test.ts +++ b/apps/mobile/src/lib/storage.test.ts @@ -3,34 +3,103 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; const mocks = vi.hoisted(() => { const values = new Map(); + let preferencesJson: string | null = null; + let preferencesUpdatedAt = 0; + let loadPreferencesFails = false; + let savePreferencesFails = false; return { - clear: () => values.clear(), + clear: () => { + values.clear(); + preferencesJson = null; + preferencesUpdatedAt = 0; + loadPreferencesFails = false; + savePreferencesFails = false; + }, + getStoredValue: (key: string) => values.get(key) ?? null, + getPreferencesJson: () => preferencesJson, + setPreferencesJson: (value: string, updatedAt: number) => { + preferencesJson = value; + preferencesUpdatedAt = updatedAt; + }, + setDatabaseFailures: (load: boolean, save: boolean) => { + loadPreferencesFails = load; + savePreferencesFails = save; + }, getItemAsync: vi.fn((key: string) => Promise.resolve(values.get(key) ?? null)), setItemAsync: vi.fn((key: string, value: string) => { values.set(key, value); return Promise.resolve(); }), + deleteItemAsync: vi.fn((key: string) => { + values.delete(key); + return Promise.resolve(); + }), + database: { + closeAsync: vi.fn(() => Promise.resolve()), + execAsync: vi.fn(() => Promise.resolve()), + withExclusiveTransactionAsync: vi.fn( + (run: (transaction: { execAsync: () => Promise }) => Promise) => + run({ execAsync: () => Promise.resolve() }), + ), + getFirstAsync: vi.fn((sql: string) => { + if (sql.includes("PRAGMA user_version")) { + return Promise.resolve({ user_version: 1 }); + } + if (loadPreferencesFails) { + return Promise.reject(new Error("database unavailable")); + } + return Promise.resolve( + preferencesJson === null + ? null + : { payload: preferencesJson, updatedAt: preferencesUpdatedAt }, + ); + }), + runAsync: vi.fn((_sql: string, payload?: unknown, updatedAt?: unknown) => { + if (savePreferencesFails) { + return Promise.reject(new Error("database unavailable")); + } + if (typeof payload === "string") { + preferencesJson = payload; + } + if (typeof updatedAt === "number") { + preferencesUpdatedAt = updatedAt; + } + return Promise.resolve(); + }), + }, }; }); vi.mock("expo-secure-store", () => ({ + deleteItemAsync: mocks.deleteItemAsync, getItemAsync: mocks.getItemAsync, setItemAsync: mocks.setItemAsync, })); +vi.mock("expo-sqlite", () => ({ + openDatabaseAsync: vi.fn(() => Promise.resolve(mocks.database)), +})); + +vi.mock("expo-crypto", () => ({ + getRandomBytes: vi.fn(() => new Uint8Array(16)), +})); + +vi.mock("expo-constants", () => ({ + default: { expoConfig: { extra: {} } }, +})); + vi.mock("react-native", () => ({ Platform: { OS: "ios", }, })); -vi.mock("./runtime", () => ({ - runtime: { - runPromise: vi.fn(), - }, -})); - -import { loadSavedConnections, saveConnection } from "./storage"; +import { + loadPreferences, + loadSavedConnections, + saveConnection, + savePreferencesPatch, +} from "../persistence/imperative"; import { toStableSavedRemoteConnection } from "./connection"; const managedConnection = { @@ -100,4 +169,75 @@ describe("mobile connection storage", () => { warn.mockRestore(); }); + + it("loads legacy preferences when SQLite is unavailable", async () => { + mocks.setDatabaseFailures(true, true); + await mocks.setItemAsync("t3code.preferences", JSON.stringify({ baseFontSize: 17 })); + + await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 17 }); + }); + + it("falls back to secure storage when SQLite cannot save preferences", async () => { + mocks.setDatabaseFailures(true, true); + await expect(savePreferencesPatch({ baseFontSize: 19 })).resolves.toEqual({ baseFontSize: 19 }); + const fallback = JSON.parse(mocks.getStoredValue("t3code.preferences.fallback") ?? "") as { + readonly payload: string; + readonly updatedAt: number; + }; + expect(JSON.parse(fallback.payload)).toEqual({ baseFontSize: 19 }); + expect(fallback.updatedAt).toEqual(expect.any(Number)); + }); + + it("reconciles fallback preferences after SQLite recovers", async () => { + mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 15 }), 10); + await mocks.setItemAsync( + "t3code.preferences.fallback", + JSON.stringify({ + payload: JSON.stringify({ baseFontSize: 19 }), + updatedAt: 20, + }), + ); + + await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 19 }); + expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 19 }); + expect(mocks.getStoredValue("t3code.preferences.fallback")).toBeNull(); + }); + + it("ignores a stale fallback when its previous deletion failed", async () => { + mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 21 }), 30); + await mocks.setItemAsync( + "t3code.preferences.fallback", + JSON.stringify({ + payload: JSON.stringify({ baseFontSize: 19 }), + updatedAt: 20, + }), + ); + + await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 21 }); + expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 21 }); + expect(mocks.getStoredValue("t3code.preferences.fallback")).toBeNull(); + }); + + it("ignores an invalid fallback even when it has a newer timestamp", async () => { + mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 21 }), 30); + await mocks.setItemAsync( + "t3code.preferences.fallback", + JSON.stringify({ payload: "{", updatedAt: 40 }), + ); + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 21 }); + expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 21 }); + expect(mocks.getStoredValue("t3code.preferences.fallback")).toBeNull(); + + warn.mockRestore(); + }); + + it("keeps SQLite authoritative when stale legacy preferences remain", async () => { + mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 21 }), 30); + await mocks.setItemAsync("t3code.preferences", JSON.stringify({ baseFontSize: 19 })); + + await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 21 }); + expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 21 }); + }); }); diff --git a/apps/mobile/src/lib/storage.ts b/apps/mobile/src/lib/storage.ts deleted file mode 100644 index 114648277b..0000000000 --- a/apps/mobile/src/lib/storage.ts +++ /dev/null @@ -1,201 +0,0 @@ -import * as Arr from "effect/Array"; -import { pipe } from "effect/Function"; -import * as Schema from "effect/Schema"; -import * as SecureStore from "expo-secure-store"; -import { EnvironmentId } from "@t3tools/contracts"; - -import { - isRelayManagedConnection, - type SavedRemoteConnection, - toStableSavedRemoteConnection, -} from "./connection"; - -const CONNECTIONS_KEY = "t3code.connections"; -const PREFERENCES_KEY = "t3code.preferences"; -const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id"; -const MobileStorageKey = Schema.Literals([ - CONNECTIONS_KEY, - PREFERENCES_KEY, - AGENT_AWARENESS_DEVICE_ID_KEY, -]); -type MobileStorageKeyValue = typeof MobileStorageKey.Type; - -export class MobileSecureStorageError extends Schema.TaggedErrorClass()( - "MobileSecureStorageError", - { - operation: Schema.Literals(["read", "write", "generate-device-id"]), - key: MobileStorageKey, - cause: Schema.Defect(), - }, -) { - override get message(): string { - return `Mobile secure storage operation ${this.operation} failed for key ${this.key}.`; - } -} - -export class MobileStorageDecodeError extends Schema.TaggedErrorClass()( - "MobileStorageDecodeError", - { - key: MobileStorageKey, - cause: Schema.Defect(), - }, -) { - override get message(): string { - return `Failed to decode mobile storage value for key ${this.key}.`; - } -} - -export class MobileStorageEncodeError extends Schema.TaggedErrorClass()( - "MobileStorageEncodeError", - { - key: MobileStorageKey, - cause: Schema.Defect(), - }, -) { - override get message(): string { - return `Failed to encode mobile storage value for key ${this.key}.`; - } -} - -export interface Preferences { - readonly liveActivitiesEnabled?: boolean; - readonly terminalFontSize?: number; -} - -async function readStorageItem(key: MobileStorageKeyValue): Promise { - try { - return await SecureStore.getItemAsync(key); - } catch (cause) { - throw new MobileSecureStorageError({ operation: "read", key, cause }); - } -} - -async function writeStorageItem(key: MobileStorageKeyValue, value: string): Promise { - try { - await SecureStore.setItemAsync(key, value); - } catch (cause) { - throw new MobileSecureStorageError({ operation: "write", key, cause }); - } -} - -async function readJsonStorageItem(key: MobileStorageKeyValue): Promise { - const raw = (await readStorageItem(key)) ?? ""; - if (!raw.trim()) { - return null; - } - - try { - return JSON.parse(raw) as T; - } catch (cause) { - console.warn( - "[mobile-storage] ignored invalid JSON", - new MobileStorageDecodeError({ key, cause }), - ); - return null; - } -} - -async function writeJsonStorageItem(key: MobileStorageKeyValue, value: unknown) { - let encoded: string; - try { - encoded = JSON.stringify(value); - } catch (cause) { - throw new MobileStorageEncodeError({ key, cause }); - } - await writeStorageItem(key, encoded); -} - -export async function loadSavedConnections(): Promise> { - const parsed = await readJsonStorageItem<{ - readonly connections?: ReadonlyArray; - }>(CONNECTIONS_KEY); - if (!parsed) { - return []; - } - - return pipe( - parsed.connections ?? [], - Arr.filter( - (c) => !!c.environmentId && (!!c.bearerToken?.trim() || isRelayManagedConnection(c)), - ), - ); -} - -export async function saveConnection(connection: SavedRemoteConnection): Promise { - const current = await loadSavedConnections(); - const stableConnection = toStableSavedRemoteConnection(connection); - const next = current.some((entry) => entry.environmentId === connection.environmentId) - ? pipe( - current, - Arr.map((entry) => - entry.environmentId === connection.environmentId ? stableConnection : entry, - ), - ) - : pipe(current, Arr.append(stableConnection)); - - await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next }); -} - -export async function clearSavedConnection(environmentId: EnvironmentId): Promise { - const current = await loadSavedConnections(); - const next = pipe( - current, - Arr.filter((entry) => entry.environmentId !== environmentId), - ); - await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next }); -} - -export async function loadPreferences(): Promise { - const parsed = await readJsonStorageItem(PREFERENCES_KEY); - if (!parsed || typeof parsed !== "object") { - return {}; - } - - const preferences: { - liveActivitiesEnabled?: boolean; - terminalFontSize?: number; - } = {}; - - if (typeof parsed.liveActivitiesEnabled === "boolean") { - preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled; - } - if (typeof parsed.terminalFontSize === "number") { - preferences.terminalFontSize = parsed.terminalFontSize; - } - - return preferences; -} - -export async function savePreferencesPatch(patch: Partial): Promise { - const current = await loadPreferences(); - const next: Preferences = { - ...current, - ...patch, - }; - await writeJsonStorageItem(PREFERENCES_KEY, next); - return next; -} - -export async function loadOrCreateAgentAwarenessDeviceId(): Promise { - const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY); - if (existing?.trim()) { - return existing; - } - - const deviceId = await import("./uuid") - .then(({ uuidv4 }) => uuidv4()) - .catch((cause) => { - throw new MobileSecureStorageError({ - operation: "generate-device-id", - key: AGENT_AWARENESS_DEVICE_ID_KEY, - cause, - }); - }); - await writeStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId); - return deviceId; -} - -export async function loadAgentAwarenessDeviceId(): Promise { - const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY); - return existing?.trim() ? existing : null; -} diff --git a/apps/mobile/src/lib/time.ts b/apps/mobile/src/lib/time.ts index 9cbdada68f..1fbbc6b3e7 100644 --- a/apps/mobile/src/lib/time.ts +++ b/apps/mobile/src/lib/time.ts @@ -1,12 +1,13 @@ export function relativeTime(input: string): string { const timestamp = Date.parse(input); if (Number.isNaN(timestamp)) { - return "now"; + return "<1m"; } + // Anything under a minute renders as "<1m" rather than a live seconds count. + // The seconds ticker changed width every second and reflowed the surrounding row. const deltaSeconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000)); - if (deltaSeconds < 10) return "now"; - if (deltaSeconds < 60) return `${deltaSeconds}s`; + if (deltaSeconds < 60) return "<1m"; const deltaMinutes = Math.floor(deltaSeconds / 60); if (deltaMinutes < 60) return `${deltaMinutes}m`; diff --git a/apps/mobile/src/lib/typography.test.ts b/apps/mobile/src/lib/typography.test.ts index 6a021dabcc..5b62e9bd31 100644 --- a/apps/mobile/src/lib/typography.test.ts +++ b/apps/mobile/src/lib/typography.test.ts @@ -3,21 +3,18 @@ import { describe, expect, it } from "vite-plus/test"; import { MOBILE_CODE_SURFACE, MOBILE_TYPOGRAPHY } from "./typography"; describe("mobile typography", () => { - it("uses the intentional compact mobile font scale", () => { + it("uses the intentional mobile font scale anchored at a 16pt body", () => { expect(Object.values(MOBILE_TYPOGRAPHY).map(({ fontSize }) => fontSize)).toEqual([ - 10, 11, 12, 13, 14, 15, 17, 20, 24, 28, + 11, 12, 13, 14, 16, 18, 21, 26, 30, ]); - }); - - it("uses a compact shared style for editable composer text", () => { - expect(MOBILE_TYPOGRAPHY.composer).toEqual({ fontSize: 14, lineHeight: 20 }); + expect(MOBILE_TYPOGRAPHY.body).toEqual({ fontSize: 16, lineHeight: 23 }); }); it("uses caption-sized code with a compact readable row height", () => { expect(MOBILE_CODE_SURFACE).toMatchObject({ fontSize: MOBILE_TYPOGRAPHY.caption.fontSize, lineNumberFontSize: MOBILE_TYPOGRAPHY.micro.fontSize, - rowHeight: 20, + rowHeight: 22, }); }); }); diff --git a/apps/mobile/src/lib/typography.ts b/apps/mobile/src/lib/typography.ts index 644fee3658..6572f38dde 100644 --- a/apps/mobile/src/lib/typography.ts +++ b/apps/mobile/src/lib/typography.ts @@ -1,19 +1,18 @@ export const MOBILE_TYPOGRAPHY = { - micro: { fontSize: 10, lineHeight: 13 }, - caption: { fontSize: 11, lineHeight: 15 }, - label: { fontSize: 12, lineHeight: 16 }, - footnote: { fontSize: 13, lineHeight: 18 }, - composer: { fontSize: 14, lineHeight: 20 }, - body: { fontSize: 15, lineHeight: 22 }, - headline: { fontSize: 17, lineHeight: 22 }, - title: { fontSize: 20, lineHeight: 26 }, - largeTitle: { fontSize: 24, lineHeight: 30 }, - display: { fontSize: 28, lineHeight: 34 }, + micro: { fontSize: 11, lineHeight: 14 }, + caption: { fontSize: 12, lineHeight: 16 }, + label: { fontSize: 13, lineHeight: 17 }, + footnote: { fontSize: 14, lineHeight: 19 }, + body: { fontSize: 16, lineHeight: 23 }, + headline: { fontSize: 18, lineHeight: 23 }, + title: { fontSize: 21, lineHeight: 28 }, + largeTitle: { fontSize: 26, lineHeight: 32 }, + display: { fontSize: 30, lineHeight: 36 }, } as const; /** Shared geometry for dense, horizontally scrolling code surfaces. */ export const MOBILE_CODE_SURFACE = { - rowHeight: 20, + rowHeight: 22, gutterWidth: 46, codePadding: 7, textVerticalInset: 2, diff --git a/apps/mobile/src/lib/useFontFamily.ts b/apps/mobile/src/lib/useFontFamily.ts new file mode 100644 index 0000000000..09805ae115 --- /dev/null +++ b/apps/mobile/src/lib/useFontFamily.ts @@ -0,0 +1,15 @@ +import { useCSSVariable } from "uniwind"; + +const FONT_FAMILY_VARIABLES = { + regular: "--font-sans", + medium: "--font-medium", + bold: "--font-bold", +} as const; + +/** + * Resolves a font family for APIs that require a style object or native prop. + * Prefer Uniwind font classes when the target component accepts `className`. + */ +export function useFontFamily(weight: keyof typeof FONT_FAMILY_VARIABLES): string { + return useCSSVariable(FONT_FAMILY_VARIABLES[weight]) as string; +} diff --git a/apps/mobile/src/lib/uuid.ts b/apps/mobile/src/lib/uuid.ts index ee757c4a06..02fd1344e5 100644 --- a/apps/mobile/src/lib/uuid.ts +++ b/apps/mobile/src/lib/uuid.ts @@ -1,3 +1,9 @@ import * as Crypto from "expo-crypto"; export const uuidv4 = () => Crypto.randomUUID(); + +/** Random lowercase hex string of `byteLength` bytes (2 chars per byte). */ +export const randomHex = (byteLength: number): string => + Array.from(Crypto.getRandomBytes(byteLength), (byte) => byte.toString(16).padStart(2, "0")).join( + "", + ); diff --git a/apps/mobile/src/native/StackHeader.tsx b/apps/mobile/src/native/StackHeader.tsx new file mode 100644 index 0000000000..8a8c355b76 --- /dev/null +++ b/apps/mobile/src/native/StackHeader.tsx @@ -0,0 +1,457 @@ +import { useNavigation, type ParamListBase } from "@react-navigation/native"; +import type { + NativeStackHeaderItem, + NativeStackHeaderItemMenu, + NativeStackNavigationOptions, + NativeStackNavigationProp, +} from "@react-navigation/native-stack"; +import { + Children, + isValidElement, + useEffect, + useLayoutEffect, + useMemo, + useRef, + type ReactElement, + type ReactNode, +} from "react"; +import type { ColorValue } from "react-native"; + +export { + nativeHeaderScrollEdgeEffects, + nativeTopScrollEdgeEffect, + type NativeHeaderScrollEdgeEffects, + type NativeTopScrollEdgeEffect, +} from "./scrollEdgeEffects"; + +export type AppNativeStackNavigationOptions = Omit< + NativeStackNavigationOptions, + "headerTintColor" | "unstable_headerLeftItems" | "unstable_headerRightItems" +> & { + readonly headerTintColor?: string | ColorValue; + readonly unstable_headerCenterItems?: unknown; + readonly unstable_headerLeftItems?: unknown; + readonly unstable_headerRightItems?: unknown; + readonly unstable_headerSubtitle?: unknown; + readonly unstable_headerToolbarItems?: unknown; + readonly unstable_navigationItemStyle?: unknown; +}; + +function useNativeStackNavigation(): NativeStackNavigationProp | null { + return useNavigation>(); +} + +function normalizeScreenOptions( + options: AppNativeStackNavigationOptions | undefined, +): NativeStackNavigationOptions | undefined { + if (!options) { + return options; + } + + const normalized = { ...options } as NativeStackNavigationOptions & { + unstable_navigationItemStyle?: unknown; + unstable_headerCenterItems?: unknown; + unstable_headerSubtitle?: unknown; + unstable_headerToolbarItems?: unknown; + }; + + if (normalized.headerTintColor !== undefined) { + normalized.headerTintColor = String(normalized.headerTintColor); + } + + return normalized as NativeStackNavigationOptions; +} + +function optionsSignature(value: unknown, seen = new WeakSet()): string { + if (value === null) return "null"; + switch (typeof value) { + case "boolean": + case "number": + case "string": + return JSON.stringify(value); + case "undefined": + return "undefined"; + case "function": + // Header factories are frequently recreated inline. Their source is + // stable across equivalent renders, while a reference comparison would + // make navigation.setOptions re-enter the navigator indefinitely. + return `function:${Function.prototype.toString.call(value)}`; + case "symbol": + return `symbol:${String(value)}`; + case "bigint": + return `bigint:${String(value)}`; + case "object": { + const object = value as object; + if (seen.has(object)) return "[circular]"; + seen.add(object); + if (Array.isArray(value)) { + return `[${value.map((entry) => optionsSignature(entry, seen)).join(",")}]`; + } + // React refs carry mutable native instances that must not make static + // screen options appear different after every render. + if ("current" in object) return "[ref]"; + return `{${Object.keys(value as Record) + .sort() + .map( + (key) => + `${JSON.stringify(key)}:${optionsSignature((value as Record)[key], seen)}`, + ) + .join(",")}}`; + } + } + return String(value); +} + +function stabilizeOptionFunctions( + value: unknown, + path: string, + latestFunctions: Map unknown>, + wrappers: Map unknown>, + seen = new WeakSet(), +): unknown { + if (typeof value === "function") { + latestFunctions.set(path, value as (...args: unknown[]) => unknown); + let wrapper = wrappers.get(path); + if (!wrapper) { + wrapper = (...args: unknown[]) => { + return latestFunctions.get(path)?.(...args); + }; + wrappers.set(path, wrapper); + } + return wrapper; + } + if (Array.isArray(value)) { + if (seen.has(value)) return value; + seen.add(value); + return value.map((entry, index) => + stabilizeOptionFunctions(entry, `${path}[${index}]`, latestFunctions, wrappers, seen), + ); + } + if (value !== null && typeof value === "object") { + if (seen.has(value) || "current" in value) return value; + seen.add(value); + return Object.fromEntries( + Object.entries(value as Record).map(([key, entry]) => [ + key, + stabilizeOptionFunctions(entry, `${path}.${key}`, latestFunctions, wrappers, seen), + ]), + ); + } + return value; +} + +export function NativeStackScreenOptions(props: { + readonly options?: AppNativeStackNavigationOptions; + readonly listeners?: Record void>; + readonly name?: string; +}) { + const navigation = useNativeStackNavigation(); + const lastAppliedOptionsSignatureRef = useRef(undefined); + const latestOptionFunctionsRef = useRef(new Map unknown>()); + const optionFunctionWrappersRef = useRef(new Map unknown>()); + const normalizedOptions = useMemo(() => normalizeScreenOptions(props.options), [props.options]); + const stableOptions = normalizedOptions + ? (stabilizeOptionFunctions( + normalizedOptions, + "options", + latestOptionFunctionsRef.current, + optionFunctionWrappersRef.current, + ) as NativeStackNavigationOptions) + : undefined; + + useLayoutEffect(() => { + if (!navigation || !stableOptions) { + return; + } + const signature = optionsSignature(stableOptions); + // Avoid re-entering navigation state when semantically equal options are + // reapplied every layout (common when callers pass unstable object literals). + if (lastAppliedOptionsSignatureRef.current === signature) { + return; + } + lastAppliedOptionsSignatureRef.current = signature; + navigation.setOptions(stableOptions); + }, [navigation, stableOptions]); + + useEffect(() => { + if (!navigation || !props.listeners) { + return; + } + const subscriptions = Object.entries(props.listeners).map(([eventName, listener]) => + navigation.addListener(eventName as never, listener as never), + ); + return () => { + for (const unsubscribe of subscriptions) { + unsubscribe(); + } + }; + }, [navigation, props.listeners]); + + return null; +} + +function labelFromChildren(children: ReactNode): string { + const parts: string[] = []; + Children.forEach(children, (child) => { + if (typeof child === "string" || typeof child === "number") { + parts.push(String(child)); + } else if (isValidElement<{ children?: ReactNode }>(child)) { + parts.push(labelFromChildren(child.props.children)); + } + }); + return parts.join(""); +} + +type NativeStackHeaderIcon = NonNullable< + Extract["icon"] +>; +type NativeStackOptionsWithToolbar = NativeStackNavigationOptions & { + unstable_headerToolbarItems?: () => NativeStackHeaderItem[]; +}; + +function iconFromProp(icon: unknown): NativeStackHeaderIcon | undefined { + if (typeof icon !== "string") { + return undefined; + } + return { type: "sfSymbol", name: icon as never }; +} + +type ToolbarElementProps = Record & { readonly children?: ReactNode }; + +function elementTypeName(element: ReactElement): string | undefined { + const type = element.type; + if (typeof type === "function") { + return (type as { displayName?: string; name?: string }).displayName ?? type.name; + } + return undefined; +} + +function convertMenuAction( + element: ReactElement, +): NativeStackHeaderItemMenu["menu"]["items"][number] | null { + const typeName = elementTypeName(element); + if (typeName === "NativeHeaderToolbarMenuAction") { + const label = labelFromChildren(element.props.children); + return { + type: "action", + label, + description: typeof element.props.subtitle === "string" ? element.props.subtitle : undefined, + disabled: Boolean(element.props.disabled), + icon: iconFromProp(element.props.icon), + onPress: + typeof element.props.onPress === "function" + ? (element.props.onPress as () => void) + : () => undefined, + state: element.props.isOn === true ? "on" : undefined, + destructive: Boolean(element.props.destructive), + discoverabilityLabel: + typeof element.props.discoverabilityLabel === "string" + ? element.props.discoverabilityLabel + : undefined, + }; + } + + if (typeName === "NativeHeaderToolbarMenu") { + return { + type: "submenu", + label: + typeof element.props.title === "string" + ? element.props.title + : labelFromChildren(element.props.children), + icon: iconFromProp(element.props.icon), + inline: Boolean(element.props.inline), + items: collectMenuItems(element.props.children), + }; + } + + return null; +} + +function collectMenuItems(children: ReactNode): NativeStackHeaderItemMenu["menu"]["items"] { + const items: NativeStackHeaderItemMenu["menu"]["items"] = []; + Children.forEach(children, (child) => { + if (!isValidElement(child)) { + return; + } + const item = convertMenuAction(child); + if (item) { + items.push(item); + return; + } + items.push(...collectMenuItems(child.props.children)); + }); + return items; +} + +function convertToolbarChild(child: ReactNode): NativeStackHeaderItem | null { + if (!isValidElement(child)) { + return null; + } + + const typeName = elementTypeName(child); + if (typeName === "NativeHeaderToolbarButton") { + return { + type: "button", + label: typeof child.props.label === "string" ? child.props.label : "", + accessibilityLabel: + typeof child.props.accessibilityLabel === "string" + ? child.props.accessibilityLabel + : undefined, + disabled: Boolean(child.props.disabled), + icon: iconFromProp(child.props.icon), + onPress: + typeof child.props.onPress === "function" + ? (child.props.onPress as () => void) + : () => undefined, + sharesBackground: !child.props.separateBackground, + tintColor: child.props.tintColor as ColorValue | undefined, + variant: "plain", + }; + } + + if (typeName === "NativeHeaderToolbarMenu") { + return { + type: "menu", + label: typeof child.props.title === "string" ? child.props.title : "", + accessibilityLabel: + typeof child.props.accessibilityLabel === "string" + ? child.props.accessibilityLabel + : undefined, + disabled: Boolean(child.props.disabled), + icon: iconFromProp(child.props.icon), + menu: { + title: typeof child.props.title === "string" ? child.props.title : undefined, + items: collectMenuItems(child.props.children), + }, + sharesBackground: !child.props.separateBackground, + tintColor: child.props.tintColor as ColorValue | undefined, + variant: "plain", + }; + } + + if (typeName === "NativeHeaderToolbarSpacer") { + return { + type: "spacing", + spacing: typeof child.props.width === "number" ? child.props.width : 8, + }; + } + + return null; +} + +function collectToolbarItems(children: ReactNode): NativeStackHeaderItem[] { + const items: NativeStackHeaderItem[] = []; + Children.forEach(children, (child) => { + const item = convertToolbarChild(child); + if (item) { + items.push(item); + } + }); + return items; +} + +function NativeHeaderToolbarRoot(props: { + readonly placement?: "left" | "right" | "bottom"; + readonly children?: ReactNode; +}) { + const navigation = useNativeStackNavigation(); + const items = useMemo(() => collectToolbarItems(props.children), [props.children]); + + useEffect(() => { + if (!navigation) { + return; + } + if (props.placement === "bottom") { + navigation.setOptions({ + unstable_headerToolbarItems: () => items, + } as NativeStackOptionsWithToolbar); + return () => { + navigation.setOptions({ + unstable_headerToolbarItems: () => [], + } as NativeStackOptionsWithToolbar); + }; + } + if (props.placement === "left") { + navigation.setOptions({ unstable_headerLeftItems: () => items }); + return () => { + navigation.setOptions({ unstable_headerLeftItems: () => [] }); + }; + } + navigation.setOptions({ unstable_headerRightItems: () => items }); + return () => { + navigation.setOptions({ unstable_headerRightItems: () => [] }); + }; + }, [items, navigation, props.placement]); + + return null; +} + +function NativeHeaderToolbarButton(_props: { + readonly accessibilityLabel?: string; + readonly disabled?: boolean; + readonly icon?: string; + readonly label?: string; + readonly onPress?: () => void; + readonly separateBackground?: boolean; + readonly tintColor?: ColorValue; +}) { + return null; +} +NativeHeaderToolbarButton.displayName = "NativeHeaderToolbarButton"; + +function NativeHeaderToolbarMenu(_props: { + readonly accessibilityLabel?: string; + readonly children?: ReactNode; + readonly disabled?: boolean; + readonly icon?: string; + readonly inline?: boolean; + readonly separateBackground?: boolean; + readonly tintColor?: ColorValue; + readonly title?: string; +}) { + return null; +} +NativeHeaderToolbarMenu.displayName = "NativeHeaderToolbarMenu"; + +function NativeHeaderToolbarMenuAction(_props: { + readonly children?: ReactNode; + readonly destructive?: boolean; + readonly disabled?: boolean; + readonly discoverabilityLabel?: string; + readonly icon?: string; + readonly isOn?: boolean; + readonly onPress?: () => void; + readonly subtitle?: string; +}) { + return null; +} +NativeHeaderToolbarMenuAction.displayName = "NativeHeaderToolbarMenuAction"; + +function NativeHeaderToolbarLabel(_props: { readonly children?: ReactNode }) { + return null; +} +NativeHeaderToolbarLabel.displayName = "NativeHeaderToolbarLabel"; + +function NativeHeaderToolbarSpacer(_props: { + readonly sharesBackground?: boolean; + readonly width?: number; +}) { + return null; +} +NativeHeaderToolbarSpacer.displayName = "NativeHeaderToolbarSpacer"; + +function NativeHeaderToolbarSearchBarSlot() { + return null; +} +NativeHeaderToolbarSearchBarSlot.displayName = "NativeHeaderToolbarSearchBarSlot"; + +export const NativeHeaderToolbar = Object.assign(NativeHeaderToolbarRoot, { + Button: NativeHeaderToolbarButton, + Label: NativeHeaderToolbarLabel, + Menu: Object.assign(NativeHeaderToolbarMenu, { + Action: NativeHeaderToolbarMenuAction, + }), + MenuAction: NativeHeaderToolbarMenuAction, + SearchBarSlot: NativeHeaderToolbarSearchBarSlot, + Spacer: NativeHeaderToolbarSpacer, +}); diff --git a/apps/mobile/src/native/T3ComposerEditor.android.tsx b/apps/mobile/src/native/T3ComposerEditor.android.tsx new file mode 100644 index 0000000000..ccf88c2de4 --- /dev/null +++ b/apps/mobile/src/native/T3ComposerEditor.android.tsx @@ -0,0 +1,6 @@ +export { ComposerEditor } from "./T3ComposerEditor.native"; +export type { + ComposerEditorHandle, + ComposerEditorProps, + ComposerEditorSelection, +} from "./T3ComposerEditor.types"; diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx index eb935030e8..4e9d62ad2c 100644 --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx @@ -14,8 +14,9 @@ import { Image, StyleSheet } from "react-native"; import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons"; import { resolveMarkdownFileIcon } from "@t3tools/mobile-markdown-text/links"; -import { MOBILE_TYPOGRAPHY } from "../lib/typography"; import { useThemeColor } from "../lib/useThemeColor"; +import { useFontFamily } from "../lib/useFontFamily"; +import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole"; import { acknowledgeComposerNativeEvent, isComposerNativeEcho, @@ -69,6 +70,7 @@ interface NativeComposerEditorProps extends ViewProps { readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void; readonly onComposerFocus?: () => void; readonly onComposerBlur?: () => void; + readonly onComposerSubmit?: () => void; } const NativeView = requireNativeView(NATIVE_MODULE_NAME); @@ -93,6 +95,7 @@ export function ComposerEditor({ onPasteImages, onFocus, onBlur, + onSubmit, contentInsetVertical = 0, ...props }: ComposerEditorProps) { @@ -105,6 +108,7 @@ export function ComposerEditor({ { eventCount: 0, value: props.value, selection: selection ?? null }, ]); const confirmedTokensRef = useRef(collectComposerInlineTokens(props.value)); + const bodyText = useScaledTextRole("body"); const textColor = useThemeColor("--color-foreground"); const placeholderColor = useThemeColor("--color-placeholder"); const chipBackground = useThemeColor("--color-subtle"); @@ -114,6 +118,7 @@ export function ComposerEditor({ const skillBorder = useThemeColor("--color-inline-skill-border"); const skillText = useThemeColor("--color-inline-skill-foreground"); const fileTint = useThemeColor("--color-icon-muted"); + const fontFamily = useFontFamily("regular"); useImperativeHandle( ref, @@ -223,19 +228,17 @@ export function ComposerEditor({ themeJson={themeJson} placeholder={props.placeholder ?? ""} fontFamily={ - typeof resolvedTextStyle.fontFamily === "string" - ? resolvedTextStyle.fontFamily - : "DMSans_400Regular" + typeof resolvedTextStyle.fontFamily === "string" ? resolvedTextStyle.fontFamily : fontFamily } fontSize={ typeof resolvedTextStyle.fontSize === "number" ? resolvedTextStyle.fontSize - : MOBILE_TYPOGRAPHY.composer.fontSize + : bodyText.fontSize } lineHeight={ typeof resolvedTextStyle.lineHeight === "number" ? resolvedTextStyle.lineHeight - : MOBILE_TYPOGRAPHY.composer.lineHeight + : bodyText.lineHeight } contentInsetVertical={contentInsetVertical} editable={props.editable ?? true} @@ -270,6 +273,7 @@ export function ComposerEditor({ onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)} onComposerFocus={onFocus} onComposerBlur={onBlur} + onComposerSubmit={onSubmit} /> ); } diff --git a/apps/mobile/src/native/T3ComposerEditor.native.tsx b/apps/mobile/src/native/T3ComposerEditor.native.tsx new file mode 100644 index 0000000000..84d1c22084 --- /dev/null +++ b/apps/mobile/src/native/T3ComposerEditor.native.tsx @@ -0,0 +1,286 @@ +import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { requireNativeView } from "expo"; +import { + useCallback, + useEffect, + useImperativeHandle, + useMemo, + useRef, + useState, + type Ref, +} from "react"; +import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native"; +import { Image, StyleSheet } from "react-native"; + +import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons"; +import { resolveMarkdownFileIcon } from "@t3tools/mobile-markdown-text/links"; +import { MOBILE_TYPOGRAPHY } from "../lib/typography"; +import { useFontFamily } from "../lib/useFontFamily"; +import { useThemeColor } from "../lib/useThemeColor"; +import { + acknowledgeComposerNativeEvent, + isComposerNativeEcho, + pruneAcknowledgedComposerNativeEvents, + resolveComposerControlledEventCount, + type ComposerNativeEventSnapshot, +} from "./composerEditorRevision"; +import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types"; + +const NATIVE_MODULE_NAME = "T3ComposerEditor"; +const EMPTY_SKILLS: NonNullable = []; + +type NativeEditorEvent = NativeSyntheticEvent<{ + readonly value: string; + readonly selection: ComposerEditorSelection; + readonly eventCount: number; +}>; + +type NativeSelectionEvent = NativeSyntheticEvent<{ + readonly value: string; + readonly selection: ComposerEditorSelection; + readonly eventCount: number; +}>; + +type NativePasteImagesEvent = NativeSyntheticEvent<{ + readonly uris: ReadonlyArray; +}>; + +interface NativeComposerEditorRef { + focus: () => Promise; + blur: () => Promise; + setSelection: (start: number, end: number) => Promise; +} + +interface NativeComposerEditorProps extends ViewProps { + readonly ref?: Ref; + readonly controlledDocumentJson: string; + readonly themeJson: string; + readonly placeholder: string; + readonly fontFamily: string; + readonly fontSize: number; + readonly lineHeight: number; + readonly contentInsetVertical: number; + readonly singleLineCentered: boolean; + readonly editable: boolean; + readonly scrollEnabled: boolean; + readonly autoFocus: boolean; + readonly autoCorrect: boolean; + readonly spellCheck: boolean; + readonly onComposerChange: (event: NativeEditorEvent) => void; + readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void; + readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void; + readonly onComposerFocus?: () => void; + readonly onComposerBlur?: () => void; +} + +const NativeView = requireNativeView(NATIVE_MODULE_NAME); + +function basename(path: string): string { + const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return separator >= 0 ? path.slice(separator + 1) : path; +} + +function fileIconUri(path: string): string { + return Image.resolveAssetSource(markdownFileIconSource(resolveMarkdownFileIcon(path))).uri; +} + +export function ComposerEditor({ + ref, + skills = EMPTY_SKILLS, + selection, + style, + textStyle, + onChangeText, + onSelectionChange, + onPasteImages, + onFocus, + onBlur, + contentInsetVertical = 0, + ...props +}: ComposerEditorProps) { + const nativeRef = useRef(null); + const mostRecentEventCountRef = useRef(0); + const [mostRecentEventCount, setMostRecentEventCount] = useState(0); + const [nativeEventSequence, setNativeEventSequence] = useState(0); + const previousRenderedEventSequenceRef = useRef(0); + const nativeEventSnapshotsRef = useRef([ + { eventCount: 0, value: props.value, selection: selection ?? null }, + ]); + const [initialConfirmedTokens] = useState(() => collectComposerInlineTokens(props.value)); + const confirmedTokensRef = useRef(initialConfirmedTokens); + const textColor = useThemeColor("--color-foreground"); + const placeholderColor = useThemeColor("--color-placeholder"); + const chipBackground = useThemeColor("--color-subtle"); + const chipBorder = useThemeColor("--color-border"); + const chipText = useThemeColor("--color-foreground"); + const skillBackground = useThemeColor("--color-inline-skill-background"); + const skillBorder = useThemeColor("--color-inline-skill-border"); + const skillText = useThemeColor("--color-inline-skill-foreground"); + const fileTint = useThemeColor("--color-icon-muted"); + + useImperativeHandle( + ref, + () => ({ + focus: () => void nativeRef.current?.focus(), + blur: () => void nativeRef.current?.blur(), + setSelection: (nextSelection) => + void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end), + }), + [], + ); + + const skillLabels = useMemo( + () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])), + [skills], + ); + const tokensJson = useMemo(() => { + const tokens = collectComposerInlineTokens(props.value, { + preserveTrailingFrom: confirmedTokensRef.current, + }); + confirmedTokensRef.current = tokens; + return JSON.stringify( + tokens.map((token) => ({ + type: token.type, + source: token.source, + start: token.start, + end: token.end, + label: + token.type === "skill" + ? (skillLabels.get(token.value) ?? token.value) + : basename(token.value), + iconUri: token.type === "mention" ? fileIconUri(token.value) : null, + })), + ); + }, [props.value, skillLabels]); + const includesNativeEvent = nativeEventSequence !== previousRenderedEventSequenceRef.current; + const controlledEventCount = includesNativeEvent + ? resolveComposerControlledEventCount( + props.value, + selection ?? null, + mostRecentEventCount, + nativeEventSnapshotsRef.current, + ) + : mostRecentEventCount; + const acknowledgesLatestNativeEvent = isComposerNativeEcho( + props.value, + selection ?? null, + mostRecentEventCount, + nativeEventSnapshotsRef.current, + ); + const isNativeEcho = + includesNativeEvent && + controlledEventCount === mostRecentEventCount && + acknowledgesLatestNativeEvent; + const controlledDocumentJson = JSON.stringify({ + value: props.value, + selection: isNativeEcho ? null : (selection ?? null), + tokensJson, + mostRecentEventCount: controlledEventCount, + isNativeEcho, + }); + useEffect(() => { + previousRenderedEventSequenceRef.current = nativeEventSequence; + }, [nativeEventSequence]); + useEffect(() => { + if (!acknowledgesLatestNativeEvent) return; + nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents( + nativeEventSnapshotsRef.current, + mostRecentEventCount, + ); + }, [acknowledgesLatestNativeEvent, mostRecentEventCount]); + const acceptNativeEvent = useCallback( + (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => { + const acknowledgedEventCount = acknowledgeComposerNativeEvent( + mostRecentEventCountRef.current, + eventCount, + ); + if (acknowledgedEventCount === null) { + return false; + } + mostRecentEventCountRef.current = acknowledgedEventCount; + nativeEventSnapshotsRef.current.push({ + eventCount: acknowledgedEventCount, + value, + selection: nextSelection, + }); + return acknowledgedEventCount; + }, + [], + ); + const themeJson = JSON.stringify({ + text: String(textColor), + placeholder: String(placeholderColor), + chipBackground: String(chipBackground), + chipBorder: String(chipBorder), + chipText: String(chipText), + skillBackground: String(skillBackground), + skillBorder: String(skillBorder), + skillText: String(skillText), + fileTint: String(fileTint), + }); + const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {}; + const regularFontFamily = useFontFamily("regular"); + return ( + } + onComposerChange={(event) => { + const acknowledgedEventCount = acceptNativeEvent( + event.nativeEvent.eventCount, + event.nativeEvent.value, + event.nativeEvent.selection, + ); + if (acknowledgedEventCount === false) return; + onChangeText(event.nativeEvent.value); + onSelectionChange?.(event.nativeEvent.selection); + setMostRecentEventCount(acknowledgedEventCount); + setNativeEventSequence((sequence) => sequence + 1); + }} + onComposerSelectionChange={(event) => { + const acknowledgedEventCount = acceptNativeEvent( + event.nativeEvent.eventCount, + event.nativeEvent.value, + event.nativeEvent.selection, + ); + if (acknowledgedEventCount === false) return; + onSelectionChange?.(event.nativeEvent.selection); + setMostRecentEventCount(acknowledgedEventCount); + setNativeEventSequence((sequence) => sequence + 1); + }} + onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)} + onComposerFocus={onFocus} + onComposerBlur={onBlur} + /> + ); +} + +export type { + ComposerEditorHandle, + ComposerEditorProps, + ComposerEditorSelection, +} from "./T3ComposerEditor.types"; diff --git a/apps/mobile/src/native/T3ComposerEditor.tsx b/apps/mobile/src/native/T3ComposerEditor.tsx index dc2dfdfee0..e082d3892a 100644 --- a/apps/mobile/src/native/T3ComposerEditor.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.tsx @@ -2,8 +2,9 @@ import { TextInputWrapper } from "expo-paste-input"; import { useImperativeHandle, useRef } from "react"; import { TextInput, type TextInput as RNTextInput } from "react-native"; -import { MOBILE_TYPOGRAPHY } from "../lib/typography"; import { useThemeColor } from "../lib/useThemeColor"; +import { useFontFamily } from "../lib/useFontFamily"; +import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole"; import { useNativePaste } from "../lib/useNativePaste"; import type { ComposerEditorProps } from "./T3ComposerEditor.types"; @@ -15,11 +16,14 @@ export function ComposerEditor({ style, textStyle, contentInsetVertical = 0, + singleLineCentered: _singleLineCentered, ...props }: ComposerEditorProps) { const inputRef = useRef(null); + const bodyText = useScaledTextRole("body"); const foregroundColor = useThemeColor("--color-foreground"); const placeholderColor = useThemeColor("--color-placeholder"); + const fontFamily = useFontFamily("regular"); const handlePaste = useNativePaste((uris) => onPasteImages?.(uris)); useImperativeHandle( @@ -47,8 +51,8 @@ export function ComposerEditor({ flex: 1, minHeight: 0, color: foregroundColor, - fontFamily: "DMSans_400Regular", - ...MOBILE_TYPOGRAPHY.composer, + fontFamily, + ...bodyText, paddingVertical: contentInsetVertical, }, textStyle, diff --git a/apps/mobile/src/native/T3ComposerEditor.types.ts b/apps/mobile/src/native/T3ComposerEditor.types.ts index d70d63fa43..bfc47ed367 100644 --- a/apps/mobile/src/native/T3ComposerEditor.types.ts +++ b/apps/mobile/src/native/T3ComposerEditor.types.ts @@ -28,6 +28,8 @@ export interface ComposerEditorProps { readonly spellCheck?: boolean; readonly multiline?: boolean; readonly contentInsetVertical?: number; + /** Android: center a single line vertically (collapsed pill); no-op on iOS. */ + readonly singleLineCentered?: boolean; readonly style?: StyleProp; readonly textStyle?: StyleProp; readonly onChangeText: (value: string) => void; @@ -35,4 +37,6 @@ export interface ComposerEditorProps { readonly onPasteImages?: (uris: ReadonlyArray) => void; readonly onFocus?: () => void; readonly onBlur?: () => void; + /** Invoked by the native editor when Command-Return is pressed on a hardware keyboard. */ + readonly onSubmit?: () => void; } diff --git a/apps/mobile/src/native/T3HeaderButton.android.tsx b/apps/mobile/src/native/T3HeaderButton.android.tsx new file mode 100644 index 0000000000..74908abd16 --- /dev/null +++ b/apps/mobile/src/native/T3HeaderButton.android.tsx @@ -0,0 +1,26 @@ +import { requireNativeView } from "expo"; +import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native"; + +interface NativeHeaderButtonProps extends ViewProps { + readonly label: string; + readonly systemImage: "gearshape" | "square.and.pencil"; + readonly onTriggered: (event: NativeSyntheticEvent>) => void; +} + +const NativeHeaderButton = requireNativeView("T3NativeControls"); + +export function T3HeaderButton(props: { + readonly accessibilityLabel: string; + readonly icon: NativeHeaderButtonProps["systemImage"]; + readonly onPress: () => void; + readonly style?: StyleProp; +}) { + return ( + + ); +} diff --git a/apps/mobile/src/native/T3KeyboardCommands.ios.tsx b/apps/mobile/src/native/T3KeyboardCommands.ios.tsx new file mode 100644 index 0000000000..ff4e817c20 --- /dev/null +++ b/apps/mobile/src/native/T3KeyboardCommands.ios.tsx @@ -0,0 +1,31 @@ +import { requireNativeView } from "expo"; +import type { PropsWithChildren } from "react"; +import type { NativeSyntheticEvent, ViewProps } from "react-native"; + +import type { HardwareKeyboardCommand } from "../features/keyboard/hardwareKeyboardCommands"; + +interface NativeKeyboardCommandsProps extends ViewProps, PropsWithChildren { + readonly enabledCommands: ReadonlyArray; + readonly onCommand: ( + event: NativeSyntheticEvent<{ readonly command: HardwareKeyboardCommand }>, + ) => void; +} + +const NativeKeyboardCommands = requireNativeView("T3KeyboardCommands"); + +export function T3KeyboardCommands( + props: PropsWithChildren<{ + readonly enabledCommands: ReadonlyArray; + readonly onCommand: (command: HardwareKeyboardCommand) => void; + }>, +) { + return ( + props.onCommand(event.nativeEvent.command)} + enabledCommands={props.enabledCommands} + style={{ flex: 1 }} + > + {props.children} + + ); +} diff --git a/apps/mobile/src/native/T3KeyboardCommands.tsx b/apps/mobile/src/native/T3KeyboardCommands.tsx new file mode 100644 index 0000000000..1f49dd172c --- /dev/null +++ b/apps/mobile/src/native/T3KeyboardCommands.tsx @@ -0,0 +1,13 @@ +import type { PropsWithChildren } from "react"; +import { View } from "react-native"; + +import type { HardwareKeyboardCommand } from "../features/keyboard/hardwareKeyboardCommands"; + +export function T3KeyboardCommands( + props: PropsWithChildren<{ + readonly enabledCommands: ReadonlyArray; + readonly onCommand: (command: HardwareKeyboardCommand) => void; + }>, +) { + return {props.children}; +} diff --git a/apps/mobile/src/native/native-glass.ts b/apps/mobile/src/native/native-glass.ts new file mode 100644 index 0000000000..40b28076d3 --- /dev/null +++ b/apps/mobile/src/native/native-glass.ts @@ -0,0 +1,9 @@ +import { isLiquidGlassSupported } from "@callstack/liquid-glass"; +import { Platform } from "react-native"; + +import { supportsNativeLiquidGlass } from "../lib/native-glass-capability"; + +export const NATIVE_LIQUID_GLASS_SUPPORTED = supportsNativeLiquidGlass( + Platform.OS, + isLiquidGlassSupported, +); diff --git a/apps/mobile/src/native/scrollEdgeEffects.test.ts b/apps/mobile/src/native/scrollEdgeEffects.test.ts new file mode 100644 index 0000000000..cf7e590671 --- /dev/null +++ b/apps/mobile/src/native/scrollEdgeEffects.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { nativeHeaderScrollEdgeEffects, nativeTopScrollEdgeEffect } from "./scrollEdgeEffects"; + +describe("nativeTopScrollEdgeEffect", () => { + it("keeps the automatic native treatment on iOS 26", () => { + expect(nativeTopScrollEdgeEffect("ios", "26.5")).toBe("automatic"); + }); + + it("keeps UIKit automatic scroll-edge sampling on iOS 27 and later", () => { + expect(nativeTopScrollEdgeEffect("ios", "27.0")).toBe("automatic"); + expect(nativeTopScrollEdgeEffect("ios", 28)).toBe("automatic"); + }); + + it("does not apply the iOS workaround to other platforms", () => { + expect(nativeTopScrollEdgeEffect("android", 27)).toBe("automatic"); + }); +}); + +describe("nativeHeaderScrollEdgeEffects", () => { + it("keeps non-top header edges hidden while applying the platform top effect", () => { + expect(nativeHeaderScrollEdgeEffects("ios", "27.0")).toEqual({ + top: "automatic", + bottom: "hidden", + left: "hidden", + right: "hidden", + }); + }); +}); diff --git a/apps/mobile/src/native/scrollEdgeEffects.ts b/apps/mobile/src/native/scrollEdgeEffects.ts new file mode 100644 index 0000000000..cb6f74295d --- /dev/null +++ b/apps/mobile/src/native/scrollEdgeEffects.ts @@ -0,0 +1,37 @@ +// Pure helpers for native header scroll-edge effects. Kept free of +// react-native / react-navigation imports so they stay unit-testable in node +// (those packages ship untranspiled Flow syntax). + +export type NativeTopScrollEdgeEffect = "automatic" | "soft"; +export type NativeHeaderScrollEdgeEffects = { + readonly top: NativeTopScrollEdgeEffect; + readonly bottom: "hidden"; + readonly left: "hidden"; + readonly right: "hidden"; +}; + +export function nativeTopScrollEdgeEffect( + os: string, + _version: number | string, +): NativeTopScrollEdgeEffect { + if (os !== "ios") { + return "automatic"; + } + + // The standalone RNS/Mail spike that matched Messages/GitHub used UIKit's + // automatic scroll-edge behavior. Forcing `soft` on iOS 27 makes production + // look like a local overlay instead of sampling the app content edge-to-edge. + return "automatic"; +} + +export function nativeHeaderScrollEdgeEffects( + os: string, + version: number | string, +): NativeHeaderScrollEdgeEffects { + return { + top: nativeTopScrollEdgeEffect(os, version), + bottom: "hidden", + left: "hidden", + right: "hidden", + }; +} diff --git a/apps/mobile/src/persistence/imperative.ts b/apps/mobile/src/persistence/imperative.ts new file mode 100644 index 0000000000..b66f6597c1 --- /dev/null +++ b/apps/mobile/src/persistence/imperative.ts @@ -0,0 +1,53 @@ +import * as Effect from "effect/Effect"; + +import { runtime } from "../lib/runtime"; +import * as MobilePreferences from "./mobile-preferences"; +import * as MobileStorage from "./mobile-storage"; + +export type { Preferences } from "./mobile-preferences"; +export type { AgentAwarenessRegistrationRecord, RecentThreadShortcut } from "./mobile-storage"; +export { MobilePreferencesLoadError, MobilePreferencesSaveError } from "./mobile-preferences"; +export { + MobileDeviceIdGenerationError, + MobileStorageDecodeError, + MobileStorageEncodeError, +} from "./mobile-storage"; +export { MobileSecureStorageError } from "./mobile-secure-storage"; + +const runStorage = ( + use: (storage: MobileStorage.MobileStorage["Service"]) => Effect.Effect, +) => runtime.runPromise(MobileStorage.MobileStorage.pipe(Effect.flatMap(use))); + +const runPreferences = ( + use: (store: MobilePreferences.MobilePreferencesStore["Service"]) => Effect.Effect, +) => runtime.runPromise(MobilePreferences.MobilePreferencesStore.pipe(Effect.flatMap(use))); + +export const loadSavedConnections = () => runStorage((storage) => storage.loadSavedConnections); +export const saveConnection = ( + connection: Parameters[0], +) => runStorage((storage) => storage.saveConnection(connection)); + +export const loadPreferences = () => runPreferences((store) => store.load); +export const savePreferencesPatch = (patch: Partial) => + runPreferences((store) => store.savePatch(patch)); +export const updatePreferences = ( + transform: (current: MobilePreferences.Preferences) => Partial, +) => runPreferences((store) => store.update(transform)); + +export const loadOrCreateAgentAwarenessDeviceId = () => + runStorage((storage) => storage.loadOrCreateAgentAwarenessDeviceId); +export const loadAgentAwarenessDeviceId = () => + runStorage((storage) => storage.loadAgentAwarenessDeviceId); +export const loadAgentAwarenessRegistrationRecord = () => + runStorage((storage) => storage.loadAgentAwarenessRegistrationRecord); +export const saveAgentAwarenessRegistrationRecord = ( + record: MobileStorage.AgentAwarenessRegistrationRecord, +) => runStorage((storage) => storage.saveAgentAwarenessRegistrationRecord(record)); +export const clearAgentAwarenessRegistrationRecord = () => + runStorage((storage) => storage.clearAgentAwarenessRegistrationRecord); + +export const loadRecentThreadShortcuts = () => + runStorage((storage) => storage.loadRecentThreadShortcuts); +export const saveRecentThreadShortcuts = ( + threads: ReadonlyArray, +) => runStorage((storage) => storage.saveRecentThreadShortcuts(threads)); diff --git a/apps/mobile/src/persistence/layer.ts b/apps/mobile/src/persistence/layer.ts new file mode 100644 index 0000000000..5a9d1dacff --- /dev/null +++ b/apps/mobile/src/persistence/layer.ts @@ -0,0 +1,16 @@ +import * as Layer from "effect/Layer"; + +import * as EnvironmentCacheStore from "../connection/environment-cache-store"; +import * as MobileDatabase from "./mobile-database"; +import * as MobilePreferences from "./mobile-preferences"; +import * as MobileSecureStorage from "./mobile-secure-storage"; +import * as MobileStorage from "./mobile-storage"; + +const baseLayer = Layer.merge(MobileDatabase.layer, MobileSecureStorage.layer); +const dependentLayer = Layer.mergeAll( + MobilePreferences.layer, + MobileStorage.layer, + EnvironmentCacheStore.layer, +).pipe(Layer.provide(baseLayer)); + +export const layer = Layer.merge(baseLayer, dependentLayer); diff --git a/apps/mobile/src/persistence/mobile-database.test.ts b/apps/mobile/src/persistence/mobile-database.test.ts new file mode 100644 index 0000000000..56c3e31657 --- /dev/null +++ b/apps/mobile/src/persistence/mobile-database.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { vi } from "vite-plus/test"; + +const openDatabaseAsync = vi.hoisted(() => vi.fn()); + +vi.mock("expo-sqlite", () => ({ openDatabaseAsync })); + +import { decodeLegacyCacheRecord, make } from "./mobile-database"; + +describe("mobile database legacy cache migration", () => { + it.effect("keeps acquisition failures typed on database operations", () => + Effect.scoped( + Effect.gen(function* () { + openDatabaseAsync.mockRejectedValueOnce(new Error("SQLite unavailable")); + + const database = yield* make; + const result = yield* Effect.result(database.loadPreferencesJson); + + expect(result).toMatchObject({ + _tag: "Failure", + failure: { _tag: "MobileDatabaseError", operation: "open" }, + }); + }), + ), + ); + + it("maps legacy thread records to their SQLite identity", () => { + const payload = JSON.stringify({ + schemaVersion: 2, + environmentId: "environment-1", + threadId: "thread-1", + snapshot: {}, + }); + + expect(decodeLegacyCacheRecord("connection-thread-snapshots", payload)).toEqual({ + environmentId: "environment-1", + kind: "thread", + cacheKey: "thread-1", + schemaVersion: 2, + payload, + }); + }); + + it("preserves the old shell payload for schema decoding after migration", () => { + const payload = JSON.stringify({ + schemaVersion: 1, + environmentId: "environment-1", + snapshotReceivedAt: "2026-07-01T00:00:00.000Z", + snapshot: {}, + }); + + expect(decodeLegacyCacheRecord("shell-snapshots", payload)).toEqual({ + environmentId: "environment-1", + kind: "shell", + cacheKey: "snapshot", + schemaVersion: 1, + payload, + }); + }); + + it("skips malformed legacy records", () => { + expect(decodeLegacyCacheRecord("connection-vcs-refs", "{not-json")).toBeNull(); + expect( + decodeLegacyCacheRecord( + "connection-vcs-refs", + JSON.stringify({ schemaVersion: 1, environmentId: "environment-1" }), + ), + ).toBeNull(); + }); +}); diff --git a/apps/mobile/src/persistence/mobile-database.ts b/apps/mobile/src/persistence/mobile-database.ts new file mode 100644 index 0000000000..33eb50f640 --- /dev/null +++ b/apps/mobile/src/persistence/mobile-database.ts @@ -0,0 +1,409 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import type { SQLiteDatabase } from "expo-sqlite"; + +const DATABASE_NAME = "t3code-client.db"; +const DATABASE_SCHEMA_VERSION = 1; +const LEGACY_CACHE_DIRECTORIES = [ + "connection-shell-snapshots", + "shell-snapshots", + "connection-thread-snapshots", + "connection-server-configs", + "connection-vcs-refs", +] as const; + +export const ClientCacheKind = Schema.Literals(["shell", "thread", "server-config", "vcs-refs"]); +export type ClientCacheKind = typeof ClientCacheKind.Type; + +export interface ClientCacheSummaryRow { + readonly environmentId: EnvironmentId; + readonly kind: ClientCacheKind; + readonly recordCount: number; + readonly payloadBytes: number; +} + +export interface StoredPreferencesJson { + readonly payload: string; + readonly updatedAt: number; +} + +const ClientCacheSummaryRows = Schema.Array( + Schema.Struct({ + environmentId: Schema.String, + kind: ClientCacheKind, + recordCount: Schema.Number, + payloadBytes: Schema.Number, + }), +); + +const MobileDatabaseOperation = Schema.Literals([ + "open", + "migrate", + "load-cache", + "save-cache", + "remove-cache", + "clear-environment-cache", + "clear-all-caches", + "inspect-caches", + "load-preferences", + "save-preferences", +]); + +export class MobileDatabaseError extends Schema.TaggedErrorClass()( + "MobileDatabaseError", + { + operation: MobileDatabaseOperation, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Mobile database operation failed: ${this.operation}.`; + } +} + +function databaseError(operation: typeof MobileDatabaseOperation.Type) { + return (cause: unknown) => new MobileDatabaseError({ operation, cause }); +} + +interface LegacyCacheRecord { + readonly environmentId: string; + readonly kind: ClientCacheKind; + readonly cacheKey: string; + readonly schemaVersion: number; + readonly payload: string; +} + +function objectRecord(value: unknown): Record | null { + return typeof value === "object" && value !== null ? (value as Record) : null; +} + +export function decodeLegacyCacheRecord( + directoryName: (typeof LEGACY_CACHE_DIRECTORIES)[number], + payload: string, +): LegacyCacheRecord | null { + let parsed: Record | null; + try { + parsed = objectRecord(JSON.parse(payload)); + } catch { + return null; + } + if ( + parsed === null || + typeof parsed.environmentId !== "string" || + typeof parsed.schemaVersion !== "number" + ) { + return null; + } + + switch (directoryName) { + case "connection-shell-snapshots": + case "shell-snapshots": + return { + environmentId: parsed.environmentId, + kind: "shell", + cacheKey: "snapshot", + schemaVersion: parsed.schemaVersion, + payload, + }; + case "connection-thread-snapshots": + return typeof parsed.threadId === "string" + ? { + environmentId: parsed.environmentId, + kind: "thread", + cacheKey: parsed.threadId, + schemaVersion: parsed.schemaVersion, + payload, + } + : null; + case "connection-server-configs": + return { + environmentId: parsed.environmentId, + kind: "server-config", + cacheKey: "config", + schemaVersion: parsed.schemaVersion, + payload, + }; + case "connection-vcs-refs": + return typeof parsed.cwd === "string" + ? { + environmentId: parsed.environmentId, + kind: "vcs-refs", + cacheKey: parsed.cwd, + schemaVersion: parsed.schemaVersion, + payload, + } + : null; + } +} + +async function migrateLegacyFileCaches(database: SQLiteDatabase): Promise { + try { + const { Directory, File, Paths } = await import("expo-file-system"); + let complete = true; + const listFiles = ( + directory: InstanceType, + ): Array> => + directory.list().flatMap((entry) => (entry instanceof File ? [entry] : listFiles(entry))); + + for (const directoryName of LEGACY_CACHE_DIRECTORIES) { + try { + const directory = new Directory(Paths.document, directoryName); + if (!directory.exists) continue; + for (const file of listFiles(directory)) { + const payload = await file.text(); + const record = decodeLegacyCacheRecord(directoryName, payload); + if (record === null) continue; + await database.runAsync( + `INSERT INTO client_cache + (environment_id, kind, cache_key, schema_version, payload, updated_at) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (environment_id, kind, cache_key) DO NOTHING`, + record.environmentId, + record.kind, + record.cacheKey, + record.schemaVersion, + record.payload, + Date.now(), + ); + } + directory.delete(); + } catch (cause) { + complete = false; + console.warn(`[mobile-database] could not migrate legacy cache ${directoryName}`, cause); + } + } + return complete; + } catch (cause) { + console.warn("[mobile-database] could not load legacy cache migration", cause); + return false; + } +} + +export class MobileDatabase extends Context.Service< + MobileDatabase, + { + readonly loadCache: ( + environmentId: EnvironmentId, + kind: ClientCacheKind, + cacheKey: string, + ) => Effect.Effect, MobileDatabaseError>; + readonly saveCache: ( + environmentId: EnvironmentId, + kind: ClientCacheKind, + cacheKey: string, + schemaVersion: number, + payload: string, + ) => Effect.Effect; + readonly removeCache: ( + environmentId: EnvironmentId, + kind: ClientCacheKind, + cacheKey: string, + ) => Effect.Effect; + readonly clearEnvironmentCache: ( + environmentId: EnvironmentId, + ) => Effect.Effect; + readonly clearAllCaches: Effect.Effect; + readonly inspectCaches: Effect.Effect< + ReadonlyArray, + MobileDatabaseError + >; + readonly loadPreferencesJson: Effect.Effect< + Option.Option, + MobileDatabaseError + >; + readonly savePreferencesJson: ( + payload: string, + updatedAt: number, + ) => Effect.Effect; + } +>()("@t3tools/mobile/persistence/MobileDatabase") {} + +const makeAvailable = Effect.gen(function* () { + const database = yield* Effect.acquireRelease( + Effect.tryPromise({ + try: async () => { + const SQLite = await import("expo-sqlite"); + return SQLite.openDatabaseAsync(DATABASE_NAME); + }, + catch: databaseError("open"), + }), + (openDatabase) => Effect.promise(() => openDatabase.closeAsync()).pipe(Effect.ignore), + ); + + yield* Effect.tryPromise({ + try: async () => { + await database.execAsync("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;"); + const schema = await database.getFirstAsync<{ readonly user_version: number }>( + "PRAGMA user_version", + ); + await database.withExclusiveTransactionAsync(async (transaction) => { + await transaction.execAsync(` + CREATE TABLE IF NOT EXISTS client_cache ( + environment_id TEXT NOT NULL, + kind TEXT NOT NULL, + cache_key TEXT NOT NULL, + schema_version INTEGER NOT NULL, + payload TEXT NOT NULL, + updated_at INTEGER NOT NULL, + PRIMARY KEY (environment_id, kind, cache_key) + ) WITHOUT ROWID; + + CREATE INDEX IF NOT EXISTS client_cache_environment_updated + ON client_cache (environment_id, updated_at DESC); + + CREATE TABLE IF NOT EXISTS client_preferences ( + singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1), + payload TEXT NOT NULL, + updated_at INTEGER NOT NULL + ); + `); + }); + if ((schema?.user_version ?? 0) < DATABASE_SCHEMA_VERSION) { + const migrated = await migrateLegacyFileCaches(database); + if (migrated) { + await database.execAsync(`PRAGMA user_version = ${DATABASE_SCHEMA_VERSION};`); + } + } + }, + catch: databaseError("migrate"), + }); + + return MobileDatabase.of({ + loadCache: Effect.fn("MobileDatabase.loadCache")((environmentId, kind, cacheKey) => + Effect.tryPromise({ + try: () => + database.getFirstAsync<{ readonly payload: string }>( + `SELECT payload + FROM client_cache + WHERE environment_id = ? AND kind = ? AND cache_key = ?`, + environmentId, + kind, + cacheKey, + ), + catch: databaseError("load-cache"), + }).pipe(Effect.map((row) => Option.fromNullishOr(row?.payload))), + ), + saveCache: Effect.fn("MobileDatabase.saveCache")( + (environmentId, kind, cacheKey, schemaVersion, payload) => + Effect.tryPromise({ + try: () => + database.runAsync( + `INSERT INTO client_cache + (environment_id, kind, cache_key, schema_version, payload, updated_at) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (environment_id, kind, cache_key) DO UPDATE SET + schema_version = excluded.schema_version, + payload = excluded.payload, + updated_at = excluded.updated_at`, + environmentId, + kind, + cacheKey, + schemaVersion, + payload, + Date.now(), + ), + catch: databaseError("save-cache"), + }).pipe(Effect.asVoid), + ), + removeCache: Effect.fn("MobileDatabase.removeCache")((environmentId, kind, cacheKey) => + Effect.tryPromise({ + try: () => + database.runAsync( + `DELETE FROM client_cache + WHERE environment_id = ? AND kind = ? AND cache_key = ?`, + environmentId, + kind, + cacheKey, + ), + catch: databaseError("remove-cache"), + }).pipe(Effect.asVoid), + ), + clearEnvironmentCache: Effect.fn("MobileDatabase.clearEnvironmentCache")((environmentId) => + Effect.tryPromise({ + try: () => + database.runAsync("DELETE FROM client_cache WHERE environment_id = ?", environmentId), + catch: databaseError("clear-environment-cache"), + }).pipe(Effect.asVoid), + ), + clearAllCaches: Effect.tryPromise({ + try: () => database.runAsync("DELETE FROM client_cache"), + catch: databaseError("clear-all-caches"), + }).pipe(Effect.asVoid), + inspectCaches: Effect.tryPromise({ + try: () => + database.getAllAsync(` + SELECT + environment_id AS environmentId, + kind, + COUNT(*) AS recordCount, + COALESCE(SUM(LENGTH(CAST(payload AS BLOB))), 0) AS payloadBytes + FROM client_cache + GROUP BY environment_id, kind + ORDER BY environment_id, kind + `), + catch: databaseError("inspect-caches"), + }).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(ClientCacheSummaryRows)), + Effect.mapError(databaseError("inspect-caches")), + Effect.map( + (rows): ReadonlyArray => + rows.map((row) => ({ + environmentId: row.environmentId as EnvironmentId, + kind: row.kind, + recordCount: row.recordCount, + payloadBytes: row.payloadBytes, + })), + ), + ), + loadPreferencesJson: Effect.tryPromise({ + try: () => + database.getFirstAsync( + `SELECT payload, updated_at AS updatedAt + FROM client_preferences + WHERE singleton = 1`, + ), + catch: databaseError("load-preferences"), + }).pipe(Effect.map(Option.fromNullishOr)), + savePreferencesJson: Effect.fn("MobileDatabase.savePreferencesJson")((payload, updatedAt) => + Effect.tryPromise({ + try: () => + database.runAsync( + `INSERT INTO client_preferences (singleton, payload, updated_at) + VALUES (1, ?, ?) + ON CONFLICT (singleton) DO UPDATE SET + payload = excluded.payload, + updated_at = excluded.updated_at`, + payload, + updatedAt, + ), + catch: databaseError("save-preferences"), + }).pipe(Effect.asVoid), + ), + }); +}); + +function makeUnavailable(error: MobileDatabaseError): MobileDatabase["Service"] { + const fail = Effect.fail(error); + return MobileDatabase.of({ + loadCache: () => fail, + saveCache: () => fail, + removeCache: () => fail, + clearEnvironmentCache: () => fail, + clearAllCaches: fail, + inspectCaches: fail, + loadPreferencesJson: fail, + savePreferencesJson: () => fail, + }); +} + +export const make = Effect.result(makeAvailable).pipe( + Effect.map((result) => + result._tag === "Success" ? result.success : makeUnavailable(result.failure), + ), +); + +export const layer = Layer.effect(MobileDatabase, make); diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts new file mode 100644 index 0000000000..6971570b0e --- /dev/null +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -0,0 +1,305 @@ +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; + +import * as MobileDatabase from "./mobile-database"; +import * as MobileSecureStorage from "./mobile-secure-storage"; +import { MobileStorageDecodeError, MobileStorageEncodeError } from "./mobile-storage"; + +const PREFERENCES_KEY = "t3code.preferences"; +const PREFERENCES_FALLBACK_KEY = "t3code.preferences.fallback"; + +export interface Preferences { + readonly liveActivitiesEnabled?: boolean; + readonly baseFontSize?: number; + readonly terminalFontSize?: number | null; + readonly markdownFontSize?: number; + readonly codeFontSize?: number | null; + readonly codeWordBreak?: boolean; + readonly connectOnboardingOptOutAccounts?: ReadonlyArray; + readonly collapsedProjectGroups?: readonly string[]; +} + +export class MobilePreferencesLoadError extends Schema.TaggedErrorClass()( + "MobilePreferencesLoadError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Failed to load mobile preferences."; + } +} + +export class MobilePreferencesSaveError extends Schema.TaggedErrorClass()( + "MobilePreferencesSaveError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Failed to save mobile preferences."; + } +} + +interface PreferencesFallback { + readonly payload: string; + readonly updatedAt: number; + readonly preferences: Preferences; +} + +export class MobilePreferencesStore extends Context.Service< + MobilePreferencesStore, + { + readonly load: Effect.Effect; + readonly savePatch: ( + patch: Partial, + ) => Effect.Effect; + readonly update: ( + transform: (current: Preferences) => Partial, + ) => Effect.Effect; + } +>()("@t3tools/mobile/persistence/MobilePreferencesStore") {} + +function sanitizePreferences(parsed: Preferences): Preferences { + const preferences: { + liveActivitiesEnabled?: boolean; + baseFontSize?: number; + terminalFontSize?: number | null; + markdownFontSize?: number; + codeFontSize?: number | null; + codeWordBreak?: boolean; + connectOnboardingOptOutAccounts?: ReadonlyArray; + collapsedProjectGroups?: readonly string[]; + } = {}; + + if (typeof parsed.liveActivitiesEnabled === "boolean") { + preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled; + } + if (typeof parsed.baseFontSize === "number") preferences.baseFontSize = parsed.baseFontSize; + if (typeof parsed.terminalFontSize === "number" || parsed.terminalFontSize === null) { + preferences.terminalFontSize = parsed.terminalFontSize; + } + if (typeof parsed.markdownFontSize === "number") { + preferences.markdownFontSize = parsed.markdownFontSize; + } + if (typeof parsed.codeFontSize === "number" || parsed.codeFontSize === null) { + preferences.codeFontSize = parsed.codeFontSize; + } + if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak; + if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) { + preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter( + (account): account is string => typeof account === "string", + ); + } + if (Array.isArray(parsed.collapsedProjectGroups)) { + preferences.collapsedProjectGroups = parsed.collapsedProjectGroups.filter( + (key): key is string => typeof key === "string", + ); + } + return preferences; +} + +export const make = Effect.fn("MobilePreferencesStore.make")(function* () { + const database = yield* MobileDatabase.MobileDatabase; + const secureStorage = yield* MobileSecureStorage.MobileSecureStorage; + const lock = yield* Semaphore.make(1); + const lastUpdatedAt = yield* Ref.make(0); + + const parsePayload = (raw: string | null): Preferences | null => { + if (raw === null || !raw.trim()) return null; + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (cause) { + console.warn( + "[mobile-storage] ignored invalid JSON", + new MobileStorageDecodeError({ key: PREFERENCES_KEY, cause }), + ); + return null; + } + return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) + ? (parsed as Preferences) + : null; + }; + + const parseFallback = (raw: string | null): PreferencesFallback | null => { + if (raw === null || !raw.trim()) return null; + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (cause) { + console.warn( + "[mobile-storage] ignored invalid JSON", + new MobileStorageDecodeError({ key: PREFERENCES_FALLBACK_KEY, cause }), + ); + return null; + } + if ( + typeof parsed !== "object" || + parsed === null || + !("payload" in parsed) || + typeof parsed.payload !== "string" || + !("updatedAt" in parsed) || + typeof parsed.updatedAt !== "number" + ) { + return null; + } + const preferences = parsePayload(parsed.payload); + return preferences === null + ? null + : { payload: parsed.payload, updatedAt: parsed.updatedAt, preferences }; + }; + + const encode = Effect.fn("MobilePreferencesStore.encode")(function* ( + key: string, + value: unknown, + ) { + return yield* Effect.try({ + try: () => JSON.stringify(value), + catch: (cause) => new MobileStorageEncodeError({ key, cause }), + }); + }); + + const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => { + const next = Math.max(Date.now(), last + 1); + return [next, next] as const; + }); + + const saveJson = Effect.fn("MobilePreferencesStore.saveJson")(function* ( + payload: string, + updatedAt?: number, + ) { + const timestamp = updatedAt ?? (yield* nextUpdatedAt); + yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, timestamp)); + const databaseResult = yield* Effect.result(database.savePreferencesJson(payload, timestamp)); + if (databaseResult._tag === "Failure") { + yield* Effect.logWarning("Database unavailable; saving preferences to secure storage.").pipe( + Effect.annotateLogs({ cause: databaseResult.failure }), + ); + const fallback = yield* encode(PREFERENCES_FALLBACK_KEY, { payload, updatedAt: timestamp }); + yield* secureStorage.setItem(PREFERENCES_FALLBACK_KEY, fallback); + return; + } + yield* secureStorage + .removeItem(PREFERENCES_FALLBACK_KEY) + .pipe( + Effect.catch((error) => + Effect.logWarning("Could not remove the mobile preferences fallback.").pipe( + Effect.annotateLogs({ error }), + ), + ), + ); + }); + + const loadUnlocked = Effect.gen(function* () { + const databaseResult = yield* Effect.result(database.loadPreferencesJson); + const databaseAvailable = databaseResult._tag === "Success"; + const storedJson = databaseAvailable + ? databaseResult.success + : Option.none(); + if (databaseResult._tag === "Failure") { + yield* Effect.logWarning("Database unavailable; loading fallback preferences.").pipe( + Effect.annotateLogs({ cause: databaseResult.failure }), + ); + } + + const fallbackResult = yield* Effect.result(secureStorage.getItem(PREFERENCES_FALLBACK_KEY)); + let fallbackJson: string | null = null; + if (fallbackResult._tag === "Success") { + fallbackJson = fallbackResult.success; + } else if (Option.isNone(storedJson)) { + return yield* fallbackResult.failure; + } else { + yield* Effect.logWarning("Could not inspect the mobile preferences fallback.").pipe( + Effect.annotateLogs({ error: fallbackResult.failure }), + ); + } + + const fallback = parseFallback(fallbackJson); + const storedPreferences = Option.isSome(storedJson) + ? parsePayload(storedJson.value.payload) + : null; + const fallbackIsNewer = + fallback !== null && + (storedPreferences === null || + (Option.isSome(storedJson) && fallback.updatedAt > storedJson.value.updatedAt)); + + let parsed: Preferences | null = null; + if (fallbackIsNewer) { + parsed = fallback.preferences; + yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, fallback.updatedAt)); + if (databaseAvailable) yield* saveJson(fallback.payload, fallback.updatedAt); + } else if (storedPreferences !== null && Option.isSome(storedJson)) { + parsed = storedPreferences; + yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, storedJson.value.updatedAt)); + if (fallbackJson !== null) { + yield* secureStorage + .removeItem(PREFERENCES_FALLBACK_KEY) + .pipe( + Effect.catch((error) => + Effect.logWarning("Could not remove a stale mobile preferences fallback.").pipe( + Effect.annotateLogs({ error }), + ), + ), + ); + } + } + + if (parsed === null) { + const legacyJson = yield* secureStorage.getItem(PREFERENCES_KEY); + const legacyPreferences = parsePayload(legacyJson); + parsed = legacyPreferences; + if (legacyJson !== null && legacyPreferences !== null && databaseAvailable) { + yield* saveJson(legacyJson); + yield* secureStorage + .removeItem(PREFERENCES_KEY) + .pipe( + Effect.catch((error) => + Effect.logWarning("Could not remove migrated mobile preferences.").pipe( + Effect.annotateLogs({ error }), + ), + ), + ); + } + } + + return parsed === null ? {} : sanitizePreferences(parsed); + }); + + const load = lock + .withPermits(1)(loadUnlocked) + .pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause }))); + + const update = Effect.fn("MobilePreferencesStore.update")((transform) => + lock + .withPermits(1)( + Effect.gen(function* () { + const current = yield* loadUnlocked; + const patch = yield* Effect.try({ + try: () => transform(current), + catch: (cause) => new MobilePreferencesSaveError({ cause }), + }); + const next: Preferences = { ...current, ...patch }; + const payload = yield* encode(PREFERENCES_KEY, next); + yield* saveJson(payload); + return next; + }), + ) + .pipe( + Effect.mapError((cause) => + cause instanceof MobilePreferencesSaveError + ? cause + : new MobilePreferencesSaveError({ cause }), + ), + ), + ); + + return MobilePreferencesStore.of({ + load, + update, + savePatch: (patch) => update(() => patch), + }); +}); + +export const layer = Layer.effect(MobilePreferencesStore, make()); diff --git a/apps/mobile/src/persistence/mobile-secure-storage.ts b/apps/mobile/src/persistence/mobile-secure-storage.ts new file mode 100644 index 0000000000..0ab7c9e4d9 --- /dev/null +++ b/apps/mobile/src/persistence/mobile-secure-storage.ts @@ -0,0 +1,52 @@ +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SecureStore from "expo-secure-store"; + +const MobileSecureStorageOperation = Schema.Literals(["read", "write", "delete"]); + +export class MobileSecureStorageError extends Schema.TaggedErrorClass()( + "MobileSecureStorageError", + { + operation: MobileSecureStorageOperation, + key: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Mobile secure storage operation ${this.operation} failed for key ${this.key}.`; + } +} + +export class MobileSecureStorage extends Context.Service< + MobileSecureStorage, + { + readonly getItem: (key: string) => Effect.Effect; + readonly setItem: (key: string, value: string) => Effect.Effect; + readonly removeItem: (key: string) => Effect.Effect; + } +>()("@t3tools/mobile/persistence/MobileSecureStorage") {} + +export const make = MobileSecureStorage.of({ + getItem: Effect.fn("MobileSecureStorage.getItem")((key) => + Effect.tryPromise({ + try: () => SecureStore.getItemAsync(key), + catch: (cause) => new MobileSecureStorageError({ operation: "read", key, cause }), + }), + ), + setItem: Effect.fn("MobileSecureStorage.setItem")((key, value) => + Effect.tryPromise({ + try: () => SecureStore.setItemAsync(key, value), + catch: (cause) => new MobileSecureStorageError({ operation: "write", key, cause }), + }), + ), + removeItem: Effect.fn("MobileSecureStorage.removeItem")((key) => + Effect.tryPromise({ + try: () => SecureStore.deleteItemAsync(key), + catch: (cause) => new MobileSecureStorageError({ operation: "delete", key, cause }), + }), + ), +}); + +export const layer = Layer.succeed(MobileSecureStorage, make); diff --git a/apps/mobile/src/persistence/mobile-storage.ts b/apps/mobile/src/persistence/mobile-storage.ts new file mode 100644 index 0000000000..266e8c1a9a --- /dev/null +++ b/apps/mobile/src/persistence/mobile-storage.ts @@ -0,0 +1,266 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import * as Arr from "effect/Array"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import { pipe } from "effect/Function"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { + isRelayManagedConnection, + type SavedRemoteConnection, + toStableSavedRemoteConnection, +} from "../lib/connection"; +import * as MobileSecureStorage from "./mobile-secure-storage"; + +const CONNECTIONS_KEY = "t3code.connections"; +const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id"; +const AGENT_AWARENESS_REGISTRATION_KEY = "t3code.agent-awareness.registration"; +const RECENT_THREAD_SHORTCUTS_KEY = "t3code.recent-thread-shortcuts"; + +export class MobileStorageDecodeError extends Schema.TaggedErrorClass()( + "MobileStorageDecodeError", + { + key: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Failed to decode mobile storage value for key ${this.key}.`; + } +} + +export class MobileStorageEncodeError extends Schema.TaggedErrorClass()( + "MobileStorageEncodeError", + { + key: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Failed to encode mobile storage value for key ${this.key}.`; + } +} + +export class MobileDeviceIdGenerationError extends Schema.TaggedErrorClass()( + "MobileDeviceIdGenerationError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Failed to generate the mobile agent-awareness device id."; + } +} + +export interface AgentAwarenessRegistrationRecord { + readonly identity: string; + readonly signature: string; + readonly pushToStartToken?: string; +} + +export interface RecentThreadShortcut { + readonly environmentId: string; + readonly threadId: string; + readonly title: string; +} + +export class MobileStorage extends Context.Service< + MobileStorage, + { + readonly loadSavedConnections: Effect.Effect< + ReadonlyArray, + MobileSecureStorage.MobileSecureStorageError + >; + readonly saveConnection: ( + connection: SavedRemoteConnection, + ) => Effect.Effect< + void, + MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError + >; + readonly clearSavedConnection: ( + environmentId: EnvironmentId, + ) => Effect.Effect< + void, + MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError + >; + readonly loadOrCreateAgentAwarenessDeviceId: Effect.Effect< + string, + MobileSecureStorage.MobileSecureStorageError | MobileDeviceIdGenerationError + >; + readonly loadAgentAwarenessDeviceId: Effect.Effect< + string | null, + MobileSecureStorage.MobileSecureStorageError + >; + readonly loadAgentAwarenessRegistrationRecord: Effect.Effect< + AgentAwarenessRegistrationRecord | null, + MobileSecureStorage.MobileSecureStorageError + >; + readonly saveAgentAwarenessRegistrationRecord: ( + record: AgentAwarenessRegistrationRecord, + ) => Effect.Effect< + void, + MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError + >; + readonly clearAgentAwarenessRegistrationRecord: Effect.Effect< + void, + MobileSecureStorage.MobileSecureStorageError + >; + readonly loadRecentThreadShortcuts: Effect.Effect< + ReadonlyArray, + MobileSecureStorage.MobileSecureStorageError + >; + readonly saveRecentThreadShortcuts: ( + threads: ReadonlyArray, + ) => Effect.Effect< + void, + MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError + >; + } +>()("@t3tools/mobile/persistence/MobileStorage") {} + +export const make = Effect.fn("MobileStorage.make")(function* () { + const secureStorage = yield* MobileSecureStorage.MobileSecureStorage; + + const parseJson = (key: string, raw: string): A | null => { + if (!raw.trim()) return null; + try { + return JSON.parse(raw) as A; + } catch (cause) { + console.warn( + "[mobile-storage] ignored invalid JSON", + new MobileStorageDecodeError({ key, cause }), + ); + return null; + } + }; + + const readJson = Effect.fn("MobileStorage.readJson")(function* (key: string) { + const raw = (yield* secureStorage.getItem(key)) ?? ""; + return parseJson(key, raw); + }); + + const writeJson = Effect.fn("MobileStorage.writeJson")(function* (key: string, value: unknown) { + const encoded = yield* Effect.try({ + try: () => JSON.stringify(value), + catch: (cause) => new MobileStorageEncodeError({ key, cause }), + }); + yield* secureStorage.setItem(key, encoded); + }); + + const loadSavedConnections = readJson<{ + readonly connections?: ReadonlyArray; + }>(CONNECTIONS_KEY).pipe( + Effect.map((parsed) => + pipe( + parsed?.connections ?? [], + Arr.filter( + (connection) => + !!connection.environmentId && + (!!connection.bearerToken?.trim() || isRelayManagedConnection(connection)), + ), + ), + ), + ); + + const saveConnection = Effect.fn("MobileStorage.saveConnection")(function* ( + connection: SavedRemoteConnection, + ) { + const current = yield* loadSavedConnections; + const stableConnection = toStableSavedRemoteConnection(connection); + const next = current.some((entry) => entry.environmentId === connection.environmentId) + ? pipe( + current, + Arr.map((entry) => + entry.environmentId === connection.environmentId ? stableConnection : entry, + ), + ) + : pipe(current, Arr.append(stableConnection)); + yield* writeJson(CONNECTIONS_KEY, { connections: next }); + }); + + const clearSavedConnection = Effect.fn("MobileStorage.clearSavedConnection")(function* ( + environmentId: EnvironmentId, + ) { + const current = yield* loadSavedConnections; + const next = pipe( + current, + Arr.filter((entry) => entry.environmentId !== environmentId), + ); + yield* writeJson(CONNECTIONS_KEY, { connections: next }); + }); + + const loadOrCreateAgentAwarenessDeviceId = Effect.gen(function* () { + const existing = yield* secureStorage.getItem(AGENT_AWARENESS_DEVICE_ID_KEY); + if (existing?.trim()) return existing; + const deviceId = yield* Effect.tryPromise({ + try: () => import("../lib/uuid").then(({ uuidv4 }) => uuidv4()), + catch: (cause) => new MobileDeviceIdGenerationError({ cause }), + }); + yield* secureStorage.setItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId); + return deviceId; + }); + + const loadAgentAwarenessDeviceId = secureStorage + .getItem(AGENT_AWARENESS_DEVICE_ID_KEY) + .pipe(Effect.map((existing) => (existing?.trim() ? existing : null))); + + const loadAgentAwarenessRegistrationRecord = readJson( + AGENT_AWARENESS_REGISTRATION_KEY, + ).pipe( + Effect.map((parsed) => { + if ( + !parsed || + typeof parsed !== "object" || + typeof parsed.identity !== "string" || + typeof parsed.signature !== "string" + ) { + return null; + } + return { + identity: parsed.identity, + signature: parsed.signature, + ...(typeof parsed.pushToStartToken === "string" && parsed.pushToStartToken + ? { pushToStartToken: parsed.pushToStartToken } + : {}), + }; + }), + ); + + // Threads most recently opened on this device, newest first — the source + // for the launcher's dynamic "recent thread" app shortcuts. + const loadRecentThreadShortcuts = readJson<{ + readonly threads?: ReadonlyArray; + }>(RECENT_THREAD_SHORTCUTS_KEY).pipe( + Effect.map((parsed) => + pipe( + parsed?.threads ?? [], + Arr.filter( + (thread) => + typeof thread?.environmentId === "string" && + thread.environmentId.length > 0 && + typeof thread.threadId === "string" && + thread.threadId.length > 0 && + typeof thread.title === "string", + ), + ), + ), + ); + + return MobileStorage.of({ + loadSavedConnections, + saveConnection, + clearSavedConnection, + loadOrCreateAgentAwarenessDeviceId, + loadAgentAwarenessDeviceId, + loadAgentAwarenessRegistrationRecord, + saveAgentAwarenessRegistrationRecord: (record) => + writeJson(AGENT_AWARENESS_REGISTRATION_KEY, record), + clearAgentAwarenessRegistrationRecord: secureStorage.setItem( + AGENT_AWARENESS_REGISTRATION_KEY, + "", + ), + loadRecentThreadShortcuts, + saveRecentThreadShortcuts: (threads) => writeJson(RECENT_THREAD_SHORTCUTS_KEY, { threads }), + }); +}); + +export const layer = Layer.effect(MobileStorage, make()); diff --git a/apps/mobile/src/state/client-cache-state.ts b/apps/mobile/src/state/client-cache-state.ts new file mode 100644 index 0000000000..3912857b57 --- /dev/null +++ b/apps/mobile/src/state/client-cache-state.ts @@ -0,0 +1,87 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import { Atom } from "effect/unstable/reactivity"; + +import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-database"; +import * as Runtime from "../lib/runtime"; + +export interface EnvironmentClientCacheSummary { + readonly environmentId: EnvironmentId; + readonly recordCount: number; + readonly payloadBytes: number; + readonly kinds: Readonly>>; +} + +export interface ClientCacheSummary { + readonly recordCount: number; + readonly payloadBytes: number; + readonly environments: ReadonlyArray; +} + +export type ClientCacheClearScope = + | { readonly type: "all" } + | { readonly type: "environment"; readonly environmentId: EnvironmentId }; + +function aggregateCacheSummary( + rows: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly kind: ClientCacheKind; + readonly recordCount: number; + readonly payloadBytes: number; + }>, +): ClientCacheSummary { + const environments = new Map(); + let recordCount = 0; + let payloadBytes = 0; + + for (const row of rows) { + recordCount += row.recordCount; + payloadBytes += row.payloadBytes; + const current = environments.get(row.environmentId) ?? { + environmentId: row.environmentId, + recordCount: 0, + payloadBytes: 0, + kinds: {}, + }; + environments.set(row.environmentId, { + environmentId: row.environmentId, + recordCount: current.recordCount + row.recordCount, + payloadBytes: current.payloadBytes + row.payloadBytes, + kinds: { ...current.kinds, [row.kind]: row.recordCount }, + }); + } + + return { + recordCount, + payloadBytes, + environments: [...environments.values()], + }; +} + +const clientCacheRuntime = Atom.runtime(Runtime.runtimeContextLayer); + +export const clientCacheSummaryAtom = clientCacheRuntime + .atom( + MobileDatabase.pipe( + Effect.flatMap((database) => database.inspectCaches), + Effect.map(aggregateCacheSummary), + ), + ) + .pipe(Atom.withLabel("mobile:client-cache:summary")); + +export const clearClientCacheAtom = clientCacheRuntime + .fn((scope: ClientCacheClearScope, get) => + MobileDatabase.pipe( + Effect.flatMap((database) => + scope.type === "all" + ? database.clearAllCaches + : database.clearEnvironmentCache(scope.environmentId), + ), + Effect.tap(() => + Effect.sync(() => { + get.refresh(clientCacheSummaryAtom); + }), + ), + ), + ) + .pipe(Atom.withLabel("mobile:client-cache:clear")); diff --git a/apps/mobile/src/state/preferences.test.ts b/apps/mobile/src/state/preferences.test.ts new file mode 100644 index 0000000000..c53594eb23 --- /dev/null +++ b/apps/mobile/src/state/preferences.test.ts @@ -0,0 +1,272 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity"; +import { vi } from "vite-plus/test"; + +vi.mock("expo-secure-store", () => ({ + getItemAsync: vi.fn(), + setItemAsync: vi.fn(), +})); + +vi.mock("react-native", () => ({ + Platform: { OS: "ios" }, +})); + +vi.mock("../lib/runtime", async () => { + const Layer = await import("effect/Layer"); + return { + runtime: { runPromise: vi.fn() }, + runtimeContextLayer: Layer.empty, + }; +}); + +import type { Preferences } from "../persistence/mobile-preferences"; +import { + createMobilePreferencesState, + MobilePreferencesLoadError, + MobilePreferencesSaveError, + MobilePreferencesStore, +} from "./preferences"; + +function deferred() { + let resolve!: (value: A) => void; + const promise = new Promise((resume) => { + resolve = resume; + }); + return { promise, resolve } as const; +} + +function makePreferencesState( + service: Omit & + Partial>, +) { + const completeService = MobilePreferencesStore.of({ + ...service, + update: + service.update ?? + ((transform) => + service.load.pipe( + Effect.flatMap((current) => service.savePatch(transform(current))), + Effect.mapError((cause) => + cause._tag === "MobilePreferencesSaveError" + ? cause + : new MobilePreferencesSaveError({ cause }), + ), + )), + }); + return createMobilePreferencesState( + Atom.runtime(Layer.succeed(MobilePreferencesStore, completeService)), + ); +} + +describe("mobile preferences state", () => { + it.effect("shares one preference load across consumers", () => + Effect.gen(function* () { + const load = vi.fn(() => Promise.resolve({ baseFontSize: 17 })); + const state = makePreferencesState({ + load: Effect.promise(load), + savePatch: (patch) => Effect.succeed(patch), + }); + const registry = AtomRegistry.make(); + const unmountFirst = registry.mount(state.preferencesAtom); + const unmountSecond = registry.mount(state.preferencesAtom); + + expect( + yield* AtomRegistry.getResult(registry, state.preferencesAtom, { + suspendOnWaiting: true, + }), + ).toEqual({ baseFontSize: 17 }); + expect(load).toHaveBeenCalledTimes(1); + + unmountSecond(); + unmountFirst(); + registry.dispose(); + }), + ); + + it.effect("preserves an optimistic patch when the initial load finishes later", () => + Effect.gen(function* () { + const pendingLoad = deferred(); + const savePatch = vi.fn((patch: Partial) => Effect.succeed(patch)); + const state = makePreferencesState({ + load: Effect.promise(() => pendingLoad.promise), + savePatch, + }); + const registry = AtomRegistry.make(); + const unmountPreferences = registry.mount(state.preferencesAtom); + const unmountUpdate = registry.mount(state.updatePreferencesAtom); + + registry.set(state.updatePreferencesAtom, { + collapsedProjectGroups: ["project:new"], + }); + pendingLoad.resolve({ + baseFontSize: 18, + collapsedProjectGroups: ["project:old"], + }); + + const preferences = yield* AtomRegistry.getResult(registry, state.preferencesAtom, { + suspendOnWaiting: true, + }); + expect(preferences).toEqual({ + baseFontSize: 18, + collapsedProjectGroups: ["project:new"], + }); + expect(savePatch).toHaveBeenCalledWith({ + collapsedProjectGroups: ["project:new"], + }); + expect(AsyncResult.isFailure(registry.get(state.updatePreferencesAtom))).toBe(false); + + unmountUpdate(); + unmountPreferences(); + registry.dispose(); + }), + ); + + it.effect("falls back to empty preferences when secure storage cannot be read", () => + Effect.gen(function* () { + const state = makePreferencesState({ + load: Effect.fail( + new MobilePreferencesLoadError({ + cause: new Error("secure storage unavailable"), + }), + ), + savePatch: (patch) => Effect.succeed(patch), + }); + const registry = AtomRegistry.make(); + const unmount = registry.mount(state.preferencesAtom); + + expect( + yield* AtomRegistry.getResult(registry, state.preferencesAtom, { + suspendOnWaiting: true, + }), + ).toEqual({}); + + unmount(); + registry.dispose(); + }), + ); + + it.effect("does not roll back a newer optimistic write with the same value", () => + Effect.gen(function* () { + let saveCount = 0; + const state = makePreferencesState({ + load: Effect.succeed({ baseFontSize: 16, codeFontSize: 13 }), + savePatch: (patch) => { + saveCount += 1; + return saveCount === 1 + ? Effect.fail(new MobilePreferencesSaveError({ cause: new Error("write failed") })) + : Effect.succeed(patch); + }, + }); + const registry = AtomRegistry.make(); + const unmountPreferences = registry.mount(state.preferencesAtom); + const unmountUpdate = registry.mount(state.updatePreferencesAtom); + + yield* AtomRegistry.getResult(registry, state.preferencesAtom, { + suspendOnWaiting: true, + }); + registry.set(state.updatePreferencesAtom, { baseFontSize: 18 }); + registry.set(state.updatePreferencesAtom, { baseFontSize: 18, codeFontSize: 15 }); + + yield* Effect.promise(() => + vi.waitFor(() => { + expect(AsyncResult.isFailure(registry.get(state.updatePreferencesAtom))).toBe(false); + expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual( + { + baseFontSize: 18, + codeFontSize: 15, + }, + ); + }), + ); + + unmountUpdate(); + unmountPreferences(); + registry.dispose(); + }), + ); + + it.effect("rolls back an optimistic field when its save fails", () => + Effect.gen(function* () { + const state = makePreferencesState({ + load: Effect.succeed({ baseFontSize: 16 }), + savePatch: () => + Effect.fail(new MobilePreferencesSaveError({ cause: new Error("write failed") })), + }); + const registry = AtomRegistry.make(); + const unmountPreferences = registry.mount(state.preferencesAtom); + const unmountUpdate = registry.mount(state.updatePreferencesAtom); + + yield* AtomRegistry.getResult(registry, state.preferencesAtom, { + suspendOnWaiting: true, + }); + registry.set(state.updatePreferencesAtom, { baseFontSize: 18 }); + + yield* Effect.promise(() => + vi.waitFor(() => { + expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual( + { + baseFontSize: 16, + }, + ); + }), + ); + + unmountUpdate(); + unmountPreferences(); + registry.dispose(); + }), + ); + + it.effect("rolls back to the last confirmed value after a later save fails", () => + Effect.gen(function* () { + let saveCount = 0; + const state = makePreferencesState({ + load: Effect.succeed({ baseFontSize: 16 }), + savePatch: () => { + saveCount += 1; + return saveCount === 1 + ? Effect.succeed({ baseFontSize: 14 }) + : Effect.fail(new MobilePreferencesSaveError({ cause: new Error("write failed") })); + }, + }); + const registry = AtomRegistry.make(); + const unmountPreferences = registry.mount(state.preferencesAtom); + const unmountUpdate = registry.mount(state.updatePreferencesAtom); + + yield* AtomRegistry.getResult(registry, state.preferencesAtom, { + suspendOnWaiting: true, + }); + registry.set(state.updatePreferencesAtom, { baseFontSize: 14 }); + yield* Effect.promise(() => + vi.waitFor(() => { + expect(saveCount).toBe(1); + expect(registry.get(state.updatePreferencesAtom).waiting).toBe(false); + expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual( + { + baseFontSize: 14, + }, + ); + }), + ); + + registry.set(state.updatePreferencesAtom, { baseFontSize: 18 }); + yield* Effect.promise(() => + vi.waitFor(() => { + expect(saveCount).toBe(2); + expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual( + { + baseFontSize: 14, + }, + ); + }), + ); + + unmountUpdate(); + unmountPreferences(); + registry.dispose(); + }), + ); +}); diff --git a/apps/mobile/src/state/preferences.ts b/apps/mobile/src/state/preferences.ts new file mode 100644 index 0000000000..d173cf55be --- /dev/null +++ b/apps/mobile/src/state/preferences.ts @@ -0,0 +1,124 @@ +import * as Effect from "effect/Effect"; +import { AsyncResult, Atom } from "effect/unstable/reactivity"; + +import { MobilePreferencesStore, type Preferences } from "../persistence/mobile-preferences"; +import * as Runtime from "../lib/runtime"; + +export { + MobilePreferencesLoadError, + MobilePreferencesSaveError, + MobilePreferencesStore, +} from "../persistence/mobile-preferences"; + +interface OptimisticPreferences { + readonly values: Partial; + readonly versions: Partial>; +} + +/** + * Owns the device preference blob for the lifetime of the app registry. + * Optimistic patches are kept separately so writes made while persistence is + * still loading cannot be replaced by the eventual read result. + */ +export function createMobilePreferencesState(runtime: Atom.AtomRuntime) { + const storedPreferencesAtom = runtime + .atom( + MobilePreferencesStore.pipe( + Effect.flatMap((store) => store.load), + Effect.catch((error) => + Effect.logWarning("Could not load mobile preferences.", error).pipe( + Effect.as({}), + ), + ), + ), + ) + .pipe(Atom.keepAlive, Atom.withLabel("mobile:preferences:stored")); + + const optimisticPatchAtom = Atom.make({ values: {}, versions: {} }).pipe( + Atom.keepAlive, + Atom.withLabel("mobile:preferences:optimistic-patch"), + ); + const confirmedPreferencesAtom = Atom.make({}).pipe( + Atom.keepAlive, + Atom.withLabel("mobile:preferences:confirmed"), + ); + let nextPatchVersion = 0; + + const preferencesAtom = Atom.make((get) => { + const stored = get(storedPreferencesAtom); + const confirmed = get(confirmedPreferencesAtom); + const optimistic = get(optimisticPatchAtom); + return AsyncResult.map(stored, (preferences) => ({ + ...preferences, + ...confirmed, + ...optimistic.values, + })); + }).pipe(Atom.keepAlive, Atom.withLabel("mobile:preferences")); + + const updatePreferencesAtom = runtime + .fn( + (patch: Partial, get) => { + const version = ++nextPatchVersion; + const current = get(optimisticPatchAtom); + const versions = { ...current.versions }; + for (const key of Object.keys(patch) as Array) { + versions[key] = version; + } + get.set(optimisticPatchAtom, { + values: { ...current.values, ...patch }, + versions, + }); + return MobilePreferencesStore.pipe( + Effect.flatMap((store) => store.savePatch(patch)), + Effect.tap((saved) => + Effect.sync(() => { + get.set(confirmedPreferencesAtom, saved); + const optimistic = get(optimisticPatchAtom); + const values = { ...optimistic.values } as Record; + const currentVersions = { ...optimistic.versions } as Record; + for (const key of Object.keys(patch) as Array) { + if (optimistic.versions[key] === version) { + delete values[key]; + delete currentVersions[key]; + } + } + get.set(optimisticPatchAtom, { + values: values as Partial, + versions: currentVersions as Partial>, + }); + }), + ), + Effect.tapError(() => + Effect.sync(() => { + const optimistic = get(optimisticPatchAtom); + const values = { ...optimistic.values } as Record; + const currentVersions = { ...optimistic.versions } as Record; + for (const key of Object.keys(patch) as Array) { + if (optimistic.versions[key] === version) { + delete values[key]; + delete currentVersions[key]; + } + } + get.set(optimisticPatchAtom, { + values: values as Partial, + versions: currentVersions as Partial>, + }); + }), + ), + ); + }, + // The storage layer serializes preference read-modify-write operations. + // Keep every invocation alive so one preference update cannot interrupt + // another update to a different field in the shared blob. + { concurrent: true }, + ) + .pipe(Atom.keepAlive, Atom.withLabel("mobile:preferences:update")); + + return { preferencesAtom, updatePreferencesAtom } as const; +} + +const mobilePreferencesRuntime = Atom.runtime(Runtime.runtimeContextLayer); +export const mobilePreferencesState = createMobilePreferencesState(mobilePreferencesRuntime); + +export const mobilePreferencesAtom = mobilePreferencesState.preferencesAtom; +export const updateMobilePreferencesAtom = mobilePreferencesState.updatePreferencesAtom; diff --git a/apps/mobile/src/state/thread-outbox-manager.ts b/apps/mobile/src/state/thread-outbox-manager.ts index 7762e6cdf7..19f89d13c5 100644 --- a/apps/mobile/src/state/thread-outbox-manager.ts +++ b/apps/mobile/src/state/thread-outbox-manager.ts @@ -15,6 +15,7 @@ export class ThreadOutboxManagerError extends Schema.TaggedErrorClass candidate.messageId !== message.messageId), + message, + ]); + }); + + // Rewrites an already-queued message. A no-op when the message has been + // removed in the meantime (e.g. deleted or delivered), so a trailing editor + // flush can never resurrect it. Returns whether the message was updated. + const update = (message: QueuedThreadMessage): Promise => + serialize(async () => { + const exists = currentMessages().some( + (candidate) => candidate.messageId === message.messageId, + ); + if (!exists) { + return false; + } + try { + await options.storage.write(message); + } catch (cause) { + throw new ThreadOutboxManagerError({ + operation: "update", + environmentId: message.environmentId, + threadId: message.threadId, + messageId: message.messageId, + cause, + }); + } + setMessages([ + ...currentMessages().filter((candidate) => candidate.messageId !== message.messageId), + message, + ]); + return true; }); const remove = (message: QueuedThreadMessage): Promise => @@ -171,6 +204,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) { serialize, load, enqueue, + update, remove, clearEnvironment, }; diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts index ed0c06ba38..3ba61be387 100644 --- a/apps/mobile/src/state/thread-outbox-model.ts +++ b/apps/mobile/src/state/thread-outbox-model.ts @@ -6,10 +6,12 @@ import { IsoDateTime, MessageId, ModelSelection, + ProjectId, ProviderInteractionMode, RuntimeMode, ThreadId, type ModelSelection as ModelSelectionType, + type ProjectId as ProjectIdType, type ProviderInteractionMode as ProviderInteractionModeType, type RuntimeMode as RuntimeModeType, } from "@t3tools/contracts"; @@ -19,11 +21,23 @@ import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema import type { DraftComposerImageAttachment } from "../lib/composerImages"; import { scopedThreadKey } from "../lib/scopedEntities"; -const THREAD_OUTBOX_SCHEMA_VERSION = 2; +const THREAD_OUTBOX_SCHEMA_VERSION = 3; const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000; +const QueuedThreadCreationSchema = Schema.Struct({ + projectId: ProjectId, + // Snapshot of the project's display metadata so a pending task stays + // presentable in the thread list even when the project shell is not loaded. + projectTitle: Schema.optional(Schema.String), + projectCwd: Schema.optional(Schema.String), + workspaceMode: Schema.Literals(["local", "worktree"]), + branch: Schema.NullOr(Schema.String), + worktreePath: Schema.NullOr(Schema.String), + startFromOrigin: Schema.optional(Schema.Boolean), +}); + export const QueuedThreadMessageSchema = Schema.Struct({ - schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]), + schemaVersion: Schema.Literals([1, 2, THREAD_OUTBOX_SCHEMA_VERSION]), environmentId: EnvironmentId, threadId: ThreadId, messageId: MessageId, @@ -33,12 +47,25 @@ export const QueuedThreadMessageSchema = Schema.Struct({ modelSelection: Schema.optional(ModelSelection), runtimeMode: Schema.optional(RuntimeMode), interactionMode: Schema.optional(ProviderInteractionMode), + // Present when the queued item creates a brand-new thread (pending task) + // instead of appending a turn to an existing one. + creation: Schema.optional(QueuedThreadCreationSchema), createdAt: IsoDateTime, }); const decodeStoredQueuedThreadMessage = Schema.decodeUnknownSync(QueuedThreadMessageSchema); const encodeStoredQueuedThreadMessage = Schema.encodeUnknownSync(QueuedThreadMessageSchema); +export interface QueuedThreadCreation { + readonly projectId: ProjectIdType; + readonly projectTitle?: string; + readonly projectCwd?: string; + readonly workspaceMode: "local" | "worktree"; + readonly branch: string | null; + readonly worktreePath: string | null; + readonly startFromOrigin?: boolean; +} + export interface QueuedThreadMessage { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; @@ -49,6 +76,7 @@ export interface QueuedThreadMessage { readonly modelSelection?: ModelSelectionType; readonly runtimeMode?: RuntimeModeType; readonly interactionMode?: ProviderInteractionModeType; + readonly creation?: QueuedThreadCreation; readonly createdAt: string; } @@ -121,17 +149,43 @@ export function threadOutboxRetryDelayMs(attempt: number): number { export type ThreadOutboxDeliveryAction = "wait" | "remove" | "send"; export function resolveThreadOutboxDeliveryAction(input: { + readonly isCreation: boolean; readonly threadExists: boolean; readonly shellStatus: EnvironmentShellStatus; readonly environmentConnected: boolean; readonly threadBusy: boolean; }): ThreadOutboxDeliveryAction { + if (input.isCreation) { + // A pending task creates its thread on delivery. If the thread already + // exists the creation command went through and only cleanup remains. + if (input.threadExists) { + return "remove"; + } + // Wait for the shell to be live before sending: until the thread list has + // synchronized, a previously delivered creation whose cleanup failed would + // look missing and get re-issued, duplicating the thread. + return input.environmentConnected && input.shellStatus === "live" ? "send" : "wait"; + } if (!input.threadExists) { return input.shellStatus === "live" ? "remove" : "wait"; } return input.environmentConnected && !input.threadBusy ? "send" : "wait"; } +/** + * A queued creation can only be dispatched once its payload would pass server + * validation; incomplete payloads stay pending until the user edits them. + */ +export function isQueuedThreadCreationSendable(message: QueuedThreadMessage): boolean { + if (!message.creation) { + return false; + } + if (message.text.trim().length === 0 || message.modelSelection === undefined) { + return false; + } + return message.creation.workspaceMode !== "worktree" || Boolean(message.creation.branch); +} + function errorMessage(error: unknown): string | null { if (error instanceof Error) { return error.message; diff --git a/apps/mobile/src/state/thread-outbox.test.ts b/apps/mobile/src/state/thread-outbox.test.ts index 68d06d2e42..6c665c432f 100644 --- a/apps/mobile/src/state/thread-outbox.test.ts +++ b/apps/mobile/src/state/thread-outbox.test.ts @@ -3,6 +3,7 @@ import { CommandId, EnvironmentId, MessageId, + ProjectId, ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; @@ -12,6 +13,7 @@ import { decodeQueuedThreadMessage, encodeQueuedThreadMessage, groupQueuedThreadMessages, + isQueuedThreadCreationSendable, modelSelectionsEqual, resolveThreadOutboxDeliveryAction, resolveThreadOutboxFailureAction, @@ -292,9 +294,68 @@ describe("thread outbox", () => { registry.dispose(); }); + it("replaces an existing message when an enqueue retry uses the same id", async () => { + const registry = AtomRegistry.make(); + const manager = createThreadOutboxManager({ + registry, + storage: { + load: async () => [], + write: async () => undefined, + remove: async () => undefined, + }, + }); + const message = queuedMessage({ + messageId: "message-1", + createdAt: "2026-06-08T10:00:01.000Z", + }); + const retried = { ...message, text: "retried" }; + + await manager.enqueue(message); + await manager.enqueue(retried); + + expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({ + "environment-1:thread-1": [retried], + }); + registry.dispose(); + }); + + it("updates a queued message in place but never resurrects a removed one", async () => { + const registry = AtomRegistry.make(); + const stored = new Map(); + const storage: ThreadOutboxStorage = { + load: async () => [...stored.values()], + write: async (message) => { + stored.set(message.messageId, message); + }, + remove: async (message) => { + stored.delete(message.messageId); + }, + }; + const manager = createThreadOutboxManager({ registry, storage }); + const message = queuedMessage({ + messageId: "message-1", + createdAt: "2026-06-08T10:00:01.000Z", + }); + + await manager.enqueue(message); + const edited = { ...message, text: "edited" }; + await expect(manager.update(edited)).resolves.toBe(true); + expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({ + "environment-1:thread-1": [edited], + }); + expect(stored.get(message.messageId)).toEqual(edited); + + await manager.remove(edited); + await expect(manager.update({ ...message, text: "stale flush" })).resolves.toBe(false); + expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({}); + expect(stored.size).toBe(0); + registry.dispose(); + }); + it("only removes a missing-thread message after shell synchronization is live", () => { expect( resolveThreadOutboxDeliveryAction({ + isCreation: false, threadExists: false, shellStatus: "synchronizing", environmentConnected: true, @@ -303,6 +364,7 @@ describe("thread outbox", () => { ).toBe("wait"); expect( resolveThreadOutboxDeliveryAction({ + isCreation: false, threadExists: false, shellStatus: "live", environmentConnected: true, @@ -311,6 +373,7 @@ describe("thread outbox", () => { ).toBe("remove"); expect( resolveThreadOutboxDeliveryAction({ + isCreation: false, threadExists: true, shellStatus: "live", environmentConnected: true, @@ -319,6 +382,89 @@ describe("thread outbox", () => { ).toBe("send"); }); + it("sends queued creations once connected and live, removing already-created ones", () => { + expect( + resolveThreadOutboxDeliveryAction({ + isCreation: true, + threadExists: false, + shellStatus: "cached", + environmentConnected: false, + threadBusy: false, + }), + ).toBe("wait"); + // Connected but not yet synchronized: a previously delivered creation may + // simply not be visible yet — sending now could duplicate the thread. + expect( + resolveThreadOutboxDeliveryAction({ + isCreation: true, + threadExists: false, + shellStatus: "synchronizing", + environmentConnected: true, + threadBusy: false, + }), + ).toBe("wait"); + expect( + resolveThreadOutboxDeliveryAction({ + isCreation: true, + threadExists: false, + shellStatus: "live", + environmentConnected: true, + threadBusy: false, + }), + ).toBe("send"); + expect( + resolveThreadOutboxDeliveryAction({ + isCreation: true, + threadExists: true, + shellStatus: "live", + environmentConnected: true, + threadBusy: true, + }), + ).toBe("remove"); + }); + + it("round-trips queued creations and gates incomplete ones from sending", () => { + const base = queuedMessage({ + messageId: "message-1", + createdAt: "2026-06-08T10:00:01.000Z", + }); + const creationMessage = { + ...base, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + }, + creation: { + projectId: ProjectId.make("project-1"), + workspaceMode: "worktree", + branch: "main", + worktreePath: null, + startFromOrigin: true, + }, + } satisfies QueuedThreadMessage; + + expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(creationMessage))).toEqual( + creationMessage, + ); + expect(isQueuedThreadCreationSendable(creationMessage)).toBe(true); + expect( + isQueuedThreadCreationSendable({ + ...creationMessage, + creation: { ...creationMessage.creation, branch: null }, + }), + ).toBe(false); + expect( + isQueuedThreadCreationSendable({ + ...creationMessage, + creation: { ...creationMessage.creation, branch: "" }, + }), + ).toBe(false); + expect(isQueuedThreadCreationSendable({ ...creationMessage, modelSelection: undefined })).toBe( + false, + ); + expect(isQueuedThreadCreationSendable(base)).toBe(false); + }); + it("retries transport failures but drops deterministic command failures", () => { expect(shouldRetryThreadOutboxDelivery(new Error("Socket is not connected"))).toBe(true); expect( diff --git a/apps/mobile/src/state/thread-outbox.ts b/apps/mobile/src/state/thread-outbox.ts index d5eb383a0e..a089c49732 100644 --- a/apps/mobile/src/state/thread-outbox.ts +++ b/apps/mobile/src/state/thread-outbox.ts @@ -20,6 +20,11 @@ export function enqueueThreadOutboxMessage(message: QueuedThreadMessage): Promis return threadOutboxManager.enqueue(message); } +/** Rewrite a queued message; no-op (false) if it was removed in the meantime. */ +export function updateThreadOutboxMessage(message: QueuedThreadMessage): Promise { + return threadOutboxManager.update(message); +} + export function removeThreadOutboxMessage(message: QueuedThreadMessage): Promise { return threadOutboxManager.remove(message); } diff --git a/apps/mobile/src/state/thread-pr-presentation.ts b/apps/mobile/src/state/thread-pr-presentation.ts new file mode 100644 index 0000000000..601e29fa44 --- /dev/null +++ b/apps/mobile/src/state/thread-pr-presentation.ts @@ -0,0 +1,36 @@ +import type { VcsStatusResult } from "@t3tools/contracts"; +import { resolveChangeRequestPresentation } from "@t3tools/shared/sourceControl"; + +export type ThreadPr = NonNullable; + +export interface ThreadPrPresentation { + readonly number: number; + readonly state: ThreadPr["state"]; + readonly url: string; + /** Compact pull request number label, e.g. "3774". */ + readonly label: string; + /** Full, provider-aware label for assistive technologies. */ + readonly accessibilityLabel: string; + readonly textClassName: string; +} + +const PR_STATE_TEXT_CLASS: Record = { + open: "text-emerald-600 dark:text-emerald-400", + merged: "text-violet-600 dark:text-violet-400", + closed: "text-zinc-500 dark:text-zinc-400", +}; + +export function presentThreadPr( + pr: ThreadPr, + provider: VcsStatusResult["sourceControlProvider"] | null | undefined, +): ThreadPrPresentation { + const presentation = resolveChangeRequestPresentation(provider); + return { + number: pr.number, + state: pr.state, + url: pr.url, + label: String(pr.number), + accessibilityLabel: `#${pr.number} ${presentation.longName} ${pr.state}`, + textClassName: PR_STATE_TEXT_CLASS[pr.state], + }; +} diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index d02abb6a26..fdabe67bc7 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -8,7 +8,9 @@ import { decodePersistedComposerDrafts, type ComposerDraft, getComposerDraftSnapshot, + mergeComposerDraftContentState, removeComposerDraftsForEnvironment, + restoreComposerDraftSnapshotState, } from "./use-composer-drafts"; const DRAFT: ComposerDraft = { @@ -94,6 +96,7 @@ describe("mobile composer drafts", () => { const draft: ComposerDraft = { text: "send this", attachments: [], + importedShareIds: ["share-1"], modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", @@ -108,7 +111,8 @@ describe("mobile composer drafts", () => { expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({ [draftKey]: { - ...draft, + modelSelection: draft.modelSelection, + workspaceSelection: draft.workspaceSelection, text: "", attachments: [], }, @@ -131,6 +135,90 @@ describe("mobile composer drafts", () => { expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft); }); + it("merges shared content into a project draft without duplicating retries", () => { + const draftKey = "new-task:environment-1:project-1"; + const sharedAttachment = { + id: "share-1:image:0", + type: "image" as const, + name: "Screenshot.png", + mimeType: "image/png", + sizeBytes: 3, + dataUrl: "data:image/png;base64,YWJj", + previewUri: "data:image/png;base64,YWJj", + }; + const existing: Record = { + [draftKey]: { text: "Existing context", attachments: [] }, + }; + const content = { + text: "Shared note", + attachments: [sharedAttachment], + sourceShareId: "share-1", + }; + + const merged = mergeComposerDraftContentState(existing, draftKey, content); + expect(merged[draftKey]).toMatchObject({ + text: "Existing context\n\nShared note", + attachments: [sharedAttachment], + importedShareIds: ["share-1"], + }); + expect(mergeComposerDraftContentState(merged, draftKey, content)).toBe(merged); + + const edited = { + ...merged, + [draftKey]: { ...merged[draftKey]!, text: "User edited the imported context" }, + }; + expect(mergeComposerDraftContentState(edited, draftKey, content)).toBe(edited); + }); + + it("preserves existing images when shared content exceeds the draft attachment limit", () => { + const draftKey = "new-task:environment-1:project-1"; + const image = (id: string) => ({ + id, + type: "image" as const, + name: `${id}.png`, + mimeType: "image/png", + sizeBytes: 3, + dataUrl: "data:image/png;base64,YWJj", + previewUri: "data:image/png;base64,YWJj", + }); + const existingImage = image("existing"); + const sharedImages = Array.from({ length: 8 }, (_, index) => image(`shared-${index}`)); + + const merged = mergeComposerDraftContentState( + { [draftKey]: { text: "", attachments: [existingImage] } }, + draftKey, + { text: "", attachments: sharedImages }, + ); + + expect(merged[draftKey]?.attachments).toHaveLength(8); + expect(merged[draftKey]?.attachments[0]).toEqual(existingImage); + expect(merged[draftKey]?.attachments.at(-1)?.id).toBe("shared-6"); + }); + + it("restores the exact draft captured before an interrupted share import", () => { + const draftKey = "new-task:environment-1:project-1"; + const beforeImport: ComposerDraft = { + text: "Existing context", + attachments: [], + runtimeMode: "approval-required", + }; + const imported: ComposerDraft = { + ...beforeImport, + text: "Existing context\n\nShared note", + importedShareIds: ["share-1"], + }; + + expect( + restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, beforeImport), + ).toEqual({ [draftKey]: beforeImport }); + expect( + restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, { + text: "", + attachments: [], + }), + ).toEqual({}); + }); + it("removes only drafts owned by the selected environment", () => { const environmentId = EnvironmentId.make("environment-cloud"); const retainedEnvironmentId = EnvironmentId.make("environment-local"); diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 9e2c156619..cdef999e04 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -1,6 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; import { ModelSelection as ModelSelectionSchema, + PROVIDER_SEND_TURN_MAX_ATTACHMENTS, ProviderInteractionMode as ProviderInteractionModeSchema, RuntimeMode as RuntimeModeSchema, type EnvironmentId, @@ -14,6 +15,7 @@ import { Atom } from "effect/unstable/reactivity"; import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema"; import type { DraftComposerImageAttachment } from "../lib/composerImages"; +import { SerializedAsyncQueue } from "../lib/serialized-async-queue"; import { appAtomRegistry } from "./atom-registry"; const COMPOSER_DRAFTS_SCHEMA_VERSION = 1; @@ -38,16 +40,24 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass; + readonly importedShareIds?: ReadonlyArray; readonly modelSelection?: ModelSelection; readonly runtimeMode?: RuntimeMode; readonly interactionMode?: ProviderInteractionMode; readonly workspaceSelection?: ComposerDraftWorkspaceSelection; } +export interface ComposerDraftContent { + readonly text: string; + readonly attachments: ReadonlyArray; + readonly sourceShareId?: string; +} + export interface ComposerDraftWorkspaceSelection { readonly mode: "local" | "worktree"; readonly branch: string | null; readonly worktreePath: string | null; + readonly startFromOrigin?: boolean; } export type ComposerDraftSettingsUpdate = Pick< @@ -59,11 +69,13 @@ const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({ mode: Schema.Literals(["local", "worktree"]), branch: Schema.NullOr(Schema.String), worktreePath: Schema.NullOr(Schema.String), + startFromOrigin: Schema.optional(Schema.Boolean), }); const ComposerDraftSchema = Schema.Struct({ text: Schema.String, attachments: Schema.Array(DraftComposerImageAttachmentSchema), + importedShareIds: Schema.optional(Schema.Array(Schema.String)), modelSelection: Schema.optional(ModelSelectionSchema), runtimeMode: Schema.optional(RuntimeModeSchema), interactionMode: Schema.optional(ProviderInteractionModeSchema), @@ -91,6 +103,7 @@ export const composerDraftsAtom = Atom.make>({}).p let loadPromise: Promise | null = null; let persistTimer: ReturnType | null = null; +const persistenceQueue = new SerializedAsyncQueue(); function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft { if (!draft) { @@ -107,6 +120,10 @@ export function getComposerDraftSnapshot(draftKey: string): ComposerDraft { return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]); } +export function isComposerDraftEmpty(draft: ComposerDraft): boolean { + return isEmptyDraft(draft); +} + function isEmptyDraft(draft: ComposerDraft): boolean { return ( draft.text.length === 0 && @@ -187,7 +204,7 @@ async function writePersistedComposerDrafts(drafts: Record): Promise { try { - await writePersistedComposerDrafts(drafts); + await persistenceQueue.run(() => writePersistedComposerDrafts(drafts)); } catch (error) { console.warn("[composer-drafts] failed to persist drafts", error); // Draft persistence is best-effort; in-memory drafts still keep working. @@ -360,8 +377,9 @@ export function clearComposerDraftContentState( if (!existing) { return current; } + const { importedShareIds: _importedShareIds, ...retained } = existing; const draft = { - ...existing, + ...retained, text: "", attachments: [], }; @@ -376,6 +394,138 @@ export function clearComposerDraftContentState( }; } +export function restoreComposerDraftSnapshotState( + current: Record, + draftKey: string, + snapshot: ComposerDraft, +): Record { + const next = { ...current }; + if (isEmptyDraft(snapshot)) { + delete next[draftKey]; + } else { + next[draftKey] = snapshot; + } + return next; +} + +function mergeComposerDraftText(existing: string, incoming: string): string { + if (incoming.length === 0) { + return existing; + } + if (existing.length === 0) { + return incoming; + } + // Import retries are possible after an interrupted native handoff. Keep the + // operation idempotent when the same shared text is already present. + if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) { + return existing; + } + return `${existing}\n\n${incoming}`; +} + +export function mergeComposerDraftContentState( + current: Record, + draftKey: string, + content: ComposerDraftContent, +): Record { + const existing = normalizeDraft(current[draftKey]); + if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) { + return current; + } + const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id)); + const incomingAttachments = content.attachments.filter((attachment) => { + if (attachmentIds.has(attachment.id)) { + return false; + } + attachmentIds.add(attachment.id); + return true; + }); + const attachments = [...existing.attachments, ...incomingAttachments].slice( + 0, + PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + ); + const text = mergeComposerDraftText(existing.text, content.text); + const importedShareIds = content.sourceShareId + ? [...(existing.importedShareIds ?? []), content.sourceShareId] + : existing.importedShareIds; + if ( + text === existing.text && + attachments.length === existing.attachments.length && + importedShareIds === existing.importedShareIds + ) { + return current; + } + return { + ...current, + [draftKey]: { + ...existing, + text, + attachments, + ...(importedShareIds ? { importedShareIds } : {}), + }, + }; +} + +/** + * Atomically moves an incoming share into a project-scoped composer draft. + * The durable write happens before the share inbox item can be acknowledged. + */ +export async function mergeComposerDraftContent( + draftKey: string, + content: ComposerDraftContent, +): Promise<{ readonly skippedAttachmentCount: number }> { + ensureComposerDraftsLoaded(); + if (loadPromise !== null) { + await loadPromise; + } + if (persistTimer !== null) { + clearTimeout(persistTimer); + persistTimer = null; + } + const current = appAtomRegistry.get(composerDraftsAtom); + const next = mergeComposerDraftContentState(current, draftKey, content); + const currentAttachmentIds = new Set( + normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id), + ); + const nextAttachmentIds = new Set( + normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id), + ); + const skippedAttachmentCount = content.attachments.filter( + (attachment) => + !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id), + ).length; + // Publish the content and its import receipt together before the filesystem + // await. Typing during persistence then builds on the receipt-bearing state, + // and its debounced write is serialized after this transaction. + if (next !== current) { + appAtomRegistry.set(composerDraftsAtom, next); + } + await persistenceQueue.run(() => writePersistedComposerDrafts(next)); + return { skippedAttachmentCount }; +} + +/** Restores the exact content/settings captured before an interrupted import. */ +export async function restoreComposerDraftSnapshot( + draftKey: string, + snapshot: ComposerDraft, +): Promise { + ensureComposerDraftsLoaded(); + if (loadPromise !== null) { + await loadPromise; + } + if (persistTimer !== null) { + clearTimeout(persistTimer); + persistTimer = null; + } + const next = restoreComposerDraftSnapshotState( + appAtomRegistry.get(composerDraftsAtom), + draftKey, + snapshot, + ); + appAtomRegistry.set(composerDraftsAtom, next); + await persistenceQueue.run(() => writePersistedComposerDrafts(next)); +} + export function clearComposerDraftContent(draftKey: string): void { updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey)); } diff --git a/apps/mobile/src/state/use-pending-new-tasks.ts b/apps/mobile/src/state/use-pending-new-tasks.ts new file mode 100644 index 0000000000..ccfe1527b3 --- /dev/null +++ b/apps/mobile/src/state/use-pending-new-tasks.ts @@ -0,0 +1,35 @@ +import { useMemo } from "react"; + +import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn"; +import { + flattenQueuedThreadMessages, + type QueuedThreadCreation, + type QueuedThreadMessage, +} from "./thread-outbox-model"; +import { useThreadOutboxMessages } from "./use-thread-outbox"; + +/** A queued new-task creation, shaped for thread-list presentation. */ +export interface PendingNewTask { + readonly message: QueuedThreadMessage; + readonly creation: QueuedThreadCreation; + readonly title: string; +} + +export function usePendingNewTasks(): ReadonlyArray { + const queuedMessagesByThreadKey = useThreadOutboxMessages(); + return useMemo(() => { + const tasks: PendingNewTask[] = []; + for (const message of flattenQueuedThreadMessages(queuedMessagesByThreadKey)) { + if (!message.creation) { + continue; + } + tasks.push({ + message, + creation: message.creation, + title: deriveThreadTitleFromPrompt(message.text), + }); + } + tasks.sort((left, right) => right.message.createdAt.localeCompare(left.message.createdAt)); + return tasks; + }, [queuedMessagesByThreadKey]); +} diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/use-thread-outbox-drain.ts index a8cfc2b1e6..20eda74731 100644 --- a/apps/mobile/src/state/use-thread-outbox-drain.ts +++ b/apps/mobile/src/state/use-thread-outbox-drain.ts @@ -1,30 +1,46 @@ import { useAtomValue } from "@effect/atom-react"; import { threadRuntimeIsActive, + type EnvironmentProject, type EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; -import { CommandId, type MessageId } from "@t3tools/contracts"; +import { + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + DEFAULT_RUNTIME_MODE, + type MessageId, +} from "@t3tools/contracts"; +import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git"; import * as Cause from "effect/Cause"; import { AsyncResult, Atom } from "effect/unstable/reactivity"; import { useCallback, useEffect, useRef, useState } from "react"; import { scopedThreadKey } from "../lib/scopedEntities"; +import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn"; +import { toUploadChatImageAttachments } from "../lib/composerImages"; +import { randomHex } from "../lib/uuid"; import { appAtomRegistry } from "./atom-registry"; -import { useThreadShells } from "./entities"; +import { useProjects, useThreadShells } from "./entities"; import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox"; import { + isQueuedThreadCreationSendable, modelSelectionsEqual, resolveThreadOutboxDeliveryAction, resolveThreadOutboxFailureAction, resolveQueuedThreadSettings, threadOutboxRetryDelayMs, + type QueuedThreadCreation, type QueuedThreadMessage, type ThreadOutboxCommandStage, } from "./thread-outbox-model"; import { threadEnvironment } from "./threads"; import { useAtomCommand } from "./use-atom-command"; -import { useThreadOutboxMessages, useThreadOutboxShellStatuses } from "./use-thread-outbox"; +import { + editingQueuedMessageIdsAtom, + useThreadOutboxMessages, + useThreadOutboxShellStatuses, +} from "./use-thread-outbox"; import { useRemoteConnectionStatus } from "./use-remote-environment-registry"; export const dispatchingQueuedMessageIdAtom = Atom.make(null).pipe( @@ -51,6 +67,17 @@ function findThread( ); } +function findCreationProject( + projects: ReadonlyArray, + message: QueuedThreadMessage, +): EnvironmentProject | undefined { + return projects.find( + (candidate) => + candidate.environmentId === message.environmentId && + candidate.id === message.creation?.projectId, + ); +} + function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId { return CommandId.make(`${message.commandId}:${setting}`); } @@ -67,9 +94,11 @@ export function useThreadOutboxDrain(): void { reportFailure: false, }); const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom); + const editingQueuedMessageIds = useAtomValue(editingQueuedMessageIdsAtom); const queuedMessagesByThreadKey = useThreadOutboxMessages(); const shellStatuses = useThreadOutboxShellStatuses(); const threads = useThreadShells(); + const projects = useProjects(); const { connectedEnvironments } = useRemoteConnectionStatus(); const [retryTick, setRetryTick] = useState(0); const retryAttemptRef = useRef(new Map()); @@ -86,52 +115,57 @@ export function useThreadOutboxDrain(): void { }; }, []); - const sendQueuedMessage = useCallback( - async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => { - const settings = resolveQueuedThreadSettings(queuedMessage, thread); - const reportFailure = ( - commandResult: AtomCommandResult, - stage: ThreadOutboxCommandStage, - ): boolean => { - if (!AsyncResult.isFailure(commandResult)) { - return false; - } - const action = resolveThreadOutboxFailureAction({ - stage, - error: Cause.squash(commandResult.cause), - interrupted: Cause.hasInterruptsOnly(commandResult.cause), - }); - const retry = action === "retry"; - console.warn("[thread-outbox] queued message delivery failed", { + const makeDeliveryHelpers = useCallback((queuedMessage: QueuedThreadMessage) => { + const reportFailure = ( + commandResult: AtomCommandResult, + stage: ThreadOutboxCommandStage, + ): boolean => { + if (!AsyncResult.isFailure(commandResult)) { + return false; + } + const action = resolveThreadOutboxFailureAction({ + stage, + error: Cause.squash(commandResult.cause), + interrupted: Cause.hasInterruptsOnly(commandResult.cause), + }); + const retry = action === "retry"; + console.warn("[thread-outbox] queued message delivery failed", { + environmentId: queuedMessage.environmentId, + threadId: queuedMessage.threadId, + messageId: queuedMessage.messageId, + stage, + cause: commandResult.cause, + retry, + }); + return retry; + }; + const completeDelivery = async ( + deliveryResult: AtomCommandResult, + ): Promise => { + if (reportFailure(deliveryResult, "start-turn")) { + return false; + } + + try { + await removeThreadOutboxMessage(queuedMessage); + return true; + } catch (error) { + console.warn("[thread-outbox] failed to remove delivered queued message", { environmentId: queuedMessage.environmentId, threadId: queuedMessage.threadId, messageId: queuedMessage.messageId, - stage, - cause: commandResult.cause, - retry, + error, }); - return retry; - }; - const completeDelivery = async ( - deliveryResult: AtomCommandResult, - ): Promise => { - if (reportFailure(deliveryResult, "start-turn")) { - return false; - } + return false; + } + }; + return { reportFailure, completeDelivery }; + }, []); - try { - await removeThreadOutboxMessage(queuedMessage); - return true; - } catch (error) { - console.warn("[thread-outbox] failed to remove delivered queued message", { - environmentId: queuedMessage.environmentId, - threadId: queuedMessage.threadId, - messageId: queuedMessage.messageId, - error, - }); - return false; - } - }; + const sendQueuedMessage = useCallback( + async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => { + const settings = resolveQueuedThreadSettings(queuedMessage, thread); + const { reportFailure, completeDelivery } = makeDeliveryHelpers(queuedMessage); if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) { const updateResult = await updateThreadMetadata({ @@ -190,7 +224,7 @@ export function useThreadOutboxDrain(): void { messageId: queuedMessage.messageId, role: "user", text: queuedMessage.text, - attachments: queuedMessage.attachments, + attachments: toUploadChatImageAttachments(queuedMessage.attachments), }, modelSelection: settings.modelSelection, runtimeMode: settings.runtimeMode, @@ -200,7 +234,50 @@ export function useThreadOutboxDrain(): void { }); return completeDelivery(deliveryResult); }, - [setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata], + [ + makeDeliveryHelpers, + setThreadInteractionMode, + setThreadRuntimeMode, + startTurn, + updateThreadMetadata, + ], + ); + + const sendQueuedCreation = useCallback( + async ( + queuedMessage: QueuedThreadMessage, + creation: QueuedThreadCreation, + projectCwd: string, + ) => { + const modelSelection = queuedMessage.modelSelection; + if (modelSelection === undefined) { + return false; + } + const { completeDelivery } = makeDeliveryHelpers(queuedMessage); + const deliveryResult = await startTurn({ + environmentId: queuedMessage.environmentId, + input: buildProjectThreadStartTurnInput({ + projectId: creation.projectId, + projectCwd, + threadId: queuedMessage.threadId, + commandId: queuedMessage.commandId, + messageId: queuedMessage.messageId, + createdAt: queuedMessage.createdAt, + text: queuedMessage.text.trim(), + attachments: queuedMessage.attachments, + modelSelection, + runtimeMode: queuedMessage.runtimeMode ?? DEFAULT_RUNTIME_MODE, + interactionMode: queuedMessage.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE, + workspaceMode: creation.workspaceMode, + branch: creation.branch, + worktreePath: creation.worktreePath, + startFromOrigin: creation.startFromOrigin ?? false, + worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex), + }), + }); + return completeDelivery(deliveryResult); + }, + [makeDeliveryHelpers, startTurn], ); useEffect(() => { @@ -213,6 +290,9 @@ export function useThreadOutboxDrain(): void { if (!nextQueuedMessage) { continue; } + if (editingQueuedMessageIds[nextQueuedMessage.messageId]) { + continue; + } if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) { continue; } @@ -222,37 +302,65 @@ export function useThreadOutboxDrain(): void { continue; } + const creation = nextQueuedMessage.creation; const environment = connectedEnvironments.find( (candidate) => candidate.environmentId === nextQueuedMessage.environmentId, ); + const shellStatus = shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty"; const deliveryAction = resolveThreadOutboxDeliveryAction({ + isCreation: creation !== undefined, threadExists: thread !== undefined, - shellStatus: shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty", + shellStatus, environmentConnected: environment?.connectionState === "connected", threadBusy: threadRuntimeIsActive(thread?.runtime), }); if (deliveryAction === "wait") { continue; } + // The live project shell is preferred for the workspace path, with the + // snapshot taken at enqueue time as the fallback so a task never dies + // just because its project shell is not loaded. + const creationProjectCwd = + creation !== undefined + ? (findCreationProject(projects, nextQueuedMessage)?.workspaceRoot ?? + creation.projectCwd ?? + null) + : null; + // An incomplete pending task (e.g. worktree mode without a branch) stays + // queued until the user finishes it in the editor. + if (deliveryAction === "send" && creation !== undefined) { + if (!isQueuedThreadCreationSendable(nextQueuedMessage)) { + continue; + } + if (creationProjectCwd === null && shellStatus !== "live") { + continue; + } + } beginDispatchingQueuedMessage(nextQueuedMessage.messageId); + const removeQueuedMessage = (warning: string) => + removeThreadOutboxMessage(nextQueuedMessage).then( + () => true, + (error) => { + console.warn(warning, { + environmentId: nextQueuedMessage.environmentId, + threadId: nextQueuedMessage.threadId, + messageId: nextQueuedMessage.messageId, + error, + }); + return false; + }, + ); const delivery = deliveryAction === "remove" - ? removeThreadOutboxMessage(nextQueuedMessage).then( - () => true, - (error) => { - console.warn("[thread-outbox] failed to remove message for a missing thread", { - environmentId: nextQueuedMessage.environmentId, - threadId: nextQueuedMessage.threadId, - messageId: nextQueuedMessage.messageId, - error, - }); - return false; - }, - ) - : thread !== undefined - ? sendQueuedMessage(nextQueuedMessage, thread) - : Promise.resolve(false); + ? removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread") + : creation !== undefined + ? creationProjectCwd !== null + ? sendQueuedCreation(nextQueuedMessage, creation, creationProjectCwd) + : removeQueuedMessage("[thread-outbox] dropped pending task for a missing project") + : thread !== undefined + ? sendQueuedMessage(nextQueuedMessage, thread) + : Promise.resolve(false); void delivery .then((sent) => { if (sent) { @@ -288,8 +396,11 @@ export function useThreadOutboxDrain(): void { }, [ connectedEnvironments, dispatchingQueuedMessageId, + editingQueuedMessageIds, + projects, queuedMessagesByThreadKey, retryTick, + sendQueuedCreation, sendQueuedMessage, shellStatuses, threads, diff --git a/apps/mobile/src/state/use-thread-outbox.ts b/apps/mobile/src/state/use-thread-outbox.ts index fb090cd088..542c2d401c 100644 --- a/apps/mobile/src/state/use-thread-outbox.ts +++ b/apps/mobile/src/state/use-thread-outbox.ts @@ -1,8 +1,9 @@ import { useAtomValue } from "@effect/atom-react"; import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell"; -import type { EnvironmentId } from "@t3tools/contracts"; +import type { EnvironmentId, MessageId } from "@t3tools/contracts"; import { Atom } from "effect/unstable/reactivity"; +import { appAtomRegistry } from "./atom-registry"; import { environmentShell } from "./shell"; import { threadOutboxManager } from "./thread-outbox"; @@ -19,6 +20,35 @@ const threadOutboxShellStatusesAtom = Atom.make( }, ).pipe(Atom.withLabel("mobile:thread-outbox:shell-statuses")); +/** + * Queued pending tasks the outbox drain must not deliver right now: the one + * open in the new-task editor, plus any whose latest edits could not be saved + * back yet (delivering those would send stale content). Editing sessions hold + * their message id here and release it once the queued payload is current. + */ +export const editingQueuedMessageIdsAtom = Atom.make>>({}).pipe( + Atom.keepAlive, + Atom.withLabel("mobile:thread-outbox:editing-message-ids"), +); + +export function holdEditingQueuedMessage(messageId: MessageId): void { + const current = appAtomRegistry.get(editingQueuedMessageIdsAtom); + if (current[messageId]) { + return; + } + appAtomRegistry.set(editingQueuedMessageIdsAtom, { ...current, [messageId]: true }); +} + +export function releaseEditingQueuedMessage(messageId: MessageId): void { + const current = appAtomRegistry.get(editingQueuedMessageIdsAtom); + if (!current[messageId]) { + return; + } + const next = { ...current }; + delete next[messageId]; + appAtomRegistry.set(editingQueuedMessageIdsAtom, next); +} + export function useThreadOutboxMessages() { return useAtomValue(threadOutboxManager.queuedMessagesByThreadKeyAtom); } diff --git a/apps/mobile/src/state/use-thread-pr.test.ts b/apps/mobile/src/state/use-thread-pr.test.ts new file mode 100644 index 0000000000..a355dddcd4 --- /dev/null +++ b/apps/mobile/src/state/use-thread-pr.test.ts @@ -0,0 +1,36 @@ +import type { VcsStatusResult } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { presentThreadPr } from "./thread-pr-presentation"; + +const pullRequest: NonNullable = { + number: 3774, + title: "Desktop-style pull request indicator", + url: "https://github.com/t3tools/t3code/pull/3774", + baseRef: "main", + headRef: "codex/desktop-style-pr-indicator", + state: "merged", +}; + +describe("presentThreadPr", () => { + it("uses the compact pull request number label without a hash prefix", () => { + expect(presentThreadPr(pullRequest, undefined)).toMatchObject({ + label: "3774", + accessibilityLabel: "#3774 pull request merged", + textClassName: "text-violet-600 dark:text-violet-400", + }); + }); + + it("uses merge-request terminology for GitLab", () => { + expect( + presentThreadPr(pullRequest, { + kind: "gitlab", + name: "GitLab", + baseUrl: "https://gitlab.com", + }), + ).toMatchObject({ + label: "3774", + accessibilityLabel: "#3774 merge request merged", + }); + }); +}); diff --git a/apps/mobile/src/state/use-thread-pr.ts b/apps/mobile/src/state/use-thread-pr.ts new file mode 100644 index 0000000000..a3440cd484 --- /dev/null +++ b/apps/mobile/src/state/use-thread-pr.ts @@ -0,0 +1,41 @@ +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; + +import { useEnvironmentQuery } from "./query"; +import { presentThreadPr, type ThreadPrPresentation } from "./thread-pr-presentation"; +import { vcsEnvironment } from "./vcs"; + +export { + presentThreadPr, + type ThreadPr, + type ThreadPrPresentation, +} from "./thread-pr-presentation"; + +/** + * Live PR status for a thread's branch. Subscriptions are deduplicated per + * (environmentId, cwd) by the atom family, so many rows on the same worktree + * or project root share one stream — and virtualization means only visible + * rows subscribe at all. + */ +export function useThreadPr( + thread: EnvironmentThreadShell, + projectCwd: string | null, +): ThreadPrPresentation | null { + const cwd = thread.worktreePath ?? projectCwd; + const gitStatus = useEnvironmentQuery( + thread.branch !== null && cwd !== null + ? vcsEnvironment.status({ + environmentId: thread.environmentId, + input: { cwd }, + }) + : null, + ); + + const status = gitStatus.data; + if (status === null || thread.branch === null || status.refName !== thread.branch) { + return null; + } + if (!status.pr) { + return null; + } + return presentThreadPr(status.pr, status.sourceControlProvider); +} diff --git a/apps/mobile/src/state/use-thread-selection.ts b/apps/mobile/src/state/use-thread-selection.ts index 06175b6d23..524540ad83 100644 --- a/apps/mobile/src/state/use-thread-selection.ts +++ b/apps/mobile/src/state/use-thread-selection.ts @@ -1,12 +1,29 @@ -import { useLocalSearchParams } from "expo-router"; -import { useMemo } from "react"; -import { EnvironmentId, ThreadId, type ScopedProjectRef } from "@t3tools/contracts"; +import { useRoute, type RouteProp } from "@react-navigation/native"; +import { useMemo, useRef } from "react"; +import { + EnvironmentId, + ThreadId, + type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadShell, + type ScopedProjectRef, + type ScopedThreadRef, +} from "@t3tools/contracts"; +import { + presentThreadShell, + type EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; +import * as Option from "effect/Option"; import { useProject, useThreadShell } from "../state/entities"; +import { useEnvironmentThread } from "../state/threads"; import { useRemoteEnvironmentRuntime, useSavedRemoteConnection, } from "./use-remote-environment-registry"; +type ThreadSelectionRouteParams = { + readonly environmentId?: string | string[]; + readonly threadId?: string | string[]; +}; function firstRouteParam(value: string | string[] | undefined): string | null { if (Array.isArray(value)) { @@ -16,14 +33,81 @@ function firstRouteParam(value: string | string[] | undefined): string | null { return value ?? null; } -export function useThreadSelection() { - const params = useLocalSearchParams<{ - environmentId?: string | string[]; - threadId?: string | string[]; - }>(); - const selectedThreadRef = useMemo(() => { - const environmentId = firstRouteParam(params.environmentId); - const threadId = firstRouteParam(params.threadId); +function latestUserMessageAt( + projection: OrchestrationV2ThreadProjection, +): OrchestrationV2ThreadShell["latestUserMessageAt"] { + for (let index = projection.messages.length - 1; index >= 0; index -= 1) { + const message = projection.messages[index]; + if (message?.role === "user") { + return message.createdAt; + } + } + + return null; +} + +/** + * Builds an optimistic thread shell from the detail projection for the window + * where the shell list has not materialized the thread yet (e.g. a thread that + * was just created from this device). + */ +function threadDetailToShell( + environmentId: EnvironmentId, + projection: OrchestrationV2ThreadProjection, +): EnvironmentThreadShell { + const thread = projection.thread; + const runsByOrdinal = projection.runs.toSorted((left, right) => right.ordinal - left.ordinal); + const latestRun = runsByOrdinal[0] ?? null; + const activeRun = + runsByOrdinal.find( + (run) => + run.status === "preparing" || + run.status === "queued" || + run.status === "starting" || + run.status === "running" || + run.status === "waiting", + ) ?? null; + const pendingRequest = + projection.runtimeRequests.find((request) => request.status === "pending") ?? null; + return presentThreadShell(environmentId, { + id: thread.id, + projectId: thread.projectId, + title: thread.title, + providerInstanceId: thread.providerInstanceId, + modelSelection: thread.modelSelection, + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + branch: thread.branch, + worktreePath: thread.worktreePath, + activeProviderThreadId: thread.activeProviderThreadId, + lineage: thread.lineage, + forkedFrom: thread.forkedFrom, + createdBy: thread.createdBy, + creationSource: thread.creationSource, + latestRunId: latestRun?.id ?? null, + activeRunId: activeRun?.id ?? null, + status: activeRun?.status ?? latestRun?.status ?? "idle", + pendingRuntimeRequest: + pendingRequest === null + ? null + : { id: pendingRequest.id, kind: pendingRequest.kind, createdAt: pendingRequest.createdAt }, + latestVisibleMessage: null, + latestUserMessageAt: latestUserMessageAt(projection), + hasActionableProposedPlan: false, + itemCount: projection.turnItems.length, + visibleItemCount: projection.visibleTurnItems.length, + createdAt: thread.createdAt, + updatedAt: thread.updatedAt, + archivedAt: thread.archivedAt, + deletedAt: thread.deletedAt, + }); +} + +function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) { + const routeParams = params ?? {}; + const routeThreadRef = useMemo(() => { + const environmentId = firstRouteParam(routeParams.environmentId); + const threadId = firstRouteParam(routeParams.threadId); if (!environmentId || !threadId) { return null; } @@ -32,8 +116,26 @@ export function useThreadSelection() { environmentId: EnvironmentId.make(environmentId), threadId: ThreadId.make(threadId), }; - }, [params.environmentId, params.threadId]); - const selectedThread = useThreadShell(selectedThreadRef); + }, [routeParams.environmentId, routeParams.threadId]); + const lastRouteThreadRef = useRef(null); + if (routeThreadRef !== null) { + lastRouteThreadRef.current = routeThreadRef; + } + const selectedThreadRef = routeThreadRef ?? lastRouteThreadRef.current; + const selectedThreadShell = useThreadShell(selectedThreadRef); + const selectedThreadDetailState = useEnvironmentThread( + selectedThreadRef?.environmentId ?? null, + selectedThreadRef?.threadId ?? null, + ); + const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data); + const selectedThread = useMemo( + () => + selectedThreadShell ?? + (selectedThreadRef !== null && selectedThreadDetail !== null + ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail) + : null), + [selectedThreadDetail, selectedThreadRef, selectedThreadShell], + ); const selectedProjectRef = useMemo( () => selectedThread === null @@ -49,11 +151,27 @@ export function useThreadSelection() { const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId); const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId); - return { - selectedThreadRef, - selectedThread, - selectedThreadProject, - selectedEnvironmentConnection, - selectedEnvironmentRuntime, - }; + return useMemo( + () => ({ + selectedThreadRef, + selectedThread, + selectedThreadProject, + selectedEnvironmentConnection, + selectedEnvironmentRuntime, + }), + [ + selectedEnvironmentConnection, + selectedEnvironmentRuntime, + selectedThread, + selectedThreadProject, + selectedThreadRef, + ], + ); +} + +type ThreadSelectionState = ReturnType; + +export function useThreadSelection(): ThreadSelectionState { + const route = useRoute>>(); + return useResolvedThreadSelection(route.params); } diff --git a/apps/mobile/src/widgets/AgentActivity.test.ts b/apps/mobile/src/widgets/AgentActivity.test.ts index 719e39554f..dc9cd0e221 100644 --- a/apps/mobile/src/widgets/AgentActivity.test.ts +++ b/apps/mobile/src/widgets/AgentActivity.test.ts @@ -2,23 +2,48 @@ import { describe, expect, it, vi } from "vite-plus/test"; vi.mock("@expo/ui/swift-ui", () => ({ HStack: "HStack", + Image: "Image", Spacer: "Spacer", Text: "Text", VStack: "VStack", + ZStack: "ZStack", })); vi.mock("@expo/ui/swift-ui/modifiers", () => ({ font: (value: unknown) => value, foregroundStyle: (value: unknown) => value, + frame: (value: unknown) => value, + layoutPriority: (value: unknown) => value, lineLimit: (value: unknown) => value, padding: (value: unknown) => value, + resizable: (value: unknown) => value, + widgetURL: (value: unknown) => ({ widgetURL: value }), })); vi.mock("expo-widgets", () => ({ createLiveActivity: vi.fn((name: string, layout: unknown) => ({ layout, name })), })); -import { AgentActivity, type AgentActivityProps } from "./AgentActivity"; +import { + AgentActivity, + type AgentActivityProps, + type AgentActivityRowProps, +} from "./AgentActivity"; + +function makeRow(overrides: Partial): AgentActivityRowProps { + return { + environmentId: "env-1", + threadId: "thread-1", + projectTitle: "Project", + threadTitle: "Thread", + modelTitle: "gpt-5.4", + phase: "running", + status: "Working", + updatedAt: "2026-05-25T13:07:00.000Z", + deepLink: "/threads/env-1/thread-1", + ...overrides, + }; +} const props = { title: "T3 Code", @@ -33,17 +58,226 @@ const environment = { isLuminanceReduced: false, } as const; +const lightEnvironment = { + colorScheme: "light", + isLuminanceReduced: false, +} as const; + describe("AgentActivity widget layout", () => { - it("formats its updated-at label without app-runtime helper references", () => { - expect(JSON.stringify(AgentActivity(props, environment as never))).toContain( - '"children":["Updated ","1:07"]', + it("tints each row by its own phase using the web sidebar's dark palette", () => { + const layout = AgentActivity( + { + ...props, + activeCount: 2, + activities: [ + makeRow({}), + makeRow({ threadId: "thread-2", phase: "waiting_for_approval", status: "Approval" }), + ], + }, + environment as never, ); - expect(AgentActivity.toString()).not.toContain("formatAgentActivityUpdatedAtLabel"); + const banner = JSON.stringify(layout.banner); + expect(banner).toContain("#7dd3fc"); // sky-300: running + expect(banner).toContain("#fcd34d"); // amber-300: waiting_for_approval }); - it("uses now when the updated-at timestamp is malformed", () => { + it("switches to the web sidebar's light palette when the scheme is light", () => { + // macOS (iPhone Mirroring / Mac notification center) renders the activity + // on a light background; the dark-material palette is illegible there. + const layout = AgentActivity( + { + ...props, + activeCount: 2, + activities: [ + makeRow({}), + makeRow({ threadId: "thread-2", phase: "waiting_for_approval", status: "Approval" }), + ], + }, + lightEnvironment as never, + ); + const banner = JSON.stringify(layout.banner); + expect(banner).toContain("#0284c7"); // sky-600: running + expect(banner).toContain("#d97706"); // amber-600: waiting_for_approval + expect(banner).not.toContain("#7dd3fc"); + expect(banner).not.toContain("#fcd34d"); + }); + + it("orders rows attention-first in the banner", () => { + const layout = AgentActivity( + { + ...props, + activeCount: 2, + activities: [ + makeRow({ threadTitle: "Working thread" }), + makeRow({ + threadId: "thread-2", + threadTitle: "Blocked thread", + phase: "waiting_for_approval", + status: "Approval", + }), + ], + }, + environment as never, + ); + const banner = JSON.stringify(layout.banner); + expect(banner.indexOf("Blocked thread")).toBeGreaterThan(-1); + expect(banner.indexOf("Blocked thread")).toBeLessThan(banner.indexOf("Working thread")); + }); + + it("summarizes the attention count in the banner header", () => { + const layout = AgentActivity( + { + ...props, + activeCount: 3, + activities: [ + makeRow({}), + makeRow({ threadId: "thread-2", phase: "waiting_for_input", status: "Input" }), + ], + }, + environment as never, + ); + const banner = JSON.stringify(layout.banner); + expect(banner).toContain("3 active agents"); + expect(banner).toContain("1 needs attention"); + }); + + it("uses the attention tint for the compact presentations when a row needs input", () => { + const layout = AgentActivity( + { + ...props, + activeCount: 2, + activities: [ + makeRow({}), + makeRow({ threadId: "thread-2", phase: "waiting_for_input", status: "Input" }), + ], + }, + environment as never, + ); + expect(JSON.stringify(layout.compactLeading)).toContain("#a5b4fc"); // indigo-300 + expect(JSON.stringify(layout.compactTrailing)).toContain("Input"); + expect(JSON.stringify(layout.minimal)).toContain("#a5b4fc"); + }); + + it("deep links the banner to the row that needs attention", () => { + const layout = AgentActivity( + { + ...props, + activeCount: 2, + activities: [ + makeRow({}), + makeRow({ + threadId: "thread-2", + phase: "waiting_for_approval", + status: "Approval", + deepLink: "/threads/env-1/thread-2", + }), + ], + }, + environment as never, + ); + expect(JSON.stringify(layout.banner)).toContain( + '"widgetURL":"t3code://threads/env-1/thread-2"', + ); + }); + + it("deep links the banner to the first row when nothing needs attention", () => { + const layout = AgentActivity({ ...props, activities: [makeRow({})] }, environment as never); + expect(JSON.stringify(layout.banner)).toContain( + '"widgetURL":"t3code://threads/env-1/thread-1"', + ); + }); + + it("omits the deep link for unsafe paths and empty aggregates", () => { + expect(JSON.stringify(AgentActivity(props, environment as never))).not.toContain("widgetURL"); expect( - JSON.stringify(AgentActivity({ ...props, updatedAt: "not-a-date" }, environment as never)), - ).toContain('"children":["Updated ","now"]'); + JSON.stringify( + AgentActivity( + { ...props, activities: [makeRow({ deepLink: "//evil.example" })] }, + environment as never, + ), + ), + ).not.toContain("widgetURL"); + }); + + it("leads with the outcome instead of a zero count when nothing is active", () => { + const layout = AgentActivity( + { + ...props, + subtitle: "Agent work completed", + activeCount: 0, + activities: [makeRow({ phase: "completed", status: "Done" })], + }, + environment as never, + ); + const banner = JSON.stringify(layout.banner); + expect(banner).toContain("Agent work completed"); + expect(banner).not.toContain("0 active"); + expect(banner).toContain("#6ee7b7"); // emerald-300 header tint + expect(JSON.stringify(layout.compactTrailing)).toContain("Done"); + expect(JSON.stringify(layout.compactTrailing)).not.toContain("0 active"); + expect(JSON.stringify(layout.expandedLeading)).toContain("Done"); + expect(JSON.stringify(layout.minimal)).toContain("checkmark.circle.fill"); + expect(JSON.stringify(layout.bannerSmall)).toContain("Done"); + }); + + it("reads Failed when the finished work ended in failure", () => { + const layout = AgentActivity( + { + ...props, + subtitle: "Agent work failed", + activeCount: 0, + activities: [makeRow({ phase: "failed", status: "Failed" })], + }, + environment as never, + ); + const banner = JSON.stringify(layout.banner); + expect(banner).toContain("Agent work failed"); + expect(banner).toContain("#fca5a5"); // red-300 header tint + expect(JSON.stringify(layout.compactTrailing)).toContain("Failed"); + expect(JSON.stringify(layout.expandedLeading)).toContain("Failed"); + expect(JSON.stringify(layout.minimal)).toContain("xmark.octagon.fill"); + }); + + it("lets a failure dominate mixed finished outcomes across every presentation", () => { + const layout = AgentActivity( + { + ...props, + // The server subtitle keys off the newest terminal row (completed + // here); the layout must still read Failed everywhere so the header + // text never disagrees with the tint, count slots, or minimal glyph. + subtitle: "Agent work completed", + activeCount: 0, + activities: [ + makeRow({ phase: "completed", status: "Done" }), + makeRow({ threadId: "thread-2", phase: "failed", status: "Failed" }), + ], + }, + environment as never, + ); + const banner = JSON.stringify(layout.banner); + expect(banner).toContain("Agent work failed"); + expect(banner).not.toContain("Agent work completed"); + expect(banner).toContain("#fca5a5"); // red-300 header tint + expect(JSON.stringify(layout.compactTrailing)).toContain("Failed"); + expect(JSON.stringify(layout.expandedLeading)).toContain("Failed"); + expect(JSON.stringify(layout.minimal)).toContain("xmark.octagon.fill"); + }); + + it("renders up to five rows in the banner", () => { + const layout = AgentActivity( + { + ...props, + activeCount: 6, + activities: [1, 2, 3, 4, 5, 6].map((n) => + makeRow({ threadId: `t${n}`, threadTitle: `Thread ${n}` }), + ), + }, + environment as never, + ); + const banner = JSON.stringify(layout.banner); + for (const visible of [1, 2, 3, 4, 5]) { + expect(banner).toContain(`Thread ${visible}`); + } + expect(banner).not.toContain("Thread 6"); }); }); diff --git a/apps/mobile/src/widgets/AgentActivity.tsx b/apps/mobile/src/widgets/AgentActivity.tsx index 56ada5f2a0..88c8564827 100644 --- a/apps/mobile/src/widgets/AgentActivity.tsx +++ b/apps/mobile/src/widgets/AgentActivity.tsx @@ -1,5 +1,15 @@ -import { HStack, Spacer, Text, VStack } from "@expo/ui/swift-ui"; -import { font, foregroundStyle, lineLimit, padding } from "@expo/ui/swift-ui/modifiers"; +import { HStack, Image, Spacer, Text, VStack, ZStack } from "@expo/ui/swift-ui"; +import type { ComponentProps } from "react"; +import { + font, + foregroundStyle, + frame, + layoutPriority, + lineLimit, + padding, + resizable, + widgetURL, +} from "@expo/ui/swift-ui/modifiers"; import { createLiveActivity, type LiveActivityComponent, @@ -37,282 +47,332 @@ export interface AgentActivityProps { readonly activities: ReadonlyArray; } +// This function is serialized into the widget extension's JS bundle, so it +// must stay self-contained: no references to module-scope helpers, only the +// imported view/modifier factories. export function AgentActivity( props: AgentActivityProps, environment: LiveActivityEnvironment, ): LiveActivityLayout { "widget"; - const row0 = props.activities[0]; - const row1 = props.activities[1]; - const row2 = props.activities[2]; - const updatedAtMatch = /^\d{4}-\d{2}-\d{2}T(\d{2}):(\d{2}):/.exec(props.updatedAt); - const updatedAtHours24 = Number(updatedAtMatch?.[1]); - const updatedAtMinutes = updatedAtMatch?.[2]; - const updatedAt = - Number.isInteger(updatedAtHours24) && - updatedAtHours24 >= 0 && - updatedAtHours24 <= 23 && - updatedAtMinutes - ? `${updatedAtHours24 % 12 || 12}:${updatedAtMinutes}` - : "now"; - const activeLabel = `${props.activeCount} active`; - const isLight = environment.colorScheme === "light"; - const primaryForeground = isLight ? "#262626" : "#f5f5f5"; - const secondaryForeground = isLight ? "#525252" : "#a3a3a3"; - const mutedForeground = isLight ? "#737373" : "#8e8e93"; - const tint = environment.isLuminanceReduced - ? secondaryForeground - : row0?.phase === "waiting_for_approval" || row0?.phase === "waiting_for_input" - ? "#f97316" - : row0?.phase === "failed" - ? "#ef4444" - : "#14b8a6"; + // Use SwiftUI's semantic label colors rather than fixed hex keyed off the + // device color scheme. A Live Activity banner always renders over a dark + // system material regardless of the device's light/dark setting, so + // scheme-derived dark text read as unreadable dark-on-dark on the lock + // screen. Semantic colors adapt to whatever material the OS places them on: + // the dark LA banner and the (light or dark) home-screen widget alike. + const primaryForeground = "primary"; + const secondaryForeground = "secondary"; + + // Status tints mirror the web sidebar's pills + // (apps/web/src/components/Sidebar.logic.ts resolveThreadStatusPill): amber + // for approval, indigo for input, sky for working, emerald for completed. + // On iPhone the LA sits on a dark material, but macOS (iPhone Mirroring / + // Mac notification center) renders it on a light one — so pick the web + // palette's light (-600) or dark (-300) variant off the color scheme. + const isLightScheme = environment.colorScheme === "light"; + const phaseTint = (phase: AgentActivityPhase | undefined): string => { + if (environment.isLuminanceReduced) { + return secondaryForeground; + } + switch (phase) { + case "waiting_for_approval": + return isLightScheme ? "#d97706" : "#fcd34d"; // amber-600 / amber-300 + case "waiting_for_input": + return isLightScheme ? "#4f46e5" : "#a5b4fc"; // indigo-600 / indigo-300 + case "failed": + return isLightScheme ? "#dc2626" : "#fca5a5"; // red-600 / red-300 + case "completed": + return isLightScheme ? "#059669" : "#6ee7b7"; // emerald-600 / emerald-300 + case "starting": + case "running": + default: + return isLightScheme ? "#0284c7" : "#7dd3fc"; // sky-600 / sky-300 + } + }; + + // Order attention-first so whatever needs the user floats to the top of every + // presentation, then failures, then in-flight work, then finished/stale. + const phasePriority = (phase: AgentActivityPhase): number => { + if (phase === "waiting_for_approval" || phase === "waiting_for_input") return 0; + if (phase === "failed") return 1; + if (phase === "running" || phase === "starting") return 2; + return 3; + }; + const ordered = [...props.activities].sort( + (a, b) => phasePriority(a.phase) - phasePriority(b.phase), + ); + const row0 = ordered[0]; + const row1 = ordered[1]; + const row2 = ordered[2]; + const row3 = ordered[3]; + const row4 = ordered[4]; + + const attentionRows = props.activities.filter( + (row) => row.phase === "waiting_for_approval" || row.phase === "waiting_for_input", + ); + const attentionRow = attentionRows[0]; + const failedRow = props.activities.find((row) => row.phase === "failed"); + const heroRow = attentionRow ?? failedRow ?? row0; + const tint = phaseTint(heroRow?.phase); + // Headline count leans on the accent when a human is actually blocked. + const headerTint = attentionRow + ? phaseTint(attentionRow.phase) + : failedRow + ? phaseTint(failedRow.phase) + : tint; + + // With nothing active the aggregate only carries recently finished work, so + // "0 active agents" (and a lone "0" in the expanded island) read as broken. + // Lead with the outcome instead. The outcome is derived here from the rows + // rather than taken from the server subtitle (which keys off the newest + // terminal row): every presentation — header text, tint, count slots, + // minimal glyph — must agree, and a failure anywhere should dominate a + // newer success. + const allDone = props.activeCount === 0; + const doneLabel = failedRow ? "Failed" : "Done"; + const outcomeLabel = failedRow ? "Agent work failed" : "Agent work completed"; + + // Header copy: "5 active agents" + (", 1 needs attention"). The banner renders + // the two parts in-line so the attention half can carry the accent color; + // `summary` is the short form for tight spots (expanded center, watch card). + const agentWord = props.activeCount === 1 ? "agent" : "agents"; + const agentsLabel = allDone ? outcomeLabel : `${props.activeCount} active ${agentWord}`; + const attentionSuffix = + attentionRows.length > 0 + ? `${attentionRows.length} need${attentionRows.length === 1 ? "s" : ""} attention` + : ""; + const activeLabel = allDone ? doneLabel : `${props.activeCount} active`; + const summary = attentionSuffix || activeLabel; + + // Any registered scheme variant routes back to this app; taps are delivered + // to the widget's containing app, so the prod scheme is safe for all builds. + const deepLinkRow = attentionRow ?? row0; + const deepLink = + deepLinkRow && deepLinkRow.deepLink.startsWith("/") && !deepLinkRow.deepLink.startsWith("//") + ? `t3code://${deepLinkRow.deepLink.slice(1)}` + : null; + + // A scannable status glyph per phase — reads faster than colored words and + // ties the compact / expanded / banner / watch presentations together. + type SFName = NonNullable["systemName"]>; + const phaseSymbol = (phase: AgentActivityPhase): SFName => { + switch (phase) { + case "waiting_for_approval": + return "exclamationmark.circle.fill"; + case "waiting_for_input": + return "questionmark.circle.fill"; + case "failed": + return "xmark.octagon.fill"; + case "completed": + return "checkmark.circle.fill"; + case "starting": + return "circle.dotted"; + case "stale": + return "clock.arrow.circlepath"; + case "running": + default: + return "arrow.triangle.2.circlepath"; + } + }; + + // SF Symbols, like the logo, ignore frame/foregroundStyle applied directly to + // the image; size + tint them through a container the resizable symbol fills. + const renderGlyph = (systemName: SFName, size: number, color: string) => ( + + + + ); + + // Single-line row used by every presentation: glyph, title, inline project, + // status. The project and status carry layoutPriority(1) so when space runs + // out it's the title that truncates, never the (short) project name or the + // status label. Single-line keeps rows inside the expanded island's hard + // height budget (~160pt) and lets the banner fit more agents. + const renderCompactRow = (row: AgentActivityRowProps) => ( + + + {row.threadTitle} + + {/* No layoutPriority and no frame on the project: two bare texts take + their ideal width when it fits and shrink proportionally only when it + doesn't — so short rows never truncate, and long title + long project + truncate together. (A maxWidth frame is greedy and reserved its full + width even for short names; layoutPriority let the project starve the + title.) */} + + {row.projectTitle} + + + + {row.status} + + + ); + + // The branded T3 mark. `assetName` resolves the template image set bundled in + // the widget extension's asset catalog. Image views only honor `resizable` + // directly (frame/foregroundStyle are dropped), so we size it via a container + // frame the resizable image fills and tint it through the container's + // foreground style, which the template image inherits. The 3:2 frame matches + // the glyph's aspect ratio so it never distorts. + const renderLogo = (height: number, color: string) => ( + + + + ); return { banner: ( - - - - - {props.title} - - - {props.subtitle} - - - - - {activeLabel} - - - {row0 ? ( - - - - {row0.threadTitle} - - - {row0.projectTitle} - {row0.modelTitle} - - - - - {row0.status} - + + {/* Logo pinned to the leading edge; the status texts centered across the + full width (ZStack so the logo doesn't skew the centering). No footer — + overflow beyond the visible rows is inferable from the count. */} + + + {renderLogo(13, primaryForeground)} + - ) : null} - {row1 ? ( - - - - {row1.threadTitle} - - - {row1.projectTitle} - {row1.modelTitle} - - - - - {row1.status} - - - ) : null} - {row2 ? ( - - - - {row2.threadTitle} - - - {row2.projectTitle} - {row2.modelTitle} - - - - - {row2.status} - - - ) : null} - - Updated {updatedAt} - - - ), - bannerSmall: ( - - - - {props.title} - - - - {activeLabel} - - - {row0 ? ( - + + + {agentsLabel} + + {attentionSuffix ? ( + · + ) : null} + {attentionSuffix ? ( + + {attentionSuffix} + + ) : null} + + + + {row0 ? renderCompactRow(row0) : null} + {row1 ? renderCompactRow(row1) : null} + {row2 ? renderCompactRow(row2) : null} + {row3 ? renderCompactRow(row3) : null} + {row4 ? renderCompactRow(row4) : null} + + ), + // Compact card for the watchOS Smart Stack + CarPlay (the `.small` family): + // brand + count, then the single most important agent with its status glyph. + bannerSmall: ( + + + {renderLogo(14, primaryForeground)} + + {attentionRows.length > 0 ? summary : activeLabel} + + + + {row0 ? ( + + {row0.threadTitle} - - {row0.projectTitle} - {row0.status} - - - ) : null} - - ), - compactLeading: ( - T3 - ), - compactTrailing: ( - - {activeLabel} - - ), - minimal: ( - T3 - ), - expandedLeading: ( - - - {activeLabel} - - - ), - expandedCenter: row0 ? ( - - - {row0.threadTitle} - - - {row0.projectTitle} - {row0.status} - - - ) : null, - expandedTrailing: ( - - Updated {updatedAt} - - ), - expandedBottom: ( - - {row0 ? ( - - - - {row0.threadTitle} - - - {row0.projectTitle} - {row0.modelTitle} - - - - + + {row0.status} ) : null} - {row1 ? ( - - - - {row1.threadTitle} - - - {row1.projectTitle} - {row1.modelTitle} - - - - - {row1.status} - - - ) : null} - {row2 ? ( - - - - {row2.threadTitle} - - - {row2.projectTitle} - {row2.modelTitle} - - - - - {row2.status} - - - ) : null} + + ), + compactLeading: renderLogo(14, tint), + compactTrailing: ( + + {attentionRow + ? attentionRow.phase === "waiting_for_approval" + ? "Approval" + : "Input" + : activeLabel} + + ), + // The shared/minimal form is a ~22pt circle — a single signal reads there, + // the wordmark does not. Show the blocking/outcome phase glyph, else the + // mark (all-done shows the hero row's checkmark/cross). + minimal: + (attentionRow || failedRow || allDone) && heroRow + ? renderGlyph(phaseSymbol(heroRow.phase), 13, phaseTint(heroRow.phase)) + : renderLogo(11, tint), + expandedLeading: ( + + {renderLogo(15, tint)} + + {allDone ? doneLabel : `${props.activeCount}`} + + + ), + // No center content: the phase glyphs + statuses in expandedBottom already + // carry the attention signal, and the expanded island's height budget is + // tight enough that a summary line there pushed the third row off. + expandedCenter: null, + // No trailing content: a timestamp is glanceable-lock-screen info, not + // useful in a view the user is actively holding open — and the trailing + // region hugs the island's corner radius, which clipped it anyway. + expandedTrailing: null, + expandedBottom: ( + // Vertical padding only: the expanded region provides its own horizontal + // content margins, so `all` padding double-indented the rows. + // Horizontal padding keeps both edges clear of the island's corner + // curvature (right edge clipped status labels; titles hugged the left). + + {row0 ? renderCompactRow(row0) : null} + {row1 ? renderCompactRow(row1) : null} + {row2 ? renderCompactRow(row2) : null} ), }; diff --git a/apps/server/package.json b/apps/server/package.json index e65ea3510d..0ce49d3542 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -1,6 +1,6 @@ { "name": "t3", - "version": "0.0.27", + "version": "0.0.28", "license": "MIT", "repository": { "type": "git", diff --git a/apps/server/scripts/t3-sqlite-state.test.ts b/apps/server/scripts/t3-sqlite-state.test.ts new file mode 100644 index 0000000000..d1ef136891 --- /dev/null +++ b/apps/server/scripts/t3-sqlite-state.test.ts @@ -0,0 +1,119 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts"; +import { runSqliteState } from "./t3-sqlite-state.ts"; + +const createFixtureDatabase = Effect.fn("createSqliteStateFixtureDatabase")(function* ( + baseDir: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const stateDir = path.join(baseDir, "userdata"); + const databasePath = path.join(stateDir, "state.sqlite"); + yield* fs.makeDirectory(stateDir, { recursive: true }); + yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE fixtures (id INTEGER PRIMARY KEY, label TEXT NOT NULL)`; + yield* sql`INSERT INTO fixtures (id, label) VALUES (1, 'existing')`; + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath }))); +}); + +it.layer(NodeServices.layer)("t3-sqlite-state", (it) => { + it.effect("reports each invalid SQL source with a specific error", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-state-input-" }); + + const multipleSources = yield* runSqliteState({ + operation: "query", + baseDir, + sql: "SELECT 1", + file: "fixture.sql", + }).pipe(Effect.flip); + assert.equal(multipleSources._tag, "SqliteStateMultipleSqlSourcesError"); + assert.equal(multipleSources.message, "Provide only one of --sql or --file."); + + const missingSource = yield* runSqliteState({ operation: "query", baseDir }).pipe( + Effect.flip, + ); + assert.equal(missingSource._tag, "SqliteStateMissingSqlSourceError"); + assert.equal(missingSource.message, "Provide one of --sql or --file."); + + const emptySql = yield* runSqliteState({ + operation: "query", + baseDir, + sql: " ", + }).pipe(Effect.flip); + assert.equal(emptySql._tag, "SqliteStateEmptySqlError"); + assert.equal(emptySql.message, "SQL input is empty."); + }), + ); + + it.effect("queries an isolated database through Effect SQL", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-state-query-" }); + yield* createFixtureDatabase(baseDir); + + const result = yield* runSqliteState({ + operation: "query", + baseDir, + sql: "SELECT id, label FROM fixtures", + }); + + assert.equal(result.operation, "query"); + if (result.operation === "query") { + assert.deepStrictEqual(result.rows, [{ id: 1, label: "existing" }]); + } + }), + ); + + it.effect("backs up isolated state before writes and refuses the shared home", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-state-exec-" }); + yield* createFixtureDatabase(baseDir); + + const mutation = yield* runSqliteState({ + operation: "exec", + baseDir, + sql: "INSERT INTO fixtures (id, label) VALUES (2, 'seeded')", + }); + assert.equal(mutation.operation, "exec"); + if (mutation.operation === "exec") { + assert.equal((yield* fs.stat(mutation.backup)).mode & 0o777, 0o600); + } + + const error = yield* runSqliteState( + { + operation: "exec", + baseDir, + sql: "DELETE FROM fixtures", + }, + { sharedHome: baseDir }, + ).pipe(Effect.flip); + assert.equal(error._tag, "SqliteStateSharedHomeMutationError"); + + const aliasParent = yield* fs.makeTempDirectoryScoped({ + prefix: "t3-sqlite-state-alias-", + }); + const aliasBaseDir = path.join(aliasParent, "shared-home-alias"); + yield* fs.symlink(baseDir, aliasBaseDir); + const aliasError = yield* runSqliteState( + { + operation: "exec", + baseDir: aliasBaseDir, + sql: "DELETE FROM fixtures", + }, + { sharedHome: baseDir }, + ).pipe(Effect.flip); + assert.equal(aliasError._tag, "SqliteStateSharedHomeMutationError"); + }), + ); +}); diff --git a/apps/server/scripts/t3-sqlite-state.ts b/apps/server/scripts/t3-sqlite-state.ts new file mode 100644 index 0000000000..de0402b364 --- /dev/null +++ b/apps/server/scripts/t3-sqlite-state.ts @@ -0,0 +1,285 @@ +#!/usr/bin/env node + +// @effect-diagnostics nodeBuiltinImport:off - node:os resolves the shared T3 home guard. +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeOS from "node:os"; +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; +import * as Console from "effect/Console"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import { Argument, Command, Flag } from "effect/unstable/cli"; + +import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts"; + +export const SqliteStateOperation = Schema.Literals(["query", "exec"]); +export type SqliteStateOperation = typeof SqliteStateOperation.Type; + +export class SqliteStateMultipleSqlSourcesError extends Schema.TaggedErrorClass()( + "SqliteStateMultipleSqlSourcesError", + {}, +) { + override get message(): string { + return "Provide only one of --sql or --file."; + } +} + +export class SqliteStateMissingSqlSourceError extends Schema.TaggedErrorClass()( + "SqliteStateMissingSqlSourceError", + {}, +) { + override get message(): string { + return "Provide one of --sql or --file."; + } +} + +export class SqliteStateEmptySqlError extends Schema.TaggedErrorClass()( + "SqliteStateEmptySqlError", + {}, +) { + override get message(): string { + return "SQL input is empty."; + } +} + +export class SqliteStateDatabaseMissingError extends Schema.TaggedErrorClass()( + "SqliteStateDatabaseMissingError", + { + databasePath: Schema.String, + }, +) { + override get message(): string { + return `Database does not exist at '${this.databasePath}'. Start T3 once to run migrations.`; + } +} + +export class SqliteStateSharedHomeMutationError extends Schema.TaggedErrorClass()( + "SqliteStateSharedHomeMutationError", + {}, +) { + override get message(): string { + return "Refusing to mutate the shared ~/.t3 database. Use an isolated --base-dir."; + } +} + +export class SqliteStateSqlFileError extends Schema.TaggedErrorClass()( + "SqliteStateSqlFileError", + { + filePath: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Failed to read SQL from '${this.filePath}'.`; + } +} + +export class SqliteStateDatabaseError extends Schema.TaggedErrorClass()( + "SqliteStateDatabaseError", + { + operation: SqliteStateOperation, + databasePath: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Failed to ${this.operation} SQLite database at '${this.databasePath}'.`; + } +} + +const SqliteStateValue = Schema.Union([ + Schema.Null, + Schema.String, + Schema.Number, + Schema.Array(Schema.Number), +]); +const SqliteStateRow = Schema.Record(Schema.String, SqliteStateValue); +const SqliteStateQueryResult = Schema.Struct({ + operation: Schema.Literal("query"), + database: Schema.String, + rows: Schema.Array(SqliteStateRow), +}); +const SqliteStateExecResult = Schema.Struct({ + operation: Schema.Literal("exec"), + database: Schema.String, + backup: Schema.String, +}); +const SqliteStateResult = Schema.Union([SqliteStateQueryResult, SqliteStateExecResult]); +const encodeSqliteStateResult = Schema.encodeEffect(fromJsonStringPretty(SqliteStateResult)); + +export type SqliteStateResult = typeof SqliteStateResult.Type; + +type RawSqliteValue = null | string | number | bigint | Uint8Array; +type RawSqliteRow = Readonly>; + +export interface RunSqliteStateInput { + readonly operation: SqliteStateOperation; + readonly baseDir: string; + readonly sql?: string | undefined; + readonly file?: string | undefined; +} + +export interface RunSqliteStateOptions { + readonly sharedHome?: string | undefined; +} + +const resolveSqlSource = Effect.fn("resolveSqliteStateSqlSource")(function* ( + sql: string | undefined, + file: string | undefined, +) { + if (sql !== undefined && file !== undefined) { + return yield* new SqliteStateMultipleSqlSourcesError(); + } + if (sql === undefined && file === undefined) { + return yield* new SqliteStateMissingSqlSourceError(); + } + + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + let source: string; + if (sql !== undefined) { + source = sql; + } else { + const filePath = path.resolve(file as string); + source = yield* fs + .readFileString(filePath) + .pipe(Effect.mapError((cause) => new SqliteStateSqlFileError({ filePath, cause }))); + } + + const trimmed = source.trim(); + if (trimmed.length === 0) { + return yield* new SqliteStateEmptySqlError(); + } + return trimmed; +}); + +function normalizeSqliteValue(value: RawSqliteValue): typeof SqliteStateValue.Type { + if (typeof value === "bigint") { + const numericValue = Number(value); + return Number.isSafeInteger(numericValue) ? numericValue : value.toString(); + } + if (value instanceof Uint8Array) { + return Array.from(value); + } + return value; +} + +function normalizeSqliteRow(row: RawSqliteRow): typeof SqliteStateRow.Type { + return Object.fromEntries( + Object.entries(row).map(([key, value]) => [key, normalizeSqliteValue(value)]), + ); +} + +export const runSqliteState = Effect.fn("runSqliteState")(function* ( + input: RunSqliteStateInput, + options: RunSqliteStateOptions = {}, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = path.resolve(input.baseDir); + const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3")); + const databasePath = path.join(baseDir, "userdata", "state.sqlite"); + const source = yield* resolveSqlSource(input.sql, input.file); + + if (!(yield* fs.exists(databasePath))) { + return yield* new SqliteStateDatabaseMissingError({ databasePath }); + } + if (input.operation === "exec") { + const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([ + fs.realPath(baseDir), + fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)), + ]); + if (canonicalBaseDir === canonicalSharedHome) { + return yield* new SqliteStateSharedHomeMutationError(); + } + } + + const program = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql.unsafe("PRAGMA busy_timeout = 5000").unprepared; + + if (input.operation === "query") { + const rows = yield* sql.unsafe(source).unprepared.pipe( + Effect.provideService(SqlClient.SafeIntegers, true), + Effect.map((rows) => rows.map(normalizeSqliteRow)), + ); + return { + operation: "query", + database: databasePath, + rows, + } as const; + } + + const timestamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-"); + const backupPath = `${databasePath}.backup-${timestamp}`; + yield* sql`VACUUM INTO ${backupPath}`; + yield* fs.chmod(backupPath, 0o600); + yield* sql.withTransaction(sql.unsafe(source).unprepared); + + return { + operation: "exec", + database: databasePath, + backup: backupPath, + } as const; + }); + + return yield* program.pipe( + Effect.provide( + NodeSqliteClient.layer({ + filename: databasePath, + readonly: input.operation === "query", + }), + ), + Effect.mapError( + (cause) => + new SqliteStateDatabaseError({ + operation: input.operation, + databasePath, + cause, + }), + ), + ); +}); + +export const t3SqliteStateCommand = Command.make( + "t3-sqlite-state", + { + operation: Argument.choice("operation", SqliteStateOperation.literals).pipe( + Argument.withDescription("Run a read-only query or a backed-up fixture mutation."), + ), + baseDir: Flag.string("base-dir").pipe( + Flag.withDescription("Explicit T3 base directory containing userdata/state.sqlite."), + ), + sql: Flag.string("sql").pipe( + Flag.optional, + Flag.withDescription("SQL source supplied directly on the command line."), + ), + file: Flag.string("file").pipe( + Flag.optional, + Flag.withDescription("Path to a SQL source file."), + ), + }, + ({ operation, baseDir, sql, file }) => + runSqliteState({ + operation, + baseDir, + sql: Option.getOrUndefined(sql), + file: Option.getOrUndefined(file), + }).pipe(Effect.flatMap(encodeSqliteStateResult), Effect.flatMap(Console.log)), +).pipe( + Command.withDescription( + "Inspect or seed an isolated T3 SQLite database with automatic backups for writes.", + ), +); + +if (import.meta.main) { + Command.run(t3SqliteStateCommand, { version: "0.0.0" }).pipe( + Effect.provide(NodeServices.layer), + NodeRuntime.runMain, + ); +} diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index f790e71f5c..06a22754e5 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -1,5 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { ThreadId } from "@t3tools/contracts"; +import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -228,6 +229,7 @@ describe("AssetAccess", () => { const fallbackResult = yield* issueAssetUrl({ resource: { _tag: "project-favicon", cwd: root }, }); + expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true); const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); const fallbackSeparatorIndex = fallbackSuffix.indexOf("/"); expect( @@ -235,7 +237,7 @@ describe("AssetAccess", () => { fallbackSuffix.slice(0, fallbackSeparatorIndex), fallbackSuffix.slice(fallbackSeparatorIndex + 1), ), - ).toEqual({ kind: "project-favicon-fallback" }); + ).toBeNull(); }).pipe(Effect.provide(testLayer)), ); diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 8d8ecbc2af..b469e0e315 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -19,6 +19,7 @@ import { WORKSPACE_BROWSER_PREVIEW_EXTENSIONS, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS, } from "@t3tools/shared/filePreview"; +import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -40,7 +41,6 @@ import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; export const ASSET_ROUTE_PREFIX = "/api/assets"; -export const FALLBACK_PROJECT_FAVICON_SVG = ``; const SIGNING_SECRET_NAME = "asset-access-signing-key"; const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000; @@ -91,9 +91,7 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema); const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson); const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson); -export type ResolvedAsset = - | { readonly kind: "file"; readonly path: string } - | { readonly kind: "project-favicon-fallback" }; +export type ResolvedAsset = { readonly kind: "file"; readonly path: string }; function decodeClaims(encodedPayload: string): AssetClaims | null { try { @@ -326,7 +324,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i relativePath, expiresAt, }; - fileName = relativePath ? path.basename(relativePath) : "favicon.svg"; + fileName = relativePath ? path.basename(relativePath) : PROJECT_FAVICON_FALLBACK_MARKER; break; } } @@ -391,9 +389,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* ( } if (claims.kind === "project-favicon") { - if (claims.relativePath === null) { - return { kind: "project-favicon-fallback" } satisfies ResolvedAsset; - } + if (claims.relativePath === null) return null; const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({ workspaceRoot: claims.workspaceRoot, relativePath: claims.relativePath, diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index 71fb00b970..780aaabde2 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -16,6 +16,8 @@ import { EnvironmentOperationForbiddenError, EnvironmentRequestInvalidError, type EnvironmentRequestInvalidReason, + EnvironmentResourceNotFoundError, + type EnvironmentResourceNotFoundReason, EnvironmentScopeRequiredError, EnvironmentAuthenticatedAuth, EnvironmentAuthenticatedPrincipal, @@ -137,6 +139,14 @@ function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_a ); } +export function failEnvironmentNotFound(reason: EnvironmentResourceNotFoundReason) { + return currentEnvironmentTraceId.pipe( + Effect.flatMap((traceId) => + Effect.fail(new EnvironmentResourceNotFoundError({ code: "not_found", reason, traceId })), + ), + ); +} + export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) { return Effect.gen(function* () { const traceId = yield* currentEnvironmentTraceId; diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index 0ececb07f3..349dd42a61 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -18,6 +18,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { deriveServerPaths } from "../config.ts"; import { resolveServerConfig } from "./config.ts"; +const deriveExplicitServerPaths = (baseDir: string, devUrl: URL | undefined) => + deriveServerPaths(baseDir, devUrl, { baseDirIsExplicit: true }); + const encodeDesktopBootstrap = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap)); const makeDesktopBootstrap = ( @@ -60,7 +63,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { Effect.gen(function* () { const { join } = yield* Path.Path; const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-env-base"); - const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173")); + const derivedPaths = yield* deriveExplicitServerPaths( + baseDir, + new URL("http://127.0.0.1:5173"), + ); const resolved = yield* resolveServerConfig( { mode: Option.none(), @@ -119,6 +125,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { tailscaleServeEnabled: false, tailscaleServePort: 443, }); + assert.equal(resolved.stateDir, join(baseDir, "userdata")); }), ); @@ -126,7 +133,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { Effect.gen(function* () { const { join } = yield* Path.Path; const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-flags-base"); - const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173")); + const derivedPaths = yield* deriveExplicitServerPaths( + baseDir, + new URL("http://127.0.0.1:4173"), + ); const resolved = yield* resolveServerConfig( { mode: Option.some("web"), @@ -185,6 +195,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { tailscaleServeEnabled: true, tailscaleServePort: 8443, }); + assert.equal(resolved.dbPath, join(baseDir, "userdata", "state.sqlite")); }), ); @@ -199,7 +210,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { tailscaleServePort: 443, }), ); - const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173")); + const derivedPaths = yield* deriveExplicitServerPaths( + baseDir, + new URL("http://127.0.0.1:4173"), + ); const resolved = yield* resolveServerConfig( { @@ -396,7 +410,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { tailscaleServePort: 443, }), ); - const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173")); + const derivedPaths = yield* deriveExplicitServerPaths( + baseDir, + new URL("http://127.0.0.1:4173"), + ); const resolved = yield* resolveServerConfig( { @@ -461,7 +478,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" }); - const derivedPaths = yield* deriveServerPaths(baseDir, undefined); + const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined); yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }); yield* fs.writeFileString( derivedPaths.settingsPath, @@ -529,7 +546,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { Effect.gen(function* () { const { join } = yield* Path.Path; const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-headless-base"); - const derivedPaths = yield* deriveServerPaths(baseDir, undefined); + const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined); const resolved = yield* resolveServerConfig( { diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index 7a9cd72d52..5a4cde0a6f 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -31,7 +31,9 @@ export const hostFlag = Flag.string("host").pipe( Flag.optional, ); export const baseDirFlag = Flag.string("base-dir").pipe( - Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."), + Flag.withDescription( + "Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).", + ), Flag.optional, ); export const devUrlFlag = Flag.string("dev-url").pipe( @@ -259,19 +261,21 @@ export const resolveServerConfig = ( resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)), () => undefined, ); + const explicitBaseDir = resolveOptionPrecedence( + normalizedFlags.baseDir, + Option.fromUndefinedOr(env.t3Home), + ).pipe(Option.filter((value) => value.trim().length > 0)); const baseDir = yield* resolveBaseDir( Option.getOrUndefined( - resolveOptionPrecedence( - normalizedFlags.baseDir, - Option.fromUndefinedOr(env.t3Home), - Option.fromUndefinedOr(bootstrap?.t3Home), - ), + resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)), ), ); const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd()); const cwd = path.resolve(yield* expandHomePath(rawCwd.trim())); yield* fs.makeDirectory(cwd, { recursive: true }); - const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl); + const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, { + baseDirIsExplicit: Option.isSome(explicitBaseDir), + }); yield* ServerConfig.ensureServerDirectories(derivedPaths); const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings( derivedPaths.settingsPath, diff --git a/apps/server/src/cli/connect.test.ts b/apps/server/src/cli/connect.test.ts index 70b0329ac9..e63cbf331b 100644 --- a/apps/server/src/cli/connect.test.ts +++ b/apps/server/src/cli/connect.test.ts @@ -1,14 +1,44 @@ import * as RelayClient from "@t3tools/shared/relayClient"; import { assert, it } from "@effect/vitest"; import * as Cause from "effect/Cause"; +import * as ConfigProvider from "effect/ConfigProvider"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as References from "effect/References"; +import * as Terminal from "effect/Terminal"; -import { acquireRelayClientForLink, reportCloudDisconnectResults } from "./connect.ts"; +import { + acquireRelayClientForLink, + formatHeadlessAuthorizationPrompt, + formatRelayClientReady, + headlessSessionConfig, + isPublishAgentActivityEnabledValue, + recoverBootServiceOffer, + reportCloudDisconnectResults, +} from "./connect.ts"; + +it("explains how to complete headless authorization", () => { + assert.equal( + formatHeadlessAuthorizationPrompt("https://example.test/connect"), + [ + "Headless authorization", + "Open this URL on a device with a browser:", + " https://example.test/connect", + "", + "After signing in, return here and enter the code shown in your browser.", + ].join("\n"), + ); +}); + +it("formats relay readiness without printing its installation path", () => { + assert.equal(formatRelayClientReady("2026.5.2"), "✓ Relay client ready · cloudflared 2026.5.2"); +}); + +const readHeadlessSessionConfig = (env: Record) => + headlessSessionConfig.pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))); const managedExecutable = { status: "available", @@ -17,6 +47,22 @@ const managedExecutable = { version: RelayClient.CLOUDFLARED_VERSION, } as const; +it.effect("detects headless operation from individual SSH config values", () => + Effect.gen(function* () { + assert.isFalse(yield* readHeadlessSessionConfig({})); + assert.isFalse(yield* readHeadlessSessionConfig({ CI: "true" })); + assert.isTrue(yield* readHeadlessSessionConfig({ SSH_CONNECTION: "client server" })); + assert.isTrue(yield* readHeadlessSessionConfig({ SSH_TTY: "/dev/pts/1" })); + }), +); + +it.effect("treats cancelling optional background setup as a successful skip", () => + Effect.gen(function* () { + const result = yield* recoverBootServiceOffer(Effect.fail(new Terminal.QuitError({}))); + assert.isFalse(result); + }), +); + it.effect("does not install the relay client when the user declines the managed download", () => Effect.gen(function* () { let installCalls = 0; @@ -153,3 +199,10 @@ it.effect("keeps disconnect causes in structured logs and out of console warning ), ); }); + +it("treats only the literal 'true' as publish-enabled", () => { + assert.equal(isPublishAgentActivityEnabledValue("true"), true); + assert.equal(isPublishAgentActivityEnabledValue("false"), false); + assert.equal(isPublishAgentActivityEnabledValue(null), false); + assert.equal(isPublishAgentActivityEnabledValue("TRUE"), false); +}); diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts index 3ce53391fa..8b11fc7334 100644 --- a/apps/server/src/cli/connect.ts +++ b/apps/server/src/cli/connect.ts @@ -6,9 +6,12 @@ import { } from "@t3tools/contracts"; import { RelayOkResponse } from "@t3tools/contracts/relay"; import * as RelayClient from "@t3tools/shared/relayClient"; +import * as Terminal from "effect/Terminal"; import { withRelayClientTracing } from "@t3tools/shared/relayTracing"; import * as Cause from "effect/Cause"; +import * as Config from "effect/Config"; import * as Console from "effect/Console"; +import * as Crypto from "effect/Crypto"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -16,6 +19,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as References from "effect/References"; +import * as Schema from "effect/Schema"; import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli"; import { FetchHttpClient, @@ -25,15 +29,23 @@ import { } from "effect/unstable/http"; import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient"; +import packageJson from "../../package.json" with { type: "json" }; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as BootService from "../cloud/bootService.ts"; import * as CliState from "../cloud/CliState.ts"; import * as CliTokenManager from "../cloud/CliTokenManager.ts"; -import { CLOUD_LINKED_USER_ID, RELAY_URL_SECRET } from "../cloud/config.ts"; +import { + CLOUD_LINKED_USER_ID, + PUBLISH_AGENT_ACTIVITY_SECRET, + RELAY_URL_SECRET, +} from "../cloud/config.ts"; import { relayUrlConfig } from "../cloud/publicConfig.ts"; import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ExternalLauncher from "../process/externalLauncher.ts"; +import * as ProcessRunner from "../processRunner.ts"; import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; @@ -42,16 +54,100 @@ const jsonFlag = Flag.boolean("json").pipe( Flag.withDefault(false), ); +const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError); + +const headlessFlag = Flag.boolean("headless").pipe( + Flag.withDescription("Authorize without a local browser using out-of-band OAuth."), + Flag.withDefault(false), +); + +/** + * Inside an SSH session there is no local browser to complete the loopback + * OAuth callback, so out-of-band OAuth is the only flow that can work. + */ +export const headlessSessionConfig = Config.all({ + sshConnection: Config.string("SSH_CONNECTION").pipe(Config.option), + sshTty: Config.string("SSH_TTY").pipe(Config.option), +}).pipe( + Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)), +); + +const promptForOutOfBandOAuthCode = Effect.fn("cloud.cli.prompt_for_out_of_band_oauth_code")( + function* ({ authorizeUrl, validate }: CliTokenManager.OutOfBandOAuthPromptInput) { + yield* Console.log(formatHeadlessAuthorizationPrompt(authorizeUrl)); + return yield* Prompt.run(Prompt.text({ message: "Authorization code", validate })); + }, +); + +export function formatHeadlessAuthorizationPrompt(authorizeUrl: string): string { + return [ + "Headless authorization", + "Open this URL on a device with a browser:", + ` ${authorizeUrl}`, + "", + "After signing in, return here and enter the code shown in your browser.", + ].join("\n"); +} + +/** Returns the connected account identity, if the flow could determine one. */ +const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: { + readonly headless: boolean; +}) { + const tokens = yield* CliTokenManager.CloudCliTokenManager; + const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig); + if (!useOutOfBandOAuth) { + const authorization = yield* tokens.get; + if (authorization._tag === "Authorized") { + return authorization.token.identity ?? null; + } + yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below."); + } + // A stored credential whose refresh fails (revoked, expired grant) must + // fall through to a fresh out-of-band authorization, not dead-end the command. + const existing = yield* tokens.getExisting.pipe( + Effect.catchTag("CloudCliCredentialRefreshError", () => + Console.log( + "The stored T3 Connect credential could not be refreshed; signing in again.", + ).pipe(Effect.as(Option.none())), + ), + ); + if (Option.isSome(existing)) { + return existing.value.identity ?? null; + } + const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin( + promptForOutOfBandOAuthCode, + ).pipe( + Effect.mapError((cause) => + // Ctrl-C / EOF at the prompt is a QuitError; let it propagate so the CLI + // cancels quietly instead of dumping an authorization error. + Terminal.isQuitError(cause) || isCloudCliTokenManagerError(cause) + ? cause + : new CliTokenManager.CloudCliAuthorizationError({ cause }), + ), + ); + yield* tokens.store(token); + return identity; +}); + function bytesToString(value: Uint8Array): string { return new TextDecoder().decode(value); } +function stringToBytes(value: string): Uint8Array { + return new TextEncoder().encode(value); +} + +export function isPublishAgentActivityEnabledValue(value: string | null): boolean { + return value === "true"; +} + interface CloudCliStatus { readonly desired: boolean; readonly authenticated: boolean; readonly linked: boolean; readonly cloudUserId: string | null; readonly relayUrl: string | null; + readonly publishAgentActivity: boolean; readonly relayClient: RelayClient.RelayClientStatus; } @@ -104,6 +200,7 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b ` Authorization: ${status.authenticated ? "stored credential" : "missing"}`, ` Environment link: ${provisioned}`, ` Relay: ${status.relayUrl ?? "not provisioned"}`, + ` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`, ...formatRelayClientStatus(status.relayClient), ...(nextStep ? ["", `Next: ${nextStep}`] : []), ].join("\n"); @@ -299,6 +396,21 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: { if (options.clearAuthorization) { const tokens = yield* CliTokenManager.CloudCliTokenManager; yield* tokens.clear; + + // uninstall itself no-ops when nothing is installed (and on non-Linux), + // so no status pre-check that could mask a real removal failure. + const bootService = yield* BootService.BootService; + yield* bootService.uninstall.pipe( + Effect.tap((removed) => + removed ? Console.log("Removed the T3 Code background service.") : Effect.void, + ), + Effect.catchTag("BootServiceUnsupportedError", () => Effect.succeed(false)), + Effect.catch((error) => + Console.warn(`Could not remove the background service: ${error.message}`).pipe( + Effect.as(false), + ), + ), + ); } yield* reportCloudDisconnectResults({ @@ -312,7 +424,7 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: { } }); -const runCloudCommand = ( +const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* ( flags: { readonly baseDir: Option.Option }, run: Effect.Effect< A, @@ -321,6 +433,8 @@ const runCloudCommand = ( | CliTokenManager.CloudCliTokenManager | RelayClient.RelayClient | EnvironmentAuth.EnvironmentAuth + | BootService.BootService + | Crypto.Crypto | FileSystem.FileSystem | HttpClient.HttpClient | Prompt.Environment @@ -330,37 +444,79 @@ const runCloudCommand = ( options?: { readonly quietLogs?: boolean; }, -) => - Effect.gen(function* () { - const logLevel = yield* GlobalFlag.LogLevel; - const config = yield* resolveCliAuthConfig(flags, logLevel); - const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel; - const runtimeLayer = Layer.mergeAll( - ServerSecretStore.layer, - CliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)), - RelayClient.layerCloudflared({ baseDir: config.baseDir }), - EnvironmentAuth.runtimeLayer, - ServerEnvironment.layer, - headlessRelayClientTracingLayer, - ).pipe( - Layer.provideMerge(FetchHttpClient.layer), - Layer.provideMerge(ServerConfig.layer(config)), - Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)), +) { + const logLevel = yield* GlobalFlag.LogLevel; + const config = yield* resolveCliAuthConfig(flags, logLevel); + const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel; + const runtimeLayer = Layer.mergeAll( + ServerSecretStore.layer, + CliTokenManager.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide(ExternalLauncher.layer), + ), + RelayClient.layerCloudflared({ baseDir: config.baseDir }), + EnvironmentAuth.runtimeLayer, + ServerEnvironment.layer, + BootService.layer({ + baseDir: config.baseDir, + logsDir: config.logsDir, + cliVersion: packageJson.version, + }).pipe(Layer.provide(ProcessRunner.layer)), + headlessRelayClientTracingLayer, + ).pipe( + Layer.provideMerge(FetchHttpClient.layer), + Layer.provideMerge(ServerConfig.layer(config)), + Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)), + ); + return yield* run.pipe(Effect.provide(runtimeLayer)); +}); + +const connectedAs = (identity: string | null): string => (identity ? ` as ${identity}` : ""); + +export function formatRelayClientReady(version: string): string { + return `✓ Relay client ready · cloudflared ${version}`; +} + +const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: { + readonly headless: boolean; + readonly publishOnly?: boolean; +}) { + const publishOnly = options.publishOnly ?? false; + if (!publishOnly) { + const relayClient = yield* RelayClient.RelayClient; + const installed = yield* acquireRelayClientForLink( + relayClient, + confirmRelayClientInstall, + reportRelayClientInstallProgress, ); - return yield* run.pipe(Effect.provide(runtimeLayer)); - }); + if (Option.isNone(installed)) { + yield* Console.log("T3 Connect setup cancelled. The relay client was not installed."); + return null; + } + yield* Console.log(formatRelayClientReady(installed.value.version)); + } + + const identity = yield* authorizeCli(options); + yield* CliState.setCliDesiredCloudLink(true, publishOnly ? "publish_only" : "managed"); + if (publishOnly) { + const secrets = yield* ServerSecretStore.ServerSecretStore; + yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true")); + } + return { identity } as const; +}); const connectLoginCommand = Command.make("login", { ...projectLocationFlags, + headless: headlessFlag, }).pipe( Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."), Command.withHandler((flags) => runCloudCommand( flags, Effect.gen(function* () { - const tokens = yield* CliTokenManager.CloudCliTokenManager; - yield* tokens.get; - yield* Console.log("Signed in to T3 Connect."); + yield* Console.log("T3 Connect\n"); + const identity = yield* authorizeCli(flags); + yield* Console.log(`✓ Signed in${connectedAs(identity)}`); }), ), ), @@ -368,32 +524,28 @@ const connectLoginCommand = Command.make("login", { const connectLinkCommand = Command.make("link", { ...projectLocationFlags, + headless: headlessFlag, + publishOnly: Flag.boolean("publish-only").pipe( + Flag.withDescription( + "Link to publish agent activity only — no managed tunnel. Reach this environment out of band (e.g. Tailscale).", + ), + Flag.withDefault(false), + ), }).pipe( Command.withDescription("Authorize this environment for T3 Connect on next start."), Command.withHandler((flags) => runCloudCommand( flags, Effect.gen(function* () { - const relayClient = yield* RelayClient.RelayClient; - const installed = yield* acquireRelayClientForLink( - relayClient, - confirmRelayClientInstall, - reportRelayClientInstallProgress, - ); - if (Option.isNone(installed)) { - yield* Console.log("T3 Connect setup cancelled. The relay client was not installed."); - return; + yield* Console.log("T3 Connect\n"); + const linked = yield* linkEnvironmentForConnect(flags); + if (linked) { + yield* Console.log( + flags.publishOnly + ? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).` + : `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`t3 serve\` to make this machine reachable.`, + ); } - yield* Console.log( - `Using relay client ${installed.value.version} from ${installed.value.executablePath}.`, - ); - - const tokens = yield* CliTokenManager.CloudCliTokenManager; - yield* tokens.get; - yield* CliState.setCliDesiredCloudLink(true); - yield* Console.log( - "This T3 environment will be available through T3 Connect the next time T3 starts.", - ); }), ), ), @@ -411,22 +563,27 @@ const connectStatusCommand = Command.make("status", { const secrets = yield* ServerSecretStore.ServerSecretStore; const relayClient = yield* RelayClient.RelayClient; const tokens = yield* CliTokenManager.CloudCliTokenManager; - const [desired, authenticated, cloudUserId, relayUrl, executable] = yield* Effect.all( - [ - CliState.readCliDesiredCloudLink, - tokens.hasCredential, - secrets.get(CLOUD_LINKED_USER_ID), - secrets.get(RELAY_URL_SECRET), - relayClient.resolve, - ], - { concurrency: "unbounded" }, - ); + const [desired, authenticated, cloudUserId, relayUrl, publishAgentActivity, executable] = + yield* Effect.all( + [ + CliState.readCliDesiredCloudLink, + tokens.hasCredential, + secrets.get(CLOUD_LINKED_USER_ID), + secrets.get(RELAY_URL_SECRET), + secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET), + relayClient.resolve, + ], + { concurrency: "unbounded" }, + ); const status: CloudCliStatus = { desired, authenticated, linked: Option.isSome(cloudUserId), cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null, relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null, + publishAgentActivity: isPublishAgentActivityEnabledValue( + Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null, + ), relayClient: executable, }; yield* Console.log(formatCloudStatus(status, { json: flags.json })); @@ -438,6 +595,76 @@ const connectStatusCommand = Command.make("status", { ), ); +const connectPublishCommand = Command.make("publish", { + ...projectLocationFlags, + disable: Flag.boolean("disable").pipe( + Flag.withDescription("Stop publishing agent activity to your mobile clients."), + Flag.withDefault(false), + ), +}).pipe( + Command.withDescription( + "Toggle publishing agent activity (push notifications and Live Activities) to your mobile clients.", + ), + Command.withHandler((flags) => + runCloudCommand( + flags, + Effect.gen(function* () { + const secrets = yield* ServerSecretStore.ServerSecretStore; + const tokens = yield* CliTokenManager.CloudCliTokenManager; + const enabled = !flags.disable; + yield* secrets.set( + PUBLISH_AGENT_ACTIVITY_SECRET, + stringToBytes(enabled ? "true" : "false"), + ); + if (!enabled) { + // If enabling scheduled a publish-only link that hasn't been + // provisioned yet, disabling must cancel it too — otherwise the next + // start still links an environment whose only purpose was publishing. + // A pending managed link is left alone; it exists for the tunnel. + const linkedNow = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID)); + if (!linkedNow && (yield* CliState.readCliDesiredLinkMode) === "publish_only") { + yield* CliState.setCliDesiredCloudLink(false); + yield* Console.log("Cancelled the pending publish-only T3 Connect link."); + } + yield* Console.log("Publishing agent activity disabled."); + return; + } + + yield* Console.log("Publishing agent activity enabled."); + const linked = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID)); + if (linked) { + return; + } + + // Publishing needs the relay to know this environment belongs to you. + // Establish a tunnel-free publish-only link automatically so signing in + // is all it takes — the mobile client can still reach the environment + // out of band without T3 Connect. + if (!(yield* tokens.hasCredential)) { + yield* Console.log( + "Run `t3 connect login` first so this environment can be authorized to publish.", + ); + return; + } + // A link may already be desired (e.g. `t3 connect link` before the + // server's first start). Never downgrade it: a desired managed link + // also covers publishing, so only request a publish-only link when no + // link is pending at all. + if (yield* CliState.readCliDesiredCloudLink) { + yield* Console.log( + "A T3 Connect link is already pending. Start T3 to finish provisioning it; publishing starts once it links.", + ); + return; + } + yield* CliState.setCliDesiredCloudLink(true, "publish_only"); + yield* Console.log( + "Restart T3 to finish authorizing this environment to publish (no managed tunnel is created).", + ); + }), + ), + ), +); + const connectUnlinkCommand = Command.make("unlink", { ...projectLocationFlags, }).pipe( @@ -456,11 +683,84 @@ const connectLogoutCommand = Command.make("logout", { ), ); -export const connectCommand = Command.make("connect").pipe( - Command.withDescription("Manage headless T3 Connect access."), +const offerBootService = Effect.gen(function* () { + const bootService = yield* BootService.BootService; + const { supported, installed, current } = yield* bootService.status; + if (!supported) { + // Don't prompt for something that can only fail; background setup is + // Linux/systemd-only for now. + return false; + } + if (installed && current) { + yield* Console.log("T3 Code is already set up to run in the background on this machine."); + return true; + } + const wanted = yield* Prompt.run( + Prompt.confirm({ + message: installed + ? "The installed T3 Code background service is from an older setup. Update it now?" + : "Run T3 Code in the background whenever this machine boots? " + + "It stays reachable through T3 Connect even after you log out.", + initial: true, + }), + ); + if (!wanted) { + return false; + } + const plan = yield* bootService.install; + yield* Console.log(`Background service installed. Logs: ${plan.logPath}`); + return true; +}); + +export const recoverBootServiceOffer = ( + offer: Effect.Effect, +) => + offer.pipe( + Effect.catchTags({ + QuitError: () => Effect.succeed(false), + BootServiceUnsupportedError: (error) => + Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)), + BootServiceCommandError: (error) => + Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)), + BootServiceInstallError: (error) => + Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)), + }), + ); + +export const connectCommand = Command.make("connect", { + ...projectLocationFlags, + headless: headlessFlag, +}).pipe( + Command.withDescription("Set up T3 Connect for this machine."), + Command.withHandler((flags) => + runCloudCommand( + flags, + Effect.gen(function* () { + yield* Console.log("T3 Connect\n"); + const linked = yield* linkEnvironmentForConnect(flags); + if (!linked) { + return; + } + // Show which account was linked so an unexpected identity (an + // authorization code for a different account) is visible before the + // machine is brought online. + yield* Console.log(`✓ Connected${connectedAs(linked.identity)}`); + + // Connect itself already succeeded; a boot-service failure must not + // fail the command, just tell the user what happened and move on. + const background = yield* recoverBootServiceOffer(offerBootService); + yield* Console.log( + background + ? "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out." + : "\nNext\n Start the server with `t3 serve` to make this machine reachable.", + ); + }), + ), + ), Command.withSubcommands([ connectLoginCommand, connectLinkCommand, + connectPublishCommand, connectStatusCommand, connectUnlinkCommand, connectLogoutCommand, diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index 4251b0f5e2..b9a3a3511e 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -520,6 +520,10 @@ const projectRemoveCommand = Command.make("remove", { project: Argument.string("project").pipe( Argument.withDescription("Project id or workspace root to remove."), ), + force: Flag.boolean("force").pipe( + Flag.withDescription("Delete the project and all of its threads."), + Flag.withDefault(false), + ), }).pipe( Command.withDescription("Remove a project."), Command.withHandler((flags) => @@ -542,6 +546,7 @@ const projectRemoveCommand = Command.make("remove", { type: "project.delete", commandId: CommandId.make(yield* projectCommandUuid), projectId: project.id, + force: flags.force, }); return `Removed project ${project.id} (${project.title}).`; }), diff --git a/apps/server/src/cloud/CliState.test.ts b/apps/server/src/cloud/CliState.test.ts index 3fbf4f12db..39f904b47b 100644 --- a/apps/server/src/cloud/CliState.test.ts +++ b/apps/server/src/cloud/CliState.test.ts @@ -56,4 +56,27 @@ it.layer(NodeServices.layer)("CliState", (it) => { } }).pipe(Effect.provide(makeTestLayer())), ); + + it.effect("round-trips the desired link mode and defaults legacy links to managed", () => + Effect.gen(function* () { + const secrets = yield* ServerSecretStore.ServerSecretStore; + + assert.equal(yield* CliState.readCliDesiredLinkMode, "managed"); + + yield* CliState.setCliDesiredCloudLink(true, "publish_only"); + assert.isTrue(yield* CliState.readCliDesiredCloudLink); + assert.equal(yield* CliState.readCliDesiredLinkMode, "publish_only"); + + yield* CliState.setCliDesiredCloudLink(true, "managed"); + assert.equal(yield* CliState.readCliDesiredLinkMode, "managed"); + + // A pre-existing link persisted the literal "true"; treat it as managed. + yield* secrets.set(CliState.CLOUD_CLI_DESIRED_LINK_SECRET, new TextEncoder().encode("true")); + assert.isTrue(yield* CliState.readCliDesiredCloudLink); + assert.equal(yield* CliState.readCliDesiredLinkMode, "managed"); + + yield* CliState.setCliDesiredCloudLink(false); + assert.equal(yield* CliState.readCliDesiredLinkMode, "managed"); + }).pipe(Effect.provide(makeTestLayer())), + ); }); diff --git a/apps/server/src/cloud/CliState.ts b/apps/server/src/cloud/CliState.ts index 2e18fff425..9af9a032f8 100644 --- a/apps/server/src/cloud/CliState.ts +++ b/apps/server/src/cloud/CliState.ts @@ -14,19 +14,43 @@ import { export const CLOUD_CLI_DESIRED_LINK_SECRET = "cloud-cli-desired-link"; -const TRUE_BYTES = new TextEncoder().encode("true"); +// "managed" provisions a Cloudflare tunnel (default, legacy value "true"). +// "publish_only" links the environment to the relay purely to publish agent +// activity — no tunnel, no relay-advertised endpoint — so activity can flow to +// mobile clients even when they reach the environment out of band (Tailscale, +// direct pairing) without T3 Connect. +export type CliDesiredLinkMode = "managed" | "publish_only"; + +const MANAGED_BYTES = new TextEncoder().encode("managed"); +const PUBLISH_ONLY_BYTES = new TextEncoder().encode("publish_only"); export const readCliDesiredCloudLink = Effect.gen(function* () { const secrets = yield* ServerSecretStore.ServerSecretStore; return Option.isSome(yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET)); }); +export const readCliDesiredLinkMode = Effect.gen(function* () { + const secrets = yield* ServerSecretStore.ServerSecretStore; + const value = yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET); + if (Option.isNone(value)) { + return "managed" as CliDesiredLinkMode; + } + // Legacy links stored the literal "true" and are always managed. + return new TextDecoder().decode(value.value) === "publish_only" + ? ("publish_only" as CliDesiredLinkMode) + : ("managed" as CliDesiredLinkMode); +}); + export const setCliDesiredCloudLink = Effect.fn("cloud.cli_state.set_desired")(function* ( desired: boolean, + mode: CliDesiredLinkMode = "managed", ) { const secrets = yield* ServerSecretStore.ServerSecretStore; if (desired) { - yield* secrets.set(CLOUD_CLI_DESIRED_LINK_SECRET, TRUE_BYTES); + yield* secrets.set( + CLOUD_CLI_DESIRED_LINK_SECRET, + mode === "publish_only" ? PUBLISH_ONLY_BYTES : MANAGED_BYTES, + ); } else { yield* secrets.remove(CLOUD_CLI_DESIRED_LINK_SECRET); } diff --git a/apps/server/src/cloud/CliTokenManager.test.ts b/apps/server/src/cloud/CliTokenManager.test.ts new file mode 100644 index 0000000000..e6eb6b7cd6 --- /dev/null +++ b/apps/server/src/cloud/CliTokenManager.test.ts @@ -0,0 +1,264 @@ +import { readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Crypto from "effect/Crypto"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Encoding from "effect/Encoding"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; +import * as Terminal from "effect/Terminal"; +import * as HttpClient from "effect/unstable/http/HttpClient"; +import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse"; + +import * as CliTokenManager from "./CliTokenManager.ts"; +import type { OutOfBandOAuthPromptInput } from "./CliTokenManager.ts"; + +// pk_test_ +const TEST_ENV = { + T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_Y2xlcmsuZXhhbXBsZS50ZXN0JA==", + T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_client_test", + T3CODE_HOSTED_APP_URL: "https://hosted.example.test", +}; + +interface RecordedTokenRequest { + readonly url: string; + readonly params: URLSearchParams; +} + +// A JWT whose payload claims { email: "theo@example.test" } (signature is not +// verified — the CLI only reads the claim to display the connected account). +const TestIdTokenHeaderJson = Schema.fromJsonString(Schema.Struct({ alg: Schema.Literal("none") })); +const TestIdTokenPayloadJson = Schema.fromJsonString(Schema.Struct({ email: Schema.String })); +const encodeTestIdTokenHeader = Schema.encodeSync(TestIdTokenHeaderJson); +const encodeTestIdTokenPayload = Schema.encodeSync(TestIdTokenPayloadJson); +const idTokenWithEmail = (() => { + const header = Encoding.encodeBase64Url(encodeTestIdTokenHeader({ alg: "none" })); + const payload = Encoding.encodeBase64Url( + encodeTestIdTokenPayload({ email: "theo@example.test" }), + ); + return `${header}.${payload}.`; +})(); + +const TestTokenResponseJson = Schema.fromJsonString( + Schema.Struct({ + access_token: Schema.String, + refresh_token: Schema.String, + id_token: Schema.String, + expires_in: Schema.Number, + token_type: Schema.String, + }), +); +const encodeTestTokenResponse = Schema.encodeSync(TestTokenResponseJson); + +const makeTokenEndpointLayer = ( + requests: Array, + options?: { readonly idToken?: string }, +) => + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => { + const body = + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : ""; + requests.push({ url: request.url, params: new URLSearchParams(body) }); + return HttpClientResponse.fromWeb( + request, + new Response( + encodeTestTokenResponse({ + access_token: "access-token-1", + refresh_token: "refresh-token-1", + id_token: options?.idToken ?? idTokenWithEmail, + expires_in: 3600, + token_type: "bearer", + }), + { status: 200, headers: { "content-type": "application/json" } }, + ), + ); + }), + ), + ); + +const provideTestEnv = Effect.provide( + ConfigProvider.layer(ConfigProvider.fromEnv({ env: TEST_ENV })), +); + +const isAuthorizationError = Schema.is(CliTokenManager.CloudCliAuthorizationError); + +class PromptRejectedError extends Schema.TaggedErrorClass()( + "PromptRejectedError", + { message: Schema.String }, +) {} + +it("formats loopback authorization with a headless-host fallback", () => { + assert.equal( + CliTokenManager.formatLoopbackAuthorizationPrompt("https://clerk.example.test/authorize"), + [ + "Open this URL to authorize T3 Connect:", + " https://clerk.example.test/authorize", + "", + "Press \u001b[1mEnter\u001b[22m to open it in your browser.", + "No browser on this device? Press \u001b[1mH\u001b[22m to switch to headless mode.", + ].join("\n"), + ); +}); + +const makeTestTerminal = (queue: Queue.Queue) => + Terminal.make({ + columns: Effect.succeed(80), + rows: Effect.succeed(24), + readInput: Effect.succeed(Queue.asDequeue(queue)), + readLine: Effect.never, + display: () => Effect.void, + }); + +const userInput = (name: string): Terminal.UserInput => ({ + input: Option.some(name), + key: { name, ctrl: false, meta: false, shift: name !== name.toLowerCase() }, +}); + +it.effect("opens the browser on Enter and switches the active flow on H", () => + Effect.gen(function* () { + const queue = yield* Queue.make(); + yield* Queue.offerAll(queue, [userInput("enter"), userInput("H")]); + const opened: Array = []; + + const result = yield* CliTokenManager.waitForLoopbackAuthorization({ + authorizationUrl: "https://clerk.example.test/authorize", + callback: Effect.never, + terminal: makeTestTerminal(queue), + launchBrowser: (url) => + Effect.sync(() => { + opened.push(url); + }), + }); + + assert.deepEqual(opened, ["https://clerk.example.test/authorize"]); + assert.deepEqual(result, { _tag: "HeadlessRequested" }); + }), +); + +it.effect("finishes normally when the browser callback wins", () => + Effect.gen(function* () { + const queue = yield* Queue.make(); + const callback = yield* Deferred.make(); + yield* Deferred.succeed(callback, "clerk-code-123"); + + const result = yield* CliTokenManager.waitForLoopbackAuthorization({ + authorizationUrl: "https://clerk.example.test/authorize", + callback: Deferred.await(callback), + terminal: makeTestTerminal(queue), + launchBrowser: () => Effect.die("browser launch should not run"), + }); + + assert.deepEqual(result, { _tag: "AuthorizationCode", code: "clerk-code-123" }); + }), +); + +it.layer(NodeServices.layer)("CliTokenManager.outOfBandOAuthLogin", (it) => { + it.effect("prints a hosted authorize URL and exchanges the out-of-band code with PKCE", () => + Effect.gen(function* () { + const requests: Array = []; + let seenAuthorizeUrl = ""; + + const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin( + ({ authorizeUrl, validate }: OutOfBandOAuthPromptInput) => + Effect.gen(function* () { + seenAuthorizeUrl = authorizeUrl; + const request = readConnectAuthorizeRequest(new URL(authorizeUrl)); + assert.isNotNull(request); + return yield* validate(`clerk-code-123.${request!.state}`).pipe( + Effect.mapError((message) => new PromptRejectedError({ message })), + ); + }), + ).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv); + + const authorizeUrl = new URL(seenAuthorizeUrl); + assert.equal(authorizeUrl.origin, "https://hosted.example.test"); + assert.equal(authorizeUrl.pathname, "/connect"); + const request = readConnectAuthorizeRequest(authorizeUrl); + assert.isNotNull(request); + assert.match(request!.state, /^[A-Za-z0-9_-]{22}$/); + + assert.equal(token.accessToken, "access-token-1"); + assert.equal(token.refreshToken, "refresh-token-1"); + assert.equal(token.identity, "theo@example.test"); + // The id_token's email claim is surfaced so connect can show the account. + assert.equal(identity, "theo@example.test"); + + assert.lengthOf(requests, 1); + const exchange = requests[0]!; + assert.equal(exchange.url, "https://clerk.example.test/oauth/token"); + assert.equal(exchange.params.get("grant_type"), "authorization_code"); + assert.equal(exchange.params.get("code"), "clerk-code-123"); + assert.equal( + exchange.params.get("redirect_uri"), + "https://hosted.example.test/connect/callback", + ); + assert.equal(exchange.params.get("client_id"), "oauth_client_test"); + // The verifier must hash to the challenge advertised in the authorize URL. + const verifier = exchange.params.get("code_verifier"); + assert.isNotNull(verifier); + const crypto = yield* Crypto.Crypto; + const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier!)); + assert.equal(Encoding.encodeBase64Url(digest), request!.challenge); + }), + ); + + it.effect("rejects out-of-band codes whose state does not match the request", () => + Effect.gen(function* () { + const requests: Array = []; + + const validationErrors: Array = []; + const result = yield* CliTokenManager.outOfBandOAuthLogin( + ({ validate }: OutOfBandOAuthPromptInput) => + validate("clerk-code-123.wrong-state").pipe( + Effect.tapError((message) => Effect.sync(() => validationErrors.push(message))), + Effect.mapError((message) => new PromptRejectedError({ message })), + ), + ).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv, Effect.flip); + + assert.lengthOf(requests, 0); + assert.lengthOf(validationErrors, 1); + assert.include(validationErrors[0], "different connect request"); + assert.instanceOf(result, PromptRejectedError); + }), + ); + + it.effect("ignores an id_token whose claims are not valid JSON", () => + Effect.gen(function* () { + const requests: Array = []; + const malformedIdToken = `header.${Encoding.encodeBase64Url("not-json")}.signature`; + + const { identity } = yield* CliTokenManager.outOfBandOAuthLogin( + ({ authorizeUrl }: OutOfBandOAuthPromptInput) => { + const request = readConnectAuthorizeRequest(new URL(authorizeUrl)); + assert.isNotNull(request); + return Effect.succeed(`clerk-code-123.${request!.state}`); + }, + ).pipe( + Effect.provide(makeTokenEndpointLayer(requests, { idToken: malformedIdToken })), + provideTestEnv, + ); + + assert.isNull(identity); + assert.lengthOf(requests, 1); + }), + ); + + it.effect("fails without touching the token endpoint when the prompt returns garbage", () => + Effect.gen(function* () { + const requests: Array = []; + + const result = yield* CliTokenManager.outOfBandOAuthLogin(() => + Effect.succeed("not-a-connect-code"), + ).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv, Effect.flip); + + assert.lengthOf(requests, 0); + assert.isTrue(isAuthorizationError(result)); + }), + ); +}); diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.ts index 00709370b2..f01599bb96 100644 --- a/apps/server/src/cloud/CliTokenManager.ts +++ b/apps/server/src/cloud/CliTokenManager.ts @@ -3,6 +3,7 @@ import * as NodeHttp from "node:http"; import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import * as Clock from "effect/Clock"; +import * as Cause from "effect/Cause"; import * as Console from "effect/Console"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; @@ -12,8 +13,10 @@ import * as Effect from "effect/Effect"; import * as Encoding from "effect/Encoding"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; +import * as Terminal from "effect/Terminal"; import * as HttpClient from "effect/unstable/http/HttpClient"; import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest"; import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse"; @@ -21,19 +24,105 @@ import * as HttpRouter from "effect/unstable/http/HttpRouter"; import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse"; +import { + buildConnectAuthorizeRequestUrl, + buildConnectClerkAuthorizeUrl, + checkConnectAuthCode, + connectCallbackUrl, +} from "@t3tools/shared/connectAuth"; + import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; -import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts"; +import * as ExternalLauncher from "../process/externalLauncher.ts"; +import { + cloudCliOAuthConfig, + hostedAppUrlConfig, + type CloudCliOAuthConfig, +} from "./publicConfig.ts"; +import { renderLoopbackAuthorizationCompleteHtml } from "./cliAuthHtml.ts"; const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token"; const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10); const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5)); +const boldTerminalText = (value: string): string => `\u001b[1m${value}\u001b[22m`; + +export function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string { + return [ + "Open this URL to authorize T3 Connect:", + ` ${authorizationUrl}`, + "", + `Press ${boldTerminalText("Enter")} to open it in your browser.`, + `No browser on this device? Press ${boldTerminalText("H")} to switch to headless mode.`, + ].join("\n"); +} + +export type LoopbackAuthorizationResult = + | { readonly _tag: "AuthorizationCode"; readonly code: string } + | { readonly _tag: "HeadlessRequested" }; + +const readLoopbackAuthorizationAction = Effect.fn( + "cloud.cli_token.read_loopback_authorization_action", +)(function* (input: Queue.Dequeue) { + while (true) { + const event = yield* Queue.take(input).pipe(Effect.mapError(() => new Terminal.QuitError({}))); + const keyName = event.key.name.toLowerCase(); + if (!event.key.ctrl && !event.key.meta && keyName === "h") { + return "headless" as const; + } + if (keyName === "enter" || keyName === "return") { + return "open-browser" as const; + } + } +}); + +export const waitForLoopbackAuthorization = Effect.fn( + "cloud.cli_token.wait_for_loopback_authorization", +)(function* (input: { + readonly authorizationUrl: string; + readonly callback: Effect.Effect; + readonly terminal: Terminal.Terminal; + readonly launchBrowser: ( + url: string, + ) => Effect.Effect; +}) { + return yield* Effect.scoped( + Effect.gen(function* () { + const terminalInput = yield* input.terminal.readInput; + while (true) { + const result = yield* Effect.raceFirst( + input.callback.pipe( + Effect.map( + (code): LoopbackAuthorizationResult => ({ _tag: "AuthorizationCode", code }), + ), + ), + readLoopbackAuthorizationAction(terminalInput), + ); + if (typeof result !== "string") { + return result; + } + if (result === "headless") { + return { _tag: "HeadlessRequested" } as const; + } + yield* input + .launchBrowser(input.authorizationUrl) + .pipe( + Effect.catch(() => + Console.warn( + `Could not open a browser on this device. Open the URL above manually, or press ${boldTerminalText("H")} to switch to headless mode.`, + ), + ), + ); + } + }), + ); +}); const PersistedToken = Schema.Struct({ accessToken: Schema.String, refreshToken: Schema.String, expiresAtEpochMs: Schema.Number, + identity: Schema.optional(Schema.String), }); -type PersistedToken = typeof PersistedToken.Type; +export type PersistedToken = typeof PersistedToken.Type; const PersistedTokenJson = Schema.fromJsonString(PersistedToken); const decodePersistedToken = Schema.decodeUnknownEffect(PersistedTokenJson); @@ -42,10 +131,39 @@ const encodePersistedToken = Schema.encodeEffect(PersistedTokenJson); const OAuthTokenResponse = Schema.Struct({ access_token: Schema.String, refresh_token: Schema.optional(Schema.String), + id_token: Schema.optional(Schema.String), expires_in: Schema.Number, token_type: Schema.String, }); +const OidcIdentityClaimsJson = Schema.fromJsonString( + Schema.Struct({ + email: Schema.optional(Schema.String), + preferred_username: Schema.optional(Schema.String), + sub: Schema.optional(Schema.String), + }), +); +const decodeOidcIdentityClaimsJson = Schema.decodeUnknownOption(OidcIdentityClaimsJson); + +/** + * Best-effort read of the `email` (or fallback) claim from an OIDC id_token. + * Only used to show the operator which account they linked, so a malformed + * token degrades to "no identity" rather than an error. + */ +function idTokenIdentity(idToken: string | undefined): string | null { + if (!idToken) return null; + const payload = idToken.split(".")[1]; + if (!payload) return null; + const decoded = Encoding.decodeBase64UrlString(payload); + if (decoded._tag !== "Success") return null; + const claims = decodeOidcIdentityClaimsJson(decoded.success); + if (Option.isNone(claims)) return null; + for (const value of [claims.value.email, claims.value.preferred_username, claims.value.sub]) { + if (typeof value === "string" && value.length > 0) return value; + } + return null; +} + export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass()( "CloudCliCredentialRemovalError", { cause: Schema.Defect() }, @@ -103,18 +221,18 @@ export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type; export class CloudCliTokenManager extends Context.Service< CloudCliTokenManager, { - readonly get: Effect.Effect; + readonly get: Effect.Effect< + | { readonly _tag: "Authorized"; readonly token: PersistedToken } + | { readonly _tag: "HeadlessRequested" }, + CloudCliTokenManagerError | Terminal.QuitError + >; readonly getExisting: Effect.Effect, CloudCliTokenManagerError>; readonly hasCredential: Effect.Effect; + readonly store: (token: PersistedToken) => Effect.Effect; readonly clear: Effect.Effect; } >()("t3/cloud/CliTokenManager/CloudCliTokenManager") {} -const wrapError = - (makeError: (cause: unknown) => WrappedError) => - (effect: Effect.Effect): Effect.Effect => - effect.pipe(Effect.mapError(makeError)); - function stringToBytes(value: string): Uint8Array { return new TextEncoder().encode(value); } @@ -123,10 +241,101 @@ function bytesToString(value: Uint8Array): string { return new TextDecoder().decode(value); } -export const make = Effect.gen(function* () { - const crypto = yield* Crypto.Crypto; +const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* ( + metadata: Pick, + params: Record, +) { const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk); + const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe( + HttpClientRequest.bodyUrlParams(params), + httpClient.execute, + Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)), + ); + const now = yield* Clock.currentTimeMillis; + const identity = idTokenIdentity(response.id_token); + return { + token: { + accessToken: response.access_token, + refreshToken: response.refresh_token ?? params.refresh_token ?? "", + expiresAtEpochMs: now + response.expires_in * 1_000, + ...(identity === null ? {} : { identity }), + } satisfies PersistedToken, + identity, + }; +}); + +const makePkceRequest = Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; + const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32)); + const challenge = Encoding.encodeBase64Url( + yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)), + ); + const state = Encoding.encodeBase64Url(yield* crypto.randomBytes(16)); + return { verifier, challenge, state }; +}); + +export interface OutOfBandOAuthPromptInput { + readonly authorizeUrl: string; + readonly validate: (value: string) => Effect.Effect; +} + +/** + * Out-of-band OAuth for machines without a local browser (SSH). The user + * opens the hosted /connect URL elsewhere, signs in, and enters the displayed + * code in this terminal. The PKCE verifier never leaves this process, so the + * authorization code is useless to an observer, and the state bundled into + * the blob preserves the loopback flow's CSRF check. + */ +export const outOfBandOAuthLogin = Effect.fn("cloud.cli_token.out_of_band_oauth_login")(function* < + E, + R, +>(promptForCode: (input: OutOfBandOAuthPromptInput) => Effect.Effect) { + const metadata = yield* cloudCliOAuthConfig; + const hostedAppUrl = yield* hostedAppUrlConfig; + const { verifier, challenge, state } = yield* makePkceRequest; + + const authorizationCode = yield* promptForCode({ + authorizeUrl: buildConnectAuthorizeRequestUrl({ hostedAppUrl, state, challenge }), + validate: (value) => { + const checked = checkConnectAuthCode(value, state); + return typeof checked === "string" ? Effect.fail(checked) : Effect.succeed(value); + }, + }).pipe( + // Clerk authorization codes expire on this horizon anyway; matching the + // loopback flow's timeout turns an abandoned prompt into a clear error. + Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT), + Effect.catchTag("TimeoutError", (cause) => + Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })), + ), + ); + // promptForCode is caller-supplied, so re-check the returned value rather + // than trusting that the prompt ran validate. + const authCode = checkConnectAuthCode(authorizationCode, state); + if (typeof authCode === "string") { + return yield* new CloudCliAuthorizationError({ cause: authCode }); + } + + return yield* exchangeToken(metadata, { + grant_type: "authorization_code", + code: authCode.code, + redirect_uri: connectCallbackUrl(hostedAppUrl), + client_id: metadata.clientId, + code_verifier: verifier, + }); +}); + +export const make = Effect.gen(function* () { + // Capture exactly the services the login/refresh flows need at build time + // (matching the behavior before the out-of-band flow captured the instances), not + // the whole ambient context. + const crypto = yield* Crypto.Crypto; + const httpClient = yield* HttpClient.HttpClient; + const services = Context.make(Crypto.Crypto, crypto).pipe( + Context.add(HttpClient.HttpClient, httpClient), + ); const secrets = yield* ServerSecretStore.ServerSecretStore; + const terminal = yield* Terminal.Terminal; + const externalLauncher = yield* ExternalLauncher.ExternalLauncher; const semaphore = yield* Semaphore.make(1); const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) { const encoded = yield* encodePersistedToken(token); @@ -136,7 +345,7 @@ export const make = Effect.gen(function* () { const clear = secrets .remove(CLOUD_CLI_OAUTH_TOKEN_SECRET) - .pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause }))); + .pipe(Effect.mapError((cause) => new CloudCliCredentialRemovalError({ cause }))); const read = Effect.fn("cloud.cli_token.read")(function* () { const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET); @@ -144,39 +353,21 @@ export const make = Effect.gen(function* () { return Option.some(yield* decodePersistedToken(bytesToString(encoded.value))); }); - const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* ( - metadata: CloudCliOAuthConfig, - params: Record, - ) { - const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe( - HttpClientRequest.bodyUrlParams(params), - httpClient.execute, - Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)), - ); - const now = yield* Clock.currentTimeMillis; - return { - accessToken: response.access_token, - refreshToken: response.refresh_token ?? params.refresh_token ?? "", - expiresAtEpochMs: now + response.expires_in * 1_000, - } satisfies PersistedToken; - }); - const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) { const metadata = yield* cloudCliOAuthConfig; - return yield* exchangeToken(metadata, { + const { token: refreshed } = yield* exchangeToken(metadata, { grant_type: "refresh_token", refresh_token: token.refreshToken, client_id: metadata.clientId, }); + return refreshed.identity === undefined && token.identity !== undefined + ? { ...refreshed, identity: token.identity } + : refreshed; }); const login = Effect.fn("cloud.cli_token.login")(function* () { const metadata = yield* cloudCliOAuthConfig; - const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32)); - const challenge = Encoding.encodeBase64Url( - yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)), - ); - const state = yield* crypto.randomUUIDv4; + const { verifier, challenge, state } = yield* makePkceRequest; const callback = yield* Deferred.make(); const callbackRoute = HttpRouter.add( "GET", @@ -191,14 +382,7 @@ export const make = Effect.gen(function* () { }); } yield* Deferred.succeed(callback, code); - return yield* HttpServerResponse.html` - - -

T3 Connect authorization complete

-

You can close this window and return to your terminal.

- - -`; + return HttpServerResponse.html(renderLoopbackAuthorizationCompleteHtml()); }), ); yield* HttpRouter.serve(callbackRoute, { @@ -214,32 +398,37 @@ export const make = Effect.gen(function* () { ), Layer.build, ); - const authorizationUrl = new URL(metadata.authorizationEndpoint); - authorizationUrl.searchParams.set("client_id", metadata.clientId); - authorizationUrl.searchParams.set("redirect_uri", metadata.redirectUri); - authorizationUrl.searchParams.set("response_type", "code"); - authorizationUrl.searchParams.set("scope", metadata.scopes.join(" ")); - authorizationUrl.searchParams.set("state", state); - authorizationUrl.searchParams.set("code_challenge", challenge); - authorizationUrl.searchParams.set("code_challenge_method", "S256"); - yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`); - const code = yield* Deferred.await(callback).pipe( - Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT), - Effect.catchTag("TimeoutError", (cause) => - Effect.fail( - new CloudCliAuthorizationTimeoutError({ - cause, - }), + const authorizationUrl = buildConnectClerkAuthorizeUrl({ + authorizationEndpoint: metadata.authorizationEndpoint, + clientId: metadata.clientId, + redirectUri: metadata.redirectUri, + scopes: metadata.scopes, + state, + challenge, + }); + yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl)); + const authorization = yield* waitForLoopbackAuthorization({ + authorizationUrl, + callback: Deferred.await(callback).pipe( + Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT), + Effect.catchTag("TimeoutError", (cause) => + Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })), ), ), - ); - return yield* exchangeToken(metadata, { + terminal, + launchBrowser: externalLauncher.launchBrowser, + }); + if (authorization._tag === "HeadlessRequested") { + return authorization; + } + const { token } = yield* exchangeToken(metadata, { grant_type: "authorization_code", - code, + code: authorization.code, redirect_uri: metadata.redirectUri, client_id: metadata.clientId, code_verifier: verifier, }); + return { _tag: "Authorized", token } as const; }); const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () { @@ -253,24 +442,50 @@ export const make = Effect.gen(function* () { }); const getExisting = semaphore.withPermits(1)( - getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))), + getExistingNoLock().pipe( + Effect.mapError((cause) => new CloudCliCredentialRefreshError({ cause })), + Effect.provide(services), + ), ); const hasCredential = semaphore.withPermits(1)( read().pipe( Effect.map(Option.isSome), - wrapError((cause) => new CloudCliCredentialReadError({ cause })), + Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })), ), ); const get = semaphore.withPermits(1)( Effect.gen(function* () { - const token = yield* getExistingNoLock(); - return Option.isSome(token) - ? token.value - : yield* Effect.scoped(login()).pipe(Effect.flatMap(persist)); - }).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))), + // A stored credential that can't be read or refreshed (corrupt, revoked, + // expired grant) must fall through to a fresh login rather than dead-end + // the command — authorizeCli applies the same fallback to out-of-band + // authorization. + const token = yield* getExistingNoLock().pipe( + Effect.orElseSucceed(() => Option.none()), + ); + if (Option.isSome(token)) { + return { _tag: "Authorized", token: token.value } as const; + } + const authorization = yield* Effect.scoped(login()); + return authorization._tag === "Authorized" + ? ({ _tag: "Authorized", token: yield* persist(authorization.token) } as const) + : authorization; + }).pipe( + Effect.mapError((cause) => + Terminal.isQuitError(cause) ? cause : new CloudCliAuthorizationError({ cause }), + ), + Effect.provide(services), + ), ); + const store = Effect.fn("cloud.cli_token.store")(function* (token: PersistedToken) { + yield* semaphore.withPermits(1)( + persist(token).pipe( + Effect.asVoid, + Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })), + ), + ); + }); - return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear }); + return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear }); }); export const layer = Layer.effect(CloudCliTokenManager, make); diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts new file mode 100644 index 0000000000..a24d54697d --- /dev/null +++ b/apps/server/src/cloud/bootService.test.ts @@ -0,0 +1,529 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; + +import { + HostProcessArguments, + HostProcessExecutablePath, + HostProcessPlatform, +} from "@t3tools/shared/hostProcess"; + +import * as ProcessRunner from "../processRunner.ts"; +import * as BootService from "./bootService.ts"; + +const isUnsupportedError = Schema.is(BootService.BootServiceUnsupportedError); +const isCommandError = Schema.is(BootService.BootServiceCommandError); + +interface RecordedCommand { + readonly command: string; + readonly args: ReadonlyArray; +} + +const makeRecordingRunnerLayer = ( + commands: Array, + options?: { + readonly failCommand?: string; + readonly failWhen?: (command: string, args: ReadonlyArray) => boolean; + }, +) => + Layer.succeed( + ProcessRunner.ProcessRunner, + ProcessRunner.ProcessRunner.of({ + run: (input) => + Effect.sync(() => { + assert.isUndefined(input.env); + commands.push({ command: input.command, args: input.args }); + const failed = + input.command === options?.failCommand || + options?.failWhen?.(input.command, input.args) === true; + return { + stdout: "", + stderr: failed ? `${input.command} exploded` : "", + code: ChildProcessSpawner.ExitCode(failed ? 1 : 0), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + }; + }), + }), + ); + +const makeHost = (entry: string): BootService.BootServiceHost => ({ + execPath: "/usr/local/bin/node", + cliEntryPath: entry, +}); + +const provideHostRefs = (home: string, platform: NodeJS.Platform = "linux") => + Effect.provide( + Layer.mergeAll( + Layer.succeed(HostProcessPlatform, platform), + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })), + ), + ); + +const makeTestContext = Effect.fn("test.makeTestContext")(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" }); + // A real file for the stable-entry cases so status can confirm the entry + // point exists. + const stableEntry = path.join(root, "bin.mjs"); + yield* fs.writeFileString(stableEntry, "#!/usr/bin/env node\n"); + return { + fs, + path, + dirs: { + home: root, + baseDir: path.join(root, ".t3"), + logsDir: path.join(root, ".t3", "userdata", "logs"), + stableEntry, + }, + }; +}); + +it("renders a systemd unit with absolute paths and append-mode logging", () => { + const unit = BootService.renderBootServiceUnit({ + nodePath: "/usr/local/bin/node", + t3EntryPath: "/home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs", + baseDir: "/home/theo/.t3", + logPath: "/home/theo/.t3/userdata/logs/boot-service.log", + unitPath: "/home/theo/.config/systemd/user/t3code.service", + }); + + assert.equal( + unit, + [ + "[Unit]", + "Description=T3 Code server (T3 Connect)", + "StartLimitIntervalSec=300", + "StartLimitBurst=5", + "", + "[Service]", + "Type=simple", + "WorkingDirectory=%h", + "Environment=T3CODE_HOME=/home/theo/.t3", + "ExecStart=/usr/local/bin/node /home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs serve", + "Restart=always", + "RestartSec=5", + "StandardOutput=append:/home/theo/.t3/userdata/logs/boot-service.log", + "StandardError=append:/home/theo/.t3/userdata/logs/boot-service.log", + "", + "[Install]", + "WantedBy=default.target", + "", + ].join("\n"), + ); +}); + +it("quotes systemd values containing spaces and escapes percent specifiers", () => { + assert.equal(BootService.quoteSystemdValue("/plain/path"), "/plain/path"); + assert.equal(BootService.quoteSystemdValue("/home/me/T3 Data"), '"/home/me/T3 Data"'); + assert.equal(BootService.quoteSystemdValue("/opt/100%cpu"), "/opt/100%%cpu"); + + const unit = BootService.renderBootServiceUnit({ + nodePath: "/home/me/my tools/node", + t3EntryPath: "/home/me/T3 Data/bin.mjs", + baseDir: "/home/me/T3 Data", + logPath: "/home/me/100%logs/boot.log", + unitPath: "/home/me/.config/systemd/user/t3code.service", + }); + assert.include(unit, 'ExecStart="/home/me/my tools/node" "/home/me/T3 Data/bin.mjs" serve'); + assert.include(unit, 'Environment=T3CODE_HOME="/home/me/T3 Data"'); + // append: paths take the rest of the line literally (spaces are fine, + // quoting is not), but % still goes through specifier expansion. + assert.include(unit, "StandardOutput=append:/home/me/100%%logs/boot.log"); + assert.include(unit, "StandardError=append:/home/me/100%%logs/boot.log"); +}); + +it("flags package-manager cache entry points as ephemeral", () => { + assert.isTrue( + BootService.isEphemeralCacheEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"), + ); + assert.isTrue( + BootService.isEphemeralCacheEntry("C:\\Users\\theo\\AppData\\npm-cache\\_npx\\abc\\bin.mjs"), + ); + assert.isTrue( + BootService.isEphemeralCacheEntry( + "/home/theo/.cache/pnpm/dlx/abc/node_modules/t3/dist/bin.mjs", + ), + ); + assert.isTrue( + BootService.isEphemeralCacheEntry("/home/theo/.bun/install/cache/t3@0.0.27/dist/bin.mjs"), + ); + assert.isFalse(BootService.isEphemeralCacheEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs")); + assert.isFalse( + BootService.isEphemeralCacheEntry( + "/home/theo/dev/pnpm/dlx-tools/t3/node_modules/t3/dist/bin.mjs", + ), + ); + assert.isFalse( + BootService.isEphemeralCacheEntry( + "/home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs", + ), + ); +}); + +it.layer(NodeServices.layer)("BootService", (it) => { + it.effect("installs the unit, enables the service, and enables linger", () => + Effect.gen(function* () { + const { dirs, fs, path } = yield* makeTestContext(); + const commands: Array = []; + const service = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost(dirs.stableEntry), + }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home)); + + const plan = yield* service.install; + + // A stable entry point is reused directly — no npm install. + assert.equal(plan.t3EntryPath, dirs.stableEntry); + assert.deepEqual( + commands.map((entry) => [entry.command, ...entry.args].join(" ")), + [ + "systemctl --user daemon-reload", + "systemctl --user enable t3code.service", + // restart (not enable --now) so repairing a stale unit replaces a + // running process instead of leaving the old one until reboot. + "systemctl --user restart t3code.service", + "loginctl enable-linger", + ], + ); + + const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service"); + const unit = yield* fs.readFileString(unitPath); + assert.include(unit, `ExecStart=/usr/local/bin/node ${dirs.stableEntry} serve`); + assert.include(unit, `Environment=T3CODE_HOME=${dirs.baseDir}`); + + const status = yield* service.status; + assert.isTrue(status.supported); + assert.isTrue(status.installed); + assert.isTrue(status.current); + + const removed = yield* service.uninstall; + assert.isTrue(removed); + assert.isFalse(yield* fs.exists(unitPath)); + const statusAfter = yield* service.status; + assert.isFalse(statusAfter.installed); + const removedAgain = yield* service.uninstall; + assert.isFalse(removedAgain); + }), + ); + + it.effect("pins a runtime via npm install when running from the npx cache", () => + Effect.gen(function* () { + const { dirs, fs, path } = yield* makeTestContext(); + const commands: Array = []; + const service = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"), + }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home)); + + const plan = yield* service.install; + + const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27"); + assert.equal( + plan.t3EntryPath, + path.join(runtimeDir, "node_modules", "t3", "dist", "bin.mjs"), + ); + assert.deepEqual(commands[0], { + command: "npm", + args: ["install", "--prefix", runtimeDir, "--no-fund", "--no-audit", "t3@0.0.27"], + }); + // Success is recorded via a sentinel so interrupted installs re-run. + assert.isTrue(yield* fs.exists(path.join(runtimeDir, ".install-complete"))); + }), + ); + + it.effect("reinstalls a pinned runtime when its entry point is missing", () => + Effect.gen(function* () { + const { dirs, fs, path } = yield* makeTestContext(); + const commands: Array = []; + const service = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"), + }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home)); + + const plan = yield* service.install; + yield* fs.makeDirectory(path.dirname(plan.t3EntryPath), { recursive: true }); + yield* fs.writeFileString(plan.t3EntryPath, "#!/usr/bin/env node\n"); + yield* fs.remove(plan.t3EntryPath); + commands.length = 0; + + yield* service.install; + + assert.isTrue(commands.some(({ command }) => command === "npm")); + }), + ); + + it.effect("reads executable metadata from host process references", () => + Effect.gen(function* () { + const { dirs } = yield* makeTestContext(); + const commands: Array = []; + const service = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + }).pipe( + Effect.provide(makeRecordingRunnerLayer(commands)), + provideHostRefs(dirs.home), + Effect.provideService(HostProcessExecutablePath, "/opt/node/bin/node"), + Effect.provideService(HostProcessArguments, ["/opt/node/bin/node", dirs.stableEntry]), + ); + + const plan = yield* service.install; + assert.equal(plan.nodePath, "/opt/node/bin/node"); + assert.equal(plan.t3EntryPath, dirs.stableEntry); + }), + ); + + it.effect("cleans up and fails when the pinned runtime install fails", () => + Effect.gen(function* () { + const { dirs, fs, path } = yield* makeTestContext(); + const commands: Array = []; + const service = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"), + }).pipe( + Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "npm" })), + provideHostRefs(dirs.home), + ); + + const error = yield* service.install.pipe(Effect.flip); + assert.isTrue(isCommandError(error)); + const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27"); + // The half-installed tree must not be reused by the next attempt. + assert.isFalse(yield* fs.exists(runtimeDir)); + assert.isFalse(yield* fs.exists(path.join(runtimeDir, ".install-complete"))); + }), + ); + + it.effect("reports an installed-but-stale unit so connect can offer a repair", () => + Effect.gen(function* () { + const { dirs, fs, path } = yield* makeTestContext(); + const commands: Array = []; + const service = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost(dirs.stableEntry), + }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home)); + + const unitDir = path.join(dirs.home, ".config", "systemd", "user"); + yield* fs.makeDirectory(unitDir, { recursive: true }); + yield* fs.writeFileString( + path.join(unitDir, "t3code.service"), + "[Service]\nExecStart=/old/node /old/t3 serve\n", + ); + + const status = yield* service.status; + assert.isTrue(status.supported); + assert.isTrue(status.installed); + assert.isFalse(status.current); + }), + ); + + it.effect("reports a current unit as stale when its entry point is gone", () => + Effect.gen(function* () { + const { dirs, fs } = yield* makeTestContext(); + const commands: Array = []; + const service = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost(dirs.stableEntry), + }).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home)); + + yield* service.install; + assert.isTrue((yield* service.status).current); + + // The pinned runtime (or global bin) was deleted to reclaim space; the + // unit still matches byte-for-byte but would crashloop at boot. + yield* fs.remove(dirs.stableEntry); + const status = yield* service.status; + assert.isTrue(status.installed); + assert.isFalse(status.current); + }), + ); + + it.effect("fails on non-Linux platforms without touching the filesystem", () => + Effect.gen(function* () { + const { dirs, fs, path } = yield* makeTestContext(); + const commands: Array = []; + const service = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"), + }).pipe( + Effect.provide(makeRecordingRunnerLayer(commands)), + provideHostRefs(dirs.home, "darwin"), + ); + + const error = yield* service.install.pipe(Effect.flip); + assert.isTrue(isUnsupportedError(error)); + assert.lengthOf(commands, 0); + assert.isFalse( + yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")), + ); + + const status = yield* service.status; + assert.isFalse(status.supported); + assert.isFalse(status.installed); + }), + ); + + it.effect("removes the unit file when an activation step fails", () => + Effect.gen(function* () { + const { dirs, fs, path } = yield* makeTestContext(); + const commands: Array = []; + const service = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"), + }).pipe( + Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "loginctl" })), + provideHostRefs(dirs.home), + ); + + const error = yield* service.install.pipe(Effect.flip); + assert.isTrue(isCommandError(error)); + // A leftover unit would make the next connect report "already set up" + // even though linger never happened. + assert.isFalse( + yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")), + ); + const status = yield* service.status; + assert.isFalse(status.installed); + assert.isTrue( + commands.some( + ({ command, args }) => + command === "systemctl" && args.join(" ") === "--user disable --now t3code.service", + ), + ); + }), + ); + + it.effect("restores the previous unit when a repair cannot activate", () => + Effect.gen(function* () { + const { dirs, fs, path } = yield* makeTestContext(); + const initialCommands: Array = []; + const initialService = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost(dirs.stableEntry), + }).pipe( + Effect.provide(makeRecordingRunnerLayer(initialCommands)), + provideHostRefs(dirs.home), + ); + yield* initialService.install; + + const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service"); + const previousUnit = yield* fs.readFileString(unitPath); + const replacementEntry = path.join(dirs.home, "replacement-bin.mjs"); + yield* fs.writeFileString(replacementEntry, "#!/usr/bin/env node\n"); + const repairCommands: Array = []; + const repairService = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.28", + host: makeHost(replacementEntry), + }).pipe( + Effect.provide(makeRecordingRunnerLayer(repairCommands, { failCommand: "loginctl" })), + provideHostRefs(dirs.home), + ); + + const error = yield* repairService.install.pipe(Effect.flip); + + assert.isTrue(isCommandError(error)); + assert.equal(yield* fs.readFileString(unitPath), previousUnit); + assert.isTrue( + repairCommands.some( + ({ command, args }) => + command === "systemctl" && args.join(" ") === "--user restart t3code.service", + ), + ); + }), + ); + + it.effect("keeps the unit when stopping it during uninstall fails", () => + Effect.gen(function* () { + const { dirs, fs, path } = yield* makeTestContext(); + const installCommands: Array = []; + const installedService = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost(dirs.stableEntry), + }).pipe( + Effect.provide(makeRecordingRunnerLayer(installCommands)), + provideHostRefs(dirs.home), + ); + yield* installedService.install; + + const uninstallCommands: Array = []; + const failingService = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost(dirs.stableEntry), + }).pipe( + Effect.provide( + makeRecordingRunnerLayer(uninstallCommands, { + failWhen: (command, args) => + command === "systemctl" && args.includes("disable") && args.includes("--now"), + }), + ), + provideHostRefs(dirs.home), + ); + + const error = yield* failingService.uninstall.pipe(Effect.flip); + + assert.isTrue(isCommandError(error)); + assert.isTrue( + yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")), + ); + }), + ); + + it.effect("appends failed steps to the boot-service log", () => + Effect.gen(function* () { + const { dirs, fs, path } = yield* makeTestContext(); + const commands: Array = []; + const service = yield* BootService.make({ + baseDir: dirs.baseDir, + logsDir: dirs.logsDir, + cliVersion: "0.0.27", + host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"), + }).pipe( + Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "systemctl" })), + provideHostRefs(dirs.home), + ); + + const error = yield* service.install.pipe(Effect.flip); + assert.isTrue(isCommandError(error)); + if (!isCommandError(error)) return; + assert.equal(error.exitCode, 1); + assert.equal(error.stderrLength, "systemctl exploded".length); + + const logPath = path.join(dirs.logsDir, "boot-service.log"); + assert.isTrue(yield* fs.exists(logPath)); + assert.include(yield* fs.readFileString(logPath), "exit code 1"); + }), + ); +}); diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts new file mode 100644 index 0000000000..0662b36704 --- /dev/null +++ b/apps/server/src/cloud/bootService.ts @@ -0,0 +1,452 @@ +import * as Context from "effect/Context"; +import * as Config from "effect/Config"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { + HostProcessArguments, + HostProcessExecutablePath, + HostProcessPlatform, +} from "@t3tools/shared/hostProcess"; + +import * as ProcessRunner from "../processRunner.ts"; + +/** + * Installs T3 Code as a per-user boot service so a connected machine stays + * reachable through T3 Connect after the SSH session ends. Linux-only for + * now: systemd user unit + loginctl enable-linger. The service runs a pinned + * runtime installed under /runtime — never `npx t3`, whose cache is + * ephemeral and whose registry fetch at boot would make startup depend on + * the network. + */ + +const BOOT_SERVICE_NAME = "t3code"; +const BOOT_RUNTIME_DIR = "runtime"; + +const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`; +const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10); + +const EPHEMERAL_CACHE_SEGMENTS = [ + "/_npx/", // npx + "\\_npx\\", + "/pnpm/dlx/", // pnpm dlx (~/.cache/pnpm/dlx and $PNPM_HOME/.pnpm/dlx) + "/.pnpm/dlx/", + "/.bun/install/cache/", // bunx +]; + +/** + * `npx t3` (and pnpm dlx / bunx) run out of ephemeral package-manager + * caches that can be evicted at any time — a boot service must never point + * there. Global installs, repo checkouts, and the pinned runtime below are + * all stable. + */ +export function isEphemeralCacheEntry(entryPath: string): boolean { + return EPHEMERAL_CACHE_SEGMENTS.some((segment) => entryPath.includes(segment)); +} + +/** + * systemd expands `%` specifiers in most directive values, including the + * `append:` file paths, which take the rest of the line literally and must + * NOT be quoted. + */ +export function escapeSystemdSpecifiers(value: string): string { + return value.replaceAll("%", "%%"); +} + +/** + * systemd word-splits ExecStart and Environment values and expands `%` + * specifiers, so paths with spaces or percents must be quoted and escaped. + */ +export function quoteSystemdValue(value: string): string { + const escaped = escapeSystemdSpecifiers(value); + return /[\s"'\\]/.test(escaped) + ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"` + : escaped; +} + +export interface BootServicePlan { + /** Absolute path of the node binary running this CLI. */ + readonly nodePath: string; + /** Absolute path of the pinned t3 entry point the unit will run. */ + readonly t3EntryPath: string; + readonly baseDir: string; + readonly logPath: string; + readonly unitPath: string; +} + +/** + * Pure so it is testable byte-for-byte. systemd user units run with a + * minimal environment: every path must be absolute, and the service must + * not rely on PATH, nvm shims, or shell profiles. Failures land in + * `logPath` because `systemctl --user` failures are otherwise invisible. + */ +export function renderBootServiceUnit(plan: BootServicePlan): string { + // No After=network-online.target: it does not exist in the systemd *user* + // manager, so ordering on it is silently ignored. The server retries its + // relay connection, and Restart=always covers early-boot failures. + return [ + "[Unit]", + "Description=T3 Code server (T3 Connect)", + // Give up after 5 crashes in 5 minutes so a persistently broken install + // (deleted runtime, broken workspace) stops instead of restarting every + // 5s forever and growing the unrotated append log without bound. + "StartLimitIntervalSec=300", + "StartLimitBurst=5", + "", + "[Service]", + "Type=simple", + "WorkingDirectory=%h", + `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`, + `ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.t3EntryPath)} serve`, + "Restart=always", + "RestartSec=5", + `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`, + `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`, + "", + "[Install]", + "WantedBy=default.target", + "", + ].join("\n"); +} + +export class BootServiceUnsupportedError extends Schema.TaggedErrorClass()( + "BootServiceUnsupportedError", + { platform: Schema.String }, +) { + override get message(): string { + return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`; + } +} + +export class BootServiceCommandError extends Schema.TaggedErrorClass()( + "BootServiceCommandError", + { + step: Schema.String, + exitCode: Schema.optional(Schema.Number), + stdoutLength: Schema.optional(Schema.Number), + stderrLength: Schema.optional(Schema.Number), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return this.exitCode === undefined + ? `Background setup failed while ${this.step}.` + : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`; + } +} + +export class BootServiceInstallError extends Schema.TaggedErrorClass()( + "BootServiceInstallError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not set up the T3 Code background service."; + } +} + +export type BootServiceError = + | BootServiceUnsupportedError + | BootServiceCommandError + | BootServiceInstallError; + +export interface BootServiceStatus { + readonly supported: boolean; + readonly installed: boolean; + /** False when the installed unit no longer matches what install would write. */ + readonly current: boolean; + readonly unitPath: string; + readonly logPath: string; +} + +export class BootService extends Context.Service< + BootService, + { + /** Installs the pinned runtime + unit, enables linger, starts the service. */ + readonly install: Effect.Effect; + /** + * Stops and removes the unit; leaves the pinned runtime for reuse. + * Returns whether a unit was actually removed. + */ + readonly uninstall: Effect.Effect; + readonly status: Effect.Effect; + } +>()("t3/cloud/bootService") {} + +export interface BootServiceHost { + readonly execPath: string; + readonly cliEntryPath: string; +} + +export const make = Effect.fn("cloud.boot_service.make")(function* (input: { + readonly baseDir: string; + readonly logsDir: string; + readonly cliVersion: string; + readonly host?: BootServiceHost; +}) { + const hostExecPath = yield* HostProcessExecutablePath; + const hostArguments = yield* HostProcessArguments; + const host = input.host ?? { + execPath: hostExecPath, + // When running the packed CLI this is dist/bin.mjs; when stable (global + // install, repo checkout) the boot service runs this same artifact. + cliEntryPath: hostArguments[1] ?? "", + }; + const platform = yield* HostProcessPlatform; + const homeDir = yield* Config.string("HOME").pipe(Config.withDefault("")); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const runner = yield* ProcessRunner.ProcessRunner; + + const unitDir = path.join(homeDir, ".config", "systemd", "user"); + const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE); + const logPath = path.join(input.logsDir, "boot-service.log"); + const runtimeVersionDir = path.join( + input.baseDir, + BOOT_RUNTIME_DIR, + "versions", + input.cliVersion, + ); + const runtimeEntryPath = path.join(runtimeVersionDir, "node_modules", "t3", "dist", "bin.mjs"); + const runtimeSentinelPath = path.join(runtimeVersionDir, ".install-complete"); + + const requireSystemdLinux = Effect.gen(function* () { + if (platform !== "linux" || homeDir === "") { + return yield* new BootServiceUnsupportedError({ platform }); + } + }); + + const runStep = Effect.fn("cloud.boot_service.run_step")(function* ( + step: string, + command: string, + args: ReadonlyArray, + options?: { readonly timeout?: Duration.Input }, + ) { + return yield* runner.run({ command, args, timeout: options?.timeout }).pipe( + Effect.mapError((cause) => new BootServiceCommandError({ step, cause })), + Effect.filterOrFail( + (result) => result.code === 0, + (result) => + new BootServiceCommandError({ + step, + exitCode: Number(result.code), + stdoutLength: result.stdout.length, + stderrLength: result.stderr.length, + }), + ), + Effect.tapError((error) => + DateTime.now.pipe( + Effect.flatMap((now) => + fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { + flag: "a", + }), + ), + Effect.ignore, + ), + ), + ); + }); + + /** + * Ensures plannedEntryPath exists before the unit points at it. A stable + * install (global bin, repo checkout) is used as-is; an ephemeral cache + * entry is replaced by `npm install --prefix`-ing the exact running + * version into /runtime/versions/. A real install (not a copy + * of bin.mjs) because t3 ships native deps like node-pty. + */ + const ensurePinnedRuntime = Effect.gen(function* () { + if (!isEphemeralCacheEntry(host.cliEntryPath)) { + return; + } + // The sentinel is written only after npm exits 0. Checking the entry + // file alone is not enough: npm extracts files before running native + // builds (node-pty), so a killed install leaves a plausible-looking but + // broken tree behind. + const alreadyPinned = yield* Effect.all([ + fs.exists(runtimeSentinelPath), + fs.exists(runtimeEntryPath), + ]).pipe( + Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists), + Effect.mapError((cause) => new BootServiceInstallError({ cause })), + ); + if (alreadyPinned) { + return; + } + yield* fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe( + Effect.andThen(fs.makeDirectory(runtimeVersionDir, { recursive: true })), + Effect.mapError((cause) => new BootServiceInstallError({ cause })), + ); + yield* runStep( + "installing the pinned t3 runtime (this can take a few minutes)", + "npm", + [ + "install", + "--prefix", + runtimeVersionDir, + "--no-fund", + "--no-audit", + `t3@${input.cliVersion}`, + ], + // Native deps (node-pty) can compile from source on slow boxes; the + // ProcessRunner default of 60s would kill a healthy install. + { timeout: PINNED_RUNTIME_INSTALL_TIMEOUT }, + ).pipe( + Effect.tapError(() => + fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(Effect.ignore), + ), + ); + yield* fs + .writeFileString(runtimeSentinelPath, `${input.cliVersion}\n`) + .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); + }); + + // Where the unit will point: derivable without touching the network, so + // status can compare units purely; install materializes it first. + const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath) + ? runtimeEntryPath + : host.cliEntryPath; + const plan: BootServicePlan = { + nodePath: host.execPath, + t3EntryPath: plannedEntryPath, + baseDir: input.baseDir, + logPath, + unitPath, + }; + + const install: BootService["Service"]["install"] = Effect.gen(function* () { + yield* requireSystemdLinux; + yield* fs + .makeDirectory(input.logsDir, { recursive: true }) + .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); + + yield* ensurePinnedRuntime; + + const previousUnit = yield* fs.exists(unitPath).pipe( + Effect.flatMap((exists) => + exists + ? fs.readFileString(unitPath).pipe(Effect.map(Option.some)) + : Effect.succeed(Option.none()), + ), + Effect.mapError((cause) => new BootServiceInstallError({ cause })), + ); + + yield* fs.makeDirectory(unitDir, { recursive: true }).pipe( + Effect.andThen(fs.writeFileString(unitPath, renderBootServiceUnit(plan))), + Effect.mapError((cause) => new BootServiceInstallError({ cause })), + ); + + // If any activation step fails, remove the unit again: a leftover file + // would make the next `t3 connect` report the service as already set up + // even though it was never enabled or lingered. + yield* Effect.gen(function* () { + yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]); + yield* runStep("enabling the service", "systemctl", [ + "--user", + "enable", + BOOT_SERVICE_UNIT_FILE, + ]); + // restart rather than enable --now: --now does not replace an already + // running process, so repairing a stale unit would leave the old + // server running until reboot. restart also starts a stopped service. + yield* runStep("starting the service", "systemctl", [ + "--user", + "restart", + BOOT_SERVICE_UNIT_FILE, + ]); + // Linger keeps the user manager (and this service) running without an + // open session — the whole point on a box reached over SSH. No + // username argument: loginctl defaults to the calling user, which is + // always right, while $USER can be stale (su without -l) or unset. + yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]); + }).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit))); + + return plan; + }).pipe(Effect.withSpan("cloud.boot_service.install")); + + // If activation fails partway (e.g. enable succeeds but restart/linger + // fails), leave nothing behind: disable removes the enable symlink, remove + // deletes the file, daemon-reload clears the stale definition — otherwise a + // dangling wants/ symlink logs "Failed to load unit" at every boot and the + // next connect misreports the state. + const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* ( + previousUnit: Option.Option, + ) { + if (Option.isSome(previousUnit)) { + yield* fs.writeFileString(unitPath, previousUnit.value).pipe(Effect.ignore); + } else { + yield* runStep("cleaning up the service", "systemctl", [ + "--user", + "disable", + "--now", + BOOT_SERVICE_UNIT_FILE, + ]).pipe(Effect.ignore); + yield* fs.remove(unitPath).pipe(Effect.ignore); + } + yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]).pipe( + Effect.ignore, + ); + if (Option.isSome(previousUnit)) { + yield* runStep("restoring the previous service", "systemctl", [ + "--user", + "restart", + BOOT_SERVICE_UNIT_FILE, + ]).pipe(Effect.ignore); + } + }); + + const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () { + yield* requireSystemdLinux; + const exists = yield* fs + .exists(unitPath) + .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); + if (!exists) { + return false; + } + yield* runStep("stopping the service", "systemctl", [ + "--user", + "disable", + "--now", + BOOT_SERVICE_UNIT_FILE, + ]); + yield* fs + .remove(unitPath) + .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); + yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]); + return true; + }).pipe(Effect.withSpan("cloud.boot_service.uninstall")); + + const status: BootService["Service"]["status"] = Effect.gen(function* () { + if (platform !== "linux" || homeDir === "") { + return { supported: false, installed: false, current: false, unitPath, logPath }; + } + const unitExists = yield* fs.exists(unitPath); + if (!unitExists) { + return { supported: true, installed: false, current: false, unitPath, logPath }; + } + const unit = yield* fs.readFileString(unitPath); + // A unit is current only if it matches what install would write now (an + // older CLI wrote a different runtime/node path) AND the entry point it + // references still exists (a pinned runtime under ~/.t3 can be deleted to + // reclaim space). Either mismatch makes connect offer a repair. + const entryExists = yield* fs.exists(plannedEntryPath); + const current = unit === renderBootServiceUnit(plan) && entryExists; + return { supported: true, installed: true, current, unitPath, logPath }; + }).pipe( + Effect.mapError((cause) => new BootServiceInstallError({ cause })), + Effect.withSpan("cloud.boot_service.status"), + ); + + return BootService.of({ install, uninstall, status }); +}); + +export const layer = (input: { + readonly baseDir: string; + readonly logsDir: string; + readonly cliVersion: string; + readonly host?: BootServiceHost; +}) => Layer.effect(BootService, make(input)); diff --git a/apps/server/src/cloud/cliAuthHtml.test.ts b/apps/server/src/cloud/cliAuthHtml.test.ts new file mode 100644 index 0000000000..1104927b98 --- /dev/null +++ b/apps/server/src/cloud/cliAuthHtml.test.ts @@ -0,0 +1,31 @@ +import { expect, it } from "@effect/vitest"; + +import { + renderLoopbackAuthorizationCompleteHtml, + resolveLoopbackAuthorizationStage, +} from "./cliAuthHtml.ts"; + +it("renders the branded loopback authorization completion page", () => { + const html = renderLoopbackAuthorizationCompleteHtml(); + + expect(resolveLoopbackAuthorizationStage()).toBe("dev"); + expect(html).toContain("T3 Code (Dev)"); + expect(html).toContain('class="stage stage-dev"'); + expect(html).not.toContain("Secure terminal handoff"); + expect(html).toContain("You're connected"); + expect(html).toContain("Return to your terminal"); + expect(html).not.toContain('class="next"'); + expect(html).toContain('name="viewport"'); + expect(html).not.toContain('class="status"'); +}); + +it("renders the matching header treatment for each release channel", () => { + const nightly = renderLoopbackAuthorizationCompleteHtml("nightly"); + const latest = renderLoopbackAuthorizationCompleteHtml("latest"); + + expect(nightly).toContain("T3 Code (Nightly)"); + expect(nightly).toContain('class="stage stage-nightly"'); + expect(latest).toContain('

T3 Code

'); + expect(latest).not.toContain("(Latest)"); + expect(latest).toContain('class="stage stage-latest"'); +}); diff --git a/apps/server/src/cloud/cliAuthHtml.ts b/apps/server/src/cloud/cliAuthHtml.ts new file mode 100644 index 0000000000..5a22a25993 --- /dev/null +++ b/apps/server/src/cloud/cliAuthHtml.ts @@ -0,0 +1,155 @@ +export type LoopbackAuthorizationStage = "dev" | "nightly" | "latest"; + +declare const __T3CODE_BUILD_CHANNEL__: "nightly" | "latest" | undefined; + +export function resolveLoopbackAuthorizationStage(): LoopbackAuthorizationStage { + return typeof __T3CODE_BUILD_CHANNEL__ === "undefined" ? "dev" : __T3CODE_BUILD_CHANNEL__; +} + +const stageBrands = { + dev: "T3 Code (Dev)", + nightly: "T3 Code (Nightly)", + latest: "T3 Code", +} as const satisfies Record; + +export function renderLoopbackAuthorizationCompleteHtml( + stage: LoopbackAuthorizationStage = resolveLoopbackAuthorizationStage(), +): string { + const stageBrand = stageBrands[stage]; + + return ` + + + + + + T3 Connect authorization complete + + + +
+
+
+

${stageBrand}

+
+
+
+

Browser authorization complete

+

You're connected

+

Return to your terminal to finish setting up T3 Connect. You can close this window.

+
+
+ +`; +} diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index ed2e5a4cf7..96abf2e4b4 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -11,7 +11,13 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as CliTokenManager from "./CliTokenManager.ts"; -import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts"; +import type { RelayLinkProofRequest } from "@t3tools/contracts/relay"; +import { + consumeCloudReplayGuards, + isSupportedLinkProviderKind, + linkProofScopes, + reconcileDesiredCloudLink, +} from "./http.ts"; import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts"; import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts"; @@ -194,6 +200,7 @@ describe("reconcileDesiredCloudLink", () => { get: unusedSecretStoreOperation(), getExisting: Effect.succeed(Option.none()), hasCredential: unusedSecretStoreOperation(), + store: () => unusedSecretStoreOperation(), clear: unusedSecretStoreOperation(), }), ), @@ -205,3 +212,32 @@ describe("reconcileDesiredCloudLink", () => { ), ); }); + +describe("link proof provider kinds", () => { + const proofRequest = ( + providerKind: RelayLinkProofRequest["endpoint"]["providerKind"], + ): RelayLinkProofRequest => ({ + challenge: "challenge", + relayIssuer: "https://relay.example.test", + endpoint: { + httpBaseUrl: "http://127.0.0.1:7331", + wsBaseUrl: "ws://127.0.0.1:7331", + providerKind, + }, + origin: { localHttpHost: "127.0.0.1", localHttpPort: 7331 }, + }); + + it("accepts managed and manual endpoints but not t3_relay", () => { + expect(isSupportedLinkProviderKind(proofRequest("cloudflare_tunnel"))).toBe(true); + expect(isSupportedLinkProviderKind(proofRequest("manual"))).toBe(true); + expect(isSupportedLinkProviderKind(proofRequest("t3_relay"))).toBe(false); + }); + + it("only claims the managed-tunnel scope for tunnel links", () => { + expect(linkProofScopes(proofRequest("cloudflare_tunnel"))).toEqual([ + "agent_activity_notifications", + "managed_tunnels", + ]); + expect(linkProofScopes(proofRequest("manual"))).toEqual(["agent_activity_notifications"]); + }); +}); diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts index fc2adca9fb..92423bb215 100644 --- a/apps/server/src/cloud/http.ts +++ b/apps/server/src/cloud/http.ts @@ -68,7 +68,7 @@ import { RELAY_URL_SECRET, } from "./config.ts"; import { relayUrlConfig } from "./publicConfig.ts"; -import { setCliDesiredCloudLink } from "./CliState.ts"; +import { readCliDesiredLinkMode, setCliDesiredCloudLink } from "./CliState.ts"; import * as CliTokenManager from "./CliTokenManager.ts"; import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts"; import { traceRelayRequest } from "./traceRelayRequest.ts"; @@ -299,8 +299,23 @@ function isAllowedEndpointOrigin(input: { return input.origin.localHttpPort === endpointRequestPort(url); } -function providerKindMatchesRequestedLinkScopes(request: RelayLinkProofRequest): boolean { - return request.endpoint.providerKind === "cloudflare_tunnel"; +// A managed (Cloudflare tunnel) endpoint is provisioned by the relay and must +// point at a loopback origin. A manual endpoint is reached out of band (e.g. +// Tailscale) or not advertised at all for publish-only links, so it is not +// tied to the managed-tunnel scope. +export function isSupportedLinkProviderKind(request: RelayLinkProofRequest): boolean { + return ( + request.endpoint.providerKind === "cloudflare_tunnel" || + request.endpoint.providerKind === "manual" + ); +} + +export function linkProofScopes( + request: RelayLinkProofRequest, +): RelayEnvironmentLinkProofPayload["scopes"] { + return request.endpoint.providerKind === "cloudflare_tunnel" + ? ["agent_activity_notifications", "managed_tunnels"] + : ["agent_activity_notifications"]; } function hasExactScope(input: { @@ -352,7 +367,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function ) { const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets); if ( - !providerKindMatchesRequestedLinkScopes(request) || + !isSupportedLinkProviderKind(request) || !isAllowedEndpointOrigin({ origin: request.origin, requestUrl, @@ -379,7 +394,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey), endpoint: request.endpoint, origin: request.origin, - scopes: ["agent_activity_notifications", "managed_tunnels"], + scopes: linkProofScopes(request), } satisfies RelayEnvironmentLinkProofPayload; return yield* signRelayJwt({ privateKey: keyPair.privateKey, @@ -537,6 +552,8 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi }), ), ); + const mode = yield* readCliDesiredLinkMode; + const managedTunnelsEnabled = mode !== "publish_only"; const relayUrl = yield* requireRelayUrl; const challenge = yield* relayClientRequest(dependencies, { url: `${relayUrl}/v1/client/environment-link-challenges`, @@ -544,7 +561,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi payload: { notificationsEnabled: true, liveActivitiesEnabled: true, - managedTunnelsEnabled: true, + managedTunnelsEnabled, }, schema: RelayEnvironmentLinkChallengeResponse, }); @@ -556,7 +573,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi endpoint: { httpBaseUrl: localOrigin, wsBaseUrl: localWsOrigin, - providerKind: "cloudflare_tunnel", + providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual", }, origin: { localHttpHost: localUrl.hostname, @@ -572,11 +589,11 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi proof, notificationsEnabled: true, liveActivitiesEnabled: true, - managedTunnelsEnabled: true, + managedTunnelsEnabled, }, schema: RelayEnvironmentLinkResponse, }); - yield* setCliDesiredCloudLink(true); + yield* setCliDesiredCloudLink(true, mode); return yield* applyCloudRelayConfig(dependencies, { relayUrl, relayIssuer: link.relayIssuer, @@ -608,20 +625,25 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* ( dependencies: CloudHttpDependencies, ) { - const [cloudUserId, relayUrl, relayIssuer, publishAgentActivity] = yield* Effect.all( - [ - dependencies.secrets.get(CLOUD_LINKED_USER_ID), - dependencies.secrets.get(RELAY_URL_SECRET), - dependencies.secrets.get(RELAY_ISSUER_SECRET), - dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET), - ], - { concurrency: 4 }, - ); + const [cloudUserId, relayUrl, relayIssuer, endpointRuntimeConfig, publishAgentActivity] = + yield* Effect.all( + [ + dependencies.secrets.get(CLOUD_LINKED_USER_ID), + dependencies.secrets.get(RELAY_URL_SECRET), + dependencies.secrets.get(RELAY_ISSUER_SECRET), + dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG), + dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET), + ], + { concurrency: 5 }, + ); return { linked: Option.isSome(cloudUserId), cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null, relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null, relayIssuer: Option.isSome(relayIssuer) ? bytesToString(relayIssuer.value) : null, + // The managed tunnel runtime config is only stored for managed links; a + // publish-only link leaves it absent. + managedTunnelActive: Option.isSome(endpointRuntimeConfig), publishAgentActivity: Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) === "true" : false, diff --git a/apps/server/src/cloud/publicConfig.test.ts b/apps/server/src/cloud/publicConfig.test.ts index c46e2671a4..96a8a1b8b8 100644 --- a/apps/server/src/cloud/publicConfig.test.ts +++ b/apps/server/src/cloud/publicConfig.test.ts @@ -4,6 +4,7 @@ import * as Effect from "effect/Effect"; import * as Result from "effect/Result"; import { + hostedAppUrlConfig, makeCloudCliOAuthConfig, makeRelayUrlConfig, resolveRelayClientTracingConfig, @@ -47,6 +48,40 @@ it.effect("rejects an injected relay URL with a non-origin path", () => makeRelayUrlConfig("https://embedded.example.test/path").pipe(provideEnv({}), Effect.flip), ); +it.effect("normalizes the hosted app URL to an absolute origin", () => + Effect.gen(function* () { + assert.equal( + yield* hostedAppUrlConfig.pipe( + provideEnv({ T3CODE_HOSTED_APP_URL: "https://nightly.app.t3.codes" }), + ), + "https://nightly.app.t3.codes", + ); + assert.equal( + yield* hostedAppUrlConfig.pipe( + provideEnv({ T3CODE_HOSTED_APP_URL: "http://localhost:5733" }), + ), + "http://localhost:5733", + ); + }), +); + +it.effect("rejects malformed or insecure hosted app URLs", () => + Effect.gen(function* () { + for (const value of [ + "app.t3.codes", + "http://app.t3.codes", + "https://app.t3.codes/nested", + "https://app.t3.codes?alias=true", + ]) { + const result = yield* hostedAppUrlConfig.pipe( + provideEnv({ T3CODE_HOSTED_APP_URL: value }), + Effect.result, + ); + assert.isTrue(Result.isFailure(result), value); + } + }), +); + it.effect("derives direct Clerk OAuth endpoints from statically injected public config", () => Effect.gen(function* () { const config = yield* makeCloudCliOAuthConfig({ diff --git a/apps/server/src/cloud/publicConfig.ts b/apps/server/src/cloud/publicConfig.ts index 176b31d756..cb07d19721 100644 --- a/apps/server/src/cloud/publicConfig.ts +++ b/apps/server/src/cloud/publicConfig.ts @@ -1,3 +1,4 @@ +import { CONNECT_OAUTH_SCOPES, DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth"; import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth"; import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl"; import * as Config from "effect/Config"; @@ -15,7 +16,7 @@ declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefi declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined; const CLOUD_CLI_OAUTH_REDIRECT_URI = "http://127.0.0.1:34338/callback"; -const CLOUD_CLI_OAUTH_SCOPES = ["openid", "profile", "email"] as const; +const CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES; function validateRelayUrl(value: string) { const relayUrl = normalizeSecureRelayUrl(value); @@ -100,6 +101,44 @@ export function makeRelayUrlConfig(fallback = buildTimeRelayUrl) { export const relayUrlConfig = makeRelayUrlConfig(); +/** + * Hosted app origin used for out-of-band OAuth on headless + * machines. Overridable so staging/nightly builds can point their CLIs at a + * matching hosted deployment. + */ +export const hostedAppUrlConfig = makePublicValueConfig( + "T3CODE_HOSTED_APP_URL", + DEFAULT_HOSTED_APP_URL, +).pipe(Config.mapOrFail(validateHostedAppUrl)); + +function validateHostedAppUrl(value: string) { + try { + const url = new URL(value); + const isLoopbackHttp = + url.protocol === "http:" && + (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]"); + if ( + (url.protocol !== "https:" && !isLoopbackHttp) || + url.pathname !== "/" || + url.search !== "" || + url.hash !== "" + ) { + throw new Error("invalid hosted app origin"); + } + return Effect.succeed(url.origin); + } catch { + return Effect.fail( + new Config.ConfigError( + new Schema.SchemaError( + new SchemaIssue.InvalidValue(Option.some(value), { + message: "Hosted app URL must be an absolute HTTPS origin (or HTTP loopback origin).", + }), + ), + ), + ); + } +} + function makePublicValueConfig(name: string, fallback: string) { const runtimeConfig = Config.nonEmptyString(name); return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe( diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 7d73723813..9dbb390bb2 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -45,6 +45,10 @@ export interface ServerDerivedPaths { readonly secretsDir: string; } +export interface DeriveServerPathsOptions { + readonly baseDirIsExplicit?: boolean; +} + /** * ServerConfig - Service tag for server runtime configuration. */ @@ -91,9 +95,13 @@ export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerCo export const deriveServerPaths = Effect.fn(function* ( baseDir: ServerConfig["Service"]["baseDir"], devUrl: ServerConfig["Service"]["devUrl"], + options: DeriveServerPathsOptions = {}, ): Effect.fn.Return { const { join } = yield* Path.Path; - const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata-v2"); + const stateDir = join( + baseDir, + devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata-v2", + ); const dbPath = join(stateDir, "state.sqlite"); const attachmentsDir = join(stateDir, "attachments"); const logsDir = join(stateDir, "logs"); diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts index 6b3290246f..61892d53d6 100644 --- a/apps/server/src/environment/ServerEnvironment.test.ts +++ b/apps/server/src/environment/ServerEnvironment.test.ts @@ -67,6 +67,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { expect(first.environmentId).toBe(second.environmentId); expect(second.capabilities.repositoryIdentity).toBe(true); + expect(second.capabilities.connectionProbe).toBe(true); }), ); diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index b5fbd8e108..1c0d34ea5b 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -135,6 +135,7 @@ export const make = Effect.gen(function* () { serverVersion: packageJson.version, capabilities: { repositoryIdentity: true, + connectionProbe: true, }, }; diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index fc7a9ef13a..b9bb40f372 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -25,11 +25,7 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; import { OtlpTracer } from "effect/unstable/observability"; import * as ServerConfig from "./config.ts"; -import { - ASSET_ROUTE_PREFIX, - FALLBACK_PROJECT_FAVICON_SVG, - resolveAsset, -} from "./assets/AssetAccess.ts"; +import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts"; import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import { traceRelayRequest } from "./cloud/traceRelayRequest.ts"; @@ -196,17 +192,6 @@ export const assetRouteLayer = HttpRouter.add( if (!asset) { return HttpServerResponse.text("Not Found", { status: 404 }); } - if (asset.kind === "project-favicon-fallback") { - return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, { - status: 200, - contentType: "image/svg+xml", - headers: { - "Cache-Control": "private, max-age=3600", - "X-Content-Type-Options": "nosniff", - }, - }); - } - return yield* HttpServerResponse.file(asset.path, { status: 200, headers: { diff --git a/apps/server/src/imageMime.test.ts b/apps/server/src/imageMime.test.ts index cc1cc2ff77..e87e4dcbd0 100644 --- a/apps/server/src/imageMime.test.ts +++ b/apps/server/src/imageMime.test.ts @@ -32,6 +32,63 @@ describe("imageMime", () => { }); }); + it("rejects payload with characters outside the base64 alphabet", () => { + expect(parseBase64DataUrl("data:image/png;base64,SGVs!bG8=")).toBeNull(); + expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull(); + }); + + it("rejects structurally malformed base64", () => { + // '=' before the trailing padding position + expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull(); + expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull(); + // more than two padding characters + expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=====AAA")).toBeNull(); + // length not a multiple of 4 + expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8")).toBeNull(); + }); + + it("accepts base64 with one or two trailing padding characters", () => { + expect(parseBase64DataUrl("data:image/png;base64,SGVsbA==")).toEqual({ + mimeType: "image/png", + base64: "SGVsbA==", + }); + expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8h")).toEqual({ + mimeType: "image/png", + base64: "SGVsbG8h", + }); + }); + + it("rejects empty and whitespace-only payloads", () => { + expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull(); + expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull(); + }); + + it("parses a case-insensitive scheme and mime type", () => { + expect(parseBase64DataUrl("DATA:IMAGE/PNG;BASE64,SGVsbG8=")).toEqual({ + mimeType: "image/png", + base64: "SGVsbG8=", + }); + }); + + it("parses a multi-megabyte payload from a deep call stack", () => { + // Regression: matching the payload with a regex borrowed the JS call + // stack, so a ~10 MB image parsed inside fiber execution threw + // "RangeError: Maximum call stack size exceeded". + const dataUrl = `data:image/png;base64,${"A".repeat(14_000_000)}`; + const atDepth = (depth: number): ReturnType => + depth === 0 ? parseBase64DataUrl(dataUrl) : atDepth(depth - 1); + const findMaxDepth = (depth: number): number => { + try { + return findMaxDepth(depth + 1); + } catch { + return depth; + } + }; + const result = atDepth(Math.floor(findMaxDepth(0) * 0.85)); + expect(result?.mimeType).toBe("image/png"); + expect(result?.base64.length).toBe(14_000_000); + }); + it("does not read inherited keys from mime extension map", () => { expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin"); }); diff --git a/apps/server/src/imageMime.ts b/apps/server/src/imageMime.ts index c8761285ab..66ce6096e8 100644 --- a/apps/server/src/imageMime.ts +++ b/apps/server/src/imageMime.ts @@ -29,17 +29,43 @@ export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([ ".webp", ]); +// Whether `code` is a character the base64 payload may contain, aside from +// the whitespace handled separately below. +function isBase64Char(code: number): boolean { + return ( + (code >= 0x61 && code <= 0x7a) || // a-z + (code >= 0x41 && code <= 0x5a) || // A-Z + (code >= 0x30 && code <= 0x39) || // 0-9 + code === 0x2b || // + + code === 0x2f || // / + code === 0x3d // = + ); +} + +function isBase64Whitespace(code: number): boolean { + return code === 0x0d || code === 0x0a || code === 0x20; // \r \n space +} + +// Data URLs carry the full image payload, so this parser must never run a +// regex across the payload: V8's regex engine borrows the JS call stack, and +// matching a multi-megabyte string from a deep call stack (e.g. inside fiber +// execution) throws "Maximum call stack size exceeded". export function parseBase64DataUrl( dataUrl: string, ): { readonly mimeType: string; readonly base64: string } | null { - const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim()); - if (!match) return null; + const trimmed = dataUrl.trim(); + if (trimmed.slice(0, 5).toLowerCase() !== "data:") return null; + + const commaIndex = trimmed.indexOf(","); + if (commaIndex === -1) return null; + const header = trimmed.slice(5, commaIndex); + if (header.length === 0) return null; const headerParts: Array = []; - for (const part of (match[1] ?? "").split(";")) { - const trimmed = part.trim(); - if (trimmed.length > 0) { - headerParts.push(trimmed); + for (const part of header.split(";")) { + const partTrimmed = part.trim(); + if (partTrimmed.length > 0) { + headerParts.push(partTrimmed); } } if (headerParts.length < 2) { @@ -51,8 +77,37 @@ export function parseBase64DataUrl( } const mimeType = headerParts[0]?.toLowerCase(); - const base64 = match[2]?.replace(/\s+/g, ""); - if (!mimeType || !base64) return null; + if (!mimeType) return null; + + const payload = trimmed.slice(commaIndex + 1); + const runs: Array = []; + let runStart = -1; + for (let index = 0; index < payload.length; index += 1) { + const code = payload.charCodeAt(index); + if (isBase64Char(code)) { + if (runStart === -1) runStart = index; + continue; + } + if (!isBase64Whitespace(code)) return null; + if (runStart !== -1) { + runs.push(payload.slice(runStart, index)); + runStart = -1; + } + } + if (runStart !== -1) { + runs.push(payload.slice(runStart)); + } + const base64 = runs.length === 1 ? runs[0]! : runs.join(""); + if (base64.length === 0 || base64.length % 4 !== 0) return null; + const firstPad = base64.indexOf("="); + if (firstPad !== -1) { + // '=' is only valid as one or two trailing padding characters; Node's + // decoder would otherwise silently truncate at the first '='. + if (base64.length - firstPad > 2) return null; + for (let index = firstPad; index < base64.length; index += 1) { + if (base64.charCodeAt(index) !== 0x3d) return null; + } + } return { mimeType, base64 }; } diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index a51ad20afb..2eef6ac841 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -411,6 +411,28 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }).pipe(Effect.provide(makeKeybindingsLayer())), ); + it.effect("replacing with a rule that already exists elsewhere does not duplicate it", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + yield* writeKeybindingsConfig(keybindingsConfigPath, [ + { key: "mod+r", command: "script.run-tests.run" }, + { key: "mod+alt+r", command: "script.run-tests.run" }, + ]); + yield* Effect.gen(function* () { + const keybindings = yield* Keybindings.Keybindings; + return yield* keybindings.upsertKeybindingRule({ + key: "mod+alt+r", + command: "script.run-tests.run", + replace: { key: "mod+r", command: "script.run-tests.run" }, + }); + }); + + const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); + const persistedView = persisted.map(({ key, command }) => ({ key, command })); + assert.deepEqual(persistedView, [{ key: "mod+alt+r", command: "script.run-tests.run" }]); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + it.effect("removes only the targeted custom keybinding", () => Effect.gen(function* () { const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 5ddae4943f..18a78fe362 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -644,7 +644,9 @@ const make = Effect.gen(function* () { const nextConfig = [ ...customConfig.filter((entry) => { if (replaceTarget) { - return !isSameKeybindingRule(entry, replaceTarget); + return ( + !isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule) + ); } return !isSameKeybindingRule(entry, rule); }), diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index c53fa28710..ffdb8d15af 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -15,6 +15,7 @@ import { type OrchestrationV2ProviderThread, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; @@ -178,6 +179,7 @@ describe("AcpAdapterV2", () => { const instanceId = ProviderInstanceId.make("acp-test"); const adapter = makeAcpAdapterV2({ + crypto: yield* Crypto.Crypto, instanceId, flavor: { driver: ACP_TEST_DRIVER, @@ -235,6 +237,7 @@ describe("AcpAdapterV2", () => { ); const instanceId = ProviderInstanceId.make("acp-test"); const adapter = makeAcpAdapterV2({ + crypto: yield* Crypto.Crypto, instanceId, flavor: { driver: ACP_TEST_DRIVER, @@ -283,6 +286,7 @@ describe("AcpAdapterV2", () => { const protocolEvents = yield* Queue.bounded(256); const instanceId = ProviderInstanceId.make("acp-test"); const adapter = makeAcpAdapterV2({ + crypto: yield* Crypto.Crypto, instanceId, flavor: { driver: ACP_TEST_DRIVER, @@ -385,6 +389,7 @@ describe("AcpAdapterV2", () => { ); const instanceId = ProviderInstanceId.make("acp-test"); const adapter = makeAcpAdapterV2({ + crypto: yield* Crypto.Crypto, instanceId, flavor: { driver: ACP_TEST_DRIVER, @@ -471,6 +476,7 @@ describe("AcpAdapterV2", () => { const instanceId = ProviderInstanceId.make("acp-test"); const protocolEvents = yield* Queue.bounded(256); const adapter = makeAcpAdapterV2({ + crypto: yield* Crypto.Crypto, instanceId, flavor: { driver: ACP_TEST_DRIVER, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts index 5b3c51f787..2c247b5cbb 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts @@ -4,6 +4,7 @@ import { type ProviderReplayTranscript, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Crypto from "effect/Crypto"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -155,7 +156,7 @@ export function makeAcpReplayRuntime(input: { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - Scope.Scope + Crypto.Crypto | Scope.Scope > { const encodedTranscript = Buffer.from(JSON.stringify(input.transcript), "utf8").toString( "base64", diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts index c3e5dd1e84..5a6517d965 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts @@ -24,6 +24,7 @@ import { } from "@t3tools/contracts"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import * as Cause from "effect/Cause"; +import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -120,7 +121,7 @@ export interface AcpAdapterV2Flavor { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - Scope.Scope + Crypto.Crypto | Scope.Scope >; readonly resolveModelId?: (selection: ModelSelection) => string | undefined; readonly registerExtensions?: ( @@ -145,6 +146,7 @@ export interface AcpAdapterV2SubagentUpdate { export interface AcpAdapterV2Options { readonly instanceId: ProviderInstanceId; readonly flavor: AcpAdapterV2Flavor; + readonly crypto: Crypto.Crypto; readonly fileSystem: FileSystem.FileSystem; readonly idAllocator: IdAllocatorV2Shape; readonly serverConfig: ServerConfig["Service"]; @@ -635,25 +637,27 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const nativeLogging = options.nativeLogging?.(input.threadId); - const runtime = yield* flavor.makeRuntime({ - cwd: input.runtimePolicy.cwd ?? process.cwd(), - mcpServers: acpMcpServers(input.threadId), - interruptPromptOnCancel: false, - clientCapabilities: { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - elicitation: { form: {} }, - }, - clientInfo: { name: "t3-code", version: "0.0.0" }, - ...(nativeLogging?.requestLogger === undefined - ? {} - : { requestLogger: nativeLogging.requestLogger }), - protocolLogging: nativeLogging?.protocolLogging ?? { - logIncoming: true, - logOutgoing: true, - logger: () => Effect.void, - }, - }); + const runtime = yield* flavor + .makeRuntime({ + cwd: input.runtimePolicy.cwd ?? process.cwd(), + mcpServers: acpMcpServers(input.threadId), + interruptPromptOnCancel: false, + clientCapabilities: { + fs: { readTextFile: false, writeTextFile: false }, + terminal: false, + elicitation: { form: {} }, + }, + clientInfo: { name: "t3-code", version: "0.0.0" }, + ...(nativeLogging?.requestLogger === undefined + ? {} + : { requestLogger: nativeLogging.requestLogger }), + protocolLogging: nativeLogging?.protocolLogging ?? { + logIncoming: true, + logOutgoing: true, + logger: () => Effect.void, + }, + }) + .pipe(Effect.provideService(Crypto.Crypto, options.crypto)); const resolveItemOrdinal = Effect.fnUntraced(function* ( context: ActiveAcpTurn, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index acb2a48d57..04e5eda12d 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Crypto from "effect/Crypto"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; @@ -107,6 +108,7 @@ describe("AcpRegistryAdapterV2", () => { }); const instanceId = ProviderInstanceId.make("acp-registry-fixture"); const adapter = makeAcpRegistryAdapterV2({ + crypto: yield* Crypto.Crypto, instanceId, settings, environment: { diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts index 93cbc7f93f..0384fab0ac 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { AcpRegistrySettings } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Crypto from "effect/Crypto"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; @@ -41,6 +42,7 @@ export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: Ac const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const crypto = yield* Crypto.Crypto; const idAllocator = yield* IdAllocatorV2; const serverConfig = yield* ServerConfig; const replayDir = yield* fileSystem @@ -57,6 +59,7 @@ export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: Ac settings: REPLAY_SETTINGS, environment: {}, childProcessSpawner, + crypto, fileSystem, idAllocator, resolver: { diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts index 66e64d94d1..a88cedce11 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts @@ -49,6 +49,7 @@ export interface AcpRegistryAdapterV2Options { readonly settings: AcpRegistrySettings; readonly environment: NodeJS.ProcessEnv; readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; + readonly crypto: Crypto.Crypto; readonly fileSystem: FileSystem.FileSystem; readonly idAllocator: IdAllocatorV2["Service"]; readonly resolver: AcpRegistryResolverShape; @@ -59,7 +60,7 @@ export interface AcpRegistryAdapterV2Options { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - Scope.Scope + Crypto.Crypto | Scope.Scope >; readonly assertComplete?: Effect.Effect; } @@ -70,7 +71,7 @@ function makeAcpRegistryRuntime(options: AcpRegistryAdapterV2Options) { ): Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - Scope.Scope + Crypto.Crypto | Scope.Scope > => Effect.gen(function* () { const resolved = yield* options.resolver @@ -111,6 +112,7 @@ export function makeAcpRegistryAdapterV2(options: AcpRegistryAdapterV2Options) { return makeAcpAdapterV2({ instanceId: options.instanceId, flavor, + crypto: options.crypto, fileSystem: options.fileSystem, idAllocator: options.idAllocator, serverConfig: options.serverConfig, @@ -139,6 +141,7 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver< function* (input: ProviderAdapterDriverCreateInput) { const hostEnvironment = yield* HostProcessEnvironment; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const crypto = yield* Crypto.Crypto; const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocatorV2; const providerEventLoggers = yield* ProviderEventLoggers; @@ -152,6 +155,7 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver< settings: { ...input.config, enabled: input.enabled }, environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment), childProcessSpawner, + crypto, fileSystem, idAllocator, resolver, diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts index 68834a7126..18fb50d0b0 100644 --- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { GrokSettings } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Crypto from "effect/Crypto"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; @@ -34,6 +35,7 @@ export function makeGrokProviderAdapterRegistryReplayLayer(transcript: AcpReplay const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const crypto = yield* Crypto.Crypto; const idAllocator = yield* IdAllocatorV2; const serverConfig = yield* ServerConfig; const replayDir = yield* fileSystem @@ -50,6 +52,7 @@ export function makeGrokProviderAdapterRegistryReplayLayer(transcript: AcpReplay settings: DEFAULT_GROK_SETTINGS, environment: {}, childProcessSpawner, + crypto, fileSystem, idAllocator, serverConfig, diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts index f74db916d8..c4b652aa9f 100644 --- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts @@ -84,6 +84,7 @@ export interface GrokAdapterV2Options { readonly settings: GrokSettings; readonly environment: NodeJS.ProcessEnv; readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; + readonly crypto: Crypto.Crypto; readonly fileSystem: FileSystem.FileSystem; readonly idAllocator: IdAllocatorV2["Service"]; readonly serverConfig: ServerConfig["Service"]; @@ -93,7 +94,7 @@ export interface GrokAdapterV2Options { ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - Scope.Scope + Crypto.Crypto | Scope.Scope >; readonly assertComplete?: Effect.Effect; } @@ -149,6 +150,7 @@ export function makeGrokAdapterV2(options: GrokAdapterV2Options) { return makeAcpAdapterV2({ instanceId: options.instanceId, flavor, + crypto: options.crypto, fileSystem: options.fileSystem, idAllocator: options.idAllocator, serverConfig: options.serverConfig, @@ -172,6 +174,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver) { const hostEnvironment = yield* HostProcessEnvironment; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const crypto = yield* Crypto.Crypto; const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocatorV2; const providerEventLoggers = yield* ProviderEventLoggers; @@ -182,6 +185,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver + Effect.fail( + new OpenCodeRuntimeError({ + operation: "loadInventoryFromCli", + detail: "OpenCode replay does not load inventory.", + }), + ), } satisfies OpenCodeRuntimeShape); }), ); diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts new file mode 100644 index 0000000000..2e437ce4b2 --- /dev/null +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -0,0 +1,33 @@ +import type { ApplicationStoredEvent } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { coalesceShellApplicationEvents } from "./ShellStream.ts"; + +function project(sequence: number, id: string): ApplicationStoredEvent { + return { + sequence, + aggregateKind: "project", + aggregateId: id, + } as ApplicationStoredEvent; +} + +function thread(sequence: number, id: string): ApplicationStoredEvent { + return { + sequence, + event: { threadId: id }, + } as ApplicationStoredEvent; +} + +describe("coalesceShellApplicationEvents", () => { + it("keeps the newest event per aggregate and preserves sequence order", () => { + expect( + coalesceShellApplicationEvents([ + thread(2, "thread-a"), + project(3, "project-a"), + thread(4, "thread-b"), + thread(5, "thread-a"), + project(6, "project-a"), + ]).map((event) => event.sequence), + ).toEqual([4, 5, 6]); + }); +}); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index fc63bf738f..d15ed17b36 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -1,10 +1,28 @@ import type { + ApplicationStoredEvent, OrchestrationV2ArchivedShellStreamItem, OrchestrationV2ThreadShellSnapshot, OrchestrationV2ShellStreamItem, OrchestrationV2StoredEvent, } from "@t3tools/contracts"; +/** Keep only the newest shell-relevant event per project/thread aggregate. */ +export function coalesceShellApplicationEvents( + events: ReadonlyArray, +): ReadonlyArray { + const latestByAggregate = new Map(); + for (const stored of events) { + const key = + "aggregateKind" in stored + ? `project:${stored.aggregateId}` + : `thread:${stored.event.threadId}`; + latestByAggregate.set(key, stored); + } + return Array.from(latestByAggregate.values()).sort( + (left, right) => left.sequence - right.sequence, + ); +} + /** Converts a committed event and its resulting shell snapshot into one delta. */ export function shellStreamItemFromSnapshot(input: { readonly stored: OrchestrationV2StoredEvent; diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts new file mode 100644 index 0000000000..3756e0b9fe --- /dev/null +++ b/apps/server/src/orchestration-v2/http.ts @@ -0,0 +1,117 @@ +import { + AuthOrchestrationReadScope, + EnvironmentHttpApi, + type OrchestrationProjectShell, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Predicate from "effect/Predicate"; +import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { + annotateEnvironmentRequest, + failEnvironmentInternal, + failEnvironmentNotFound, + requireEnvironmentScope, +} from "../auth/http.ts"; +import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import * as OrchestrationEventStore from "../persistence/Services/OrchestrationEventStore.ts"; +import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts"; +import * as ThreadManagementService from "./ThreadManagementService.ts"; + +function isThreadNotFound(error: unknown): boolean { + return ( + Predicate.hasProperty(error, "cause") && + Predicate.hasProperty(error.cause, "_tag") && + error.cause._tag === "ProjectionStoreThreadNotFoundError" + ); +} + +/** + * Serves orchestration V2 snapshots over HTTP so clients can load the + * (potentially large) shell and thread projections off the socket — gzip + * compressible and cacheable — and then resume the WebSocket subscription via + * `afterSequence`. + */ +export const orchestrationHttpApiLayer = HttpApiBuilder.group( + EnvironmentHttpApi, + "orchestration", + Effect.fnUntraced(function* (handlers) { + const sql = yield* SqlClient.SqlClient; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; + const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService; + + const enrichProjectShells = Effect.fn("http.orchestration.enrichProjectShells")( + (projects: ReadonlyArray) => + Effect.forEach( + projects, + (project) => + projectEnrichment.getAvailable(project.workspaceRoot).pipe( + Effect.map((enrichment) => ({ + ...project, + repositoryIdentity: enrichment.repositoryIdentity, + })), + ), + { concurrency: 16 }, + ), + ); + + const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(function* () { + const base = yield* sql.withTransaction( + Effect.gen(function* () { + const projects = yield* projectionSnapshotQuery.getShellSnapshotWithoutEnrichment(); + const threads = yield* threadManagement.getShellSnapshot(); + return { + schemaVersion: threads.schemaVersion, + snapshotSequence: yield* applicationEvents.latestApplicationSequence, + projects: projects.projects, + threads: threads.threads, + archivedThreads: threads.archivedThreads, + } as const; + }), + ); + const projects = yield* enrichProjectShells(base.projects); + return { ...base, projects }; + }); + + return handlers + .handle( + "shellSnapshot", + Effect.fn("environment.orchestration.shellSnapshot")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + yield* requireEnvironmentScope(AuthOrchestrationReadScope); + return yield* loadShellSnapshot().pipe( + Effect.catch((cause) => + failEnvironmentInternal("orchestration_snapshot_failed", cause), + ), + ); + }), + ) + .handle( + "threadSnapshot", + Effect.fn("environment.orchestration.threadSnapshot")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + yield* requireEnvironmentScope(AuthOrchestrationReadScope); + const snapshot = yield* threadManagement.getThreadSnapshot(args.params.threadId).pipe( + Effect.catch( + Effect.fnUntraced(function* (error) { + if (isThreadNotFound(error)) { + return yield* failEnvironmentNotFound("thread_not_found"); + } + return yield* failEnvironmentInternal( + "orchestration_thread_snapshot_failed", + error, + ); + }), + ), + ); + return { + snapshotSequence: snapshot.snapshotSequence, + projection: snapshot.projection, + }; + }), + ); + }), +); diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts index a0ac914f80..3749a8c90c 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts @@ -311,8 +311,8 @@ const makeOrchestrationEngine = Effect.gen(function* () { Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }), ); - const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) => - eventStore.readFromSequence(fromSequenceExclusive); + const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) => + eventStore.readFromSequence(fromSequenceExclusive, limit); const dispatch: OrchestrationEngineShape["dispatch"] = (command) => Effect.gen(function* () { @@ -334,6 +334,11 @@ const makeOrchestrationEngine = Effect.gen(function* () { get streamDomainEvents(): OrchestrationEngineShape["streamDomainEvents"] { return Stream.fromPubSub(eventPubSub); }, + // The command read model's snapshotSequence tracks the latest committed + // event sequence (updated on the worker fiber). A plain property read is a + // consistent, committed value — reassignment of `commandReadModel` is + // atomic on the single-threaded event loop. + latestSequence: Effect.sync(() => commandReadModel.snapshotSequence), } satisfies OrchestrationEngineShape; }); diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 90e172c34a..62b4bc4d90 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -16,6 +16,7 @@ import { OrchestrationReadModel, OrchestrationShellSnapshot, OrchestrationThread, + OrchestrationThreadDetailSnapshot, type OrchestrationCheckpointSummary, type OrchestrationLatestTurn, type OrchestrationMessage, @@ -2050,6 +2051,35 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ); }); + const getThreadDetailSnapshot: ProjectionSnapshotQueryShape["getThreadDetailSnapshot"] = ( + threadId, + ) => + // Read the thread detail and the snapshot sequence within a single + // transaction so the sequence is consistent with the returned state; a + // projector update landing between two separate reads could otherwise return + // a sequence ahead of the thread detail, causing the client to resume from + // too far and drop events. + sql + .withTransaction( + Effect.gen(function* () { + const thread = yield* getThreadDetailById(threadId); + if (Option.isNone(thread)) { + return Option.none(); + } + const { snapshotSequence } = yield* getSnapshotSequence(); + return Option.some({ snapshotSequence, thread: thread.value }); + }), + ) + .pipe( + Effect.mapError((error) => + isPersistenceError(error) + ? error + : toPersistenceSqlError("ProjectionSnapshotQuery.getThreadDetailSnapshot:transaction")( + error, + ), + ), + ); + return { getCommandReadModel, getSnapshot, @@ -2065,6 +2095,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { getFullThreadDiffContext, getThreadShellById, getThreadDetailById, + getThreadDetailSnapshot, } satisfies ProjectionSnapshotQueryShape; }); diff --git a/apps/server/src/orchestration/Services/OrchestrationEngine.ts b/apps/server/src/orchestration/Services/OrchestrationEngine.ts index 998edf1e37..fbb827c5a8 100644 --- a/apps/server/src/orchestration/Services/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Services/OrchestrationEngine.ts @@ -29,10 +29,15 @@ export interface OrchestrationEngineShape { * Replay persisted orchestration events from an exclusive sequence cursor. * * @param fromSequenceExclusive - Sequence cursor (exclusive). + * @param limit - Maximum number of events to read. Defaults to the event + * store's page-bounded default; pass a higher value when the caller must + * read every event after the cursor (e.g. per-thread catch-up that filters + * a small subset out of a potentially larger global range). * @returns Stream containing ordered events. */ readonly readEvents: ( fromSequenceExclusive: number, + limit?: number, ) => Stream.Stream; /** @@ -54,6 +59,13 @@ export interface OrchestrationEngineShape { * This is a hot runtime stream (new events only), not a historical replay. */ readonly streamDomainEvents: Stream.Stream; + + /** + * The latest sequence reflected in the engine's authoritative command read + * model (0 if none). Used to gauge how far behind a resuming client is before + * choosing between an incremental replay and a fresh projected snapshot. + */ + readonly latestSequence: Effect.Effect; } /** diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts index 91991d3ddc..7d56588f73 100644 --- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts @@ -14,6 +14,7 @@ import type { OrchestrationReadModel, OrchestrationShellSnapshot, OrchestrationThread, + OrchestrationThreadDetailSnapshot, OrchestrationThreadShell, } from "@t3tools/contracts/legacy-orchestration"; import * as Context from "effect/Context"; @@ -166,6 +167,16 @@ export interface ProjectionSnapshotQueryShape { readonly getThreadDetailById: ( threadId: ThreadId, ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Read a single active thread detail together with the projection snapshot + * sequence in one consistent transaction, so the returned `snapshotSequence` + * exactly matches the state reflected in `thread` (no interleaving projector + * update between the two reads). + */ + readonly getThreadDetailSnapshot: ( + threadId: ThreadId, + ) => Effect.Effect, ProjectionRepositoryError>; } /** diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.ts index a0cc0eb38a..8ab1b53732 100644 --- a/apps/server/src/orchestration/commandInvariants.ts +++ b/apps/server/src/orchestration/commandInvariants.ts @@ -5,6 +5,7 @@ import type { OrchestrationReadModel, OrchestrationThread, } from "@t3tools/contracts/legacy-orchestration"; +import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import * as Effect from "effect/Effect"; import { OrchestrationCommandInvariantError } from "./Errors.ts"; @@ -70,6 +71,30 @@ export function requireProjectAbsent(input: { ); } +export function requireActiveProjectWorkspaceRootAbsent(input: { + readonly readModel: OrchestrationReadModel; + readonly command: OrchestrationCommand; + readonly workspaceRoot: string; + readonly exceptProjectId?: ProjectId; +}): Effect.Effect { + const normalizedWorkspaceRoot = normalizeProjectPathForComparison(input.workspaceRoot); + const existingProject = input.readModel.projects.find( + (project) => + project.deletedAt === null && + normalizeProjectPathForComparison(project.workspaceRoot) === normalizedWorkspaceRoot && + project.id !== input.exceptProjectId, + ); + if (existingProject === undefined) { + return Effect.void; + } + return Effect.fail( + invariantError( + input.command.type, + `Active project '${existingProject.id}' already exists for workspace root '${normalizedWorkspaceRoot}'.`, + ), + ); +} + export function requireThread(input: { readonly readModel: OrchestrationReadModel; readonly command: OrchestrationCommand; diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 4638b116e0..e5fd5d655c 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -12,6 +12,7 @@ import type * as PlatformError from "effect/PlatformError"; import { OrchestrationCommandInvariantError } from "./Errors.ts"; import { listThreadsByProjectId, + requireActiveProjectWorkspaceRootAbsent, requireProject, requireProjectAbsent, requireThread, @@ -111,6 +112,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command, projectId: command.projectId, }); + yield* requireActiveProjectWorkspaceRootAbsent({ + readModel, + command, + workspaceRoot: command.workspaceRoot, + exceptProjectId: command.projectId, + }); return { ...(yield* withEventBase({ @@ -138,6 +145,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command, projectId: command.projectId, }); + if (command.workspaceRoot !== undefined) { + yield* requireActiveProjectWorkspaceRootAbsent({ + readModel, + command, + workspaceRoot: command.workspaceRoot, + exceptProjectId: command.projectId, + }); + } const occurredAt = yield* nowIso; return { ...(yield* withEventBase({ @@ -313,11 +328,17 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" } case "thread.meta.update": { - yield* requireThread({ + const thread = yield* requireThread({ readModel, command, threadId: command.threadId, }); + const branch = + command.branch !== undefined && + command.expectedBranch !== undefined && + thread.branch !== command.expectedBranch + ? thread.branch + : command.branch; const occurredAt = yield* nowIso; return { ...(yield* withEventBase({ @@ -333,7 +354,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...(command.modelSelection !== undefined ? { modelSelection: command.modelSelection } : {}), - ...(command.branch !== undefined ? { branch: command.branch } : {}), + ...(branch !== undefined ? { branch } : {}), ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}), updatedAt: occurredAt, }, diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts index 88979fae04..234a065cd7 100644 --- a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts +++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts @@ -203,6 +203,20 @@ layer("OrchestrationEventStore", (it) => { assert.isTrue("aggregateKind" in applicationEvents[0]!); assert.isTrue("event" in applicationEvents[1]!); + const finiteReplay = yield* eventStore + .readApplicationEvents({ + afterSequence: baselineSequence, + throughSequence: threadEvent!.sequence, + }) + .pipe( + Stream.runCollect, + Effect.map((chunk) => Array.from(chunk)), + ); + assert.deepEqual( + finiteReplay.map((event) => event.sequence), + [projectEvent.sequence, threadEvent!.sequence], + ); + const legacyReplay = yield* eventStore.readFromSequence(projectEvent.sequence - 1).pipe( Stream.runCollect, Effect.map((chunk) => Array.from(chunk)), diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts index cf7db447d1..0beedd9956 100644 --- a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts @@ -504,7 +504,7 @@ const makeEventStore = Effect.gen(function* () { ), ); - const readApplicationEvents = (input: { + const readApplicationEventPage = (input: { readonly afterSequence: number; readonly throughSequence: number; readonly limit: number; @@ -534,7 +534,7 @@ const makeEventStore = Effect.gen(function* () { afterSequence: number, ): Stream.Stream => Stream.unwrap( - readApplicationEvents({ + readApplicationEventPage({ afterSequence, throughSequence: input.throughSequence, limit: READ_PAGE_SIZE, @@ -581,6 +581,7 @@ const makeEventStore = Effect.gen(function* () { readAgentEvents, latestAgentSequence, latestApplicationSequence, + readApplicationEvents: catchUpApplicationEvents, publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid), streamApplicationEvents, } satisfies OrchestrationEventStoreShape; diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index e2a6d96722..9f07f218d9 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -139,15 +139,11 @@ export interface RunMigrationsOptions { export const runMigrations = Effect.fn("runMigrations")(function* ({ toMigrationInclusive, }: RunMigrationsOptions = {}) { - yield* Effect.log( - toMigrationInclusive === undefined - ? "Running all migrations..." - : `Running migrations 1 through ${toMigrationInclusive}...`, - ); const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) }); - yield* Effect.log("Migrations ran successfully").pipe( - Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }), - ); + const migrations = executedMigrations.map(([id, name]) => `${id}_${name}`); + yield* migrations.length === 0 + ? Effect.logDebug("Database schema is current") + : Effect.log("Migrations ran successfully").pipe(Effect.annotateLogs({ migrations })); return executedMigrations; }); diff --git a/apps/server/src/persistence/ProviderSessionRuntime.ts b/apps/server/src/persistence/ProviderSessionRuntime.ts index 1cb31d99c4..bffdac594f 100644 --- a/apps/server/src/persistence/ProviderSessionRuntime.ts +++ b/apps/server/src/persistence/ProviderSessionRuntime.ts @@ -1,7 +1,9 @@ +import * as Arr from "effect/Array"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as Struct from "effect/Struct"; import * as SqlClient from "effect/unstable/sql/SqlClient"; @@ -275,18 +277,30 @@ export const make = Effect.gen(function* () { ), ), Effect.flatMap((rows) => + // Skip rows that no longer decode (e.g. written by an older build) + // instead of failing the whole list — one stale row must not disable + // every consumer that enumerates sessions, such as the reaper. Effect.forEach(rows, (row) => decodeRuntimeRow(row).pipe( - Effect.mapError((cause) => - PersistenceDecodeError.fromSchemaError( - "ProviderSessionRuntimeRepository.list:decodeRows", - cause, - { threadId: row.threadId }, - ), + Effect.map(Option.some), + Effect.catch((cause) => + Effect.logWarning("provider.session.runtime.row-skipped", { + threadId: row.threadId, + error: PersistenceDecodeError.fromSchemaError( + "ProviderSessionRuntimeRepository.list:decodeRows", + cause, + { threadId: row.threadId }, + ).message, + }).pipe(Effect.as(Option.none())), ), ), ), ), + Effect.map((decoded) => + Arr.filterMap(decoded, (row) => + Option.isSome(row) ? Result.succeed(row.value) : Result.failVoid, + ), + ), ); const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = ( diff --git a/apps/server/src/persistence/RepositoryErrorCorrelation.test.ts b/apps/server/src/persistence/RepositoryErrorCorrelation.test.ts index f7425200fd..379b06e2a2 100644 --- a/apps/server/src/persistence/RepositoryErrorCorrelation.test.ts +++ b/apps/server/src/persistence/RepositoryErrorCorrelation.test.ts @@ -182,7 +182,7 @@ describe("persistence error correlation", () => { }).pipe(Effect.provide(authPairingLinkLayer)), ); - it.effect("correlates provider runtime SQL and per-row decode failures by thread", () => + it.effect("skips undecodable provider runtime rows and correlates SQL failures by thread", () => Effect.gen(function* () { const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; const sql = yield* SqlClient.SqlClient; @@ -215,16 +215,24 @@ describe("persistence error correlation", () => { ) `; - const decodeError = yield* Effect.flip(runtimes.list()); - assert.instanceOf(decodeError, PersistenceErrors.PersistenceDecodeError); - assert.deepStrictEqual(decodeError.correlation, { threadId }); - assert.equal( - decodeError.message, - `Decode error in ProviderSessionRuntimeRepository.list:decodeRows: ${decodeError.issue}`, + const validThreadId = ThreadId.make("thread-valid"); + yield* runtimes.upsert({ + threadId: validThreadId, + providerName: "codex", + providerInstanceId: null, + adapterKey: "codex", + runtimeMode: "full-access", + status: "running", + lastSeenAt, + resumeCursor: null, + runtimePayload: null, + }); + + const listed = yield* runtimes.list(); + assert.deepStrictEqual( + listed.map((runtime) => runtime.threadId), + [validThreadId], ); - assert.notInclude(decodeError.issue, runtimePayload); - assert.notInclude(decodeError.message, runtimePayload); - assert.notInclude(decodeError.message, lastSeenAt); yield* sql`DROP TABLE provider_session_runtime`; const sqlFailure = yield* Effect.flip( diff --git a/apps/server/src/persistence/Services/OrchestrationEventStore.ts b/apps/server/src/persistence/Services/OrchestrationEventStore.ts index 801d4137a0..eb1f0cd7bb 100644 --- a/apps/server/src/persistence/Services/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/Services/OrchestrationEventStore.ts @@ -82,6 +82,12 @@ export interface OrchestrationEventStoreShape { readonly latestApplicationSequence: Effect.Effect; + /** Read the finite retained application-event range `(afterSequence, throughSequence]`. */ + readonly readApplicationEvents: (input: { + readonly afterSequence: number; + readonly throughSequence: number; + }) => Stream.Stream; + /** Publish only after the surrounding event/projection transaction commits. */ readonly publishCommitted: (events: ReadonlyArray) => Effect.Effect; diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts index 1b5bd2fe29..f3a659c75b 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.ts @@ -1,3 +1,5 @@ +import type { ProviderInteractionMode } from "@t3tools/contracts"; + const T3_CODE_BROWSER_TOOL_INSTRUCTIONS = ` ## T3 Code collaborative browser @@ -155,3 +157,26 @@ In Default mode, strongly prefer making reasonable assumptions and executing the ${T3_CODE_BROWSER_TOOL_INSTRUCTIONS} ${T3_CODE_THREAD_ORCHESTRATION_INSTRUCTIONS} `; + +export interface CodexRuntimeInfo { + readonly model: string; + readonly reasoningEffort: string; +} + +// Values come from trusted config, but keep the block single-line regardless. +function toSingleLine(value: string): string { + return value.replaceAll(/\s+/g, " ").trim(); +} + +export function buildCodexDeveloperInstructions( + interactionMode: ProviderInteractionMode, + runtime: CodexRuntimeInfo, +): string { + const base = + interactionMode === "plan" + ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS + : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS; + return `${base} + +In case you're asked: you are running in T3 Code through the Codex harness, as ${toSingleLine(runtime.model)} with ${toSingleLine(runtime.reasoningEffort)} reasoning effort. No need to mention this otherwise.`; +} diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index c4b95525b1..6934d79995 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -121,6 +121,7 @@ export const ClaudeDriver: ProviderDriver = { Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; + const { cwd } = yield* ServerConfig; const httpClient = yield* HttpClient.HttpClient; const serverSettings = yield* ServerSettingsService; const processEnv = mergeProviderInstanceEnvironment(environment); @@ -167,11 +168,11 @@ export const ClaudeDriver: ProviderDriver = { capacity: 1, timeToLive: CAPABILITIES_PROBE_TTL, lookup: () => - probeClaudeCapabilities(effectiveConfig, processEnv).pipe( + probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe( Effect.provideService(Path.Path, path), ), }); - const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig); + const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig, cwd); const checkProvider = checkClaudeProviderStatus( effectiveConfig, diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts new file mode 100644 index 0000000000..020fc48a46 --- /dev/null +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it } from "@effect/vitest"; +import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; +import { SpawnExecutableResolution } from "@t3tools/shared/shell"; +import * as Effect from "effect/Effect"; + +import { ClaudeExecutableFileCheck, resolveClaudeSdkExecutablePath } from "./ClaudeExecutable.ts"; + +const NPM_DIR = "C:\\Users\\dev\\AppData\\Roaming\\npm"; +const NPM_SHIM = `${NPM_DIR}\\claude.cmd`; +const NPM_PACKAGE_EXE = `${NPM_DIR}\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe`; +const NPM_PACKAGE_CLI = `${NPM_DIR}\\node_modules\\@anthropic-ai\\claude-code\\cli.js`; + +function withWindowsResolution(input: { + readonly resolvedCommand: string | undefined; + readonly existingFiles?: ReadonlyArray; +}) { + const existing = new Set(input.existingFiles ?? []); + return (effect: Effect.Effect) => + effect.pipe( + Effect.provideService(HostProcessPlatform, "win32"), + Effect.provideService(SpawnExecutableResolution, () => input.resolvedCommand), + Effect.provideService(ClaudeExecutableFileCheck, (filePath) => existing.has(filePath)), + ); +} + +describe("resolveClaudeSdkExecutablePath", () => { + it.effect("returns the configured path unchanged on non-Windows platforms", () => + Effect.gen(function* () { + expect( + yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( + Effect.provideService(HostProcessPlatform, "darwin"), + Effect.provideService(SpawnExecutableResolution, () => { + throw new Error("must not resolve on non-Windows platforms"); + }), + ), + ).toBe("claude"); + }), + ); + + it.effect("returns the resolved absolute path for native Windows executables", () => + Effect.gen(function* () { + const nativeBinary = "C:\\Users\\dev\\.local\\bin\\claude.exe"; + expect( + yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( + withWindowsResolution({ resolvedCommand: nativeBinary }), + ), + ).toBe(nativeBinary); + }), + ); + + it.effect("follows an npm launcher shim to the packaged native binary", () => + Effect.gen(function* () { + expect( + yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( + withWindowsResolution({ + resolvedCommand: NPM_SHIM, + existingFiles: [NPM_PACKAGE_EXE, NPM_PACKAGE_CLI], + }), + ), + ).toBe(NPM_PACKAGE_EXE); + }), + ); + + it.effect("follows .bat and .ps1 launcher shims the same way", () => + Effect.gen(function* () { + for (const shim of [`${NPM_DIR}\\claude.bat`, `${NPM_DIR}\\claude.ps1`]) { + expect( + yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( + withWindowsResolution({ + resolvedCommand: shim, + existingFiles: [NPM_PACKAGE_EXE], + }), + ), + ).toBe(NPM_PACKAGE_EXE); + } + }), + ); + + it.effect("normalizes mixed-case shim extensions before matching", () => + Effect.gen(function* () { + expect( + yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( + withWindowsResolution({ + resolvedCommand: `${NPM_DIR}\\claude.CMD`, + existingFiles: [NPM_PACKAGE_EXE], + }), + ), + ).toBe(NPM_PACKAGE_EXE); + }), + ); + + it.effect("falls back to cli.js when the package ships no native binary", () => + Effect.gen(function* () { + expect( + yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( + withWindowsResolution({ + resolvedCommand: NPM_SHIM, + existingFiles: [NPM_PACKAGE_CLI], + }), + ), + ).toBe(NPM_PACKAGE_CLI); + }), + ); + + it.effect("returns the configured path when a shim has no known package entry", () => + Effect.gen(function* () { + expect( + yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( + withWindowsResolution({ resolvedCommand: NPM_SHIM }), + ), + ).toBe("claude"); + }), + ); + + it.effect("returns the configured path when command resolution finds nothing", () => + Effect.gen(function* () { + expect( + yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( + withWindowsResolution({ resolvedCommand: undefined }), + ), + ).toBe("claude"); + }), + ); +}); diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.ts new file mode 100644 index 0000000000..febfdb26f9 --- /dev/null +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.ts @@ -0,0 +1,90 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; +import { SpawnExecutableResolution } from "@t3tools/shared/shell"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; + +/** + * Windows launcher-script extensions that Node cannot spawn without a shell + * (`spawn EINVAL` since Node 20.12) and that the Claude Agent SDK therefore + * cannot use as `pathToClaudeCodeExecutable`. + */ +const WINDOWS_SHIM_EXTENSIONS: ReadonlySet = new Set([".cmd", ".bat", ".ps1"]); + +/** + * Entry points of the npm `@anthropic-ai/claude-code` package relative to the + * global `node_modules` directory that sits next to the npm launcher shim. + * Newer package versions ship a native `bin/claude.exe`; older versions only + * ship `cli.js`, which the SDK runs with a JavaScript runtime. + */ +const NPM_PACKAGE_ENTRY_CANDIDATES = [ + ["node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe"], + ["node_modules", "@anthropic-ai", "claude-code", "cli.js"], +] as const; + +export type ExecutableFileCheck = (filePath: string) => boolean; + +function isExistingFile(filePath: string): boolean { + try { + return NodeFS.statSync(filePath).isFile(); + } catch { + return false; + } +} + +/** Injectable file-existence check so tests can run against a fake filesystem. */ +export const ClaudeExecutableFileCheck = Context.Reference( + "server/provider/Drivers/ClaudeExecutableFileCheck", + { + defaultValue: () => isExistingFile, + }, +); + +/** + * Resolves the configured Claude binary path into a value the Claude Agent + * SDK can spawn directly via `pathToClaudeCodeExecutable`. + * + * The SDK spawns the given path without a shell and without Windows PATH / + * PATHEXT resolution, so a bare command name like `claude` fails with + * "native binary not found" and an npm `claude.cmd` shim fails with + * `spawn EINVAL`. CLI probes avoid this via `resolveSpawnCommand`, which can + * fall back to `shell: true`; the SDK offers no such escape hatch. + * + * On Windows this resolves the command against PATH/PATHEXT and, when the + * result is an npm launcher shim, follows it to the real package entry + * (`bin/claude.exe`, or `cli.js` for older package versions). On other + * platforms the configured value is returned unchanged. + */ +export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecutablePath")( + function* (binaryPath: string, environment: NodeJS.ProcessEnv): Effect.fn.Return { + const platform = yield* HostProcessPlatform; + if (platform !== "win32") { + return binaryPath; + } + + const resolveExecutable = yield* SpawnExecutableResolution; + const isFile = yield* ClaudeExecutableFileCheck; + const resolved = resolveExecutable(binaryPath, platform, environment) ?? binaryPath; + const extension = NodePath.win32.extname(resolved).toLowerCase(); + if (!WINDOWS_SHIM_EXTENSIONS.has(extension)) { + return resolved; + } + + const shimDirectory = NodePath.win32.dirname(resolved); + for (const entrySegments of NPM_PACKAGE_ENTRY_CANDIDATES) { + const candidate = NodePath.win32.join(shimDirectory, ...entrySegments); + if (isFile(candidate)) { + return candidate; + } + } + + yield* Effect.logWarning( + "Claude launcher shim resolved but no known package entry was found next to it; the Claude Agent SDK cannot spawn launcher scripts directly.", + { binaryPath, resolvedShimPath: resolved }, + ); + return binaryPath; + }, +); diff --git a/apps/server/src/provider/Drivers/ClaudeHome.test.ts b/apps/server/src/provider/Drivers/ClaudeHome.test.ts index 87298f8012..a7ff41fc89 100644 --- a/apps/server/src/provider/Drivers/ClaudeHome.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeHome.test.ts @@ -31,14 +31,23 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => { const resolved = path.resolve(NodeOS.homedir(), ".claude-work"); expect(yield* resolveClaudeHomePath({ homePath })).toBe(resolved); - expect((yield* makeClaudeEnvironment({ homePath })).HOME).toBe(resolved); + expect((yield* makeClaudeEnvironment({ homePath })).CLAUDE_CONFIG_DIR).toBe(resolved); expect(yield* makeClaudeContinuationGroupKey({ homePath })).toBe(`claude:home:${resolved}`); expect(yield* makeClaudeCapabilitiesCacheKey({ binaryPath: "claude", homePath })).toBe( - `claude\0${resolved}`, + `claude\0${resolved}\0`, ); }), ); + it.effect("separates capability probes by cwd", () => + Effect.gen(function* () { + const config = { binaryPath: "claude", homePath: "" }; + const first = yield* makeClaudeCapabilitiesCacheKey(config, "/repo-a"); + const second = yield* makeClaudeCapabilitiesCacheKey(config, "/repo-b"); + expect(first).not.toBe(second); + }), + ); + it.effect("keeps continuation compatible across instances with the same Claude HOME", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/provider/Drivers/ClaudeHome.ts b/apps/server/src/provider/Drivers/ClaudeHome.ts index 65c74f9764..b3ef22b640 100644 --- a/apps/server/src/provider/Drivers/ClaudeHome.ts +++ b/apps/server/src/provider/Drivers/ClaudeHome.ts @@ -24,7 +24,13 @@ export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function const resolvedHomePath = yield* resolveClaudeHomePath(config); return { ...resolvedBaseEnv, - HOME: resolvedHomePath, + // Isolate this instance's config via CLAUDE_CONFIG_DIR rather than HOME. + // Overriding HOME also relocates the macOS login keychain lookup + // ($HOME/Library/Keychains), so the spawned CLI can't find its stored + // OAuth credentials and reports "Not logged in". CLAUDE_CONFIG_DIR points + // Claude Code at its config dir directly while leaving HOME (and the + // keychain) intact. + CLAUDE_CONFIG_DIR: resolvedHomePath, }; }); @@ -38,8 +44,9 @@ export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationG export const makeClaudeCapabilitiesCacheKey = Effect.fn("makeClaudeCapabilitiesCacheKey")( function* ( config: Pick, + cwd?: string, ): Effect.fn.Return { const resolvedHomePath = yield* resolveClaudeHomePath(config); - return `${config.binaryPath}\0${resolvedHomePath}`; + return `${config.binaryPath}\0${resolvedHomePath}\0${cwd ?? ""}`; }, ); diff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts index ec78b1665e..03c717abb1 100644 --- a/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts +++ b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts @@ -114,6 +114,9 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => { const sessionsTarget = yield* fileSystem.readLink(path.join(shadowHome, "sessions")); const configTarget = yield* fileSystem.readLink(path.join(shadowHome, "config.toml")); + const mcpOauthLocksTarget = yield* fileSystem.readLink( + path.join(shadowHome, "mcp-oauth-locks"), + ); const modelsCacheExists = yield* fileSystem.exists( path.join(shadowHome, "models_cache.json"), ); @@ -124,12 +127,45 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => { expect(sessionsTarget).toBe(path.join(sharedHome, "sessions")); expect(configTarget).toBe(path.join(sharedHome, "config.toml")); + expect(mcpOauthLocksTarget).toBe(path.join(sharedHome, "mcp-oauth-locks")); expect(modelsCacheExists).toBe(false); expect(authLinkResult._tag).toBe("Failure"); expect(authContents).toContain("shadow"); }), ); + it.effect("replaces Codex-created local MCP OAuth locks with the shared lock directory", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const sharedHome = yield* makeTempDir("t3code-codex-shared-"); + const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-"); + const shadowHome = path.join(shadowRoot, "shadow"); + const sharedLocks = path.join(sharedHome, "mcp-oauth-locks"); + const shadowLocks = path.join(shadowHome, "mcp-oauth-locks"); + + yield* writeTextFile(path.join(sharedLocks, "file-store.lock"), ""); + yield* writeTextFile(path.join(shadowLocks, "file-store.lock"), ""); + + const layout = yield* resolveCodexHomeLayout( + decodeCodexSettings({ + homePath: sharedHome, + shadowHomePath: shadowHome, + }), + ); + + yield* materializeCodexShadowHome(layout); + + const locksTarget = yield* fileSystem.readLink(shadowLocks); + const sharedLockExists = yield* fileSystem.exists( + path.join(sharedLocks, "file-store.lock"), + ); + + expect(locksTarget).toBe(sharedLocks); + expect(sharedLockExists).toBe(true); + }), + ); + it.effect("accepts Codex-created shadow-local runtime directories", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.ts index d2d09e9d84..92e923c0b6 100644 --- a/apps/server/src/provider/Drivers/CodexHomeLayout.ts +++ b/apps/server/src/provider/Drivers/CodexHomeLayout.ts @@ -26,10 +26,12 @@ const KNOWN_SHARED_DIRECTORIES = [ "plugins", "cache", "logs", + "mcp-oauth-locks", ] as const; const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "models_cache.json"]); const SHADOW_LOCAL_ENTRY_NAMES = new Set(["log", "memories", "tmp"]); +const REPLACEABLE_SHARED_RUNTIME_DIRECTORIES = new Set(["mcp-oauth-locks"]); function resolveHomePath(path: Path.Path, value: string | undefined): string { const expanded = @@ -225,16 +227,6 @@ const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (inpu linkPath: link, }); - if (state._tag === "NotSymlink") { - return yield* new CodexShadowHomeEntryConflictError({ - sharedHomePath: input.sharedHomePath, - effectiveHomePath: input.effectiveHomePath, - entryName: input.entryName, - linkPath: link, - targetPath: target, - }); - } - const createLink = input.fileSystem.symlink(target, link).pipe( Effect.catchTags({ PlatformError: (cause) => @@ -250,6 +242,33 @@ const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (inpu }), ); + if (state._tag === "NotSymlink") { + if (!REPLACEABLE_SHARED_RUNTIME_DIRECTORIES.has(input.entryName)) { + return yield* new CodexShadowHomeEntryConflictError({ + sharedHomePath: input.sharedHomePath, + effectiveHomePath: input.effectiveHomePath, + entryName: input.entryName, + linkPath: link, + targetPath: target, + }); + } + + yield* input.fileSystem.remove(link, { recursive: true }).pipe( + Effect.catchTags({ + PlatformError: (cause) => + new CodexShadowHomeFileSystemError({ + sharedHomePath: input.sharedHomePath, + effectiveHomePath: input.effectiveHomePath, + operation: "remove", + path: link, + entryName: input.entryName, + cause, + }), + }), + ); + return yield* createLink; + } + if (state._tag === "Missing") { return yield* createLink; } diff --git a/apps/server/src/provider/Drivers/GrokDriver.ts b/apps/server/src/provider/Drivers/GrokDriver.ts index f5cc9528cd..c152fa2efe 100644 --- a/apps/server/src/provider/Drivers/GrokDriver.ts +++ b/apps/server/src/provider/Drivers/GrokDriver.ts @@ -86,6 +86,7 @@ export const GrokDriver: ProviderDriver = { defaultConfig: (): GrokSettings => decodeGrokSettings({}), create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const serverSettings = yield* ServerSettingsService; @@ -128,6 +129,7 @@ export const GrokDriver: ProviderDriver = { const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe( Effect.map(stampIdentity), + Effect.provideService(Crypto.Crypto, crypto), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ); diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index bd5f7ebffc..ff0d199245 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -2,7 +2,6 @@ import { type ClaudeSettings, type ModelCapabilities, type ModelSelection, - ProviderDriverKind, type ServerProviderModel, type ServerProviderSlashCommand, } from "@t3tools/contracts"; @@ -37,13 +36,13 @@ import { spawnAndCollect, type ServerProviderDraft, } from "../providerSnapshot.ts"; +import { resolveClaudeSdkExecutablePath } from "../Drivers/ClaudeExecutable.ts"; import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts"; const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({ optionDescriptors: [], }); -const PROVIDER = ProviderDriverKind.make("claudeAgent"); const CLAUDE_PRESENTATION = { displayName: "Claude", showInteractionModeToggle: true, @@ -193,6 +192,36 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], }), }, + { + slug: "claude-sonnet-5", + name: "Claude Sonnet 5", + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: [ + buildSelectOptionDescriptor({ + id: "effort", + label: "Reasoning", + options: [ + { value: "low", label: "Low" }, + { value: "medium", label: "Medium" }, + { value: "high", label: "High", isDefault: true }, + { value: "xhigh", label: "Extra High" }, + { value: "max", label: "Max" }, + { value: "ultrathink", label: "Ultrathink" }, + ], + promptInjectedValues: ["ultrathink"], + }), + buildSelectOptionDescriptor({ + id: "contextWindow", + label: "Context Window", + options: [ + { value: "200k", label: "200k", isDefault: true }, + { value: "1m", label: "1M" }, + ], + }), + ], + }), + }, { slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6", @@ -322,7 +351,12 @@ export function normalizeClaudeCliEffort( if (effort === "ultracode") { return "xhigh"; } - if (effort === "xhigh" && model !== "claude-fable-5" && model !== "claude-opus-4-8") { + if ( + effort === "xhigh" && + model !== "claude-fable-5" && + model !== "claude-opus-4-8" && + model !== "claude-sonnet-5" + ) { return "max"; } if (effort === "max" && model === "claude-sonnet-4-6") { @@ -444,9 +478,19 @@ function claudeAuthMetadata(input: { return undefined; } +function apiProviderAuthMetadata( + apiProvider: string | undefined, +): { readonly type: string; readonly label: string } | undefined { + return apiProvider === "bedrock" ? { type: "bedrock", label: "Amazon Bedrock" } : undefined; +} + // ── SDK capability probe ──────────────────────────────────────────── -const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000; +// Amazon Bedrock initializes far slower than first-party auth: the SDK boots the +// Bedrock backend and runs the `awsAuthRefresh` credential hook before returning +// account info. The previous 8s budget expired mid-init, so the probe returned +// `undefined` and left the provider unverified and unselectable in the picker. +const CAPABILITIES_PROBE_TIMEOUT_MS = 25_000; function nonEmptyProbeString(value: string): string | undefined { const candidate = value.trim(); @@ -457,6 +501,12 @@ type ClaudeCapabilitiesProbe = { readonly email: string | undefined; readonly subscriptionType: string | undefined; readonly tokenSource: string | undefined; + /** + * Active API backend reported by the SDK's `AccountInfo`. Anthropic OAuth + * login only applies when `"firstParty"`; for Amazon Bedrock (`"bedrock"`) + * the subscription/token fields are absent and auth is external AWS creds. + */ + readonly apiProvider: string | undefined; readonly slashCommands: ReadonlyArray; }; @@ -548,10 +598,15 @@ function waitForAbortSignal(signal: AbortSignal): Promise { const probeClaudeCapabilities = ( claudeSettings: ClaudeSettings, environment?: NodeJS.ProcessEnv, + cwd?: string, ) => { const abort = new AbortController(); return Effect.gen(function* () { const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment); + const executablePath = yield* resolveClaudeSdkExecutablePath( + claudeSettings.binaryPath, + claudeEnvironment, + ); return yield* Effect.tryPromise(async () => { const q = claudeQuery({ // Never yield — we only need initialization data, not a conversation. @@ -562,11 +617,12 @@ const probeClaudeCapabilities = ( })(), options: { persistSession: false, - pathToClaudeCodeExecutable: claudeSettings.binaryPath, + pathToClaudeCodeExecutable: executablePath, abortController: abort, settingSources: ["user", "project", "local"], allowedTools: [], env: claudeEnvironment, + ...(cwd ? { cwd } : {}), stderr: () => {}, }, }); @@ -576,12 +632,14 @@ const probeClaudeCapabilities = ( readonly email?: string; readonly subscriptionType?: string; readonly tokenSource?: string; + readonly apiProvider?: string; } | undefined; return { email: account?.email, subscriptionType: account?.subscriptionType, tokenSource: account?.tokenSource, + apiProvider: account?.apiProvider, slashCommands: parseClaudeInitializationCommands(init.commands), } satisfies ClaudeCapabilitiesProbe; }); @@ -631,7 +689,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( const checkedAt = DateTime.formatIso(yield* DateTime.now); const allModels = providerModelsFromSettings( BUILT_IN_MODELS, - PROVIDER, claudeSettings.customModels, DEFAULT_CLAUDE_MODEL_CAPABILITIES, ); @@ -722,7 +779,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( const models = providerModelsFromSettings( getBuiltInClaudeModelsForVersion(parsedVersion), - PROVIDER, claudeSettings.customModels, DEFAULT_CLAUDE_MODEL_CAPABILITIES, ); @@ -757,10 +813,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( }); } - const authMetadata = claudeAuthMetadata({ - subscriptionType: capabilities.subscriptionType, - authMethod: capabilities.tokenSource, - }); + const authMetadata = + claudeAuthMetadata({ + subscriptionType: capabilities.subscriptionType, + authMethod: capabilities.tokenSource, + }) ?? apiProviderAuthMetadata(capabilities.apiProvider); return buildServerProvider({ presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, @@ -790,7 +847,6 @@ export const makePendingClaudeProvider = ( const checkedAt = yield* nowIso; const models = providerModelsFromSettings( BUILT_IN_MODELS, - PROVIDER, claudeSettings.customModels, DEFAULT_CLAUDE_MODEL_CAPABILITIES, ); diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index 811c362f1e..9306087a0b 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -26,6 +26,7 @@ import { ServerSettingsError } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; +import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts"; import { AUTH_PROBE_TIMEOUT_MS, buildServerProvider, @@ -56,6 +57,8 @@ const REASONING_EFFORT_LABELS: Readonly> = { medium: "Medium", high: "High", xhigh: "Extra High", + max: "Max", + ultra: "Ultra", }; const DEFAULT_SERVICE_TIER_ID = "default"; @@ -287,6 +290,7 @@ export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams { const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: { readonly binaryPath: string; readonly homePath?: string; + readonly launchArgs?: string; readonly cwd: string; readonly customModels?: ReadonlyArray; readonly environment?: NodeJS.ProcessEnv; @@ -301,10 +305,14 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun ...input.environment, ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}), }; - const spawnCommand = yield* resolveSpawnCommand(input.binaryPath, ["app-server"], { - env: environment, - extendEnv: true, - }); + const spawnCommand = yield* resolveSpawnCommand( + input.binaryPath, + codexAppServerArgs(input.launchArgs), + { + env: environment, + extendEnv: true, + }, + ); const child = yield* spawner .spawn( ChildProcess.make(spawnCommand.command, spawnCommand.args, { @@ -463,6 +471,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu probe: (input: { readonly binaryPath: string; readonly homePath?: string; + readonly launchArgs?: string; readonly cwd: string; readonly customModels: ReadonlyArray; readonly environment?: NodeJS.ProcessEnv; @@ -501,6 +510,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu const probeResult = yield* probe({ binaryPath: codexSettings.binaryPath, homePath: codexSettings.homePath, + launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment), cwd: process.cwd(), customModels: codexSettings.customModels, environment: resolvedEnvironment, diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts index 8aeacd870c..119fa36303 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts @@ -4,14 +4,16 @@ import { it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { describe } from "vite-plus/test"; -import { ThreadId } from "@t3tools/contracts"; +import { DEFAULT_MODEL, ThreadId } from "@t3tools/contracts"; import * as CodexErrors from "effect-codex-app-server/errors"; import * as CodexRpc from "effect-codex-app-server/rpc"; import { + buildCodexDeveloperInstructions, CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, } from "../CodexDeveloperInstructions.ts"; +import { codexSessionAppServerArgs } from "./codexLaunchArgs.ts"; import { buildTurnStartParams, hasConfiguredMcpServer, @@ -118,7 +120,10 @@ describe("buildTurnStartParams", () => { settings: { model: "gpt-5.3-codex", reasoning_effort: "medium", - developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, + developer_instructions: buildCodexDeveloperInstructions("plan", { + model: "gpt-5.3-codex", + reasoningEffort: "medium", + }), }, }, }); @@ -163,12 +168,31 @@ describe("buildTurnStartParams", () => { settings: { model: "gpt-5.3-codex", reasoning_effort: "medium", - developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, + developer_instructions: buildCodexDeveloperInstructions("default", { + model: "gpt-5.3-codex", + reasoningEffort: "medium", + }), }, }, }); }); + it("reports the same fallback model and effort in settings and instructions", () => { + const params = Effect.runSync( + buildTurnStartParams({ + threadId: "provider-thread-1", + runtimeMode: "full-access", + prompt: "Go", + interactionMode: "default", + }), + ); + + const settings = params.collaborationMode?.settings; + NodeAssert.equal(settings?.model, DEFAULT_MODEL); + NodeAssert.equal(settings?.reasoning_effort, "medium"); + NodeAssert.ok(settings?.developer_instructions?.includes(`as ${DEFAULT_MODEL} with medium`)); + }); + it("omits collaboration mode when interaction mode is absent", () => { const params = Effect.runSync( buildTurnStartParams({ @@ -194,6 +218,53 @@ describe("buildTurnStartParams", () => { }); }); +describe("buildCodexDeveloperInstructions", () => { + it("appends runtime info after the mode instructions", () => { + const instructions = buildCodexDeveloperInstructions("default", { + model: "gpt-5.3-codex", + reasoningEffort: "high", + }); + + NodeAssert.ok(instructions.startsWith(CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS)); + NodeAssert.match(instructions, /T3 Code/); + NodeAssert.match(instructions, /Codex harness/); + NodeAssert.match(instructions, /as gpt-5\.3-codex with high reasoning effort/); + }); + + it("includes runtime info alongside plan mode instructions", () => { + const instructions = buildCodexDeveloperInstructions("plan", { + model: "gpt-5.3-codex", + reasoningEffort: "medium", + }); + + NodeAssert.ok(instructions.startsWith(CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS)); + NodeAssert.match(instructions, /as gpt-5\.3-codex with medium reasoning effort/); + }); + + it("varies with the model and effort of each turn", () => { + const first = buildCodexDeveloperInstructions("default", { + model: "gpt-5.3-codex", + reasoningEffort: "medium", + }); + const second = buildCodexDeveloperInstructions("default", { + model: "gpt-5.4", + reasoningEffort: "high", + }); + + NodeAssert.notEqual(first, second); + }); + + it("flattens multiline metadata into single-line runtime info", () => { + const instructions = buildCodexDeveloperInstructions("default", { + model: "gpt\n5.3\ncodex", + reasoningEffort: " high\neffort ", + }); + + NodeAssert.match(instructions, /as gpt 5\.3 codex with high effort reasoning effort/); + NodeAssert.doesNotMatch(instructions, /[^<]*\n/); + }); +}); + describe("T3 browser developer instructions", () => { it("prefers the product-native preview tools in both collaboration modes", () => { for (const instructions of [ @@ -219,6 +290,33 @@ describe("hasConfiguredMcpServer", () => { }); }); +describe("codexSessionAppServerArgs", () => { + it("keeps the app-server subcommand when explicit args are provided", () => { + NodeAssert.deepStrictEqual(codexSessionAppServerArgs(["-c", "model=gpt-5"], undefined), [ + "app-server", + "-c", + "model=gpt-5", + ]); + }); + + it("keeps launch args when explicit app-server args are provided", () => { + NodeAssert.deepStrictEqual( + codexSessionAppServerArgs( + ["-c", "mcp_servers.t3-code.url=http://127.0.0.1/mcp"], + "--strict-config --enable foo", + ), + [ + "app-server", + "--strict-config", + "--enable", + "foo", + "-c", + "mcp_servers.t3-code.url=http://127.0.0.1/mcp", + ], + ); + }); +}); + describe("isRecoverableThreadResumeError", () => { it("matches missing thread errors", () => { NodeAssert.equal( diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index 99ac498f0c..5a81e915e3 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -36,11 +36,9 @@ import * as CodexRpc from "effect-codex-app-server/rpc"; import * as EffectCodexSchema from "effect-codex-app-server/schema"; import { buildCodexInitializeParams } from "./CodexProvider.ts"; +import { codexSessionAppServerArgs } from "./codexLaunchArgs.ts"; import { expandHomePath } from "../../pathExpansion.ts"; -import { - CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, - CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, -} from "../CodexDeveloperInstructions.ts"; +import { buildCodexDeveloperInstructions } from "../CodexDeveloperInstructions.ts"; const decodeV2TurnStartResponse = Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse); const PROVIDER = ProviderDriverKind.make("codex"); @@ -100,6 +98,7 @@ export interface CodexSessionRuntimeOptions { readonly providerInstanceId?: ProviderInstanceId; readonly binaryPath: string; readonly homePath?: string; + readonly launchArgs?: string; readonly environment?: NodeJS.ProcessEnv; readonly cwd: string; readonly runtimeMode: RuntimeMode; @@ -331,15 +330,16 @@ function buildCodexCollaborationMode(input: { return undefined; } const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL; + const reasoningEffort = input.effort ?? "medium"; return { mode: input.interactionMode, settings: { model, - reasoning_effort: input.effort ?? "medium", - developer_instructions: - input.interactionMode === "plan" - ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS - : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, + reasoning_effort: reasoningEffort, + developer_instructions: buildCodexDeveloperInstructions(input.interactionMode, { + model, + reasoningEffort, + }), }, }; } @@ -719,11 +719,11 @@ export const makeCodexSessionRuntime = ( ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}), }; const extendEnv = options.environment === undefined; - const spawnCommand = yield* resolveSpawnCommand( - options.binaryPath, - ["app-server", ...(options.appServerArgs ?? [])], - { env, extendEnv }, - ); + const appServerArgs = codexSessionAppServerArgs(options.appServerArgs, options.launchArgs); + const spawnCommand = yield* resolveSpawnCommand(options.binaryPath, appServerArgs, { + env, + extendEnv, + }); const child = yield* spawner .spawn( ChildProcess.make(spawnCommand.command, spawnCommand.args, { diff --git a/apps/server/src/provider/Layers/CursorProvider.ts b/apps/server/src/provider/Layers/CursorProvider.ts index 3e62e4d67c..3e9631c83e 100644 --- a/apps/server/src/provider/Layers/CursorProvider.ts +++ b/apps/server/src/provider/Layers/CursorProvider.ts @@ -7,7 +7,6 @@ import type { ServerProviderModel, ServerProviderState, } from "@t3tools/contracts"; -import { ProviderDriverKind } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -24,7 +23,6 @@ import { } from "../providerSnapshot.ts"; import { CursorSdkCatalog } from "./CursorSdkCatalog.ts"; -const PROVIDER = ProviderDriverKind.make("cursor"); const CURSOR_PRESENTATION = { displayName: "Cursor", showInteractionModeToggle: true, @@ -77,7 +75,7 @@ export function buildInitialCursorProviderSnapshot( export function getCursorFallbackModels( cursorSettings: Pick, ): ReadonlyArray { - return providerModelsFromSettings([], PROVIDER, cursorSettings.customModels, EMPTY_CAPABILITIES); + return providerModelsFromSettings([], cursorSettings.customModels, EMPTY_CAPABILITIES); } function toTitleCaseWords(value: string): string { @@ -228,7 +226,6 @@ export function buildCursorProviderSnapshot(input: { checkedAt: input.checkedAt, models: providerModelsFromSettings( input.discoveredModels ?? [], - PROVIDER, input.cursorSettings.customModels, EMPTY_CAPABILITIES, ), diff --git a/apps/server/src/provider/Layers/GrokProvider.ts b/apps/server/src/provider/Layers/GrokProvider.ts index c13abc1115..5280a8b61b 100644 --- a/apps/server/src/provider/Layers/GrokProvider.ts +++ b/apps/server/src/provider/Layers/GrokProvider.ts @@ -1,12 +1,12 @@ import { type GrokSettings, type ModelCapabilities, - ProviderDriverKind, type ServerProvider, type ServerProviderModel, } from "@t3tools/contracts"; import type * as EffectAcpSchema from "effect-acp/schema"; import { causeErrorTag } from "@t3tools/shared/observability"; +import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -36,7 +36,6 @@ const GROK_PRESENTATION = { showInteractionModeToggle: false, requiresNewThreadForModelChange: true, } as const; -const PROVIDER = ProviderDriverKind.make("grok"); const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({ optionDescriptors: [], }); @@ -96,12 +95,7 @@ function grokModelsFromSettings( customModels: ReadonlyArray | undefined, builtInModels: ReadonlyArray = GROK_BUILT_IN_MODELS, ): ReadonlyArray { - return providerModelsFromSettings( - builtInModels, - PROVIDER, - customModels ?? [], - EMPTY_CAPABILITIES, - ); + return providerModelsFromSettings(builtInModels, customModels ?? [], EMPTY_CAPABILITIES); } function buildGrokDiscoveredModelsFromSessionModelState( @@ -166,7 +160,11 @@ const runGrokVersionCommand = ( export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* ( grokSettings: GrokSettings, environment: NodeJS.ProcessEnv = process.env, -): Effect.fn.Return { +): Effect.fn.Return< + ServerProviderDraft, + never, + ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto +> { const checkedAt = DateTime.formatIso(yield* DateTime.now); const fallbackModels = grokModelsFromSettings(grokSettings.customModels); diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts index b0e785512d..05160517bf 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts @@ -95,6 +95,13 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = { }), ) : Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory), + loadInventoryFromCli: () => + runtimeMock.state.inventoryError + ? Effect.succeed({ + providerList: { all: [], default: {}, connected: [] as string[] }, + agents: [], + } as OpenCodeInventory) + : Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory), }; beforeEach(() => { @@ -197,11 +204,22 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => { }), ); - it.effect("closes the local OpenCode server scope after provider refresh", () => + it.effect("does not spawn a local server for health check (uses CLI instead)", () => Effect.gen(function* () { yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd()); - NodeAssert.equal(runtimeMock.state.closeCalls, 1); + NodeAssert.equal(runtimeMock.state.closeCalls, 0); + }), + ); + + it.effect("degrades gracefully on CLI failure for local installs", () => + Effect.gen(function* () { + runtimeMock.state.inventoryError = new Error("opencode models failed"); + const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd()); + + NodeAssert.equal(snapshot.status, "warning"); + NodeAssert.equal(snapshot.installed, true); + NodeAssert.equal(snapshot.models.length, 0); }), ); }); diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.ts b/apps/server/src/provider/Layers/OpenCodeProvider.ts index a8285e960f..21014e33f0 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.ts @@ -1,5 +1,4 @@ import { - ProviderDriverKind, type ModelCapabilities, type OpenCodeSettings, type ServerProviderModel, @@ -25,7 +24,6 @@ import { } from "../opencodeRuntime.ts"; import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2"; -const PROVIDER = ProviderDriverKind.make("opencode"); const OPENCODE_PRESENTATION = { displayName: "OpenCode", showInteractionModeToggle: false, @@ -259,7 +257,6 @@ export const makePendingOpenCodeProvider = ( const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso); const models = providerModelsFromSettings( [], - PROVIDER, openCodeSettings.customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES, ); @@ -319,12 +316,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu presentation: OPENCODE_PRESENTATION, enabled: openCodeSettings.enabled, checkedAt, - models: providerModelsFromSettings( - [], - PROVIDER, - customModels, - DEFAULT_OPENCODE_MODEL_CAPABILITIES, - ), + models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES), probe: { installed: failure.installed, version, @@ -340,12 +332,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu presentation: OPENCODE_PRESENTATION, enabled: false, checkedAt, - models: providerModelsFromSettings( - [], - PROVIDER, - customModels, - DEFAULT_OPENCODE_MODEL_CAPABILITIES, - ), + models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES), probe: { installed: false, version: null, @@ -391,12 +378,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu presentation: OPENCODE_PRESENTATION, enabled: openCodeSettings.enabled, checkedAt, - models: providerModelsFromSettings( - [], - PROVIDER, - customModels, - DEFAULT_OPENCODE_MODEL_CAPABILITIES, - ), + models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES), probe: { installed: true, version, @@ -409,26 +391,32 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu } const inventoryExit = yield* Effect.exit( - Effect.scoped( - Effect.gen(function* () { - const server = yield* openCodeRuntime.connectToOpenCodeServer({ - binaryPath: openCodeSettings.binaryPath, - serverUrl: openCodeSettings.serverUrl, - environment: resolvedEnvironment, - }); - return yield* openCodeRuntime.loadOpenCodeInventory( - openCodeRuntime.createOpenCodeSdkClient({ - baseUrl: server.url, - directory: cwd, - ...(isExternalServer && openCodeSettings.serverPassword - ? { serverPassword: openCodeSettings.serverPassword } - : {}), + (isExternalServer + ? Effect.scoped( + Effect.gen(function* () { + const server = yield* openCodeRuntime.connectToOpenCodeServer({ + binaryPath: openCodeSettings.binaryPath, + serverUrl: openCodeSettings.serverUrl, + environment: resolvedEnvironment, + }); + return yield* openCodeRuntime.loadOpenCodeInventory( + openCodeRuntime.createOpenCodeSdkClient({ + baseUrl: server.url, + directory: cwd, + ...(openCodeSettings.serverPassword + ? { serverPassword: openCodeSettings.serverPassword } + : {}), + }), + ); }), - ); - }).pipe( - Effect.mapError( - (cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }), - ), + ) + : openCodeRuntime.loadInventoryFromCli({ + binaryPath: openCodeSettings.binaryPath, + environment: resolvedEnvironment, + }) + ).pipe( + Effect.mapError( + (cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }), ), ), ); @@ -438,7 +426,6 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu const models = providerModelsFromSettings( flattenOpenCodeModels(inventoryExit.value), - PROVIDER, customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES, ); diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts index 6eb0d000c2..dd5155f778 100644 --- a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts +++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts @@ -63,6 +63,7 @@ const makeCodexConfig = (overrides: Partial): CodexSettings => ({ binaryPath: "codex", homePath: "", shadowHomePath: "", + launchArgs: "", customModels: [], ...overrides, }); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 842bb4f962..ebf7aaabf0 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -55,6 +55,7 @@ const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTING const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({}); const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({}); +const decodeCodexSettings = Schema.decodeSync(CodexSettings); const disabledCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({ enabled: false, }); @@ -100,6 +101,7 @@ type TestClaudeCapabilities = { readonly email: string | undefined; readonly subscriptionType: string | undefined; readonly tokenSource: string | undefined; + readonly apiProvider: string | undefined; readonly slashCommands: ReadonlyArray; }; @@ -109,6 +111,7 @@ function claudeCapabilities(overrides: Partial = {}) { email: undefined, subscriptionType: undefined, tokenSource: undefined, + apiProvider: undefined, slashCommands: [], ...overrides, }); @@ -346,6 +349,21 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te }), ); + it.effect("passes configured launch args to the Codex provider probe", () => + Effect.gen(function* () { + let observedLaunchArgs: string | undefined; + const settings = decodeCodexSettings({ launchArgs: "--strict-config --enable foo" }); + + const status = yield* checkCodexProviderStatus(settings, (input) => { + observedLaunchArgs = input.launchArgs; + return Effect.succeed(makeCodexProbeSnapshot()); + }); + + assert.strictEqual(status.status, "ready"); + assert.strictEqual(observedLaunchArgs, "--strict-config --enable foo"); + }), + ); + it.effect("returns unauthenticated when app-server requires OpenAI auth", () => Effect.gen(function* () { const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => @@ -1396,7 +1414,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive), Layer.provideMerge( mockCommandSpawnerLayer((command, args) => { - if (command === "agent") { + if (command === "cursor-agent") { cursorSpawned = true; } const joined = args.join(" "); @@ -1492,6 +1510,30 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te ), ); + it.effect("returns ready and labels Bedrock-backed Claude as authenticated", () => + Effect.gen(function* () { + // Bedrock authenticates via external AWS credentials, so the SDK init + // reports only `apiProvider` with no subscription or token. + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities({ apiProvider: "bedrock" }), + ); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "bedrock"); + assert.strictEqual(status.auth.label, "Amazon Bedrock"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + it.effect("includes Claude Fable 5 on supported Claude Code versions", () => Effect.gen(function* () { const status = yield* checkClaudeProviderStatus( @@ -1719,8 +1761,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te ), ); - it.effect("runs Claude status probes with the configured Claude HOME", () => { - const claudeHome = "/tmp/t3code-claude-home"; + it.effect("runs Claude status probes with the configured CLAUDE_CONFIG_DIR", () => { + const claudeConfigDir = "/tmp/t3code-claude-home"; const recorded = recordingMockSpawnerLayer((args) => { const joined = args.join(" "); if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; @@ -1737,14 +1779,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te const status = yield* checkClaudeProviderStatus( { ...defaultClaudeSettings, - homePath: claudeHome, + homePath: claudeConfigDir, }, claudeCapabilities(), ); assert.strictEqual(status.status, "ready"); assert.deepStrictEqual( - recorded.commands.map((command) => command.env?.HOME), - [claudeHome], + recorded.commands.map((command) => command.env?.CLAUDE_CONFIG_DIR), + [claudeConfigDir], ); }).pipe(Effect.provide(recorded.layer)); }); diff --git a/apps/server/src/provider/Layers/codexLaunchArgs.test.ts b/apps/server/src/provider/Layers/codexLaunchArgs.test.ts new file mode 100644 index 0000000000..115ac28eaf --- /dev/null +++ b/apps/server/src/provider/Layers/codexLaunchArgs.test.ts @@ -0,0 +1,59 @@ +import * as NodeAssert from "node:assert/strict"; + +import { describe, it } from "vite-plus/test"; + +import { + codexAppServerArgs, + codexExecLaunchArgs, + resolveCodexLaunchArgs, +} from "./codexLaunchArgs.ts"; + +describe("resolveCodexLaunchArgs", () => { + it("uses T3CODE_CODEX_LAUNCH_ARGS before configured settings", () => { + NodeAssert.equal( + resolveCodexLaunchArgs(" --strict-config ", { T3CODE_CODEX_LAUNCH_ARGS: "--enable foo" }), + "--enable foo", + ); + }); + + it("uses configured settings when T3CODE_CODEX_LAUNCH_ARGS is empty", () => { + NodeAssert.equal( + resolveCodexLaunchArgs(" --strict-config ", { T3CODE_CODEX_LAUNCH_ARGS: " " }), + "--strict-config", + ); + }); + + it("ignores whitespace-only environment values", () => { + NodeAssert.equal(resolveCodexLaunchArgs("", { T3CODE_CODEX_LAUNCH_ARGS: " " }), ""); + }); +}); + +describe("codexAppServerArgs", () => { + it("returns the app-server command for empty launch args", () => { + NodeAssert.deepStrictEqual(codexAppServerArgs(""), ["app-server"]); + }); + + it("appends parsed launch args after app-server", () => { + NodeAssert.deepStrictEqual(codexAppServerArgs("--strict-config --enable foo"), [ + "app-server", + "--strict-config", + "--enable", + "foo", + ]); + }); +}); + +describe("codexExecLaunchArgs", () => { + it("keeps shared codex flags and omits app-server-only flags", () => { + NodeAssert.deepStrictEqual( + codexExecLaunchArgs('--strict-config --enable foo --listen off --config model="gpt 5"'), + ["--strict-config", "--enable", "foo", "--config", "model=gpt 5"], + ); + }); + + it("does not pair value-taking flags with adjacent flags", () => { + NodeAssert.deepStrictEqual(codexExecLaunchArgs("--config --strict-config --enable --disable"), [ + "--strict-config", + ]); + }); +}); diff --git a/apps/server/src/provider/Layers/codexLaunchArgs.ts b/apps/server/src/provider/Layers/codexLaunchArgs.ts new file mode 100644 index 0000000000..771a4f0b6e --- /dev/null +++ b/apps/server/src/provider/Layers/codexLaunchArgs.ts @@ -0,0 +1,48 @@ +import { tokenizeCliArgs } from "@t3tools/shared/cliArgs"; + +export const T3CODE_CODEX_LAUNCH_ARGS_ENV = "T3CODE_CODEX_LAUNCH_ARGS"; + +export const resolveCodexLaunchArgs = ( + launchArgs?: string, + environment: NodeJS.ProcessEnv = process.env, +) => environment[T3CODE_CODEX_LAUNCH_ARGS_ENV]?.trim() || launchArgs?.trim() || ""; + +export const codexLaunchArgv = (launchArgs?: string): ReadonlyArray => + tokenizeCliArgs(launchArgs); + +export const codexAppServerArgs = (launchArgs?: string) => [ + "app-server", + ...codexLaunchArgv(launchArgs), +]; + +export const codexExecLaunchArgs = (launchArgs?: string) => { + const args = codexLaunchArgv(launchArgs); + const execArgs: Array = []; + + for (let index = 0; index < args.length; index++) { + const arg = args[index]; + if (arg === undefined) continue; + + if (arg === "--strict-config" || arg.startsWith("--config=") || arg.startsWith("-c=")) { + execArgs.push(arg); + } else if (arg === "--config" || arg === "-c" || arg === "--enable" || arg === "--disable") { + const value = args[index + 1]; + if (value !== undefined && !value.startsWith("-")) { + execArgs.push(arg, value); + index++; + } + } else if (arg.startsWith("--enable=") || arg.startsWith("--disable=")) { + execArgs.push(arg); + } + } + + return execArgs; +}; + +export const codexSessionAppServerArgs = ( + appServerArgs: ReadonlyArray | undefined, + launchArgs: string | undefined, +) => { + const launchAppServerArgs = codexAppServerArgs(launchArgs); + return appServerArgs ? [...launchAppServerArgs, ...appServerArgs] : launchAppServerArgs; +}; diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index d535f1500a..b09a317009 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -203,6 +203,43 @@ describe("AcpSessionRuntime", () => { ), ); + it.effect("keeps assistant item IDs unique when a provider session restarts", () => { + const collectFirstAssistantItemId = Effect.gen(function* () { + const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; + const started = yield* runtime.start(); + expect(started.sessionId).toBe("mock-session-1"); + + yield* runtime.prompt({ + prompt: [{ type: "text", text: "hi" }], + }); + + const events = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4))); + const assistantStart = events.find((event) => event._tag === "AssistantItemStarted"); + expect(assistantStart?._tag).toBe("AssistantItemStarted"); + return assistantStart?._tag === "AssistantItemStarted" ? assistantStart.itemId : ""; + }).pipe( + Effect.provide( + AcpSessionRuntime.layer({ + spawn: { + command: mockAgentCommand, + args: mockAgentArgs, + }, + cwd: process.cwd(), + clientInfo: { name: "t3-test", version: "0.0.0" }, + authMethodId: "test", + }), + ), + Effect.scoped, + ); + + return Effect.gen(function* () { + const beforeRestart = yield* collectFirstAssistantItemId; + const afterRestart = yield* collectFirstAssistantItemId; + + expect(afterRestart).not.toBe(beforeRestart); + }).pipe(Effect.provide(NodeServices.layer)); + }); + it.effect("drops session updates emitted for a child ACP session", () => Effect.gen(function* () { const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index d80005633c..b2b0c5aee4 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -1,6 +1,7 @@ import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -281,7 +282,7 @@ export class AcpSessionRuntime extends Context.Service< ): Layer.Layer< AcpSessionRuntime, EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner + ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto > { return Layer.effect(AcpSessionRuntime, make(options)); } @@ -312,14 +313,24 @@ export const make = ( ): Effect.Effect< AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner | Scope.Scope + ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope > => Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const runtimeScope = yield* Scope.Scope; const eventQueue = yield* Queue.unbounded(); const modeStateRef = yield* Ref.make(undefined); const toolCallsRef = yield* Ref.make(new Map()); + const assistantItemRuntimeId = yield* crypto.randomUUIDv4.pipe( + Effect.mapError( + (cause) => + new EffectAcpErrors.AcpTransportError({ + detail: "Failed to generate an ACP assistant item runtime identifier.", + cause, + }), + ), + ); const assistantSegmentRef = yield* Ref.make({ nextSegmentIndex: 0 }); const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined)); const startStateRef = yield* Ref.make({ _tag: "NotStarted" }); @@ -429,6 +440,7 @@ export const make = ( modeStateRef, toolCallsRef, assistantSegmentRef, + assistantItemRuntimeId, params: notification, }); }), @@ -991,7 +1003,7 @@ export const layer = ( ): Layer.Layer< AcpSessionRuntime, EffectAcpErrors.AcpError, - ChildProcessSpawner.ChildProcessSpawner + ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto > => Layer.effect(AcpSessionRuntime, make(options)); function sessionConfigOptionsFromSetup( @@ -1023,12 +1035,14 @@ const handleSessionUpdate = ({ modeStateRef, toolCallsRef, assistantSegmentRef, + assistantItemRuntimeId, params, }: { readonly queue: Queue.Queue; readonly modeStateRef: Ref.Ref; readonly toolCallsRef: Ref.Ref>; readonly assistantSegmentRef: Ref.Ref; + readonly assistantItemRuntimeId: string; readonly params: EffectAcpSchema.SessionNotification; }): Effect.Effect => Effect.gen(function* () { @@ -1076,6 +1090,7 @@ const handleSessionUpdate = ({ queue, assistantSegmentRef, sessionId: params.sessionId, + assistantItemRuntimeId, }); yield* Queue.offer(queue, { ...event, @@ -1113,17 +1128,19 @@ function shouldEmitToolCallUpdate( return previous === undefined || previous.title !== next.title || previous.detail !== next.detail; } -const assistantItemId = (sessionId: string, segmentIndex: number) => - `assistant:${sessionId}:segment:${segmentIndex}`; +const assistantItemId = (sessionId: string, runtimeId: string, segmentIndex: number) => + `assistant:${sessionId}:runtime:${runtimeId}:segment:${segmentIndex}`; const ensureActiveAssistantSegment = ({ queue, assistantSegmentRef, sessionId, + assistantItemRuntimeId, }: { readonly queue: Queue.Queue; readonly assistantSegmentRef: Ref.Ref; readonly sessionId: string; + readonly assistantItemRuntimeId: string; }) => Ref.modify( assistantSegmentRef, @@ -1131,7 +1148,7 @@ const ensureActiveAssistantSegment = ({ if (current.activeItemId) { return [{ itemId: current.activeItemId }, current] as const; } - const itemId = assistantItemId(sessionId, current.nextSegmentIndex); + const itemId = assistantItemId(sessionId, assistantItemRuntimeId, current.nextSegmentIndex); return [ { itemId, diff --git a/apps/server/src/provider/acp/GrokAcpSupport.ts b/apps/server/src/provider/acp/GrokAcpSupport.ts index 3e6d63a539..c928b3ed80 100644 --- a/apps/server/src/provider/acp/GrokAcpSupport.ts +++ b/apps/server/src/provider/acp/GrokAcpSupport.ts @@ -1,4 +1,5 @@ import { type GrokSettings, ProviderDriverKind } from "@t3tools/contracts"; +import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Scope from "effect/Scope"; @@ -55,7 +56,7 @@ export const makeGrokAcpRuntime = ( ): Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, - Scope.Scope + Crypto.Crypto | Scope.Scope > => Effect.gen(function* () { const acpContext = yield* Layer.build( diff --git a/apps/server/src/provider/opencodeRuntime.cliParsers.test.ts b/apps/server/src/provider/opencodeRuntime.cliParsers.test.ts new file mode 100644 index 0000000000..6208f04507 --- /dev/null +++ b/apps/server/src/provider/opencodeRuntime.cliParsers.test.ts @@ -0,0 +1,229 @@ +import * as NodeAssert from "node:assert/strict"; + +import { describe, it } from "vite-plus/test"; + +import { parseModelsCliOutput, parseAgentListCliOutput } from "./opencodeRuntime.ts"; + +describe("parseModelsCliOutput", () => { + it("parses a single model from a single provider", () => { + const stdout = [ + "anthropic/claude-sonnet-4-5", + JSON.stringify({ + id: "claude-sonnet-4-5", + providerID: "anthropic", + name: "Claude Sonnet 4.5", + capabilities: { temperature: true, reasoning: true, toolcall: true }, + cost: { input: 3, output: 15 }, + limit: { context: 200000, output: 8192 }, + status: "active", + options: {}, + headers: {}, + release_date: "2025-01-01", + }), + ].join("\n"); + + const result = parseModelsCliOutput(stdout); + NodeAssert.equal(result.providers.size, 1); + NodeAssert.equal(result.connected.length, 1); + NodeAssert.equal(result.connected[0], "anthropic"); + + const provider = result.providers.get("anthropic")!; + NodeAssert.ok(provider); + NodeAssert.equal(provider.id, "anthropic"); + NodeAssert.equal(provider.name, "anthropic"); + NodeAssert.equal(Object.keys(provider.models).length, 1); + + const model = provider.models["claude-sonnet-4-5"]!; + NodeAssert.ok(model); + NodeAssert.equal(model.id, "claude-sonnet-4-5"); + NodeAssert.equal(model.providerID, "anthropic"); + NodeAssert.equal(model.name, "Claude Sonnet 4.5"); + }); + + it("parses multiple models from multiple providers", () => { + const stdout = [ + "anthropic/claude-sonnet-4-5", + JSON.stringify({ id: "claude-sonnet-4-5", providerID: "anthropic", name: "Sonnet 4.5" }), + "anthropic/claude-haiku-4-5", + JSON.stringify({ id: "claude-haiku-4-5", providerID: "anthropic", name: "Haiku 4.5" }), + "openai/gpt-4o", + JSON.stringify({ id: "gpt-4o", providerID: "openai", name: "GPT-4o" }), + ].join("\n"); + + const result = parseModelsCliOutput(stdout); + NodeAssert.equal(result.providers.size, 2); + NodeAssert.equal(result.connected.length, 2); + NodeAssert.equal([...result.connected].sort().join(","), "anthropic,openai"); + NodeAssert.equal(Object.keys(result.providers.get("anthropic")!.models).length, 2); + NodeAssert.equal(Object.keys(result.providers.get("openai")!.models).length, 1); + }); + + it("handles empty input", () => { + const result = parseModelsCliOutput(""); + NodeAssert.equal(result.providers.size, 0); + NodeAssert.equal(result.connected.length, 0); + }); + + it("skips unparseable JSON blocks", () => { + const stdout = [ + "anthropic/claude-sonnet-4-5", + "this is not valid json {{{", + "anthropic/claude-haiku-4-5", + JSON.stringify({ id: "claude-haiku-4-5", providerID: "anthropic", name: "Haiku 4.5" }), + ].join("\n"); + + const result = parseModelsCliOutput(stdout); + NodeAssert.equal(result.providers.size, 1); + const provider = result.providers.get("anthropic")!; + NodeAssert.equal(Object.keys(provider.models).length, 1); + NodeAssert.ok(provider.models["claude-haiku-4-5"]); + }); + + it("handles Windows-style CRLF line endings", () => { + const stdout = + "anthropic/claude-sonnet-4-5\r\n" + + JSON.stringify({ id: "claude-sonnet-4-5", providerID: "anthropic", name: "Sonnet" }) + + "\r\n"; + + const result = parseModelsCliOutput(stdout); + NodeAssert.equal(result.providers.size, 1); + NodeAssert.ok(result.providers.get("anthropic")!.models["claude-sonnet-4-5"]); + }); + + it("handles model JSON with variants and nested fields", () => { + const stdout = [ + "opencode/gpt-5.4", + JSON.stringify({ + id: "gpt-5.4", + providerID: "opencode", + name: "GPT-5.4", + family: "gpt", + capabilities: { + temperature: true, + reasoning: true, + attachment: false, + toolcall: true, + input: { text: true, audio: false, image: false, video: false, pdf: false }, + output: { text: true, audio: false, image: false, video: false, pdf: false }, + interleaved: false, + }, + cost: { input: 0, output: 0, cache: { read: 0, write: 0 } }, + limit: { context: 200000, input: 160000, output: 32000 }, + status: "active", + options: {}, + headers: {}, + release_date: "2025-01-01", + variants: { none: {}, low: {}, medium: {}, high: {} }, + }), + ].join("\n"); + + const result = parseModelsCliOutput(stdout); + const model = result.providers.get("opencode")!.models["gpt-5.4"]!; + NodeAssert.ok(model); + NodeAssert.ok(model.capabilities); + NodeAssert.equal(model.capabilities!.reasoning, true); + NodeAssert.ok(model.variants); + NodeAssert.equal(model.variants!["medium"] !== undefined, true); + }); +}); + +describe("parseAgentListCliOutput", () => { + it("parses a single agent", () => { + const stdout = [ + "build (primary)", + " " + JSON.stringify([{ permission: "*", action: "allow", pattern: "*" }]), + ].join("\n"); + + const result = parseAgentListCliOutput(stdout); + NodeAssert.equal(result.length, 1); + NodeAssert.equal(result[0]!.name, "build"); + NodeAssert.equal(result[0]!.mode, "primary"); + NodeAssert.equal(result[0]!.permission.length, 1); + }); + + it("parses multiple agents", () => { + const stdout = [ + "build (primary)", + " " + JSON.stringify([{ permission: "*", action: "allow", pattern: "*" }]), + "explore (subagent)", + " " + JSON.stringify([{ permission: "read", action: "allow", pattern: "*" }]), + "plan (primary)", + " " + JSON.stringify([{ permission: "edit", action: "ask", pattern: "*.md" }]), + ].join("\n"); + + const result = parseAgentListCliOutput(stdout); + NodeAssert.equal(result.length, 3); + NodeAssert.equal(result[0]!.name, "build"); + NodeAssert.equal(result[0]!.mode, "primary"); + NodeAssert.equal(result[1]!.name, "explore"); + NodeAssert.equal(result[1]!.mode, "subagent"); + NodeAssert.equal(result[2]!.name, "plan"); + NodeAssert.equal(result[2]!.mode, "primary"); + }); + + it("handles empty input", () => { + const result = parseAgentListCliOutput(""); + NodeAssert.equal(result.length, 0); + }); + + it("skips agents with unparseable permission JSON", () => { + const stdout = [ + "build (primary)", + " not valid json {", + "explore (subagent)", + " " + JSON.stringify([{ permission: "read", action: "allow", pattern: "*" }]), + ].join("\n"); + + const result = parseAgentListCliOutput(stdout); + NodeAssert.equal(result.length, 1); + NodeAssert.equal(result[0]!.name, "explore"); + }); + + it("handles real-world permission blocks with nested paths", () => { + const permissions = [ + { permission: "*", action: "allow", pattern: "*" }, + { + permission: "external_directory", + pattern: "C:\\Users\\test\\.local\\*", + action: "allow", + }, + { permission: "read", pattern: "*.env", action: "ask" }, + ]; + const stdout = ["build (primary)", " " + JSON.stringify(permissions)].join("\n"); + + const result = parseAgentListCliOutput(stdout); + NodeAssert.equal(result.length, 1); + NodeAssert.equal(result[0]!.permission.length, 3); + NodeAssert.equal(result[0]!.permission[0]!.action, "allow"); + NodeAssert.equal(result[0]!.permission[2]!.action, "ask"); + }); + + it("handles agent names with spaces", () => { + const stdout = [ + "code reviewer (subagent)", + " " + JSON.stringify([{ permission: "read", action: "allow", pattern: "*" }]), + "my custom agent (primary)", + " " + JSON.stringify([{ permission: "edit", action: "ask", pattern: "*.ts" }]), + ].join("\n"); + + const result = parseAgentListCliOutput(stdout); + NodeAssert.equal(result.length, 2); + NodeAssert.equal(result[0]!.name, "code reviewer"); + NodeAssert.equal(result[0]!.mode, "subagent"); + NodeAssert.equal(result[1]!.name, "my custom agent"); + NodeAssert.equal(result[1]!.mode, "primary"); + }); + + it("marks known hidden agents", () => { + const stdout = [ + "compaction (primary)", + " " + JSON.stringify([{ permission: "*", action: "allow", pattern: "*" }]), + "build (primary)", + " " + JSON.stringify([{ permission: "*", action: "allow", pattern: "*" }]), + ].join("\n"); + + const result = parseAgentListCliOutput(stdout); + NodeAssert.equal(result[0]!.hidden, true); + NodeAssert.equal(result[1]!.hidden, false); + }); +}); diff --git a/apps/server/src/provider/opencodeRuntime.ts b/apps/server/src/provider/opencodeRuntime.ts index a83c134d5b..b853662b03 100644 --- a/apps/server/src/provider/opencodeRuntime.ts +++ b/apps/server/src/provider/opencodeRuntime.ts @@ -5,6 +5,7 @@ import { createOpencodeClient, type Agent, type FilePartInput, + type Model, type OpencodeClient, type PermissionRuleset, type ProviderListResponse, @@ -37,7 +38,7 @@ const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJ const OPENCODE_EMPTY_CONFIG_CONTENT = "{}"; const OPENCODE_SERVER_READY_PREFIX = "opencode server listening"; -const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000; +const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 30_000; const DEFAULT_HOSTNAME = "127.0.0.1"; export interface OpenCodeServerProcess { readonly url: string; @@ -147,6 +148,10 @@ export interface OpenCodeRuntimeShape { readonly loadOpenCodeInventory: ( client: OpencodeClient, ) => Effect.Effect; + readonly loadInventoryFromCli: (input: { + readonly binaryPath: string; + readonly environment?: NodeJS.ProcessEnv; + }) => Effect.Effect; } function parseServerUrlFromOutput(output: string): string | null { @@ -160,6 +165,113 @@ function parseServerUrlFromOutput(output: string): string | null { return null; } +const SLUG_LINE_RE = /^(\S+\/\S+)\s*$/; +const AGENT_HEADER_RE = /^(.+)\s+\((\S+)\)\s*$/; + +// Agents that are always hidden in OpenCode but the CLI "agent list" command +// does not expose the hidden flag. Keep in sync with OpenCode agent +// definitions (in the OpenCode repo: packages/opencode/src/agent/agent.ts). +const KNOWN_HIDDEN_AGENTS = new Set(["compaction", "summary", "title"]); + +/** @internal */ +export function parseModelsCliOutput(stdout: string): { + readonly providers: ReadonlyMap< + string, + { readonly id: string; readonly name: string; readonly models: { [key: string]: Model } } + >; + readonly connected: ReadonlyArray; +} { + const providers = new Map< + string, + { id: string; name: string; models: { [key: string]: Model } } + >(); + const lines = stdout.split("\n"); + let currentSlug: string | null = null; + const jsonLines: Array = []; + + const flushModel = () => { + if (currentSlug !== null && jsonLines.length > 0) { + const jsonStr = jsonLines.join("\n").trim(); + if (jsonStr.length > 0) { + try { + const model = JSON.parse(jsonStr) as Model; + const separator = currentSlug.indexOf("/"); + if (separator > 0) { + const providerID = currentSlug.slice(0, separator); + const modelID = currentSlug.slice(separator + 1); + let provider = providers.get(providerID); + if (!provider) { + provider = { id: providerID, name: providerID, models: {} }; + providers.set(providerID, provider); + } + provider.models[modelID] = model; + } + } catch { + // Skip unparseable model JSON + } + } + } + currentSlug = null; + jsonLines.length = 0; + }; + + for (const line of lines) { + const slugMatch = SLUG_LINE_RE.exec(line); + if (slugMatch) { + flushModel(); + currentSlug = slugMatch[1]!; + } else if (currentSlug !== null) { + jsonLines.push(line); + } + } + flushModel(); + + return { providers, connected: [...providers.keys()] }; +} + +/** @internal */ +export function parseAgentListCliOutput(stdout: string): ReadonlyArray { + const agents: Array = []; + const lines = stdout.split("\n"); + let currentHeader: { name: string; mode: string } | null = null; + const blockLines: Array = []; + + const flushAgent = () => { + if (currentHeader !== null) { + const jsonStr = blockLines.join("\n").trim(); + if (jsonStr.length > 0) { + try { + const permission = JSON.parse(jsonStr); + agents.push({ + name: currentHeader.name, + mode: currentHeader.mode as Agent["mode"], + hidden: KNOWN_HIDDEN_AGENTS.has(currentHeader.name), + permission, + options: {}, + }); + } catch { + // Skip unparseable agent + } + } + } + currentHeader = null; + blockLines.length = 0; + }; + + for (const line of lines) { + const match = AGENT_HEADER_RE.exec(line); + if (match) { + flushAgent(); + currentHeader = { name: match[1]!, mode: match[2]! }; + } else if (currentHeader !== null) { + blockLines.push(line); + } + } + flushAgent(); + + return agents; +} + export function parseOpenCodeModelSlug( slug: string | null | undefined, ): ParsedOpenCodeModelSlug | null { @@ -542,12 +654,76 @@ const makeOpenCodeRuntime = Effect.gen(function* () { Effect.map(([providerList, agents]) => ({ providerList, agents })), ); + const loadInventoryFromCli: OpenCodeRuntimeShape["loadInventoryFromCli"] = (input) => + Effect.gen(function* () { + const env = input.environment !== undefined ? { environment: input.environment } : ({} as {}); + + const runModelsCli = () => + runOpenCodeCommand({ + binaryPath: input.binaryPath, + args: ["models", "--verbose"], + ...env, + }).pipe(Effect.exit); + const runAgentsCli = () => + runOpenCodeCommand({ binaryPath: input.binaryPath, args: ["agent", "list"], ...env }).pipe( + Effect.exit, + ); + + // First attempt — run both in parallel + let [modelsResult, agentsResult] = yield* Effect.all([runModelsCli(), runAgentsCli()], { + concurrency: "unbounded", + }); + + // Retry once after 1s on transient failures (e.g. SQLite "database is locked") + const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0; + const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0; + if (needsModelsRetry || needsAgentsRetry) { + yield* Effect.sleep("1 second"); + const [m2, a2] = yield* Effect.all( + [ + needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult), + needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult), + ], + { concurrency: "unbounded" }, + ); + modelsResult = m2; + agentsResult = a2; + } + + // Degrade gracefully on failure — return empty inventory (warning status, not error) + let connected: string[] = []; + let allProviders: ProviderListResponse["all"] = []; + if (modelsResult._tag === "Success" && modelsResult.value.code === 0) { + const parsed = parseModelsCliOutput(modelsResult.value.stdout); + connected = [...parsed.connected]; + allProviders = [...parsed.providers.values()].map((p) => ({ + id: p.id, + name: p.name, + source: "config" as const, + env: [], + options: {}, + models: p.models, + })); + } + + let agents: ReadonlyArray = []; + if (agentsResult._tag === "Success" && agentsResult.value.code === 0) { + agents = parseAgentListCliOutput(agentsResult.value.stdout); + } + + return { + providerList: { all: allProviders, default: {}, connected }, + agents, + }; + }); + return { startOpenCodeServerProcess, connectToOpenCodeServer, runOpenCodeCommand, createOpenCodeSdkClient, loadOpenCodeInventory, + loadInventoryFromCli, } satisfies OpenCodeRuntimeShape; }); diff --git a/apps/server/src/provider/providerSnapshot.test.ts b/apps/server/src/provider/providerSnapshot.test.ts index abe138fdfb..0115727806 100644 --- a/apps/server/src/provider/providerSnapshot.test.ts +++ b/apps/server/src/provider/providerSnapshot.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "@effect/vitest"; -import { ProviderDriverKind, type ModelCapabilities } from "@t3tools/contracts"; +import type { ModelCapabilities } from "@t3tools/contracts"; import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; import { createModelCapabilities } from "@t3tools/shared/model"; import * as Effect from "effect/Effect"; @@ -38,7 +38,6 @@ describe("providerModelsFromSettings", () => { it("applies the provided capabilities to custom models", () => { const models = providerModelsFromSettings( [], - ProviderDriverKind.make("opencode"), ["openai/gpt-5"], OPENCODE_CUSTOM_MODEL_CAPABILITIES, ); @@ -52,6 +51,25 @@ describe("providerModelsFromSettings", () => { }, ]); }); + + it("preserves a custom slug that collides with a provider alias", () => { + const capabilities = createModelCapabilities({ optionDescriptors: [] }); + const models = providerModelsFromSettings( + [ + { + slug: "claude-opus-4-8", + name: "Claude Opus 4.8", + isCustom: false, + capabilities, + }, + ], + [" opus "], + capabilities, + ); + + expect(models.map((model) => model.slug)).toEqual(["claude-opus-4-8", "opus"]); + expect(models[1]?.isCustom).toBe(true); + }); }); describe("ProviderCommandNotFoundError", () => { diff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.ts index dfe31ffdc4..e741a7a2c1 100644 --- a/apps/server/src/provider/providerSnapshot.ts +++ b/apps/server/src/provider/providerSnapshot.ts @@ -13,7 +13,7 @@ import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { normalizeModelSlug } from "@t3tools/shared/model"; +import { normalizeCustomModelSlug } from "@t3tools/shared/model"; import { isWindowsCommandNotFound } from "../processRunner.ts"; import { createProviderVersionAdvisory } from "./providerMaintenance.ts"; import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts"; @@ -140,7 +140,6 @@ export function parseGenericCliVersion(output: string): string | null { export function providerModelsFromSettings( builtInModels: ReadonlyArray, - provider: ProviderDriverKind, customModels: ReadonlyArray, customModelCapabilities: ModelCapabilities, ): ReadonlyArray { @@ -149,7 +148,7 @@ export function providerModelsFromSettings( const customEntries: ServerProviderModel[] = []; for (const candidate of customModels) { - const normalized = normalizeModelSlug(candidate, provider); + const normalized = normalizeCustomModelSlug(candidate); if (!normalized || seen.has(normalized)) { continue; } diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index 9b04cf57cf..99161b7bc7 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -181,6 +181,24 @@ const makePublishProof = Effect.fn("makePublishProof")(function* (input: { return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload }); }); +// Compact, log-safe view of the fields the awareness phase ladder reads. +export function describeThreadShellForAwareness( + thread: Option.Option, +): Record { + if (Option.isNone(thread)) { + return { found: false }; + } + const shell = thread.value; + return { + found: true, + status: shell.status, + activeRunId: shell.activeRunId ?? null, + latestRunId: shell.latestRunId ?? null, + pendingRuntimeRequestKind: shell.pendingRuntimeRequest?.kind ?? null, + hasActionableProposedPlan: shell.hasActionableProposedPlan, + }; +} + export function resolveAgentAwarenessRelayPublishSnapshot(input: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; @@ -284,6 +302,14 @@ export const make = Effect.gen(function* () { transformClient: relayEnvironmentClient(relayConfig.environmentCredential), }).pipe(Effect.provide(FetchHttpClient.layer)); + // Deadlines for publishes that need confirmation (tombstones and + // first-state completions). The confirming publish is re-enqueued through + // the same drainable worker as every other publish, so a confirmed + // tombstone can never race an in-flight live update; a recovered state + // clears the deadline. Assigned after the worker exists. + const publishConfirmDeadlines = new Map(); + let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect = () => Effect.void; + const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) { const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe( Effect.orElseSucceed(() => false), @@ -362,6 +388,11 @@ export const make = Effect.gen(function* () { const publishIdentity = agentAwarenessPublishIdentity(snapshot.state); const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef); if (publishedStateByThread.get(threadId) === publishIdentity) { + // The projection is back at (or never left) the last published state, so + // any pending deferred confirmation is moot. Leaving the deadline in + // place would let a much later transient null find it already expired + // and publish a tombstone immediately, skipping the deferral window. + publishConfirmDeadlines.delete(threadId); yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", { environmentId, threadId, @@ -370,6 +401,50 @@ export const make = Effect.gen(function* () { return; } + // Two projections need confirmation before publishing, because both can + // appear transiently while the projector is mid-write and publishing them + // immediately is destructive or noisy: + // - null (tombstone) while the previous published state was live: deletes + // the thread from every armed card mid-conversation. + // - completed as the thread's FIRST published state: sessions boot at + // "ready" before their first turn, which projects as completed for an + // instant and sends a spurious Done notification at thread birth. + // Defer, schedule a re-publish through the ordinary worker queue, and + // only publish if the projection still holds when it drains. + const requiresConfirmation = + (snapshot.state === null && + publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) || + (snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId)); + if (requiresConfirmation) { + const nowMs = (yield* DateTime.now).epochMilliseconds; + const deadline = publishConfirmDeadlines.get(threadId); + if (deadline === undefined) { + publishConfirmDeadlines.set(threadId, nowMs + 5_000); + yield* Effect.logInfo("agent activity publish deferred pending confirmation", { + environmentId, + threadId, + reason: snapshot.reason, + statePhase: snapshot.state?.phase ?? null, + shell: describeThreadShellForAwareness(thread), + }); + yield* schedulePublishConfirm(threadId); + return; + } + if (nowMs < deadline) { + return; + } + publishConfirmDeadlines.delete(threadId); + yield* Effect.logInfo("agent activity deferred publish confirmed", { + environmentId, + threadId, + reason: snapshot.reason, + statePhase: snapshot.state?.phase ?? null, + shell: describeThreadShellForAwareness(thread), + }); + } else { + publishConfirmDeadlines.delete(threadId); + } + if (snapshot.reason === "thread-not-found") { yield* Effect.logDebug("publishing agent activity tombstone; thread not found", { environmentId, @@ -461,6 +536,19 @@ export const make = Effect.gen(function* () { const worker = yield* makeDrainableWorker(publishThread); + schedulePublishConfirm = (threadId) => + Effect.forkDetach( + Effect.sleep("5 seconds").pipe( + Effect.andThen(worker.enqueue(threadId)), + Effect.catchCause((cause) => + Effect.logWarning("deferred agent activity confirmation failed", { + threadId, + cause: Cause.pretty(cause), + }), + ), + ), + ).pipe(Effect.asVoid); + const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")( function* () { const [relayConfig, publishEnabled] = yield* Effect.all([ diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index bf3a8c20d1..0bf127e344 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -82,6 +82,7 @@ import { makePersistedServerRuntimeState, persistServerRuntimeState, } from "./serverRuntimeState.ts"; +import { orchestrationHttpApiLayer } from "./orchestration-v2/http.ts"; import { projectHttpApiLayer } from "./project/http.ts"; import * as NetService from "@t3tools/shared/Net"; import * as RelayClient from "@t3tools/shared/relayClient"; @@ -294,7 +295,10 @@ const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe( Layer.provideMerge(ServerSecretStore.layer), Layer.provideMerge( Layer.mergeAll( - CloudCliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)), + CloudCliTokenManager.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide(ExternalLauncher.layer), + ), CloudManagedEndpointRuntimeLive, ), ), @@ -320,6 +324,7 @@ export const makeRoutesLayer = Layer.mergeAll( HttpApiBuilder.layer(EnvironmentHttpApi).pipe( Layer.provide(authHttpApiLayer), Layer.provide(connectHttpApiLayer), + Layer.provide(orchestrationHttpApiLayer), Layer.provide(projectHttpApiLayer), Layer.provide(serverEnvironmentHttpApiLayer), Layer.provide(environmentAuthenticatedAuthLayer), diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 504d99e18d..487ae9b45b 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -179,6 +179,7 @@ it.layer(NodeServices.layer)("server settings", (it) => { binaryPath: "/opt/homebrew/bin/codex", homePath: "/Users/julius/.codex", shadowHomePath: "", + launchArgs: "", customModels: [], }); assert.deepEqual(next.providers.claudeAgent, { @@ -420,6 +421,7 @@ it.layer(NodeServices.layer)("server settings", (it) => { binaryPath: "/opt/homebrew/bin/codex", homePath: "", shadowHomePath: "", + launchArgs: "", customModels: [], }); assert.deepEqual(next.providers.claudeAgent, { diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 3a1cabc4a2..1cf7e8dffe 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1334,6 +1334,63 @@ it.layer( }), ); + it.effect("strips AppImage runtime env from terminal sessions", () => + Effect.gen(function* () { + const appDir = "/tmp/.mount_T3Codeabc123"; + const { manager, ptyAdapter } = yield* createManager(5, { + env: { + APPIMAGE: "/home/user/T3-Code.AppImage", + APPDIR: appDir, + ARGV0: "/home/user/T3-Code.AppImage", + OWD: "/home/user/project", + PATH: `${appDir}/usr/bin:${appDir}:/usr/local/bin:/usr/bin:/bin`, + LD_LIBRARY_PATH: `${appDir}/usr/lib:/home/user/.local/lib`, + TEST_TERMINAL_KEEP: "keep-me", + }, + }); + yield* manager.open(openInput()); + const spawnInput = ptyAdapter.spawnInputs[0]; + expect(spawnInput).toBeDefined(); + if (!spawnInput) return; + + // AppImage runtime markers must never reach the PTY — tools inside the + // terminal otherwise resolve against the AppImage mount (e.g. PHP_BINARY + // reporting the AppImage path instead of the real binary). + expect(spawnInput.env.APPIMAGE).toBeUndefined(); + expect(spawnInput.env.APPDIR).toBeUndefined(); + expect(spawnInput.env.ARGV0).toBeUndefined(); + expect(spawnInput.env.OWD).toBeUndefined(); + // PATH/LD_LIBRARY_PATH keep the user's real entries but drop the AppImage + // mount segments that the runtime prepended. + expect(spawnInput.env.PATH).toBe("/usr/local/bin:/usr/bin:/bin"); + expect(spawnInput.env.LD_LIBRARY_PATH).toBe("/home/user/.local/lib"); + // Unrelated host vars still pass through untouched. + expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me"); + }), + ); + + it.effect("leaves the environment untouched when not launched from an AppImage", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + env: { + PATH: "/usr/local/bin:/usr/bin:/bin", + LD_LIBRARY_PATH: "/home/user/.local/lib", + // Without APPIMAGE/APPDIR set, OWD is an ordinary variable and must + // not be stripped — only an AppImage launch gives it special meaning. + OWD: "/home/user/keep-this", + }, + }); + yield* manager.open(openInput()); + const spawnInput = ptyAdapter.spawnInputs[0]; + expect(spawnInput).toBeDefined(); + if (!spawnInput) return; + + expect(spawnInput.env.PATH).toBe("/usr/local/bin:/usr/bin:/bin"); + expect(spawnInput.env.LD_LIBRARY_PATH).toBe("/home/user/.local/lib"); + expect(spawnInput.env.OWD).toBe("/home/user/keep-this"); + }), + ); + it.effect("injects runtime env overrides into spawned terminals", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 6347fdfc64..caa5106bb9 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -1065,6 +1065,53 @@ function shouldExcludeTerminalEnvKey(key: string): boolean { return TERMINAL_ENV_BLOCKLIST.has(normalizedKey); } +// Marker variables the AppImage runtime injects into the process it launches. +// They describe the AppImage itself, not the user's session, so terminals must +// not inherit them. +const APPIMAGE_RUNTIME_ENV_KEYS = ["APPIMAGE", "APPDIR", "ARGV0", "OWD"] as const; +// PATH-style variables the AppImage runtime prepends with its temporary mount +// (e.g. /tmp/.mount_T3-XXXX/usr/bin). Only the mount segments are dropped; the +// user's real entries are preserved. +const APPIMAGE_PATH_LIKE_ENV_KEYS = ["PATH", "LD_LIBRARY_PATH"] as const; + +function isPathSegmentUnderAppDir(segment: string, appDir: string): boolean { + return segment === appDir || segment.startsWith(`${appDir}/`); +} + +// On Linux AppImage builds the runtime mounts the app under a temporary dir and +// injects APPIMAGE/APPDIR/ARGV0/OWD plus mount entries on PATH/LD_LIBRARY_PATH. +// The integrated terminal inherits the server process environment, so without +// this scrub those leak into the PTY and tools resolve against the AppImage +// mount instead of the user's real environment (e.g. `php` reporting +// PHP_BINARY as the AppImage path). See issue #1699. The scrub is gated on an +// actual AppImage launch so non-AppImage environments are left untouched. +function stripAppImageRuntimeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + if (env.APPIMAGE === undefined && env.APPDIR === undefined) return env; + + const scrubbed: NodeJS.ProcessEnv = { ...env }; + for (const key of APPIMAGE_RUNTIME_ENV_KEYS) { + delete scrubbed[key]; + } + + const appDir = env.APPDIR?.replace(/\/+$/, ""); + if (appDir) { + for (const key of APPIMAGE_PATH_LIKE_ENV_KEYS) { + const value = scrubbed[key]; + if (value === undefined) continue; + const kept = value + .split(":") + .filter((segment) => segment.length > 0 && !isPathSegmentUnderAppDir(segment, appDir)); + if (kept.length > 0) { + scrubbed[key] = kept.join(":"); + } else { + delete scrubbed[key]; + } + } + } + + return scrubbed; +} + function createTerminalSpawnEnv( baseEnv: NodeJS.ProcessEnv, runtimeEnv?: Record | null, @@ -1080,7 +1127,7 @@ function createTerminalSpawnEnv( spawnEnv[key] = value; } } - return spawnEnv; + return stripAppImageRuntimeEnv(spawnEnv); } function normalizedRuntimeEnv( diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index c8fe4ead3b..0f3905a0cb 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -51,8 +51,8 @@ function makeFakeClaudeBinary(dir: string) { " exit 4", " }", "fi", - 'if [ -n "$T3_FAKE_CLAUDE_HOME_MUST_BE" ] && [ "$HOME" != "$T3_FAKE_CLAUDE_HOME_MUST_BE" ]; then', - ' printf "%s\\n" "HOME was $HOME" >&2', + 'if [ -n "$T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE" ] && [ "$CLAUDE_CONFIG_DIR" != "$T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE" ]; then', + ' printf "%s\\n" "CLAUDE_CONFIG_DIR was $CLAUDE_CONFIG_DIR" >&2', " exit 5", "fi", 'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then', @@ -76,7 +76,7 @@ function withFakeClaudeEnv( argsMustContain?: string; argsMustNotContain?: string; stdinMustContain?: string; - homeMustBe?: string; + configDirMustBe?: string; claudeConfig?: Partial; }, effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect, @@ -92,7 +92,7 @@ function withFakeClaudeEnv( const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN; const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN; const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; - const previousHomeMustBe = process.env.T3_FAKE_CLAUDE_HOME_MUST_BE; + const previousConfigDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE; yield* Effect.acquireRelease( Effect.sync(() => { @@ -129,10 +129,10 @@ function withFakeClaudeEnv( delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; } - if (input.homeMustBe !== undefined) { - process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = input.homeMustBe; + if (input.configDirMustBe !== undefined) { + process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = input.configDirMustBe; } else { - delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE; + delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE; } }), () => @@ -175,10 +175,10 @@ function withFakeClaudeEnv( process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain; } - if (previousHomeMustBe === undefined) { - delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE; + if (previousConfigDirMustBe === undefined) { + delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE; } else { - process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = previousHomeMustBe; + process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = previousConfigDirMustBe; } }), ); @@ -286,10 +286,10 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => { ), ); - it.effect("runs Claude text generation with the configured Claude HOME", () => + it.effect("runs Claude text generation with the configured CLAUDE_CONFIG_DIR", () => Effect.gen(function* () { const path = yield* Path.Path; - const claudeHome = path.join(process.cwd(), ".claude-work-test"); + const claudeConfigDir = path.join(process.cwd(), ".claude-work-test"); return yield* withFakeClaudeEnv( { // @effect-diagnostics-next-line preferSchemaOverJson:off @@ -298,8 +298,8 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => { title: "Use Claude home", }, }), - homeMustBe: claudeHome, - claudeConfig: { homePath: claudeHome }, + configDirMustBe: claudeConfigDir, + claudeConfig: { homePath: claudeConfigDir }, }, (textGeneration) => Effect.gen(function* () { diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index 24054a9587..657118fff5 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -35,6 +35,8 @@ function makeFakeCodexBinary( requireServiceTier?: string; requireReasoningEffort?: string; forbidReasoningEffort?: boolean; + requireArg?: string; + forbidArg?: string; stdinMustContain?: string; stdinMustNotContain?: string; }, @@ -50,6 +52,7 @@ function makeFakeCodexBinary( codexPath, [ "#!/bin/sh", + 'original_args="$*"', 'output_path=""', 'seen_image="0"', 'seen_service_tier=""', @@ -87,6 +90,22 @@ function makeFakeCodexBinary( " shift", "done", 'stdin_content="$(cat)"', + ...(input.requireArg !== undefined + ? [ + `case " $original_args " in *" ${input.requireArg} "*) ;; *)`, + ` printf "%s\\n" "missing arg: ${input.requireArg}" >&2`, + ` exit 8`, + "esac", + ] + : []), + ...(input.forbidArg !== undefined + ? [ + `case " $original_args " in *" ${input.forbidArg} "*)`, + ` printf "%s\\n" "forbidden arg: ${input.forbidArg}" >&2`, + ` exit 9`, + "esac", + ] + : []), ...(input.requireImage ? [ 'if [ "$seen_image" != "1" ]; then', @@ -166,8 +185,12 @@ function withFakeCodexEnv( requireServiceTier?: string; requireReasoningEffort?: string; forbidReasoningEffort?: boolean; + requireArg?: string; + forbidArg?: string; stdinMustContain?: string; stdinMustNotContain?: string; + launchArgs?: string; + environment?: NodeJS.ProcessEnv; }, effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect, ) { @@ -175,8 +198,8 @@ function withFakeCodexEnv( const fs = yield* FileSystem.FileSystem; const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" }); const codexPath = yield* makeFakeCodexBinary(tempDir, input); - const config = decodeCodexSettings({ binaryPath: codexPath }); - const textGeneration = yield* makeCodexTextGeneration(config); + const config = decodeCodexSettings({ binaryPath: codexPath, launchArgs: input.launchArgs }); + const textGeneration = yield* makeCodexTextGeneration(config, input.environment); return yield* effectFn(textGeneration); }).pipe(Effect.scoped); } @@ -237,6 +260,51 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => { ), ); + it.effect("passes exec-safe launch args into codex exec", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + subject: "Add important change", + body: "", + }), + launchArgs: "--strict-config --listen off", + requireArg: "--strict-config", + forbidArg: "--listen", + }, + (textGeneration) => + textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/codex-effect", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }), + ), + ); + + it.effect("uses T3CODE_CODEX_LAUNCH_ARGS for codex exec over settings", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + subject: "Add important change", + body: "", + }), + launchArgs: "--enable settings-feature", + environment: { T3CODE_CODEX_LAUNCH_ARGS: " --strict-config --listen off " }, + requireArg: "--strict-config", + forbidArg: "settings-feature", + }, + (textGeneration) => + textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/codex-effect", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }), + ), + ); + it.effect("defaults git text generation codex effort to low", () => withFakeCodexEnv( { diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index 0e68994fd3..6a5c0df43c 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -14,6 +14,7 @@ import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { resolveAttachmentPath } from "../attachmentStore.ts"; import * as ServerConfig from "../config.ts"; import { expandHomePath } from "../pathExpansion.ts"; +import { codexExecLaunchArgs, resolveCodexLaunchArgs } from "../provider/Layers/codexLaunchArgs.ts"; import { TextGenerationError } from "@t3tools/contracts"; import * as TextGeneration from "./TextGeneration.ts"; import { @@ -174,6 +175,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func const outputPath = yield* writeTempFile(operation, "codex-output", ""); const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () { + const launchArgs = resolveCodexLaunchArgs(codexConfig.launchArgs, resolvedEnvironment); const reasoningEffort = getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT; @@ -182,6 +184,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func codexConfig.binaryPath || "codex", [ "exec", + ...codexExecLaunchArgs(launchArgs), "--ephemeral", "--skip-git-repo-check", "-s", diff --git a/apps/server/src/textGeneration/GrokTextGeneration.ts b/apps/server/src/textGeneration/GrokTextGeneration.ts index 1bb5821630..fd367acdf4 100644 --- a/apps/server/src/textGeneration/GrokTextGeneration.ts +++ b/apps/server/src/textGeneration/GrokTextGeneration.ts @@ -1,3 +1,4 @@ +import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; @@ -37,6 +38,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi grokSettings: GrokSettings, environment: NodeJS.ProcessEnv = process.env, ) { + const crypto = yield* Crypto.Crypto; const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const runGrokJson = ({ @@ -65,7 +67,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi childProcessSpawner: commandSpawner, cwd, clientInfo: { name: "t3-code-git-text", version: "0.0.0" }, - }); + }).pipe(Effect.provideService(Crypto.Crypto, crypto)); yield* runtime.handleSessionUpdate((notification) => { const update = notification.update; diff --git a/apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts b/apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts index 558a8663b6..1fcf9bc4c7 100644 --- a/apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts @@ -107,6 +107,14 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = { cause: null, }), ), + loadInventoryFromCli: () => + Effect.fail( + new OpenCodeRuntime.OpenCodeRuntimeError({ + operation: "loadInventoryFromCli", + detail: "OpenCodeRuntimeTestDouble.loadInventoryFromCli not used in this test", + cause: null, + }), + ), }; const DEFAULT_TEST_MODEL_SELECTION = { diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index dc58fc2543..8c627525b4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -6,6 +6,9 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as Scope from "effect/Scope"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { GitCommandError } from "@t3tools/contracts"; import { ServerConfig } from "../config.ts"; @@ -20,6 +23,21 @@ const TestLayer = GitVcsDriver.layer.pipe( Layer.provideMerge(NodeServices.layer), ); +const makeNonRepositoryHandle = () => + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.empty, + stderr: Stream.encodeText(Stream.make("fatal: not a git repository")), + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); + const makeTmpDir = ( prefix = "git-vcs-driver-test-", ): Effect.Effect => @@ -77,7 +95,62 @@ const initRepoWithCommit = ( return { initialBranch }; }); +it.effect("uses stable diagnostics for every parsed non-repository command", () => { + const commands: Array<{ readonly args: ReadonlyArray; readonly lcAll?: string }> = []; + const spawner = ChildProcessSpawner.make((command) => + Effect.sync(() => { + if (!ChildProcess.isStandardCommand(command)) { + return assert.fail("expected a standard Git command"); + } + commands.push({ + args: command.args, + ...(command.options.env?.LC_ALL ? { lcAll: command.options.env.LC_ALL } : {}), + }); + return makeNonRepositoryHandle(); + }), + ); + const nodeServicesLayer = Layer.merge( + NodeServices.layer, + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const layer = GitVcsDriver.layer.pipe( + Layer.provide(ServerConfigLayer), + Layer.provideMerge(nodeServicesLayer), + ); + + return Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const cwd = "/repo"; + + yield* driver.statusDetailsLocal(cwd); + yield* driver.statusDetailsRemote(cwd, { refreshUpstream: false }); + yield* driver.listRefs({ cwd }); + + assert.deepStrictEqual(commands, [ + { args: ["status", "--porcelain=2", "--branch"], lcAll: "C" }, + { args: ["rev-parse", "--abbrev-ref", "HEAD"], lcAll: "C" }, + { args: ["branch", "--no-color", "--no-column"], lcAll: "C" }, + ]); + }).pipe(Effect.provide(layer)); +}); + it.layer(TestLayer)("GitVcsDriver core integration", (it) => { + describe("process environment", () => { + it.effect("preserves the caller locale for general Git subprocesses", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + + const locale = yield* git( + cwd, + ["-c", 'alias.print-locale=!printf "%s" "$LC_ALL"', "print-locale"], + { LC_ALL: "zh_CN.UTF-8" }, + ); + + assert.equal(locale, "zh_CN.UTF-8"); + }), + ); + }); + describe("structured errors", () => { it.effect("preserves structured spawn context and the platform cause", () => Effect.gen(function* () { @@ -620,6 +693,24 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => { assert.notInclude(status, "a.txt"); }), ); + + it.effect("treats selected file paths literally", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + + yield* writeTextFile(cwd, "selected[1].txt", "literal\n"); + yield* writeTextFile(cwd, "selected1.txt", "pattern match\n"); + + yield* driver.prepareCommitContext(cwd, ["selected[1].txt"]); + + assert.equal(yield* git(cwd, ["diff", "--cached", "--name-only"]), "selected[1].txt"); + + const status = yield* git(cwd, ["status", "--porcelain"]); + assert.include(status, "?? selected1.txt"); + }), + ); }); describe("remote operations", () => { diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index a406cbce54..6293ff7c29 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -830,6 +830,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }), ); + const executeGitWithStableDiagnostics = ( + operation: string, + cwd: string, + args: readonly string[], + options: ExecuteGitOptions = {}, + ): Effect.Effect => + executeGit(operation, cwd, args, { + ...options, + env: { + ...options.env, + LC_ALL: "C", + }, + }); + const runGit = ( operation: string, cwd: string, @@ -1184,7 +1198,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* (cwd: string) { - const branchResult = yield* executeGit( + const branchResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.statusDetailsRemote.branch", cwd, ["rev-parse", "--abbrev-ref", "HEAD"], @@ -1304,7 +1318,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) { - const statusResult = yield* executeGit( + const statusResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.statusDetails.status", cwd, ["status", "--porcelain=2", "--branch"], @@ -1524,6 +1538,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }), ); yield* runGit("GitVcsDriver.prepareCommitContext.addSelected", cwd, [ + "--literal-pathspecs", "add", "-A", "--", @@ -1985,7 +2000,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const branchRecencyPromise = readBranchRecency(input.cwd).pipe( Effect.orElseSucceed(() => new Map()), ); - const localBranchResult = yield* executeGit( + const localBranchResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.listRefs.branchNoColor", input.cwd, ["branch", "--no-color", "--no-column"], diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 2431951755..25c2cad095 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -20,6 +20,7 @@ import { AuthAccessReadScope, AuthAccessStreamError, type AuthAccessStreamEvent, + type ApplicationStoredEvent, type AuthEnvironmentScope, AuthSessionId, CommandId, @@ -35,6 +36,7 @@ import { OrchestrationV2GetThreadProjectionError, OrchestrationV2ThreadLaunchError, type OrchestrationProjectShell, + type OrchestrationV2ShellSnapshot, type ProjectEntriesFailure, type ProjectFileFailure, type ProjectFileOperation, @@ -74,6 +76,7 @@ import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts" import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; import { archivedShellStreamItemFromSnapshot, + coalesceShellApplicationEvents, shellStreamItemFromSnapshot, } from "./orchestration-v2/ShellStream.ts"; import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts"; @@ -313,6 +316,7 @@ const RPC_REQUIRED_SCOPE = new Map([ [ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell, AuthOrchestrationReadScope], [ORCHESTRATION_V2_WS_METHODS.subscribeShell, AuthOrchestrationReadScope], [ORCHESTRATION_V2_WS_METHODS.subscribeThread, AuthOrchestrationReadScope], + [WS_METHODS.serverProbe, AuthOrchestrationReadScope], [WS_METHODS.serverGetConfig, AuthOrchestrationReadScope], [WS_METHODS.serverRefreshProviders, AuthOrchestrationOperateScope], [WS_METHODS.serverUpdateProvider, AuthOrchestrationOperateScope], @@ -593,6 +597,8 @@ const makeWsRpcLayer = ( otlpMetricsEnabled: config.otlpMetricsUrl !== undefined, }, settings, + shellResumeCompletionMarker: true, + threadResumeCompletionMarker: true, }; }); @@ -602,11 +608,89 @@ const makeWsRpcLayer = ( .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid); const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subscribeThread")( - function* (input: { readonly threadId: ThreadId }) { + function* (input: { + readonly threadId: ThreadId; + readonly afterSequence?: number; + readonly requestCompletionMarker?: boolean; + }) { yield* Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId, }); + const eventStreamFrom = (afterSequence: number) => + threadManagement + .streamStoredEventsFrom({ + threadId: input.threadId, + afterSequence, + }) + .pipe( + Stream.map((stored) => ({ + kind: "event" as const, + sequence: stored.sequence, + event: stored.event, + })), + Stream.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: `Failed while streaming orchestration V2 thread ${input.threadId}`, + cause, + }), + ), + ); + + const replayThrough = (afterSequence: number, throughSequence: number) => + applicationEvents + .readAgentEvents({ + threadId: input.threadId, + afterSequence, + throughSequence, + }) + .pipe( + Stream.map((stored) => ({ + kind: "event" as const, + sequence: stored.sequence, + event: stored.event, + })), + Stream.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: `Failed while replaying orchestration V2 thread ${input.threadId}`, + cause, + }), + ), + ); + + const completionMarker = + input.requestCompletionMarker === true + ? Stream.make({ kind: "synchronized" as const }) + : Stream.empty; + + // When the client already holds the projection (cached, or loaded over + // HTTP) it passes that snapshot's sequence, and we resume by replaying + // persisted events after it instead of re-sending the (potentially + // multi-KB) snapshot frame over the socket. The event sink subscribes + // to live events before reading the persisted tail, so no event + // published during the replay window is lost; overlapping events are + // deduped by sequence on the client. + if (input.afterSequence !== undefined) { + const highWater = yield* applicationEvents.latestAgentSequence(input.threadId).pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: `Failed to prepare orchestration V2 thread ${input.threadId} replay`, + cause, + }), + ), + ); + return Stream.concat( + Stream.concat(replayThrough(input.afterSequence, highWater), completionMarker), + eventStreamFrom(highWater), + ); + } + const snapshot = yield* threadManagement.getThreadSnapshot(input.threadId).pipe( Effect.mapError( (cause) => @@ -619,40 +703,25 @@ const makeWsRpcLayer = ( ); const { projection, snapshotSequence } = snapshot; - const liveStream = threadManagement - .streamStoredEventsFrom({ - threadId: input.threadId, - afterSequence: snapshotSequence, - }) - .pipe( - Stream.map((stored) => ({ - kind: "event" as const, - sequence: stored.sequence, - event: stored.event, - })), - Stream.mapError( - (cause) => - new OrchestrationV2GetThreadProjectionError({ - threadId: input.threadId, - message: `Failed while streaming orchestration V2 thread ${input.threadId}`, - cause, - }), - ), - ); - return Stream.concat( - Stream.make({ - kind: "snapshot" as const, - snapshotSequence, - projection, - }), - liveStream, + Stream.concat( + Stream.make({ + kind: "snapshot" as const, + snapshotSequence, + projection, + }), + completionMarker, + ), + eventStreamFrom(snapshotSequence), ); }, ); const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subscribeShell")( - function* () { + function* (input: { + readonly afterSequence?: number; + readonly requestCompletionMarker?: boolean; + }) { const enrichmentChanges = yield* projectEnrichment.subscribeChanges; const loadSnapshot = Effect.fn("ws.orchestrationV2.loadShellSnapshot")(function* () { const base = yield* sql.withTransaction( @@ -671,57 +740,65 @@ const makeWsRpcLayer = ( const projects = yield* enrichProjectShells(base.projects); return { ...base, projects }; }); - const snapshot = yield* loadSnapshot().pipe( - Effect.mapError( - (cause) => - new OrchestrationV2GetShellSnapshotError({ - message: "Failed to load the application shell snapshot", - cause, - }), - ), - ); - - const live = applicationEvents - .streamApplicationEvents({ afterSequence: snapshot.snapshotSequence }) - .pipe( - Stream.mapEffect((stored) => - Effect.gen(function* () { - if ("aggregateKind" in stored) { - if (stored.type === "project.deleted") { - return { - kind: "project.removed" as const, - sequence: stored.sequence, - projectId: stored.payload.projectId, - }; - } - const project = yield* projectionSnapshotQuery.getProjectShellById( - stored.payload.projectId, - ); - return Option.match(project, { - onNone: () => ({ - kind: "project.removed" as const, - sequence: stored.sequence, - projectId: stored.payload.projectId, - }), - onSome: (value) => ({ - kind: "project.updated" as const, - sequence: stored.sequence, - project: value, - }), - }); - } - const nextSnapshot = yield* threadManagement.getShellSnapshot(); - return shellStreamItemFromSnapshot({ stored, snapshot: nextSnapshot }); - }), - ), - Stream.mapError( - (cause) => - new OrchestrationV2GetShellSnapshotError({ - message: "Failed while streaming the application shell", - cause, - }), - ), + const projectItem = Effect.fn("ws.orchestrationV2.projectShellItem")(function* ( + stored: Extract, + ) { + if (stored.type === "project.deleted") { + return { + kind: "project.removed" as const, + sequence: stored.sequence, + projectId: stored.payload.projectId, + }; + } + const project = yield* projectionSnapshotQuery.getProjectShellById( + stored.payload.projectId, ); + return Option.match(project, { + onNone: () => ({ + kind: "project.removed" as const, + sequence: stored.sequence, + projectId: stored.payload.projectId, + }), + onSome: (value) => ({ + kind: "project.updated" as const, + sequence: stored.sequence, + project: value, + }), + }); + }); + + const projectShellItems = Effect.fn("ws.orchestrationV2.projectShellItems")(function* ( + events: ReadonlyArray, + ) { + const survivors = coalesceShellApplicationEvents(events); + const needsThreadSnapshot = survivors.some((stored) => !("aggregateKind" in stored)); + const threadSnapshot = needsThreadSnapshot + ? yield* threadManagement.getShellSnapshot().pipe(Effect.map(Option.some)) + : Option.none(); + return yield* Effect.forEach( + survivors, + (stored) => + "aggregateKind" in stored + ? projectItem(stored) + : Effect.succeed( + shellStreamItemFromSnapshot({ + stored, + snapshot: Option.getOrThrow(threadSnapshot), + }), + ), + { concurrency: 8 }, + ); + }); + + const toShellStream = (stream: Stream.Stream) => + stream.pipe( + Stream.groupedWithin(512, Duration.millis(50)), + Stream.mapEffect((events) => projectShellItems(Array.from(events))), + Stream.flatMap(Stream.fromIterable), + ); + + const liveFrom = (afterSequence: number) => + toShellStream(applicationEvents.streamApplicationEvents({ afterSequence })); const enrichmentRefreshes = Stream.fromSubscription(enrichmentChanges).pipe( Stream.filter((change) => change.repositoryIdentityResolved), @@ -730,10 +807,52 @@ const makeWsRpcLayer = ( Stream.map((snapshot) => ({ kind: "snapshot" as const, snapshot })), ); - return Stream.merge( - Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), live), - enrichmentRefreshes, - ).pipe( + // When the client already holds a shell snapshot (cached, or loaded + // over HTTP) it passes that snapshot's sequence, and we resume by + // replaying application events after it instead of re-sending the + // whole projects/threads list over the socket. The event store + // subscribes to live events before reading the persisted tail, so no + // event published during the replay window is lost; overlapping events + // are deduped by sequence on the client. + const completionMarker = + input.requestCompletionMarker === true + ? Stream.make({ kind: "synchronized" as const }) + : Stream.empty; + const snapshotThenLive = (snapshot: OrchestrationV2ShellSnapshot) => + Stream.concat( + Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), completionMarker), + liveFrom(snapshot.snapshotSequence), + ); + + const base = yield* Effect.gen(function* () { + if (input.afterSequence === undefined) { + return snapshotThenLive(yield* loadSnapshot()); + } + + const highWater = yield* applicationEvents.latestApplicationSequence; + const replayGap = highWater - input.afterSequence; + if (replayGap < 0 || replayGap > 1_000) { + return snapshotThenLive(yield* loadSnapshot()); + } + + const replay = toShellStream( + applicationEvents.readApplicationEvents({ + afterSequence: input.afterSequence, + throughSequence: highWater, + }), + ); + return Stream.concat(Stream.concat(replay, completionMarker), liveFrom(highWater)); + }).pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed to prepare the application shell stream", + cause, + }), + ), + ); + + return Stream.merge(base, enrichmentRefreshes).pipe( Stream.mapError( (cause) => new OrchestrationV2GetShellSnapshotError({ @@ -1013,10 +1132,10 @@ const makeWsRpcLayer = ( subscribeOrchestrationV2ArchivedShell(), { "rpc.aggregate": "orchestration" }, ), - [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (_input) => + [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input) => observeRpcStreamEffect( ORCHESTRATION_V2_WS_METHODS.subscribeShell, - subscribeOrchestrationV2Shell(), + subscribeOrchestrationV2Shell(input), { "rpc.aggregate": "orchestrationV2", }, @@ -1057,6 +1176,10 @@ const makeWsRpcLayer = ( "rpc.aggregate": "scheduledTasks", "scheduled_task.id": input.id, }), + [WS_METHODS.serverProbe]: (_input) => + observeRpcEffect(WS_METHODS.serverProbe, Effect.succeed({}), { + "rpc.aggregate": "server", + }), [WS_METHODS.serverGetConfig]: (_input) => observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, { "rpc.aggregate": "server", diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts index 473df069ed..521654f327 100644 --- a/apps/server/vite.config.ts +++ b/apps/server/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig, mergeConfig } from "vite-plus"; import baseConfig from "../../vite.config.ts"; import { loadRepoEnv } from "../../scripts/lib/public-config.ts"; +import packageJson from "./package.json" with { type: "json" }; const bundledPackagePrefixes = [ "@pierre/diffs", @@ -16,6 +17,7 @@ export function shouldBundleCliDependency(id: string): boolean { } const repoEnv = loadRepoEnv(); +const cliBuildChannel = packageJson.version.includes("-nightly.") ? "nightly" : "latest"; export default mergeConfig( baseConfig, @@ -42,6 +44,7 @@ export default mergeConfig( js: "#!/usr/bin/env node\n", }, define: { + __T3CODE_BUILD_CHANNEL__: JSON.stringify(cliBuildChannel), __T3CODE_BUILD_RELAY_URL__: JSON.stringify(repoEnv.T3CODE_RELAY_URL?.trim() ?? ""), __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: JSON.stringify( repoEnv.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ?? "", diff --git a/apps/web/package.json b/apps/web/package.json index 484422f1a5..5a1579a478 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/web", - "version": "0.0.27", + "version": "0.0.28", "private": true, "type": "module", "scripts": { diff --git a/apps/web/public/apple-touch-icon.png b/apps/web/public/apple-touch-icon.png index e0e1b9659b..3eed25ea6b 100644 Binary files a/apps/web/public/apple-touch-icon.png and b/apps/web/public/apple-touch-icon.png differ diff --git a/apps/web/public/favicon-16x16.png b/apps/web/public/favicon-16x16.png index 673d845999..a3431b8c6d 100644 Binary files a/apps/web/public/favicon-16x16.png and b/apps/web/public/favicon-16x16.png differ diff --git a/apps/web/public/favicon-32x32.png b/apps/web/public/favicon-32x32.png index 25bcc95d4a..862f762997 100644 Binary files a/apps/web/public/favicon-32x32.png and b/apps/web/public/favicon-32x32.png differ diff --git a/apps/web/public/favicon.ico b/apps/web/public/favicon.ico index 36975b9978..750da22602 100644 Binary files a/apps/web/public/favicon.ico and b/apps/web/public/favicon.ico differ diff --git a/apps/web/src/assets/assetUrls.ts b/apps/web/src/assets/assetUrls.ts index 673b093e33..701af3a79f 100644 --- a/apps/web/src/assets/assetUrls.ts +++ b/apps/web/src/assets/assetUrls.ts @@ -9,7 +9,15 @@ import { usePreparedConnection } from "~/state/session"; export { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; -export function useAssetUrl(environmentId: EnvironmentId, resource: AssetResource): string | null { +export type AssetUrlState = + | { readonly _tag: "Loading" } + | { readonly _tag: "Failure" } + | { readonly _tag: "Success"; readonly url: string }; + +export function useAssetUrlState( + environmentId: EnvironmentId, + resource: AssetResource, +): AssetUrlState { const preparedConnection = usePreparedConnection(environmentId); const result = useAtomValue( assetEnvironment.createUrl({ @@ -17,10 +25,22 @@ export function useAssetUrl(environmentId: EnvironmentId, resource: AssetResourc input: { resource }, }), ); + if (result._tag === "Failure") { + return { _tag: "Failure" }; + } if (preparedConnection._tag === "None" || result._tag !== "Success") { + return { _tag: "Loading" }; + } + const url = resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl); + return url === null ? { _tag: "Failure" } : { _tag: "Success", url }; +} + +export function useAssetUrl(environmentId: EnvironmentId, resource: AssetResource): string | null { + const result = useAssetUrlState(environmentId, resource); + if (result._tag !== "Success") { return null; } - return resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl); + return result.url; } export function useAssetUrls( diff --git a/apps/web/src/branding.logic.ts b/apps/web/src/branding.logic.ts index b87276f1b9..056fbb76e6 100644 --- a/apps/web/src/branding.logic.ts +++ b/apps/web/src/branding.logic.ts @@ -4,6 +4,10 @@ export function formatAppDisplayName(input: { readonly baseName: string; readonly stageLabel: string; }): string { + if (input.stageLabel.trim().toLowerCase() === "latest") { + return input.baseName; + } + return `${input.baseName} (${input.stageLabel})`; } diff --git a/apps/web/src/branding.test.ts b/apps/web/src/branding.test.ts index 4aa969c027..e1c87bcf05 100644 --- a/apps/web/src/branding.test.ts +++ b/apps/web/src/branding.test.ts @@ -50,6 +50,17 @@ describe("branding", () => { expect(branding.APP_DISPLAY_NAME).toBe("T3 Code (Nightly)"); }); + it("does not label the latest hosted app channel", async () => { + vi.stubEnv("VITE_HOSTED_APP_CHANNEL", "latest"); + + const branding = await import("./branding"); + + expect(branding.HOSTED_APP_CHANNEL).toBe("latest"); + expect(branding.HOSTED_APP_CHANNEL_LABEL).toBe("Latest"); + expect(branding.APP_STAGE_LABEL).toBe("Latest"); + expect(branding.APP_DISPLAY_NAME).toBe("T3 Code"); + }); + it("ignores unknown hosted app channels", async () => { vi.stubEnv("VITE_HOSTED_APP_CHANNEL", "preview"); diff --git a/apps/web/src/browser/browserTargetResolver.test.ts b/apps/web/src/browser/browserTargetResolver.test.ts index d3c7f6a8da..6f89d86df8 100644 --- a/apps/web/src/browser/browserTargetResolver.test.ts +++ b/apps/web/src/browser/browserTargetResolver.test.ts @@ -25,6 +25,89 @@ describe("browser target resolver", () => { }); }); + it("maps localhost URL navigation onto a remote Tailscale IPv4 host", async () => { + readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://100.65.180.100:3773" }); + const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver"); + expect( + resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), { + kind: "url", + url: "http://localhost:5173/dashboard?mode=test#results", + }), + ).toEqual({ + requestedUrl: "http://localhost:5173/dashboard?mode=test#results", + resolvedUrl: "http://100.65.180.100:5173/dashboard?mode=test#results", + resolutionKind: "direct-private-network", + environmentId: "environment-1", + }); + }); + + it("preserves URL credentials when mapping localhost onto a remote host", async () => { + readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://100.65.180.100:3773" }); + const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver"); + expect( + resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), { + kind: "url", + url: "http://user:p%40ss@localhost:5173/dashboard", + }).resolvedUrl, + ).toBe("http://user:p%40ss@100.65.180.100:5173/dashboard"); + }); + + it("maps credentialed localhost URLs onto private IPv6 hosts", async () => { + readPreparedConnection.mockReturnValue({ + httpBaseUrl: "http://[fd7a:115c:a1e0::53]:3773", + }); + const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver"); + expect( + resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), { + kind: "url", + url: "http://user:p%40ss@localhost:5173/dashboard?mode=test#results", + }).resolvedUrl, + ).toBe("http://user:p%40ss@[fd7a:115c:a1e0::53]:5173/dashboard?mode=test#results"); + }); + + it("maps schemeless localhost navigation onto a remote environment host", async () => { + readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://192.168.1.25:3773" }); + const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver"); + expect( + resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), { + kind: "url", + url: "localhost:3000/app", + }).resolvedUrl, + ).toBe("http://192.168.1.25:3000/app"); + }); + + it("keeps localhost navigation local for a local environment", async () => { + readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://127.0.0.1:3773" }); + const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver"); + expect( + resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), { + kind: "url", + url: "localhost:3000/app", + }), + ).toEqual({ + requestedUrl: "localhost:3000/app", + resolvedUrl: "localhost:3000/app", + resolutionKind: "direct", + environmentId: "environment-1", + }); + }); + + it("keeps localhost navigation local for the full IPv4 loopback range", async () => { + readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://127.0.0.2:3773" }); + const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver"); + expect( + resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), { + kind: "url", + url: "http://localhost:3000/app", + }), + ).toEqual({ + requestedUrl: "http://localhost:3000/app", + resolvedUrl: "http://localhost:3000/app", + resolutionKind: "direct", + environmentId: "environment-1", + }); + }); + it("refuses public relay hosts until the authenticated gateway exists", async () => { readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://relay.example.com" }); const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver"); @@ -34,6 +117,12 @@ describe("browser target resolver", () => { port: 5173, }), ).toThrow(/authenticated preview gateway/); + expect(() => + resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), { + kind: "url", + url: "http://localhost:5173", + }), + ).toThrow(/authenticated preview gateway/); }); it("normalizes schemeless localhost server-picker values", async () => { @@ -63,7 +152,9 @@ describe("browser target resolver", () => { }); it("supports private IPv6 environment hosts", async () => { - readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://[::1]:3773" }); + readPreparedConnection.mockReturnValue({ + httpBaseUrl: "http://[fd7a:115c:a1e0::53]:3773", + }); const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver"); expect( resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), { @@ -71,7 +162,18 @@ describe("browser target resolver", () => { port: 5173, path: "/app?mode=test", }).resolvedUrl, - ).toBe("http://[::1]:5173/app?mode=test"); + ).toBe("http://[fd7a:115c:a1e0::53]:5173/app?mode=test"); + }); + + it("supports a local IPv6 environment host", async () => { + readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://[::1]:3773" }); + const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver"); + expect( + resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), { + kind: "environment-port", + port: 5173, + }).resolvedUrl, + ).toBe("http://[::1]:5173/"); }); it("leaves malformed input for the normal navigation error path", async () => { diff --git a/apps/web/src/browser/browserTargetResolver.ts b/apps/web/src/browser/browserTargetResolver.ts index 9142cce1e7..9b201dbdba 100644 --- a/apps/web/src/browser/browserTargetResolver.ts +++ b/apps/web/src/browser/browserTargetResolver.ts @@ -7,43 +7,60 @@ import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview"; import { readPreparedConnection } from "~/state/session"; -const isPrivateNetworkHost = (host: string): boolean => { - const normalized = host.toLowerCase().replace(/^\[|\]$/g, ""); - if (normalized === "localhost" || normalized === "::1" || normalized.endsWith(".local")) { - return true; - } - if (normalized.endsWith(".ts.net")) return true; - const parts = normalized.split(".").map(Number); - if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return false; - return ( - parts[0] === 10 || - (parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) || - (parts[0] === 192 && parts[1] === 168) || - parts[0] === 127 || - (parts[0] === 169 && parts[1] === 254) - ); +const normalizeHostname = (host: string): string => host.toLowerCase().replace(/^\[|\]$/g, ""); + +const parseIpv4Address = (host: string): readonly number[] | null => { + const parts = normalizeHostname(host).split(".").map(Number); + return parts.length === 4 && + parts.every((part) => Number.isInteger(part) && part >= 0 && part <= 255) + ? parts + : null; }; const isLocalLoopbackHost = (host: string): boolean => { - const normalized = host.toLowerCase().replace(/^\[|\]$/g, ""); - return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1"; + const normalized = normalizeHostname(host); + if (normalized === "localhost" || normalized === "::1") return true; + return parseIpv4Address(normalized)?.[0] === 127; }; -export function resolveBrowserNavigationTarget( - environmentId: EnvironmentId, - target: BrowserNavigationTarget, -): PreviewUrlResolution { - if (target.kind === "url") { - return { - requestedUrl: target.url, - resolvedUrl: target.url, - resolutionKind: "direct", - environmentId, - }; +const isPrivateNetworkHost = (host: string): boolean => { + const normalized = normalizeHostname(host); + if (isLocalLoopbackHost(normalized) || normalized.endsWith(".local")) { + return true; } + if (normalized.endsWith(".ts.net")) return true; + const parts = parseIpv4Address(normalized); + if (parts) { + return ( + parts[0] === 10 || + (parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127) || + (parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) || + (parts[0] === 192 && parts[1] === 168) || + (parts[0] === 169 && parts[1] === 254) + ); + } + const firstIpv6Token = normalized.split(":", 1)[0] ?? ""; + if (!normalized.includes(":") || !/^[\da-f]{1,4}$/u.test(firstIpv6Token)) return false; + const firstIpv6Hextet = Number.parseInt(firstIpv6Token, 16); + return ( + Number.isInteger(firstIpv6Hextet) && + ((firstIpv6Hextet & 0xfe00) === 0xfc00 || (firstIpv6Hextet & 0xffc0) === 0xfe80) + ); +}; + +const readEnvironmentUrl = (environmentId: EnvironmentId): URL => { const connection = readPreparedConnection(environmentId); if (!connection) throw new Error(`Environment ${environmentId} is not connected.`); - const environmentUrl = new URL(connection.httpBaseUrl); + return new URL(connection.httpBaseUrl); +}; + +const resolveEnvironmentPortTarget = ( + environmentId: EnvironmentId, + target: Extract, + environmentUrl: URL, + requestedUrl?: string, + sourceUrl?: URL, +): PreviewUrlResolution => { if (!isPrivateNetworkHost(environmentUrl.hostname)) { throw new Error( "This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.", @@ -51,40 +68,72 @@ export function resolveBrowserNavigationTarget( } const protocol = target.protocol ?? "http"; const path = target.path?.startsWith("/") ? target.path : `/${target.path ?? ""}`; - const requestedUrl = `${protocol}://localhost:${target.port}${path}`; const normalizedEnvironmentHost = environmentUrl.hostname.replace(/^\[|\]$/g, ""); const resolvedHost = normalizedEnvironmentHost.includes(":") ? `[${normalizedEnvironmentHost}]` : normalizedEnvironmentHost; - const resolved = new URL(path, `${protocol}://${resolvedHost}:${target.port}`); + const resolved = sourceUrl + ? new URL(sourceUrl) + : new URL(path, `${protocol}://${resolvedHost}:${target.port}`); + if (sourceUrl) { + resolved.hostname = resolvedHost; + resolved.port = String(target.port); + } return { - requestedUrl, + requestedUrl: requestedUrl ?? `${protocol}://localhost:${target.port}${path}`, resolvedUrl: resolved.toString(), - resolutionKind: - normalizedEnvironmentHost === "localhost" || normalizedEnvironmentHost === "127.0.0.1" - ? "direct" - : "direct-private-network", + resolutionKind: isLocalLoopbackHost(normalizedEnvironmentHost) + ? "direct" + : "direct-private-network", environmentId, }; +}; + +export function resolveBrowserNavigationTarget( + environmentId: EnvironmentId, + target: BrowserNavigationTarget, +): PreviewUrlResolution { + if (target.kind === "url") { + let parsed: URL | null = null; + try { + parsed = new URL(normalizePreviewUrl(target.url)); + } catch { + // Preserve the existing direct-navigation behavior so the preview host + // reports malformed URL errors through its normal navigation path. + } + if (parsed && isLoopbackHost(parsed.hostname)) { + const environmentUrl = readEnvironmentUrl(environmentId); + if (parsed.hostname === "0.0.0.0" || !isLocalLoopbackHost(environmentUrl.hostname)) { + return resolveEnvironmentPortTarget( + environmentId, + { + kind: "environment-port", + port: Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80)), + protocol: parsed.protocol === "https:" ? "https" : "http", + path: `${parsed.pathname}${parsed.search}${parsed.hash}`, + }, + environmentUrl, + target.url, + parsed, + ); + } + } + return { + requestedUrl: target.url, + resolvedUrl: target.url, + resolutionKind: "direct", + environmentId, + }; + } + return resolveEnvironmentPortTarget(environmentId, target, readEnvironmentUrl(environmentId)); } export function resolveDiscoveredServerUrl(environmentId: EnvironmentId, rawUrl: string): string { try { const normalizedUrl = normalizePreviewUrl(rawUrl); - const parsed = new URL(normalizedUrl); - if (!isLoopbackHost(parsed.hostname)) return normalizedUrl; - const connection = readPreparedConnection(environmentId); - if (!connection) throw new Error(`Environment ${environmentId} is not connected.`); - const environmentUrl = new URL(connection.httpBaseUrl); - if (parsed.hostname !== "0.0.0.0" && isLocalLoopbackHost(environmentUrl.hostname)) { - return normalizedUrl; - } - const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80)); return resolveBrowserNavigationTarget(environmentId, { - kind: "environment-port", - port, - protocol: parsed.protocol === "https:" ? "https" : "http", - path: `${parsed.pathname}${parsed.search}${parsed.hash}`, + kind: "url", + url: normalizedUrl, }).resolvedUrl; } catch { return rawUrl; diff --git a/apps/web/src/cloud/connectCliAuth.test.ts b/apps/web/src/cloud/connectCliAuth.test.ts new file mode 100644 index 0000000000..61d854eb6a --- /dev/null +++ b/apps/web/src/cloud/connectCliAuth.test.ts @@ -0,0 +1,69 @@ +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { + buildConnectCliClerkAuthorizeUrl, + hasConnectCliAuthConfig, + readConnectCliCallbackResult, +} from "./connectCliAuth"; + +// Any pk_test_* key decodes to .clerk.accounts.dev. +const TEST_PUBLISHABLE_KEY = `pk_test_${btoa("witty-mole-42.clerk.accounts.dev$")}`; + +describe("connectCliAuth", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("requires both the publishable key and the CLI OAuth client id", () => { + vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY); + vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", "t3-relay"); + vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.com"); + expect(hasConnectCliAuthConfig()).toBe(false); + + vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123"); + expect(hasConnectCliAuthConfig()).toBe(true); + }); + + it("builds the Clerk authorize URL with the configured hosted origin's callback", () => { + vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY); + vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123"); + vi.stubEnv("VITE_HOSTED_APP_URL", "https://nightly.app.t3.codes"); + + const authorizeUrl = buildConnectCliClerkAuthorizeUrl({ + state: "state-1", + challenge: "challenge-1", + }); + expect(authorizeUrl).not.toBeNull(); + + const url = new URL(authorizeUrl!); + expect(url.hostname).toBe("witty-mole-42.clerk.accounts.dev"); + expect(url.pathname).toBe("/oauth/authorize"); + expect(url.searchParams.get("redirect_uri")).toBe( + "https://nightly.app.t3.codes/connect/callback", + ); + expect(url.searchParams.get("state")).toBe("state-1"); + expect(url.searchParams.get("code_challenge")).toBe("challenge-1"); + expect(url.searchParams.get("code_challenge_method")).toBe("S256"); + }); + + it("returns null when the CLI OAuth client id is not configured", () => { + vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY); + expect( + buildConnectCliClerkAuthorizeUrl({ state: "state-1", challenge: "challenge-1" }), + ).toBeNull(); + }); + + it("reads the code and state Clerk echoes back to the callback", () => { + expect( + readConnectCliCallbackResult( + new URL("https://app.t3.codes/connect/callback?code=abc&state=state-1"), + ), + ).toEqual({ code: "abc", state: "state-1" }); + expect( + readConnectCliCallbackResult(new URL("https://app.t3.codes/connect/callback?code=abc")), + ).toBeNull(); + expect( + readConnectCliCallbackResult(new URL("https://app.t3.codes/connect/callback?state=s")), + ).toBeNull(); + }); +}); diff --git a/apps/web/src/cloud/connectCliAuth.ts b/apps/web/src/cloud/connectCliAuth.ts new file mode 100644 index 0000000000..849319dceb --- /dev/null +++ b/apps/web/src/cloud/connectCliAuth.ts @@ -0,0 +1,91 @@ +import { + buildConnectClerkAuthorizeUrl, + connectCallbackUrl, + CONNECT_OAUTH_SCOPES, + type ConnectAuthorizeRequest, +} from "@t3tools/shared/connectAuth"; +import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth"; + +import { configuredHostedAppUrl, isHostedStaticApp } from "../hostedPairing"; +import { hasCloudPublicConfig, resolveCloudPublicConfig, trimNonEmpty } from "./publicConfig"; + +const CONNECT_CLI_AUTH_STATE_STORAGE_KEY = "t3code-connect-cli-auth-state"; + +export function resolveConnectCliOAuthClientId(): string | null { + return trimNonEmpty(import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID as string | undefined); +} + +export function hasConnectCliAuthConfig(): boolean { + return Boolean( + resolveCloudPublicConfig().clerkPublishableKey && resolveConnectCliOAuthClientId(), + ); +} + +/** + * Gate for the /connect routes: the CLI handshake only exists on the hosted + * deployment (the same bundle ships inside local instances) and needs the + * Clerk CLI OAuth client configured at build time. + */ +export function connectCliAuthRoutesEnabled(): boolean { + return isHostedStaticApp() && hasCloudPublicConfig() && hasConnectCliAuthConfig(); +} + +/** + * Builds the Clerk authorize URL for a CLI-initiated connect request. The + * state is mirrored into sessionStorage so the callback page can verify the + * response matches a request this browser actually started. + */ +export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeRequest): string | null { + const { clerkPublishableKey } = resolveCloudPublicConfig(); + const clientId = resolveConnectCliOAuthClientId(); + if (!clerkPublishableKey || !clientId) { + return null; + } + return buildConnectClerkAuthorizeUrl({ + authorizationEndpoint: `${clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey)}/oauth/authorize`, + clientId, + redirectUri: connectCallbackUrl(configuredHostedAppUrl()), + scopes: CONNECT_OAUTH_SCOPES, + state: request.state, + challenge: request.challenge, + }); +} + +export function rememberConnectCliAuthState(state: string): void { + try { + window.sessionStorage.setItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY, state); + } catch { + // Session storage can be unavailable (e.g. blocked). The callback page + // then falls back to trusting the state Clerk echoed back. + } +} + +/** + * Read-only on purpose: this runs during render, where a removal would be + * consumed by React's double-invoked/discarded renders (StrictMode) and + * silently disable the state check. The value is not a secret and is + * overwritten by the next /connect visit. + */ +export function readConnectCliAuthState(): string | null { + try { + return window.sessionStorage.getItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY); + } catch { + return null; + } +} + +export interface ConnectCliCallbackResult { + readonly code: string; + readonly state: string; +} + +export function readConnectCliCallbackResult( + url: URL = new URL(window.location.href), +): ConnectCliCallbackResult | null { + const code = url.searchParams.get("code")?.trim() ?? ""; + const state = url.searchParams.get("state")?.trim() ?? ""; + if (!code || !state) { + return null; + } + return { code, state }; +} diff --git a/apps/web/src/cloud/connectOnboarding.ts b/apps/web/src/cloud/connectOnboarding.ts new file mode 100644 index 0000000000..7d61e11c6c --- /dev/null +++ b/apps/web/src/cloud/connectOnboarding.ts @@ -0,0 +1,18 @@ +import * as Schema from "effect/Schema"; + +/** + * Accounts that opted out of the post-sign-in T3 Connect onboarding wizard + * ("Don't show this again"). The wizard otherwise shows on every sign-in, + * since sign-out clears the connected environments. + */ +export const CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY = "t3code:connect-onboarding-opt-out:v1"; + +export const ConnectOnboardingOptOutSchema = Schema.Struct({ + optOutAccounts: Schema.Array(Schema.String), +}); + +export type ConnectOnboardingOptOutState = typeof ConnectOnboardingOptOutSchema.Type; + +export const EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE: ConnectOnboardingOptOutState = { + optOutAccounts: [], +}; diff --git a/apps/web/src/cloud/linkEnvironment.test.ts b/apps/web/src/cloud/linkEnvironment.test.ts index 7e6f2365e5..38e205beab 100644 --- a/apps/web/src/cloud/linkEnvironment.test.ts +++ b/apps/web/src/cloud/linkEnvironment.test.ts @@ -204,6 +204,7 @@ describe("web cloud link environment client", () => { cloudUserId: "user-1", relayUrl: "https://relay.example.test", relayIssuer: "https://relay.example.test", + managedTunnelActive: true, publishAgentActivity: false, }), ); @@ -217,6 +218,7 @@ describe("web cloud link environment client", () => { cloudUserId: "user-1", relayUrl: "https://relay.example.test", relayIssuer: "https://relay.example.test", + managedTunnelActive: true, publishAgentActivity: false, }), ); @@ -234,6 +236,7 @@ describe("web cloud link environment client", () => { cloudUserId: "user-1", relayUrl: "https://relay.example.test", relayIssuer: "https://relay.example.test", + managedTunnelActive: true, publishAgentActivity: false, }), ); @@ -261,6 +264,7 @@ describe("web cloud link environment client", () => { cloudUserId: "user-1", relayUrl: "https://relay.example.test", relayIssuer: "https://relay.example.test", + managedTunnelActive: true, publishAgentActivity: true, }), ); @@ -339,6 +343,57 @@ describe("web cloud link environment client", () => { }), ); + it.effect("links publish-only without a managed tunnel", () => + Effect.gen(function* () { + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + Response.json({ + challenge: "challenge", + expiresAt: "2026-06-06T00:05:00.000Z", + }), + ) + .mockResolvedValueOnce(Response.json("signed-proof")) + .mockResolvedValueOnce( + Response.json({ + ok: true, + environmentId: TARGET.environmentId, + endpoint: { + httpBaseUrl: TARGET.httpBaseUrl, + wsBaseUrl: TARGET.wsBaseUrl, + providerKind: "manual", + }, + endpointRuntime: null, + relayIssuer: "https://relay.example.test", + cloudUserId: "user-1", + environmentCredential: "environment-credential", + cloudMintPublicKey: "public-key", + }), + ) + .mockResolvedValueOnce( + Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }), + ); + vi.stubGlobal("fetch", fetchMock); + + yield* withServices( + linkPrimaryEnvironmentToCloud({ + target: TARGET, + clerkToken: "clerk-token", + mode: "publish_only", + }), + ); + + // @effect-diagnostics-next-line preferSchemaOverJson:off + expect(JSON.parse(bodyText(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({ + managedTunnelsEnabled: false, + }); + // @effect-diagnostics-next-line preferSchemaOverJson:off + expect(JSON.parse(bodyText(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({ + endpoint: { providerKind: "manual" }, + }); + }), + ); + it.effect("installs a missing relay client before linking", () => Effect.gen(function* () { vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ malformed: true }))); diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.ts index 20bf75c7d6..ec25fd104d 100644 --- a/apps/web/src/cloud/linkEnvironment.ts +++ b/apps/web/src/cloud/linkEnvironment.ts @@ -383,9 +383,17 @@ export function unlinkPrimaryEnvironmentFromCloud(input: { }).pipe(Effect.provide(primaryEnvironmentHttpLayer)); } +// "publish_only" links the environment to the relay for agent-activity +// publishing alone: no managed tunnel is provisioned, so it can be toggled +// independently of T3 Connect while clients reach the environment out of band. +export type CloudLinkMode = "managed" | "publish_only"; + +const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind; + export function linkPrimaryEnvironmentToCloud(input: { readonly target: CloudLinkTarget; readonly clerkToken: string; + readonly mode?: CloudLinkMode; }): Effect.Effect< void, CloudEnvironmentLinkError, @@ -398,9 +406,15 @@ export function linkPrimaryEnvironmentToCloud(input: { message: "T3CODE_RELAY_URL is not configured.", }); } + const managedTunnelsEnabled = (input.mode ?? "managed") === "managed"; + const providerKind = managedTunnelsEnabled + ? MANAGED_ENDPOINT_PROVIDER_KIND + : PUBLISH_ONLY_PROVIDER_KIND; const relayClient = yield* ManagedRelay.ManagedRelayClient; const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl); - yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId)); + if (managedTunnelsEnabled) { + yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId)); + } const challenge = yield* relayClient .createEnvironmentLinkChallenge({ @@ -408,7 +422,7 @@ export function linkPrimaryEnvironmentToCloud(input: { payload: { notificationsEnabled: true, liveActivitiesEnabled: true, - managedTunnelsEnabled: true, + managedTunnelsEnabled, }, }) .pipe( @@ -427,7 +441,7 @@ export function linkPrimaryEnvironmentToCloud(input: { endpoint: { httpBaseUrl: input.target.httpBaseUrl, wsBaseUrl: input.target.wsBaseUrl, - providerKind: MANAGED_ENDPOINT_PROVIDER_KIND, + providerKind, }, origin: endpointOrigin(input.target.httpBaseUrl), }, @@ -440,7 +454,7 @@ export function linkPrimaryEnvironmentToCloud(input: { proof, notificationsEnabled: true, liveActivitiesEnabled: true, - managedTunnelsEnabled: true, + managedTunnelsEnabled, }, }) .pipe( @@ -450,7 +464,7 @@ export function linkPrimaryEnvironmentToCloud(input: { ); yield* ensureLinkedEnvironmentMatches({ expectedEnvironmentId: input.target.environmentId, - expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND, + expectedProviderKind: providerKind, link, }); diff --git a/apps/web/src/cloud/linkEnvironmentAtoms.ts b/apps/web/src/cloud/linkEnvironmentAtoms.ts index 4cb62271a4..1094e860e4 100644 --- a/apps/web/src/cloud/linkEnvironmentAtoms.ts +++ b/apps/web/src/cloud/linkEnvironmentAtoms.ts @@ -6,6 +6,7 @@ import { import { connectionAtomRuntime } from "../connection/runtime"; import { linkPrimaryEnvironmentToCloud, + type CloudLinkMode, type CloudLinkTarget, unlinkPrimaryEnvironmentFromCloud, updatePrimaryCloudPreferences, @@ -21,8 +22,11 @@ export const linkPrimaryEnvironment = createRuntimeCommand(connectionAtomRuntime label: "web:cloud:link-primary-environment", scheduler: cloudLinkScheduler, concurrency: cloudLinkConcurrency, - execute: (input: { readonly target: CloudLinkTarget; readonly clerkToken: string }) => - linkPrimaryEnvironmentToCloud(input), + execute: (input: { + readonly target: CloudLinkTarget; + readonly clerkToken: string; + readonly mode?: CloudLinkMode; + }) => linkPrimaryEnvironmentToCloud(input), }); export const unlinkPrimaryEnvironment = createRuntimeCommand(connectionAtomRuntime, { diff --git a/apps/web/src/cloud/publicConfig.ts b/apps/web/src/cloud/publicConfig.ts index d9d0e5f44c..2caf4f52f3 100644 --- a/apps/web/src/cloud/publicConfig.ts +++ b/apps/web/src/cloud/publicConfig.ts @@ -24,7 +24,7 @@ export interface CloudPublicConfig { }; } -function trimNonEmpty(value: string | undefined): string | null { +export function trimNonEmpty(value: string | undefined): string | null { return value?.trim() || null; } diff --git a/apps/web/src/cloud/useCloudLinkController.ts b/apps/web/src/cloud/useCloudLinkController.ts new file mode 100644 index 0000000000..d915968808 --- /dev/null +++ b/apps/web/src/cloud/useCloudLinkController.ts @@ -0,0 +1,163 @@ +import { useAuth } from "@clerk/react"; +import { findErrorTraceId } from "@t3tools/client-runtime/errors"; +import { + isAtomCommandInterrupted, + settlePromise, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { useState } from "react"; + +import { toastManager } from "../components/ui/toast"; +import { relayEnvironmentDiscovery } from "../state/relay"; +import { useAtomCommand } from "../state/use-atom-command"; +import { + linkPrimaryEnvironment as linkPrimaryEnvironmentAtom, + unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom, + updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom, +} from "./linkEnvironmentAtoms"; +import { usePrimaryCloudLinkState } from "./primaryCloudLinkState"; +import { resolveRelayClerkTokenOptions } from "./publicConfig"; + +export interface CloudLinkDesiredState { + readonly managedTunnel: boolean; + readonly publish: boolean; +} + +/** + * Drives the primary environment's T3 Connect link. T3 Connect (managed + * tunnel) and agent-activity publishing are independent capabilities backed by + * a single relay link, so consumers express the full desired state and + * `reconcileCloudState` applies it: unlink when neither is wanted, otherwise + * (re)link with the mode the managed-tunnel bit implies and set the publish + * preference. Re-linking only happens when the managed-tunnel mode actually + * changes, so flipping publish alone is cheap. + */ +export function useCloudLinkController() { + const { getToken, isSignedIn } = useAuth(); + const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, { + reportFailure: false, + }); + const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, { + reportFailure: false, + }); + const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, { + reportFailure: false, + }); + const updatePrimaryEnvironmentPreferences = useAtomCommand( + updatePrimaryEnvironmentPreferencesAtom, + { reportFailure: false }, + ); + const primaryCloudLinkState = usePrimaryCloudLinkState(); + const [operationError, setOperationError] = useState(null); + + const reportUpdateFailure = (cause: unknown) => { + const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access."; + const traceId = findErrorTraceId(cause); + console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause }); + setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message); + toastManager.add({ + type: "error", + title: "Could not update T3 Connect", + description: message, + data: traceId + ? { + secondaryActionProps: { + children: "Copy trace ID", + onClick: () => void navigator.clipboard?.writeText(traceId), + }, + } + : undefined, + }); + }; + + // Older environment servers predate the managedTunnelActive field; for them a + // link always implies a managed tunnel, so fall back to `linked`. + const managedTunnelActive = + primaryCloudLinkState.data?.managedTunnelActive ?? primaryCloudLinkState.data?.linked ?? false; + const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false; + const linked = primaryCloudLinkState.data?.linked ?? false; + + const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise => { + setOperationError(null); + const target = primaryCloudLinkState.target; + if (!target) { + reportUpdateFailure(new Error("Local environment is not ready yet.")); + return false; + } + const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions())); + const wantsLink = desired.managedTunnel || desired.publish; + + // A failure after this point may follow a partially applied mutation (e.g. + // the link succeeded but the preference update did not), so every exit — + // success or failure — refreshes the rendered state to whatever the server + // actually holds now. + if (!wantsLink) { + // Unlink works without a relay token — a failed token read must not + // leave the user unable to turn T3 Connect off. + const unlinkResult = await unlinkPrimaryEnvironment({ + target, + clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null, + }); + if (unlinkResult._tag === "Failure") { + if (!isAtomCommandInterrupted(unlinkResult)) { + reportUpdateFailure(squashAtomCommandFailure(unlinkResult)); + } + primaryCloudLinkState.refresh(); + return false; + } + } else { + if (tokenResult._tag === "Failure") { + reportUpdateFailure(squashAtomCommandFailure(tokenResult)); + return false; + } + const clerkToken = tokenResult.value; + if (!clerkToken) { + reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this.")); + return false; + } + if (!linked || managedTunnelActive !== desired.managedTunnel) { + const linkResult = await linkPrimaryEnvironment({ + target, + clerkToken, + mode: desired.managedTunnel ? "managed" : "publish_only", + }); + if (linkResult._tag === "Failure") { + if (!isAtomCommandInterrupted(linkResult)) { + reportUpdateFailure(squashAtomCommandFailure(linkResult)); + } + primaryCloudLinkState.refresh(); + return false; + } + } + const prefResult = await updatePrimaryEnvironmentPreferences({ + target, + publishAgentActivity: desired.publish, + }); + if (prefResult._tag === "Failure") { + if (!isAtomCommandInterrupted(prefResult)) { + reportUpdateFailure(squashAtomCommandFailure(prefResult)); + } + primaryCloudLinkState.refresh(); + return false; + } + } + + primaryCloudLinkState.refresh(); + const refreshResult = await refreshRelayEnvironments(); + if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) { + reportUpdateFailure(squashAtomCommandFailure(refreshResult)); + return false; + } + return true; + }; + + return { + isSignedIn, + linkState: primaryCloudLinkState, + linked, + managedTunnelActive, + publishAgentActivity, + operationError, + reconcileCloudState, + }; +} diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 0f1a8f9d42..6c692dc3de 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -1,28 +1,62 @@ import { useAtomValue } from "@effect/atom-react"; -import { useEffect, type CSSProperties, type ReactNode } from "react"; -import { useNavigate } from "@tanstack/react-router"; +import * as Schema from "effect/Schema"; +import { useEffect, useState, type CSSProperties, type ReactNode } from "react"; +import { useLocation, useNavigate } from "@tanstack/react-router"; import { isElectron } from "../env"; +import { getLocalStorageItem } from "../hooks/useLocalStorage"; import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; -import { isMacPlatform } from "../lib/utils"; +import { cn, isMacPlatform } from "../lib/utils"; import { primaryServerKeybindingsAtom } from "../state/server"; import ThreadSidebar from "./Sidebar"; -import { Sidebar, SidebarProvider, SidebarRail, SidebarTrigger, useSidebar } from "./ui/sidebar"; +import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop"; +import { + resolveInitialThreadSidebarWidth, + resolveThreadSidebarMaximumWidth, + THREAD_MAIN_CONTENT_MIN_WIDTH, + THREAD_SIDEBAR_MIN_WIDTH, + THREAD_SIDEBAR_WIDTH_STORAGE_KEY, +} from "./threadSidebarWidth"; +import { + Sidebar, + SidebarProvider, + SidebarRail, + SidebarTrigger, + useSidebar, + useSidebarVisibility, +} from "./ui/sidebar"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; -const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width"; -const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16; -const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16; const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "90px"; +function readInitialThreadSidebarWidth(): number { + try { + return resolveInitialThreadSidebarWidth( + getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite), + window.innerWidth, + ); + } catch (error) { + console.error("Could not read persisted thread sidebar width.", error); + return resolveInitialThreadSidebarWidth(null, window.innerWidth); + } +} + function SidebarControl() { const keybindings = useAtomValue(primaryServerKeybindingsAtom); const { toggleSidebar } = useSidebar(); + const isSidebarVisible = useSidebarVisibility(); + const stageBackdropVariant = useSidebarStageBackdropVariant(); const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle"); useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { if (event.defaultPrevented) return; + if ( + event.target instanceof HTMLElement && + event.target.closest("[data-keybinding-capture]") + ) { + return; + } if (resolveShortcutCommand(event, keybindings) !== "sidebar.toggle") return; event.preventDefault(); @@ -30,8 +64,9 @@ function SidebarControl() { toggleSidebar(); }; - window.addEventListener("keydown", onKeyDown); - return () => window.removeEventListener("keydown", onKeyDown); + // Capture before focused editors consume commands such as Mod+B for rich-text formatting. + window.addEventListener("keydown", onKeyDown, true); + return () => window.removeEventListener("keydown", onKeyDown, true); }, [keybindings, toggleSidebar]); return ( @@ -42,7 +77,15 @@ function SidebarControl() { + } /> @@ -55,10 +98,39 @@ function SidebarControl() { export function AppSidebarLayout({ children }: { children: ReactNode }) { const navigate = useNavigate(); - const macosWindowControlsStyle = - isElectron && isMacPlatform(navigator.platform) - ? ({ "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET } as CSSProperties) - : undefined; + const pathname = useLocation({ select: (location) => location.pathname }); + const isMacosDesktop = isElectron && isMacPlatform(navigator.platform); + const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth); + const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(window.innerWidth); + const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => { + const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState; + return isMacosDesktop && typeof getWindowFullscreenState === "function" + ? getWindowFullscreenState() + : false; + }); + const sidebarProviderStyle = { + "--sidebar-width": `${sidebarWidth}px`, + ...(isMacosDesktop && !isWindowFullscreen + ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET } + : {}), + } as CSSProperties; + + useEffect(() => { + if (!isMacosDesktop) return; + const bridge = window.desktopBridge; + if (!bridge) return; + const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge; + if ( + typeof getWindowFullscreenState !== "function" || + typeof onWindowFullscreenStateChange !== "function" + ) { + return; + } + + const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen); + setIsWindowFullscreen(getWindowFullscreenState()); + return unsubscribe; + }, [isMacosDesktop]); useEffect(() => { const onMenuAction = window.desktopBridge?.onMenuAction; @@ -68,26 +140,32 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) { const unsubscribe = onMenuAction((action) => { if (action === "open-settings") { - void navigate({ to: "/settings" }); + const isSettingsRoute = /^\/settings(\/|$)/.test(pathname); + if (!isSettingsRoute) { + void navigate({ to: "/settings" }); + } } }); return () => { unsubscribe?.(); }; - }, [navigate]); + }, [navigate, pathname]); return ( - + + shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) => + nextWidth <= currentWidth || wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH, storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY, + onResize: setSidebarWidth, }} > diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index b04e98a8a6..c85340c715 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -32,7 +32,7 @@ import React, { useState, type ReactNode, } from "react"; -import type { Components } from "react-markdown"; +import type { Components, Options as ReactMarkdownOptions } from "react-markdown"; import ReactMarkdown from "react-markdown"; import { defaultUrlTransform } from "react-markdown"; import rehypeRaw from "rehype-raw"; @@ -60,6 +60,7 @@ import { serializeTableElementToCsv, serializeTableElementToMarkdown, } from "../markdown-clipboard"; +import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation"; import { normalizeMarkdownLinkDestination, resolveMarkdownFileLinkMeta, @@ -164,6 +165,24 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = { }, } satisfies Parameters[0]; +const CHAT_MARKDOWN_REMARK_PLUGINS = [ + remarkGfm, + remarkNormalizeListItemIndentation, + remarkPreserveCodeMeta, +] satisfies NonNullable; + +const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [ + remarkGfm, + remarkNormalizeListItemIndentation, + remarkBreaks, + remarkPreserveCodeMeta, +] satisfies NonNullable; + +const CHAT_MARKDOWN_REHYPE_PLUGINS = [ + rehypeRaw, + [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA], +] satisfies NonNullable; + function extractFenceLanguage(className: string | undefined): string { const match = className?.match(CODE_FENCE_LANGUAGE_REGEX); const raw = match?.[1] ?? "text"; @@ -1545,11 +1564,9 @@ function ChatMarkdown({ > diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 9b9fb7192a..750a6c823f 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -1,4 +1,11 @@ -import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, RunId } from "@t3tools/contracts"; +import { + EnvironmentId, + MessageId, + ProjectId, + ProviderInstanceId, + ThreadId, + RunId, +} from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import type { Thread } from "../types"; @@ -409,6 +416,36 @@ describe("hasServerAcknowledgedLocalDispatch", () => { ).toBe(true); }); + it("acknowledges a steering message projected onto the current running run", () => { + const runningRun = { + ...completedTurn, + status: "running" as const, + completedAt: null, + }; + const runningRuntime = { + ...readySession, + status: "running" as const, + activeRunId: runningRun.runId, + }; + const localDispatch = createLocalDispatchSnapshot( + makeThread({ latestRun: runningRun, runtime: runningRuntime }), + { latestUserMessageId: MessageId.make("message-before-steer") }, + ); + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "running", + latestRun: runningRun, + latestUserMessageId: MessageId.make("message-steer"), + runtime: runningRuntime, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(true); + }); + it("acknowledges pending user interaction and errors immediately", () => { const localDispatch = createLocalDispatchSnapshot(makeThread()); const common = { diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index efa6b0691f..e3f2529f52 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -364,6 +364,7 @@ export async function waitForStartedServerThread( export interface LocalDispatchSnapshot { startedAt: string; preparingWorktree: boolean; + latestUserMessageId: ChatMessage["id"] | null; latestRunId: RunId | null; latestRunRequestedAt: string | null; latestRunStartedAt: string | null; @@ -374,13 +375,14 @@ export interface LocalDispatchSnapshot { export function createLocalDispatchSnapshot( activeThread: Thread | undefined, - options?: { preparingWorktree?: boolean }, + options?: { preparingWorktree?: boolean; latestUserMessageId?: ChatMessage["id"] | null }, ): LocalDispatchSnapshot { const latestRun = activeThread?.latestRun ?? null; const runtime = activeThread?.runtime ?? null; return { startedAt: new Date().toISOString(), preparingWorktree: Boolean(options?.preparingWorktree), + latestUserMessageId: options?.latestUserMessageId ?? null, latestRunId: latestRun?.runId ?? null, latestRunRequestedAt: latestRun?.requestedAt ?? null, latestRunStartedAt: latestRun?.startedAt ?? null, @@ -394,6 +396,7 @@ export function hasServerAcknowledgedLocalDispatch(input: { localDispatch: LocalDispatchSnapshot | null; phase: SessionPhase; latestRun: Thread["latestRun"] | null; + latestUserMessageId?: ChatMessage["id"] | null; runtime: Thread["runtime"] | null; hasPendingApproval: boolean; hasPendingUserInput: boolean; @@ -408,6 +411,8 @@ export function hasServerAcknowledgedLocalDispatch(input: { const latestRun = input.latestRun ?? null; const runtime = input.runtime ?? null; + const latestUserMessageChanged = + input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null); const latestRunChanged = input.localDispatch.latestRunId !== (latestRun?.runId ?? null) || input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) || @@ -415,6 +420,9 @@ export function hasServerAcknowledgedLocalDispatch(input: { input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null); if (input.phase === "running") { + if (latestUserMessageChanged) { + return true; + } if (!latestRunChanged) { return false; } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 8b1d2c672b..23cfef5e7f 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -56,6 +56,7 @@ import { useRef, useState, } from "react"; +import { flushSync } from "react-dom"; import { useNavigate } from "@tanstack/react-router"; import { useShallow } from "zustand/react/shallow"; import { @@ -152,6 +153,7 @@ import { stackedThreadToast, toastManager } from "./ui/toast"; import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings"; import { type NewProjectScriptInput } from "./ProjectScriptsControl"; import { + buildProjectScript, commandForProjectScript, nextProjectScriptId, projectScriptIdFromCommand, @@ -211,6 +213,7 @@ import { } from "../state/entities"; import { environmentShell } from "../state/shell"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; +import { DraftHeroHeadline } from "./chat/DraftHeroHeadline"; import { ExpandedImageDialog } from "./chat/ExpandedImageDialog"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; import { MessagesTimeline } from "./chat/MessagesTimeline"; @@ -229,6 +232,14 @@ import { resolveEffectiveEnvMode } from "./BranchToolbar.logic"; import { ProviderStatusBanner } from "./chat/ProviderStatusBanner"; import { ThreadErrorBanner } from "./chat/ThreadErrorBanner"; import { QueuedRunsControl } from "./chat/QueuedRunsControl"; +import { + DRAFT_HERO_TRANSITION_ANIMATION_ID, + DRAFT_HERO_TRANSITION_DURATION_MS, + DRAFT_HERO_TRANSITION_EASING, + MOBILE_COMPOSER_VIEW_TRANSITION_NAME, + MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME, + runMobileComposerTransition, +} from "./chat/draftHeroTransition"; import type { ComposerDispatchMode } from "./chat/composerDispatch"; import { MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, @@ -272,6 +283,70 @@ const EMPTY_PROVIDERS: ServerProvider[] = []; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; const EMPTY_ATTACHMENT_IDS: string[] = []; const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; + +function useDraftHeroLayoutTransition(isDraftHeroState: boolean) { + const transitionGroupRef = useRef(null); + const composerAnchorRef = useRef(null); + const previousStateRef = useRef(isDraftHeroState); + const previousComposerRectRef = useRef(null); + const animationRef = useRef(null); + + const captureComposerRect = () => { + previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null; + }; + + useLayoutEffect(() => { + const transitionGroup = transitionGroupRef.current; + const nextComposerRect = composerAnchorRef.current?.getBoundingClientRect() ?? null; + const stateChanged = previousStateRef.current !== isDraftHeroState; + const prefersReducedMotion = + typeof window !== "undefined" && + window.matchMedia?.("(prefers-reduced-motion: reduce)").matches; + const mobileComposerTransitionActive = + typeof document !== "undefined" && + document.documentElement.dataset.mobileComposerRouteTransition === "true"; + + animationRef.current?.cancel(); + animationRef.current = null; + const previousComposerRect = previousComposerRectRef.current; + if ( + stateChanged && + !prefersReducedMotion && + !mobileComposerTransitionActive && + transitionGroup && + previousComposerRect && + nextComposerRect && + typeof transitionGroup.animate === "function" + ) { + const translateX = previousComposerRect.left - nextComposerRect.left; + const translateY = previousComposerRect.top - nextComposerRect.top; + if (Math.abs(translateX) >= 0.5 || Math.abs(translateY) >= 0.5) { + const animation = transitionGroup.animate( + [ + { transform: `translate3d(${translateX}px, ${translateY}px, 0)` }, + { transform: "translate3d(0, 0, 0)" }, + ], + { + duration: DRAFT_HERO_TRANSITION_DURATION_MS, + easing: DRAFT_HERO_TRANSITION_EASING, + }, + ); + animation.id = DRAFT_HERO_TRANSITION_ANIMATION_ID; + animationRef.current = animation; + void animation.finished + .catch(() => undefined) + .then(() => { + if (animationRef.current === animation) animationRef.current = null; + }); + } + } + previousStateRef.current = isDraftHeroState; + previousComposerRectRef.current = nextComposerRect; + }, [isDraftHeroState]); + + return { transitionGroupRef, composerAnchorRef, captureComposerRect } as const; +} + const PreviewPanel = lazy(() => import("./preview/PreviewPanel").then((module) => ({ default: module.PreviewPanel })), ); @@ -358,6 +433,7 @@ type ChatViewProps = threadId: ThreadId; onDiffPanelOpen?: () => void; reserveTitleBarControlInset?: boolean; + forceExpandedMobileComposer?: boolean; routeKind: "server"; draftId?: never; } @@ -366,6 +442,7 @@ type ChatViewProps = threadId: ThreadId; onDiffPanelOpen?: () => void; reserveTitleBarControlInset?: boolean; + forceExpandedMobileComposer?: boolean; routeKind: "draft"; draftId: DraftId; }; @@ -381,6 +458,7 @@ type PersistentTerminalLaunchContext = Pick new Set(serverProjection?.messages.map((message) => message.id) ?? []), [serverProjection], ); const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); - const activeThreadLastVisitedAt = useUiStateStore((store) => - routeKind === "server" ? store.threadLastVisitedAtById[routeThreadKey] : undefined, + const activeThreadLastVisitedAt = useUiStateStore( + (store) => store.threadLastVisitedAtById[routeThreadKey], ); const settings = useEnvironmentSettings(environmentId); const setStickyComposerModelSelection = useComposerDraftStore( @@ -1136,10 +1224,10 @@ function ChatViewContent(props: ChatViewProps) { const optimisticUserMessagesRef = useRef(optimisticUserMessages); optimisticUserMessagesRef.current = optimisticUserMessages; const [localDraftErrorsByDraftId, setLocalDraftErrorsByDraftId] = useState< - Record + Record >({}); const [localServerErrorsByThreadKey, setLocalServerErrorsByThreadKey] = useState< - Record + Record >({}); const [isConnecting, _setIsConnecting] = useState(false); const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false); @@ -1254,11 +1342,45 @@ function ChatViewContent(props: ChatViewProps) { ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) : null; const fallbackDraftProject = useProject(fallbackDraftProjectRef); - const localDraftError = - routeKind === "server" && serverThread - ? null - : ((draftId ? localDraftErrorsByDraftId[draftId] : null) ?? null); - const localServerError = localServerErrorsByThreadKey[routeThreadKey] ?? null; + const localDraftError = serverThread + ? null + : ((draftId ? localDraftErrorsByDraftId[draftId]?.message : null) ?? null); + const localServerError = localServerErrorsByThreadKey[routeThreadKey]?.message ?? null; + // Draft errors are keyed by draftId while server errors are keyed by thread + // key, so a pending draft entry must migrate when the server thread loads or + // a failed send would silently disappear on promotion. When both keys hold + // an entry, the most recent write wins. + useEffect(() => { + if (!serverThread || !draftId) { + return; + } + const pendingDraftEntry = localDraftErrorsByDraftId[draftId]; + if (pendingDraftEntry === undefined) { + return; + } + setLocalDraftErrorsByDraftId((existing) => { + if (existing[draftId] === undefined) { + return existing; + } + const next = { ...existing }; + delete next[draftId]; + return next; + }); + setLocalServerErrorsByThreadKey((existing) => { + const currentEntry = existing[routeThreadKey]; + if ( + currentEntry !== undefined && + (currentEntry.at > pendingDraftEntry.at || + currentEntry.message === pendingDraftEntry.message) + ) { + return existing; + } + return { + ...existing, + [routeThreadKey]: pendingDraftEntry, + }; + }); + }, [draftId, localDraftErrorsByDraftId, routeThreadKey, serverThread]); const localDraftThread = useMemo( () => draftThread @@ -1273,7 +1395,7 @@ function ChatViewContent(props: ChatViewProps) { : undefined, [draftThread, fallbackDraftProject?.defaultModelSelection, threadId], ); - const isServerThread = routeKind === "server" && serverThread !== null; + const isServerThread = serverThread !== null; const activeThread = isServerThread ? serverThread : localDraftThread; const serverLatestRun = useMemo( () => (serverProjection === null ? null : deriveLatestThreadRun(serverProjection)), @@ -1842,6 +1964,8 @@ function ChatViewContent(props: ChatViewProps) { } = useLocalDispatchState({ activeThread, activeLatestRun, + latestUserMessageId: + serverProjection?.messages.findLast((message) => message.role === "user")?.id ?? null, phase, activePendingApproval: activePendingApproval?.requestId ?? null, activePendingUserInput: activePendingUserInput?.requestId ?? null, @@ -2081,6 +2205,13 @@ function ChatViewContent(props: ChatViewProps) { [optimisticUserMessages], ); const timelineEntries = isServerThread ? serverTimelineEntries : draftTimelineEntries; + const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState(null); + const draftHeroDockRequested = + activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey; + const isDraftHeroState = + isLocalDraftThread && timelineEntries.length === 0 && !isWorking && !draftHeroDockRequested; + const draftHeroTransition = useDraftHeroLayoutTransition(isDraftHeroState); + const captureDraftHeroComposerRect = draftHeroTransition.captureComposerRect; const { turnDiffSummaries } = useTurnDiffSummaries(serverProjection); const turnDiffSummaryByAssistantMessageId = useMemo(() => { const byMessageId = new Map(); @@ -2105,12 +2236,13 @@ function ChatViewContent(props: ChatViewProps) { worktreePath: activeThread?.worktreePath ?? null, }) : null; + const gitStatusCwd = activeThread?.worktreePath ?? gitCwd; const gitStatusQuery = useEnvironmentQuery( - gitCwd === null + gitStatusCwd === null ? null : vcsEnvironment.status({ environmentId, - input: { cwd: gitCwd }, + input: { cwd: gitStatusCwd }, }), ); const keybindings = useAtomValue(primaryServerKeybindingsAtom); @@ -2156,6 +2288,9 @@ function ChatViewContent(props: ChatViewProps) { terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null; // Default true while loading to avoid toolbar flicker. const isGitRepo = gitStatusQuery.data?.isRepo ?? true; + const initialDiffPanelGitScope = + gitStatusQuery.data?.hasWorkingTreeChanges === true ? "unstaged" : "branch"; + const diffPanelGitStatusResolutionKey = gitStatusQuery.data ? "resolved" : "pending"; const terminalShortcutLabelOptions = useMemo( () => ({ context: { @@ -2227,6 +2362,7 @@ function ChatViewContent(props: ChatViewProps) { (targetThreadId: ThreadId | null, error: string | null) => { if (!targetThreadId) return; const nextError = sanitizeThreadErrorMessage(error); + const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() }; if ( serverThread && targetThreadId === routeThreadRef.threadId && @@ -2234,24 +2370,24 @@ function ChatViewContent(props: ChatViewProps) { serverThread.id === targetThreadId ) { setLocalServerErrorsByThreadKey((existing) => { - if ((existing[routeThreadKey] ?? null) === nextError) { + if ((existing[routeThreadKey]?.message ?? null) === nextError) { return existing; } return { ...existing, - [routeThreadKey]: nextError, + [routeThreadKey]: nextEntry, }; }); return; } const localDraftErrorKey = draftId ?? targetThreadId; setLocalDraftErrorsByDraftId((existing) => { - if ((existing[localDraftErrorKey] ?? null) === nextError) { + if ((existing[localDraftErrorKey]?.message ?? null) === nextError) { return existing; } return { ...existing, - [localDraftErrorKey]: nextError, + [localDraftErrorKey]: nextEntry, }; }); }, @@ -2604,13 +2740,7 @@ function ChatViewContent(props: ChatViewProps) { input.name, activeProject.scripts.map((script) => script.id), ); - const nextScript: ProjectScript = { - id: nextId, - name: input.name, - command: input.command, - icon: input.icon, - runOnWorktreeCreate: input.runOnWorktreeCreate, - }; + const nextScript = buildProjectScript(nextId, input); const nextScripts = input.runOnWorktreeCreate ? [ ...activeProject.scripts.map((script) => @@ -2644,13 +2774,7 @@ function ChatViewContent(props: ChatViewProps) { return AsyncResult.failure(Cause.fail(new Error("Script not found."))); } - const updatedScript: ProjectScript = { - ...existingScript, - name: input.name, - command: input.command, - icon: input.icon, - runOnWorktreeCreate: input.runOnWorktreeCreate, - }; + const updatedScript = buildProjectScript(existingScript.id, input); const nextScripts = activeProject.scripts.map((script) => script.id === scriptId ? updatedScript @@ -2772,9 +2896,19 @@ function ChatViewContent(props: ChatViewProps) { }, [activeThreadRef, openPreview]); const addDiffSurface = useCallback(() => { if (!activeThreadRef || !isServerThread || !isGitRepo) return; + if (planSidebarOpen) { + dismissPlanSidebarForCurrentTurn(); + } useRightPanelStore.getState().open(activeThreadRef, "diff"); onDiffPanelOpen?.(); - }, [activeThreadRef, isGitRepo, isServerThread, onDiffPanelOpen]); + }, [ + activeThreadRef, + dismissPlanSidebarForCurrentTurn, + isGitRepo, + isServerThread, + onDiffPanelOpen, + planSidebarOpen, + ]); const openChangesFromThreadPanel = useCallback(() => { addDiffSurface(); }, [addDiffSurface]); @@ -4106,7 +4240,16 @@ function ChatViewContent(props: ChatViewProps) { } return; } - if (!activeProject) return; + if (!activeProject) { + toastManager.add( + stackedThreadToast({ + type: "warning", + title: "Choose a project first", + description: "This draft no longer points to an available project.", + }), + ); + return; + } const threadIdForSend = activeThread.id; const isFirstMessage = !isServerThread || activeMessageCount === 0; const baseBranchForWorktree = @@ -4124,6 +4267,21 @@ function ChatViewContent(props: ChatViewProps) { } sendInFlightRef.current = true; + if (isDraftHeroState && activeThreadKey) { + let resolveDockStarted: (() => void) | undefined; + const dockStarted = new Promise((resolve) => { + resolveDockStarted = resolve; + }); + const dockTransition = runMobileComposerTransition(() => { + flushSync(() => { + captureDraftHeroComposerRect(); + setDockedDraftHeroThreadKey(activeThreadKey); + }); + resolveDockStarted?.(); + }); + void dockTransition.catch(() => resolveDockStarted?.()); + await dockStarted; + } beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) }); const composerImagesSnapshot = [...composerImages]; @@ -4383,6 +4541,9 @@ function ChatViewContent(props: ChatViewProps) { } sendInFlightRef.current = false; if (!turnStartSucceeded) { + setDockedDraftHeroThreadKey((currentThreadKey) => + currentThreadKey === activeThreadKey ? null : currentThreadKey, + ); resetLocalDispatch(); } }; @@ -5094,7 +5255,12 @@ function ChatViewContent(props: ChatViewProps) { /> ) : activeRightPanelSurface?.kind === "diff" ? ( - + ) : activeRightPanelSurface?.kind === "plan" ? ( {/* scroll to end pill — shown when user has scrolled away from the live edge */} @@ -5346,29 +5513,62 @@ function ChatViewContent(props: ChatViewProps) { )} - {/* Input bar */} + {/* Input bar — centered for an empty draft, docked after sending. */}
-