Compare commits

..
Author SHA1 Message Date
Cursor Agent 1cc9019479 fix: skip idle terminal.onEvent subscription and release pruned terminal buffers
- connection.ts: Only subscribe to client.terminal.onEvent when
  applyTerminalEvent handler is provided. No production caller passes
  this handler, so the subscription was a no-op wasting WebSocket traffic.

- terminalSessionState.ts: Reset buffer atoms to EMPTY_TERMINAL_BUFFER_STATE
  when metadata snapshot pruning removes terminals no longer reported by
  the server. Releases up to 512KB of retained string data per pruned
  terminal session on long-running clients.
2026-05-22 02:39:23 +00:00
Julius Marminge 4db082a2d2 Unify mobile new-task and project sheet headers
- Extract shared new-task sheet header
- Refresh add-project form spacing and controls
- Align project creation screens with the new sheet layout
2026-05-21 19:18:55 -07:00
Julius Marminge 907f4d7501 Add mobile project onboarding flow
- Add new project screens for local folders and remote repositories
- Support source-control provider lookup, clone destination selection, and folder browsing
- Extract shared add-project path helpers and add coverage for the new runtime logic
2026-05-21 18:30:24 -07:00
Julius Marminge 1e929ad74f Handle intentional WS closes and heartbeat freshness
- Ignore intentional close events during transport disposal
- Track heartbeat freshness from pong traffic and reset on reconnect
- Propagate request lifecycle hooks through the RPC client
2026-05-20 15:10:41 +02:00
Julius Marmingeandcodex 3ee6fbba2c Fix CI regressions after branch sync
Co-authored-by: codex <[email protected]>
2026-05-20 13:48:49 +02:00
Julius Marmingeandcodex 6b48288f77 Sync mobile remote branch with main
Co-authored-by: codex <[email protected]>
2026-05-20 13:17:57 +02:00
Julius Marminge 2632c9251e Refine mobile environment connection flows
- Rename backends to environments across mobile UI
- Add richer loading and empty states for connections, home, and new task flows
- Improve review section loading handling and terminal keyboard layout
2026-05-20 11:06:48 +02:00
Julius Marminge 89672b3d89 Refactor mobile ordering and catalog assembly
- Replace ad hoc sorts with shared Effect order helpers
- Rework remote catalog and review/terminal lists for clearer data flow
- Keep threaded/review selection and diff adapters aligned with the new ordering logic
2026-05-20 11:05:43 +02:00
Julius Marminge 90fea7bb2f Refactor collection handling for mobile remote connect
- Replace chained array transforms with explicit loops across mobile and server paths
- Tighten provider, git, and orchestration parsing while preserving behavior
- Improve remote-connect UI data shaping and thread activity filtering
2026-05-20 11:05:37 +02:00
Julius Marminge 7793bd6de7 Normalize branch and model selection handling
- Deduplicate terminal IDs and favorite model slugs with trim-aware iteration
- Use effect-based filtering for local branch and built-in model lists
- Switch stable array handling to non-mutating `toSorted`
2026-05-20 11:05:37 +02:00
Julius Marminge 7f03f4d19a Harden remote connect and subscription handling
- Scope cleartext mobile config to development
- Fix stale loads, ordering, and terminal reuse
- Clean up terminal metadata subscriptions on failure
2026-05-20 11:05:37 +02:00
Julius Marmingeandcodex 4ac2618403 Fix browser VCS status test mocks
Co-authored-by: codex <[email protected]>
2026-05-20 11:05:37 +02:00
Julius Marminge e7b41d72a8 Rename git state to VCS and add diff preview caching
- Replace git-scoped client/runtime state with VCS-scoped APIs
- Add checkpoint diff preview state and reuse cached diffs
- Update mobile and web review flows to use the new shared state
2026-05-20 11:05:36 +02:00
Julius Marminge c87cc163f8 Refactor client runtime state refresh handling
- Move archived threads state into shared client-runtime
- Add stale-aware refresh/invalidation for path search, discovery, and VCS refs
- Wire provider invalidations through the web runtime
2026-05-20 11:05:15 +02:00
Julius Marminge 570cc46e51 Replace git react-query layer with vcsRefManager and source control acti
- Migrate branch selector and git actions to useVcsRefs and new source control action hooks
- Remove gitReactQuery and projectReactQuery modules in favor of sourceControlActions and vcsRefState
- Add staleTimeMs to mobile vcs ref manager configuration
2026-05-20 11:05:15 +02:00
Julius Marminge 8d65f131f0 Rename branch state to VCS refs
- Switch mobile and client-runtime state to the generic VcsRef API
- Preserve background refreshes with client change handling and errors
2026-05-20 11:05:07 +02:00
Julius Marminge fbd89d303c Handle truncated git review diff previews safely
- Drop unterminated paths from truncated NUL-separated git stdout
- Preserve truncation state when building untracked review diffs
2026-05-20 11:04:26 +02:00
Julius Marminge e793c07a21 Refactor mobile remote search and review state
- Move composer path search and source-control discovery into shared managed state
- Persist review async/loading state in atoms and add coverage
- Update mobile/web composers and review highlighter initialization
2026-05-20 11:03:29 +02:00
Julius Marmingeandcodex ab95f11360 Fix mobile native static check typecheck
Co-authored-by: codex <[email protected]>
2026-05-20 11:02:23 +02:00
Julius Marminge d950f45672 Refactor review sheet into focused native review hooks
- Split file visibility, diff data, and comment selection logic out of `ReviewSheet`
- Add tests for review file visibility and native diff bridge behavior
- Wire review selection and mobile remote connect state through shared hooks
2026-05-20 11:02:23 +02:00
Julius Marminge 594df47fb7 Restrict review diff preview to workspace roots
- Reject diff preview requests outside the configured workspace
- Add tests covering allowed and denied cwd paths
2026-05-20 11:02:13 +02:00
Yash Singh b487b0588c use custom react-native-nitro-markdown 2026-05-20 11:02:13 +02:00
Julius Marminge 3c9c14f6b3 rm 2026-05-20 11:02:13 +02:00
Julius Marminge 8916eeb042 Switch review preview timestamps to DateTimeUtc
- Emit Effect DateTime values from review and git diff previews
- Tighten the contract to require UTC datetime output
2026-05-20 11:02:13 +02:00
Julius Marminge 6db3098a21 Add remote review diff plumbing
- Move review diff parsing and highlighting into shared mobile diff modules
- Add review service and wire server, web, and mobile around remote review selection
2026-05-20 11:02:13 +02:00
Julius Marminge eba28035d2 Add inline review comment selection to mobile diffs
- render comment rows and line selection state in the native diff view
- wire long-press/tap gestures to start and complete review comments
- tighten shared diff utilities and add coverage
2026-05-20 10:55:55 +02:00
Julius Marmingeandcodex a49c2d1301 Fix saved environment runtime test mocks
Co-authored-by: codex <[email protected]>
2026-05-20 10:55:20 +02:00
Yash SinghandJulius Marminge 509a7a84cc feat: ios16 support (#2469)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-20 10:54:25 +02:00
Julius Marmingeandcodex 9aae833e45 Fix terminal attach session launch context
Co-authored-by: codex <[email protected]>
2026-05-20 10:54:13 +02:00
Julius Marmingeandcodex b305a44b9f Use branded ids in mobile runtime flows
Co-authored-by: codex <[email protected]>
2026-05-20 10:54:13 +02:00
Julius Marmingeandcodex 7a285d1172 Add mobile source control discovery runtime state
- Share source control discovery state across mobile environment lifecycles
- Resolve discovery clients through centralized mobile environment sessions
- Ignore stale in-flight discovery refreshes after invalidation or reset
- Mark pending web shell/thread-detail runtime migration points

Co-authored-by: codex <[email protected]>
2026-05-20 10:53:18 +02:00
Julius Marminge 37908166ed Add native mobile review diff rendering and static checks
- Add iOS review diff module, parser, and highlighter support
- Wire mobile native lint tooling into CI and local docs
- Include fixtures and tests for the new diff pipeline
2026-05-20 10:52:49 +02:00
Julius Marminge da56bd50d9 Add mobile review profiling and syntax highlight debug tools
- Add a debug diff scratch route with fixture-driven highlighting
- Wrap review screen in a shared highlighter provider
- Document profiling steps and add a Hermes profiling script
2026-05-20 10:52:49 +02:00
Julius Marminge e27b561b84 terminals 2026-05-20 10:52:49 +02:00
Julius Marminge df425a86ca Ignore fast mode updates for Opencode models
- Skip remote fast-mode selection changes when the current provider is `opencode`
- Keep existing model selection state unchanged for unsupported providers
2026-05-20 10:48:51 +02:00
Julius Marminge 2faef729a4 Extract WebSocket RPC client into shared runtime package
- Move ws RPC client and transport primitives into `@t3tools/client-runtime`
- Update web settings and environment code to use shared runtime types
- Keep reconnect and transport tests aligned with the new package boundary
2026-05-20 10:48:51 +02:00
Julius Marminge cca1bacc71 Refactor remote terminal session state handling
- Tighten environment/thread ID typing across mobile and shared state
- Track terminal metadata and subprocess status when attaching sessions
- Update launch and status flows for remote terminals
2026-05-20 10:44:52 +02:00
Julius Marminge f1ae412400 move some stuff around 2026-05-20 10:40:34 +02:00
Julius Marmingeandcodex ccac2d8228 Fix post-rebase mobile typecheck issues
Co-authored-by: codex <[email protected]>
2026-05-20 10:40:34 +02:00
Julius Marminge 58587923b4 Stage remote terminal launches and replay hydrated buffers
- Carry pending launch context into terminal open
- Delay buffer replay until surface hydration is stable
- Co-authored-by: codex <[email protected]>
2026-05-20 10:40:34 +02:00
Julius Marminge 343074470f Set mobile config scheme per app variant
- Use variant-specific Expo schemes for development, preview, and production
- Preserve the production `t3code` scheme while fixing remote-connect routing
2026-05-20 10:40:34 +02:00
Julius MarmingeandJulius Marminge 3c78384d43 feat(mobile): Add terminal powered by libghostty (#2056)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-20 10:40:34 +02:00
Julius Marminge dcf4d6d38e Improve mobile review diff rendering
- Switch review screen to a virtualized list layout
- Queue diff highlighting and default to the JS engine
- Add word-diff helpers and tests
2026-05-20 10:40:27 +02:00
Julius Marminge 43d534ad67 shiki loading changes 2026-05-20 10:40:00 +02:00
Julius Marminge 4de9770810 get native highlighter setup properly 2026-05-20 10:39:45 +02:00
Julius Marmingeandcodex df4223bf7d Enhance mobile review comments with diff previews
- Add syntax-highlighted diff rendering and cached review state
- Support pasted/attached images in review comments
- Improve mobile review sheet handling for large or partial diffs

Co-authored-by: codex <[email protected]>
2026-05-20 10:39:33 +02:00
Julius Marmingeandcodex 14e56f8a09 Add T3 Code mobile app and shared remote runtime
Rebuild PR #2013 on top of current origin/main without the duplicated commit lineage.

Co-authored-by: codex <[email protected]>
2026-05-20 10:39:21 +02:00
t3-code[bot] d1e85c4e8f chore(release): prepare v0.0.24 2026-05-15 06:40:13 +00:00
Julius Marminge ea20e80021 Exclude workspace packages from desktop runtime deps (#2688) 2026-05-14 07:32:48 +00:00
Julius MarmingeandJulius Marminge 9e632f5cec [codex] add diagnostics resource history (#2685)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-14 09:14:32 +02:00
Julius Marminge 4120e94598 Back off VCS remote refresh failures (#2686) 2026-05-14 08:41:02 +02:00
Theo Browne 34bb18c8cf feat(marketing): Made marketing site less cringe (#2681) 2026-05-13 18:31:06 -07:00
Julius Marminge 90eea047a9 Skip healthy env reconnects after browser resume (#2677) 2026-05-13 22:29:36 +02:00
Julius Marminge f92e1e1b06 Simplify workspace package builds and deps (#2676) 2026-05-13 21:35:01 +02:00
Julius Marminge 556c42452c Harden GitHub workflow permissions
- Restrict release workflow defaults to read-only access
- Grant `id-token` only to the publish job
- Document safe handling for `pull_request_target` in PR size checks
2026-05-13 14:19:18 +02:00
Julius Marminge 7e20b23e7e Constrain provider update popover overflow (#2669) 2026-05-13 10:23:31 +02:00
206 changed files with 8654 additions and 2847 deletions

No files matched your search

+3
View File
@@ -124,6 +124,9 @@ jobs:
group: pr-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
steps:
# This pull_request_target job may fetch untrusted PR commits only as passive
# git data. Do not add dependency installs, build/test scripts, or cache
# actions here; use pull_request plus workflow_run for that pattern instead.
- name: Checkout base repository
uses: actions/checkout@v4
with:
+5 -2
View File
@@ -23,8 +23,8 @@ on:
type: string
permissions:
contents: write
id-token: write
contents: read
id-token: none
jobs:
check_changes:
@@ -420,6 +420,9 @@ jobs:
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
permissions:
contents: read
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v6
+1
View File
@@ -23,5 +23,6 @@ __screenshots__/
.tanstack
squashfs-root/
.vercel
.gstack/
dist-electron/
.electron-runtime/
+5 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.23",
"version": "0.0.24",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -16,6 +16,10 @@
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/ssh": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-updater": "^6.6.2"
@@ -23,13 +27,7 @@
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/ssh": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
@@ -3,7 +3,7 @@ import * as NodeOS from "node:os";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/client-runtime";
} from "@t3tools/shared/advertisedEndpoint";
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
@@ -1,4 +1,4 @@
import { createAdvertisedEndpoint } from "@t3tools/client-runtime";
import { createAdvertisedEndpoint } from "@t3tools/shared/advertisedEndpoint";
import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts";
import {
buildTailscaleHttpsBaseUrl,
+1 -1
View File
@@ -12,7 +12,7 @@ export default defineConfig([
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
noExternal: (id) => id.startsWith("@t3tools/"),
},
{
...shared,
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 244 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 358 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="257" preserveAspectRatio="xMidYMid" viewBox="0 0 256 257"><path fill="#D97757" d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"></path></svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

@@ -0,0 +1 @@
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>

After

Width:  |  Height:  |  Size: 649 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="260" preserveAspectRatio="xMidYMid" viewBox="0 0 256 260"><path fill="#fff" d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512"><svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="512" height="512" fill="#131010"></rect><path d="M320 224V352H192V224H320Z" fill="#5A5858"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M384 416H128V96H384V416ZM320 160H192V352H320V160Z" fill="white"></path></svg></svg>

After

Width:  |  Height:  |  Size: 464 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 652 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

@@ -0,0 +1,53 @@
---
interface Props {
class?: string;
idPrefix: string;
}
const { class: className, idPrefix } = Astro.props;
---
<svg
class={className}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 256 295"
aria-hidden="true"
>
<defs>
<linearGradient id={`${idPrefix}0`} x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}6`} x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}8`} x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%">
<stop offset="0%" stop-color="#FFF" stop-opacity=".8" />
<stop offset="100%" stop-color="#FFF" stop-opacity="0" />
</linearGradient>
<linearGradient id={`${idPrefix}c`} x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}e`} x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}i`} x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
</defs>
<g fill="none">
<path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905" />
<path fill={`url(#${idPrefix}6)`} d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903" />
<path fill={`url(#${idPrefix}8)`} d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293" />
<path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z" />
<path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z" />
<path fill={`url(#${idPrefix}c)`} stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)" />
<path fill={`url(#${idPrefix}e)`} stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)" />
<path fill={`url(#${idPrefix}i)`} stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)" />
<path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255" />
</g>
</svg>
+254 -72
View File
@@ -6,7 +6,7 @@ interface Props {
const {
title = "T3 Code",
description = "T3 Code — The best way to code with AI.",
description = "T3 Code — The open-source control plane for coding agents.",
} = Astro.props;
---
@@ -18,7 +18,7 @@ const {
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&family=JetBrains+Mono:wght@400;500&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
@@ -30,18 +30,25 @@ const {
<body>
<div class="page">
<nav class="nav">
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
<div class="nav-inner">
<a href="/" class="nav-brand" aria-label="T3 Code home">
<span class="nav-brand-name">T3 Code</span>
</a>
<div class="nav-right">
<a
class="nav-gh"
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
</svg>
<span>GitHub</span>
</a>
<a class="btn btn-primary" href="/#download">Download</a>
</div>
</div>
</nav>
<main class="main">
@@ -49,23 +56,54 @@ const {
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<div class="footer-inner">
<div class="footer-brand">
<img src="/icon.webp" alt="" />
<span>&copy; {new Date().getFullYear()} T3 Tools Inc · MIT licensed</span>
</div>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
</div>
</div>
</footer>
</div>
<script>
const nav = document.querySelector(".nav");
const onScroll = () => {
if (!nav) return;
if (window.scrollY > 12) nav.classList.add("is-scrolled");
else nav.classList.remove("is-scrolled");
};
window.addEventListener("scroll", onScroll, { passive: true });
onScroll();
</script>
</body>
</html>
<style is:global>
:root {
--bg: #09090b;
--bg-elev: #0c0c0e;
--bg-card: #111113;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--fg-faint: #52525b;
--border: rgba(255, 255, 255, 0.08);
--border-strong: rgba(255, 255, 255, 0.14);
--accent-h: 250;
--accent: oklch(0.68 0.17 var(--accent-h));
--accent-dim: oklch(0.68 0.17 var(--accent-h) / 0.15);
--ok: oklch(0.72 0.16 150);
--warn: oklch(0.76 0.15 75);
--font-sans: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
--font-mono: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, monospace;
--radius: 12px;
--radius-sm: 8px;
--radius-lg: 16px;
}
* {
@@ -76,16 +114,19 @@ const {
html {
color-scheme: dark;
scroll-behavior: smooth;
}
body {
background: var(--bg);
color: var(--fg);
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
font-family: var(--font-sans);
font-feature-settings: "ss01", "ss02";
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
line-height: 1.5;
}
body::after {
@@ -105,11 +146,103 @@ const {
text-decoration: none;
}
img {
button {
font-family: inherit;
cursor: pointer;
border: 0;
background: none;
color: inherit;
}
img,
svg {
display: block;
max-width: 100%;
}
.eyebrow {
font-family: var(--font-mono);
font-size: 11px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--fg-dim);
font-weight: 500;
}
.display {
font-weight: 500;
letter-spacing: -0.035em;
line-height: 1.05;
}
.container {
width: 100%;
max-width: 1240px;
margin: 0 auto;
padding: 0 32px;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
font-weight: 500;
font-size: 14px;
padding: 10px 18px;
border-radius: 8px;
transition: transform 0.18s ease, background 0.18s ease,
border-color 0.18s ease, color 0.18s ease;
white-space: nowrap;
}
.btn-primary {
background: var(--fg);
color: #09090b;
font-weight: 600;
}
.btn-primary:hover {
transform: translateY(-1px);
background: #fff;
}
.btn-primary:active {
transform: translateY(0);
}
.btn-ghost {
color: var(--fg-muted);
border: 1px solid var(--border);
background: transparent;
}
.btn-ghost:hover {
color: var(--fg);
border-color: var(--border-strong);
background: rgba(255, 255, 255, 0.02);
}
.btn-lg {
padding: 14px 22px;
font-size: 15px;
border-radius: 10px;
}
.tile {
position: relative;
border: 1px solid var(--border);
border-radius: var(--radius);
background: linear-gradient(180deg, rgba(255, 255, 255, 0.015), rgba(255, 255, 255, 0));
overflow: hidden;
}
:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: 4px;
}
@keyframes fade-in {
from {
opacity: 0;
@@ -120,11 +253,26 @@ const {
transform: translateY(0);
}
}
@keyframes pulse {
50% { opacity: 0.4; }
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@keyframes floatDrift {
0%, 100% { translate: 0 0; }
50% { translate: 0 -10px; }
}
@keyframes blink {
50% { opacity: 0; }
}
</style>
<style>
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
@@ -132,97 +280,131 @@ const {
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
position: sticky;
top: 0;
z-index: 50;
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
background: color-mix(in srgb, var(--bg) 75%, transparent);
border-bottom: 1px solid transparent;
transition: border-color 0.3s ease;
}
.nav.is-scrolled {
border-bottom-color: var(--border);
}
.nav-inner {
max-width: 1240px;
margin: 0 auto;
padding: 12px 32px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
gap: 24px;
}
.nav-brand {
display: flex;
display: inline-flex;
align-items: center;
}
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-github {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--fg-muted);
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-github:hover {
color: var(--fg);
transition: color 0.2s ease;
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
.nav-brand:hover {
color: #fff;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
.nav-brand-name {
font-size: 16px;
font-weight: 650;
letter-spacing: -0.025em;
line-height: 1;
}
/* ── Main content ── */
.nav-right {
display: inline-flex;
align-items: center;
gap: 8px;
}
.nav-gh {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 12px;
border: 1px solid var(--border);
border-radius: 8px;
color: var(--fg-muted);
font-family: var(--font-mono);
font-size: 12px;
transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease;
}
.nav-gh:hover {
color: var(--fg);
background: rgba(255, 255, 255, 0.04);
border-color: var(--border-strong);
}
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
/* ── Footer ── */
.footer {
margin-top: auto;
border-top: 1px solid var(--border);
padding: 40px 0 32px;
}
.footer-inner {
max-width: 1240px;
margin: 0 auto;
padding: 0 32px;
display: flex;
flex-wrap: wrap;
gap: 24px;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
}
.footer-brand {
display: flex;
align-items: center;
gap: 10px;
font-size: 13px;
color: var(--fg-dim);
}
.footer-brand img {
width: 20px;
height: 20px;
border-radius: 4px;
}
.footer-links {
display: flex;
gap: 1.25rem;
gap: 20px;
}
.footer-links a {
font-size: 13px;
color: var(--fg-dim);
transition: color 0.3s ease;
transition: color 0.2s ease;
}
.footer-links a:hover {
color: var(--fg);
}
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem;
}
.footer {
padding: 1.25rem;
@media (max-width: 820px) {
.nav-inner,
.footer-inner {
padding-left: 20px;
padding-right: 20px;
}
}
</style>
+123
View File
@@ -0,0 +1,123 @@
export type Tweet = {
handle: string;
content: string;
excerpt?: string;
link: string;
};
export const tweets = [
{
handle: "Shay_Benshabtay",
content:
"T3 code is not perfect, but it's damn good. Open and fun , I can make my own fork for my uses and use the great tooling with my own needs.",
link: "https://x.com/Shay_Benshabtay/status/2054668503857156326",
},
{
handle: "teja2495",
content:
"I’ve completely switched to T3 Code for all my workflows. I just switch between different subscriptions and harnesses depending on what I need.",
excerpt: "I’ve completely switched to T3 Code for all my workflows.",
link: "https://x.com/teja2495/status/2052420254991581623",
},
{
handle: "developedbyed",
content: "might say alpha but T3 code is pretty awesome, really fast too",
link: "https://x.com/developedbyed/status/2030627970532921605",
},
{
handle: "tannerlinsley",
content:
"The minute T3 Code supports Claude Code, it could potentially become my daily driver. There's something special there.",
link: "https://x.com/tannerlinsley/status/2031102771529920966",
},
{
handle: "aronprins",
content:
"I already loved T3 Code by @theo and @jullerino, but their Connections implementation is next level epic and for this they should both earn maximum repect 🔥🫡",
excerpt: "I already loved T3 Code, but their Connections implementation is next level epic.",
link: "https://x.com/aronprins/status/2045102518196183109",
},
{
handle: "BennettBuhner",
content:
"T3 Code is literally Codex but better; all your favorite models and harnesses, accessible anywhere! The app is great but the website is even greater, so instead of needing to SSH into a machine, T3 IS my SSH!",
excerpt:
"T3 Code is literally Codex but better; all your favorite models and harnesses, accessible anywhere.",
link: "https://x.com/BennettBuhner/status/2054667115697754387",
},
{
handle: "ex0t1clol",
content: "T3 Code is proof electron apps don't have to suck",
link: "https://x.com/ex0t1clol/status/2054666870008021197",
},
{
handle: "Josikinz",
content:
"T3 code is better because it’s like if the codex Mac app didn’t make my computer run like shit 😋",
link: "https://x.com/Josikinz/status/2030367951694745870",
},
{
handle: "jetpackjoe_",
content: "T3 code is pretty alright I guess",
link: "https://x.com/jetpackjoe_/status/2054666792933404959",
},
{
handle: "mil000",
content: "T3 code saved my relationship!",
link: "https://x.com/mil000/status/2030120041451246071",
},
{
handle: "_winter_wonders",
content: "Heartbreaking: AI-hater has to admit T3 Code is really good.",
link: "https://x.com/_winter_wonders/status/2052350198764970434",
},
{
handle: "kostyniuk00",
content:
"I was not expecting a year ago, that my anti-AI colleagues would thank me a year later, for persuading them to try T3 Code Beta, that really helped them with organizing their workflows. \n\nFantastic product by @jullerino and @theo. Go try it out if you haven’t yet!",
excerpt:
"My anti-AI colleagues thanked me for persuading them to try T3 Code Beta. Fantastic product.",
link: "https://x.com/kostyniuk00/status/2052041388179468521",
},
{
handle: "gnukeith",
content:
"I tried T3 Code it actually fixed issues that Opus couldn’t solve in Claude Code + Theo has replied with “UwU” under my post. Dario has not.",
link: "https://x.com/gnukeith/status/2054670073579630730",
},
{
handle: "peculiarnewbie",
content: "T3 Code is iOS and other harnesses are androids",
link: "https://x.com/peculiarnewbie/status/2054671685027233827",
},
{
handle: "leodev",
content:
"T3 Code is probably the first coding gui that didn't suck performance wise and had a smart team behind it.",
link: "https://x.com/leodev/status/2054679746353537042",
},
{
handle: "pocarles",
content:
"Only using Codex and T3 now.\n\nI thought all AI coding harnesses had roughly the same impact. Using T3 Code taught me how wrong I was. The interface between you and the model changes everything.",
excerpt:
"Using T3 Code taught me how wrong I was. The interface between you and the model changes everything.",
link: "https://x.com/pocarles/status/2054673964274758046",
},
{
handle: "DavidKPiano",
content: "It's like Claude Code if they didn't vibe-code the entire thing",
link: "https://x.com/DavidKPiano/status/2054682983504719930",
},
{
handle: "iamkaffe",
content: "T3Code was the first one to truly care about Linux users.",
link: "https://x.com/iamkaffe/status/2054675539311411280",
},
{
handle: "uwunetes",
content:
"claude code make me go *whine whine whine* and t3 code make me go woof woof awooooo!!!",
link: "https://x.com/uwunetes/status/2054683356022120640",
},
] satisfies Tweet[];
+8 -2
View File
@@ -4,6 +4,7 @@ import { RELEASES_URL } from "../lib/releases";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
<div class="download-page">
<h1 class="heading">Download T3 Code</h1>
<p class="subheading">
<span id="version-label">Loading latest release&hellip;</span>
@@ -64,6 +65,7 @@ import { RELEASES_URL } from "../lib/releases";
GitHub releases page<span aria-hidden="true"> &#8599;</span>
</a>
</p>
</div>
</Layout>
<script>
@@ -111,7 +113,11 @@ import { RELEASES_URL } from "../lib/releases";
</script>
<style>
.main {
.download-page {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding: 8vh 1.5rem 4rem;
}
@@ -257,7 +263,7 @@ import { RELEASES_URL } from "../lib/releases";
/* ── Mobile ── */
@media (max-width: 640px) {
.main {
.download-page {
padding: 5vh 1.25rem 4rem;
}
File diff suppressed because it is too large. Load diff
+19
View File
@@ -0,0 +1,19 @@
https://x.com/Shay_Benshabtay/status/2054668503857156326
https://x.com/teja2495/status/2052420254991581623
https://x.com/developedbyed/status/2030627970532921605
https://x.com/tannerlinsley/status/2031102771529920966
https://x.com/aronprins/status/2045102518196183109
https://x.com/BennettBuhner/status/2054667115697754387
https://x.com/ex0t1clol/status/2054666870008021197
https://x.com/Josikinz/status/2030367951694745870
https://x.com/jetpackjoe_/status/2054666792933404959
https://x.com/mil000/status/2030120041451246071
https://x.com/_winter_wonders/status/2052350198764970434
https://x.com/kostyniuk00/status/2052041388179468521
https://x.com/gnukeith/status/2054670073579630730
https://x.com/peculiarnewbie/status/2054671685027233827
https://x.com/leodev/status/2054679746353537042
https://x.com/pocarles/status/2054673964274758046
https://x.com/DavidKPiano/status/2054682983504719930
https://x.com/iamkaffe/status/2054675539311411280
https://x.com/uwunetes/status/2054683356022120640
@@ -824,12 +824,9 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
var nextOffsets: [CGFloat] = []
var nextFileHeaderRowIndices: [Int] = []
nextOffsets.reserveCapacity(rows.count)
var maxTextWidthsByFileId: [String: CGFloat] = [:]
var maxColumnCountsByFileId: [String: Int] = [:]
var offset: CGFloat = 0
let font = codeFont
let measureAttrs: [NSAttributedString.Key: Any] = [.font: font, .ligature: 0]
for (index, row) in rows.enumerated() {
nextOffsets.append(offset)
if row.kind == "file" {
@@ -840,24 +837,24 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
let fileId = resolvedFileId(for: row)
switch row.kind {
case "line":
if let content = row.content {
let width = ceil((content as NSString).size(withAttributes: measureAttrs).width)
maxTextWidthsByFileId[fileId] = max(maxTextWidthsByFileId[fileId] ?? 0, width)
}
maxColumnCountsByFileId[fileId] = max(
maxColumnCountsByFileId[fileId] ?? 0,
row.content?.count ?? 0
)
case "hunk":
if let text = row.text {
let width = ceil((text as NSString).size(withAttributes: measureAttrs).width)
maxTextWidthsByFileId[fileId] = max(maxTextWidthsByFileId[fileId] ?? 0, width)
}
maxColumnCountsByFileId[fileId] = max(
maxColumnCountsByFileId[fileId] ?? 0,
row.text?.count ?? 0
)
default:
continue
}
}
let characterWidth = monospaceCharacterWidth(font: font)
let characterWidth = monospaceCharacterWidth(font: codeFont)
codeCharacterWidth = characterWidth
contentWidthsByFileId = maxTextWidthsByFileId.mapValues { maxTextWidth in
let measuredWidth = maxTextWidth + style.codePadding * 2
contentWidthsByFileId = maxColumnCountsByFileId.mapValues { maxColumnCount in
let measuredWidth = ceil(CGFloat(maxColumnCount) * characterWidth) + style.codePadding * 2
return max(0, min(style.contentWidth, measuredWidth))
}
rowOffsets = nextOffsets
@@ -2019,24 +2016,13 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
let highlightY = rowRect.midY - highlightHeight / 2
fillColor.setFill()
let nsContent = (row.content ?? "") as NSString
let measureAttrs: [NSAttributedString.Key: Any] = [.font: codeFont, .ligature: 0]
for range in ranges {
guard range.end > range.start else {
continue
}
let clampedStart = min(range.start, nsContent.length)
let clampedEnd = min(range.end, nsContent.length)
let prefixWidth = clampedStart > 0
? nsContent.substring(to: clampedStart).size(withAttributes: measureAttrs).width
: 0
let rangeTextWidth = clampedEnd > clampedStart
? nsContent.substring(with: NSRange(location: clampedStart, length: clampedEnd - clampedStart))
.size(withAttributes: measureAttrs).width
: 0
let startX = codeStartX - horizontalOffset + prefixWidth
let width = max(2, rangeTextWidth)
let startX = codeStartX - horizontalOffset + CGFloat(range.start) * codeCharacterWidth
let width = max(2, CGFloat(range.end - range.start) * codeCharacterWidth)
let highlightRect = CGRect(
x: startX,
y: highlightY,
+3 -3
View File
@@ -33,7 +33,7 @@ export default function ConnectionsRouteScreen() {
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: "Backends",
title: "Environments",
headerRight: () => (
<Link href="/connections/new" asChild>
<Pressable className="h-10 w-10 items-center justify-center rounded-full bg-primary active:opacity-70">
@@ -53,10 +53,10 @@ export default function ConnectionsRouteScreen() {
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 16,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
{hasEnvironments ? (
@@ -92,7 +92,7 @@ export default function ConnectionsRouteScreen() {
/>
</View>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
No backends connected yet.{"\n"}Tap{" "}
No environments connected yet.{"\n"}Tap{" "}
<Text className="font-t3-bold text-foreground">+</Text> to add one.
</Text>
</View>
+12 -13
View File
@@ -16,11 +16,10 @@ import { buildPairingUrl, parsePairingUrl } from "../../features/connection/pair
export default function ConnectionsNewRouteScreen() {
const {
connectionError,
connectionPairingUrl,
connectionState,
onChangeConnectionPairingUrl,
onConnectPress,
pairingConnectionError,
} = useRemoteConnections();
const router = useRouter();
const params = useLocalSearchParams<{ mode?: string }>();
@@ -35,8 +34,7 @@ export default function ConnectionsNewRouteScreen() {
const textColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled =
isSubmitting || connectionState === "connecting" || hostInput.trim().length === 0;
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
useEffect(() => {
const { host, code } = parsePairingUrl(connectionPairingUrl);
@@ -45,10 +43,10 @@ export default function ConnectionsNewRouteScreen() {
}, [connectionPairingUrl]);
useEffect(() => {
if (connectionError) {
if (pairingConnectionError) {
setIsSubmitting(false);
}
}, [connectionError]);
}, [pairingConnectionError]);
const handleHostChange = useCallback((value: string) => {
setHostInput(value);
@@ -72,7 +70,10 @@ export default function ConnectionsNewRouteScreen() {
return;
}
Alert.alert("Camera access needed", "Allow camera access to scan a backend pairing QR code.");
Alert.alert(
"Camera access needed",
"Allow camera access to scan an environment pairing QR code.",
);
}, [cameraPermission?.granted, requestCameraPermission]);
const closeScanner = useCallback(() => {
@@ -126,7 +127,7 @@ export default function ConnectionsNewRouteScreen() {
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: showScanner ? "Scan QR Code" : "Add Backend",
title: showScanner ? "Scan QR Code" : "Add Environment",
headerRight: () => (
<Pressable
className="h-10 w-10 items-center justify-center rounded-full border border-border bg-secondary"
@@ -154,10 +155,10 @@ export default function ConnectionsNewRouteScreen() {
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 16,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
<View collapsable={false} className="gap-5">
@@ -231,13 +232,11 @@ export default function ConnectionsNewRouteScreen() {
/>
</View>
{connectionError ? <ErrorBanner message={connectionError} /> : null}
{pairingConnectionError ? <ErrorBanner message={pairingConnectionError} /> : null}
<ConnectionSheetButton
icon="plus"
label={
isSubmitting || connectionState === "connecting" ? "Pairing..." : "Add backend"
}
label={isSubmitting ? "Pairing..." : "Add environment"}
disabled={connectDisabled}
tone="primary"
onPress={() => {
+41 -8
View File
@@ -1,23 +1,50 @@
import { Stack, useRouter } from "expo-router";
import { useState } from "react";
import { Text as RNText, View, useColorScheme } from "react-native";
import { type ComponentProps, useState } from "react";
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
import { SymbolView } from "expo-symbols";
import { useThemeColor } from "../lib/useThemeColor";
import { buildThreadRoutePath } from "../lib/routes";
import { useRemoteCatalog } from "../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
import type { RemoteCatalogState } from "../state/use-remote-catalog";
function resolveHeaderStatus(state: RemoteCatalogState): {
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly color: string;
readonly label: string;
} {
if (state.isLoadingSavedConnections) {
return { icon: "hourglass", color: "#737373", label: "Loading environments" };
}
if (state.connectionError) {
return { icon: "exclamationmark.triangle.fill", color: "#ef4444", label: "Environment error" };
}
if (state.connectionState === "ready") {
return { icon: "checkmark.circle.fill", color: "#22c55e", label: "Environment online" };
}
if (state.connectionState === "connecting" || state.connectionState === "reconnecting") {
return {
icon: "arrow.triangle.2.circlepath",
color: "#f59e0b",
label: "Environment connecting",
};
}
return { icon: "wifi.slash", color: "#ef4444", label: "Environment offline" };
}
/* ─── Route screen ───────────────────────────────────────────────────── */
export default function HomeRouteScreen() {
const { projects, threads } = useRemoteCatalog();
const { projects, state: catalogState, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
const isDark = useColorScheme() === "dark";
const iconColor = String(useThemeColor("--color-icon"));
const status = resolveHeaderStatus(catalogState);
return (
<>
@@ -78,11 +105,15 @@ export default function HomeRouteScreen() {
</Stack.Toolbar>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon="network"
onPress={() => router.push("/connections")}
separateBackground
/>
<Stack.Toolbar.View hidesSharedBackground>
<Pressable
accessibilityLabel={status.label}
className="h-11 w-11 items-center justify-center rounded-full bg-card active:opacity-70"
onPress={() => router.push("/connections")}
>
<SymbolView name={status.icon} size={21} tintColor={status.color} type="monochrome" />
</Pressable>
</Stack.Toolbar.View>
</Stack.Toolbar>
{/* Bottom toolbar: search + compose, visually split like iMessage */}
@@ -99,8 +130,10 @@ export default function HomeRouteScreen() {
<HomeScreen
projects={projects}
threads={threads}
catalogState={catalogState}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
onAddConnection={() => router.push("/connections/new")}
onSelectThread={(thread) => {
router.push(buildThreadRoutePath(thread));
}}
+4
View File
@@ -18,6 +18,10 @@ export default function NewTaskLayout() {
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen
name="add-project"
options={{ animation: "slide_from_right", headerShown: false }}
/>
<Stack.Screen name="draft" options={{ animation: "slide_from_right" }} />
</Stack>
</NewTaskFlowProvider>
@@ -0,0 +1,17 @@
import { Stack } from "expo-router";
import { useThemeColor } from "../../../lib/useThemeColor";
export default function AddProjectLayout() {
const sheetStyle = {
backgroundColor: useThemeColor("--color-sheet"),
};
return (
<Stack screenOptions={{ headerShown: false, contentStyle: sheetStyle }}>
<Stack.Screen name="index" options={{ animation: "slide_from_right" }} />
<Stack.Screen name="repository" options={{ animation: "slide_from_right" }} />
<Stack.Screen name="destination" options={{ animation: "slide_from_right" }} />
<Stack.Screen name="local" options={{ animation: "slide_from_right" }} />
</Stack>
);
}
@@ -0,0 +1,12 @@
import { Stack } from "expo-router";
import { AddProjectDestinationScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectDestinationRoute() {
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<AddProjectDestinationScreen />
</>
);
}
@@ -0,0 +1,12 @@
import { Stack } from "expo-router";
import { AddProjectSourceScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectRoute() {
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<AddProjectSourceScreen />
</>
);
}
@@ -0,0 +1,12 @@
import { Stack } from "expo-router";
import { AddProjectLocalFolderScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectLocalRoute() {
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<AddProjectLocalFolderScreen />
</>
);
}
@@ -0,0 +1,12 @@
import { Stack } from "expo-router";
import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen";
export default function AddProjectRepositoryRoute() {
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<AddProjectRepositoryScreen />
</>
);
}
+139 -42
View File
@@ -1,83 +1,153 @@
import { Link, Stack } from "expo-router";
import { Link, Stack, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useMemo } from "react";
import { Pressable, ScrollView, View } from "react-native";
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 { NewTaskSheetHeader } from "../../features/threads/NewTaskSheetHeader";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { type RemoteCatalogState, useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
function deriveProjectEmptyState(catalogState: RemoteCatalogState): {
readonly title: string;
readonly detail: string;
readonly loading: boolean;
} {
if (catalogState.isLoadingSavedConnections) {
return {
title: "Loading environments",
detail: "Checking saved environments on this device.",
loading: true,
};
}
if (!catalogState.hasSavedConnections) {
return {
title: "No environments connected",
detail: "Add an environment before creating a task.",
loading: false,
};
}
if (catalogState.connectionState === "disconnected" && !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, threads } = useRemoteCatalog();
const { projects, state: catalogState, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
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(
() =>
repositoryGroups
.map((group) => {
const project = group.projects[0]?.project;
if (!project) {
return null;
}
return {
environmentId: project.environmentId,
id: project.id,
key: group.key,
title: project.title,
workspaceRoot: project.workspaceRoot,
};
})
.filter((entry) => entry !== null),
[repositoryGroups],
);
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 (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen options={{ headerShown: false }} />
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold">Choose project</Text>
</View>
<NewTaskSheetHeader title="Choose project" />
<ScrollView
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
{items.length === 0 ? (
<View collapsable={false} className="items-center rounded-[24px] bg-card px-6 py-8">
<Text className="text-[16px] font-medium text-foreground-muted">
Loading projects...
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
{projectEmptyState.loading ? <ActivityIndicator color={accentColor} /> : null}
<Text className="text-center text-[17px] font-t3-bold text-foreground">
{projectEmptyState.title}
</Text>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
{projectEmptyState.detail}
</Text>
{!catalogState.hasReadyEnvironment ? (
<Pressable
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
onPress={() => router.push("/connections/new")}
>
<Text className="text-[13px] font-t3-bold text-primary-foreground">
Add environment
</Text>
</Pressable>
) : (
<Pressable
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
onPress={() => router.push("/new/add-project")}
>
<Text className="text-[13px] font-t3-bold text-primary-foreground">
Add new project
</Text>
</Pressable>
)}
</View>
) : (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{items.map((item, index) => {
const isFirst = index === 0;
const isLast = index === items.length - 1;
return (
<Link
@@ -101,8 +171,8 @@ export default function NewTaskRoute() {
borderTopColor: borderSubtleColor,
borderTopLeftRadius: isFirst ? 24 : 0,
borderTopRightRadius: isFirst ? 24 : 0,
borderBottomLeftRadius: isLast ? 24 : 0,
borderBottomRightRadius: isLast ? 24 : 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
}}
>
<View className="flex-row items-center justify-between gap-3">
@@ -127,6 +197,33 @@ export default function NewTaskRoute() {
</Link>
);
})}
<Pressable
className="bg-card"
style={{
paddingHorizontal: 16,
paddingVertical: 18,
borderTopWidth: 1,
borderTopColor: borderSubtleColor,
borderBottomLeftRadius: 24,
borderBottomRightRadius: 24,
}}
onPress={() => router.push("/new/add-project")}
>
<View className="flex-row items-center justify-between gap-3">
<View className="h-[22px] w-[22px] items-center justify-center rounded-full bg-subtle">
<SymbolView name="plus" size={13} tintColor={accentColor} type="monochrome" />
</View>
<View className="flex-1">
<Text className="text-[18px] font-t3-bold">Add new project</Text>
</View>
<SymbolView
name="chevron.right"
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</View>
</Pressable>
</View>
)}
</ScrollView>
@@ -1,5 +1,10 @@
import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";
import { ReviewSheet } from "../../../../features/review/ReviewSheet";
export default function ReviewRoute() {
return <ReviewSheet />;
return (
<ReviewHighlighterProvider>
<ReviewSheet />
</ReviewHighlighterProvider>
);
}
+17 -2
View File
@@ -1,14 +1,29 @@
import { View } from "react-native";
import { Pressable, View } from "react-native";
import { AppText as Text } from "./AppText";
export function EmptyState(props: { readonly title: string; readonly detail: string }) {
export function EmptyState(props: {
readonly title: string;
readonly detail: string;
readonly actionLabel?: string;
readonly onAction?: () => void;
}) {
return (
<View className="rounded-[22px] border border-border bg-card p-5">
<Text className="font-t3-bold text-lg text-foreground">{props.title}</Text>
<Text className="mt-2 font-sans text-sm leading-[21px] text-foreground-muted">
{props.detail}
</Text>
{props.actionLabel && props.onAction ? (
<Pressable
className="mt-4 self-start rounded-full bg-primary px-4 py-2.5 active:opacity-70"
onPress={props.onAction}
>
<Text className="text-[13px] font-t3-bold text-primary-foreground">
{props.actionLabel}
</Text>
</Pressable>
) : null}
</View>
);
}
@@ -0,0 +1,99 @@
import Svg, { Defs, LinearGradient, Path, Stop } from "react-native-svg";
export type SourceControlIconKind = "github" | "gitlab" | "bitbucket" | "azure-devops";
export function SourceControlIcon(props: {
readonly kind: SourceControlIconKind;
readonly size?: number;
readonly color?: string;
}) {
const size = props.size ?? 18;
switch (props.kind) {
case "github":
return (
<Svg width={size} height={size} viewBox="0 0 16 16" fill="none">
<Path
fillRule="evenodd"
clipRule="evenodd"
d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82A7.68 7.68 0 0 1 8.02 3.86c.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8Z"
fill={props.color ?? "#24292F"}
/>
</Svg>
);
case "gitlab":
return (
<Svg width={size} height={size} viewBox="0 0 32 32" fill="none">
<Path
d="m31.46 12.78-.04-.12-4.35-11.35A1.14 1.14 0 0 0 25.94.6c-.24 0-.47.1-.66.24-.19.15-.33.36-.39.6l-2.94 9h-11.9l-2.94-9A1.14 1.14 0 0 0 6.07.58a1.15 1.15 0 0 0-1.14.72L.58 12.68l-.05.11a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48 6.67-5h.02a8.09 8.09 0 0 0 2.7-9.36Z"
fill="#E24329"
/>
<Path
d="m31.46 12.78-.04-.12a14.75 14.75 0 0 0-5.86 2.64l-9.55 7.24 6.09 4.6 6.67-5h.02a8.09 8.09 0 0 0 2.67-9.36Z"
fill="#FC6D26"
/>
<Path
d="m9.9 27.14 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48-6.1-4.6-6.07 4.6Z"
fill="#FCA326"
/>
<Path
d="M6.44 15.3a14.71 14.71 0 0 0-5.86-2.63l-.05.12a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 6.1-4.6-9.56-7.24Z"
fill="#FC6D26"
/>
</Svg>
);
case "azure-devops":
return (
<Svg width={size} height={size} viewBox="0 0 96 96">
<Defs>
<LinearGradient id="azure-a" x1="42.83" x2="15.79" y1="12.69" y2="92.57">
<Stop offset="0" stopColor="#114A8B" />
<Stop offset="1" stopColor="#0669BC" />
</LinearGradient>
<LinearGradient id="azure-b" x1="47.84" x2="77.52" y1="10.36" y2="89.44">
<Stop offset="0" stopColor="#3CCBF4" />
<Stop offset="1" stopColor="#2892DF" />
</LinearGradient>
</Defs>
<Path
fill="url(#azure-a)"
d="M33.34 6.54h26.04l-27.03 80.1a4.15 4.15 0 0 1-3.94 2.81H8.15a4.14 4.14 0 0 1-3.93-5.47L29.4 9.38a4.15 4.15 0 0 1 3.94-2.83z"
/>
<Path
fill="#0078D4"
d="M71.17 60.26H29.88a1.91 1.91 0 0 0-1.3 3.31l26.53 24.76a4.17 4.17 0 0 0 2.85 1.13h23.38z"
/>
<Path
fill="url(#azure-b)"
d="M66.6 9.36a4.14 4.14 0 0 0-3.93-2.82H33.65a4.15 4.15 0 0 1 3.93 2.82l25.18 74.62a4.15 4.15 0 0 1-3.93 5.48h29.02a4.15 4.15 0 0 0 3.93-5.48z"
/>
</Svg>
);
case "bitbucket":
return (
<Svg width={size} height={size} viewBox="8.4 14.39 2481.29 2231.21">
<Defs>
<LinearGradient
id="bitbucket-a"
x1="945.1094"
y1="1524.8389"
x2="944.4923"
y2="1524.1893"
gradientTransform="matrix(1996.6343 0 0 -1480.3047 -1884485.625 2258195)"
>
<Stop offset="0.18" stopColor="#0052CC" />
<Stop offset="1" stopColor="#2684FF" />
</LinearGradient>
</Defs>
<Path
fill="#2684FF"
d="M88.92,14.4C45.02,13.83,8.97,48.96,8.41,92.86c-0.06,4.61,0.28,9.22,1.02,13.77l337.48,2048.72 c8.68,51.75,53.26,89.8,105.74,90.24h1619.03c39.38,0.5,73.19-27.9,79.49-66.78l337.49-2071.78c7.03-43.34-22.41-84.17-65.75-91.2 c-4.55-0.74-9.15-1.08-13.76-1.02L88.92,14.4z M1509.99,1495.09H993.24l-139.92-731h781.89L1509.99,1495.09z"
/>
<Path
fill="url(#bitbucket-a)"
d="M2379.27,763.06h-745.5l-125.12,730.42H992.31l-609.67,723.67c19.32,16.71,43.96,26,69.5,26.21h1618.13 c39.35,0.51,73.14-27.88,79.44-66.72L2379.27,763.06z"
/>
</Svg>
);
}
}
@@ -9,6 +9,25 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/App
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
function connectionStatusLabel(environment: ConnectedEnvironmentSummary): string | null {
if (environment.connectionError) {
return null;
}
switch (environment.connectionState) {
case "ready":
return "Connected";
case "connecting":
return "Connecting";
case "reconnecting":
return "Reconnecting";
case "disconnected":
return null;
case "idle":
return null;
}
}
export function ConnectionEnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly expanded: boolean;
@@ -27,6 +46,7 @@ export function ConnectionEnvironmentRow(props: {
const placeholderColor = useThemeColor("--color-placeholder");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground");
const statusLabel = connectionStatusLabel(props.environment);
const handleSave = useCallback(() => {
props.onUpdate(props.environment.environmentId, {
@@ -42,7 +62,14 @@ export function ConnectionEnvironmentRow(props: {
className="flex-row items-center gap-3 px-4 py-3.5 active:opacity-70"
onPress={props.onToggle}
>
<ConnectionStatusDot state={props.environment.connectionState} pulse={false} size={8} />
<ConnectionStatusDot
state={props.environment.connectionState}
pulse={
props.environment.connectionState === "connecting" ||
props.environment.connectionState === "reconnecting"
}
size={8}
/>
<View className="flex-1 gap-0.5">
<Text
@@ -54,6 +81,11 @@ export function ConnectionEnvironmentRow(props: {
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{props.environment.displayUrl}
</Text>
{statusLabel ? (
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{statusLabel}
</Text>
) : null}
{props.environment.connectionError ? (
<Text
className="text-[12px] leading-[16px] text-rose-500 dark:text-rose-400"
@@ -16,11 +16,10 @@ import { buildPairingUrl, parsePairingUrl } from "./pairing";
export function NewConnectionRouteScreen() {
const {
connectionError,
connectionPairingUrl,
connectionState,
onChangeConnectionPairingUrl,
onConnectPress,
pairingConnectionError,
} = useRemoteConnections();
const router = useRouter();
const params = useLocalSearchParams<{ mode?: string }>();
@@ -35,8 +34,7 @@ export function NewConnectionRouteScreen() {
const textColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled =
isSubmitting || connectionState === "connecting" || hostInput.trim().length === 0;
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
useEffect(() => {
const { host, code } = parsePairingUrl(connectionPairingUrl);
@@ -45,10 +43,10 @@ export function NewConnectionRouteScreen() {
}, [connectionPairingUrl]);
useEffect(() => {
if (connectionError) {
if (pairingConnectionError) {
setIsSubmitting(false);
}
}, [connectionError]);
}, [pairingConnectionError]);
const handleHostChange = useCallback((value: string) => {
setHostInput(value);
@@ -72,7 +70,10 @@ export function NewConnectionRouteScreen() {
return;
}
Alert.alert("Camera access needed", "Allow camera access to scan a backend pairing QR code.");
Alert.alert(
"Camera access needed",
"Allow camera access to scan an environment pairing QR code.",
);
}, [cameraPermission?.granted, requestCameraPermission]);
const closeScanner = useCallback(() => {
@@ -126,7 +127,7 @@ export function NewConnectionRouteScreen() {
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: showScanner ? "Scan QR Code" : "Add Backend",
title: showScanner ? "Scan QR Code" : "Add Environment",
headerRight: () => (
<Pressable
className="h-10 w-10 items-center justify-center rounded-full border border-border bg-secondary"
@@ -154,10 +155,10 @@ export function NewConnectionRouteScreen() {
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 16,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
<View collapsable={false} className="gap-5">
@@ -231,13 +232,11 @@ export function NewConnectionRouteScreen() {
/>
</View>
{connectionError ? <ErrorBanner message={connectionError} /> : null}
{pairingConnectionError ? <ErrorBanner message={pairingConnectionError} /> : null}
<ConnectionSheetButton
icon="plus"
label={
isSubmitting || connectionState === "connecting" ? "Pairing..." : "Add backend"
}
label={isSubmitting ? "Pairing..." : "Add environment"}
disabled={connectDisabled}
tone="primary"
onPress={() => {
+92 -12
View File
@@ -5,7 +5,9 @@ import type {
} from "@t3tools/client-runtime";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
@@ -14,6 +16,7 @@ import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import type { RemoteCatalogState } from "../../state/use-remote-catalog";
import { useVcsStatus } from "../../state/use-vcs-status";
import { threadStatusTone } from "../threads/threadPresentation";
@@ -22,8 +25,10 @@ import { threadStatusTone } from "../threads/threadPresentation";
interface HomeScreenProps {
readonly projects: ReadonlyArray<EnvironmentScopedProjectShell>;
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
readonly catalogState: RemoteCatalogState;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly searchQuery: string;
readonly onAddConnection: () => void;
readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void;
}
@@ -33,6 +38,15 @@ interface ProjectGroup {
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
}
const projectGroupActivityOrder = Order.mapInput(
Order.Struct({
activityAt: Order.flip(Order.Number),
}),
(group: ProjectGroup) => ({
activityAt: new Date(group.threads[0]!.updatedAt ?? group.threads[0]!.createdAt).getTime(),
}),
);
/* ─── Status indicator colors ────────────────────────────────────────── */
function statusColors(thread: EnvironmentScopedThreadShell): { bg: string; fg: string } {
@@ -52,6 +66,64 @@ function statusColors(thread: EnvironmentScopedThreadShell): { bg: string; fg: s
const COLLAPSED_THREAD_LIMIT = 6;
function deriveEmptyState(props: {
readonly catalogState: RemoteCatalogState;
readonly projectCount: number;
}): { readonly title: string; readonly detail: string; readonly loading: boolean } {
const { catalogState } = props;
if (catalogState.isLoadingSavedConnections) {
return {
title: "Loading environments",
detail: "Checking saved environments on this device.",
loading: true,
};
}
if (!catalogState.hasSavedConnections) {
return {
title: "No environments connected",
detail: "Add an environment to load projects and start coding sessions.",
loading: false,
};
}
if (catalogState.connectionState === "disconnected" && !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 and threads from the saved environment.",
loading: true,
};
}
if (props.projectCount === 0 && catalogState.hasLoadedShellSnapshot) {
return {
title: "No projects found",
detail: "The connected environment did not report any projects.",
loading: false,
};
}
return {
title: "No threads yet",
detail: "Create a task to start a new coding session in one of your connected projects.",
loading: false,
};
}
/* ─── Project group header ───────────────────────────────────────────── */
function ProjectGroupLabel(props: {
@@ -222,6 +294,7 @@ function ThreadRow(props: {
export function HomeScreen(props: HomeScreenProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
const accentColor = useThemeColor("--color-icon-muted");
const toggleExpanded = useCallback((key: string) => {
setExpandedProjects((prev) => {
@@ -271,18 +344,16 @@ export function HomeScreen(props: HomeScreenProps) {
}
}
groups.sort((a, b) => {
const aTime = new Date(a.threads[0]!.updatedAt ?? a.threads[0]!.createdAt).getTime();
const bTime = new Date(b.threads[0]!.updatedAt ?? b.threads[0]!.createdAt).getTime();
return bTime - aTime;
});
return groups;
return Arr.sort(groups, projectGroupActivityOrder);
}, [props.projects, filteredThreads]);
/* Empty states */
const hasAnyThreads = props.threads.length > 0;
const hasResults = filteredThreads.length > 0;
const emptyState = deriveEmptyState({
catalogState: props.catalogState,
projectCount: props.projects.length,
});
return (
<ScrollView
@@ -299,10 +370,19 @@ export function HomeScreen(props: HomeScreenProps) {
}}
>
{!hasAnyThreads ? (
<EmptyState
title="No threads yet"
detail="Create a task to start a new coding session in one of your connected projects."
/>
<View>
<EmptyState
title={emptyState.title}
detail={emptyState.detail}
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
/>
{emptyState.loading ? (
<View className="absolute right-5 top-5">
<ActivityIndicator color={accentColor} />
</View>
) : null}
</View>
) : !hasResults ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : (
@@ -0,0 +1,827 @@
import {
addProjectRemoteSourceLabel,
addProjectRemoteSourcePathHint,
addProjectRemoteSourceProvider,
appendBrowsePathSegment,
buildAddProjectRemoteSourceReadiness,
buildProjectCreateCommand,
canNavigateUp,
ensureBrowseDirectoryPath,
findExistingAddProject,
getAddProjectInitialQuery,
getBrowseDirectoryPath,
getBrowseLeafPathSegment,
getBrowseParentPath,
hasTrailingPathSeparator,
inferProjectTitleFromPath,
isFilesystemBrowseQuery,
resolveAddProjectPath,
sortAddProjectProviderSources,
type AddProjectRemoteSource,
} from "@t3tools/client-runtime";
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
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";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner";
import { SourceControlIcon } from "../../components/SourceControlIcon";
import { useThemeColor } from "../../lib/useThemeColor";
import { uuidv4 } from "../../lib/uuid";
import { getEnvironmentClient } from "../../state/environment-session-registry";
import { useFilesystemBrowse } from "../../state/use-filesystem-browse";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
import {
refreshSourceControlDiscoveryForEnvironment,
useSourceControlDiscovery,
} from "../../state/use-source-control-discovery";
import { NewTaskSheetHeader } from "../threads/NewTaskSheetHeader";
interface EnvironmentOption {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly platform: string;
readonly baseDirectory: string | null;
}
const environmentOptionOrder = Order.mapInput(
Order.Struct({
label: Order.String,
}),
(environment: EnvironmentOption) => ({ label: environment.label }),
);
const browseEntryOrder = Order.mapInput(
Order.String,
(entry: { readonly name: string }) => entry.name,
);
function platformFromOs(os: string | null | undefined): string {
if (os === "windows") return "Win32";
if (os === "darwin") return "MacIntel";
if (os === "linux") return "Linux";
return "";
}
function errorMessage(error: unknown): string {
return error instanceof Error && error.message.trim().length > 0
? error.message
: "An error occurred.";
}
function stringParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) return value[0] ?? null;
return value ?? null;
}
function sourceFromParam(value: string | string[] | undefined): AddProjectRemoteSource {
const source = stringParam(value);
if (
source === "url" ||
source === "github" ||
source === "gitlab" ||
source === "bitbucket" ||
source === "azure-devops"
) {
return source;
}
return "url";
}
function SectionTitle(props: { readonly children: string }) {
return (
<Text
className="px-1 text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.7 }}
>
{props.children}
</Text>
);
}
function AddProjectShell(props: {
readonly title: string;
readonly closeToNew?: boolean;
readonly children: ReactNode;
}) {
const router = useRouter();
const insets = useSafeAreaInsets();
return (
<View className="flex-1 bg-sheet">
<NewTaskSheetHeader
eyebrow="New project"
title={props.title}
control={{
icon: props.closeToNew ? "xmark" : "chevron.left",
onPress: () => router.back(),
}}
/>
<ScrollView
keyboardShouldPersistTaps="handled"
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 16,
paddingBottom: Math.max(insets.bottom, 18) + 18,
gap: 10,
}}
>
{props.children}
</ScrollView>
</View>
);
}
function ListSection(props: { readonly children: ReactNode }) {
return <View className="overflow-hidden rounded-[24px] bg-card">{props.children}</View>;
}
function ListRow(props: {
readonly title: string;
readonly subtitle?: string | null;
readonly icon: ReactNode;
readonly disabled?: boolean;
readonly selected?: boolean;
readonly isFirst?: boolean;
readonly right?: ReactNode;
readonly onPress?: () => void;
}) {
const borderColor = useThemeColor("--color-border-subtle");
const chevronColor = useThemeColor("--color-chevron");
return (
<Pressable
disabled={props.disabled}
onPress={props.onPress}
className="bg-card px-3.5 py-2.5 active:opacity-70"
style={{
opacity: props.disabled ? 0.45 : 1,
borderTopWidth: props.isFirst ? 0 : 1,
borderTopColor: borderColor,
}}
>
<View className="flex-row items-center gap-3">
<View
className={
props.selected
? "h-7 w-7 items-center justify-center rounded-full bg-primary"
: "h-7 w-7 items-center justify-center"
}
>
{props.icon}
</View>
<View className="flex-1 gap-0.5">
<Text className="text-[15px] font-t3-bold">{props.title}</Text>
{props.subtitle ? (
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={2}>
{props.subtitle}
</Text>
) : null}
</View>
{"right" in props ? (
props.right
) : !props.disabled ? (
<SymbolView name="chevron.right" size={13} tintColor={chevronColor} type="monochrome" />
) : null}
</View>
</Pressable>
);
}
function PrimaryActionButton(props: {
readonly label: string;
readonly disabled?: boolean;
readonly loading?: boolean;
readonly onPress: () => void;
}) {
const primaryForeground = useThemeColor("--color-primary-foreground");
return (
<Pressable
disabled={props.disabled}
onPress={props.onPress}
className="h-12 items-center justify-center rounded-full bg-primary active:opacity-70 disabled:opacity-45"
>
{props.loading ? (
<ActivityIndicator color={String(primaryForeground)} />
) : (
<Text className="text-[14px] font-t3-bold text-primary-foreground">{props.label}</Text>
)}
</Pressable>
);
}
function ProjectPathInput(props: {
readonly value: string;
readonly onChangeText: (value: string) => void;
readonly onSubmit: () => void;
}) {
return (
<TextInput
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-[15px] leading-[20px]"
value={props.value}
onChangeText={props.onChangeText}
autoCapitalize="none"
autoCorrect={false}
placeholder="~/projects/my-app"
returnKeyType="done"
onSubmitEditing={props.onSubmit}
/>
);
}
function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
const { serverConfigByEnvironmentId } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
return useMemo<ReadonlyArray<EnvironmentOption>>(() => {
const options = Object.values(savedConnectionsById).map((connection) => {
const config = serverConfigByEnvironmentId[connection.environmentId];
return {
environmentId: connection.environmentId,
label: connection.environmentLabel,
platform: platformFromOs(config?.environment.platform.os ?? null),
baseDirectory: config?.settings.addProjectBaseDirectory ?? null,
};
});
return Arr.sort(options, environmentOptionOrder);
}, [savedConnectionsById, serverConfigByEnvironmentId]);
}
function useSelectedEnvironment(): {
readonly environmentOptions: ReadonlyArray<EnvironmentOption>;
readonly selectedEnvironment: EnvironmentOption | null;
readonly setSelectedEnvironmentId: (environmentId: EnvironmentId) => void;
} {
const router = useRouter();
const params = useLocalSearchParams<{ environmentId?: string }>();
const environmentOptions = useEnvironmentOptions();
const requestedEnvironmentId = stringParam(params.environmentId) as EnvironmentId | null;
const selectedEnvironment =
environmentOptions.find(
(environment) => environment.environmentId === requestedEnvironmentId,
) ??
environmentOptions[0] ??
null;
return {
environmentOptions,
selectedEnvironment,
setSelectedEnvironmentId: (environmentId) => router.setParams({ environmentId }),
};
}
function EmptyEnvironmentState() {
const router = useRouter();
return (
<View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
<Text className="text-center text-[17px] font-t3-bold">No environments connected</Text>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Add an environment before adding a project.
</Text>
<Pressable
onPress={() => router.replace("/connections/new")}
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
>
<Text className="text-[13px] font-t3-bold text-primary-foreground">Add environment</Text>
</Pressable>
</View>
);
}
function SourceControlRow(props: {
readonly source: AddProjectRemoteSource;
readonly selectedEnvironmentId: EnvironmentId;
readonly ready: boolean;
readonly hint: string;
readonly isFirst: boolean;
}) {
const router = useRouter();
const iconColor = useThemeColor("--color-icon");
const title =
props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`;
const subtitle =
props.source === "url"
? "Clone from a remote URL"
: `Clone ${addProjectRemoteSourceLabel(props.source)} ${props.hint}`;
const icon =
props.source === "url" ? (
<SymbolView name="link" size={17} tintColor={iconColor} type="monochrome" />
) : (
<SourceControlIcon kind={props.source} size={18} color={String(iconColor)} />
);
if (!props.ready) {
return (
<ListRow title={title} subtitle={props.hint} icon={icon} disabled isFirst={props.isFirst} />
);
}
return (
<ListRow
title={title}
subtitle={subtitle}
icon={icon}
isFirst={props.isFirst}
onPress={() =>
router.push({
pathname: "/new/add-project/repository",
params: {
environmentId: props.selectedEnvironmentId,
source: props.source,
},
})
}
/>
);
}
export function AddProjectSourceScreen() {
const router = useRouter();
const accentColor = useThemeColor("--color-icon-muted");
const iconColor = useThemeColor("--color-icon");
const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
useSelectedEnvironment();
const discoveryState = useSourceControlDiscovery(selectedEnvironment?.environmentId ?? null);
const readiness = useMemo(
() => buildAddProjectRemoteSourceReadiness(discoveryState.data),
[discoveryState.data],
);
useEffect(() => {
if (!selectedEnvironment) return;
void refreshSourceControlDiscoveryForEnvironment(selectedEnvironment.environmentId);
}, [selectedEnvironment]);
return (
<AddProjectShell title="Select source" closeToNew>
{environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null}
{environmentOptions.length > 1 ? (
<>
<SectionTitle>Connected environments</SectionTitle>
<ListSection>
{environmentOptions.map((environment, index) => (
<ListRow
key={environment.environmentId}
title={environment.label}
subtitle={environment.environmentId}
icon={
<SymbolView
name="server.rack"
size={17}
tintColor={iconColor}
type="monochrome"
/>
}
selected={environment.environmentId === selectedEnvironment?.environmentId}
isFirst={index === 0}
right={
environment.environmentId === selectedEnvironment?.environmentId ? (
<SymbolView
name="checkmark"
size={14}
tintColor={iconColor}
type="monochrome"
/>
) : null
}
onPress={() => setSelectedEnvironmentId(environment.environmentId)}
/>
))}
</ListSection>
</>
) : null}
{selectedEnvironment ? (
<>
<ListSection>
<ListRow
title="Local folder"
subtitle="Browse a folder on disk"
icon={
<SymbolView
name="folder.badge.plus"
size={17}
tintColor={iconColor}
type="monochrome"
/>
}
isFirst
onPress={() =>
router.push({
pathname: "/new/add-project/local",
params: { environmentId: selectedEnvironment.environmentId },
})
}
/>
{(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
(candidate) => (
<SourceControlRow
key={candidate}
source={candidate}
selectedEnvironmentId={selectedEnvironment.environmentId}
ready={readiness[candidate].ready}
hint={
readiness[candidate].ready
? addProjectRemoteSourcePathHint(candidate)
: (readiness[candidate].hint ?? "")
}
isFirst={false}
/>
),
)}
</ListSection>
{discoveryState.isPending ? <ActivityIndicator color={accentColor} /> : null}
</>
) : null}
</AddProjectShell>
);
}
function useCreateProject(environment: EnvironmentOption | null) {
const router = useRouter();
const { projects } = useRemoteCatalog();
return useCallback(
async (workspaceRoot: string) => {
if (!environment) return;
const client = getEnvironmentClient(environment.environmentId);
if (!client) throw new Error("Environment API is not available.");
const existing = findExistingAddProject({
projects,
environmentId: environment.environmentId,
path: workspaceRoot,
});
if (existing) {
Alert.alert("Project already exists", existing.title);
router.replace({
pathname: "/new/draft",
params: {
environmentId: existing.environmentId,
projectId: existing.id,
title: existing.title,
},
});
return;
}
const projectId = ProjectId.make(uuidv4());
await client.orchestration.dispatchCommand(
buildProjectCreateCommand({
commandId: CommandId.make(uuidv4()),
projectId,
workspaceRoot,
createdAt: new Date().toISOString(),
}),
);
router.replace({
pathname: "/new/draft",
params: {
environmentId: environment.environmentId,
projectId,
title: inferProjectTitleFromPath(workspaceRoot),
},
});
},
[environment, projects, router],
);
}
function useEnvironmentFromParam(): EnvironmentOption | null {
const params = useLocalSearchParams<{ environmentId?: string }>();
const environmentOptions = useEnvironmentOptions();
const environmentId = stringParam(params.environmentId) as EnvironmentId | null;
return (
environmentOptions.find((environment) => environment.environmentId === environmentId) ??
environmentOptions[0] ??
null
);
}
export function AddProjectRepositoryScreen() {
const router = useRouter();
const params = useLocalSearchParams<{ environmentId?: string; source?: string }>();
const environment = useEnvironmentFromParam();
const source = sourceFromParam(params.source);
const [repositoryInput, setRepositoryInput] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const lookupRepository = useCallback(async () => {
if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
setError(null);
setIsSubmitting(true);
try {
const provider = addProjectRemoteSourceProvider(source);
if (!provider) {
const remoteUrl = repositoryInput.trim();
router.push({
pathname: "/new/add-project/destination",
params: {
environmentId: environment.environmentId,
source,
remoteUrl,
repositoryTitle: remoteUrl,
},
});
return;
}
const client = getEnvironmentClient(environment.environmentId);
if (!client) throw new Error("Environment API is not available.");
const repository = await client.sourceControl.lookupRepository({
provider,
repository: repositoryInput.trim(),
});
router.push({
pathname: "/new/add-project/destination",
params: {
environmentId: environment.environmentId,
source,
remoteUrl: repository.sshUrl,
repositoryTitle: repository.nameWithOwner,
},
});
} catch (nextError) {
setError(errorMessage(nextError));
} finally {
setIsSubmitting(false);
}
}, [environment, isSubmitting, repositoryInput, router, source]);
return (
<AddProjectShell title={source === "url" ? "Git URL" : addProjectRemoteSourceLabel(source)}>
{error ? <ErrorBanner message={error} /> : null}
<TextInput
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-[15px] leading-[20px]"
value={repositoryInput}
onChangeText={setRepositoryInput}
autoCapitalize="none"
autoCorrect={false}
placeholder={
source === "url"
? "https://github.com/org/repo.git"
: addProjectRemoteSourcePathHint(source)
}
returnKeyType="next"
onSubmitEditing={() => void lookupRepository()}
/>
<PrimaryActionButton
label={source === "url" ? "Continue" : "Lookup repository"}
disabled={isSubmitting || repositoryInput.trim().length === 0}
onPress={() => void lookupRepository()}
loading={isSubmitting}
/>
</AddProjectShell>
);
}
function FolderBrowser(props: {
readonly environment: EnvironmentOption;
readonly pathInput: string;
readonly setPathInput: (path: string) => void;
}) {
const accentColor = useThemeColor("--color-icon-muted");
const browseDirectoryPath = useMemo(
() =>
isFilesystemBrowseQuery(props.pathInput, props.environment.platform)
? getBrowseDirectoryPath(props.pathInput)
: "",
[props.environment.platform, props.pathInput],
);
const browseFilterQuery =
browseDirectoryPath.length > 0 && !hasTrailingPathSeparator(props.pathInput)
? getBrowseLeafPathSegment(props.pathInput).toLowerCase()
: "";
const browseInput = useMemo(
() => (browseDirectoryPath.length > 0 ? { partialPath: browseDirectoryPath } : null),
[browseDirectoryPath],
);
const browseState = useFilesystemBrowse(props.environment.environmentId, browseInput);
const visibleBrowseEntries = useMemo(
() =>
Arr.sort(
Arr.filter(
browseState.data?.entries ?? [],
(entry) =>
!entry.name.startsWith(".") && entry.name.toLowerCase().startsWith(browseFilterQuery),
),
browseEntryOrder,
),
[browseFilterQuery, browseState.data?.entries],
);
const parentBrowsePath = getBrowseParentPath(browseDirectoryPath);
const canBrowseUpPath = canNavigateUp(browseDirectoryPath);
return (
<>
<SectionTitle>Browse folders</SectionTitle>
{browseState.error ? <ErrorBanner message={browseState.error} /> : null}
<ListSection>
{browseState.isPending && browseState.data === null ? (
<View className="items-center py-5">
<ActivityIndicator color={accentColor} />
</View>
) : null}
{canBrowseUpPath ? (
<ListRow
title=".."
icon={
<SymbolView
name="arrow.turn.left.up"
size={17}
tintColor={accentColor}
type="monochrome"
/>
}
isFirst
right={null}
onPress={() => {
if (parentBrowsePath) props.setPathInput(parentBrowsePath);
}}
/>
) : null}
{visibleBrowseEntries.map((entry, index) => (
<ListRow
key={entry.fullPath}
title={entry.name}
icon={<SymbolView name="folder" size={17} tintColor={accentColor} type="monochrome" />}
isFirst={index === 0 && !canBrowseUpPath}
right={null}
onPress={() =>
props.setPathInput(
browseDirectoryPath.length > 0
? appendBrowsePathSegment(browseDirectoryPath, entry.name)
: ensureBrowseDirectoryPath(entry.fullPath),
)
}
/>
))}
</ListSection>
</>
);
}
export function AddProjectLocalFolderScreen() {
const environment = useEnvironmentFromParam();
const createProject = useCreateProject(environment);
const [pathInput, setPathInput] = useState(() =>
getAddProjectInitialQuery(environment?.baseDirectory),
);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!environment) return;
setPathInput(getAddProjectInitialQuery(environment.baseDirectory));
}, [environment]);
const submitPath = useCallback(async () => {
if (!environment || isSubmitting) return;
setError(null);
const resolved = resolveAddProjectPath({
rawPath: pathInput,
currentProjectCwd: null,
platform: environment.platform,
});
if (!resolved.ok) {
setError(resolved.error);
return;
}
setIsSubmitting(true);
try {
await createProject(resolved.path);
} catch (nextError) {
setError(errorMessage(nextError));
} finally {
setIsSubmitting(false);
}
}, [createProject, environment, isSubmitting, pathInput]);
return (
<AddProjectShell title="Local folder">
{error ? <ErrorBanner message={error} /> : null}
{environment ? (
<>
<ProjectPathInput
value={pathInput}
onChangeText={setPathInput}
onSubmit={() => void submitPath()}
/>
<PrimaryActionButton
label="Add project"
disabled={isSubmitting}
onPress={() => void submitPath()}
loading={isSubmitting}
/>
<FolderBrowser
environment={environment}
pathInput={pathInput}
setPathInput={setPathInput}
/>
</>
) : (
<EmptyEnvironmentState />
)}
</AddProjectShell>
);
}
export function AddProjectDestinationScreen() {
const params = useLocalSearchParams<{
environmentId?: string;
remoteUrl?: string;
repositoryTitle?: string;
}>();
const environment = useEnvironmentFromParam();
const createProject = useCreateProject(environment);
const remoteUrl = stringParam(params.remoteUrl);
const repositoryTitle = stringParam(params.repositoryTitle);
const [pathInput, setPathInput] = useState(() =>
getAddProjectInitialQuery(environment?.baseDirectory),
);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!environment) return;
setPathInput(getAddProjectInitialQuery(environment.baseDirectory));
}, [environment]);
const submitPath = useCallback(async () => {
if (!environment || !remoteUrl || isSubmitting) return;
setError(null);
const resolved = resolveAddProjectPath({
rawPath: pathInput,
currentProjectCwd: null,
platform: environment.platform,
});
if (!resolved.ok) {
setError(resolved.error);
return;
}
setIsSubmitting(true);
try {
const client = getEnvironmentClient(environment.environmentId);
if (!client) throw new Error("Environment API is not available.");
const result = await client.sourceControl.cloneRepository({
remoteUrl,
destinationPath: resolved.path,
});
await createProject(result.cwd);
} catch (nextError) {
setError(errorMessage(nextError));
} finally {
setIsSubmitting(false);
}
}, [createProject, environment, isSubmitting, pathInput, remoteUrl]);
return (
<AddProjectShell title="Clone destination">
{error ? <ErrorBanner message={error} /> : null}
{repositoryTitle ? (
<View className="rounded-[24px] bg-card px-4 py-3">
<Text className="text-[14px] font-t3-bold">{repositoryTitle}</Text>
<Text className="mt-0.5 text-[12px] text-foreground-muted" numberOfLines={2}>
{remoteUrl}
</Text>
</View>
) : null}
{environment ? (
<>
<ProjectPathInput
value={pathInput}
onChangeText={setPathInput}
onSubmit={() => void submitPath()}
/>
<PrimaryActionButton
label="Clone project"
disabled={isSubmitting || !remoteUrl}
onPress={() => void submitPath()}
loading={isSubmitting}
/>
<FolderBrowser
environment={environment}
pathInput={pathInput}
setPathInput={setPathInput}
/>
</>
) : (
<EmptyEnvironmentState />
)}
</AddProjectShell>
);
}
@@ -385,9 +385,6 @@ export function ReviewSheet() {
}}
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
paddingTop: REVIEW_HEADER_SPACING,
}}
>
{listHeader}
{!selectedSection ? (
@@ -1,129 +0,0 @@
import { describe, expect, it } from "vitest";
import { buildNativeReviewDiffData } from "./nativeReviewDiffAdapter";
import { buildReviewParsedDiff } from "./reviewModel";
describe("buildNativeReviewDiffData", () => {
it("maps real parsed file diffs into native rows with headers, hunks, lines, and notices", () => {
const parsed = buildReviewParsedDiff(
[
"diff --git a/apps/demo/src/main.ts b/apps/demo/src/main.ts",
"index 1111111..2222222 100644",
"--- a/apps/demo/src/main.ts",
"+++ b/apps/demo/src/main.ts",
"@@ -1,2 +1,2 @@",
"-const retryLimit = 2;",
"+const retryLimit = 4;",
" console.log(retryLimit);",
"diff --git a/apps/demo/src/old.ts b/apps/demo/src/new.ts",
"similarity index 100%",
"rename from apps/demo/src/old.ts",
"rename to apps/demo/src/new.ts",
"diff --git a/apps/demo/assets/review-logo.png b/apps/demo/assets/review-logo.png",
"new file mode 100644",
"index 0000000..1111111",
"Binary files /dev/null and b/apps/demo/assets/review-logo.png differ",
].join("\n"),
"native-adapter-test",
);
const data = buildNativeReviewDiffData({
parsedDiff: parsed,
comments: [
{
id: "comment-1",
sectionId: "dirty",
sectionTitle: "Working tree",
filePath: "apps/demo/src/main.ts",
startIndex: 1,
endIndex: 1,
rangeLabel: "+2",
text: "Please keep this configurable.",
diff: "",
},
],
});
expect(data.additions).toBe(1);
expect(data.deletions).toBe(1);
expect(data.files).toEqual(
expect.arrayContaining([
expect.objectContaining({
path: "apps/demo/src/main.ts",
language: "typescript",
additions: 1,
deletions: 1,
}),
expect.objectContaining({
path: "apps/demo/src/new.ts",
language: "typescript",
additions: 0,
deletions: 0,
}),
]),
);
expect(data.rows).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "file",
filePath: "apps/demo/src/main.ts",
changeType: "modified",
}),
expect.objectContaining({
kind: "hunk",
text: "@@ -1,2 +1,2 @@",
}),
expect.objectContaining({
kind: "line",
change: "delete",
content: "const retryLimit = 2;",
wordDiffRanges: [{ start: 19, end: 20 }],
}),
expect.objectContaining({
kind: "line",
change: "add",
content: "const retryLimit = 4;",
wordDiffRanges: [{ start: 19, end: 20 }],
}),
expect.objectContaining({
kind: "comment",
id: "comment-1",
filePath: "apps/demo/src/main.ts",
commentText: "Please keep this configurable.",
commentRangeLabel: "+2",
}),
expect.objectContaining({
kind: "file",
filePath: "apps/demo/src/new.ts",
previousPath: "apps/demo/src/old.ts",
changeType: "rename-pure",
}),
expect.objectContaining({
kind: "notice",
text: "This file was renamed without modifications.",
}),
expect.objectContaining({
kind: "notice",
text: "Unsupported format. Diff contents are not available.",
}),
]),
);
const changedLine = data.rows.find(
(row) =>
row.kind === "line" && row.change === "add" && row.content === "const retryLimit = 4;",
);
expect(changedLine?.id).toBeTruthy();
const changedTarget = data.commentTargetsByRowId.get(changedLine?.id ?? "");
expect(changedTarget).toMatchObject({
filePath: "apps/demo/src/main.ts",
lineIndex: 1,
lines: expect.arrayContaining([
expect.objectContaining({ content: "const retryLimit = 2;" }),
expect.objectContaining({ content: "const retryLimit = 4;" }),
]),
});
const changedCommentLine = changedTarget?.lines[changedTarget.lineIndex];
expect(data.rowIdByCommentLineId.get(changedCommentLine?.id ?? "")).toBe(changedLine?.id);
});
});
@@ -3,6 +3,8 @@ import type {
NativeReviewDiffFile,
NativeReviewDiffLanguage,
} from "../diffs/nativeReviewDiffTypes";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import { getPierreTerminalTheme, type TerminalAppearanceScheme } from "../terminal/terminalTheme";
import { computeWordAltDiffRanges } from "./reviewWordDiffs";
import {
@@ -188,19 +190,22 @@ function trimWordDiffRanges(
content: string,
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
): NonNullable<NativeReviewDiffRow["wordDiffRanges"]> {
return ranges.flatMap((range) => {
let start = Math.max(0, range.start);
let end = Math.min(content.length, range.end);
return pipe(
ranges,
Arr.flatMap((range) => {
let start = Math.max(0, range.start);
let end = Math.min(content.length, range.end);
while (start < end && /\s/.test(content[start] ?? "")) {
start += 1;
}
while (end > start && /\s/.test(content[end - 1] ?? "")) {
end -= 1;
}
while (start < end && /\s/.test(content[start] ?? "")) {
start += 1;
}
while (end > start && /\s/.test(content[end - 1] ?? "")) {
end -= 1;
}
return end > start ? [{ start, end }] : [];
});
return end > start ? [{ start, end }] : [];
}),
);
}
function nonWhitespaceLength(value: string) {
@@ -410,7 +415,7 @@ export function buildNativeReviewDiffData(
const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
const rowIdByCommentLineId = new Map<string, string>();
const rows = addNativeWordDiffRanges(
parsedDiff.files.flatMap((file) =>
Arr.flatMap(parsedDiff.files, (file) =>
mapFileRows(file, comments, commentTargetsByRowId, rowIdByCommentLineId),
),
);
@@ -95,6 +95,7 @@ describe("buildReviewSectionItems", () => {
loadingTurnIds: {
[getReviewSectionIdForCheckpoint(checkpoints[1])]: true,
},
loadingGitSections: false,
});
expect(items.map((item) => item.id)).toEqual([
@@ -110,6 +111,28 @@ describe("buildReviewSectionItems", () => {
});
expect(getDefaultReviewSectionId(items)).toBe("turn:2");
});
it("shows dirty worktree while git preview is loading", () => {
const items = buildReviewSectionItems({
checkpoints: [],
gitSections: [],
turnDiffById: {},
loadingTurnIds: {},
loadingGitSections: true,
});
expect(items).toEqual([
expect.objectContaining({
id: "git:working-tree",
kind: "working-tree",
title: "Dirty worktree",
subtitle: "Tracked, staged, and untracked worktree changes",
diff: null,
isLoading: true,
}),
]);
expect(getDefaultReviewSectionId(items)).toBe("git:working-tree");
});
});
describe("buildReviewParsedDiff", () => {
+32 -6
View File
@@ -2,10 +2,15 @@ import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as Order from "effect/Order";
export type ReviewSectionKind = "turn" | "working-tree" | "branch-range";
const DIRTY_WORKTREE_SECTION_ID = "git:working-tree";
const DIRTY_WORKTREE_TITLE = "Dirty worktree";
const DIRTY_WORKTREE_SUBTITLE = "Tracked, staged, and untracked worktree changes";
export interface ReviewSectionItem {
readonly id: string;
readonly kind: ReviewSectionKind;
@@ -152,7 +157,7 @@ const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>(
function gitSubtitle(section: ReviewDiffPreviewSource): string | null {
if (section.kind === "working-tree") {
return "Tracked, staged, and untracked worktree changes";
return DIRTY_WORKTREE_SUBTITLE;
}
if (section.baseRef) {
return `${section.baseRef} ... ${section.headRef ?? "HEAD"}`;
@@ -513,9 +518,10 @@ export function getReviewSectionIdForCheckpoint(
export function getReadyReviewCheckpoints(
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
): ReadonlyArray<OrchestrationCheckpointSummary> {
return Arr.sort(
checkpoints.filter((checkpoint) => checkpoint.status === "ready"),
readyCheckpointOrder,
return pipe(
checkpoints,
Arr.filter((checkpoint) => checkpoint.status === "ready"),
Arr.sort(readyCheckpointOrder),
);
}
@@ -524,6 +530,7 @@ export function buildReviewSectionItems(input: {
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
readonly loadingGitSections: boolean;
}): ReadonlyArray<ReviewSectionItem> {
const turnItems = getReadyReviewCheckpoints(input.checkpoints).map<ReviewSectionItem>(
(checkpoint) => {
@@ -547,8 +554,23 @@ export function buildReviewSectionItems(input: {
diff: section.diff,
isLoading: false,
}));
const hasDirtyWorktreeItem = gitItems.some((item) => item.id === DIRTY_WORKTREE_SECTION_ID);
const visibleGitItems =
input.loadingGitSections && !hasDirtyWorktreeItem
? [
{
id: DIRTY_WORKTREE_SECTION_ID,
kind: "working-tree",
title: DIRTY_WORKTREE_TITLE,
subtitle: DIRTY_WORKTREE_SUBTITLE,
diff: null,
isLoading: true,
} satisfies ReviewSectionItem,
...gitItems,
]
: gitItems;
return [...turnItems, ...gitItems];
return [...turnItems, ...visibleGitItems];
}
export function getDefaultReviewSectionId(
@@ -579,7 +601,11 @@ export function buildReviewParsedDiff(
const parsedPatches = runDiffParserSilently(() =>
parsePatchFiles(text, buildPatchCacheKey(text, cacheScope)),
);
const files = parsedPatches.flatMap((patch) => patch.files).map(mapRenderableFile);
const files = pipe(
parsedPatches,
Arr.flatMap((patch) => patch.files),
Arr.map(mapRenderableFile),
);
if (files.length === 0) {
return {
@@ -1001,12 +1001,15 @@ export async function highlightReviewSelectedLines(input: {
const language =
loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));
const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];
const additionLikeLines = input.lines
.filter((line) => line.change !== "delete")
.map((line) => `${line.content}\n`);
const deletionLines = input.lines
.filter((line) => line.change === "delete")
.map((line) => `${line.content}\n`);
const additionLikeLines: string[] = [];
const deletionLines: string[] = [];
for (const line of input.lines) {
if (line.change === "delete") {
deletionLines.push(`${line.content}\n`);
} else {
additionLikeLines.push(`${line.content}\n`);
}
}
const [additionTokens, deletionTokens] = await Promise.all([
highlightLines(joinPatchLines(additionLikeLines), language, shikiTheme),
highlightLines(joinPatchLines(deletionLines), language, shikiTheme),
@@ -1,6 +1,9 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import type { NativeSyntheticEvent } from "react-native";
import { useRouter } from "expo-router";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as Result from "effect/Result";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
@@ -53,10 +56,13 @@ export function useReviewCommentSelectionController(input: {
activeCommentTarget.sectionTitle === selectedSection?.title &&
activeCommentTarget.startIndex !== activeCommentTarget.endIndex
) {
return getSelectedReviewCommentLines(activeCommentTarget).flatMap((line) => {
const rowId = nativeReviewDiffData.rowIdByCommentLineId.get(line.id);
return rowId ? [rowId] : [];
});
return pipe(
getSelectedReviewCommentLines(activeCommentTarget),
Arr.filterMap((line) => {
const rowId = nativeReviewDiffData.rowIdByCommentLineId.get(line.id);
return rowId ? Result.succeed(rowId) : Result.failVoid;
}),
);
}
return pendingNativeCommentSelection ? [pendingNativeCommentSelection.rowId] : [];
@@ -66,8 +66,15 @@ export function useReviewSections(input: {
gitSections: reviewCache.gitSections,
turnDiffById: reviewCache.turnDiffById,
loadingTurnIds,
loadingGitSections: diffPreview.isPending,
}),
[loadingTurnIds, readyCheckpoints, reviewCache.gitSections, reviewCache.turnDiffById],
[
diffPreview.isPending,
loadingTurnIds,
readyCheckpoints,
reviewCache.gitSections,
reviewCache.turnDiffById,
],
);
const selectedSection = useMemo(
() =>
@@ -9,7 +9,6 @@ import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
import { KeyboardStickyView } from "react-native-keyboard-controller";
import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
@@ -191,7 +190,6 @@ function pickRunningTerminalSessionForBootstrap(
export function ThreadTerminalRouteScreen() {
const router = useRouter();
const keyboard = useAnimatedKeyboard();
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
const params = useLocalSearchParams<{
@@ -397,12 +395,6 @@ export function ThreadTerminalRouteScreen() {
];
}, [hostPlatform]);
const terminalBottomInset = TERMINAL_ACCESSORY_HEIGHT;
const terminalContainerAnimatedStyle = useAnimatedStyle(() => ({
paddingBottom:
keyboard.height.value > 0
? keyboard.height.value + TERMINAL_ACCESSORY_HEIGHT
: terminalBottomInset,
}));
const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
() =>
@@ -1031,7 +1023,7 @@ export function ThreadTerminalRouteScreen() {
</Stack.Toolbar>
<View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
<Animated.View style={[{ flex: 1 }, terminalContainerAnimatedStyle]}>
<View style={{ flex: 1, paddingBottom: terminalBottomInset }}>
<TerminalSurface
buffer={terminalSurfaceBuffer}
fontSize={fontSize}
@@ -1041,7 +1033,7 @@ export function ThreadTerminalRouteScreen() {
style={{ flex: 1 }}
terminalKey={terminalKey}
/>
</Animated.View>
</View>
<KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
<View
@@ -1,6 +1,8 @@
import type { KnownTerminalSession } from "@t3tools/client-runtime";
import { DEFAULT_TERMINAL_ID, type ProjectScript } from "@t3tools/contracts";
import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
export {
getTerminalLabel,
@@ -18,6 +20,14 @@ export interface TerminalMenuSession {
readonly updatedAt: string | null;
}
const terminalMenuSessionOrder = Order.make<TerminalMenuSession>((left, right) => {
const comparison = left.terminalId.localeCompare(right.terminalId, undefined, { numeric: true });
if (comparison === 0) {
return 0;
}
return comparison < 0 ? -1 : 1;
});
export function basename(input: string | null): string | null {
if (!input) {
return null;
@@ -101,9 +111,7 @@ export function buildTerminalMenuSessions(input: {
sessionsById.set(input.currentSession.terminalId, input.currentSession);
}
return Array.from(sessionsById.values()).sort((left, right) =>
left.terminalId.localeCompare(right.terminalId, undefined, { numeric: true }),
);
return Arr.sort(sessionsById.values(), terminalMenuSessionOrder);
}
export function resolveProjectScriptTerminalId(input: {
@@ -1,16 +1,15 @@
import { MenuView } from "@react-native-menu/menu";
import { useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { TextInputWrapper } from "expo-paste-input";
import { useCallback, useEffect, useMemo } from "react";
import { Pressable, View, useColorScheme } from "react-native";
import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated";
import { View, useColorScheme } from "react-native";
import { KeyboardStickyView } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { EnvironmentId, type ModelSelection } from "@t3tools/contracts";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { AppTextInput as TextInput } from "../../components/AppText";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { ControlPill } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
@@ -20,9 +19,22 @@ import { buildThreadRoutePath } from "../../lib/routes";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useNativePaste } from "../../lib/useNativePaste";
import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions";
import { NewTaskSheetHeader } from "./NewTaskSheetHeader";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useProjectActions } from "./use-project-actions";
function withModelSelectionOption(
selection: ModelSelection,
id: string,
value: string | boolean | undefined,
): ModelSelection {
const options = (selection.options ?? []).filter((option) => option.id !== id);
return {
...selection,
options: value === undefined ? options : [...options, { id, value }],
};
}
export function NewTaskDraftScreen(props: {
readonly initialProjectRef?: {
readonly environmentId?: string;
@@ -35,16 +47,9 @@ export function NewTaskDraftScreen(props: {
const router = useRouter();
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const keyboard = useAnimatedKeyboard();
const containerAnimatedStyle = useAnimatedStyle(() => ({
paddingBottom: keyboard.height.value,
}));
const controlsBottomPadding = useAnimatedStyle(() => ({
paddingBottom: keyboard.height.value > 0 ? 4 : Math.max(insets.bottom, 10),
}));
const controlsBottomPadding = Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
const iconColor = useThemeColor("--color-icon");
const borderColor = useThemeColor("--color-border");
useEffect(() => {
@@ -352,19 +357,17 @@ export function NewTaskDraftScreen(props: {
try {
const modelWithOptions: ModelSelection =
flow.selectedModelOption?.providerDriver === "claudeAgent"
? {
...flow.selectedModel,
options: [
{ id: "effort", value: flow.effort },
...(flow.fastMode ? [{ id: "fastMode", value: true }] : []),
{ id: "contextWindow", value: flow.contextWindow },
],
}
? withModelSelectionOption(
withModelSelectionOption(
withModelSelectionOption(flow.selectedModel, "effort", flow.effort),
"fastMode",
flow.fastMode || undefined,
),
"contextWindow",
flow.contextWindow,
)
: flow.selectedModelOption?.providerDriver === "codex"
? {
...flow.selectedModel,
...(flow.fastMode ? { options: [{ id: "fastMode", value: true }] } : {}),
}
? withModelSelectionOption(flow.selectedModel, "fastMode", flow.fastMode || undefined)
: flow.selectedModel;
const createdThread = await onCreateThreadWithOptions({
@@ -390,130 +393,107 @@ export function NewTaskDraftScreen(props: {
if (!selectedProject) {
return (
<View className="flex-1 bg-sheet">
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold">Loading task</Text>
</View>
<NewTaskSheetHeader title="Loading task" />
</View>
);
}
return (
<Animated.View className="flex-1 bg-sheet" style={containerAnimatedStyle}>
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
{flow.logicalProjects.length > 1 ? (
<Pressable
className="absolute left-3 top-4 h-9 w-9 items-center justify-center rounded-full bg-subtle"
style={{ zIndex: 1 }}
onPress={() => router.back()}
>
<SymbolView
name="chevron.left"
size={16}
tintColor={iconColor}
type="monochrome"
weight="medium"
/>
</Pressable>
) : null}
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold">{selectedProject.title}</Text>
</View>
<View className="flex-1 bg-sheet">
<NewTaskSheetHeader
title={selectedProject.title}
control={
flow.logicalProjects.length > 1
? { icon: "chevron.left", onPress: () => router.back() }
: undefined
}
/>
<View style={{ flex: 1, paddingHorizontal: 20, paddingTop: 8 }}>
<TextInputWrapper onPaste={(payload) => void handleNativePaste(payload)}>
<TextInputWrapper
onPaste={(payload) => void handleNativePaste(payload)}
style={{ flex: 1 }}
>
<TextInput
multiline
value={flow.prompt}
onChangeText={flow.setPrompt}
placeholder={`Describe a coding task in ${selectedProject.title}`}
textAlignVertical="top"
className="flex-1 border-0 bg-transparent text-[18px] leading-[28px]"
className="h-full flex-1 border-0 bg-transparent text-[18px] leading-[28px]"
style={{ flex: 1 }}
/>
</TextInputWrapper>
</View>
<Animated.View
style={[
{
<KeyboardStickyView>
<View
style={{
borderTopWidth: 1,
borderTopColor: borderColor,
},
controlsBottomPadding,
]}
>
{flow.attachments.length > 0 ? (
<View style={{ paddingHorizontal: 16, paddingTop: 12 }}>
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={flow.removeAttachment}
imageSize={88}
imageBorderRadius={20}
/>
</View>
) : null}
<View className="flex-row items-center justify-between gap-2 px-4 pb-1 pt-4">
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
<MenuView
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
paddingBottom: controlsBottomPadding,
}}
>
{flow.attachments.length > 0 ? (
<View style={{ paddingHorizontal: 16, paddingTop: 12 }}>
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={flow.removeAttachment}
imageSize={88}
imageBorderRadius={20}
/>
</View>
) : null}
<View className="flex-row items-center justify-between gap-2 px-4 pb-1 pt-4">
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
<MenuView
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill
iconNode={
<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
}
/>
</MenuView>
<MenuView
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="slider.horizontal.3" />
</MenuView>
<MenuView
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="desktopcomputer" />
</MenuView>
<MenuView
actions={workspaceMenuActions}
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="point.topleft.down.curvedto.point.bottomright.up" />
</MenuView>
<ControlPill
iconNode={
<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
icon="arrow.up"
label={flow.submitting ? "Starting" : "Start"}
onPress={() => void handleStart()}
variant="primary"
disabled={
!flow.selectedProject ||
!flow.selectedModel ||
flow.prompt.trim().length === 0 ||
flow.submitting ||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
}
/>
</MenuView>
<MenuView
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="slider.horizontal.3" />
</MenuView>
<MenuView
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="desktopcomputer" />
</MenuView>
<MenuView
actions={workspaceMenuActions}
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
themeVariant={isDarkMode ? "dark" : "light"}
>
<ControlPill icon="point.topleft.down.curvedto.point.bottomright.up" />
</MenuView>
<ControlPill
icon="arrow.up"
label={flow.submitting ? "Starting" : "Start"}
onPress={() => void handleStart()}
variant="primary"
disabled={
!flow.selectedProject ||
!flow.selectedModel ||
flow.prompt.trim().length === 0 ||
flow.submitting ||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
}
/>
</View>
</View>
</Animated.View>
</Animated.View>
</KeyboardStickyView>
</View>
);
}
@@ -0,0 +1,46 @@
import { SymbolView } from "expo-symbols";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
export function NewTaskSheetHeader(props: {
readonly eyebrow?: string;
readonly title: string;
readonly control?: {
readonly icon: "chevron.left" | "xmark";
readonly onPress: () => void;
};
}) {
const iconColor = useThemeColor("--color-icon");
return (
<>
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
{props.control ? (
<Pressable
className="absolute left-3 top-4 h-9 w-9 items-center justify-center rounded-full bg-subtle"
style={{ zIndex: 1 }}
onPress={props.control.onPress}
>
<SymbolView
name={props.control.icon}
size={16}
tintColor={iconColor}
type="monochrome"
weight="medium"
/>
</Pressable>
) : null}
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
{props.eyebrow ?? "New task"}
</Text>
<Text className="text-[28px] font-t3-bold">{props.title}</Text>
</View>
</>
);
}
@@ -13,10 +13,6 @@ import {
replaceTextRange,
type ComposerTrigger,
} from "@t3tools/shared/composerTrigger";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
import { TextInputWrapper } from "expo-paste-input";
import type { ReactNode } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -46,8 +42,12 @@ import {
normalizeSearchQuery,
scoreQueryMatch,
} from "@t3tools/shared/searchRanking";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
import { useComposerPathSearch } from "../../state/use-composer-path-search";
import { CLAUDE_AGENT_EFFORT_OPTIONS, type ClaudeAgentEffort } from "./claudeEffortOptions";
import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions";
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
/**
@@ -69,22 +69,6 @@ export const COMPOSER_EXPANDED_CHROME = 174;
*/
export const COMPOSER_EXPANDED_TOOLBAR_CHROME = 54;
function withModelSelectionOption(
selection: ModelSelection,
id: string,
value: string | boolean | undefined,
): ModelSelection {
const options = (selection.options ?? []).filter((option) => option.id !== id);
if (value !== undefined) {
options.push({ id, value });
}
if (options.length === 0) {
const { options: _options, ...rest } = selection;
return rest as ModelSelection;
}
return { ...selection, options } as ModelSelection;
}
export interface ThreadComposerProps {
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
@@ -149,6 +133,18 @@ function ComposerSurface(props: {
);
}
function withModelSelectionOption(
selection: ModelSelection,
id: string,
value: string | boolean | undefined,
): ModelSelection {
const options = (selection.options ?? []).filter((option) => option.id !== id);
return {
...selection,
options: value === undefined ? options : [...options, { id, value }],
};
}
export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
const isDarkMode = useColorScheme() === "dark";
const themePlaceholderColor = useThemeColor("--color-placeholder");
@@ -188,25 +184,29 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
props.queueCount > 0;
const sendLabel = props.activeThreadBusy || props.queueCount > 0 ? "Queue" : "Send";
const modelProvider = props.selectedThread.modelSelection?.instanceId ?? null;
const currentModelSelection = props.selectedThread.modelSelection;
const currentModelDriver =
props.serverConfig?.providers.find(
(provider) => provider.instanceId === currentModelSelection.instanceId,
)?.driver ?? currentModelSelection.instanceId;
const modelProvider = currentModelDriver;
const currentRuntimeMode = props.selectedThread.runtimeMode;
const currentInteractionMode = props.selectedThread.interactionMode ?? "default";
const selectedProviderStatus = useMemo(() => {
if (!props.serverConfig) return null;
return (
props.serverConfig.providers.find(
(p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
) ?? null
);
}, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
// Extract current model options (effort, fastMode, contextWindow)
const selectedProviderDriver = selectedProviderStatus?.driver ?? null;
const currentEffort =
currentModelDriver === "claudeAgent"
? ((getModelSelectionStringOptionValue(currentModelSelection, "effort") ??
"high") as ClaudeAgentEffort)
selectedProviderDriver === "claudeAgent"
? (getModelSelectionStringOptionValue(currentModelSelection, "effort") ?? "high")
: "high";
const currentFastMode =
getModelSelectionBooleanOptionValue(currentModelSelection, "fastMode") ?? false;
const currentContextWindow =
currentModelDriver === "claudeAgent"
selectedProviderDriver === "claudeAgent"
? (getModelSelectionStringOptionValue(currentModelSelection, "contextWindow") ?? "1M")
: "1M";
@@ -235,16 +235,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
query: composerTrigger?.kind === "path" ? composerTrigger.query : null,
});
// ── Build menu items ─────────────────────────────────────
const selectedProviderStatus = useMemo(() => {
if (!props.serverConfig) return null;
return (
props.serverConfig.providers.find(
(p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
) ?? null
);
}, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
const composerMenuItems: ComposerCommandItem[] = useMemo(() => {
if (!composerTrigger) return [];
@@ -275,15 +265,17 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
];
const builtIn = allBuiltIn.filter((item) => item.command.includes(q));
const providerCommands: ComposerCommandItem[] = (selectedProviderStatus?.slashCommands ?? [])
.filter((cmd) => cmd.name.toLowerCase().includes(q))
.map((cmd) => ({
const providerCommands: ComposerCommandItem[] = [];
for (const cmd of selectedProviderStatus?.slashCommands ?? []) {
if (!cmd.name.toLowerCase().includes(q)) continue;
providerCommands.push({
id: `pcmd:${cmd.name}`,
type: "provider-slash-command" as const,
command: cmd,
label: `/${cmd.name}`,
description: cmd.description ?? "",
}));
});
}
return [...builtIn, ...providerCommands];
}
@@ -565,8 +557,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
if (event.startsWith("options:effort:")) {
const effort = event.slice("options:effort:".length);
const updated: ModelSelection =
currentModelDriver === "claudeAgent"
? withModelSelectionOption(currentModelSelection, "effort", effort)
selectedProviderDriver === "claudeAgent"
? withModelSelectionOption(
currentModelSelection,
"effort",
effort as typeof currentEffort,
)
: currentModelSelection;
void props.onUpdateModelSelection(updated);
return;
@@ -574,7 +570,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
if (event.startsWith("options:fast-mode:")) {
const fastMode = event.endsWith(":on");
const nextFast = fastMode || undefined;
if (currentModelDriver === "opencode") {
if (selectedProviderDriver === "opencode") {
return;
}
const updated = withModelSelectionOption(currentModelSelection, "fastMode", nextFast);
@@ -584,7 +580,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
if (event.startsWith("options:context-window:")) {
const contextWindow = event.slice("options:context-window:".length);
const updated: ModelSelection =
currentModelDriver === "claudeAgent"
selectedProviderDriver === "claudeAgent"
? withModelSelectionOption(currentModelSelection, "contextWindow", contextWindow)
: currentModelSelection;
void props.onUpdateModelSelection(updated);
@@ -201,14 +201,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const { onOpenDrawer, onRefresh } = props;
const insets = useSafeAreaInsets();
const selectedProvider = props.serverConfig?.providers.find(
(provider) => provider.instanceId === props.selectedThread.modelSelection.instanceId,
);
const agentName =
selectedProvider?.displayName ??
selectedProvider?.driver ??
props.selectedThread.modelSelection.instanceId;
const agentLabel = `${agentName} agent`;
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const composerBottomInset = Math.max(insets.bottom, 12);
const [composerExpanded, setComposerExpanded] = useState(false);
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
@@ -87,20 +87,20 @@ export function ThreadGitControls(props: {
const currentBranchLabel = gitStatus?.refName ?? props.currentBranch ?? "Detached HEAD";
const busy = gitOperationLabel !== null;
const isRepo = gitStatus?.isRepo ?? true;
const hasOriginRemote = gitStatus?.hasPrimaryRemote ?? false;
const isDefaultBranch = gitStatus?.isDefaultRef ?? false;
const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
const isDefaultRef = gitStatus?.isDefaultRef ?? false;
const quickAction = useMemo(
() =>
isRepo
? resolveQuickAction(gitStatus, busy, isDefaultBranch, hasOriginRemote)
? resolveQuickAction(gitStatus, busy, isDefaultRef, hasPrimaryRemote)
: {
label: "Git unavailable",
disabled: true,
kind: "show_hint" as const,
hint: "This workspace is not a git repository.",
},
[busy, gitStatus, hasOriginRemote, isDefaultBranch, isRepo],
[busy, gitStatus, hasPrimaryRemote, isDefaultRef, isRepo],
);
const quickActionHint = quickAction.disabled
@@ -148,7 +148,7 @@ export function ThreadGitControls(props: {
branchName &&
confirmableAction &&
!input.featureBranch &&
requiresDefaultBranchConfirmation(input.action, isDefaultBranch)
requiresDefaultBranchConfirmation(input.action, isDefaultRef)
) {
router.push({
pathname: "/threads/[environmentId]/[threadId]/git-confirm",
@@ -167,7 +167,7 @@ export function ThreadGitControls(props: {
await onRunAction(input);
},
[environmentId, gitStatus, isDefaultBranch, onRunAction, router, threadId],
[environmentId, gitStatus, isDefaultRef, onRunAction, router, threadId],
);
const runQuickAction = useCallback(async () => {
@@ -1,6 +1,8 @@
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo, useState } from "react";
import { 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, {
@@ -22,15 +24,16 @@ import {
EnvironmentScopedThreadShell,
} from "@t3tools/client-runtime";
function compareThreadActivity(
left: EnvironmentScopedThreadShell,
right: EnvironmentScopedThreadShell,
): number {
return (
new Date(right.updatedAt ?? right.createdAt).getTime() -
new Date(left.updatedAt ?? left.createdAt).getTime() || left.title.localeCompare(right.title)
);
}
const threadActivityOrder = Order.mapInput(
Order.Struct({
activityAt: Order.flip(Order.Number),
title: Order.String,
}),
(thread: EnvironmentScopedThreadShell) => ({
activityAt: new Date(thread.updatedAt ?? thread.createdAt).getTime(),
title: thread.title,
}),
);
export function ThreadNavigationDrawer(props: {
readonly visible: boolean;
@@ -60,13 +63,17 @@ export function ThreadNavigationDrawer(props: {
);
const groupedThreads = useMemo(
() =>
repositoryGroups.map((group) => ({
key: group.key,
title: group.projects[0]?.project.title ?? group.title,
threads: group.projects
.flatMap((projectGroup) => projectGroup.threads)
.sort(compareThreadActivity),
})),
repositoryGroups.map((group) => {
const threads: EnvironmentScopedThreadShell[] = [];
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],
);
@@ -181,10 +188,10 @@ export function ThreadNavigationDrawer(props: {
<ScrollView
showsVerticalScrollIndicator={false}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 12 }}
contentContainerStyle={{
gap: 20,
paddingHorizontal: 14,
paddingBottom: Math.max(insets.bottom, 18) + 12,
}}
>
{groupedThreads.map((group) => (
@@ -44,21 +44,21 @@ export function GitBranchesSheet() {
);
const [worktreeBranchName, setWorktreeBranchName] = useState("");
const disabledExistingBranches = new Set(
availableBranches
.filter(
(branch) => branch.worktreePath !== null && branch.worktreePath !== currentWorktreePath,
)
.map((branch) => branch.name),
);
const disabledExistingBranchNames: Array<string> = [];
for (const branch of availableBranches) {
if (branch.worktreePath !== null && branch.worktreePath !== currentWorktreePath) {
disabledExistingBranchNames.push(branch.name);
}
}
const disabledExistingBranches = new Set(disabledExistingBranchNames);
return (
<ScrollView
showsVerticalScrollIndicator={false}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
gap: 16,
}}
>
@@ -33,7 +33,7 @@ export function GitCommitSheet() {
});
const busy = gitState.gitOperationLabel !== null;
const isDefaultBranch = gitStatus.data?.isDefaultRef ?? false;
const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
const allFiles = gitStatus.data?.workingTree?.files ?? [];
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
@@ -65,10 +65,10 @@ export function GitCommitSheet() {
<ScrollView
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
gap: 16,
}}
>
@@ -79,7 +79,7 @@ export function GitCommitSheet() {
{gitStatus.data?.refName ?? "(detached HEAD)"}
</Text>
</View>
{isDefaultBranch ? (
{isDefaultRef ? (
<Text
className="text-[12px] leading-[18px]"
style={{ color: isDarkMode ? "#fbbf24" : "#b45309" }}
@@ -47,7 +47,7 @@ export function GitOverviewSheet() {
const busy = gitOperationLabel !== null;
const isRepo = gitStatus.data?.isRepo ?? true;
const hasPrimaryRemote = gitStatus.data?.hasPrimaryRemote ?? false;
const isDefaultBranch = gitStatus.data?.isDefaultRef ?? false;
const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
const menuItems = useMemo(
() => (isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote) : []),
@@ -62,7 +62,7 @@ export function GitOverviewSheet() {
item,
gitStatus: gitStatus.data,
isBusy: busy,
hasPrimaryRemote,
hasOriginRemote: hasPrimaryRemote,
}),
})),
[busy, gitStatus.data, hasPrimaryRemote, menuItems],
@@ -102,7 +102,7 @@ export function GitOverviewSheet() {
branchName &&
confirmableAction &&
!input.featureBranch &&
requiresDefaultBranchConfirmation(input.action, isDefaultBranch)
requiresDefaultBranchConfirmation(input.action, isDefaultRef)
) {
router.push({
pathname: "/threads/[environmentId]/[threadId]/git-confirm",
@@ -122,7 +122,7 @@ export function GitOverviewSheet() {
router.dismiss();
await gitActions.onRunSelectedThreadGitAction(input);
},
[environmentId, gitActions, gitStatus.data, isDefaultBranch, router, threadId],
[environmentId, gitActions, gitStatus.data, isDefaultRef, router, threadId],
);
const onPressMenuItem = useCallback(
@@ -184,10 +184,10 @@ export function GitOverviewSheet() {
<ScrollView
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
gap: 14,
}}
>
+15 -16
View File
@@ -5,22 +5,26 @@ export type ModelOption = {
readonly label: string;
readonly subtitle: string;
readonly providerKey: string;
readonly providerDriver: string;
readonly providerLabel: string;
readonly providerDriver: string;
readonly selection: ModelSelection;
};
export type ProviderGroup = {
readonly providerKey: string;
readonly providerDriver: string;
readonly providerLabel: string;
readonly models: ReadonlyArray<ModelOption>;
};
function providerDisplayLabel(provider: string): string {
if (provider === "codex") return "Codex";
if (provider === "claudeAgent") return "Claude";
return provider;
function providerDisplayLabel(provider: {
readonly displayName?: string | undefined;
readonly driver: string;
readonly instanceId: string;
}): string {
if (provider.displayName) return provider.displayName;
if (provider.driver === "codex") return "Codex";
if (provider.driver === "claudeAgent") return "Claude";
return provider.instanceId;
}
export function buildModelOptions(
@@ -34,7 +38,7 @@ export function buildModelOptions(
continue;
}
const providerLabel = provider.displayName ?? providerDisplayLabel(provider.driver);
const providerLabel = providerDisplayLabel(provider);
for (const model of provider.models) {
const key = `${provider.instanceId}:${model.slug}`;
options.set(key, {
@@ -42,8 +46,8 @@ export function buildModelOptions(
label: model.name,
subtitle: providerLabel,
providerKey: provider.instanceId,
providerDriver: provider.driver,
providerLabel,
providerDriver: provider.driver,
selection: {
instanceId: provider.instanceId,
model: model.slug,
@@ -55,14 +59,14 @@ export function buildModelOptions(
if (fallbackModelSelection) {
const key = `${fallbackModelSelection.instanceId}:${fallbackModelSelection.model}`;
if (!options.has(key)) {
const providerLabel = providerDisplayLabel(fallbackModelSelection.instanceId);
const providerLabel = fallbackModelSelection.instanceId;
options.set(key, {
key,
label: fallbackModelSelection.model,
subtitle: providerLabel,
providerKey: fallbackModelSelection.instanceId,
providerDriver: fallbackModelSelection.instanceId,
providerLabel,
providerDriver: fallbackModelSelection.instanceId,
selection: fallbackModelSelection,
});
}
@@ -72,17 +76,13 @@ export function buildModelOptions(
}
export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyArray<ProviderGroup> {
const groups = new Map<
string,
{ providerDriver: string; providerLabel: string; models: ModelOption[] }
>();
const groups = new Map<string, { providerLabel: string; models: ModelOption[] }>();
for (const option of options) {
const existing = groups.get(option.providerKey);
if (existing) {
existing.models.push(option);
} else {
groups.set(option.providerKey, {
providerDriver: option.providerDriver,
providerLabel: option.providerLabel,
models: [option],
});
@@ -91,7 +91,6 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
return [...groups.entries()].map(([providerKey, group]) => ({
providerKey,
providerDriver: group.providerDriver,
providerLabel: group.providerLabel,
models: group.models,
}));
+108 -1
View File
@@ -1,12 +1,21 @@
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as SecureStore from "expo-secure-store";
import type { EnvironmentId } from "@t3tools/contracts";
import type { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts";
import type { SavedRemoteConnection } from "./connection";
const CONNECTIONS_KEY = "t3code.connections";
const PREFERENCES_KEY = "t3code.preferences";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
export interface CachedShellSnapshot {
readonly schemaVersion: typeof SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION;
readonly environmentId: EnvironmentId;
readonly snapshotReceivedAt: string;
readonly snapshot: OrchestrationShellSnapshot;
}
export interface MobilePreferences {
readonly terminalFontSize?: number;
@@ -33,6 +42,104 @@ async function readJsonStorageItem<T>(key: string): Promise<T | null> {
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isShellSnapshot(value: unknown): value is OrchestrationShellSnapshot {
if (!isRecord(value)) {
return false;
}
return (
typeof value.snapshotSequence === "number" &&
Array.isArray(value.projects) &&
Array.isArray(value.threads) &&
typeof value.updatedAt === "string"
);
}
function isCachedShellSnapshot(value: unknown): value is CachedShellSnapshot {
if (!isRecord(value)) {
return false;
}
return (
value.schemaVersion === SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION &&
typeof value.environmentId === "string" &&
typeof value.snapshotReceivedAt === "string" &&
isShellSnapshot(value.snapshot)
);
}
function cachedShellSnapshotFileName(environmentId: EnvironmentId): string {
return `${encodeURIComponent(environmentId)}.json`;
}
async function getShellSnapshotCacheDirectory() {
const { Directory, Paths } = await import("expo-file-system");
const directory = new Directory(Paths.document, SHELL_SNAPSHOT_CACHE_DIRECTORY);
directory.create({ idempotent: true, intermediates: true });
return directory;
}
export async function loadCachedShellSnapshot(
environmentId: EnvironmentId,
): Promise<CachedShellSnapshot | null> {
try {
const { File } = await import("expo-file-system");
const directory = await getShellSnapshotCacheDirectory();
const file = new File(directory, cachedShellSnapshotFileName(environmentId));
if (!file.exists) {
return null;
}
const parsed = JSON.parse(await file.text()) as unknown;
if (!isCachedShellSnapshot(parsed) || parsed.environmentId !== environmentId) {
return null;
}
return parsed;
} catch {
return null;
}
}
export async function saveCachedShellSnapshot(
environmentId: EnvironmentId,
snapshot: OrchestrationShellSnapshot,
): Promise<void> {
try {
const { File } = await import("expo-file-system");
const directory = await getShellSnapshotCacheDirectory();
const file = new File(directory, cachedShellSnapshotFileName(environmentId));
const document: CachedShellSnapshot = {
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
snapshotReceivedAt: new Date().toISOString(),
snapshot,
};
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(document));
} catch {
// Cache persistence is best-effort and should never block live data.
}
}
export async function clearCachedShellSnapshot(environmentId: EnvironmentId): Promise<void> {
try {
const { File } = await import("expo-file-system");
const directory = await getShellSnapshotCacheDirectory();
const file = new File(directory, cachedShellSnapshotFileName(environmentId));
if (file.exists) {
file.delete();
}
} catch {
// Ignore cache cleanup failures.
}
}
export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
const parsed = await readJsonStorageItem<{
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
+17 -11
View File
@@ -205,14 +205,16 @@ function deriveWorkLogEntries(
latestTurnId: TurnId | undefined,
): WorkLogEntry[] {
const ordered = Arr.sort(activities, activityOrder);
const entries = ordered
.filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
.filter((activity) => activity.kind !== "tool.started")
.filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
.filter((activity) => activity.kind !== "context-window.updated")
.filter((activity) => activity.summary !== "Checkpoint captured")
.filter((activity) => !isPlanBoundaryToolActivity(activity))
.map(toDerivedWorkLogEntry);
const entries: DerivedWorkLogEntry[] = [];
for (const activity of ordered) {
if (latestTurnId && activity.turnId !== latestTurnId) continue;
if (activity.kind === "tool.started") continue;
if (activity.kind === "task.started" || activity.kind === "task.completed") continue;
if (activity.kind === "context-window.updated") continue;
if (activity.summary === "Checkpoint captured") continue;
if (isPlanBoundaryToolActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
}
return collapseDerivedWorkLogEntries(entries).map(
({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
);
@@ -525,9 +527,13 @@ function formatCommandValue(value: unknown): string | null {
if (!Array.isArray(value)) {
return null;
}
const parts = value
.map((entry) => asTrimmedString(entry))
.filter((entry): entry is string => entry !== null);
const parts: Array<string> = [];
for (const entry of value) {
const part = asTrimmedString(entry);
if (part !== null) {
parts.push(part);
}
}
if (parts.length === 0) {
return null;
}
@@ -0,0 +1,82 @@
import { useAtomValue } from "@effect/atom-react";
import {
EMPTY_FILESYSTEM_BROWSE_ATOM,
EMPTY_FILESYSTEM_BROWSE_STATE,
type FilesystemBrowseClient,
type FilesystemBrowseState,
type FilesystemBrowseTarget,
createFilesystemBrowseManager,
filesystemBrowseStateAtom,
getFilesystemBrowseTargetKey,
} from "@t3tools/client-runtime";
import type {
EnvironmentId,
FilesystemBrowseInput,
FilesystemBrowseResult,
} from "@t3tools/contracts";
import { useEffect, useMemo } from "react";
import { appAtomRegistry } from "./atom-registry";
import {
getEnvironmentClient,
subscribeEnvironmentConnections,
} from "./environment-session-registry";
const filesystemBrowseManager = createFilesystemBrowseManager<EnvironmentId>({
getRegistry: () => appAtomRegistry,
getClient: (environmentId) => getEnvironmentClient(environmentId)?.filesystem ?? null,
subscribeClientChanges: subscribeEnvironmentConnections,
});
function filesystemBrowseTargetForEnvironment(
environmentId: EnvironmentId | null,
input: FilesystemBrowseInput | null,
): FilesystemBrowseTarget<EnvironmentId> {
return { key: environmentId, input };
}
export function refreshFilesystemBrowseForEnvironment(
environmentId: EnvironmentId | null,
input: FilesystemBrowseInput | null,
client?: FilesystemBrowseClient | null,
): Promise<FilesystemBrowseResult | null> {
return filesystemBrowseManager.refresh(
filesystemBrowseTargetForEnvironment(environmentId, input),
client ?? undefined,
);
}
export function invalidateFilesystemBrowseForEnvironment(
environmentId: EnvironmentId | null,
input: FilesystemBrowseInput | null,
): void {
filesystemBrowseManager.invalidate(filesystemBrowseTargetForEnvironment(environmentId, input));
}
export function resetFilesystemBrowseState(): void {
filesystemBrowseManager.reset();
}
export function resetFilesystemBrowseStateForTests(): void {
resetFilesystemBrowseState();
}
export function useFilesystemBrowse(
environmentId: EnvironmentId | null,
input: FilesystemBrowseInput | null,
): FilesystemBrowseState {
const target = useMemo(
() => filesystemBrowseTargetForEnvironment(environmentId, input),
[environmentId, input],
);
useEffect(() => {
return filesystemBrowseManager.watch(target);
}, [target]);
const targetKey = getFilesystemBrowseTargetKey(target);
const state = useAtomValue(
targetKey !== null ? filesystemBrowseStateAtom(targetKey) : EMPTY_FILESYSTEM_BROWSE_ATOM,
);
return targetKey === null ? EMPTY_FILESYSTEM_BROWSE_STATE : state;
}
+122 -39
View File
@@ -11,23 +11,33 @@ import {
} from "@t3tools/client-runtime";
import { ConnectedEnvironmentSummary } from "./remote-runtime-types";
import { useShellSnapshotStates } from "./use-shell-snapshot";
import type { SavedRemoteConnection } from "../lib/connection";
import { useCachedShellSnapshotMetadata, useShellSnapshotStates } from "./use-shell-snapshot";
import {
useRemoteConnectionStatus,
useRemoteEnvironmentState,
} from "./use-remote-environment-registry";
const projectsSortOrder = Order.make<EnvironmentScopedProjectShell>(
(left, right) =>
(left.title.localeCompare(right.title) as -1 | 0 | 1) ||
(left.environmentId.localeCompare(right.environmentId) as -1 | 0 | 1),
const projectsSortOrder = Order.mapInput(
Order.Struct({
title: Order.String,
environmentId: Order.String,
}),
(project: EnvironmentScopedProjectShell) => ({
title: project.title,
environmentId: project.environmentId,
}),
);
const threadsSortOrder = Order.make<EnvironmentScopedThreadShell>(
(left, right) =>
((new Date(right.updatedAt ?? right.createdAt).getTime() -
new Date(left.updatedAt ?? left.createdAt).getTime()) as -1 | 0 | 1) ||
(left.environmentId.localeCompare(right.environmentId) as -1 | 0 | 1),
const threadsSortOrder = Order.mapInput(
Order.Struct({
activityAt: Order.flip(Order.Number),
environmentId: Order.String,
}),
(thread: EnvironmentScopedThreadShell) => ({
activityAt: new Date(thread.updatedAt ?? thread.createdAt).getTime(),
environmentId: thread.environmentId,
}),
);
function deriveOverallConnectionState(
@@ -48,38 +58,62 @@ function deriveOverallConnectionState(
return "disconnected";
}
function listRemoteCatalogEnvironmentIds(
savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>,
): ReadonlyArray<SavedRemoteConnection["environmentId"]> {
const environmentIds: SavedRemoteConnection["environmentId"][] = [];
for (const connection of Object.values(savedConnectionsById)) {
environmentIds.push(connection.environmentId);
}
return environmentIds;
}
export interface RemoteCatalogState {
readonly isLoadingSavedConnections: boolean;
readonly hasSavedConnections: boolean;
readonly hasLoadedShellSnapshot: boolean;
readonly hasPendingShellSnapshot: boolean;
readonly hasReadyEnvironment: boolean;
readonly hasConnectingEnvironment: boolean;
readonly connectionState: EnvironmentConnectionState;
readonly connectionError: string | null;
readonly shellSnapshotError: string | null;
readonly isUsingCachedData: boolean;
readonly latestCachedSnapshotReceivedAt: string | null;
}
export function useRemoteCatalog() {
const { connectedEnvironments, connectionState } = useRemoteConnectionStatus();
const { environmentStateById, savedConnectionsById } = useRemoteEnvironmentState();
const shellSnapshotStates = useShellSnapshotStates(
Object.values(savedConnectionsById).map((connection) => connection.environmentId),
const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
const { environmentStateById, isLoadingSavedConnection, savedConnectionsById } =
useRemoteEnvironmentState();
const catalogEnvironmentIds = useMemo(
() => listRemoteCatalogEnvironmentIds(savedConnectionsById),
[savedConnectionsById],
);
const shellSnapshotStates = useShellSnapshotStates(catalogEnvironmentIds);
const cachedShellSnapshotMetadata = useCachedShellSnapshotMetadata();
const projects = useMemo(
() =>
Arr.sort(
Object.values(savedConnectionsById).flatMap((connection) =>
(shellSnapshotStates[connection.environmentId]?.data?.projects ?? []).map((project) =>
scopeProjectShell(connection.environmentId, project),
),
),
projectsSortOrder,
),
[savedConnectionsById, shellSnapshotStates],
);
const projects = useMemo(() => {
const scopedProjects: EnvironmentScopedProjectShell[] = [];
for (const connection of Object.values(savedConnectionsById)) {
const projects = shellSnapshotStates[connection.environmentId]?.data?.projects ?? [];
for (const project of projects) {
scopedProjects.push(scopeProjectShell(connection.environmentId, project));
}
}
return Arr.sort(scopedProjects, projectsSortOrder);
}, [savedConnectionsById, shellSnapshotStates]);
const threads = useMemo(
() =>
Arr.sort(
Object.values(savedConnectionsById).flatMap((connection) =>
(shellSnapshotStates[connection.environmentId]?.data?.threads ?? []).map((thread) =>
scopeThreadShell(connection.environmentId, thread),
),
),
threadsSortOrder,
),
[savedConnectionsById, shellSnapshotStates],
);
const threads = useMemo(() => {
const scopedThreads: EnvironmentScopedThreadShell[] = [];
for (const connection of Object.values(savedConnectionsById)) {
const threads = shellSnapshotStates[connection.environmentId]?.data?.threads ?? [];
for (const thread of threads) {
scopedThreads.push(scopeThreadShell(connection.environmentId, thread));
}
}
return Arr.sort(scopedThreads, threadsSortOrder);
}, [savedConnectionsById, shellSnapshotStates]);
const serverConfigByEnvironmentId = useMemo(
() =>
@@ -105,11 +139,60 @@ export function useRemoteCatalog() {
[threads],
);
const state = useMemo<RemoteCatalogState>(() => {
const shellSnapshots = Object.values(shellSnapshotStates);
const cachedSnapshotReceivedAts: string[] = [];
for (const environmentId of catalogEnvironmentIds) {
const metadata = cachedShellSnapshotMetadata[environmentId];
if (metadata) {
cachedSnapshotReceivedAts.push(metadata.snapshotReceivedAt);
}
}
let shellSnapshotError: string | null = null;
for (const snapshot of shellSnapshots) {
if (snapshot.error !== null) {
shellSnapshotError = snapshot.error;
break;
}
}
return {
isLoadingSavedConnections: isLoadingSavedConnection,
hasSavedConnections: catalogEnvironmentIds.length > 0,
hasLoadedShellSnapshot: shellSnapshots.some((snapshot) => snapshot.data !== null),
hasPendingShellSnapshot: shellSnapshots.some((snapshot) => snapshot.isPending),
hasReadyEnvironment: connectedEnvironments.some(
(environment) => environment.connectionState === "ready",
),
hasConnectingEnvironment: connectedEnvironments.some(
(environment) =>
environment.connectionState === "connecting" ||
environment.connectionState === "reconnecting",
),
connectionState: connectionState ?? overallConnectionState,
connectionError,
shellSnapshotError,
isUsingCachedData: cachedSnapshotReceivedAts.length > 0,
latestCachedSnapshotReceivedAt:
Arr.sort(cachedSnapshotReceivedAts, Order.flip(Order.String))[0] ?? null,
};
}, [
cachedShellSnapshotMetadata,
catalogEnvironmentIds,
connectedEnvironments,
connectionError,
connectionState,
isLoadingSavedConnection,
overallConnectionState,
shellSnapshotStates,
]);
return {
projects,
threads,
serverConfigByEnvironmentId,
connectionState: connectionState ?? overallConnectionState,
connectionState: state.connectionState,
connectionError: state.connectionError,
state,
hasRemoteActivity,
};
}
@@ -19,7 +19,14 @@ import { pipe } from "effect/Function";
import { Atom } from "effect/unstable/reactivity";
import { type SavedRemoteConnection, bootstrapRemoteConnection } from "../lib/connection";
import { terminalDebugLog } from "../features/terminal/terminalDebugLog";
import { clearSavedConnection, loadSavedConnections, saveConnection } from "../lib/storage";
import {
clearCachedShellSnapshot,
clearSavedConnection,
loadCachedShellSnapshot,
loadSavedConnections,
saveCachedShellSnapshot,
saveConnection,
} from "../lib/storage";
import { appAtomRegistry } from "./atom-registry";
import {
drainEnvironmentSessions,
@@ -33,10 +40,16 @@ import {
resetSourceControlDiscoveryState,
} from "./use-source-control-discovery";
import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime";
import { shellSnapshotManager } from "./use-shell-snapshot";
import {
clearCachedShellSnapshotMetadata,
hydrateCachedShellSnapshot,
markShellSnapshotLive,
shellSnapshotManager,
} from "./use-shell-snapshot";
import { subscribeTerminalMetadata, terminalSessionManager } from "./use-terminal-session";
const terminalMetadataUnsubscribers = new Map<EnvironmentId, () => void>();
const SAVED_CONNECTION_BOOTSTRAP_TIMEOUT_MS = 8_000;
interface RemoteEnvironmentLocalState {
readonly isLoadingSavedConnection: boolean;
@@ -137,22 +150,49 @@ function setEnvironmentConnectionStatus(
}));
}
function withTimeout<T>(
promise: Promise<T>,
timeoutMs: number,
timeoutMessage: string,
): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error(timeoutMessage));
}, timeoutMs);
promise.then(
(value) => {
clearTimeout(timeoutId);
resolve(value);
},
(error: unknown) => {
clearTimeout(timeoutId);
reject(error);
},
);
});
}
export async function disconnectEnvironment(
environmentId: EnvironmentId,
options?: { readonly removeSaved?: boolean },
options?: { readonly preserveShellSnapshot?: boolean; readonly removeSaved?: boolean },
) {
const session = removeEnvironmentSession(environmentId);
notifyEnvironmentConnectionListeners();
await session?.connection.dispose();
terminalMetadataUnsubscribers.get(environmentId)?.();
terminalMetadataUnsubscribers.delete(environmentId);
shellSnapshotManager.invalidate({ environmentId });
if (!options?.preserveShellSnapshot) {
shellSnapshotManager.invalidate({ environmentId });
}
invalidateSourceControlDiscoveryForEnvironment(environmentId);
terminalSessionManager.invalidateEnvironment(environmentId);
environmentRuntimeManager.invalidate({ environmentId });
if (options?.removeSaved) {
await clearSavedConnection(environmentId);
await clearCachedShellSnapshot(environmentId);
clearCachedShellSnapshotMetadata(environmentId);
removeSavedConnection(environmentId);
}
}
@@ -161,7 +201,7 @@ export async function connectSavedEnvironment(
connection: SavedRemoteConnection,
options?: { readonly persist?: boolean },
) {
await disconnectEnvironment(connection.environmentId);
await disconnectEnvironment(connection.environmentId, { preserveShellSnapshot: true });
if (options?.persist !== false) {
await saveConnection(connection);
@@ -182,15 +222,15 @@ export async function connectSavedEnvironment(
onAttempt: () => {
environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (previous) => {
const nextState =
previous.connectionState === "ready" ||
previous.connectionState === "reconnecting" ||
previous.connectionState === "disconnected"
previous.connectionState === "ready" || previous.connectionState === "reconnecting"
? "reconnecting"
: "connecting";
const keepSettledFailure =
previous.connectionState === "disconnected" && previous.connectionError !== null;
return {
...previous,
connectionState: nextState,
connectionError: null,
connectionState: keepSettledFailure ? "disconnected" : nextState,
connectionError: keepSettledFailure ? previous.connectionError : null,
};
});
},
@@ -230,6 +270,8 @@ export async function connectSavedEnvironment(
},
syncShellSnapshot: (snapshot, environmentId) => {
shellSnapshotManager.syncSnapshot({ environmentId }, snapshot);
markShellSnapshotLive(environmentId);
void saveCachedShellSnapshot(environmentId, snapshot);
environmentRuntimeManager.patch({ environmentId }, (runtime) => ({
...runtime,
connectionState: "ready",
@@ -264,7 +306,11 @@ export async function connectSavedEnvironment(
notifyEnvironmentConnectionListeners();
try {
await environmentConnection.ensureBootstrapped();
await withTimeout(
environmentConnection.ensureBootstrapped(),
SAVED_CONNECTION_BOOTSTRAP_TIMEOUT_MS,
"Environment did not respond before the connection timeout.",
);
} catch (error) {
setEnvironmentConnectionStatus(
connection.environmentId,
@@ -274,8 +320,13 @@ export async function connectSavedEnvironment(
}
}
const environmentsSortOrder = Order.make<ConnectedEnvironmentSummary>(
(left, right) => left.environmentLabel.localeCompare(right.environmentLabel) as -1 | 0 | 1,
const environmentsSortOrder = Order.mapInput(
Order.Struct({
environmentLabel: Order.String,
}),
(environment: ConnectedEnvironmentSummary) => ({
environmentLabel: environment.environmentLabel,
}),
);
function deriveConnectedEnvironments(
@@ -315,13 +366,28 @@ export function useRemoteEnvironmentBootstrap() {
setIsLoadingSavedConnection(false);
void Promise.all(
connections.map((connection) =>
connectSavedEnvironment(connection, {
persist: false,
void (async () => {
await Promise.all(
connections.map(async (connection) => {
const cached = await loadCachedShellSnapshot(connection.environmentId);
if (!cancelled && cached) {
hydrateCachedShellSnapshot(cached);
}
}),
),
);
);
if (cancelled) {
return;
}
await Promise.all(
connections.map((connection) =>
connectSavedEnvironment(connection, {
persist: false,
}),
),
);
})();
})
.catch(() => {
if (!cancelled) {
@@ -410,7 +476,7 @@ export function useRemoteConnectionStatus() {
}
export function useRemoteConnections() {
const { connectionPairingUrl } = useRemoteEnvironmentState();
const { connectionPairingUrl, pendingConnectionError } = useRemoteEnvironmentState();
const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
const onConnectPress = useCallback(
@@ -487,6 +553,7 @@ export function useRemoteConnections() {
connectionPairingUrl,
connectionState,
connectionError,
pairingConnectionError: pendingConnectionError,
connectedEnvironments,
connectedEnvironmentCount: connectedEnvironments.length,
onChangeConnectionPairingUrl: setConnectionPairingUrl,
@@ -1,6 +1,7 @@
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useAtomValue } from "@effect/atom-react";
import { Atom } from "effect/unstable/reactivity";
import {
EMPTY_SHELL_SNAPSHOT_ATOM,
EMPTY_SHELL_SNAPSHOT_STATE,
@@ -13,11 +14,47 @@ import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
import { appAtomRegistry } from "./atom-registry";
import type { CachedShellSnapshot } from "../lib/storage";
const cachedShellSnapshotMetadataAtom = Atom.make<
Readonly<Record<EnvironmentId, { readonly snapshotReceivedAt: string }>>
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:cached-shell-snapshot-metadata"));
export const shellSnapshotManager = createShellSnapshotManager({
getRegistry: () => appAtomRegistry,
});
export function hydrateCachedShellSnapshot(cached: CachedShellSnapshot): void {
shellSnapshotManager.syncSnapshot({ environmentId: cached.environmentId }, cached.snapshot);
appAtomRegistry.set(cachedShellSnapshotMetadataAtom, {
...appAtomRegistry.get(cachedShellSnapshotMetadataAtom),
[cached.environmentId]: {
snapshotReceivedAt: cached.snapshotReceivedAt,
},
});
}
export function markShellSnapshotLive(environmentId: EnvironmentId): void {
const current = appAtomRegistry.get(cachedShellSnapshotMetadataAtom);
if (current[environmentId] === undefined) {
return;
}
const next = { ...current };
delete next[environmentId];
appAtomRegistry.set(cachedShellSnapshotMetadataAtom, next);
}
export function clearCachedShellSnapshotMetadata(environmentId: EnvironmentId): void {
markShellSnapshotLive(environmentId);
}
export function useCachedShellSnapshotMetadata(): Readonly<
Record<EnvironmentId, { readonly snapshotReceivedAt: string }>
> {
return useAtomValue(cachedShellSnapshotMetadataAtom);
}
export function useShellSnapshot(environmentId: EnvironmentId | null): ShellSnapshotState {
const targetKey = getShellSnapshotTargetKey({ environmentId });
const state = useAtomValue(
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.23",
"version": "0.0.24",
"license": "MIT",
"repository": {
"type": "git",
@@ -20,13 +20,13 @@
"build:bundle": "tsdown",
"start": "node dist/bin.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@opencode-ai/sdk": "^1.3.15",
"@pierre/diffs": "catalog:",
+16 -10
View File
@@ -64,11 +64,16 @@ export const makeAuthControlPlane = Effect.gen(function* () {
const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
bootstrapCredentials.listActive().pipe(
Effect.map((pairingLinks) =>
pairingLinks
.filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
.filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
.map((pairingLink) =>
Effect.map((pairingLinks) => {
const activeLinks: Array<AuthPairingLink> = [];
for (const pairingLink of pairingLinks) {
if (input?.role && pairingLink.role !== input.role) {
continue;
}
if (input?.excludeSubjects?.includes(pairingLink.subject)) {
continue;
}
activeLinks.push(
pairingLink.label
? ({
id: pairingLink.id,
@@ -87,11 +92,12 @@ export const makeAuthControlPlane = Effect.gen(function* () {
createdAt: pairingLink.createdAt,
expiresAt: pairingLink.expiresAt,
} satisfies AuthPairingLink),
)
.toSorted(
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
),
),
);
}
return activeLinks.toSorted(
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
);
}),
Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
);
@@ -15,7 +15,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
interface ProcessRow {
export interface ProcessRow {
readonly pid: number;
readonly ppid: number;
readonly pgid: number | null;
@@ -186,7 +186,7 @@ function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
}
}
function buildDescendantEntries(
export function buildDescendantEntries(
rows: ReadonlyArray<ProcessRow>,
serverPid: number,
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
@@ -230,7 +230,7 @@ function buildDescendantEntries(
return entries;
}
function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
export function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
if (row.ppid !== serverPid) return false;
const command = row.command.trim();
@@ -370,7 +370,7 @@ function readWindowsProcessRows(): Effect.Effect<
);
}
const readProcessRows = (platform = process.platform) =>
export const readProcessRows = (platform = process.platform) =>
platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
export function aggregateProcessDiagnostics(input: {
@@ -0,0 +1,231 @@
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import {
aggregateProcessResourceHistory,
collectMonitoredSamples,
} from "./ProcessResourceMonitor.ts";
describe("ProcessResourceMonitor", () => {
it.effect("samples the server root process and descendants", () =>
Effect.sync(() => {
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const samples = collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 2,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
{
pid: 101,
ppid: 100,
pgid: 100,
status: "S",
cpuPercent: 10,
rssBytes: 2_000,
elapsed: "00:20",
command: "codex app-server",
},
{
pid: 102,
ppid: 101,
pgid: 100,
status: "R",
cpuPercent: 50,
rssBytes: 3_000,
elapsed: "00:05",
command: "rg needle",
},
{
pid: 200,
ppid: 1,
pgid: 200,
status: "R",
cpuPercent: 99,
rssBytes: 9_000,
elapsed: "00:05",
command: "unrelated",
},
],
});
expect(samples.map((sample) => sample.pid)).toEqual([100, 101, 102]);
expect(samples.map((sample) => sample.depth)).toEqual([0, 1, 2]);
expect(samples[0]?.isServerRoot).toBe(true);
expect(samples[1]?.isServerRoot).toBe(false);
}),
);
it.effect("rolls samples up by process and CPU time", () =>
Effect.sync(() => {
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.000Z");
const samples = [
...collectMonitoredSamples({
serverPid: 100,
sampledAt: firstAt,
sampledAtMs: DateTime.toEpochMillis(firstAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 10,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
],
}),
...collectMonitoredSamples({
serverPid: 100,
sampledAt: secondAt,
sampledAtMs: DateTime.toEpochMillis(secondAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 30,
rssBytes: 2_000,
elapsed: "01:05",
command: "t3 server",
},
],
}),
];
const result = aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
expect(Option.isNone(result.error)).toBe(true);
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.avgCpuPercent).toBe(20);
expect(result.topProcesses[0]?.maxCpuPercent).toBe(30);
expect(result.topProcesses[0]?.cpuSecondsApprox).toBe(2);
expect(result.totalCpuSecondsApprox).toBe(2);
expect(result.buckets.some((bucket) => bucket.maxCpuPercent === 30)).toBe(true);
}),
);
it.effect("keeps a process grouped when elapsed time drifts between samples", () =>
Effect.sync(() => {
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.400Z");
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.900Z");
const samples = [
...collectMonitoredSamples({
serverPid: 100,
sampledAt: firstAt,
sampledAtMs: DateTime.toEpochMillis(firstAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 1,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
],
}),
...collectMonitoredSamples({
serverPid: 100,
sampledAt: secondAt,
sampledAtMs: DateTime.toEpochMillis(secondAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 2,
rssBytes: 2_000,
elapsed: "01:06",
command: "t3 server",
},
],
}),
];
const result = aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.isServerRoot).toBe(true);
expect(result.topProcesses[0]?.sampleCount).toBe(2);
expect(result.topProcesses[0]?.maxRssBytes).toBe(2_000);
}),
);
it.effect("returns all process summaries in the selected window", () =>
Effect.sync(() => {
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const samples = collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 1,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
...Array.from({ length: 35 }, (_, index) => ({
pid: 200 + index,
ppid: index === 0 ? 100 : 199 + index,
pgid: 100,
status: "S",
cpuPercent: 35 - index,
rssBytes: 2_000 + index,
elapsed: "00:10",
command: `worker ${index}`,
})),
],
});
const result = aggregateProcessResourceHistory({
samples,
readAt: sampledAt,
readAtMs: DateTime.toEpochMillis(sampledAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
expect(result.topProcesses).toHaveLength(36);
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
}),
);
});
@@ -0,0 +1,299 @@
import type {
ServerProcessResourceHistoryBucket,
ServerProcessResourceHistoryInput,
ServerProcessResourceHistoryResult,
ServerProcessResourceHistorySummary,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
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 { ChildProcessSpawner } from "effect/unstable/process";
import {
buildDescendantEntries,
isDiagnosticsQueryProcess,
type ProcessRow,
readProcessRows,
} from "./ProcessDiagnostics.ts";
const SAMPLE_INTERVAL_MS = 5_000;
const RETENTION_MS = 60 * 60_000;
const MAX_RETAINED_SAMPLES = 20_000;
export interface ProcessResourceSample {
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
readonly processKey: string;
readonly pid: number;
readonly ppid: number;
readonly command: string;
readonly cpuPercent: number;
readonly rssBytes: number;
readonly depth: number;
readonly isServerRoot: boolean;
}
interface MonitorState {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly lastError: string | null;
}
export interface ProcessResourceMonitorShape {
readonly readHistory: (
input: ServerProcessResourceHistoryInput,
) => Effect.Effect<ServerProcessResourceHistoryResult>;
}
export class ProcessResourceMonitor extends Context.Service<
ProcessResourceMonitor,
ProcessResourceMonitorShape
>()("t3/diagnostics/ProcessResourceMonitor") {}
function dateTimeFromMillis(ms: number): DateTime.Utc {
return DateTime.makeUnsafe(ms);
}
function sampleKey(row: Pick<ProcessRow, "pid" | "command">): string {
return `${row.pid}:${row.command}`;
}
function findServerRootRow(rows: ReadonlyArray<ProcessRow>, serverPid: number): ProcessRow | null {
return rows.find((row) => row.pid === serverPid) ?? null;
}
export function collectMonitoredSamples(input: {
readonly rows: ReadonlyArray<ProcessRow>;
readonly serverPid: number;
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
}): ReadonlyArray<ProcessResourceSample> {
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
const root = findServerRootRow(rows, input.serverPid);
const descendants = buildDescendantEntries(rows, input.serverPid);
const samples: ProcessResourceSample[] = [];
if (root) {
samples.push({
sampledAt: input.sampledAt,
sampledAtMs: input.sampledAtMs,
processKey: sampleKey(root),
pid: root.pid,
ppid: root.ppid,
command: root.command,
cpuPercent: root.cpuPercent,
rssBytes: root.rssBytes,
depth: 0,
isServerRoot: true,
});
}
for (const process of descendants) {
samples.push({
sampledAt: input.sampledAt,
sampledAtMs: input.sampledAtMs,
processKey: sampleKey(process),
pid: process.pid,
ppid: process.ppid,
command: process.command,
cpuPercent: process.cpuPercent,
rssBytes: process.rssBytes,
depth: process.depth + 1,
isServerRoot: false,
});
}
return samples;
}
function trimSamples(
samples: ReadonlyArray<ProcessResourceSample>,
nowMs: number,
): ReadonlyArray<ProcessResourceSample> {
const minSampledAtMs = nowMs - RETENTION_MS;
const retained = samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
return retained.length <= MAX_RETAINED_SAMPLES
? retained
: retained.slice(retained.length - MAX_RETAINED_SAMPLES);
}
function summarizeProcesses(
samples: ReadonlyArray<ProcessResourceSample>,
): ReadonlyArray<ServerProcessResourceHistorySummary> {
const groups = new Map<string, ProcessResourceSample[]>();
for (const sample of samples) {
const processSamples = groups.get(sample.processKey) ?? [];
processSamples.push(sample);
groups.set(sample.processKey, processSamples);
}
return [...groups.entries()]
.map(([processKey, processSamples]) => {
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
const first = sorted[0]!;
const latest = sorted[sorted.length - 1]!;
const cpuPercentTotal = sorted.reduce((total, sample) => total + sample.cpuPercent, 0);
const maxCpuPercent = Math.max(...sorted.map((sample) => sample.cpuPercent));
const maxRssBytes = Math.max(...sorted.map((sample) => sample.rssBytes));
const cpuSecondsApprox = sorted.reduce(
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
0,
);
return {
processKey,
pid: latest.pid,
ppid: latest.ppid,
command: latest.command,
depth: latest.depth,
isServerRoot: latest.isServerRoot,
firstSeenAt: first.sampledAt,
lastSeenAt: latest.sampledAt,
currentCpuPercent: latest.cpuPercent,
avgCpuPercent: cpuPercentTotal / sorted.length,
maxCpuPercent,
cpuSecondsApprox,
currentRssBytes: latest.rssBytes,
maxRssBytes,
sampleCount: sorted.length,
} satisfies ServerProcessResourceHistorySummary;
})
.toSorted((left, right) => right.cpuSecondsApprox - left.cpuSecondsApprox);
}
function buildBuckets(input: {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly nowMs: number;
readonly windowMs: number;
readonly bucketMs: number;
}): ReadonlyArray<ServerProcessResourceHistoryBucket> {
const bucketMs = Math.max(1_000, input.bucketMs);
const windowStartMs = input.nowMs - input.windowMs;
const buckets: ServerProcessResourceHistoryBucket[] = [];
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += bucketMs) {
const endedAtMs = Math.min(input.nowMs, startedAtMs + bucketMs);
const bucketSamples = input.samples.filter(
(sample) =>
sample.sampledAtMs >= startedAtMs &&
(endedAtMs === input.nowMs
? sample.sampledAtMs <= endedAtMs
: sample.sampledAtMs < endedAtMs),
);
const samplesByRead = new Map<number, ProcessResourceSample[]>();
for (const sample of bucketSamples) {
const samplesAtTime = samplesByRead.get(sample.sampledAtMs) ?? [];
samplesAtTime.push(sample);
samplesByRead.set(sample.sampledAtMs, samplesAtTime);
}
const readTotals = [...samplesByRead.values()].map((samplesAtTime) => ({
cpuPercent: samplesAtTime.reduce((total, sample) => total + sample.cpuPercent, 0),
rssBytes: samplesAtTime.reduce((total, sample) => total + sample.rssBytes, 0),
processCount: samplesAtTime.length,
}));
const avgCpuPercent =
readTotals.length === 0
? 0
: readTotals.reduce((total, read) => total + read.cpuPercent, 0) / readTotals.length;
buckets.push({
startedAt: dateTimeFromMillis(startedAtMs),
endedAt: dateTimeFromMillis(endedAtMs),
avgCpuPercent,
maxCpuPercent: readTotals.length ? Math.max(...readTotals.map((read) => read.cpuPercent)) : 0,
maxRssBytes: readTotals.length ? Math.max(...readTotals.map((read) => read.rssBytes)) : 0,
maxProcessCount: readTotals.length
? Math.max(...readTotals.map((read) => read.processCount))
: 0,
});
}
return buckets;
}
export function aggregateProcessResourceHistory(input: {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly readAt: DateTime.Utc;
readonly readAtMs: number;
readonly windowMs: number;
readonly bucketMs: number;
readonly lastError: string | null;
}): ServerProcessResourceHistoryResult {
const windowMs = Math.max(1_000, input.windowMs);
const bucketMs = Math.max(1_000, input.bucketMs);
const minSampledAtMs = input.readAtMs - windowMs;
const samples = input.samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
const topProcesses = summarizeProcesses(samples);
const totalCpuSecondsApprox = samples.reduce(
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
0,
);
return {
readAt: input.readAt,
windowMs,
bucketMs,
sampleIntervalMs: SAMPLE_INTERVAL_MS,
retainedSampleCount: input.samples.length,
totalCpuSecondsApprox,
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
topProcesses,
error: input.lastError ? Option.some({ message: input.lastError }) : Option.none(),
};
}
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: null });
const sampleOnce = Effect.gen(function* () {
const sampledAt = yield* DateTime.now;
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
const rows = yield* readProcessRows().pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const samples = collectMonitoredSamples({
rows,
serverPid: process.pid,
sampledAt,
sampledAtMs,
});
yield* Ref.update(state, (current) => ({
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
lastError: null,
}));
}).pipe(
Effect.catch((error: unknown) =>
Ref.update(state, (current) => ({
...current,
lastError: error instanceof Error ? error.message : "Failed to sample process resources.",
})),
),
);
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
Effect.forkScoped,
);
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
Effect.gen(function* () {
const readAt = yield* DateTime.now;
const readAtMs = DateTime.toEpochMillis(readAt);
const current = yield* Ref.get(state);
return aggregateProcessResourceHistory({
samples: current.samples,
readAt,
readAtMs,
windowMs: input.windowMs,
bucketMs: input.bucketMs,
lastError: current.lastError,
});
});
return ProcessResourceMonitor.of({ readHistory });
});
export const layer = Layer.effect(ProcessResourceMonitor, make());
+8 -4
View File
@@ -1,8 +1,12 @@
export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
const remoteNames: Array<string> = [];
for (const line of stdout.split("\n")) {
const remoteName = line.trim();
if (remoteName.length > 0) {
remoteNames.push(remoteName);
}
}
return remoteNames;
}
export function parseRemoteNames(stdout: string): ReadonlyArray<string> {
+7 -4
View File
@@ -35,10 +35,13 @@ export function parseBase64DataUrl(
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
if (!match) return null;
const headerParts = (match[1] ?? "")
.split(";")
.map((part) => part.trim())
.filter((part) => part.length > 0);
const headerParts: Array<string> = [];
for (const part of (match[1] ?? "").split(";")) {
const trimmed = part.trim();
if (trimmed.length > 0) {
headerParts.push(trimmed);
}
}
if (headerParts.length < 2) {
return null;
}
+6 -3
View File
@@ -32,6 +32,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
import * as PubSub from "effect/PubSub";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as SchemaTransformation from "effect/SchemaTransformation";
@@ -538,9 +539,11 @@ const makeKeybindings = Effect.gen(function* () {
return;
}
const matchingDefaults = DEFAULT_KEYBINDINGS.filter((defaultRule) =>
customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule)),
).map((rule) => rule.command);
const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>
customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))
? Result.succeed(defaultRule.command)
: Result.failVoid,
);
if (matchingDefaults.length > 0) {
yield* Effect.logWarning("default keybinding rule already defined in user config", {
path: keybindingsConfigPath,
@@ -18,6 +18,7 @@ const DEFAULT_RPC_SPAN_ATTRIBUTES = {
const RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet<string> = new Set([
WS_METHODS.serverGetTraceDiagnostics,
WS_METHODS.serverGetProcessDiagnostics,
WS_METHODS.serverGetProcessResourceHistory,
WS_METHODS.serverSignalProcess,
]);
@@ -1,5 +1,6 @@
import {
CommandId,
type CheckpointRef,
EventId,
MessageId,
type ProjectId,
@@ -683,9 +684,12 @@ const make = Effect.gen(function* () {
});
}
const staleCheckpointRefs = thread.checkpoints
.filter((checkpoint) => checkpoint.checkpointTurnCount > event.payload.turnCount)
.map((checkpoint) => checkpoint.checkpointRef);
const staleCheckpointRefs: Array<CheckpointRef> = [];
for (const checkpoint of thread.checkpoints) {
if (checkpoint.checkpointTurnCount > event.payload.turnCount) {
staleCheckpointRefs.push(checkpoint.checkpointRef);
}
}
if (staleCheckpointRefs.length > 0) {
yield* checkpointStore.deleteCheckpointRefs({
@@ -536,12 +536,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
projectionPendingApprovalRepository.listByThreadId({ threadId }),
]);
const latestUserMessageAt =
messages
.filter((message) => message.role === "user")
.map((message) => message.createdAt)
.toSorted()
.at(-1) ?? null;
let latestUserMessageAt: string | null = null;
for (const message of messages) {
if (
message.role === "user" &&
(latestUserMessageAt === null || message.createdAt > latestUserMessageAt)
) {
latestUserMessageAt = message.createdAt;
}
}
const pendingApprovalCount = pendingApprovals.filter(
(approval) => approval.status === "pending",
@@ -24,9 +24,11 @@ import {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
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";
@@ -1488,34 +1490,36 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
projects: projectRows
.filter((row) => row.deletedAt === null)
.map((row) =>
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
),
threads: threadRows
.filter((row) => row.deletedAt === null)
.map(
(row): OrchestrationThreadShell => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
}),
),
projects: Arr.filterMap(projectRows, (row) =>
row.deletedAt === null
? Result.succeed(
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
)
: Result.failVoid,
),
threads: Arr.filterMap(threadRows, (row) =>
row.deletedAt === null
? Result.succeed({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
} satisfies OrchestrationThreadShell)
: Result.failVoid,
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
};
@@ -1621,11 +1625,13 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
projects: projectRows
.filter((row) => row.deletedAt === null && activeProjectIds.has(row.projectId))
.map((row) =>
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
),
projects: Arr.filterMap(projectRows, (row) =>
row.deletedAt === null && activeProjectIds.has(row.projectId)
? Result.succeed(
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
)
: Result.failVoid,
),
threads: threadRows.map(
(row): OrchestrationThreadShell => ({
id: row.threadId,
@@ -244,9 +244,13 @@ function toProcessError(
function normalizeClaudeStreamMessages(
cause: Cause.Cause<{ readonly message: string }>,
): ReadonlyArray<string> {
const errors = Cause.prettyErrors(cause)
.map((error) => error.message.trim())
.filter((message) => message.length > 0);
const errors: Array<string> = [];
for (const error of Cause.prettyErrors(cause)) {
const message = error.message.trim();
if (message.length > 0) {
errors.push(message);
}
}
if (errors.length > 0) {
return errors;
}
Loaded 100 of 206 files, more files were not shown because too many files have changed in this diff. Show more