Compare commits

..
Author SHA1 Message Date
Yash Singh 59d508ed52 feat: resizable sidebar 2026-03-05 21:30:32 -06:00
github-actions[bot] d5c97faac5 chore(release): prepare v0.0.0-alpha.20 2026-03-06 00:31:16 +00:00
Julius Marminge 531b12e192 repo too 2026-03-05 16:15:34 -08:00
Julius Marminge b293b083fc add missing bin to published package 2026-03-05 16:15:34 -08:00
Julius Marminge b297e20f4e Fix release target commit and gate version bump steps
- Set `target_commitish` from preflight ref when creating GitHub releases
- Track whether package versions changed and expose it via step output
- Run format, lockfile refresh, and bump commit only when changes exist
2026-03-05 16:15:34 -08:00
Julius MarmingeandClaude Opus 4.6 44be7f3ac3 Run oxfmt on package.json files after version bump
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-05 16:15:34 -08:00
Julius MarmingeandClaude Opus 4.6 ea5a100a74 Defer release commit+tag to finalize job
Move the version bump commit and tag creation out of the preflight job
into a new finalize job that runs only after build, publish, and release
all succeed. This prevents orphaned version commits and tags on main
when downstream jobs fail.

- Preflight: validate version, lint/test only — no commit/tag/push
- Release: softprops/action-gh-release creates tag for workflow_dispatch
- Finalize: bump package.json versions, refresh lockfile, commit to main

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-05 16:15:34 -08:00
Julius Marminge 6841fa17d4 Scope changed-files tree PR to relevant files
- revert unrelated server-side attachment/image changes from this branch\n- keep changed-files tree UX fixes (icons, directory behavior, whitespace-safe paths, stat visibility)\n\nCo-authored-by: codex <[email protected]>
2026-03-05 15:56:40 -08:00
Julius Marminge 5c03804bac Improve changed-files tree UX and harden attachment path handling
- Compact single-directory chains in turn diff trees and preserve branch points
- Add per-turn expand/collapse-all controls and themed VS Code file icons in ChatView
- Centralize attachment route prefix stripping and tighten image/extension normalization helpers
2026-03-05 15:56:40 -08:00
Julius Marminge d6ed393255 Render changed files as expandable tree with aggregated diff stats
- Replace flat changed-files chips in ChatView with a nested, expandable tree
- Extract diff tree/stat logic into turnDiffTree utilities
- Add unit tests for stat aggregation, nesting, and Windows path normalization
2026-03-05 15:56:40 -08:00
Julius Marminge 2d9139767a Refine sidebar thread actions and list preview
- Move "New thread" action to each project header with hover icon + shortcut tooltip
- Limit thread lists to 6 items by default with per-project Show more/Show less controls
- Remove the global sidebar-level new thread button
2026-03-05 15:16:10 -08:00
Julius Marminge 95fcc89074 Prevent toast content overflow in collapsed stack
- Use the larger of shared stack height and per-toast height to avoid clipping
- Make toast content columns flexible with `min-w-0` and `break-words`
- Keep action buttons from shrinking so long text wraps instead of overflowing
2026-03-05 14:43:19 -08:00
Julius Marminge eb59853596 Add Copy Thread ID action to thread context menu
- Add a `Copy Thread ID` item to the thread context menu in the sidebar
- Copy the selected thread ID via Clipboard API
- Show success/error toasts based on copy result
2026-03-05 14:42:02 -08:00
Julius Marminge a2682de421 Use mention adjacency helper in composer onChange
- replace Lexical-node cursor adjacency check with text/cursor helper
- prevent `@query` typing from being treated as mention-pill adjacent
- add regression test for non-pill `@pac` input
2026-03-05 11:04:40 -08:00
Julius Marminge 325c0a3687 Limit composer mention arrow jumps to adjacent mention boundaries
- Only intercept left/right arrow keys when cursor is directly next to a mention
- Prevent default arrow behavior only for those mention-boundary moves
- Add `isCollapsedCursorAdjacentToMention` logic with coverage for left/right adjacency cases
2026-03-05 11:04:40 -08:00
Julius Marminge 7c7fcf46c2 Handle system timeline messages with assistant height rules
- Route `system` messages through assistant height estimation
- Keep user attachment height logic scoped to user messages
- Add regression test for system-message sizing behavior
2026-03-05 10:20:34 -08:00
Julius Marminge 0c39733cbf Expand ChatView height parity tests across responsive viewports
- Add viewport matrix coverage for long text and attachment row-height parity
- Reuse a mount/measure test harness to validate resize behavior in one session
- Ensure production CSS and viewport sizing are applied before measurements
2026-03-05 10:20:34 -08:00
Julius Marminge a76413594e Fix chat attachment height on narrow timeline resizes
- recompute timeline width from the root element on ResizeObserver updates
- rerun width effect when message/working state changes
- reduce minimum user chars per line for narrow layouts and add regression test
2026-03-05 10:20:34 -08:00
Julius Marminge 1100d5a6f7 Use vi.waitFor in ChatView browser measurement helpers
- Replace manual timeout polling loops with `vi.waitFor` in test helpers
- Improve reliability of locating and measuring virtualized user rows in attachment-height tests
2026-03-05 10:20:34 -08:00
Julius Marminge 9abf967700 Use vitest-browser-react in ChatView browser tests
- replace manual `createRoot` mounting with `render`/`unmount` from vitest-browser-react
- add `vitest-browser-react` to web devDependencies and lockfile
2026-03-05 10:20:34 -08:00
Julius Marminge cc83094bc6 add back title 2026-03-05 10:20:34 -08:00
Julius Marminge f5bdc138f6 Stabilize ChatView attachment height browser test with MSW
- Run ChatView browser tests through the real app router/store stack
- Add MSW worker setup and mocked WS/attachment responses for full-app rendering
- Extract shared `getRouter` setup and add a timeline root data hook for reliable measurement
2026-03-05 10:20:34 -08:00
Julius Marminge 2d8ca48175 Use real TanStack router in ChatView browser tests
- Replace mocked router hooks with a memory router + RouterProvider
- Render ChatView through a test route to exercise attachment height layout in realistic routing context
2026-03-05 10:20:34 -08:00
Julius Marminge 4ca4a1f99c Migrate ChatView height browser tests to Vitest + Playwright
- Replace Playwright e2e timeline-height test setup with Vitest browser config
- Add `ChatView.browser.tsx` parity tests for text wrapping and attachment height estimation
- Add row data attributes in `ChatView` to support in-browser measurement targeting
2026-03-05 10:20:34 -08:00
Julius Marminge 5470801c4a Add Playwright timeline height parity tests to CI
- add browser E2E tests validating timeline height estimator against rendered DOM
- configure Playwright test runner and scripts in `apps/web`
- run browser tests in CI with Playwright browser caching and install step
2026-03-05 10:20:34 -08:00
Julius Marminge 2ad2d3e6f5 Make chat timeline height estimates width-aware and test them
- extract `estimateTimelineMessageHeight` into `timelineHeight.ts`
- account for timeline width and explicit newlines when estimating wrapped lines
- re-measure virtualized rows on width changes to fix attachment/message height sizing
- add Vitest coverage for assistant/user wrapping and attachment row height rules
2026-03-05 10:20:34 -08:00
Julius MarmingeandClaude Opus 4.6 b175d6b2a3 Fix CLI publish using stale package.json version
The publish_cli job was checking out the default ref instead of the
preflight commit, so it published with the pre-bump version. Add the
correct ref to checkout and a --app-version flag as a safety override.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-04 10:20:07 -08:00
github-actions[bot]andcodex c5c12aa738 chore(release): prepare v0.0.0-alpha.18
Co-authored-by: codex <[email protected]>
2026-03-04 18:01:45 +00:00
Julius Marminge 7241400edd Add electron-updater and refresh lockfile package versions
- add `electron-updater` dependency for `apps/desktop`
- bump workspace package versions from `0.0.0-alpha.13` to `0.0.0-alpha.16`
- update transitive lockfile entries accordingly
2026-03-04 09:58:22 -08:00
Julius Marminge 310fd0b187 Wait for child process tree shutdown before forcing kill
- add `childTreeGracePeriodMs` constant for shutdown timing
- await grace period after `TERM` before sending `KILL` to avoid dev process leaks
2026-03-04 09:58:22 -08:00
Julius Marminge db94743220 Remove electronmon-specific cleanup from desktop dev script
- drop `electronmon` from desktop dependencies
- stop killing stale processes by matching electronmon hook paths
- keep cleanup scoped to `--t3code-dev-root` processes only
2026-03-04 09:58:22 -08:00
Julius Marminge 07aaf37fd4 Prevent desktop dev Electron process leaks during restarts
- replace `electronmon` with explicit Electron spawn/stop lifecycle management
- debounce file-watch restarts for main/preload/server build outputs
- add stale-process cleanup and forced child-tree shutdown fallback
2026-03-04 09:58:22 -08:00
Julius MarmingeandClaude Opus 4.6 65a808808f Fix electron-updater auth for private GitHub repos
Use setFeedURL with private: true when a GitHub token is provided so
electron-updater queries the GitHub API instead of the public Atom feed
which rejects Bearer auth headers.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-04 00:27:47 -08:00
github-actions[bot]andcodex cca1aa1588 chore(release): prepare v0.0.0-alpha.16
Co-authored-by: codex <[email protected]>
2026-03-04 07:21:44 +00:00
Julius Marminge c9d4b773c9 Remove target arg from electron-builder invocation
- stop passing `options.target` to the electron-builder CLI
- keep platform flag, arch, and `--publish never` unchanged
2026-03-03 23:13:53 -08:00
github-actions[bot]andcodex e23f3102f4 chore(release): prepare v0.0.0-alpha.15
Co-authored-by: codex <[email protected]>
2026-03-04 06:35:27 +00:00
Julius Marminge ec89587c37 Refactor desktop update flow with retryable action results
- Extract desktop updater state transitions into `updateMachine` reducers with tests
- Extend update IPC/contracts to return `{accepted, completed, state}` for download/install actions
- Add web sidebar update-button logic for retryable download/install errors and clearer tooltips
2026-03-03 22:31:45 -08:00
Julius Marminge 32d89806d7 Extract desktop update state helpers and improve update UX
- Add `updateState` helpers for auto-update eligibility reasons and progress throttling
- Show a user-facing dialog when manual update checks are unavailable
- Ensure manual update checks can open a window when none exist
- Add tests for disable-reason logic and 10% download progress bucketing
2026-03-03 22:31:45 -08:00
Julius Marminge 2fd4e06b34 Allow update checks when status is available
- Stop skipping `checkForUpdates` when updater state is `available`
- Continue skipping only while an update is downloading or already downloaded
2026-03-03 22:31:45 -08:00
Julius Marminge 3cffdce1c1 Harden desktop auto-update timer lifecycle
- track and clear startup + poll update timers through one cleanup path
- prevent update checks from starting while the app is quitting
- reset startup timer before scheduling to avoid duplicate checks
2026-03-03 22:31:45 -08:00
Cursor AgentandJulius Marminge 6d2f4f4cdf fix: remove misleading log and redundant guard in handleCheckForUpdatesMenuClick
The guard for status === 'downloaded' logged 'skipping automatic install'
but the function only checks for updates, never installs. The guard was
also redundant since checkForUpdates() already returns early for
'downloaded', 'downloading', and 'available' statuses with correct
log messages.

Co-authored-by: Julius Marminge <[email protected]>

Applied via @cursor push command
2026-03-03 22:31:45 -08:00
Julius Marminge 865d7bd684 Guard update install while app is quitting
- Prevent update install from running when shutdown is already in progress
- Ignore install IPC calls once `isQuitting` is set to avoid duplicate install attempts
2026-03-03 22:31:45 -08:00
Julius Marminge 392d63231c Harden desktop update flow and prevent duplicate update actions
- Skip redundant update checks while update is available/downloading/downloaded
- Wait for backend shutdown before `quitAndInstall` and improve updater error/progress handling
- Prevent sidebar update button clicks during download while preserving tooltip interactivity
2026-03-03 22:31:45 -08:00
Julius Marminge 7559f5ad70 style 2026-03-03 22:31:45 -08:00
Julius Marminge 605e8143e0 Prevent redundant checks during desktop update download
- Skip desktop auto-update checks while an update is downloading or already downloaded
- Subscribe to update-state events before initial fetch in sidebar to avoid stale state races
2026-03-03 22:31:45 -08:00
Julius Marmingeandcodex 5b056cd337 fix: remove duplicate catalog resolver after rebase
Co-authored-by: codex <[email protected]>
2026-03-03 22:31:45 -08:00
Julius Marminge 6c350489b1 Add desktop auto-update flow and publish updater assets
- wire `electron-updater` into desktop main/preload IPC and shared contracts
- add sidebar update action for download/install state in Electron UI
- update release workflow/build script to include `latest*.yml` and `*.blockmap` assets
2026-03-03 22:31:45 -08:00
julius 2ae63f4aa2 Fix shell: true side effects on Windows (orphaned processes, swallowed ENOENT)
Add tree-kill via taskkill /T /F in processRunner and codexAppServerManager so timeout enforcement and session stop properly terminate the entire process tree instead of just the cmd.exe wrapper. Detect Windows command not found (exit 9009) in normalizeExitError. Pre-validate editor commands with isCommandAvailable in open.ts before spawning. Fix ProviderHealth test import and dev-runner test path assertion for Windows.

Made-with: Cursor
2026-03-03 21:03:16 -08:00
julius 3d0233e3b0 fmt test 2026-03-03 21:03:16 -08:00
julius 64f2c3a465 effectify 2026-03-03 21:03:16 -08:00
julius 0a12333448 Fix Codex process spawning and health checks on Windows
- Run Codex-related child processes with `shell` on Windows for reliable command execution
- Switch provider auth probe to `codex login status` and update health-check expectations
- Use Node PTY on Windows instead of Bun PTY in server runtime setup
2026-03-03 21:03:16 -08:00
Julius Marminge 9db54c9b19 Handle Codex auth JSON arrays and flag missing auth markers
- Parse nested/array JSON auth status output from `codex auth status --json`
- Return `unauthenticated` when JSON contains `authenticated: false`
- Return warning when JSON is parseable but lacks an auth marker
2026-03-03 21:03:16 -08:00
julius 34430e3514 windows dev 2026-03-03 21:03:16 -08:00
Julius Marminge 99e44f2c23 Add Codex provider health status to server config and chat banner
- add startup ProviderHealth service/layer to probe Codex install and auth state
- extend server contracts and WS payloads to include provider statuses
- show non-ready provider warnings in ChatView and cover with server/web tests
2026-03-03 21:03:16 -08:00
github-actions[bot]andcodex 7a0f2d9b30 chore(release): prepare v0.0.0-alpha.14
Co-authored-by: codex <[email protected]>
2026-03-04 03:03:52 +00:00
Julius Marminge 4bf310f7ca disable provenacnes while repo is private 2026-03-03 18:59:11 -08:00
github-actions[bot]andcodex 8b9fbe701d chore(release): prepare v0.0.0-alpha.13
Co-authored-by: codex <[email protected]>
2026-03-04 02:25:54 +00:00
Julius Marminge 0c5be023e4 fix test 2026-03-03 18:22:29 -08:00
Julius Marminge 86e87a8789 better lables 2026-03-03 18:22:29 -08:00
Julius Marminge 404e78a506 logging 2026-03-03 18:22:29 -08:00
Julius Marminge 73563c7c25 Add Vitest to root devDependencies
- add `vitest` via catalog in root `package.json`
- update `bun.lock` to include the new workspace dependency
2026-03-03 18:22:29 -08:00
Julius Marminge 326595b148 Add Vitest to web app and remove unused composer/env props
- add `vitest` to `apps/web` devDependencies and lockfile
- remove unused `envMode` prop from `BranchToolbar` usage and signature
- drop unused composer command input ref in `ChatView`
2026-03-03 18:22:29 -08:00
Julius Marminge 41a8468b08 Add effect dependency to desktop app package
- include `effect` in `apps/desktop` runtime dependencies
- update `bun.lock` to reflect the new dependency
2026-03-03 18:22:29 -08:00
Julius Marminge ced2ecb6ba install node 2026-03-03 18:22:29 -08:00
Julius Marminge 2d746b3a7e rm 2026-03-03 18:22:29 -08:00
Julius Marminge e6ac39de75 Migrate dev-runner to typed Effect CLI config and env fallbacks
- Replace string-based env override plumbing with typed config/flag parsing
- Split server/web offset resolution from explicit port/dev-url overrides
- Refactor and expand dev-runner tests around offset/env behavior
- Add `vitest` as a contracts dev dependency for test execution
2026-03-03 18:22:29 -08:00
Julius Marminge b76a0a6c91 Migrate dev runner to TypeScript and share NetService
- Replace `scripts/dev-runner.mjs` with typed `scripts/dev-runner.ts` in a new `@t3tools/scripts` workspace
- Move networking helpers into `@t3tools/shared/Net` and reuse them in server and desktop
- Add shared NetService tests and align workspace deps to `catalog:` versions
2026-03-03 18:22:29 -08:00
Julius Marminge 9fdec3c2c8 Fix npm publish command process invocation
- Pass command and args directly to `ChildProcess.make` in the publish CLI
- Remove fragile template-literal invocation to ensure command runs reliably
2026-03-03 10:55:23 -08:00
Julius Marminge 760fe643e8 helper 2026-03-03 10:01:18 -08:00
Julius Marminge 93af851dc5 type 2026-03-03 10:01:18 -08:00
Julius Marminge fabb3e0734 Extract branch selector and refresh branches on menu open
- Move branch combobox logic into `BranchToolbarBranchSelector` to simplify `BranchToolbar`
- Re-fetch git branches when opening the selector so options are current
- Preserve draft env mode correctly when switching between main and worktree branches
2026-03-03 10:01:18 -08:00
Julius Marminge 9ca9a862a5 Fix branch selector default and loading behavior in worktree mode
- Default new worktree branch selection to the current checked-out branch when unset
- Extract branch value resolution into shared logic with tests
- Stabilize virtualized branch list scroll/measurement to avoid loading glitches
2026-03-03 10:01:18 -08:00
github-actions[bot]andcodex 827dc9ff9f chore(release): prepare v0.0.0-alpha.12
Co-authored-by: codex <[email protected]>
2026-03-03 18:01:00 +00:00
Julius Marminge 09b32ac9dd Extract slash model option filtering into shared app settings helper
- add `getSlashModelOptions` to centralize `/model` suggestion filtering
- include custom saved model slugs in slash-command suggestions
- update ChatView to consume shared helper and add focused tests
2026-03-03 09:31:54 -08:00
Julius Marminge 253684e280 kewl 2026-03-03 09:18:08 -08:00
Julius Marminge f6d40ce841 log? 2026-03-03 09:12:28 -08:00
github-actions[bot]andcodex 36fb1bb7e4 chore(release): prepare v0.0.0-alpha.11
Co-authored-by: codex <[email protected]>
2026-03-03 17:09:58 +00:00
Julius Marminge 4a82c1608f fix pub 2026-03-03 09:06:05 -08:00
github-actions[bot]andcodex 3efb3da007 chore(release): prepare v0.0.0-alpha.10
Co-authored-by: codex <[email protected]>
2026-03-03 08:33:23 +00:00
Julius Marminge 11606fd9c6 cli for pub 2026-03-03 00:30:15 -08:00
github-actions[bot]andcodex a935db07ef chore(release): prepare v0.0.0-alpha.9
Co-authored-by: codex <[email protected]>
2026-03-03 07:36:01 +00:00
Julius Marminge 98860a9549 ignore scripts on publish 2026-03-02 23:33:14 -08:00
github-actions[bot]andcodex 7688742b2a chore(release): prepare v0.0.0-alpha.8
Co-authored-by: codex <[email protected]>
2026-03-03 07:02:39 +00:00
Julius Marminge b2efe4f83c cwd 2026-03-02 22:56:37 -08:00
github-actions[bot]andcodex f934b435fa chore(release): prepare v0.0.0-alpha.7
Co-authored-by: codex <[email protected]>
2026-03-03 06:46:02 +00:00
Julius Marminge 3c121585da publish cli? 2026-03-02 22:42:21 -08:00
github-actions[bot]andcodex 40acfbd2df chore(release): prepare v0.0.0-alpha.6
Co-authored-by: codex <[email protected]>
2026-03-03 06:01:37 +00:00
Julius Marminge 0af61bf6ba verbose 2026-03-02 21:58:36 -08:00
github-actions[bot]andcodex 7b2968f2ff chore(release): prepare v0.0.0-alpha.5
Co-authored-by: codex <[email protected]>
2026-03-03 05:55:00 +00:00
Julius Marminge a1c7b98f98 fix build script 2026-03-02 20:59:56 -08:00
Julius Marmingeandcodex 99ea16a969 Restore Open PR CTA for commit_push with existing PR
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex ebe44d03a5 Revert git action button logic toward main behavior
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex dcd2d50768 Keep non-default quick action on full PR flow
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex f11764c517 Fix PR CTAs and quick action after push
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex 77c81b7468 Restore Open PR toast action after PR creation
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex 7a5ccd3310 Fix toast follow-up actions to avoid re-branching
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex e4df6fcf8e Scope default-branch PR confirmation to full stack
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex b2be7f4e4f Address PR feedback on git workflows
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge 94beb21a43 Skip commit progress stages when create-PR runs push-only
- pass `forcePushOnlyProgress` for the create-PR action
- add logic test to ensure only push and PR stages are shown
2026-03-02 20:46:05 -08:00
Julius Marminge 30e05538b7 Limit default-branch confirmation to direct push
- Stop showing default-branch confirmation for `commit_push_pr`
- Keep confirmation only for direct `commit_push` actions
- Update logic test to match the new behavior
2026-03-02 20:46:05 -08:00
Julius Marminge c884947ea8 Scope branch checkout effect during auto branch creation
- Wrap checkout in `Effect.scoped` when creating a new feature branch
- Align branch switch lifecycle with scoped effect handling
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 61289a152d Fix duplicated branch logic and feature-branch dialog on push-only
Deduplicate feature/ prefix logic in resolveAutoFeatureBranchName by
delegating to sanitizeFeatureBranchName. Skip the default-branch
confirmation dialog when there are no uncommitted changes (push-only),
since runFeatureBranchStep requires dirty worktree. Add merge-base
assertions to feature branch tests.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 906550f9af Merge feature-branch checkout into atomic runStackedAction
Consolidate the fragile 3-RPC flow (suggestCommitAndBranch → createBranch +
checkout → runStackedAction) into a single server-side operation triggered by
`runStackedAction({ featureBranch: true })`. The server now generates the
branch name via AI, deduplicates it, creates + checks out the branch, then
runs the normal commit/push/PR pipeline atomically.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge c2aaa89b57 Document contracts and shared package responsibilities
- Clarify that `packages/contracts` is schema-only with no runtime logic
- Add `packages/shared` as the home for shared runtime utilities and subpath exports
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 dde48e9414 Move branch sanitization from contracts to new shared package
Create @t3tools/shared with explicit subpath exports (no barrel) for
shared utility logic. Move sanitizeBranchFragment and
sanitizeFeatureBranchName to @t3tools/shared/git, keeping contracts
focused on schemas.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 b1608f41ad Extract branch sanitization to shared contracts module
Move sanitizeBranchFragment and sanitizeFeatureBranchName from three
duplicate definitions (CodexTextGeneration, GitManager, GitActionsControl)
into packages/contracts/src/git.ts. Remove the redundant double-sanitization
of branch names between the TextGeneration and GitManager layers —
CodexTextGeneration now owns sanitization of model output while GitManager
trusts the result and only sanitizes the custom commit message path.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge 78d89e3d35 non-dupicate 2026-03-02 20:46:05 -08:00
Julius Marminge 1309495218 optional 2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.5 c34a4c69e5 Add AI-generated semantic branch naming for git commits
Replace date-based auto feature branch names (feature/stacked-YYYYMMDD)
with semantically meaningful names derived from AI-generated commit
messages. The text generation prompt now returns a branch field alongside
subject and body, and a new suggestCommitAndBranch endpoint exposes this
to the web client for the default-branch checkout flow.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge 2f6cac0cf0 no forwardref needed 2026-03-02 20:31:39 -08:00
Julius Marminge 5c26df3a4f Virtualize branch picker list and forward ComboboxList ref
- Add virtualized rendering and filtered item handling in `BranchToolbar`
- Memoize branch-derived data and sync highlight scrolling for large branch sets
- Convert `ComboboxList` to `forwardRef` to support virtualizer scroll targeting
2026-03-02 20:31:39 -08:00
100 changed files with 8283 additions and 1927 deletions

No files matched your search

+17 -1
View File
@@ -8,7 +8,7 @@ on:
jobs:
quality:
name: Lint, Typecheck, Test, Build
name: Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Checkout
@@ -34,6 +34,14 @@ jobs:
restore-keys: |
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install dependencies
run: bun install --frozen-lockfile
@@ -46,6 +54,14 @@ jobs:
- name: Test
run: bun run test
- name: Install browser test runtime
run: |
cd apps/web
bunx playwright install --with-deps chromium
- name: Browser test
run: bun run --cwd apps/web test:browser
- name: Build desktop pipeline
run: bun run build:desktop
+141 -100
View File
@@ -22,12 +22,10 @@ jobs:
outputs:
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
ref: ${{ steps.release_ref.outputs.value }}
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- id: release_meta
name: Resolve release version
@@ -58,32 +56,6 @@ jobs:
with:
node-version-file: package.json
- name: Update version strings
if: github.event_name == 'workflow_dispatch'
env:
RELEASE_VERSION: ${{ steps.release_meta.outputs.version }}
run: |
node --input-type=module -e '
import { readFileSync, writeFileSync } from "node:fs";
const files = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
];
for (const file of files) {
const packageJson = JSON.parse(readFileSync(file, "utf8"));
packageJson.version = process.env.RELEASE_VERSION;
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
}
'
- name: Refresh lockfile
if: github.event_name == 'workflow_dispatch'
run: bun install
- name: Install dependencies
run: bun install --frozen-lockfile
@@ -96,39 +68,6 @@ jobs:
- name: Test
run: bun run test
- name: Commit and push release version + tag
if: github.event_name == 'workflow_dispatch'
shell: bash
env:
RELEASE_TAG: ${{ steps.release_meta.outputs.tag }}
run: |
if git ls-remote --exit-code --tags origin "$RELEASE_TAG" >/dev/null 2>&1; then
echo "Tag $RELEASE_TAG already exists on origin." >&2
exit 1
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
if ! git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG" -m "Co-authored-by: codex <[email protected]>"
fi
git tag "$RELEASE_TAG"
git push origin "HEAD:${GITHUB_REF_NAME}"
git push origin "refs/tags/$RELEASE_TAG"
- id: release_ref
name: Resolve source ref
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
echo "value=refs/tags/${{ steps.release_meta.outputs.tag }}" >> "$GITHUB_OUTPUT"
else
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
fi
build:
name: Build ${{ matrix.label }}
needs: preflight
@@ -198,6 +137,7 @@ jobs:
--target "${{ matrix.target }}"
--arch "${{ matrix.arch }}"
--build-version "${{ needs.preflight.outputs.version }}"
--verbose
)
has_all() {
@@ -239,57 +179,71 @@ jobs:
bun run dist:desktop:artifact -- "${args[@]}"
- name: Collect release assets
shell: bash
run: |
set -euo pipefail
mkdir -p release-publish
shopt -s nullglob
for pattern in \
"release/*.dmg" \
"release/*.zip" \
"release/*.AppImage" \
"release/*.exe" \
"release/*.blockmap" \
"release/latest*.yml"; do
for file in $pattern; do
cp "$file" release-publish/
done
done
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
if [[ -f release-publish/latest-mac.yml ]]; then
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
fi
fi
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release/*
path: release-publish/*
if-no-files-found: error
# publish_cli:
# name: Publish CLI to npm
# needs: [preflight, build]
# runs-on: ubuntu-24.04
# steps:
# - name: Checkout
# uses: actions/checkout@v4
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
# - name: Setup Bun
# uses: oven-sh/setup-bun@v2
# with:
# bun-version-file: package.json
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
# - name: Setup Node
# uses: actions/setup-node@v4
# with:
# node-version-file: package.json
# registry-url: https://registry.npmjs.org
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
# - name: Install dependencies
# run: bun install --frozen-lockfile
- name: Install dependencies
run: bun install --frozen-lockfile
# - name: Set CLI package version from release tag
# env:
# RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
# run: |
# node --input-type=module -e '
# import { readFileSync, writeFileSync } from "node:fs";
# const packagePath = "apps/server/package.json";
# const packageJson = JSON.parse(readFileSync(packagePath, "utf8"));
# packageJson.version = process.env.RELEASE_VERSION;
# writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
# '
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
# - name: Build CLI package
# run: bun run build --filter=@t3tools/web --filter=t3
# - name: Publish CLI package
# run: bun --cwd apps/server publish --access public
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose
release:
name: Publish GitHub Release
needs: [preflight, build]
# needs: [preflight, build, publish_cli]
needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
steps:
- name: Download all desktop artifacts
@@ -303,7 +257,94 @@ jobs:
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: T3 Code v${{ needs.preflight.outputs.version }}
generate_release_notes: true
files: release-assets/*
make_latest: true
files: |
release-assets/*.dmg
release-assets/*.zip
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/latest*.yml
fail_on_unmatched_files: true
finalize:
name: Finalize release
needs: [preflight, release]
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- id: update_versions
name: Update version strings
env:
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
run: |
node --input-type=module -e '
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
const files = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
];
let changed = false;
for (const file of files) {
const packageJson = JSON.parse(readFileSync(file, "utf8"));
if (packageJson.version !== process.env.RELEASE_VERSION) {
packageJson.version = process.env.RELEASE_VERSION;
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
changed = true;
}
}
if (!changed) {
console.log("All package.json versions already match release version.");
}
appendFileSync(process.env.GITHUB_OUTPUT, `changed=${changed}\n`);
'
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
- name: Refresh lockfile
if: steps.update_versions.outputs.changed == 'true'
run: bun install
- name: Commit and push version bump
if: steps.update_versions.outputs.changed == 'true'
shell: bash
env:
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
run: |
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
echo "No version changes to commit."
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG"
git push origin HEAD:main
+4 -1
View File
@@ -11,4 +11,7 @@ packages/*/dist
build/
.logs/
release/
.t3
.t3
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
+6 -5
View File
@@ -18,11 +18,16 @@ This repository is a VERY EARLY WIP. Proposing sweeping changes that improve lon
If a tradeoff is required, choose correctness and robustness over short-term convenience.
## Maintainability
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
## Package Roles
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
## Codex App Server (Important)
@@ -45,7 +50,3 @@ Docs:
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
## Dummy Change
- Placeholder line to validate a docs-only edit.
+9 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0-alpha.4",
"version": "0.0.0-alpha.20",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
@@ -14,15 +14,17 @@
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"electron": "40.6.0"
"effect": "catalog:",
"electron": "40.6.0",
"electron-updater": "^6.6.2"
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@types/node": "^24.10.13",
"electronmon": "^2.0.2",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
"@t3tools/shared": "workspace:*",
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
"wait-on": "^8.0.2"
},
"productName": "T3 Code (Alpha)"
+164 -27
View File
@@ -1,43 +1,171 @@
import { spawnSync } from "node:child_process";
import electronmon from "electronmon";
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
const devServerUrl = `http://localhost:${port}`;
const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200;
await waitOn({
resources: [
`tcp:${port}`,
"file:dist-electron/main.js",
"file:dist-electron/preload.js",
"file:../server/dist/index.mjs",
],
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
});
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const monitor = await electronmon({
cwd: desktopDir,
args: ["dist-electron/main.js"],
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
electronPath: resolveElectronPath(),
});
let shuttingDown = false;
let restartTimer = null;
let currentApp = null;
let restartQueue = Promise.resolve();
const expectedExits = new WeakSet();
const watchers = [];
function killChildTreeByPid(pid, signal) {
if (process.platform === "win32" || typeof pid !== "number") {
return;
}
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
}
function cleanupStaleDevApps() {
if (process.platform === "win32") {
return;
}
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
}
function startApp() {
if (shuttingDown || currentApp !== null) {
return;
}
const app = spawn(
resolveElectronPath(),
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
{
cwd: desktopDir,
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
stdio: "inherit",
},
);
currentApp = app;
app.once("error", () => {
if (currentApp === app) {
currentApp = null;
}
if (!shuttingDown) {
scheduleRestart();
}
});
app.once("exit", () => {
if (currentApp === app) {
currentApp = null;
}
if (!shuttingDown && !expectedExits.has(app)) {
scheduleRestart();
}
});
}
async function stopApp() {
const app = currentApp;
if (!app) {
return;
}
currentApp = null;
expectedExits.add(app);
await new Promise((resolve) => {
let settled = false;
const finish = () => {
if (settled) {
return;
}
settled = true;
resolve();
};
app.once("exit", finish);
app.kill("SIGTERM");
killChildTreeByPid(app.pid, "TERM");
setTimeout(() => {
if (settled) {
return;
}
app.kill("SIGKILL");
killChildTreeByPid(app.pid, "KILL");
finish();
}, forcedShutdownTimeoutMs).unref();
});
}
function scheduleRestart() {
if (shuttingDown) {
return;
}
if (restartTimer) {
clearTimeout(restartTimer);
}
restartTimer = setTimeout(() => {
restartTimer = null;
restartQueue = restartQueue
.catch(() => undefined)
.then(async () => {
await stopApp();
if (!shuttingDown) {
startApp();
}
});
}, restartDebounceMs);
}
function startWatchers() {
for (const { directory, files } of watchedDirectories) {
const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
return;
}
scheduleRestart();
});
watchers.push(watcher);
}
}
function killChildTree(signal) {
if (process.platform === "win32") {
return;
}
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
}
@@ -45,20 +173,29 @@ async function shutdown(exitCode) {
if (shuttingDown) return;
shuttingDown = true;
try {
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
} catch {
// Best effort only; fallback process kill below handles stubborn children.
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = null;
}
for (const watcher of watchers) {
watcher.close();
}
await stopApp();
killChildTree("TERM");
setTimeout(() => {
killChildTree("KILL");
}, 1_200).unref();
await new Promise((resolve) => {
setTimeout(resolve, childTreeGracePeriodMs);
});
killChildTree("KILL");
process.exit(exitCode);
}
startWatchers();
cleanupStaleDevApps();
startApp();
process.once("SIGINT", () => {
void shutdown(130);
});
+2 -2
View File
@@ -1,11 +1,11 @@
import { execFileSync } from "node:child_process";
import * as ChildProcess from "node:child_process";
export function fixPath(): void {
if (process.platform !== "darwin") return;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
const result = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], {
encoding: "utf8",
timeout: 5000,
});
+614 -66
View File
@@ -1,16 +1,36 @@
import { spawn, type ChildProcess } from "node:child_process";
import { randomBytes } from "node:crypto";
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import * as ChildProcess from "node:child_process";
import * as Crypto from "node:crypto";
import * as FS from "node:fs";
import * as OS from "node:os";
import * as Path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, shell } from "electron";
import type { MenuItemConstructorOptions } from "electron";
import * as Effect from "effect/Effect";
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
import {
getAutoUpdateDisabledReason,
shouldBroadcastDownloadProgress,
} from "./updateState";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
reduceDesktopUpdateStateOnCheckStart,
reduceDesktopUpdateStateOnDownloadComplete,
reduceDesktopUpdateStateOnDownloadFailure,
reduceDesktopUpdateStateOnDownloadProgress,
reduceDesktopUpdateStateOnDownloadStart,
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
fixPath();
@@ -19,18 +39,30 @@ const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const STATE_DIR =
process.env.T3CODE_STATE_DIR?.trim() || path.join(os.homedir(), ".t3", "userdata");
process.env.T3CODE_STATE_DIR?.trim() || Path.join(OS.homedir(), ".t3", "userdata");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = path.resolve(__dirname, "../../..");
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code";
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
const COMMIT_HASH_DISPLAY_LENGTH = 12;
const LOG_DIR = Path.join(STATE_DIR, "logs");
const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const LOG_FILE_MAX_FILES = 10;
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess | null = null;
let backendProcess: ChildProcess.ChildProcess | null = null;
let backendPort = 0;
let backendAuthToken = "";
let backendWsUrl = "";
@@ -39,8 +71,133 @@ let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
let desktopProtocolRegistered = false;
let aboutCommitHashCache: string | null | undefined;
let desktopLogSink: RotatingFileSink | null = null;
let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const initialUpdateState = (): DesktopUpdateState => createInitialDesktopUpdateState(app.getVersion());
function logTimestamp(): string {
return new Date().toISOString();
}
function logScope(scope: string): string {
return `${scope} run=${APP_RUN_ID}`;
}
function sanitizeLogValue(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function writeDesktopLogHeader(message: string): void {
if (!desktopLogSink) return;
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
}
function writeBackendSessionBoundary(phase: "START" | "END", details: string): void {
if (!backendLogSink) return;
const normalizedDetails = sanitizeLogValue(details);
backendLogSink.write(
`[${logTimestamp()}] ---- APP SESSION ${phase} run=${APP_RUN_ID} ${normalizedDetails} ----\n`,
);
}
function formatErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
return String(error);
}
function writeDesktopStreamChunk(
streamName: "stdout" | "stderr",
chunk: unknown,
encoding: BufferEncoding | undefined,
): void {
if (!desktopLogSink) return;
const buffer = Buffer.isBuffer(chunk)
? chunk
: Buffer.from(String(chunk), typeof chunk === "string" ? encoding : undefined);
desktopLogSink.write(`[${logTimestamp()}] [${logScope(streamName)}] `);
desktopLogSink.write(buffer);
if (buffer.length === 0 || buffer[buffer.length - 1] !== 0x0a) {
desktopLogSink.write("\n");
}
}
function installStdIoCapture(): void {
if (!app.isPackaged || desktopLogSink === null || restoreStdIoCapture !== null) {
return;
}
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
const originalStderrWrite = process.stderr.write.bind(process.stderr);
const patchWrite =
(streamName: "stdout" | "stderr", originalWrite: typeof process.stdout.write) =>
(
chunk: string | Uint8Array,
encodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),
callback?: (error?: Error | null) => void,
): boolean => {
const encoding = typeof encodingOrCallback === "string" ? encodingOrCallback : undefined;
writeDesktopStreamChunk(streamName, chunk, encoding);
if (typeof encodingOrCallback === "function") {
return originalWrite(chunk, encodingOrCallback);
}
if (callback !== undefined) {
return originalWrite(chunk, encoding, callback);
}
if (encoding !== undefined) {
return originalWrite(chunk, encoding);
}
return originalWrite(chunk);
};
process.stdout.write = patchWrite("stdout", originalStdoutWrite);
process.stderr.write = patchWrite("stderr", originalStderrWrite);
restoreStdIoCapture = () => {
process.stdout.write = originalStdoutWrite;
process.stderr.write = originalStderrWrite;
restoreStdIoCapture = null;
};
}
function initializePackagedLogging(): void {
if (!app.isPackaged) return;
try {
desktopLogSink = new RotatingFileSink({
filePath: Path.join(LOG_DIR, "desktop-main.log"),
maxBytes: LOG_FILE_MAX_BYTES,
maxFiles: LOG_FILE_MAX_FILES,
});
backendLogSink = new RotatingFileSink({
filePath: Path.join(LOG_DIR, "server-child.log"),
maxBytes: LOG_FILE_MAX_BYTES,
maxFiles: LOG_FILE_MAX_FILES,
});
installStdIoCapture();
writeDesktopLogHeader(`runtime log capture enabled logDir=${LOG_DIR}`);
} catch (error) {
// Logging setup should never block app startup.
console.error("[desktop] failed to initialize packaged logging", error);
}
}
function captureBackendOutput(child: ChildProcess.ChildProcess): void {
if (!app.isPackaged || backendLogSink === null) return;
const writeChunk = (chunk: unknown): void => {
if (!backendLogSink) return;
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
backendLogSink.write(buffer);
};
child.stdout?.on("data", writeChunk);
child.stderr?.on("data", writeChunk);
}
initializePackagedLogging();
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
if (process.platform !== "darwin") return undefined;
@@ -64,6 +221,18 @@ function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
return undefined;
}
}
let updatePollTimer: ReturnType<typeof setInterval> | null = null;
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
let updateCheckInFlight = false;
let updateDownloadInFlight = false;
let updaterConfigured = false;
let updateState: DesktopUpdateState = initialUpdateState();
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
if (updateDownloadInFlight) return "download";
if (updateCheckInFlight) return "check";
return updateState.errorContext;
}
protocol.registerSchemesAsPrivileged([
{
@@ -84,6 +253,28 @@ function resolveAppRoot(): string {
return app.getAppPath();
}
/** Read the baked-in app-update.yml config (if applicable). */
function readAppUpdateYml(): Record<string, string> | null {
try {
// electron-updater reads from process.resourcesPath in packaged builds,
// or dev-app-update.yml via app.getAppPath() in dev.
const ymlPath = app.isPackaged
? Path.join(process.resourcesPath, "app-update.yml")
: Path.join(app.getAppPath(), "dev-app-update.yml");
const raw = FS.readFileSync(ymlPath, "utf-8");
// The YAML is simple key-value pairs — avoid pulling in a YAML parser by
// doing a line-based parse (fields: provider, owner, repo, releaseType, …).
const entries: Record<string, string> = {};
for (const line of raw.split("\n")) {
const match = line.match(/^(\w+):\s*(.+)$/);
if (match?.[1] && match[2]) entries[match[1]] = match[2].trim();
}
return entries.provider ? entries : null;
} catch {
return null;
}
}
function normalizeCommitHash(value: unknown): string | null {
if (typeof value !== "string") {
return null;
@@ -96,13 +287,13 @@ function normalizeCommitHash(value: unknown): string | null {
}
function resolveEmbeddedCommitHash(): string | null {
const packageJsonPath = path.join(resolveAppRoot(), "package.json");
if (!fs.existsSync(packageJsonPath)) {
const packageJsonPath = Path.join(resolveAppRoot(), "package.json");
if (!FS.existsSync(packageJsonPath)) {
return null;
}
try {
const raw = fs.readFileSync(packageJsonPath, "utf8");
const raw = FS.readFileSync(packageJsonPath, "utf8");
const parsed = JSON.parse(raw) as { t3codeCommitHash?: unknown };
return normalizeCommitHash(parsed.t3codeCommitHash);
} catch {
@@ -133,25 +324,25 @@ function resolveAboutCommitHash(): string | null {
}
function resolveBackendEntry(): string {
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
}
function resolveBackendCwd(): string {
if (!app.isPackaged) {
return resolveAppRoot();
}
return os.homedir();
return OS.homedir();
}
function resolveDesktopStaticDir(): string | null {
const appRoot = resolveAppRoot();
const candidates = [
path.join(appRoot, "apps/server/dist/client"),
path.join(appRoot, "apps/web/dist"),
Path.join(appRoot, "apps/server/dist/client"),
Path.join(appRoot, "apps/web/dist"),
];
for (const candidate of candidates) {
if (fs.existsSync(path.join(candidate, "index.html"))) {
if (FS.existsSync(Path.join(candidate, "index.html"))) {
return candidate;
}
}
@@ -162,35 +353,50 @@ function resolveDesktopStaticDir(): string | null {
function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
const url = new URL(requestUrl);
const rawPath = decodeURIComponent(url.pathname);
const normalizedPath = path.posix.normalize(rawPath).replace(/^\/+/, "");
const normalizedPath = Path.posix.normalize(rawPath).replace(/^\/+/, "");
if (normalizedPath.includes("..")) {
return path.join(staticRoot, "index.html");
return Path.join(staticRoot, "index.html");
}
const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
const resolvedPath = path.join(staticRoot, requestedPath);
const resolvedPath = Path.join(staticRoot, requestedPath);
if (path.extname(resolvedPath)) {
if (Path.extname(resolvedPath)) {
return resolvedPath;
}
const nestedIndex = path.join(resolvedPath, "index.html");
if (fs.existsSync(nestedIndex)) {
const nestedIndex = Path.join(resolvedPath, "index.html");
if (FS.existsSync(nestedIndex)) {
return nestedIndex;
}
return path.join(staticRoot, "index.html");
return Path.join(staticRoot, "index.html");
}
function isStaticAssetRequest(requestUrl: string): boolean {
try {
const url = new URL(requestUrl);
return path.extname(url.pathname).length > 0;
return Path.extname(url.pathname).length > 0;
} catch {
return false;
}
}
function handleFatalStartupError(stage: string, error: unknown): void {
const message = formatErrorMessage(error);
const detail =
error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
writeDesktopLogHeader(`fatal startup error stage=${stage} message=${message}`);
console.error(`[desktop] fatal startup error (${stage})`, error);
if (!isQuitting) {
isQuitting = true;
dialog.showErrorBox("T3 Code failed to start", `Stage: ${stage}\n${message}${detail}`);
}
stopBackend();
restoreStdIoCapture?.();
app.quit();
}
function registerDesktopProtocol(): void {
if (isDevelopment || desktopProtocolRegistered) return;
@@ -201,19 +407,19 @@ function registerDesktopProtocol(): void {
);
}
const staticRootResolved = path.resolve(staticRoot);
const staticRootPrefix = `${staticRootResolved}${path.sep}`;
const fallbackIndex = path.join(staticRootResolved, "index.html");
const staticRootResolved = Path.resolve(staticRoot);
const staticRootPrefix = `${staticRootResolved}${Path.sep}`;
const fallbackIndex = Path.join(staticRootResolved, "index.html");
protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
try {
const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
const resolvedCandidate = path.resolve(candidate);
const resolvedCandidate = Path.resolve(candidate);
const isInRoot =
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
const isAssetRequest = isStaticAssetRequest(request.url);
if (!isInRoot || !fs.existsSync(resolvedCandidate)) {
if (!isInRoot || !FS.existsSync(resolvedCandidate)) {
if (isAssetRequest) {
callback({ error: -6 });
return;
@@ -256,6 +462,32 @@ function dispatchMenuAction(action: string): void {
send();
}
function handleCheckForUpdatesMenuClick(): void {
const disabledReason = getAutoUpdateDisabledReason({
isDevelopment,
isPackaged: app.isPackaged,
platform: process.platform,
appImage: process.env.APPIMAGE,
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
});
if (disabledReason) {
console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
void dialog.showMessageBox({
type: "info",
title: "Updates unavailable",
message: "Automatic updates are not available right now.",
detail: disabledReason,
buttons: ["OK"],
});
return;
}
if (!BrowserWindow.getAllWindows().length) {
mainWindow = createWindow();
}
void checkForUpdates("menu");
}
function configureApplicationMenu(): void {
const template: MenuItemConstructorOptions[] = [];
@@ -264,6 +496,11 @@ function configureApplicationMenu(): void {
label: app.name,
submenu: [
{ role: "about" },
{
label: "Check for Updates...",
click: () => handleCheckForUpdatesMenuClick(),
},
{ type: "separator" },
{
label: "Settings...",
accelerator: "CmdOrCtrl+,",
@@ -301,6 +538,15 @@ function configureApplicationMenu(): void {
{ role: "editMenu" },
{ role: "viewMenu" },
{ role: "windowMenu" },
{
role: "help",
submenu: [
{
label: "Check for Updates...",
click: () => handleCheckForUpdatesMenuClick(),
},
],
},
);
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
@@ -308,13 +554,13 @@ function configureApplicationMenu(): void {
function resolveResourcePath(fileName: string): string | null {
const candidates = [
path.join(__dirname, "../resources", fileName),
path.join(process.resourcesPath, "resources", fileName),
path.join(process.resourcesPath, fileName),
Path.join(__dirname, "../resources", fileName),
Path.join(process.resourcesPath, "resources", fileName),
Path.join(process.resourcesPath, fileName),
];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
if (FS.existsSync(candidate)) {
return candidate;
}
}
@@ -347,24 +593,200 @@ function configureAppIdentity(): void {
}
}
async function reserveLoopbackPort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.listen(0, "127.0.0.1", () => {
const address = probe.address();
const port = typeof address === "object" && address !== null ? address.port : 0;
probe.close(() => {
if (port > 0) {
resolve(port);
return;
}
reject(new Error("Failed to reserve backend port"));
});
});
probe.on("error", reject);
});
function clearUpdatePollTimer(): void {
if (updateStartupTimer) {
clearTimeout(updateStartupTimer);
updateStartupTimer = null;
}
if (updatePollTimer) {
clearInterval(updatePollTimer);
updatePollTimer = null;
}
}
function emitUpdateState(): void {
for (const window of BrowserWindow.getAllWindows()) {
if (window.isDestroyed()) continue;
window.webContents.send(UPDATE_STATE_CHANNEL, updateState);
}
}
function setUpdateState(patch: Partial<DesktopUpdateState>): void {
updateState = { ...updateState, ...patch };
emitUpdateState();
}
function shouldEnableAutoUpdates(): boolean {
return (
getAutoUpdateDisabledReason({
isDevelopment,
isPackaged: app.isPackaged,
platform: process.platform,
appImage: process.env.APPIMAGE,
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
}) === null
);
}
async function checkForUpdates(reason: string): Promise<void> {
if (isQuitting || !updaterConfigured || updateCheckInFlight) return;
if (updateState.status === "downloading" || updateState.status === "downloaded") {
console.info(
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
);
return;
}
updateCheckInFlight = true;
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
console.info(`[desktop-updater] Checking for updates (${reason})...`);
try {
await autoUpdater.checkForUpdates();
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
setUpdateState(reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()));
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
} finally {
updateCheckInFlight = false;
}
}
async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
return { accepted: false, completed: false };
}
updateDownloadInFlight = true;
setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState));
console.info("[desktop-updater] Downloading update...");
try {
await autoUpdater.downloadUpdate();
return { accepted: true, completed: true };
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
setUpdateState(reduceDesktopUpdateStateOnDownloadFailure(updateState, message));
console.error(`[desktop-updater] Failed to download update: ${message}`);
return { accepted: true, completed: false };
} finally {
updateDownloadInFlight = false;
}
}
async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
return { accepted: false, completed: false };
}
isQuitting = true;
clearUpdatePollTimer();
try {
await stopBackendAndWaitForExit();
autoUpdater.quitAndInstall();
return { accepted: true, completed: true };
} catch (error: unknown) {
const message = formatErrorMessage(error);
isQuitting = false;
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
console.error(`[desktop-updater] Failed to install update: ${message}`);
return { accepted: true, completed: false };
}
}
function configureAutoUpdater(): void {
const enabled = shouldEnableAutoUpdates();
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion()),
enabled,
status: enabled ? "idle" : "disabled",
});
if (!enabled) {
return;
}
updaterConfigured = true;
const githubToken =
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() ||
process.env.GH_TOKEN?.trim() ||
"";
if (githubToken) {
// When a token is provided, re-configure the feed with `private: true` so
// electron-updater uses the GitHub API (api.github.com) instead of the
// public Atom feed (github.com/…/releases.atom) which rejects Bearer auth.
const appUpdateYml = readAppUpdateYml();
if (appUpdateYml?.provider === "github") {
autoUpdater.setFeedURL({
...appUpdateYml,
provider: "github" as const,
private: true,
token: githubToken,
});
}
}
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
autoUpdater.allowPrerelease = app.getVersion().includes("-");
let lastLoggedDownloadMilestone = -1;
autoUpdater.on("checking-for-update", () => {
console.info("[desktop-updater] Looking for updates...");
});
autoUpdater.on("update-available", (info) => {
setUpdateState(reduceDesktopUpdateStateOnUpdateAvailable(updateState, info.version, new Date().toISOString()));
lastLoggedDownloadMilestone = -1;
console.info(`[desktop-updater] Update available: ${info.version}`);
});
autoUpdater.on("update-not-available", () => {
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
lastLoggedDownloadMilestone = -1;
console.info("[desktop-updater] No updates available.");
});
autoUpdater.on("error", (error) => {
const message = formatErrorMessage(error);
if (!updateCheckInFlight && !updateDownloadInFlight) {
setUpdateState({
status: "error",
message,
checkedAt: new Date().toISOString(),
downloadPercent: null,
errorContext: resolveUpdaterErrorContext(),
canRetry: updateState.availableVersion !== null || updateState.downloadedVersion !== null,
});
}
console.error(`[desktop-updater] Updater error: ${message}`);
});
autoUpdater.on("download-progress", (progress) => {
const percent = Math.floor(progress.percent);
if (
shouldBroadcastDownloadProgress(updateState, progress.percent) ||
updateState.message !== null
) {
setUpdateState(reduceDesktopUpdateStateOnDownloadProgress(updateState, progress.percent));
}
const milestone = percent - (percent % 10);
if (milestone > lastLoggedDownloadMilestone) {
lastLoggedDownloadMilestone = milestone;
console.info(`[desktop-updater] Download progress: ${percent}%`);
}
});
autoUpdater.on("update-downloaded", (info) => {
setUpdateState(reduceDesktopUpdateStateOnDownloadComplete(updateState, info.version));
console.info(`[desktop-updater] Update downloaded: ${info.version}`);
});
clearUpdatePollTimer();
updateStartupTimer = setTimeout(() => {
updateStartupTimer = null;
void checkForUpdates("startup");
}, AUTO_UPDATE_STARTUP_DELAY_MS);
updateStartupTimer.unref();
updatePollTimer = setInterval(() => {
void checkForUpdates("poll");
}, AUTO_UPDATE_POLL_INTERVAL_MS);
updatePollTimer.unref();
}
function backendEnv(): NodeJS.ProcessEnv {
return {
...process.env,
@@ -393,12 +815,13 @@ function startBackend(): void {
if (isQuitting || backendProcess) return;
const backendEntry = resolveBackendEntry();
if (!fs.existsSync(backendEntry)) {
if (!FS.existsSync(backendEntry)) {
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
return;
}
const child = spawn(process.execPath, [backendEntry], {
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
const child = ChildProcess.spawn(process.execPath, [backendEntry], {
cwd: resolveBackendCwd(),
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
@@ -406,9 +829,20 @@ function startBackend(): void {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
stdio: "inherit",
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
});
backendProcess = child;
let backendSessionClosed = false;
const closeBackendSession = (details: string) => {
if (backendSessionClosed) return;
backendSessionClosed = true;
writeBackendSessionBoundary("END", details);
};
writeBackendSessionBoundary(
"START",
`pid=${child.pid ?? "unknown"} port=${backendPort} cwd=${resolveBackendCwd()}`,
);
captureBackendOutput(child);
child.once("spawn", () => {
restartAttempt = 0;
@@ -418,6 +852,7 @@ function startBackend(): void {
if (backendProcess === child) {
backendProcess = null;
}
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
scheduleBackendRestart(error.message);
});
@@ -425,6 +860,9 @@ function startBackend(): void {
if (backendProcess === child) {
backendProcess = null;
}
closeBackendSession(
`pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
);
if (isQuitting) return;
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
scheduleBackendRestart(reason);
@@ -451,6 +889,57 @@ function stopBackend(): void {
}
}
async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = null;
}
const child = backendProcess;
backendProcess = null;
if (!child) return;
const backendChild = child;
if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
await new Promise<void>((resolve) => {
let settled = false;
let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
let exitTimeoutTimer: ReturnType<typeof setTimeout> | null = null;
function settle(): void {
if (settled) return;
settled = true;
backendChild.off("exit", onExit);
if (forceKillTimer) {
clearTimeout(forceKillTimer);
}
if (exitTimeoutTimer) {
clearTimeout(exitTimeoutTimer);
}
resolve();
}
function onExit(): void {
settle();
}
backendChild.once("exit", onExit);
backendChild.kill("SIGTERM");
forceKillTimer = setTimeout(() => {
if (backendChild.exitCode === null && backendChild.signalCode === null) {
backendChild.kill("SIGKILL");
}
}, 2_000);
forceKillTimer.unref();
exitTimeoutTimer = setTimeout(() => {
settle();
}, timeoutMs);
exitTimeoutTimer.unref();
});
}
function registerIpcHandlers(): void {
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
@@ -561,6 +1050,36 @@ function registerIpcHandlers(): void {
return false;
}
});
ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
const result = await downloadAvailableUpdate();
return {
accepted: result.accepted,
completed: result.completed,
state: updateState,
} satisfies DesktopUpdateActionResult;
});
ipcMain.removeHandler(UPDATE_INSTALL_CHANNEL);
ipcMain.handle(UPDATE_INSTALL_CHANNEL, async () => {
if (isQuitting) {
return {
accepted: false,
completed: false,
state: updateState,
} satisfies DesktopUpdateActionResult;
}
const result = await installDownloadedUpdate();
return {
accepted: result.accepted,
completed: result.completed,
state: updateState,
} satisfies DesktopUpdateActionResult;
});
}
function getIconOption(): { icon: string } | Record<string, never> {
@@ -583,7 +1102,7 @@ function createWindow(): BrowserWindow {
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 16, y: 18 },
webPreferences: {
preload: path.join(__dirname, "preload.js"),
preload: Path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
@@ -597,6 +1116,7 @@ function createWindow(): BrowserWindow {
});
window.webContents.on("did-finish-load", () => {
window.setTitle(APP_DISPLAY_NAME);
emitUpdateState();
});
window.once("ready-to-show", () => {
window.show();
@@ -621,33 +1141,55 @@ function createWindow(): BrowserWindow {
configureAppIdentity();
async function bootstrap(): Promise<void> {
backendPort = await reserveLoopbackPort();
backendAuthToken = randomBytes(24).toString("hex");
writeDesktopLogHeader("bootstrap start");
backendPort = await Effect.service(NetService).pipe(
Effect.flatMap((net) => net.reserveLoopbackPort()),
Effect.provide(NetService.layer),
Effect.runPromise,
);
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
backendAuthToken = Crypto.randomBytes(24).toString("hex");
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
registerIpcHandlers();
writeDesktopLogHeader("bootstrap ipc handlers registered");
startBackend();
writeDesktopLogHeader("bootstrap backend start requested");
mainWindow = createWindow();
writeDesktopLogHeader("bootstrap main window created");
}
app.on("before-quit", () => {
isQuitting = true;
writeDesktopLogHeader("before-quit received");
clearUpdatePollTimer();
stopBackend();
restoreStdIoCapture?.();
});
app.whenReady().then(() => {
configureAppIdentity();
configureApplicationMenu();
registerDesktopProtocol();
void bootstrap();
app
.whenReady()
.then(() => {
writeDesktopLogHeader("app ready");
configureAppIdentity();
configureApplicationMenu();
registerDesktopProtocol();
configureAutoUpdater();
void bootstrap().catch((error) => {
handleFatalStartupError("bootstrap", error);
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
mainWindow = createWindow();
}
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
mainWindow = createWindow();
}
});
})
.catch((error) => {
handleFatalStartupError("whenReady", error);
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
@@ -659,14 +1201,20 @@ if (process.platform !== "win32") {
process.on("SIGINT", () => {
if (isQuitting) return;
isQuitting = true;
writeDesktopLogHeader("SIGINT received");
clearUpdatePollTimer();
stopBackend();
restoreStdIoCapture?.();
app.quit();
});
process.on("SIGTERM", () => {
if (isQuitting) return;
isQuitting = true;
writeDesktopLogHeader("SIGTERM received");
clearUpdatePollTimer();
stopBackend();
restoreStdIoCapture?.();
app.quit();
});
}
+18
View File
@@ -6,6 +6,10 @@ const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
@@ -25,4 +29,18 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
onUpdateState: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
if (typeof state !== "object" || state === null) return;
listener(state as Parameters<typeof listener>[0]);
};
ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
};
},
} satisfies DesktopBridge);
+74
View File
@@ -0,0 +1,74 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { afterEach, describe, expect, it } from "vitest";
const tempRoots: string[] = [];
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-rotating-log-"));
tempRoots.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempRoots.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("RotatingFileSink", () => {
it("rotates when writes exceed max bytes", () => {
const dir = makeTempDir();
const logPath = path.join(dir, "desktop-main.log");
const sink = new RotatingFileSink({
filePath: logPath,
maxBytes: 10,
maxFiles: 3,
});
sink.write("12345");
sink.write("67890");
sink.write("abc");
expect(fs.readFileSync(path.join(dir, "desktop-main.log"), "utf8")).toBe("abc");
expect(fs.readFileSync(path.join(dir, "desktop-main.log.1"), "utf8")).toBe("1234567890");
});
it("retains only maxFiles backups", () => {
const dir = makeTempDir();
const logPath = path.join(dir, "server-child.log");
const sink = new RotatingFileSink({
filePath: logPath,
maxBytes: 4,
maxFiles: 2,
});
sink.write("aaaa");
sink.write("bbbb");
sink.write("cccc");
sink.write("dddd");
expect(fs.existsSync(path.join(dir, "server-child.log.1"))).toBe(true);
expect(fs.existsSync(path.join(dir, "server-child.log.2"))).toBe(true);
expect(fs.existsSync(path.join(dir, "server-child.log.3"))).toBe(false);
});
it("prunes stale backups above maxFiles on startup", () => {
const dir = makeTempDir();
const logPath = path.join(dir, "desktop-main.log");
fs.writeFileSync(path.join(dir, "desktop-main.log.1"), "first");
fs.writeFileSync(path.join(dir, "desktop-main.log.4"), "stale");
const sink = new RotatingFileSink({
filePath: logPath,
maxBytes: 16,
maxFiles: 2,
});
sink.write("hello");
expect(fs.existsSync(path.join(dir, "desktop-main.log.4"))).toBe(false);
});
});
+130
View File
@@ -0,0 +1,130 @@
import { describe, expect, it } from "vitest";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
reduceDesktopUpdateStateOnCheckStart,
reduceDesktopUpdateStateOnDownloadComplete,
reduceDesktopUpdateStateOnDownloadFailure,
reduceDesktopUpdateStateOnDownloadProgress,
reduceDesktopUpdateStateOnDownloadStart,
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
describe("updateMachine", () => {
it("clears transient errors when a check starts", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "error",
message: "network",
errorContext: "check",
canRetry: true,
},
"2026-03-04T00:00:00.000Z",
);
expect(state.status).toBe("checking");
expect(state.message).toBeNull();
expect(state.errorContext).toBeNull();
expect(state.canRetry).toBe(false);
});
it("records a check failure without exposing an action", () => {
const state = reduceDesktopUpdateStateOnCheckFailure(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "checking",
},
"network unavailable",
"2026-03-04T00:00:00.000Z",
);
expect(state.status).toBe("error");
expect(state.errorContext).toBe("check");
expect(state.canRetry).toBe(true);
});
it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
downloadPercent: 43,
},
"checksum mismatch",
);
expect(state.status).toBe("available");
expect(state.availableVersion).toBe("1.1.0");
expect(state.errorContext).toBe("download");
expect(state.canRetry).toBe(true);
});
it("transitions to downloaded and then preserves install retry state", () => {
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
},
"1.1.0",
);
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");
expect(downloaded.status).toBe("downloaded");
expect(downloaded.downloadedVersion).toBe("1.1.0");
expect(failedInstall.status).toBe("downloaded");
expect(failedInstall.errorContext).toBe("install");
expect(failedInstall.canRetry).toBe(true);
});
it("clears stale download state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "error",
availableVersion: "1.1.0",
downloadedVersion: "1.1.0",
message: "old failure",
errorContext: "download",
canRetry: true,
},
"2026-03-04T00:00:00.000Z",
);
expect(state.status).toBe("up-to-date");
expect(state.availableVersion).toBeNull();
expect(state.downloadedVersion).toBeNull();
expect(state.message).toBeNull();
expect(state.errorContext).toBeNull();
});
it("tracks available, download start, and progress cleanly", () => {
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "checking",
},
"1.1.0",
"2026-03-04T00:00:00.000Z",
);
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
expect(available.status).toBe("available");
expect(downloading.status).toBe("downloading");
expect(downloading.downloadPercent).toBe(0);
expect(progress.downloadPercent).toBe(55.5);
expect(progress.errorContext).toBeNull();
});
});
+155
View File
@@ -0,0 +1,155 @@
import type { DesktopUpdateState } from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
export function createInitialDesktopUpdateState(currentVersion: string): DesktopUpdateState {
return {
enabled: false,
status: "disabled",
currentVersion,
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
checkedAt: null,
message: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnCheckStart(
state: DesktopUpdateState,
checkedAt: string,
): DesktopUpdateState {
return {
...state,
status: "checking",
checkedAt,
message: null,
downloadPercent: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnCheckFailure(
state: DesktopUpdateState,
message: string,
checkedAt: string,
): DesktopUpdateState {
return {
...state,
status: "error",
message,
checkedAt,
downloadPercent: null,
errorContext: "check",
canRetry: true,
};
}
export function reduceDesktopUpdateStateOnUpdateAvailable(
state: DesktopUpdateState,
version: string,
checkedAt: string,
): DesktopUpdateState {
return {
...state,
status: "available",
availableVersion: version,
downloadedVersion: null,
downloadPercent: null,
checkedAt,
message: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnNoUpdate(
state: DesktopUpdateState,
checkedAt: string,
): DesktopUpdateState {
return {
...state,
status: "up-to-date",
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
checkedAt,
message: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnDownloadStart(
state: DesktopUpdateState,
): DesktopUpdateState {
return {
...state,
status: "downloading",
downloadPercent: 0,
message: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnDownloadFailure(
state: DesktopUpdateState,
message: string,
): DesktopUpdateState {
return {
...state,
status: nextStatusAfterDownloadFailure(state),
message,
downloadPercent: null,
errorContext: "download",
canRetry: getCanRetryAfterDownloadFailure(state),
};
}
export function reduceDesktopUpdateStateOnDownloadProgress(
state: DesktopUpdateState,
percent: number,
): DesktopUpdateState {
return {
...state,
status: "downloading",
downloadPercent: percent,
message: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnDownloadComplete(
state: DesktopUpdateState,
version: string,
): DesktopUpdateState {
return {
...state,
status: "downloaded",
availableVersion: version,
downloadedVersion: version,
downloadPercent: 100,
message: null,
errorContext: null,
canRetry: true,
};
}
export function reduceDesktopUpdateStateOnInstallFailure(
state: DesktopUpdateState,
message: string,
): DesktopUpdateState {
return {
...state,
status: "downloaded",
message,
errorContext: "install",
canRetry: true,
};
}
+142
View File
@@ -0,0 +1,142 @@
import { describe, expect, it } from "vitest";
import type { DesktopUpdateState } from "@t3tools/contracts";
import {
getCanRetryAfterDownloadFailure,
getAutoUpdateDisabledReason,
nextStatusAfterDownloadFailure,
shouldBroadcastDownloadProgress,
} from "./updateState";
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
currentVersion: "1.0.0",
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
checkedAt: null,
message: null,
errorContext: null,
canRetry: false,
};
describe("shouldBroadcastDownloadProgress", () => {
it("broadcasts the first downloading progress update", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: null },
1,
),
).toBe(true);
});
it("skips progress updates within the same 10% bucket", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: 11.2 },
18.7,
),
).toBe(false);
});
it("broadcasts progress updates when a new 10% bucket is reached", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: 19.9 },
20.1,
),
).toBe(true);
});
it("broadcasts progress updates when a retry resets the download percentage", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: 50.4 },
0.2,
),
).toBe(true);
});
});
describe("getAutoUpdateDisabledReason", () => {
it("reports development builds as disabled", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: true,
isPackaged: false,
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
}),
).toContain("packaged production builds");
});
it("reports env-disabled auto updates", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "darwin",
appImage: undefined,
disabledByEnv: true,
}),
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
});
it("reports linux non-AppImage builds as disabled", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "linux",
appImage: undefined,
disabledByEnv: false,
}),
).toContain("AppImage");
});
});
describe("nextStatusAfterDownloadFailure", () => {
it("returns available when an update version is still known", () => {
expect(
nextStatusAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: "1.1.0",
}),
).toBe("available");
});
it("returns error when no update version can be retried", () => {
expect(
nextStatusAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: null,
}),
).toBe("error");
});
});
describe("getCanRetryAfterDownloadFailure", () => {
it("returns true when an available version is still present", () => {
expect(
getCanRetryAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: "1.1.0",
}),
).toBe(true);
});
it("returns false when no version is available to retry", () => {
expect(
getCanRetryAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: null,
}),
).toBe(false);
});
});
+48
View File
@@ -0,0 +1,48 @@
import type { DesktopUpdateState } from "@t3tools/contracts";
export function shouldBroadcastDownloadProgress(
currentState: DesktopUpdateState,
nextPercent: number,
): boolean {
if (currentState.status !== "downloading") {
return true;
}
const currentPercent = currentState.downloadPercent;
if (currentPercent === null) {
return true;
}
const previousStep = Math.floor(currentPercent / 10);
const nextStep = Math.floor(nextPercent / 10);
return nextStep !== previousStep || nextPercent === 100;
}
export function nextStatusAfterDownloadFailure(
currentState: DesktopUpdateState,
): DesktopUpdateState["status"] {
return currentState.availableVersion ? "available" : "error";
}
export function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean {
return currentState.availableVersion !== null;
}
export function getAutoUpdateDisabledReason(args: {
isDevelopment: boolean;
isPackaged: boolean;
platform: NodeJS.Platform;
appImage?: string | undefined;
disabledByEnv: boolean;
}): string | null {
if (args.isDevelopment || !args.isPackaged) {
return "Automatic updates are only available in packaged production builds.";
}
if (args.disabledByEnv) {
return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
}
if (args.platform === "linux" && !args.appImage) {
return "Automatic updates on Linux require running the AppImage build.";
}
return null;
}
+1 -1
View File
@@ -12,7 +12,7 @@ export default defineConfig([
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: ["@t3tools/contracts"],
noExternal: (id) => id.startsWith("@t3tools/"),
},
{
...shared,
+18 -10
View File
@@ -1,6 +1,11 @@
{
"name": "t3",
"version": "0.0.0-alpha.4",
"version": "0.0.0-alpha.20",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
"directory": "apps/server"
},
"bin": {
"t3": "./dist/index.mjs"
},
@@ -8,10 +13,9 @@
"dist"
],
"type": "module",
"main": "./dist/index.mjs",
"scripts": {
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5733} bun run src/index.ts",
"build": "tsdown && node scripts/bundle-client.ts",
"dev": "bun run src/index.ts",
"build": "node scripts/cli.ts build",
"start": "node dist/index.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
@@ -27,15 +31,19 @@
"ws": "^8.18.0"
},
"devDependencies": {
"@effect/language-service": "0.75.1",
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0"
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"engines": {
"node": "^22.13 || ^23.4 || >=24.10"
}
}
-19
View File
@@ -1,19 +0,0 @@
/**
* Copies the built web app into dist/client/ so the published npm package
* includes the web UI. This runs as a post-build step.
*/
import * as fs from "node:fs";
import * as path from "node:path";
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
const target = path.resolve(import.meta.dirname, "../dist/client");
if (!fs.existsSync(webDist)) {
console.log(
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
);
process.exit(0);
}
fs.cpSync(webDist, target, { recursive: true });
console.log("✓ Bundled web app into dist/client");
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
class CliError extends Data.TaggedError("CliError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
);
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(command);
const exitCode = yield* child.exitCode;
if (exitCode !== 0) {
return yield* new CliError({
message: `Command exited with non-zero exit code (${exitCode})`,
});
}
});
// ---------------------------------------------------------------------------
// build subcommand
// ---------------------------------------------------------------------------
const buildCmd = Command.make(
"build",
{
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
},
(config) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
yield* Effect.log("[cli] Running tsdown...");
yield* runCommand(
ChildProcess.make({
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
})`bun tsdown`,
);
const webDist = path.join(repoRoot, "apps/web/dist");
const clientTarget = path.join(serverDir, "dist/client");
if (yield* fs.exists(webDist)) {
yield* fs.copy(webDist, clientTarget);
yield* Effect.log("[cli] Bundled web app into dist/client");
} else {
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
}
}),
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
// ---------------------------------------------------------------------------
// publish subcommand
// ---------------------------------------------------------------------------
const publishCmd = Command.make(
"publish",
{
tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
access: Flag.string("access").pipe(Flag.withDefault("public")),
appVersion: Flag.string("app-version").pipe(Flag.optional),
provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
},
(config) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
const packageJsonPath = path.join(serverDir, "package.json");
const backupPath = `${packageJsonPath}.bak`;
// Assert build assets exist
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new CliError({
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
});
}
}
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
Effect.gen(function* () {
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
// Build package.json for publish
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg = {
name: serverPackageJson.name,
repository: serverPackageJson.repository,
bin: serverPackageJson.bin,
type: serverPackageJson.type,
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
};
// Resolve catalog: entries in production dependencies
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* Effect.log("[cli] Resolved package.json for publish");
}),
// Use: npm publish
() =>
Effect.gen(function* () {
const args = ["publish", "--access", config.access, "--tag", config.tag];
if (config.provenance) args.push("--provenance");
if (config.dryRun) args.push("--dry-run");
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
yield* runCommand(
ChildProcess.make("npm", [...args], {
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
}),
);
}),
// Release: restore
() =>
Effect.gen(function* () {
yield* fs.rename(backupPath, packageJsonPath);
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
}),
);
}),
).pipe(Command.withDescription("Publish the server package to npm."));
// ---------------------------------------------------------------------------
// root command
// ---------------------------------------------------------------------------
const cli = Command.make("cli").pipe(
Command.withDescription("T3 server build & publish CLI."),
Command.withSubcommands([buildCmd, publishCmd]),
);
Command.run(cli, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
NodeRuntime.runMain,
);
+20 -2
View File
@@ -1,4 +1,4 @@
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import { EventEmitter } from "node:events";
import readline from "node:readline";
@@ -104,6 +104,23 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"does not exist",
];
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChildTree(child: ChildProcessWithoutNullStreams): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill();
}
export function normalizeCodexModelSlug(
model: string | undefined | null,
preferredId?: string,
@@ -185,6 +202,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
},
stdio: ["pipe", "pipe", "pipe"],
shell: process.platform === "win32",
});
const output = readline.createInterface({ input: child.stdout });
@@ -475,7 +493,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context.output.close();
if (!context.child.killed) {
context.child.kill();
killChildTree(context.child);
}
this.updateSession(context, {
+2 -65
View File
@@ -1,13 +1,12 @@
/**
* ServerConfig and NetService - Runtime configuration services.
* ServerConfig - Runtime configuration services.
*
* Defines process-level server configuration and networking helpers used by
* startup and runtime layers.
*
* @module ServerConfig
*/
import * as Net from "node:net";
import { Data, Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
export const DEFAULT_PORT = 3773;
@@ -60,68 +59,6 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
);
}
// Helpers
export class NetError extends Data.TaggedError("NetError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
/**
* NetServiceShape - Networking helper operations used during startup.
*/
export interface NetServiceShape {
/**
* Resolve an available listening port, preferring the provided port first.
*
* Falls back to an ephemeral OS-assigned port when the preferred port is in use.
*/
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
}
/**
* NetService - Service tag for startup networking helpers.
*/
export class NetService extends ServiceMap.Service<NetService, NetServiceShape>()(
"t3/config/NetService",
) {
static readonly layer = Layer.succeed(NetService, {
findAvailablePort: (preferred) =>
Effect.callback<number, NetError>((resume) => {
let fallbackServer: Net.Server | null = null;
const server = Net.createServer();
server.listen(preferred, () => {
server.close(() => resume(Effect.succeed(preferred)));
});
server.on("error", () => {
const fallback = Net.createServer();
fallback.listen(0, () => {
const addr = fallback.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
fallback.close(() => {
resume(
port > 0
? Effect.succeed(port)
: Effect.fail(new NetError({ message: "Could not find an available port." })),
);
});
});
fallback.on("error", (cause) => {
resume(
Effect.fail(new NetError({ message: "Failed to find an available port", cause })),
);
});
fallbackServer = fallback;
});
return Effect.sync(() => {
server.close();
fallbackServer?.close();
});
}),
});
}
export const resolveStaticDir = Effect.fn(function* () {
const { join, resolve } = yield* Path.Path;
const { exists } = yield* FileSystem.FileSystem;
@@ -189,7 +189,7 @@ function withFakeCodexEnv<A, E, R>(
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
it.effect("generates and sanitizes commit messages", () =>
it.effect("generates and sanitizes commit messages without branch by default", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
@@ -197,6 +197,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
" Add important change to the system with too much detail and a trailing period.\nsecondary line",
body: "\n- added migration\n- updated tests\n",
}),
stdinMustNotContain: "branch must be a short semantic git branch fragment",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
@@ -211,6 +212,34 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
expect(generated.subject.length).toBeLessThanOrEqual(72);
expect(generated.subject.endsWith(".")).toBe(false);
expect(generated.body).toBe("- added migration\n- updated tests");
expect(generated.branch).toBeUndefined();
}),
),
);
it.effect("generates commit message with branch when includeBranch is true", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
subject: "Add important change",
body: "",
branch: "fix/important-system-change",
}),
stdinMustContain: "branch must be a short semantic git branch fragment",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
includeBranch: true,
});
expect(generated.subject).toBe("Add important change");
expect(generated.branch).toBe("feature/fix/important-system-change");
}),
),
);
@@ -3,6 +3,8 @@ import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../Errors.ts";
@@ -93,24 +95,6 @@ function sanitizePrTitle(raw: string): string {
return "Update project changes";
}
function sanitizeBranchName(raw: string): string {
const normalized = raw
.trim()
.toLowerCase()
.replace(/['"`]/g, "")
.replace(/^[./\s_-]+|[./\s_-]+$/g, "");
const branchFragment = normalized
.replace(/[^a-z0-9/_-]+/g, "-")
.replace(/\/+/g, "/")
.replace(/-+/g, "-")
.replace(/^[./_-]+|[./_-]+$/g, "")
.slice(0, 64)
.replace(/[./_-]+$/g, "");
return branchFragment.length > 0 ? branchFragment : "update";
}
const makeCodexTextGeneration = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -240,6 +224,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.make(new TextEncoder().encode(prompt)),
},
@@ -328,12 +313,19 @@ const makeCodexTextGeneration = Effect.gen(function* () {
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
const wantsBranch = input.includeBranch === true;
const prompt = [
"You write concise git commit messages.",
"Return a JSON object with keys: subject, body.",
wantsBranch
? "Return a JSON object with keys: subject, body, branch."
: "Return a JSON object with keys: subject, body.",
"Rules:",
"- subject must be imperative, <= 72 chars, and no trailing period",
"- body can be empty string or short bullet points",
...(wantsBranch
? ["- branch must be a short semantic git branch fragment for this change"]
: []),
"- capture the primary user-visible or developer-visible change",
"",
`Branch: ${input.branch ?? "(detached)"}`,
@@ -345,20 +337,31 @@ const makeCodexTextGeneration = Effect.gen(function* () {
limitSection(input.stagedPatch, 40_000),
].join("\n");
const outputSchemaJson = wantsBranch
? Schema.Struct({
subject: Schema.String,
body: Schema.String,
branch: Schema.String,
})
: Schema.Struct({
subject: Schema.String,
body: Schema.String,
});
return runCodexJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: Schema.Struct({
subject: Schema.String,
body: Schema.String,
}),
outputSchemaJson,
}).pipe(
Effect.map(
(generated) =>
({
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
}) satisfies CommitMessageGenerationResult,
),
);
@@ -408,7 +411,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
return Effect.gen(function* () {
const { imagePaths } = yield* materializeImageAttachments("generateBranchName", input.attachments);
const { imagePaths } = yield* materializeImageAttachments(
"generateBranchName",
input.attachments,
);
const attachmentLines = (input.attachments ?? []).map(
(attachment) =>
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
@@ -446,7 +452,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
});
return {
branch: sanitizeBranchName(generated.branch),
branch: sanitizeBranchFragment(generated.branch),
} satisfies BranchNameGenerationResult;
});
};
@@ -110,6 +110,7 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
createBranch: (input) => core.createBranch(input),
checkoutBranch: (input) => core.checkoutBranch(input),
initRepo: (input) => core.initRepo(input),
listLocalBranchNames: (cwd) => core.listLocalBranchNames(cwd),
} satisfies GitCoreShape;
});
+15
View File
@@ -1172,6 +1172,20 @@ const makeGitCore = Effect.gen(function* () {
fallbackErrorMessage: "git init failed",
}).pipe(Effect.asVoid);
const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) =>
runGitStdout("GitCore.listLocalBranchNames", cwd, [
"branch",
"--list",
"--format=%(refname:short)",
]).pipe(
Effect.map((stdout) =>
stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0),
),
);
return {
status,
statusDetails,
@@ -1188,6 +1202,7 @@ const makeGitCore = Effect.gen(function* () {
createBranch,
checkoutBranch,
initRepo,
listLocalBranchNames,
} satisfies GitCoreShape;
});
+134 -3
View File
@@ -32,7 +32,11 @@ interface FakeGitTextGeneration {
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
includeBranch?: boolean;
}) => Effect.Effect<
{ subject: string; body: string; branch?: string | undefined },
TextGenerationError
>;
generatePrContent: (input: {
cwd: string;
baseBranch: string;
@@ -104,10 +108,13 @@ function createBareRemote(): Effect.Effect<
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
const implementation: FakeGitTextGeneration = {
generateCommitMessage: () =>
generateCommitMessage: (input) =>
Effect.succeed({
subject: "Implement stacked git actions",
body: "",
...(input.includeBranch
? { branch: "feature/implement-stacked-git-actions" }
: {}),
}),
generatePrContent: () =>
Effect.succeed({
@@ -283,6 +290,7 @@ function runStackedAction(
cwd: string;
action: "commit" | "commit_push" | "commit_push_pr";
commitMessage?: string;
featureBranch?: boolean;
},
) {
return manager.runStackedAction(input);
@@ -475,6 +483,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("skipped_not_requested");
@@ -495,12 +504,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
textGeneration: {
generateCommitMessage: () =>
generateCommitMessage: (input) =>
Effect.sync(() => {
generatedCount += 1;
return {
subject: "this should not be used",
body: "",
...(input.includeBranch ? { branch: "feature/unused" } : {}),
};
}),
},
@@ -511,6 +521,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
commitMessage: "feat: custom summary line\n\n- details from user",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.commit.status).toBe("created");
expect(result.commit.subject).toBe("feat: custom summary line");
expect(generatedCount).toBe(0);
@@ -527,6 +538,101 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("creates feature branch, commits, and pushes with featureBranch option", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nfeature-branch\n");
let generatedCount = 0;
const { manager } = yield* makeManager({
textGeneration: {
generateCommitMessage: (input) =>
Effect.sync(() => {
generatedCount += 1;
return {
subject: "Implement stacked git actions",
body: "",
...(input.includeBranch
? { branch: "feature/implement-stacked-git-actions" }
: {}),
};
}),
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push",
featureBranch: true,
});
expect(result.branch.status).toBe("created");
expect(result.branch.name).toBe("feature/implement-stacked-git-actions");
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "HEAD"]).pipe(
Effect.map((result) => result.stdout.trim()),
),
).toBe("feature/implement-stacked-git-actions");
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
Effect.map((r) => r.stdout.trim()),
);
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", "HEAD"]).pipe(
Effect.map((r) => r.stdout.trim()),
);
expect(mergeBase).toBe(mainSha);
expect(generatedCount).toBe(1);
}),
);
it.effect("featureBranch uses custom commit message and derives branch name", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom-feature\n");
let generatedCount = 0;
const { manager } = yield* makeManager({
textGeneration: {
generateCommitMessage: (input) =>
Effect.sync(() => {
generatedCount += 1;
return {
subject: "unused",
body: "",
...(input.includeBranch ? { branch: "feature/unused" } : {}),
};
}),
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit",
featureBranch: true,
commitMessage: "feat: custom summary line\n\n- details from user",
});
expect(result.branch.status).toBe("created");
expect(result.branch.name).toBe("feature/feat-custom-summary-line");
expect(result.commit.status).toBe("created");
expect(result.commit.subject).toBe("feat: custom summary line");
expect(generatedCount).toBe(0);
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
Effect.map((r) => r.stdout.trim()),
);
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", result.branch.name!]).pipe(
Effect.map((r) => r.stdout.trim()),
);
expect(mergeBase).toBe(mainSha);
}),
);
it.effect("skips commit when there are no uncommitted changes", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -538,12 +644,32 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.commit.status).toBe("skipped_no_changes");
expect(result.push.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("skipped_not_requested");
}),
);
it.effect("featureBranch returns error when worktree is clean", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const { manager } = yield* makeManager();
const errorMessage = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit",
featureBranch: true,
}).pipe(
Effect.flip,
Effect.map((error) => error.message),
);
expect(errorMessage).toContain("no changes to commit");
}),
);
it.effect("commits and pushes with upstream auto-setup when needed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -559,6 +685,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
@@ -603,6 +730,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
@@ -635,6 +763,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.commit.status).toBe("skipped_no_changes");
expect(result.push.status).toBe("skipped_up_to_date");
}),
@@ -669,6 +798,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(42);
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
@@ -709,6 +839,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(88);
expect(
+140 -22
View File
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Path } from "effect";
import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { GitManagerError } from "../Errors.ts";
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
@@ -85,9 +86,14 @@ function limitContext(value: string, maxChars: number): string {
return `${value.slice(0, maxChars)}\n\n[truncated]`;
}
function sanitizeCommitMessage(generated: { subject: string; body: string }): {
function sanitizeCommitMessage(generated: {
subject: string;
body: string;
branch?: string | undefined;
}): {
subject: string;
body: string;
branch?: string | undefined;
} {
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const subject = rawSubject.replace(/[.]+$/g, "").trim();
@@ -95,9 +101,25 @@ function sanitizeCommitMessage(generated: { subject: string; body: string }): {
return {
subject: safeSubject,
body: generated.body.trim(),
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
};
}
interface CommitAndBranchSuggestion {
subject: string;
body: string;
branch?: string | undefined;
commitMessage: string;
}
function formatCommitMessage(subject: string, body: string): string {
const trimmedBody = body.trim();
if (trimmedBody.length === 0) {
return subject;
}
return `${subject}\n\n${trimmedBody}`;
}
function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
const normalized = raw.replace(/\r\n/g, "\n").trim();
if (normalized.length === 0) {
@@ -253,30 +275,72 @@ export const makeGitManager = Effect.gen(function* () {
return "main";
});
const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>
const resolveCommitAndBranchSuggestion = (input: {
cwd: string;
branch: string | null;
commitMessage?: string;
/** When true, also produce a semantic feature branch name. */
includeBranch?: boolean;
}) =>
Effect.gen(function* () {
const context = yield* gitCore.prepareCommitContext(cwd);
const context = yield* gitCore.prepareCommitContext(input.cwd);
if (!context) {
return null;
}
const customCommit = parseCustomCommitMessage(input.commitMessage ?? "");
if (customCommit) {
return {
subject: customCommit.subject,
body: customCommit.body,
...(input.includeBranch
? { branch: sanitizeFeatureBranchName(customCommit.subject) }
: {}),
commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),
};
}
const generated = yield* textGeneration
.generateCommitMessage({
cwd: input.cwd,
branch: input.branch,
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
...(input.includeBranch ? { includeBranch: true } : {}),
})
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
return {
subject: generated.subject,
body: generated.body,
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
commitMessage: formatCommitMessage(generated.subject, generated.body),
};
});
const runCommitStep = (
cwd: string,
branch: string | null,
commitMessage?: string,
preResolvedSuggestion?: CommitAndBranchSuggestion,
) =>
Effect.gen(function* () {
const suggestion =
preResolvedSuggestion ??
(yield* resolveCommitAndBranchSuggestion({
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
}));
if (!suggestion) {
return { status: "skipped_no_changes" as const };
}
let generated = parseCustomCommitMessage(commitMessage ?? "");
if (!generated) {
generated = yield* textGeneration
.generateCommitMessage({
cwd,
branch,
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
})
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
}
const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
return {
status: "created" as const,
commitSha,
subject: generated.subject,
subject: suggestion.subject,
};
});
@@ -381,34 +445,88 @@ export const makeGitManager = Effect.gen(function* () {
};
});
const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
Effect.gen(function* () {
const suggestion = yield* resolveCommitAndBranchSuggestion({
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
includeBranch: true,
});
if (!suggestion) {
return yield* gitManagerError(
"runFeatureBranchStep",
"Cannot create a feature branch because there are no changes to commit.",
);
}
const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
return {
branchStep: { status: "created" as const, name: resolvedBranch },
resolvedCommitMessage: suggestion.commitMessage,
resolvedCommitSuggestion: suggestion,
};
});
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
function* (input) {
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (wantsPush && !initialStatus.branch) {
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (wantsPr && !initialStatus.branch) {
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
let commitMessageForStep = input.commitMessage;
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
if (input.featureBranch) {
const result = yield* runFeatureBranchStep(
input.cwd,
initialStatus.branch,
input.commitMessage,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
} else {
branchStep = { status: "skipped_not_requested" as const };
}
const currentBranch = branchStep.name ?? initialStatus.branch;
const commit = yield* runCommitStep(
input.cwd,
currentBranch,
commitMessageForStep,
preResolvedCommitSuggestion,
);
const push = wantsPush
? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? yield* runPrStep(input.cwd, initialStatus.branch)
? yield* runPrStep(input.cwd, currentBranch)
: { status: "skipped_not_requested" as const };
return {
action: input.action,
branch: branchStep,
commit,
push,
pr,
+5
View File
@@ -157,6 +157,11 @@ export interface GitCoreShape {
* Initialize a repository in the provided directory.
*/
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
/**
* List local branch names (short format).
*/
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
}
/**
@@ -29,6 +29,7 @@ export interface GitManagerShape {
/**
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first.
*/
readonly runStackedAction: (
input: GitRunStackedActionInput,
@@ -17,11 +17,15 @@ export interface CommitMessageGenerationInput {
branch: string | null;
stagedSummary: string;
stagedPatch: string;
/** When true, the model also returns a semantic branch name for the change. */
includeBranch?: boolean;
}
export interface CommitMessageGenerationResult {
subject: string;
body: string;
/** Only present when `includeBranch` was set on the input. */
branch?: string | undefined;
}
export interface PrContentGenerationInput {
+1 -1
View File
@@ -8,7 +8,7 @@ import { OpenLive } from "./open";
import { Command } from "effect/unstable/cli";
import { version } from "../package.json" with { type: "json" };
import { ServerLive } from "./wsServer";
import { NetService } from "./config";
import { NetService } from "@t3tools/shared/Net";
const RuntimeLayer = Layer.empty.pipe(
Layer.provideMerge(CliConfig.layer),
+5 -1
View File
@@ -6,9 +6,10 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Command from "effect/unstable/cli/Command";
import { beforeEach } from "vitest";
import { NetService } from "@t3tools/shared/Net";
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
import { NetService, ServerConfig, type ServerConfigShape } from "./config";
import { ServerConfig, type ServerConfigShape } from "./config";
import { Open, type OpenShape } from "./open";
import { Server, type ServerShape } from "./wsServer";
@@ -33,6 +34,9 @@ const testLayer = Layer.mergeAll(
resolveStaticDir: Effect.undefined,
} satisfies CliConfigShape),
Layer.succeed(NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(0),
findAvailablePort,
}),
Layer.succeed(Server, {
+3 -1
View File
@@ -8,10 +8,10 @@
*/
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
import {
DEFAULT_PORT,
NetService,
resolveStaticDir,
ServerConfig,
type RuntimeMode,
@@ -21,6 +21,7 @@ import { fixPath, resolveStateDir } from "./os-jank";
import { Open } from "./open";
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
import { Server } from "./wsServer";
export class StartupError extends Data.TaggedError("StartupError")<{
@@ -197,6 +198,7 @@ const LayerLive = (input: CliInput) =>
Layer.empty.pipe(
Layer.provideMerge(makeServerRuntimeServicesLayer()),
Layer.provideMerge(makeServerProviderLayer()),
Layer.provideMerge(ProviderHealthLive),
Layer.provideMerge(SqlitePersistence.layerConfig),
Layer.provideMerge(ServerConfigLive(input)),
);
+28 -19
View File
@@ -224,28 +224,37 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
});
export const launchDetached = (launch: EditorLaunch) =>
Effect.callback<void, OpenError>((resume) => {
let child;
try {
child = spawn(launch.command, [...launch.args], {
detached: true,
stdio: "ignore",
});
} catch (error) {
return resume(
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
);
Effect.gen(function* () {
if (!isCommandAvailable(launch.command)) {
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
}
const handleSpawn = () => {
child.unref();
resume(Effect.void);
};
yield* Effect.callback<void, OpenError>((resume) => {
let child;
try {
child = spawn(launch.command, [...launch.args], {
detached: true,
stdio: "ignore",
shell: process.platform === "win32",
});
} catch (error) {
return resume(
Effect.fail(
new OpenError({ message: "failed to spawn detached process", cause: error }),
),
);
}
child.once("spawn", handleSpawn);
child.once("error", (cause) =>
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
);
const handleSpawn = () => {
child.unref();
resume(Effect.void);
};
child.once("spawn", handleSpawn);
child.once("error", (cause) =>
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
);
});
});
const make = Effect.gen(function* () {
+32 -4
View File
@@ -1,4 +1,4 @@
import { spawn } from "node:child_process";
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
export interface ProcessRunOptions {
cwd?: string | undefined;
@@ -37,11 +37,21 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
}
function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
if (process.platform !== "win32") return false;
if (code === 9009) return true;
return /is not recognized as an internal or external command/i.test(stderr);
}
function normalizeExitError(
command: string,
args: readonly string[],
result: ProcessRunResult,
): Error {
if (isWindowsCommandNotFound(result.code, result.stderr)) {
return new Error(`Command not found: ${command}`);
}
const reason = result.timedOut
? "timed out"
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
@@ -70,6 +80,23 @@ function normalizeBufferError(
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill(signal);
}
function appendChunkWithinLimit(
target: string,
currentBytes: number,
@@ -112,6 +139,7 @@ export async function runProcess(
cwd: options.cwd,
env: options.env,
stdio: "pipe",
shell: process.platform === "win32",
});
let stdout = "";
@@ -126,9 +154,9 @@ export async function runProcess(
const timeoutTimer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
killChild(child, "SIGTERM");
forceKillTimer = setTimeout(() => {
child.kill("SIGKILL");
killChild(child, "SIGKILL");
}, 1_000);
}, timeoutMs);
@@ -143,7 +171,7 @@ export async function runProcess(
};
const fail = (error: Error): void => {
child.kill("SIGTERM");
killChild(child, "SIGTERM");
finalize(() => {
reject(error);
});
@@ -15,7 +15,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { afterAll, assert, it, vi } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, Fiber, Layer, Stream } from "effect";
import { Effect, Fiber, Layer, Option, Stream } from "effect";
import {
CodexAppServerManager,
@@ -24,6 +24,7 @@ import {
import { ServerConfig } from "../../config.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
@@ -121,10 +122,21 @@ class FakeCodexManager extends CodexAppServerManager {
}
}
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
upsert: () => Effect.void,
getProvider: () =>
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
getBinding: () => Effect.succeed(Option.none()),
getThreadId: () => Effect.succeed(Option.none()),
remove: () => Effect.void,
listSessionIds: () => Effect.succeed([]),
});
const validationManager = new FakeCodexManager();
const validationLayer = it.layer(
makeCodexAdapterLive({ manager: validationManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
);
@@ -159,6 +171,7 @@ sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
const sessionErrorLayer = it.layer(
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
);
@@ -195,6 +208,7 @@ const lifecycleManager = new FakeCodexManager();
const lifecycleLayer = it.layer(
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
);
+38 -15
View File
@@ -17,7 +17,7 @@ import {
ProviderThreadId,
ProviderTurnId,
} from "@t3tools/contracts";
import { Effect, FileSystem, Layer, Queue, Schema, Stream } from "effect";
import { Effect, FileSystem, Layer, Option, Queue, Schema, Stream } from "effect";
import {
ProviderAdapterProcessError,
@@ -28,10 +28,11 @@ import {
type ProviderAdapterError,
} from "../Errors.ts";
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = "codex" as const;
@@ -39,6 +40,7 @@ export interface CodexAdapterLiveOptions {
readonly manager?: CodexAppServerManager;
readonly makeManager?: () => CodexAppServerManager;
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: EventNdjsonLogger;
}
function toMessage(cause: unknown, fallback: string): string {
@@ -430,10 +432,14 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const serverConfig = yield* Effect.service(ServerConfig);
const directory = yield* ProviderSessionDirectory;
const nativeEventLogger =
options?.nativeEventLogPath !== undefined
? makeEventNdjsonLogger(options.nativeEventLogPath)
: undefined;
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined);
const manager = yield* Effect.acquireRelease(
Effect.sync(() => {
@@ -495,9 +501,11 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
new Error(`Invalid attachment id '${attachment.id}'.`),
);
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError((cause) => toRequestError(input.sessionId, "turn/start", cause)),
);
const bytes = yield* fileSystem
.readFile(attachmentPath)
.pipe(
Effect.mapError((cause) => toRequestError(input.sessionId, "turn/start", cause)),
);
return {
type: "image" as const,
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
@@ -579,14 +587,29 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
yield* Effect.acquireRelease(
Effect.sync(() => {
const listener = (event: ProviderEvent) => {
nativeEventLogger?.write({
observedAt: new Date().toISOString(),
event,
Effect.gen(function* () {
const writeNativeEvent = (event: ProviderEvent) =>
Effect.gen(function* () {
if (!nativeEventLogger) {
return;
}
const orchestrationThreadId = yield* Effect.catch(
directory.getThreadId(event.sessionId).pipe(
Effect.map((threadIdOption) =>
Option.isSome(threadIdOption) ? threadIdOption.value : null,
),
),
() => Effect.succeed(null),
);
yield* nativeEventLogger.write(event, orchestrationThreadId);
});
Queue.offerAllUnsafe(runtimeEventQueue, mapToRuntimeEvents(event));
};
const services = yield* Effect.services<never>();
const listener = (event: ProviderEvent) =>
Effect.gen(function* () {
yield* writeNativeEvent(event);
yield* Queue.offerAll(runtimeEventQueue, mapToRuntimeEvents(event));
}).pipe(Effect.runPromiseWith(services));
manager.on("event", listener);
return listener;
}),
@@ -2,36 +2,165 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { ThreadId } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
function parseLogLine(line: string) {
const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
assert.notEqual(match, null);
if (!match) {
throw new Error(`invalid log line: ${line}`);
}
const observedAt = match[1];
const stream = match[2];
const payload = match[3];
if (!observedAt || !stream || payload === undefined) {
throw new Error(`invalid log line: ${line}`);
}
return {
observedAt,
stream,
payload,
};
}
describe("EventNdjsonLogger", () => {
it("writes NDJSON records to disk", () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const filePath = path.join(tempDir, "provider-native.ndjson");
it.effect("writes effect-style lines to thread-scoped files", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const basePath = path.join(tempDir, "provider-native.ndjson");
try {
const logger = makeEventNdjsonLogger(filePath);
expect(logger).toBeDefined();
if (!logger) {
return;
try {
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
assert.notEqual(logger, undefined);
if (!logger) {
return;
}
yield* logger.write(
{ threadId: "provider-thread-1", id: "evt-1" },
ThreadId.makeUnsafe("thread-1"),
);
yield* logger.write(
{ type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" },
ThreadId.makeUnsafe("thread-2"),
);
yield* logger.close();
const threadOnePath = path.join(tempDir, "thread-1.log");
const threadTwoPath = path.join(tempDir, "thread-2.log");
assert.equal(fs.existsSync(threadOnePath), true);
assert.equal(fs.existsSync(threadTwoPath), true);
const first = parseLogLine(fs.readFileSync(threadOnePath, "utf8").trim());
const second = parseLogLine(fs.readFileSync(threadTwoPath, "utf8").trim());
assert.equal(Number.isNaN(Date.parse(first.observedAt)), false);
assert.equal(first.stream, "NTIVE");
assert.equal(first.payload, '{"threadId":"provider-thread-1","id":"evt-1"}');
assert.equal(Number.isNaN(Date.parse(second.observedAt)), false);
assert.equal(second.stream, "NTIVE");
assert.equal(
second.payload,
'{"type":"turn.completed","threadId":"provider-thread-2","id":"evt-2"}',
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
logger.write({ type: "native", payload: { id: "evt-1" } });
logger.write({ type: "canonical", payload: { id: "evt-2" } });
logger.close();
it.effect(
"falls back to a global segment when orchestration thread id is missing or invalid",
() =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const basePath = path.join(tempDir, "provider-canonical.ndjson");
const raw = fs.readFileSync(filePath, "utf8").trim();
const lines = raw.split("\n");
expect(lines.length).toBe(2);
try {
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "orchestration" });
assert.notEqual(logger, undefined);
if (!logger) {
return;
}
const first = JSON.parse(lines[0] ?? "{}");
const second = JSON.parse(lines[1] ?? "{}");
expect(first).toEqual({ type: "native", payload: { id: "evt-1" } });
expect(second).toEqual({ type: "canonical", payload: { id: "evt-2" } });
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
yield* logger.write({ id: "evt-no-thread" }, null);
yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
yield* logger.close();
const globalPath = path.join(tempDir, "_global.log");
assert.equal(fs.existsSync(globalPath), true);
const lines = fs
.readFileSync(globalPath, "utf8")
.trim()
.split("\n")
.map((line) => parseLogLine(line));
assert.equal(lines.length, 2);
assert.equal(Number.isNaN(Date.parse(lines[0]?.observedAt ?? "")), false);
assert.equal(Number.isNaN(Date.parse(lines[1]?.observedAt ?? "")), false);
assert.equal(lines[0]?.stream, "CANON");
assert.equal(lines[0]?.payload, '{"id":"evt-no-thread"}');
assert.equal(lines[1]?.stream, "CANON");
assert.equal(lines[1]?.payload, '{"id":"evt-invalid-thread"}');
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("rotates per-thread files when max size is exceeded", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const basePath = path.join(tempDir, "provider-native.ndjson");
try {
const logger = yield* makeEventNdjsonLogger(basePath, {
stream: "native",
maxBytes: 120,
maxFiles: 2,
});
assert.notEqual(logger, undefined);
if (!logger) {
return;
}
for (let index = 0; index < 10; index += 1) {
yield* logger.write(
{
threadId: "provider-thread-rotate",
id: `evt-${index}`,
payload: "x".repeat(40),
},
ThreadId.makeUnsafe("thread-rotate"),
);
}
yield* logger.close();
const fileStem = "thread-rotate.log";
const matchingFiles = fs
.readdirSync(tempDir)
.filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
.toSorted();
assert.equal(
matchingFiles.some((entry) => entry === `${fileStem}.1`),
true,
);
assert.equal(
matchingFiles.some((entry) => entry === fileStem || entry === `${fileStem}.2`),
true,
);
assert.equal(
matchingFiles.some((entry) => entry === `${fileStem}.3`),
false,
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
});
@@ -1,66 +1,257 @@
/**
* Provider event NDJSON logger helper.
* Provider event logger helper.
*
* Best-effort writer for observability logs. Failures are downgraded to warnings
* so provider runtime behavior is unaffected.
* Best-effort writer for observability logs. Each record is formatted as a
* single effect-style text line in a thread-scoped file. Failures are
* downgraded to warnings so provider runtime behavior is unaffected.
*/
import fs from "node:fs";
import path from "node:path";
import { createLogger } from "../../logger.ts";
import type { ThreadId } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { Effect, Exit, Logger, Scope } from "effect";
const logger = createLogger("provider-observability");
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
const DEFAULT_MAX_FILES = 10;
const DEFAULT_BATCH_WINDOW_MS = 200;
const GLOBAL_THREAD_SEGMENT = "_global";
const LOG_SCOPE = "provider-observability";
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
export interface EventNdjsonLogger {
readonly filePath: string;
write: (record: unknown) => void;
close: () => void;
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
close: () => Effect.Effect<void>;
}
function stringifyRecord(record: unknown): string | undefined {
try {
return JSON.stringify(record);
} catch (error) {
logger.warn("failed to serialize provider event log record", { error });
return undefined;
export interface EventNdjsonLoggerOptions {
readonly stream: EventNdjsonStream;
readonly maxBytes?: number;
readonly maxFiles?: number;
readonly batchWindowMs?: number;
}
interface ThreadWriter {
writeMessage: (message: string) => Effect.Effect<void>;
close: () => Effect.Effect<void>;
}
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
}
function resolveThreadSegment(raw: string | null | undefined): string {
const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
return normalized ?? GLOBAL_THREAD_SEGMENT;
}
function formatLoggerMessage(message: unknown): string {
if (Array.isArray(message)) {
return message.map((part) => (typeof part === "string" ? part : String(part))).join(" ");
}
return typeof message === "string" ? message : String(message);
}
function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
return Logger.make(
({ date, message }) =>
`[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
);
}
function resolveStreamLabel(stream: EventNdjsonStream): string {
switch (stream) {
case "native":
return "NTIVE";
case "canonical":
case "orchestration":
default:
return "CANON";
}
}
export function makeEventNdjsonLogger(filePath: string): EventNdjsonLogger | undefined {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.appendFileSync(filePath, "", { encoding: "utf8", flag: "a" });
} catch (error) {
logger.warn("failed to create provider event log directory", { filePath, error });
return undefined;
}
function toLogMessage(event: unknown): Effect.Effect<string | undefined> {
return Effect.gen(function* () {
const serialized = yield* Effect.sync(() => {
try {
return { ok: true as const, value: JSON.stringify(event) };
} catch (error) {
return { ok: false as const, error };
}
});
try {
let broken = false;
if (!serialized.ok) {
yield* logWarning("failed to serialize provider event log record", {
error: serialized.error,
});
return undefined;
}
if (typeof serialized.value !== "string") {
return undefined;
}
return serialized.value;
});
}
function makeThreadWriter(input: {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly streamLabel: string;
}): Effect.Effect<ThreadWriter | undefined> {
return Effect.gen(function* () {
const sinkResult = yield* Effect.sync(() => {
try {
return {
ok: true as const,
sink: new RotatingFileSink({
filePath: input.filePath,
maxBytes: input.maxBytes,
maxFiles: input.maxFiles,
throwOnError: true,
}),
};
} catch (error) {
return { ok: false as const, error };
}
});
if (!sinkResult.ok) {
yield* logWarning("failed to initialize provider thread log file", {
filePath: input.filePath,
error: sinkResult.error,
});
return undefined;
}
const sink = sinkResult.sink;
const scope = yield* Scope.make();
const lineLogger = makeLineLogger(input.streamLabel);
const batchedLogger = yield* Logger.batched(lineLogger, {
window: input.batchWindowMs,
flush: (messages) =>
Effect.gen(function* () {
const flushResult = yield* Effect.sync(() => {
try {
for (const message of messages) {
sink.write(message);
}
return { ok: true as const };
} catch (error) {
return { ok: false as const, error };
}
});
if (!flushResult.ok) {
yield* logWarning("provider event log batch flush failed", {
filePath: input.filePath,
error: flushResult.error,
});
}
}),
}).pipe(Effect.provideService(Scope.Scope, scope));
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
return {
writeMessage(message: string) {
return Effect.log(message).pipe(Effect.provide(loggerLayer));
},
close() {
return Scope.close(scope, Exit.void);
},
} satisfies ThreadWriter;
});
}
export function makeEventNdjsonLogger(
filePath: string,
options: EventNdjsonLoggerOptions,
): Effect.Effect<EventNdjsonLogger | undefined> {
return Effect.gen(function* () {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
const streamLabel = resolveStreamLabel(options.stream);
const directoryReady = yield* Effect.sync(() => {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
return true;
} catch (error) {
return { ok: false as const, error };
}
});
if (directoryReady !== true) {
yield* logWarning("failed to create provider event log directory", {
filePath,
error: directoryReady.error,
});
return undefined;
}
const threadWriters = new Map<string, ThreadWriter>();
const failedSegments = new Set<string>();
const resolveThreadWriter = (threadSegment: string): Effect.Effect<ThreadWriter | undefined> =>
Effect.gen(function* () {
if (failedSegments.has(threadSegment)) {
return undefined;
}
const existing = threadWriters.get(threadSegment);
if (existing) {
return existing;
}
const writer = yield* makeThreadWriter({
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
});
if (!writer) {
failedSegments.add(threadSegment);
return undefined;
}
threadWriters.set(threadSegment, writer);
return writer;
});
return {
filePath,
write(record: unknown) {
if (broken) {
return;
}
const serialized = stringifyRecord(record);
if (!serialized) {
return;
}
try {
fs.appendFileSync(filePath, `${serialized}\n`, { encoding: "utf8", flag: "a" });
} catch (error) {
broken = true;
logger.warn("provider event log write failed", { filePath, error });
}
write(event: unknown, threadId: ThreadId | null) {
return Effect.gen(function* () {
const threadSegment = resolveThreadSegment(threadId);
const message = yield* toLogMessage(event);
if (!message) {
return;
}
const writer = yield* resolveThreadWriter(threadSegment);
if (!writer) {
return;
}
yield* writer.writeMessage(message);
});
},
close() {
// no-op for sync append logger
return Effect.gen(function* () {
for (const writer of threadWriters.values()) {
yield* writer.close();
}
threadWriters.clear();
});
},
};
} catch (error) {
logger.warn("failed to create provider event log file", { filePath, error });
return undefined;
}
} satisfies EventNdjsonLogger;
});
}
@@ -0,0 +1,190 @@
import assert from "node:assert/strict";
import { it } from "@effect/vitest";
import { Effect, Layer, Sink, Stream } from "effect";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { checkCodexProviderStatus, parseAuthStatusFromOutput } from "./ProviderHealth";
// ── Test helpers ────────────────────────────────────────────────────
const encoder = new TextEncoder();
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(result.stdout)),
stderr: Stream.make(encoder.encode(result.stderr)),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
function mockSpawnerLayer(
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const cmd = command as unknown as { args: ReadonlyArray<string> };
return Effect.succeed(mockHandle(handler(cmd.args)));
}),
);
}
function failingSpawnerLayer(description: string) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description,
}),
),
),
);
}
// ── Tests ───────────────────────────────────────────────────────────
it.effect("returns ready when codex is installed and authenticated", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unavailable when codex is missing", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
it.effect("returns unauthenticated when auth probe reports login required", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect(
"returns unauthenticated when login status output includes 'not logged in'",
() =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when login status command is unsupported", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
// ── Pure function tests ─────────────────────────────────────────────
it("parseAuthStatusFromOutput: exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("parseAuthStatusFromOutput: JSON with authenticated=false is unauthenticated", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"authenticated":false}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("parseAuthStatusFromOutput: JSON without auth marker is warning", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"ok":true}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
@@ -0,0 +1,303 @@
/**
* ProviderHealthLive - Startup-time provider health checks.
*
* Performs one-time provider readiness probes when the server starts and
* keeps the resulting snapshot in memory for `server.getConfig`.
*
* Uses effect's ChildProcessSpawner to run CLI probes natively.
*
* @module ProviderHealthLive
*/
import type {
ServerProviderAuthStatus,
ServerProviderStatus,
ServerProviderStatusState,
} from "@t3tools/contracts";
import { Effect, Layer, Option, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
const DEFAULT_TIMEOUT_MS = 4_000;
const CODEX_PROVIDER = "codex" as const;
// ── Pure helpers ────────────────────────────────────────────────────
export interface CommandResult {
readonly stdout: string;
readonly stderr: string;
readonly code: number;
}
function nonEmptyTrimmed(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function isCommandMissingCause(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const lower = error.message.toLowerCase();
return (
lower.includes("command not found: codex") ||
lower.includes("spawn codex enoent") ||
lower.includes("enoent") ||
lower.includes("notfound")
);
}
function detailFromResult(
result: CommandResult & { readonly timedOut?: boolean },
): string | undefined {
if (result.timedOut) return "Timed out while running command.";
const stderr = nonEmptyTrimmed(result.stderr);
if (stderr) return stderr;
const stdout = nonEmptyTrimmed(result.stdout);
if (stdout) return stdout;
if (result.code !== 0) {
return `Command exited with code ${result.code}.`;
}
return undefined;
}
function extractAuthBoolean(value: unknown): boolean | undefined {
if (Array.isArray(value)) {
for (const entry of value) {
const nested = extractAuthBoolean(entry);
if (nested !== undefined) return nested;
}
return undefined;
}
if (!value || typeof value !== "object") return undefined;
const record = value as Record<string, unknown>;
for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
if (typeof record[key] === "boolean") return record[key];
}
for (const key of ["auth", "status", "session", "account"] as const) {
const nested = extractAuthBoolean(record[key]);
if (nested !== undefined) return nested;
}
return undefined;
}
export function parseAuthStatusFromOutput(result: CommandResult): {
readonly status: ServerProviderStatusState;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
authStatus: "unknown",
message: "Codex CLI authentication status command is unavailable in this Codex version.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `codex login`") ||
lowerOutput.includes("run codex login")
) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
message:
"Could not verify Codex authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
message: detail
? `Could not verify Codex authentication status. ${detail}`
: "Could not verify Codex authentication status.",
};
}
// ── Effect-native command execution ─────────────────────────────────
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
Stream.runFold(
stream,
() => "",
(acc, chunk) => acc + new TextDecoder().decode(chunk),
);
const runCodexCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make("codex", [...args], {
shell: process.platform === "win32",
});
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
// ── Health check ────────────────────────────────────────────────────
export const checkCodexProviderStatus: Effect.Effect<
ServerProviderStatus,
never,
ChildProcessSpawner.ChildProcessSpawner
> = Effect.gen(function* () {
const checkedAt = new Date().toISOString();
// Probe 1: `codex --version` — is the CLI reachable?
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
};
}
if (Option.isNone(versionProbe.success)) {
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: "Codex CLI is installed but failed to run. Timed out while running command.",
};
}
const version = versionProbe.success.value;
if (version.code !== 0) {
const detail = detailFromResult(version);
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
};
}
// Probe 2: `codex login status` — is the user authenticated?
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return {
provider: CODEX_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
};
}
if (Option.isNone(authProbe.success)) {
return {
provider: CODEX_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message: "Could not verify Codex authentication status. Timed out while running command.",
};
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
return {
provider: CODEX_PROVIDER,
status: parsed.status,
available: true,
authStatus: parsed.authStatus,
checkedAt,
...(parsed.message ? { message: parsed.message } : {}),
} satisfies ServerProviderStatus;
});
// ── Layer ───────────────────────────────────────────────────────────
export const ProviderHealthLive = Layer.effect(
ProviderHealth,
Effect.gen(function* () {
const codexStatus = yield* checkCodexProviderStatus;
return {
getStatuses: Effect.succeed([codexStatus]),
} satisfies ProviderHealthShape;
}),
);
@@ -30,10 +30,11 @@ import {
ProviderSessionDirectory,
type ProviderSessionBinding,
} from "../Services/ProviderSessionDirectory.ts";
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
export interface ProviderServiceLiveOptions {
readonly canonicalEventLogPath?: string;
readonly canonicalEventLogger?: EventNdjsonLogger;
}
const ProviderRollbackConversationInput = Schema.Struct({
@@ -108,9 +109,12 @@ function readPersistedCwd(
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
Effect.gen(function* () {
const canonicalEventLogger =
options?.canonicalEventLogPath !== undefined
? makeEventNdjsonLogger(options.canonicalEventLogPath)
: undefined;
options?.canonicalEventLogger ??
(options?.canonicalEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
stream: "canonical",
})
: undefined);
const registry = yield* ProviderAdapterRegistry;
const directory = yield* ProviderSessionDirectory;
@@ -140,12 +144,20 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
canonicalizeRuntimeEventSession(event).pipe(
Effect.tap((canonicalEvent) =>
Effect.sync(() => {
canonicalEventLogger?.write({
observedAt: new Date().toISOString(),
event: canonicalEvent,
});
}),
canonicalEventLogger
? Effect.flatMap(
Effect.catch(
directory.getThreadId(canonicalEvent.sessionId).pipe(
Effect.map((threadIdOption) =>
Option.isSome(threadIdOption) ? threadIdOption.value : null,
),
),
() => Effect.succeed<ThreadId | null>(null),
),
(orchestrationThreadId) =>
canonicalEventLogger.write(canonicalEvent, orchestrationThreadId),
)
: Effect.void,
),
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
Effect.asVoid,
@@ -0,0 +1,22 @@
/**
* ProviderHealth - Provider readiness snapshot service.
*
* Owns startup-time provider health checks (install/auth reachability) and
* exposes the cached results to transport layers.
*
* @module ProviderHealth
*/
import type { ServerProviderStatus } from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
export interface ProviderHealthShape {
/**
* Read provider health statuses computed at server startup.
*/
readonly getStatuses: Effect.Effect<ReadonlyArray<ServerProviderStatus>>;
}
export class ProviderHealth extends ServiceMap.Service<ProviderHealth, ProviderHealthShape>()(
"t3/provider/Services/ProviderHealth",
) {}
+23 -8
View File
@@ -23,6 +23,7 @@ import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRe
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
import { ProviderService } from "./provider/Services/ProviderService";
import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger";
import { TerminalManagerLive } from "./terminal/Layers/Manager";
import { KeybindingsLive } from "./keybindings";
@@ -41,17 +42,27 @@ export function makeServerProviderLayer(): Layer.Layer<
> {
return Effect.gen(function* () {
const { stateDir } = yield* ServerConfig;
const providerLogsDir = path.join(stateDir, "logs", "providers");
const codexAdapterLayer = makeCodexAdapterLive({
nativeEventLogPath: path.join(providerLogsDir, "provider-native.ndjson"),
const providerLogsDir = path.join(stateDir, "logs", "provider");
const providerEventLogPath = path.join(providerLogsDir, "events.log");
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "canonical",
});
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(Layer.provide(codexAdapterLayer));
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
);
return makeProviderServiceLive({
canonicalEventLogPath: path.join(providerLogsDir, "provider-canonical.ndjson"),
}).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
const codexAdapterLayer = makeCodexAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
Layer.provide(codexAdapterLayer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
return makeProviderServiceLive(
canonicalEventLogger ? { canonicalEventLogger } : undefined,
).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
}).pipe(Layer.unwrap);
}
@@ -94,7 +105,11 @@ export function makeServerRuntimeServicesLayer() {
);
const terminalLayer = TerminalManagerLive.pipe(
Layer.provide(typeof Bun !== "undefined" ? BunPtyAdapterLive : NodePtyAdapterLive),
Layer.provide(
typeof Bun !== "undefined" && process.platform !== "win32"
? BunPtyAdapterLive
: NodePtyAdapterLive,
),
);
const gitManagerLayer = GitManagerLive.pipe(
+31 -1
View File
@@ -25,6 +25,7 @@ import {
WS_METHODS,
type WebSocketResponse,
type ProviderRuntimeEvent,
type ServerProviderStatus,
type KeybindingsConfig,
type ResolvedKeybindingsConfig,
type WsPush,
@@ -43,6 +44,7 @@ import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
import { SqlClient, SqlError } from "effect/unstable/sql";
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
import { ProviderHealth, type ProviderHealthShape } from "./provider/Services/ProviderHealth";
import { Open, type OpenShape } from "./open";
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
import type { GitCoreShape } from "./git/Services/GitCore.ts";
@@ -69,6 +71,20 @@ const defaultOpenService: OpenShape = {
openInEditor: () => Effect.void,
};
const defaultProviderStatuses: ReadonlyArray<ServerProviderStatus> = [
{
provider: "codex",
status: "ready",
available: true,
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
},
];
const defaultProviderHealthService: ProviderHealthShape = {
getStatuses: Effect.succeed(defaultProviderStatuses),
};
class MockTerminalManager implements TerminalManagerShape {
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
private readonly listeners = new Set<(event: TerminalEvent) => void>();
@@ -377,6 +393,7 @@ describe("WebSocket Server", () => {
stateDir?: string;
staticDir?: string;
providerLayer?: Layer.Layer<ProviderService, never>;
providerHealth?: ProviderHealthShape;
open?: OpenShape;
gitManager?: GitManagerShape;
gitCore?: Pick<
@@ -394,6 +411,10 @@ describe("WebSocket Server", () => {
const scope = await Effect.runPromise(Scope.make("sequential"));
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
const providerHealthLayer = Layer.succeed(
ProviderHealth,
options.providerHealth ?? defaultProviderHealthService,
);
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
const serverConfigLayer = Layer.succeed(ServerConfig, {
mode: "web",
@@ -428,6 +449,7 @@ describe("WebSocket Server", () => {
);
const dependenciesLayer = Layer.empty.pipe(
Layer.provideMerge(runtimeLayer),
Layer.provideMerge(providerHealthLayer),
Layer.provideMerge(openLayer),
Layer.provideMerge(serverConfigLayer),
Layer.provideMerge(NodeServices.layer),
@@ -736,6 +758,7 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
@@ -761,6 +784,7 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
@@ -796,6 +820,7 @@ describe("WebSocket Server", () => {
message: expect.stringContaining("expected JSON array"),
},
],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
@@ -830,6 +855,7 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: string;
keybindings: ResolvedKeybindingsConfig;
issues: Array<{ kind: string; index?: number; message: string }>;
providers: ReadonlyArray<ServerProviderStatus>;
availableEditors: unknown;
};
expect(result.cwd).toBe("/my/workspace");
@@ -849,6 +875,7 @@ describe("WebSocket Server", () => {
expect(result.keybindings).toHaveLength(DEFAULT_RESOLVED_KEYBINDINGS.length);
expect(result.keybindings.some((entry) => entry.command === "terminal.toggle")).toBe(true);
expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true);
expect(result.providers).toEqual(defaultProviderStatuses);
expectAvailableEditors(result.availableEditors);
});
@@ -877,6 +904,7 @@ describe("WebSocket Server", () => {
);
expect(malformedPush.data).toEqual({
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
providers: defaultProviderStatuses,
});
fs.writeFileSync(keybindingsPath, "[]", "utf8");
@@ -887,7 +915,7 @@ describe("WebSocket Server", () => {
Array.isArray((push.data as { issues?: unknown[] }).issues) &&
(push.data as { issues: unknown[] }).issues.length === 0,
);
expect(successPush.data).toEqual({ issues: [] });
expect(successPush.data).toEqual({ issues: [], providers: defaultProviderStatuses });
});
it("routes shell.openInEditor through the injected open service", async () => {
@@ -947,6 +975,7 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: compileKeybindings(persistedConfig),
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
@@ -994,6 +1023,7 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: compileKeybindings(persistedConfig),
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
});
expectAvailableEditors(
+11 -2
View File
@@ -52,6 +52,7 @@ import { OrchestrationEngineService } from "./orchestration/Services/Orchestrati
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
import { ProviderService } from "./provider/Services/ProviderService";
import { ProviderHealth } from "./provider/Services/ProviderHealth";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
import { clamp } from "effect/Number";
import { Open, resolveAvailableEditors } from "./open";
@@ -154,7 +155,8 @@ export type ServerCoreRuntimeServices =
| ProjectionSnapshotQuery
| CheckpointDiffQuery
| OrchestrationReactor
| ProviderService;
| ProviderService
| ProviderHealth;
export type ServerRuntimeServices =
| ServerCoreRuntimeServices
@@ -198,6 +200,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const gitManager = yield* GitManager;
const terminalManager = yield* TerminalManager;
const keybindingsManager = yield* Keybindings;
const providerHealth = yield* ProviderHealth;
const git = yield* GitCore;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -212,6 +215,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
),
);
const providerStatuses = yield* providerHealth.getStatuses;
const clients = yield* Ref.make(new Set<WebSocket>());
const logger = createLogger("ws");
@@ -537,7 +542,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
broadcastPush({
type: "push",
channel: WS_CHANNELS.serverConfigUpdated,
data: event,
data: {
issues: event.issues,
providers: providerStatuses,
},
}),
).pipe(Effect.forkIn(subscriptionsScope));
@@ -735,6 +743,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
providers: providerStatuses,
availableEditors,
};
+1 -1
View File
@@ -21,5 +21,5 @@
}
]
},
"include": ["src", "tsdown.config.ts", "scripts", "integration"]
"include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"]
}
+4 -1
View File
@@ -3,10 +3,13 @@ import { defineConfig } from "tsdown";
export default defineConfig({
entry: ["src/index.ts"],
format: ["esm", "cjs"],
checks: {
legacyCjs: false,
},
outDir: "dist",
sourcemap: true,
clean: true,
noExternal: ["@t3tools/contracts"],
noExternal: (id) => id.startsWith("@t3tools/"),
inlineOnly: false,
banner: {
js: "#!/usr/bin/env node\n",
+13 -4
View File
@@ -1,20 +1,24 @@
{
"name": "@t3tools/web",
"version": "0.0.0-alpha.4",
"version": "0.0.0-alpha.20",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"prepare": "effect-language-service patch",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests"
"test": "vitest run --passWithNoTests",
"test:browser": "vitest run --config vitest.browser.config.ts",
"test:browser:install": "playwright install --with-deps chromium"
},
"dependencies": {
"@base-ui/react": "^1.2.0",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-query": "^5.90.0",
"@tanstack/react-router": "^1.160.2",
@@ -39,9 +43,14 @@
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^5.1.4",
"@vitest/browser-playwright": "^4.0.18",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"msw": "^2.12.10",
"playwright": "^1.58.2",
"tailwindcss": "^4.0.0",
"typescript": "^5.7.3",
"vite": "^8.0.0-beta.12"
"typescript": "catalog:",
"vite": "^8.0.0-beta.12",
"vitest": "catalog:",
"vitest-browser-react": "^2.0.5"
}
}
+349
View File
@@ -0,0 +1,349 @@
/* eslint-disable */
/* tslint:disable */
/**
* Mock Service Worker.
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
*/
const PACKAGE_VERSION = '2.12.10'
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()
addEventListener('install', function () {
self.skipWaiting()
})
addEventListener('activate', function (event) {
event.waitUntil(self.clients.claim())
})
addEventListener('message', async function (event) {
const clientId = Reflect.get(event.source || {}, 'id')
if (!clientId || !self.clients) {
return
}
const client = await self.clients.get(clientId)
if (!client) {
return
}
const allClients = await self.clients.matchAll({
type: 'window',
})
switch (event.data) {
case 'KEEPALIVE_REQUEST': {
sendToClient(client, {
type: 'KEEPALIVE_RESPONSE',
})
break
}
case 'INTEGRITY_CHECK_REQUEST': {
sendToClient(client, {
type: 'INTEGRITY_CHECK_RESPONSE',
payload: {
packageVersion: PACKAGE_VERSION,
checksum: INTEGRITY_CHECKSUM,
},
})
break
}
case 'MOCK_ACTIVATE': {
activeClientIds.add(clientId)
sendToClient(client, {
type: 'MOCKING_ENABLED',
payload: {
client: {
id: client.id,
frameType: client.frameType,
},
},
})
break
}
case 'CLIENT_CLOSED': {
activeClientIds.delete(clientId)
const remainingClients = allClients.filter((client) => {
return client.id !== clientId
})
// Unregister itself when there are no more clients
if (remainingClients.length === 0) {
self.registration.unregister()
}
break
}
}
})
addEventListener('fetch', function (event) {
const requestInterceptedAt = Date.now()
// Bypass navigation requests.
if (event.request.mode === 'navigate') {
return
}
// Opening the DevTools triggers the "only-if-cached" request
// that cannot be handled by the worker. Bypass such requests.
if (
event.request.cache === 'only-if-cached' &&
event.request.mode !== 'same-origin'
) {
return
}
// Bypass all requests when there are no active clients.
// Prevents the self-unregistered worked from handling requests
// after it's been terminated (still remains active until the next reload).
if (activeClientIds.size === 0) {
return
}
const requestId = crypto.randomUUID()
event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
})
/**
* @param {FetchEvent} event
* @param {string} requestId
* @param {number} requestInterceptedAt
*/
async function handleRequest(event, requestId, requestInterceptedAt) {
const client = await resolveMainClient(event)
const requestCloneForEvents = event.request.clone()
const response = await getResponse(
event,
client,
requestId,
requestInterceptedAt,
)
// Send back the response clone for the "response:*" life-cycle events.
// Ensure MSW is active and ready to handle the message, otherwise
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
const serializedRequest = await serializeRequest(requestCloneForEvents)
// Clone the response so both the client and the library could consume it.
const responseClone = response.clone()
sendToClient(
client,
{
type: 'RESPONSE',
payload: {
isMockedResponse: IS_MOCKED_RESPONSE in response,
request: {
id: requestId,
...serializedRequest,
},
response: {
type: responseClone.type,
status: responseClone.status,
statusText: responseClone.statusText,
headers: Object.fromEntries(responseClone.headers.entries()),
body: responseClone.body,
},
},
},
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
)
}
return response
}
/**
* Resolve the main client for the given event.
* Client that issues a request doesn't necessarily equal the client
* that registered the worker. It's with the latter the worker should
* communicate with during the response resolving phase.
* @param {FetchEvent} event
* @returns {Promise<Client | undefined>}
*/
async function resolveMainClient(event) {
const client = await self.clients.get(event.clientId)
if (activeClientIds.has(event.clientId)) {
return client
}
if (client?.frameType === 'top-level') {
return client
}
const allClients = await self.clients.matchAll({
type: 'window',
})
return allClients
.filter((client) => {
// Get only those clients that are currently visible.
return client.visibilityState === 'visible'
})
.find((client) => {
// Find the client ID that's recorded in the
// set of clients that have registered the worker.
return activeClientIds.has(client.id)
})
}
/**
* @param {FetchEvent} event
* @param {Client | undefined} client
* @param {string} requestId
* @param {number} requestInterceptedAt
* @returns {Promise<Response>}
*/
async function getResponse(event, client, requestId, requestInterceptedAt) {
// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
const requestClone = event.request.clone()
function passthrough() {
// Cast the request headers to a new Headers instance
// so the headers can be manipulated with.
const headers = new Headers(requestClone.headers)
// Remove the "accept" header value that marked this request as passthrough.
// This prevents request alteration and also keeps it compliant with the
// user-defined CORS policies.
const acceptHeader = headers.get('accept')
if (acceptHeader) {
const values = acceptHeader.split(',').map((value) => value.trim())
const filteredValues = values.filter(
(value) => value !== 'msw/passthrough',
)
if (filteredValues.length > 0) {
headers.set('accept', filteredValues.join(', '))
} else {
headers.delete('accept')
}
}
return fetch(requestClone, { headers })
}
// Bypass mocking when the client is not active.
if (!client) {
return passthrough()
}
// Bypass initial page load requests (i.e. static assets).
// The absence of the immediate/parent client in the map of the active clients
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
// and is not ready to handle requests.
if (!activeClientIds.has(client.id)) {
return passthrough()
}
// Notify the client that a request has been intercepted.
const serializedRequest = await serializeRequest(event.request)
const clientMessage = await sendToClient(
client,
{
type: 'REQUEST',
payload: {
id: requestId,
interceptedAt: requestInterceptedAt,
...serializedRequest,
},
},
[serializedRequest.body],
)
switch (clientMessage.type) {
case 'MOCK_RESPONSE': {
return respondWithMock(clientMessage.data)
}
case 'PASSTHROUGH': {
return passthrough()
}
}
return passthrough()
}
/**
* @param {Client} client
* @param {any} message
* @param {Array<Transferable>} transferrables
* @returns {Promise<any>}
*/
function sendToClient(client, message, transferrables = []) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel()
channel.port1.onmessage = (event) => {
if (event.data && event.data.error) {
return reject(event.data.error)
}
resolve(event.data)
}
client.postMessage(message, [
channel.port2,
...transferrables.filter(Boolean),
])
})
}
/**
* @param {Response} response
* @returns {Response}
*/
function respondWithMock(response) {
// Setting response status code to 0 is a no-op.
// However, when responding with a "Response.error()", the produced Response
// instance will have status code set to 0. Since it's not possible to create
// a Response instance with status code 0, handle that use-case separately.
if (response.status === 0) {
return Response.error()
}
const mockedResponse = new Response(response.body, response)
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
value: true,
enumerable: true,
})
return mockedResponse
}
/**
* @param {Request} request
*/
async function serializeRequest(request) {
return {
url: request.url,
mode: request.mode,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: await request.arrayBuffer(),
keepalive: request.keepalive,
}
}
+15 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { getAppModelOptions, normalizeCustomModelSlugs } from "./appSettings";
import { getAppModelOptions, getSlashModelOptions, normalizeCustomModelSlugs } from "./appSettings";
describe("normalizeCustomModelSlugs", () => {
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
@@ -40,3 +40,17 @@ describe("getAppModelOptions", () => {
});
});
});
describe("getSlashModelOptions", () => {
it("includes saved custom model slugs for /model command suggestions", () => {
const options = getSlashModelOptions(["custom/internal-model"], "", "gpt-5.3-codex");
expect(options.some((option) => option.slug === "custom/internal-model")).toBe(true);
});
it("filters slash-model suggestions across built-in and custom model names", () => {
const options = getSlashModelOptions(["openai/gpt-oss-120b"], "oss", "gpt-5.3-codex");
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
});
});
+18
View File
@@ -105,6 +105,24 @@ export function getAppModelOptions(
return options;
}
export function getSlashModelOptions(
customModels: readonly string[],
query: string,
selectedModel?: string | null,
): AppModelOption[] {
const normalizedQuery = query.trim().toLowerCase();
const options = getAppModelOptions(customModels, selectedModel);
if (!normalizedQuery) {
return options;
}
return options.filter((option) => {
const searchSlug = option.slug.toLowerCase();
const searchName = option.name.toLowerCase();
return searchSlug.includes(normalizedQuery) || searchName.includes(normalizedQuery);
});
}
function emitChange(): void {
for (const listener of listeners) {
listener();
@@ -3,8 +3,77 @@ import { describe, expect, it } from "vitest";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
resolveDraftEnvModeAfterBranchChange,
resolveBranchToolbarValue,
} from "./BranchToolbar.logic";
describe("resolveDraftEnvModeAfterBranchChange", () => {
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
expect(
resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: null,
currentWorktreePath: "/repo/.t3/worktrees/feature-a",
effectiveEnvMode: "worktree",
}),
).toBe("local");
});
it("keeps new-worktree mode when selecting a base branch before worktree creation", () => {
expect(
resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: null,
currentWorktreePath: null,
effectiveEnvMode: "worktree",
}),
).toBe("worktree");
});
it("uses worktree mode when selecting a branch already attached to a worktree", () => {
expect(
resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: "/repo/.t3/worktrees/feature-a",
currentWorktreePath: null,
effectiveEnvMode: "local",
}),
).toBe("worktree");
});
});
describe("resolveBranchToolbarValue", () => {
it("defaults new-worktree mode to current git branch when no explicit base branch is set", () => {
expect(
resolveBranchToolbarValue({
envMode: "worktree",
activeWorktreePath: null,
activeThreadBranch: null,
currentGitBranch: "main",
}),
).toBe("main");
});
it("keeps an explicitly selected worktree base branch", () => {
expect(
resolveBranchToolbarValue({
envMode: "worktree",
activeWorktreePath: null,
activeThreadBranch: "feature/base",
currentGitBranch: "main",
}),
).toBe("feature/base");
});
it("shows the actual checked-out branch when not selecting a new worktree base", () => {
expect(
resolveBranchToolbarValue({
envMode: "local",
activeWorktreePath: null,
activeThreadBranch: "feature/base",
currentGitBranch: "main",
}),
).toBe("main");
});
});
describe("deriveLocalBranchNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
@@ -1,5 +1,46 @@
import type { GitBranch } from "@t3tools/contracts";
export type EnvMode = "local" | "worktree";
export function resolveEffectiveEnvMode(input: {
activeWorktreePath: string | null;
hasServerThread: boolean;
draftThreadEnvMode: EnvMode | undefined;
}): EnvMode {
const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input;
return activeWorktreePath || (!hasServerThread && draftThreadEnvMode === "worktree")
? "worktree"
: "local";
}
export function resolveDraftEnvModeAfterBranchChange(input: {
nextWorktreePath: string | null;
currentWorktreePath: string | null;
effectiveEnvMode: EnvMode;
}): EnvMode {
const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
if (nextWorktreePath) {
return "worktree";
}
if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
return "worktree";
}
return "local";
}
export function resolveBranchToolbarValue(input: {
envMode: EnvMode;
activeWorktreePath: string | null;
activeThreadBranch: string | null;
currentGitBranch: string | null;
}): string | null {
const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
if (envMode === "worktree" && !activeWorktreePath) {
return activeThreadBranch ?? currentGitBranch;
}
return currentGitBranch ?? activeThreadBranch;
}
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
const firstSeparatorIndex = branchName.indexOf("/");
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
+69 -287
View File
@@ -1,40 +1,27 @@
import type { GitBranch, ThreadId } from "@t3tools/contracts";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useOptimistic, useState, useTransition } from "react";
import type { ThreadId } from "@t3tools/contracts";
import { useCallback } from "react";
import { newCommandId } from "../lib/utils";
import { gitBranchesQueryOptions, invalidateGitQueries } from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
EnvMode,
resolveDraftEnvModeAfterBranchChange,
resolveEffectiveEnvMode,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { Button } from "./ui/button";
import {
Combobox,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxTrigger,
} from "./ui/combobox";
import { ChevronDownIcon } from "lucide-react";
import { toastManager } from "./ui/toast";
interface BranchToolbarProps {
threadId: ThreadId;
envMode: "local" | "worktree";
onEnvModeChange: (mode: "local" | "worktree") => void;
onEnvModeChange: (mode: EnvMode) => void;
envLocked: boolean;
onComposerFocusRequest?: () => void;
}
export default function BranchToolbar({
threadId,
envMode,
onEnvModeChange,
envLocked,
onComposerFocusRequest,
@@ -42,13 +29,8 @@ export default function BranchToolbar({
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
const setThreadErrorAction = useStore((store) => store.setError);
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const serverThread = threads.find((thread) => thread.id === threadId);
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
@@ -58,184 +40,64 @@ export default function BranchToolbar({
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
const hasServerThread = serverThread !== undefined;
const effectiveEnvMode: "local" | "worktree" =
activeWorktreePath || (!hasServerThread && draftThread?.envMode === "worktree")
? "worktree"
: envMode;
const effectiveEnvMode = resolveEffectiveEnvMode({
activeWorktreePath,
hasServerThread,
draftThreadEnvMode: draftThread?.envMode,
});
// ── Queries ───────────────────────────────────────────────────────────
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
const currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
const canonicalActiveBranch =
effectiveEnvMode === "worktree" && !activeWorktreePath
? activeThreadBranch
: (currentGitBranch ?? activeThreadBranch);
const branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
const createBranchItemValue = canCreateBranch
? `__create_new_branch__:${trimmedBranchQuery}`
: null;
const branchPickerItems =
createBranchItemValue && !hasExactBranchMatch
? [...branchNames, createBranchItemValue]
: branchNames;
// ── Helpers ───────────────────────────────────────────────────────────
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
canonicalActiveBranch,
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
);
const [isBranchActionPending, startBranchActionTransition] = useTransition();
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
await action().catch(() => undefined);
await invalidateGitQueries(queryClient).catch(() => undefined);
});
};
const setThreadError = (error: string | null) => {
if (!activeThreadId) return;
setThreadErrorAction(activeThreadId, error);
};
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
if (!activeThreadId) return;
const api = readNativeApi();
// If the effective cwd is about to change, stop the running session so the
// next message creates a new one with the correct cwd.
const sessionId = serverThread?.session?.sessionId;
if (sessionId && worktreePath !== activeWorktreePath && api) {
void api.orchestration
.dispatchCommand({
type: "thread.session.stop",
const setThreadBranch = useCallback(
(branch: string | null, worktreePath: string | null) => {
if (!activeThreadId) return;
const api = readNativeApi();
// If the effective cwd is about to change, stop the running session so the
// next message creates a new one with the correct cwd.
const sessionId = serverThread?.session?.sessionId;
if (sessionId && worktreePath !== activeWorktreePath && api) {
void api.orchestration
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId: activeThreadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
}
if (api && hasServerThread) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
}
if (api && hasServerThread) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
branch,
worktreePath,
});
}
if (hasServerThread) {
setThreadBranchAction(activeThreadId, branch, worktreePath);
return;
}
const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: worktreePath,
currentWorktreePath: activeWorktreePath,
effectiveEnvMode,
});
setDraftThreadContext(threadId, {
branch,
worktreePath,
envMode: nextDraftEnvMode,
});
}
if (hasServerThread) {
setThreadBranchAction(activeThreadId, branch, worktreePath);
return;
}
setDraftThreadContext(threadId, {
branch,
worktreePath,
envMode: effectiveEnvMode,
});
};
const selectBranch = (branch: GitBranch) => {
const api = readNativeApi();
if (!api || !activeThreadId || !branchCwd || isBranchActionPending) return;
// For new worktree mode, selecting a branch picks the base branch.
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
// If the branch already lives in a worktree, redirect there instead of
// trying to checkout (which git would reject with "already used by worktree").
if (branch.worktreePath) {
const isMainWorktree = branch.worktreePath === activeProject?.cwd;
// Main worktree → switch back to local (project cwd, worktreePath=null).
// Secondary worktree → point the thread at that worktree path.
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
const selectedBranchName = branch.isRemote
? deriveLocalBranchNameFromRemoteRef(branch.name)
: branch.name;
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
runBranchAction(async () => {
setOptimisticBranch(selectedBranchName);
try {
await api.git.checkout({ cwd: branchCwd, branch: branch.name });
await invalidateGitQueries(queryClient);
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: error instanceof Error ? error.message : "An error occurred.",
});
return;
}
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
}
setOptimisticBranch(nextBranchName);
setThreadBranch(nextBranchName, activeWorktreePath);
});
};
const createBranch = (rawName: string) => {
const name = rawName.trim();
const api = readNativeApi();
if (!api || !activeThreadId || !branchCwd || !name || isBranchActionPending) return;
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
runBranchAction(async () => {
setOptimisticBranch(name);
try {
await api.git.createBranch({ cwd: branchCwd, branch: name });
try {
await api.git.checkout({ cwd: branchCwd, branch: name });
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: error instanceof Error ? error.message : "An error occurred.",
});
return;
}
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to create branch.",
description: error instanceof Error ? error.message : "An error occurred.",
});
return;
}
setOptimisticBranch(name);
setThreadBranch(name, activeWorktreePath);
setBranchQuery("");
});
};
},
[
activeThreadId,
serverThread?.session?.sessionId,
activeWorktreePath,
hasServerThread,
setThreadBranchAction,
setDraftThreadContext,
threadId,
effectiveEnvMode,
],
);
if (!activeThreadId || !activeProject) return null;
@@ -259,96 +121,16 @@ export default function BranchToolbar({
)}
</div>
<Combobox
items={branchPickerItems}
autoHighlight
onOpenChange={(open) => {
setIsBranchMenuOpen(open);
if (!open) setBranchQuery("");
else void invalidateGitQueries(queryClient);
}}
open={isBranchMenuOpen}
value={resolvedActiveBranch}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={branchesQuery.isLoading || isBranchActionPending}
>
<span className="max-w-[240px] truncate">
{resolvedActiveBranch
? effectiveEnvMode === "worktree" && !activeWorktreePath
? `From ${resolvedActiveBranch}`
: resolvedActiveBranch
: "Select branch"}
</span>
<ChevronDownIcon />
</ComboboxTrigger>
<ComboboxPopup align="end" side="top" className="w-64">
<div className="border-b p-1">
<ComboboxInput
className="[&_input]:font-sans rounded-md"
inputClassName="ring-0"
placeholder="Search branches..."
showTrigger={false}
size="sm"
value={branchQuery}
onChange={(event) => setBranchQuery(event.target.value)}
/>
</div>
<ComboboxEmpty>No branches found.</ComboboxEmpty>
<ComboboxList className="max-h-56">
{(itemValue) => {
if (createBranchItemValue && itemValue === createBranchItemValue) {
return (
<ComboboxItem
hideIndicator
key={itemValue}
value={itemValue}
onClick={() => createBranch(trimmedBranchQuery)}
>
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
</ComboboxItem>
);
}
const branch = branchByName.get(itemValue);
if (!branch) return null;
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
const badge = branch.current
? "current"
: hasSecondaryWorktree
? "worktree"
: branch.isRemote
? "remote"
: branch.isDefault
? "default"
: null;
return (
<ComboboxItem
hideIndicator
key={itemValue}
value={itemValue}
className={
itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
}
onClick={() => selectBranch(branch)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{badge && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
)}
</div>
</ComboboxItem>
);
}}
</ComboboxList>
</ComboboxPopup>
</Combobox>
<BranchToolbarBranchSelector
activeProjectCwd={activeProject.cwd}
activeThreadBranch={activeThreadBranch}
activeWorktreePath={activeWorktreePath}
branchCwd={branchCwd}
effectiveEnvMode={effectiveEnvMode}
envLocked={envLocked}
onSetThreadBranch={setThreadBranch}
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
/>
</div>
);
}
@@ -0,0 +1,408 @@
import type { GitBranch } from "@t3tools/contracts";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { ChevronDownIcon } from "lucide-react";
import {
useCallback,
useEffect,
useMemo,
useOptimistic,
useRef,
useState,
useTransition,
} from "react";
import { gitBranchesQueryOptions, gitQueryKeys, invalidateGitQueries } from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
EnvMode,
resolveBranchToolbarValue,
} from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
Combobox,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxTrigger,
} from "./ui/combobox";
import { toastManager } from "./ui/toast";
interface BranchToolbarBranchSelectorProps {
activeProjectCwd: string;
activeThreadBranch: string | null;
activeWorktreePath: string | null;
branchCwd: string | null;
effectiveEnvMode: EnvMode;
envLocked: boolean;
onSetThreadBranch: (branch: string | null, worktreePath: string | null) => void;
onComposerFocusRequest?: () => void;
}
function toBranchActionErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : "An error occurred.";
}
function getBranchTriggerLabel(input: {
activeWorktreePath: string | null;
effectiveEnvMode: EnvMode;
resolvedActiveBranch: string | null;
}): string {
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
if (!resolvedActiveBranch) {
return "Select branch";
}
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
return `From ${resolvedActiveBranch}`;
}
return resolvedActiveBranch;
}
export function BranchToolbarBranchSelector({
activeProjectCwd,
activeThreadBranch,
activeWorktreePath,
branchCwd,
effectiveEnvMode,
envLocked,
onSetThreadBranch,
onComposerFocusRequest,
}: BranchToolbarBranchSelectorProps) {
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branches = useMemo(
() => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
[branchesQuery.data?.branches],
);
const currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
const canonicalActiveBranch = resolveBranchToolbarValue({
envMode: effectiveEnvMode,
activeWorktreePath,
activeThreadBranch,
currentGitBranch,
});
const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
const branchByName = useMemo(
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
[branches],
);
const trimmedBranchQuery = branchQuery.trim();
const normalizedBranchQuery = trimmedBranchQuery.toLowerCase();
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
const createBranchItemValue = canCreateBranch
? `__create_new_branch__:${trimmedBranchQuery}`
: null;
const branchPickerItems = useMemo(
() =>
createBranchItemValue && !hasExactBranchMatch
? [...branchNames, createBranchItemValue]
: branchNames,
[branchNames, createBranchItemValue, hasExactBranchMatch],
);
const filteredBranchPickerItems = useMemo(
() =>
normalizedBranchQuery.length === 0
? branchPickerItems
: branchPickerItems.filter((itemValue) => {
if (createBranchItemValue && itemValue === createBranchItemValue) return true;
return itemValue.toLowerCase().includes(normalizedBranchQuery);
}),
[branchPickerItems, createBranchItemValue, normalizedBranchQuery],
);
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
canonicalActiveBranch,
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
);
const [isBranchActionPending, startBranchActionTransition] = useTransition();
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
await action().catch(() => undefined);
await invalidateGitQueries(queryClient).catch(() => undefined);
});
};
const selectBranch = (branch: GitBranch) => {
const api = readNativeApi();
if (!api || !branchCwd || isBranchActionPending) return;
// In new-worktree mode, selecting a branch sets the base branch.
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
onSetThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
// If the branch already lives in a worktree, point the thread there.
if (branch.worktreePath) {
const isMainWorktree = branch.worktreePath === activeProjectCwd;
onSetThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
const selectedBranchName = branch.isRemote
? deriveLocalBranchNameFromRemoteRef(branch.name)
: branch.name;
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
runBranchAction(async () => {
setOptimisticBranch(selectedBranchName);
try {
await api.git.checkout({ cwd: branchCwd, branch: branch.name });
await invalidateGitQueries(queryClient);
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: toBranchActionErrorMessage(error),
});
return;
}
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
}
setOptimisticBranch(nextBranchName);
onSetThreadBranch(nextBranchName, activeWorktreePath);
});
};
const createBranch = (rawName: string) => {
const name = rawName.trim();
const api = readNativeApi();
if (!api || !branchCwd || !name || isBranchActionPending) return;
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
runBranchAction(async () => {
setOptimisticBranch(name);
try {
await api.git.createBranch({ cwd: branchCwd, branch: name });
try {
await api.git.checkout({ cwd: branchCwd, branch: name });
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: toBranchActionErrorMessage(error),
});
return;
}
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to create branch.",
description: toBranchActionErrorMessage(error),
});
return;
}
setOptimisticBranch(name);
onSetThreadBranch(name, activeWorktreePath);
setBranchQuery("");
});
};
useEffect(() => {
if (
effectiveEnvMode !== "worktree" ||
activeWorktreePath ||
activeThreadBranch ||
!currentGitBranch
) {
return;
}
onSetThreadBranch(currentGitBranch, null);
}, [
activeThreadBranch,
activeWorktreePath,
currentGitBranch,
effectiveEnvMode,
onSetThreadBranch,
]);
const handleOpenChange = useCallback(
(open: boolean) => {
setIsBranchMenuOpen(open);
if (!open) {
setBranchQuery("");
return;
}
void queryClient.invalidateQueries({
queryKey: gitQueryKeys.branches(branchCwd),
});
},
[branchCwd, queryClient],
);
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
const branchListVirtualizer = useVirtualizer({
count: filteredBranchPickerItems.length,
estimateSize: () => 28,
getScrollElement: () => branchListScrollElementRef.current,
overscan: 12,
enabled: isBranchMenuOpen,
initialRect: {
height: 224,
width: 0,
},
});
const virtualBranchRows = branchListVirtualizer.getVirtualItems();
const setBranchListRef = useCallback(
(element: HTMLDivElement | null) => {
branchListScrollElementRef.current =
(element?.parentElement as HTMLDivElement | null) ?? null;
if (element) {
branchListVirtualizer.measure();
}
},
[branchListVirtualizer],
);
useEffect(() => {
if (!isBranchMenuOpen) return;
queueMicrotask(() => {
branchListVirtualizer.measure();
});
}, [branchListVirtualizer, filteredBranchPickerItems.length, isBranchMenuOpen]);
const triggerLabel = getBranchTriggerLabel({
activeWorktreePath,
effectiveEnvMode,
resolvedActiveBranch,
});
return (
<Combobox
items={branchPickerItems}
filteredItems={filteredBranchPickerItems}
autoHighlight
virtualized
onItemHighlighted={(_value, eventDetails) => {
if (!isBranchMenuOpen || eventDetails.index < 0) return;
branchListVirtualizer.scrollToIndex(eventDetails.index, { align: "auto" });
}}
onOpenChange={handleOpenChange}
open={isBranchMenuOpen}
value={resolvedActiveBranch}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={branchesQuery.isLoading || isBranchActionPending}
>
<span className="max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon />
</ComboboxTrigger>
<ComboboxPopup align="end" side="top" className="w-64">
<div className="border-b p-1">
<ComboboxInput
className="[&_input]:font-sans rounded-md"
inputClassName="ring-0"
placeholder="Search branches..."
showTrigger={false}
size="sm"
value={branchQuery}
onChange={(event) => setBranchQuery(event.target.value)}
/>
</div>
<ComboboxEmpty>No branches found.</ComboboxEmpty>
<ComboboxList ref={setBranchListRef} className="max-h-56">
<div
className="relative"
style={{
height: `${branchListVirtualizer.getTotalSize()}px`,
}}
>
{virtualBranchRows.map((virtualRow) => {
const itemValue = filteredBranchPickerItems[virtualRow.index];
if (!itemValue) return null;
if (createBranchItemValue && itemValue === createBranchItemValue) {
return (
<ComboboxItem
hideIndicator
key={itemValue}
index={virtualRow.index}
value={itemValue}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
transform: `translateY(${virtualRow.start}px)`,
}}
onClick={() => createBranch(trimmedBranchQuery)}
>
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
</ComboboxItem>
);
}
const branch = branchByName.get(itemValue);
if (!branch) return null;
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProjectCwd;
const badge = branch.current
? "current"
: hasSecondaryWorktree
? "worktree"
: branch.isRemote
? "remote"
: branch.isDefault
? "default"
: null;
return (
<ComboboxItem
hideIndicator
key={itemValue}
index={virtualRow.index}
value={itemValue}
className={
itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
transform: `translateY(${virtualRow.start}px)`,
}}
onClick={() => selectBranch(branch)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{badge && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
)}
</div>
</ComboboxItem>
);
})}
</div>
</ComboboxList>
</ComboboxPopup>
</Combobox>
);
}
@@ -0,0 +1,713 @@
// Production CSS is part of the behavior under test because row height depends on it.
import "../index.css";
import {
ORCHESTRATION_WS_METHODS,
type MessageId,
type OrchestrationReadModel,
type ProjectId,
type ProviderSessionId,
type ServerConfig,
type ThreadId,
type WsWelcomePayload,
WS_CHANNELS,
WS_METHODS,
} from "@t3tools/contracts";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { HttpResponse, http, ws } from "msw";
import { setupWorker } from "msw/browser";
import { page } from "vitest/browser";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { getRouter } from "../router";
import { useStore } from "../store";
import { estimateTimelineMessageHeight } from "./timelineHeight";
const THREAD_ID = "thread-browser-test" as ThreadId;
const PROJECT_ID = "project-1" as ProjectId;
const NOW_ISO = "2026-03-04T12:00:00.000Z";
const BASE_TIME_MS = Date.parse(NOW_ISO);
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='300'></svg>";
interface WsRequestEnvelope {
id: string;
body: {
_tag: string;
[key: string]: unknown;
};
}
interface TestFixture {
snapshot: OrchestrationReadModel;
serverConfig: ServerConfig;
welcome: WsWelcomePayload;
}
let fixture: TestFixture;
const wsLink = ws.link(/ws(s)?:\/\/.*/);
interface ViewportSpec {
name: string;
width: number;
height: number;
textTolerancePx: number;
attachmentTolerancePx: number;
}
const DEFAULT_VIEWPORT: ViewportSpec = {
name: "desktop",
width: 960,
height: 1_100,
textTolerancePx: 44,
attachmentTolerancePx: 56,
};
const TEXT_VIEWPORT_MATRIX = [
DEFAULT_VIEWPORT,
{ name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 },
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
] as const satisfies readonly ViewportSpec[];
const ATTACHMENT_VIEWPORT_MATRIX = [
DEFAULT_VIEWPORT,
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
] as const satisfies readonly ViewportSpec[];
interface UserRowMeasurement {
measuredRowHeightPx: number;
timelineWidthMeasuredPx: number;
renderedInVirtualizedRegion: boolean;
}
interface MountedChatView {
cleanup: () => Promise<void>;
measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
setViewport: (viewport: ViewportSpec) => Promise<void>;
}
function isoAt(offsetSeconds: number): string {
return new Date(BASE_TIME_MS + offsetSeconds * 1_000).toISOString();
}
function createBaseServerConfig(): ServerConfig {
return {
cwd: "/repo/project",
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
keybindings: [],
issues: [],
providers: [
{
provider: "codex",
status: "ready",
available: true,
authStatus: "authenticated",
checkedAt: NOW_ISO,
},
],
availableEditors: [],
};
}
function createUserMessage(options: {
id: MessageId;
text: string;
offsetSeconds: number;
attachments?: Array<{
type: "image";
id: string;
name: string;
mimeType: string;
sizeBytes: number;
}>;
}) {
return {
id: options.id,
role: "user" as const,
text: options.text,
...(options.attachments ? { attachments: options.attachments } : {}),
turnId: null,
streaming: false,
createdAt: isoAt(options.offsetSeconds),
updatedAt: isoAt(options.offsetSeconds + 1),
};
}
function createAssistantMessage(options: { id: MessageId; text: string; offsetSeconds: number }) {
return {
id: options.id,
role: "assistant" as const,
text: options.text,
turnId: null,
streaming: false,
createdAt: isoAt(options.offsetSeconds),
updatedAt: isoAt(options.offsetSeconds + 1),
};
}
function createSnapshotForTargetUser(options: {
targetMessageId: MessageId;
targetText: string;
targetAttachmentCount?: number;
}): OrchestrationReadModel {
const messages: Array<OrchestrationReadModel["threads"][number]["messages"][number]> = [];
for (let index = 0; index < 22; index += 1) {
const isTarget = index === 3;
const userId = `msg-user-${index}` as MessageId;
const assistantId = `msg-assistant-${index}` as MessageId;
const attachments =
isTarget && (options.targetAttachmentCount ?? 0) > 0
? Array.from({ length: options.targetAttachmentCount ?? 0 }, (_, attachmentIndex) => ({
type: "image" as const,
id: `attachment-${attachmentIndex + 1}`,
name: `attachment-${attachmentIndex + 1}.png`,
mimeType: "image/png",
sizeBytes: 128,
}))
: undefined;
messages.push(
createUserMessage({
id: isTarget ? options.targetMessageId : userId,
text: isTarget ? options.targetText : `filler user message ${index}`,
offsetSeconds: messages.length * 3,
...(attachments ? { attachments } : {}),
}),
);
messages.push(
createAssistantMessage({
id: assistantId,
text: `assistant filler ${index}`,
offsetSeconds: messages.length * 3,
}),
);
}
return {
snapshotSequence: 1,
projects: [
{
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo/project",
defaultModel: "gpt-5",
scripts: [],
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
deletedAt: null,
},
],
threads: [
{
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Browser test thread",
model: "gpt-5",
branch: "main",
worktreePath: null,
latestTurn: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
deletedAt: null,
messages,
activities: [],
checkpoints: [],
session: {
threadId: THREAD_ID,
status: "ready",
providerName: "codex",
providerSessionId: "session-1" as ProviderSessionId,
providerThreadId: null,
approvalPolicy: "on-failure",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: NOW_ISO,
},
},
],
updatedAt: NOW_ISO,
};
}
function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
return {
snapshot,
serverConfig: createBaseServerConfig(),
welcome: {
cwd: "/repo/project",
projectName: "Project",
bootstrapProjectId: PROJECT_ID,
bootstrapThreadId: THREAD_ID,
},
};
}
function resolveWsRpc(tag: string): unknown {
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
return fixture.snapshot;
}
if (tag === WS_METHODS.serverGetConfig) {
return fixture.serverConfig;
}
if (tag === WS_METHODS.gitListBranches) {
return {
isRepo: true,
branches: [
{
name: "main",
current: true,
isDefault: true,
worktreePath: null,
},
],
};
}
if (tag === WS_METHODS.gitStatus) {
return {
branch: "main",
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
}
if (tag === WS_METHODS.projectsSearchEntries) {
return {
entries: [],
truncated: false,
};
}
return {};
}
const worker = setupWorker(
wsLink.addEventListener("connection", ({ client }) => {
client.send(
JSON.stringify({
type: "push",
channel: WS_CHANNELS.serverWelcome,
data: fixture.welcome,
}),
);
client.addEventListener("message", (event) => {
const rawData = event.data;
if (typeof rawData !== "string") return;
let request: WsRequestEnvelope;
try {
request = JSON.parse(rawData) as WsRequestEnvelope;
} catch {
return;
}
const method = request.body?._tag;
if (typeof method !== "string") return;
client.send(
JSON.stringify({
id: request.id,
result: resolveWsRpc(method),
}),
);
});
}),
http.get("*/attachments/:attachmentId", () =>
HttpResponse.text(ATTACHMENT_SVG, {
headers: {
"Content-Type": "image/svg+xml",
},
}),
),
http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
);
async function nextFrame(): Promise<void> {
await new Promise<void>((resolve) => {
window.requestAnimationFrame(() => resolve());
});
}
async function waitForLayout(): Promise<void> {
await nextFrame();
await nextFrame();
await nextFrame();
}
async function setViewport(viewport: ViewportSpec): Promise<void> {
await page.viewport(viewport.width, viewport.height);
await waitForLayout();
}
async function waitForProductionStyles(): Promise<void> {
await vi.waitFor(
() => {
expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).not.toBe(
"",
);
expect(getComputedStyle(document.body).marginTop).toBe("0px");
},
{
timeout: 4_000,
interval: 16,
},
);
}
async function waitForElement<T extends Element>(
query: () => T | null,
errorMessage: string,
): Promise<T> {
let element: T | null = null;
await vi.waitFor(
() => {
element = query();
expect(element, errorMessage).toBeTruthy();
},
{
timeout: 8_000,
interval: 16,
},
);
if (!element) {
throw new Error(errorMessage);
}
return element;
}
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
const images = Array.from(scope.querySelectorAll("img"));
if (images.length === 0) {
return;
}
await Promise.all(
images.map(
(image) =>
new Promise<void>((resolve) => {
if (image.complete) {
resolve();
return;
}
image.addEventListener("load", () => resolve(), { once: true });
image.addEventListener("error", () => resolve(), { once: true });
}),
),
);
await waitForLayout();
}
async function measureUserRow(options: {
host: HTMLElement;
targetMessageId: MessageId;
}): Promise<UserRowMeasurement> {
const { host, targetMessageId } = options;
const rowSelector = `[data-message-id="${targetMessageId}"][data-message-role="user"]`;
const scrollContainer = await waitForElement(
() => host.querySelector<HTMLDivElement>("div.overflow-y-auto.overscroll-y-contain"),
"Unable to find ChatView message scroll container.",
);
let row: HTMLElement | null = null;
await vi.waitFor(
async () => {
scrollContainer.scrollTop = 0;
scrollContainer.dispatchEvent(new Event("scroll"));
await waitForLayout();
row = host.querySelector<HTMLElement>(rowSelector);
expect(row, "Unable to locate targeted user message row.").toBeTruthy();
},
{
timeout: 8_000,
interval: 16,
},
);
await waitForImagesToLoad(row!);
scrollContainer.scrollTop = 0;
scrollContainer.dispatchEvent(new Event("scroll"));
await nextFrame();
const timelineRoot =
row!.closest<HTMLElement>('[data-timeline-root="true"]') ??
host.querySelector<HTMLElement>('[data-timeline-root="true"]');
if (!(timelineRoot instanceof HTMLElement)) {
throw new Error("Unable to locate timeline root container.");
}
let timelineWidthMeasuredPx = 0;
let measuredRowHeightPx = 0;
let renderedInVirtualizedRegion = false;
await vi.waitFor(
async () => {
scrollContainer.scrollTop = 0;
scrollContainer.dispatchEvent(new Event("scroll"));
await nextFrame();
const measuredRow = host.querySelector<HTMLElement>(rowSelector);
expect(measuredRow, "Unable to measure targeted user row height.").toBeTruthy();
timelineWidthMeasuredPx = timelineRoot.getBoundingClientRect().width;
measuredRowHeightPx = measuredRow!.getBoundingClientRect().height;
renderedInVirtualizedRegion = measuredRow!.closest("[data-index]") instanceof HTMLElement;
expect(timelineWidthMeasuredPx, "Unable to measure timeline width.").toBeGreaterThan(0);
expect(measuredRowHeightPx, "Unable to measure targeted user row height.").toBeGreaterThan(0);
},
{
timeout: 4_000,
interval: 16,
},
);
return { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion };
}
async function mountChatView(options: {
viewport: ViewportSpec;
snapshot: OrchestrationReadModel;
}): Promise<MountedChatView> {
fixture = buildFixture(options.snapshot);
await setViewport(options.viewport);
await waitForProductionStyles();
const host = document.createElement("div");
host.style.position = "fixed";
host.style.inset = "0";
host.style.width = "100vw";
host.style.height = "100vh";
host.style.display = "grid";
host.style.overflow = "hidden";
document.body.append(host);
const router = getRouter(
createMemoryHistory({
initialEntries: [`/${THREAD_ID}`],
}),
);
const screen = await render(<RouterProvider router={router} />, {
container: host,
});
await waitForLayout();
return {
cleanup: async () => {
await screen.unmount();
host.remove();
},
measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }),
setViewport: async (viewport: ViewportSpec) => {
await setViewport(viewport);
await waitForProductionStyles();
},
};
}
async function measureUserRowAtViewport(options: {
snapshot: OrchestrationReadModel;
targetMessageId: MessageId;
viewport: ViewportSpec;
}): Promise<UserRowMeasurement> {
const mounted = await mountChatView({
viewport: options.viewport,
snapshot: options.snapshot,
});
try {
return await mounted.measureUserRow(options.targetMessageId);
} finally {
await mounted.cleanup();
}
}
describe("ChatView timeline estimator parity (full app)", () => {
beforeAll(async () => {
fixture = buildFixture(
createSnapshotForTargetUser({
targetMessageId: "msg-user-bootstrap" as MessageId,
targetText: "bootstrap",
}),
);
await worker.start({
onUnhandledRequest: "bypass",
quiet: true,
serviceWorker: {
url: "/mockServiceWorker.js",
},
});
});
afterAll(async () => {
await worker.stop();
});
beforeEach(async () => {
await setViewport(DEFAULT_VIEWPORT);
localStorage.clear();
document.body.innerHTML = "";
useStore.setState({
projects: [],
threads: [],
threadsHydrated: false,
runtimeMode: "full-access",
});
});
afterEach(() => {
document.body.innerHTML = "";
});
it.each(TEXT_VIEWPORT_MATRIX)(
"keeps long user message estimate close at the $name viewport",
async (viewport) => {
const userText = "x".repeat(3_200);
const targetMessageId = `msg-user-target-long-${viewport.name}` as MessageId;
const mounted = await mountChatView({
viewport,
snapshot: createSnapshotForTargetUser({
targetMessageId,
targetText: userText,
}),
});
try {
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
await mounted.measureUserRow(targetMessageId);
expect(renderedInVirtualizedRegion).toBe(true);
const estimatedHeightPx = estimateTimelineMessageHeight(
{ role: "user", text: userText, attachments: [] },
{ timelineWidthPx: timelineWidthMeasuredPx },
);
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
viewport.textTolerancePx,
);
} finally {
await mounted.cleanup();
}
},
);
it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => {
const userText = "x".repeat(3_200);
const targetMessageId = "msg-user-target-resize" as MessageId;
const mounted = await mountChatView({
viewport: TEXT_VIEWPORT_MATRIX[0],
snapshot: createSnapshotForTargetUser({
targetMessageId,
targetText: userText,
}),
});
try {
const measurements: Array<UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }> = [];
for (const viewport of TEXT_VIEWPORT_MATRIX) {
await mounted.setViewport(viewport);
const measurement = await mounted.measureUserRow(targetMessageId);
const estimatedHeightPx = estimateTimelineMessageHeight(
{ role: "user", text: userText, attachments: [] },
{ timelineWidthPx: measurement.timelineWidthMeasuredPx },
);
expect(measurement.renderedInVirtualizedRegion).toBe(true);
expect(Math.abs(measurement.measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
viewport.textTolerancePx,
);
measurements.push({ ...measurement, viewport, estimatedHeightPx });
}
expect(new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx))).size).toBeGreaterThanOrEqual(3);
const byMeasuredWidth = measurements.toSorted(
(left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx,
);
const narrowest = byMeasuredWidth[0]!;
const widest = byMeasuredWidth.at(-1)!;
expect(narrowest.timelineWidthMeasuredPx).toBeLessThan(widest.timelineWidthMeasuredPx);
expect(narrowest.measuredRowHeightPx).toBeGreaterThan(widest.measuredRowHeightPx);
expect(narrowest.estimatedHeightPx).toBeGreaterThan(widest.estimatedHeightPx);
} finally {
await mounted.cleanup();
}
});
it("tracks additional rendered wrapping when ChatView width narrows between desktop and mobile viewports", async () => {
const userText = "x".repeat(2_400);
const targetMessageId = "msg-user-target-wrap" as MessageId;
const snapshot = createSnapshotForTargetUser({
targetMessageId,
targetText: userText,
});
const desktopMeasurement = await measureUserRowAtViewport({
viewport: TEXT_VIEWPORT_MATRIX[0],
snapshot,
targetMessageId,
});
const mobileMeasurement = await measureUserRowAtViewport({
viewport: TEXT_VIEWPORT_MATRIX[2],
snapshot,
targetMessageId,
});
const estimatedDesktopPx = estimateTimelineMessageHeight(
{ role: "user", text: userText, attachments: [] },
{ timelineWidthPx: desktopMeasurement.timelineWidthMeasuredPx },
);
const estimatedMobilePx = estimateTimelineMessageHeight(
{ role: "user", text: userText, attachments: [] },
{ timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx },
);
const measuredDeltaPx = mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;
const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx;
expect(measuredDeltaPx).toBeGreaterThan(0);
expect(estimatedDeltaPx).toBeGreaterThan(0);
const ratio = estimatedDeltaPx / measuredDeltaPx;
expect(ratio).toBeGreaterThan(0.65);
expect(ratio).toBeLessThan(1.35);
});
it.each(ATTACHMENT_VIEWPORT_MATRIX)(
"keeps user attachment estimate close at the $name viewport",
async (viewport) => {
const targetMessageId = `msg-user-target-attachments-${viewport.name}` as MessageId;
const userText = "message with image attachments";
const mounted = await mountChatView({
viewport,
snapshot: createSnapshotForTargetUser({
targetMessageId,
targetText: userText,
targetAttachmentCount: 3,
}),
});
try {
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
await mounted.measureUserRow(targetMessageId);
expect(renderedInVirtualizedRegion).toBe(true);
const estimatedHeightPx = estimateTimelineMessageHeight(
{
role: "user",
text: userText,
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }],
},
{ timelineWidthPx: timelineWidthMeasuredPx },
);
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
viewport.attachmentTolerancePx,
);
} finally {
await mounted.cleanup();
}
},
);
});
+326 -121
View File
@@ -15,6 +15,7 @@ import {
type ReasoningEffort,
type ResolvedKeybindingsConfig,
type ProviderApprovalDecision,
type ServerProviderStatus,
type ThreadId,
type TurnId,
normalizeModelSlug,
@@ -62,11 +63,17 @@ import {
MAX_THREAD_TERMINAL_COUNT,
type ChatMessage,
type Thread,
type TurnDiffFileChange,
type TurnDiffSummary,
} from "../types";
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import {
buildTurnDiffTree,
summarizeTurnDiffStats,
type TurnDiffTreeNode,
} from "../lib/turnDiffTree";
import BranchToolbar from "./BranchToolbar";
import GitActionsControl from "./GitActionsControl";
import {
@@ -118,7 +125,7 @@ import { Toggle } from "./ui/toggle";
import { SidebarTrigger } from "./ui/sidebar";
import { newCommandId, newMessageId } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
import { getAppModelOptions, useAppSettings } from "../appSettings";
import { getAppModelOptions, getSlashModelOptions, useAppSettings } from "../appSettings";
import {
type ComposerImageAttachment,
type DraftThreadEnvMode,
@@ -130,6 +137,7 @@ import {
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { clamp } from "effect/Number";
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
import { estimateTimelineMessageHeight } from "./timelineHeight";
function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt);
@@ -148,6 +156,7 @@ const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
const EMPTY_AVAILABLE_EDITORS: EditorId[] = [];
const EMPTY_PROVIDER_STATUSES: ServerProviderStatus[] = [];
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
const SCRIPT_TERMINAL_COLS = 120;
const SCRIPT_TERMINAL_ROWS = 30;
@@ -331,6 +340,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
pathValue: string;
kind: "file" | "directory";
theme: "light" | "dark";
className?: string;
}) {
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
const iconUrl = useMemo(
@@ -341,9 +351,9 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
if (failed) {
return props.kind === "directory" ? (
<FolderIcon className="size-4 text-muted-foreground/80" />
<FolderIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
) : (
<FileIcon className="size-4 text-muted-foreground/80" />
<FileIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
);
}
@@ -352,7 +362,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
src={iconUrl}
alt=""
aria-hidden="true"
className="size-4 shrink-0"
className={cn("size-4 shrink-0", props.className)}
loading="lazy"
onError={() => setFailedIconUrl(iconUrl)}
/>
@@ -524,7 +534,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
const pendingUserScrollUpIntentRef = useRef(false);
const pendingAutoScrollFrameRef = useRef<number | null>(null);
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
const composerCommandInputRef = useRef<HTMLInputElement>(null);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerFormHeightRef = useRef(0);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
@@ -632,6 +641,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => getAppModelOptions(settings.customCodexModels, selectedModel),
[selectedModel, settings.customCodexModels],
);
const slashModelOptions = useMemo(
() =>
getSlashModelOptions(settings.customCodexModels, composerTrigger?.query ?? "", selectedModel),
[composerTrigger?.query, selectedModel, settings.customCodexModels],
);
const phase = derivePhase(activeThread?.session ?? null);
const isSendBusy = sendPhase !== "idle";
const isPreparingWorktree = sendPhase === "preparing-worktree";
@@ -907,26 +921,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
];
}
return modelOptions
.map(({ slug, name }) => ({
slug,
name,
searchSlug: slug.toLowerCase(),
searchName: name.toLowerCase(),
}))
.filter(({ searchSlug, searchName }) => {
const query = composerTrigger.query.trim().toLowerCase();
if (!query) return true;
return searchSlug.includes(query) || searchName.includes(query);
})
.map(({ slug, name }) => ({
id: `model:${slug}`,
type: "model" as const,
model: slug,
label: name,
description: slug,
}));
}, [composerTrigger, modelOptions, workspaceEntries]);
return slashModelOptions.map(({ slug, name }) => ({
id: `model:${slug}`,
type: "model" as const,
model: slug,
label: name,
description: slug,
}));
}, [composerTrigger, slashModelOptions, workspaceEntries]);
const composerMenuOpen = Boolean(composerTrigger);
const activeComposerMenuItem = useMemo(
() =>
@@ -944,6 +946,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
const providerStatuses = serverConfigQuery.data?.providers ?? EMPTY_PROVIDER_STATUSES;
const activeProvider = activeThread?.session?.provider ?? "codex";
const activeProviderStatus = useMemo(
() => providerStatuses.find((status) => status.provider === activeProvider) ?? null,
[activeProvider, providerStatuses],
);
const activeProjectCwd = activeProject?.cwd ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const threadTerminalRuntimeEnv = useMemo(() => {
@@ -2320,12 +2328,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
return;
}
if (item.type === "slash-command") {
const applied = applyPromptReplacement(
trigger.rangeStart,
trigger.rangeEnd,
"/model ",
{ expectedText: expectedToken },
);
const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "/model ", {
expectedText: expectedToken,
});
if (applied) {
setComposerHighlightedItemId(null);
}
@@ -2368,18 +2373,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
workspaceEntriesQuery.isLoading ||
workspaceEntriesQuery.isFetching);
const onPromptChange = useCallback((nextPrompt: string, nextCursor: number, cursorAdjacentToMention: boolean) => {
promptRef.current = nextPrompt;
setPrompt(nextPrompt);
setComposerCursor(nextCursor);
setComposerTrigger(
cursorAdjacentToMention
? null
: detectComposerTrigger(nextPrompt, expandCollapsedComposerCursor(nextPrompt, nextCursor)),
);
}, [setPrompt]);
const onPromptChange = useCallback(
(nextPrompt: string, nextCursor: number, cursorAdjacentToMention: boolean) => {
promptRef.current = nextPrompt;
setPrompt(nextPrompt);
setComposerCursor(nextCursor);
setComposerTrigger(
cursorAdjacentToMention
? null
: detectComposerTrigger(
nextPrompt,
expandCollapsedComposerCursor(nextPrompt, nextCursor),
),
);
},
[setPrompt],
);
const onComposerCommandKey = (key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab", event: KeyboardEvent) => {
const onComposerCommandKey = (
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
event: KeyboardEvent,
) => {
const { trigger } = resolveActiveComposerTrigger();
const menuIsActive = composerMenuOpenRef.current || trigger !== null;
@@ -2499,6 +2513,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
</header>
{/* Error banner */}
<ProviderHealthBanner status={activeProviderStatus} />
<ThreadErrorBanner error={activeThread.error} />
<PendingApprovalsPanel
pendingApprovals={pendingApprovals}
@@ -2540,6 +2555,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
/>
</div>
@@ -2786,7 +2802,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
{isGitRepo && (
<BranchToolbar
threadId={activeThread.id}
envMode={envMode}
onEnvModeChange={onEnvModeChange}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
@@ -3000,6 +3015,35 @@ const ThreadErrorBanner = memo(function ThreadErrorBanner({ error }: { error: st
);
});
const ProviderHealthBanner = memo(function ProviderHealthBanner({
status,
}: {
status: ServerProviderStatus | null;
}) {
if (!status || status.status === "ready") {
return null;
}
const defaultMessage =
status.status === "error"
? `${status.provider} provider is unavailable.`
: `${status.provider} provider has limited availability.`;
return (
<div className="pt-3 mx-auto max-w-3xl">
<Alert variant={status.status === "error" ? "error" : "warning"}>
<CircleAlertIcon />
<AlertTitle>
{status.provider === "codex" ? "Codex provider status" : `${status.provider} status`}
</AlertTitle>
<AlertDescription className="line-clamp-3" title={status.message ?? defaultMessage}>
{status.message ?? defaultMessage}
</AlertDescription>
</Alert>
</div>
);
});
interface PendingApprovalsPanelProps {
pendingApprovals: PendingApproval[];
respondingRequestIds: ApprovalRequestId[];
@@ -3091,6 +3135,156 @@ const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: stri
);
});
function hasNonZeroStat(stat: { additions: number; deletions: number }): boolean {
return stat.additions > 0 || stat.deletions > 0;
}
const DiffStatLabel = memo(function DiffStatLabel(props: {
additions: number;
deletions: number;
showParentheses?: boolean;
}) {
const { additions, deletions, showParentheses = false } = props;
return (
<>
{showParentheses && <span className="text-muted-foreground/70">(</span>}
<span className="text-success">+{additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{deletions}</span>
{showParentheses && <span className="text-muted-foreground/70">)</span>}
</>
);
});
function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
const paths: string[] = [];
for (const node of nodes) {
if (node.kind !== "directory") continue;
paths.push(node.path);
paths.push(...collectDirectoryPaths(node.children));
}
return paths;
}
function buildDirectoryExpansionState(
directoryPaths: ReadonlyArray<string>,
expanded: boolean,
): Record<string, boolean> {
const expandedState: Record<string, boolean> = {};
for (const directoryPath of directoryPaths) {
expandedState[directoryPath] = expanded;
}
return expandedState;
}
const ChangedFilesTree = memo(function ChangedFilesTree(props: {
turnId: TurnId;
files: ReadonlyArray<TurnDiffFileChange>;
allDirectoriesExpanded: boolean;
resolvedTheme: "light" | "dark";
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;
const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
const directoryPathsKey = useMemo(() => collectDirectoryPaths(treeNodes).join("\u0000"), [treeNodes]);
const allDirectoryExpansionState = useMemo(
() =>
buildDirectoryExpansionState(
directoryPathsKey ? directoryPathsKey.split("\u0000") : [],
allDirectoriesExpanded,
),
[allDirectoriesExpanded, directoryPathsKey],
);
const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(
() => buildDirectoryExpansionState((directoryPathsKey ? directoryPathsKey.split("\u0000") : []), true),
);
useEffect(() => {
setExpandedDirectories(allDirectoryExpansionState);
}, [allDirectoryExpansionState]);
const toggleDirectory = useCallback((pathValue: string, fallbackExpanded: boolean) => {
setExpandedDirectories((current) => ({
...current,
[pathValue]: !(current[pathValue] ?? fallbackExpanded),
}));
}, []);
const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
const leftPadding = 8 + depth * 14;
if (node.kind === "directory") {
const isExpanded = expandedDirectories[node.path] ?? depth === 0;
return (
<div key={`dir:${node.path}`}>
<button
type="button"
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => toggleDirectory(node.path, depth === 0)}
>
<ChevronRightIcon
aria-hidden="true"
className={cn(
"size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
isExpanded && "rotate-90",
)}
/>
{isExpanded ? (
<FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
) : (
<FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
)}
<span className="truncate font-mono text-[11px] text-muted-foreground/90 group-hover:text-foreground/90">
{node.name}
</span>
{hasNonZeroStat(node.stat) && (
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
</span>
)}
</button>
{isExpanded && (
<div className="space-y-0.5">
{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}
</div>
)}
</div>
);
}
return (
<button
key={`file:${node.path}`}
type="button"
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => onOpenTurnDiff(turnId, node.path)}
>
<span aria-hidden="true" className="size-3.5 shrink-0" />
<VscodeEntryIcon
pathValue={node.path}
kind="file"
theme={resolvedTheme}
className="size-3.5 text-muted-foreground/70"
/>
<span className="truncate font-mono text-[11px] text-muted-foreground/80 group-hover:text-foreground/90">
{node.name}
</span>
{node.stat && (
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
</span>
)}
</button>
);
};
return (
<div className="space-y-0.5">
{treeNodes.map((node) => renderTreeNode(node, 0))}
</div>
);
});
interface MessagesTimelineProps {
hasMessages: boolean;
isWorking: boolean;
@@ -3110,6 +3304,7 @@ interface MessagesTimelineProps {
isRevertingCheckpoint: boolean;
onImageExpand: (preview: ExpandedImagePreview) => void;
markdownCwd: string | undefined;
resolvedTheme: "light" | "dark";
}
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
@@ -3131,20 +3326,6 @@ type TimelineRow =
}
| { kind: "working"; id: string; createdAt: string | null };
function estimateTimelineMessageHeight(message: TimelineMessage): number {
const textLength = message.text.length;
if (message.role === "assistant") {
const estimatedLines = Math.max(1, Math.ceil(textLength / 72));
return 78 + Math.min(estimatedLines * 22, 820);
}
const estimatedLines = Math.max(1, Math.ceil(textLength / 56));
const attachmentCount = message.attachments?.length ?? 0;
const attachmentRows = Math.ceil(attachmentCount / 2);
const attachmentHeight = attachmentRows * 124;
return 96 + Math.min(estimatedLines * 22, 620) + attachmentHeight;
}
const MessagesTimeline = memo(function MessagesTimeline({
hasMessages,
isWorking,
@@ -3164,7 +3345,36 @@ const MessagesTimeline = memo(function MessagesTimeline({
isRevertingCheckpoint,
onImageExpand,
markdownCwd,
resolvedTheme,
}: MessagesTimelineProps) {
const timelineRootRef = useRef<HTMLDivElement | null>(null);
const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
useLayoutEffect(() => {
const timelineRoot = timelineRootRef.current;
if (!timelineRoot) return;
const updateWidth = (nextWidth: number) => {
setTimelineWidthPx((previousWidth) => {
if (previousWidth !== null && Math.abs(previousWidth - nextWidth) < 0.5) {
return previousWidth;
}
return nextWidth;
});
};
updateWidth(timelineRoot.getBoundingClientRect().width);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => {
updateWidth(timelineRoot.getBoundingClientRect().width);
});
observer.observe(timelineRoot);
return () => {
observer.disconnect();
};
}, [hasMessages, isWorking]);
const rows = useMemo<TimelineRow[]>(() => {
const nextRows: TimelineRow[] = [];
@@ -3268,12 +3478,16 @@ const MessagesTimeline = memo(function MessagesTimeline({
if (!row) return 96;
if (row.kind === "work") return 112;
if (row.kind === "working") return 40;
return estimateTimelineMessageHeight(row.message);
return estimateTimelineMessageHeight(row.message, { timelineWidthPx });
},
measureElement: measureVirtualElement,
useAnimationFrameWithResizeObserver: true,
overscan: 8,
});
useEffect(() => {
if (timelineWidthPx === null) return;
rowVirtualizer.measure();
}, [rowVirtualizer, timelineWidthPx]);
useEffect(() => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => {
const viewportHeight = instance.scrollRect?.height ?? 0;
@@ -3304,9 +3518,23 @@ const MessagesTimeline = memo(function MessagesTimeline({
const virtualRows = rowVirtualizer.getVirtualItems();
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
const [allDirectoriesExpandedByTurnId, setAllDirectoriesExpandedByTurnId] = useState<
Record<string, boolean>
>({});
const onToggleAllDirectories = useCallback((turnId: TurnId) => {
setAllDirectoriesExpandedByTurnId((current) => ({
...current,
[turnId]: !(current[turnId] ?? true),
}));
}, []);
const renderRowContent = (row: TimelineRow) => (
<div className="pb-4">
<div
className="pb-4"
data-timeline-row-kind={row.kind}
data-message-id={row.kind === "message" ? row.message.id : undefined}
data-message-role={row.kind === "message" ? row.message.role : undefined}
>
{row.kind === "work" &&
(() => {
const groupId = row.id;
@@ -3472,81 +3700,54 @@ const MessagesTimeline = memo(function MessagesTimeline({
if (!turnSummary) return null;
const checkpointFiles = turnSummary.files;
if (checkpointFiles.length === 0) return null;
const summaryStat = checkpointFiles.reduce(
(acc, file) => {
if (
typeof file.additions !== "number" ||
typeof file.deletions !== "number"
) {
return acc;
}
return {
additions: acc.additions + file.additions,
deletions: acc.deletions + file.deletions,
};
},
{ additions: 0, deletions: 0 },
);
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
const changedFileCountLabel = String(checkpointFiles.length);
const allDirectoriesExpanded =
allDirectoriesExpandedByTurnId[turnSummary.turnId] ?? true;
return (
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
<div className="mb-1.5 flex items-center justify-between gap-2">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
<span>Changed files ({changedFileCountLabel})</span>
{(summaryStat.additions > 0 || summaryStat.deletions > 0) && (
{hasNonZeroStat(summaryStat) && (
<>
<span className="mx-1">•</span>
<span className="text-success">+{summaryStat.additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{summaryStat.deletions}</span>
<DiffStatLabel
additions={summaryStat.additions}
deletions={summaryStat.deletions}
/>
</>
)}
</p>
<Button
type="button"
size="xs"
variant="outline"
onClick={() =>
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
}
>
View diff
</Button>
</div>
<div className="flex flex-wrap gap-1.5">
{checkpointFiles.map((file) => (
<button
key={`${turnSummary.turnId}:${file.path}`}
<div className="flex items-center gap-1.5">
<Button
type="button"
className="rounded-md border border-border/70 bg-background/70 px-2 py-1 font-mono text-[11px] text-muted-foreground/80 transition-colors hover:border-border hover:text-foreground/90"
onClick={() => onOpenTurnDiff(turnSummary.turnId, file.path)}
size="xs"
variant="outline"
onClick={() => onToggleAllDirectories(turnSummary.turnId)}
>
{(() => {
const stat =
typeof file.additions === "number" &&
typeof file.deletions === "number"
? {
additions: file.additions,
deletions: file.deletions,
}
: null;
if (!stat) {
return file.path;
}
return (
<>
<span>{file.path}</span>
<span className="ml-1 text-muted-foreground/70">(</span>
<span className="text-success">+{stat.additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{stat.deletions}</span>
<span className="text-muted-foreground/70">)</span>
</>
);
})()}
</button>
))}
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
</Button>
<Button
type="button"
size="xs"
variant="outline"
onClick={() =>
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
}
>
View diff
</Button>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
</div>
);
})()}
@@ -3589,7 +3790,11 @@ const MessagesTimeline = memo(function MessagesTimeline({
}
return (
<div className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden">
<div
ref={timelineRootRef}
data-timeline-root="true"
className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden"
>
{virtualizedRowCount > 0 && (
<div className="relative" style={{ height: `${rowVirtualizer.getTotalSize()}px` }}>
{virtualRows.map((virtualRow: VirtualItem) => {
@@ -50,6 +50,7 @@ import {
type Ref,
} from "react";
import { isCollapsedCursorAdjacentToMention } from "~/composer-logic";
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
import { cn } from "~/lib/utils";
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
@@ -469,16 +470,25 @@ function ComposerMentionArrowPlugin() {
useEffect(() => {
const unregisterLeft = editor.registerCommand(
KEY_ARROW_LEFT_COMMAND,
() => {
let currentOffset = -1;
(event) => {
let nextOffset: number | null = null;
editor.getEditorState().read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
currentOffset = $readSelectionOffsetFromEditorState(0);
const currentOffset = $readSelectionOffsetFromEditorState(0);
if (currentOffset <= 0) return;
const promptValue = $getRoot().getTextContent();
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "left")) {
return;
}
nextOffset = currentOffset - 1;
});
if (currentOffset <= 0) return false;
if (nextOffset === null) return false;
const selectionOffset = nextOffset;
event?.preventDefault();
event?.stopPropagation();
editor.update(() => {
$setSelectionAtComposerOffset(currentOffset - 1);
$setSelectionAtComposerOffset(selectionOffset);
});
return true;
},
@@ -486,18 +496,26 @@ function ComposerMentionArrowPlugin() {
);
const unregisterRight = editor.registerCommand(
KEY_ARROW_RIGHT_COMMAND,
() => {
let currentOffset = -1;
let composerLength = 0;
(event) => {
let nextOffset: number | null = null;
editor.getEditorState().read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
composerLength = $getComposerRootLength();
currentOffset = $readSelectionOffsetFromEditorState(0);
const currentOffset = $readSelectionOffsetFromEditorState(0);
const composerLength = $getComposerRootLength();
if (currentOffset >= composerLength) return;
const promptValue = $getRoot().getTextContent();
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "right")) {
return;
}
nextOffset = currentOffset + 1;
});
if (currentOffset < 0 || currentOffset >= composerLength) return false;
if (nextOffset === null) return false;
const selectionOffset = nextOffset;
event?.preventDefault();
event?.stopPropagation();
editor.update(() => {
$setSelectionAtComposerOffset(currentOffset + 1);
$setSelectionAtComposerOffset(selectionOffset);
});
return true;
},
@@ -540,29 +558,6 @@ function ComposerMentionSelectionNormalizePlugin() {
return null;
}
function $isCursorAdjacentToMention(): boolean {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return false;
const anchorNode = selection.anchor.getNode();
if (anchorNode instanceof ComposerMentionNode) return true;
if ($isElementNode(anchorNode)) {
const childIndex = selection.anchor.offset - 1;
if (childIndex >= 0) {
const child = anchorNode.getChildAtIndex(childIndex);
if (child instanceof ComposerMentionNode) return true;
}
}
if ($isTextNode(anchorNode) && selection.anchor.offset === 0) {
const prev = anchorNode.getPreviousSibling();
if (prev instanceof ComposerMentionNode) return true;
}
return false;
}
function ComposerMentionBackspacePlugin() {
const [editor] = useLexicalComposerContext();
@@ -738,7 +733,10 @@ function ComposerPromptEditorInner({
value: nextValue,
cursor: nextCursor,
};
onChangeRef.current(nextValue, nextCursor, $isCursorAdjacentToMention());
const cursorAdjacentToMention =
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
onChangeRef.current(nextValue, nextCursor, cursorAdjacentToMention);
});
}, []);
@@ -737,7 +737,7 @@ describe("when: branch has no upstream configured", () => {
});
describe("requiresDefaultBranchConfirmation", () => {
it("requires confirmation only for push actions on default branch", () => {
it("requires confirmation for push actions on default branch", () => {
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
assert.isTrue(requiresDefaultBranchConfirmation("commit_push", true));
assert.isTrue(requiresDefaultBranchConfirmation("commit_push_pr", true));
@@ -804,6 +804,17 @@ describe("buildGitActionProgressStages", () => {
assert.deepEqual(stages, ["Pushing to origin/feature/test..."]);
});
it("skips commit stages for create-pr flow when push-only is forced", () => {
const stages = buildGitActionProgressStages({
action: "commit_push_pr",
hasCustomCommitMessage: false,
hasWorkingTreeChanges: true,
forcePushOnly: true,
pushTarget: "origin/feature/test",
});
assert.deepEqual(stages, ["Pushing to origin/feature/test...", "Creating PR..."]);
});
it("includes commit stages for commit+push when working tree is dirty", () => {
const stages = buildGitActionProgressStages({
action: "commit_push",
@@ -823,6 +834,7 @@ describe("summarizeGitResult", () => {
it("returns commit-focused toast for commit action", () => {
const result = summarizeGitResult({
action: "commit",
branch: { status: "skipped_not_requested" },
commit: {
status: "created",
commitSha: "0123456789abcdef",
@@ -841,6 +853,7 @@ describe("summarizeGitResult", () => {
it("returns push-focused toast for push action", () => {
const result = summarizeGitResult({
action: "commit_push",
branch: { status: "skipped_not_requested" },
commit: {
status: "created",
commitSha: "abcdef0123456789",
@@ -863,6 +876,7 @@ describe("summarizeGitResult", () => {
it("returns PR-focused toast for created PR action", () => {
const result = summarizeGitResult({
action: "commit_push_pr",
branch: { status: "skipped_not_requested" },
commit: {
status: "created",
commitSha: "89abcdef01234567",
@@ -888,6 +902,7 @@ describe("summarizeGitResult", () => {
it("truncates long description text", () => {
const result = summarizeGitResult({
action: "commit_push_pr",
branch: { status: "skipped_not_requested" },
commit: {
status: "created",
commitSha: "89abcdef01234567",
@@ -910,18 +925,31 @@ describe("summarizeGitResult", () => {
});
describe("resolveAutoFeatureBranchName", () => {
const day = new Date("2026-03-01T12:00:00.000Z");
it("returns the base auto feature branch name when available", () => {
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], day);
assert.equal(branch, "feature/stacked-20260301");
it("uses semantic preferred branch names when available", () => {
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
assert.equal(branch, "feature/fix-toast-copy");
});
it("increments suffix when the base name already exists", () => {
it("normalizes preferred names that already include a branch namespace", () => {
const branch = resolveAutoFeatureBranchName(["main"], "feature/refine-toolbar-actions");
assert.equal(branch, "feature/refine-toolbar-actions");
});
it("increments suffix when the preferred branch name already exists", () => {
const branch = resolveAutoFeatureBranchName(
["main", "feature/stacked-20260301", "feature/stacked-20260301-2"],
day,
["main", "feature/fix-toast-copy", "feature/fix-toast-copy-2"],
"fix toast copy",
);
assert.equal(branch, "feature/stacked-20260301-3");
assert.equal(branch, "feature/fix-toast-copy-3");
});
it("treats existing branch names as case-insensitive for collision checks", () => {
const branch = resolveAutoFeatureBranchName(["Feature/Ticket-1"], "feature/ticket-1");
assert.equal(branch, "feature/ticket-1-2");
});
it("falls back to feature/update when no preferred name is provided", () => {
const branch = resolveAutoFeatureBranchName(["main"]);
assert.equal(branch, "feature/update");
});
});
@@ -35,7 +35,6 @@ export type DefaultBranchConfirmableAction = "commit_push" | "commit_push_pr";
const SHORT_SHA_LENGTH = 7;
const TOAST_DESCRIPTION_MAX = 72;
const AUTO_FEATURE_BRANCH_PREFIX = "feature/stacked";
function shortenSha(sha: string | undefined): string | null {
if (!sha) return null;
@@ -58,7 +57,9 @@ export function buildGitActionProgressStages(input: {
hasWorkingTreeChanges: boolean;
forcePushOnly?: boolean;
pushTarget?: string;
featureBranch?: boolean;
}): string[] {
const branchStages = input.featureBranch ? ["Preparing feature branch..."] : [];
const shouldIncludeCommitStages =
!input.forcePushOnly && (input.action === "commit" || input.hasWorkingTreeChanges);
const commitStages = !shouldIncludeCommitStages
@@ -68,12 +69,12 @@ export function buildGitActionProgressStages(input: {
: ["Generating commit message...", "Committing..."];
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
if (input.action === "commit") {
return commitStages;
return [...branchStages, ...commitStages];
}
if (input.action === "commit_push") {
return [...commitStages, pushStage];
return [...branchStages, ...commitStages, pushStage];
}
return [...commitStages, pushStage, "Creating PR..."];
return [...branchStages, ...commitStages, pushStage, "Creating PR..."];
}
const withDescription = (title: string, description: string | undefined) =>
@@ -321,29 +322,5 @@ export function resolveDefaultBranchActionDialogCopy(input: {
};
}
function formatDateForBranch(now: Date): string {
const year = now.getUTCFullYear();
const month = String(now.getUTCMonth() + 1).padStart(2, "0");
const day = String(now.getUTCDate()).padStart(2, "0");
return `${year}${month}${day}`;
}
export function resolveAutoFeatureBranchName(
existingBranchNames: readonly string[],
now = new Date(),
): string {
const daySlug = formatDateForBranch(now);
const base = `${AUTO_FEATURE_BRANCH_PREFIX}-${daySlug}`;
const existingNames = new Set(existingBranchNames);
if (!existingNames.has(base)) {
return base;
}
let suffix = 2;
while (existingNames.has(`${base}-${suffix}`)) {
suffix += 1;
}
return `${base}-${suffix}`;
}
// Re-export from shared for backwards compatibility in this module's exports
export { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
+17 -59
View File
@@ -1,4 +1,4 @@
import { type GitStatusResult, type GitStackedAction, type ThreadId } from "@t3tools/contracts";
import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts";
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
@@ -11,7 +11,6 @@ import {
type GitQuickAction,
type DefaultBranchConfirmableAction,
requiresDefaultBranchConfirmation,
resolveAutoFeatureBranchName,
resolveDefaultBranchActionDialogCopy,
resolveQuickAction,
summarizeGitResult,
@@ -34,7 +33,6 @@ import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
import {
gitBranchesQueryOptions,
gitCreateBranchAndCheckoutMutationOptions,
gitInitMutationOptions,
gitMutationKeys,
gitPullMutationOptions,
@@ -172,18 +170,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const runImmediateGitActionMutation = useMutation(
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
);
const createBranchAndCheckoutMutation = useMutation(
gitCreateBranchAndCheckoutMutationOptions({ cwd: gitCwd, queryClient }),
);
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
const isRunStackedActionRunning =
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
const isCreateBranchAndCheckoutRunning =
useIsMutating({ mutationKey: gitMutationKeys.createBranchAndCheckout(gitCwd) }) > 0;
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
const isGitActionRunning =
isRunStackedActionRunning || isCreateBranchAndCheckoutRunning || isPullRunning;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
@@ -247,6 +239,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
onConfirmed,
skipDefaultBranchPrompt = false,
statusOverride,
featureBranch = false,
isDefaultBranchOverride,
progressToastId,
}: {
@@ -256,12 +249,13 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: GitStatusResult | null;
featureBranch?: boolean;
isDefaultBranchOverride?: boolean;
progressToastId?: GitActionToastId;
}) => {
const actionStatus = statusOverride ?? gitStatusForActions;
const actionIsDefaultBranch = isDefaultBranchOverride ?? isDefaultBranch;
const actionBranch = actionStatus?.branch ?? null;
const actionIsDefaultBranch = isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);
const includesCommit =
!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
if (
@@ -284,12 +278,13 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
}
onConfirmed?.();
const pushTarget = actionBranch ? `origin/${actionBranch}` : undefined;
const pushTarget = !featureBranch && actionBranch ? `origin/${actionBranch}` : undefined;
const progressStages = buildGitActionProgressStages({
action,
hasCustomCommitMessage: !!commitMessage?.trim(),
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
forcePushOnly: forcePushOnlyProgress,
featureBranch,
...(pushTarget ? { pushTarget } : {}),
});
const resolvedProgressToastId =
@@ -328,6 +323,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const promise = runImmediateGitActionMutation.mutateAsync({
action,
...(commitMessage ? { commitMessage } : {}),
...(featureBranch ? { featureBranch } : {}),
});
try {
@@ -341,7 +337,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const shouldOfferOpenPrCta =
(action === "commit_push" || action === "commit_push_pr") &&
!!prUrl &&
!actionIsDefaultBranch;
(!actionIsDefaultBranch ||
result.pr.status === "created" ||
result.pr.status === "opened_existing");
const shouldOfferCreatePrCta =
action === "commit_push" &&
!prUrl &&
@@ -395,6 +393,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
closeResultToast();
void runGitActionWithToast({
action: "commit_push_pr",
forcePushOnlyProgress: true,
statusOverride: actionStatus,
isDefaultBranchOverride: actionIsDefaultBranch,
});
@@ -443,54 +442,13 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
}) => {
const branchName = resolveAutoFeatureBranchName(
branchList?.branches.map((branch) => branch.name) ?? [],
);
const checkoutPromise = createBranchAndCheckoutMutation.mutateAsync(branchName);
const checkoutToastId = toastManager.add({
type: "loading",
title: `Creating ${branchName}...`,
timeout: 0,
data: threadToastData,
void runGitActionWithToast({
...actionParams,
featureBranch: true,
skipDefaultBranchPrompt: true,
});
void checkoutPromise
.then(() => {
const statusOverride = gitStatusForActions
? {
...gitStatusForActions,
branch: branchName,
pr: null,
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
}
: null;
return runGitActionWithToast({
...actionParams,
skipDefaultBranchPrompt: true,
statusOverride,
isDefaultBranchOverride: false,
progressToastId: checkoutToastId,
});
})
.catch((error) => {
toastManager.update(checkoutToastId, {
type: "error",
title: "Failed to checkout feature branch",
description: error instanceof Error ? error.message : "An error occurred.",
data: threadToastData,
});
});
},
[
branchList?.branches,
createBranchAndCheckoutMutation,
gitStatusForActions,
runGitActionWithToast,
threadToastData,
],
[runGitActionWithToast],
);
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
+293 -64
View File
@@ -1,7 +1,15 @@
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
import {
ChevronRightIcon,
FolderIcon,
GitPullRequestIcon,
RocketIcon,
SquarePenIcon,
TerminalIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
DEFAULT_MODEL,
type DesktopUpdateState,
ProjectId,
ThreadId,
type GitStatusResult,
@@ -14,7 +22,7 @@ import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
import { type Thread } from "../types";
import { derivePendingApprovals } from "../session-logic";
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
@@ -23,6 +31,15 @@ import { readNativeApi } from "../nativeApi";
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { toastManager } from "./ui/toast";
import {
getDesktopUpdateActionError,
getDesktopUpdateButtonTooltip,
isDesktopUpdateButtonDisabled,
resolveDesktopUpdateButtonAction,
shouldHighlightDesktopUpdateError,
shouldShowDesktopUpdateButton,
shouldToastDesktopUpdateActionResult,
} from "./desktopUpdate.logic";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import {
@@ -30,6 +47,7 @@ import {
SidebarFooter,
SidebarGroup,
SidebarHeader,
SidebarMenuAction,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
@@ -43,6 +61,14 @@ import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "
import { isNonEmpty as isNonEmptyString } from "effect/String";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
async function copyTextToClipboard(text: string): Promise<void> {
if (typeof navigator === "undefined" || navigator.clipboard?.writeText === undefined) {
throw new Error("Clipboard API unavailable.");
}
await navigator.clipboard.writeText(text);
}
function formatRelativeTime(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
@@ -268,8 +294,12 @@ export default function Sidebar() {
const [isAddingProject, setIsAddingProject] = useState(false);
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
ReadonlySet<ProjectId>
>(() => new Set());
const renamingCommittedRef = useRef(false);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const [desktopUpdateState, setDesktopUpdateState] = useState<DesktopUpdateState | null>(null);
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<ThreadId, boolean>();
for (const thread of threads) {
@@ -564,6 +594,7 @@ export default function Sidebar() {
[
{ id: "rename", label: "Rename thread" },
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-thread-id", label: "Copy Thread ID" },
{ id: "delete", label: "Delete", destructive: true },
],
position,
@@ -582,6 +613,23 @@ export default function Sidebar() {
markThreadUnread(threadId);
return;
}
if (clicked === "copy-thread-id") {
try {
await copyTextToClipboard(threadId);
toastManager.add({
type: "success",
title: "Thread ID copied",
description: threadId,
});
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to copy thread ID",
description: error instanceof Error ? error.message : "An error occurred.",
});
}
return;
}
if (clicked !== "delete") return;
if (appSettings.confirmThreadDelete) {
const confirmed = await api.dialogs.confirm(
@@ -766,8 +814,7 @@ export default function Sidebar() {
}
if (!isChatNewShortcut(event, keybindings)) return;
const projectId =
activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
if (!projectId) return;
event.preventDefault();
void handleNewThread(projectId, {
@@ -783,14 +830,142 @@ export default function Sidebar() {
};
}, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, threads]);
const onCreateThreadClick = () => {
if (projects.length === 0) {
setAddingProject(true);
useEffect(() => {
if (!isElectron) return;
const bridge = window.desktopBridge;
if (
!bridge ||
typeof bridge.getUpdateState !== "function" ||
typeof bridge.onUpdateState !== "function"
) {
return;
}
const firstProject = projects[0];
if (firstProject) void handleNewThread(firstProject.id);
};
let disposed = false;
let receivedSubscriptionUpdate = false;
const unsubscribe = bridge.onUpdateState((nextState) => {
if (disposed) return;
receivedSubscriptionUpdate = true;
setDesktopUpdateState(nextState);
});
void bridge
.getUpdateState()
.then((nextState) => {
if (disposed || receivedSubscriptionUpdate) return;
setDesktopUpdateState(nextState);
})
.catch(() => undefined);
return () => {
disposed = true;
unsubscribe();
};
}, []);
const showDesktopUpdateButton = isElectron && shouldShowDesktopUpdateButton(desktopUpdateState);
const desktopUpdateTooltip = desktopUpdateState
? getDesktopUpdateButtonTooltip(desktopUpdateState)
: "Update available";
const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState);
const desktopUpdateButtonAction = desktopUpdateState
? resolveDesktopUpdateButtonAction(desktopUpdateState)
: "none";
const desktopUpdateButtonInteractivityClasses = desktopUpdateButtonDisabled
? "cursor-not-allowed opacity-60"
: "hover:bg-accent hover:text-foreground";
const desktopUpdateButtonClasses =
desktopUpdateState?.status === "downloaded"
? "text-emerald-500"
: desktopUpdateState?.status === "downloading"
? "text-sky-400"
: shouldHighlightDesktopUpdateError(desktopUpdateState)
? "text-rose-500 animate-pulse"
: "text-amber-500 animate-pulse";
const newThreadShortcutLabel = useMemo(
() =>
shortcutLabelForCommand(keybindings, "chat.newLocal") ??
shortcutLabelForCommand(keybindings, "chat.new"),
[keybindings],
);
const handleDesktopUpdateButtonClick = useCallback(() => {
const bridge = window.desktopBridge;
if (!bridge || !desktopUpdateState) return;
if (desktopUpdateButtonDisabled || desktopUpdateButtonAction === "none") return;
if (desktopUpdateButtonAction === "download") {
void bridge
.downloadUpdate()
.then((result) => {
if (result.completed) {
toastManager.add({
type: "success",
title: "Update downloaded",
description: "Restart the app from the update button to install it.",
});
}
if (!shouldToastDesktopUpdateActionResult(result)) return;
const actionError = getDesktopUpdateActionError(result);
if (!actionError) return;
toastManager.add({
type: "error",
title: "Could not download update",
description: actionError,
});
})
.catch((error) => {
toastManager.add({
type: "error",
title: "Could not start update download",
description: error instanceof Error ? error.message : "An unexpected error occurred.",
});
});
return;
}
if (desktopUpdateButtonAction === "install") {
void bridge
.installUpdate()
.then((result) => {
if (!shouldToastDesktopUpdateActionResult(result)) return;
const actionError = getDesktopUpdateActionError(result);
if (!actionError) return;
toastManager.add({
type: "error",
title: "Could not install update",
description: actionError,
});
})
.catch((error) => {
toastManager.add({
type: "error",
title: "Could not install update",
description: error instanceof Error ? error.message : "An unexpected error occurred.",
});
});
}
}, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]);
const expandThreadListForProject = useCallback((projectId: ProjectId) => {
setExpandedThreadListsByProject((current) => {
if (current.has(projectId)) return current;
const next = new Set(current);
next.add(projectId);
return next;
});
}, []);
const collapseThreadListForProject = useCallback((projectId: ProjectId) => {
setExpandedThreadListsByProject((current) => {
if (!current.has(projectId)) return current;
const next = new Set(current);
next.delete(projectId);
return next;
});
}, []);
const wordmark = (
<div className="flex items-center gap-2">
@@ -807,30 +982,36 @@ export default function Sidebar() {
</div>
);
const newThreadButton = (
<button
type="button"
className="flex w-full items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent"
onClick={onCreateThreadClick}
>
<span className="text-foreground">+</span>
New thread
</button>
);
return (
<>
{isElectron ? (
<>
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
{wordmark}
{showDesktopUpdateButton && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={desktopUpdateTooltip}
aria-disabled={desktopUpdateButtonDisabled || undefined}
disabled={desktopUpdateButtonDisabled}
className={`inline-flex size-7 ml-auto mt-2 items-center justify-center rounded-md text-muted-foreground transition-colors ${desktopUpdateButtonInteractivityClasses} ${desktopUpdateButtonClasses}`}
onClick={handleDesktopUpdateButtonClick}
>
<RocketIcon className="size-3.5" />
</button>
}
/>
<TooltipPopup side="bottom">{desktopUpdateTooltip}</TooltipPopup>
</Tooltip>
)}
</SidebarHeader>
<div className="px-4 py-2">{newThreadButton}</div>
</>
) : (
<SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
{wordmark}
{newThreadButton}
</SidebarHeader>
)}
@@ -838,13 +1019,19 @@ export default function Sidebar() {
<SidebarGroup className="px-2 py-2">
<SidebarMenu>
{projects.map((project) => {
const visibleThreads = threads
const projectThreads = threads
.filter((thread) => thread.projectId === project.id)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
if (byDate !== 0) return byDate;
return b.id.localeCompare(a.id);
});
const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
const hasHiddenThreads = projectThreads.length > THREAD_PREVIEW_LIMIT;
const visibleThreads =
hasHiddenThreads && !isThreadListExpanded
? projectThreads.slice(0, THREAD_PREVIEW_LIMIT)
: projectThreads;
return (
<Collapsible
@@ -857,34 +1044,61 @@ export default function Sidebar() {
}}
>
<SidebarMenuItem>
<CollapsibleTrigger
render={
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-left hover:bg-accent"
<div className="group/project-header relative">
<CollapsibleTrigger
render={
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-left hover:bg-accent group-hover/project-header:bg-accent group-hover/project-header:text-sidebar-accent-foreground"
/>
}
onContextMenu={(event) => {
event.preventDefault();
void handleProjectContextMenu(project.id, {
x: event.clientX,
y: event.clientY,
});
}}
>
<ChevronRightIcon
className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
project.expanded ? "rotate-90" : ""
}`}
/>
}
onContextMenu={(event) => {
event.preventDefault();
void handleProjectContextMenu(project.id, {
x: event.clientX,
y: event.clientY,
});
}}
>
<ChevronRightIcon
className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
project.expanded ? "rotate-90" : ""
}`}
/>
<ProjectFavicon cwd={project.cwd} />
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
<span className="text-[10px] text-muted-foreground/60">
{visibleThreads.length}
</span>
</CollapsibleTrigger>
<ProjectFavicon cwd={project.cwd} />
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
</CollapsibleTrigger>
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuAction
render={
<button
type="button"
aria-label={`Create new thread in ${project.name}`}
/>
}
showOnHover
className="top-1 right-1 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground"
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
void handleNewThread(project.id);
}}
>
<SquarePenIcon className="size-3.5" />
</SidebarMenuAction>
}
/>
<TooltipPopup side="top">
{newThreadShortcutLabel
? `New thread (${newThreadShortcutLabel})`
: "New thread"}
</TooltipPopup>
</Tooltip>
</div>
<CollapsibleContent>
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
@@ -1028,19 +1242,34 @@ export default function Sidebar() {
);
})}
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
onClick={() => {
void handleNewThread(project.id);
}}
>
<span>+</span>
<span>New thread</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
{hasHiddenThreads && !isThreadListExpanded && (
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
onClick={() => {
expandThreadListForProject(project.id);
}}
>
<span>Show more</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
{hasHiddenThreads && isThreadListExpanded && (
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
onClick={() => {
collapseThreadListForProject(project.id);
}}
>
<span>Show less</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
</SidebarMenuSub>
</CollapsibleContent>
</SidebarMenuItem>
@@ -0,0 +1,174 @@
import { describe, expect, it } from "vitest";
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
import {
getDesktopUpdateActionError,
getDesktopUpdateButtonTooltip,
isDesktopUpdateButtonDisabled,
resolveDesktopUpdateButtonAction,
shouldHighlightDesktopUpdateError,
shouldShowDesktopUpdateButton,
shouldToastDesktopUpdateActionResult,
} from "./desktopUpdate.logic";
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
currentVersion: "1.0.0",
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
checkedAt: null,
message: null,
errorContext: null,
canRetry: false,
};
describe("desktop update button state", () => {
it("shows a download action when an update is available", () => {
const state: DesktopUpdateState = { ...baseState, status: "available", availableVersion: "1.1.0" };
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
expect(resolveDesktopUpdateButtonAction(state)).toBe("download");
});
it("keeps retry action available after a download error", () => {
const state: DesktopUpdateState = {
...baseState,
status: "error",
availableVersion: "1.1.0",
message: "network timeout",
errorContext: "download",
canRetry: true,
};
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
expect(resolveDesktopUpdateButtonAction(state)).toBe("download");
expect(getDesktopUpdateButtonTooltip(state)).toContain("Click to retry");
});
it("keeps install action available after an install error", () => {
const state: DesktopUpdateState = {
...baseState,
status: "error",
downloadedVersion: "1.1.0",
availableVersion: "1.1.0",
message: "shutdown timeout",
errorContext: "install",
canRetry: true,
};
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
expect(resolveDesktopUpdateButtonAction(state)).toBe("install");
expect(getDesktopUpdateButtonTooltip(state)).toContain("Click to retry");
});
it("hides the button for non-actionable check errors", () => {
const state: DesktopUpdateState = {
...baseState,
status: "error",
message: "network unavailable",
errorContext: "check",
canRetry: true,
};
expect(shouldShowDesktopUpdateButton(state)).toBe(false);
expect(resolveDesktopUpdateButtonAction(state)).toBe("none");
});
it("disables the button while downloading", () => {
const state: DesktopUpdateState = {
...baseState,
status: "downloading",
availableVersion: "1.1.0",
downloadPercent: 42.5,
};
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
expect(isDesktopUpdateButtonDisabled(state)).toBe(true);
expect(getDesktopUpdateButtonTooltip(state)).toContain("42%");
});
});
describe("getDesktopUpdateActionError", () => {
it("returns user-visible message for accepted failed attempts", () => {
const result: DesktopUpdateActionResult = {
accepted: true,
completed: false,
state: {
...baseState,
status: "available",
availableVersion: "1.1.0",
message: "checksum mismatch",
errorContext: "download",
canRetry: true,
},
};
expect(getDesktopUpdateActionError(result)).toBe("checksum mismatch");
});
it("ignores messages for non-accepted attempts", () => {
const result: DesktopUpdateActionResult = {
accepted: false,
completed: false,
state: {
...baseState,
status: "error",
message: "background failure",
errorContext: "check",
canRetry: false,
},
};
expect(getDesktopUpdateActionError(result)).toBeNull();
});
it("ignores messages for successful attempts", () => {
const result: DesktopUpdateActionResult = {
accepted: true,
completed: true,
state: {
...baseState,
status: "downloaded",
downloadedVersion: "1.1.0",
availableVersion: "1.1.0",
message: null,
errorContext: null,
canRetry: true,
},
};
expect(getDesktopUpdateActionError(result)).toBeNull();
});
});
describe("desktop update UI helpers", () => {
it("toasts only for accepted incomplete actions", () => {
expect(
shouldToastDesktopUpdateActionResult({
accepted: true,
completed: false,
state: baseState,
}),
).toBe(true);
expect(
shouldToastDesktopUpdateActionResult({
accepted: true,
completed: true,
state: baseState,
}),
).toBe(false);
});
it("highlights only actionable updater errors", () => {
expect(
shouldHighlightDesktopUpdateError({
...baseState,
status: "error",
errorContext: "download",
canRetry: true,
}),
).toBe(true);
expect(
shouldHighlightDesktopUpdateError({
...baseState,
status: "error",
errorContext: "check",
canRetry: true,
}),
).toBe(false);
});
});
@@ -0,0 +1,77 @@
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
export type DesktopUpdateButtonAction = "download" | "install" | "none";
export function resolveDesktopUpdateButtonAction(
state: DesktopUpdateState,
): DesktopUpdateButtonAction {
if (state.status === "available") {
return "download";
}
if (state.status === "downloaded") {
return "install";
}
if (state.status === "error") {
if (state.errorContext === "install" && state.downloadedVersion) {
return "install";
}
if (state.errorContext === "download" && state.availableVersion) {
return "download";
}
}
return "none";
}
export function shouldShowDesktopUpdateButton(state: DesktopUpdateState | null): boolean {
if (!state || !state.enabled) {
return false;
}
if (state.status === "downloading") {
return true;
}
return resolveDesktopUpdateButtonAction(state) !== "none";
}
export function isDesktopUpdateButtonDisabled(state: DesktopUpdateState | null): boolean {
return state?.status === "downloading";
}
export function getDesktopUpdateButtonTooltip(state: DesktopUpdateState): string {
if (state.status === "available") {
return `Update ${state.availableVersion ?? "available"} ready to download`;
}
if (state.status === "downloading") {
const progress =
typeof state.downloadPercent === "number" ? ` (${Math.floor(state.downloadPercent)}%)` : "";
return `Downloading update${progress}`;
}
if (state.status === "downloaded") {
return `Update ${state.downloadedVersion ?? state.availableVersion ?? "ready"} downloaded. Click to restart and install.`;
}
if (state.status === "error") {
if (state.errorContext === "download" && state.availableVersion) {
return `Download failed for ${state.availableVersion}. Click to retry.`;
}
if (state.errorContext === "install" && state.downloadedVersion) {
return `Install failed for ${state.downloadedVersion}. Click to retry.`;
}
return state.message ?? "Update failed";
}
return "Update available";
}
export function getDesktopUpdateActionError(result: DesktopUpdateActionResult): string | null {
if (!result.accepted || result.completed) return null;
if (typeof result.state.message !== "string") return null;
const message = result.state.message.trim();
return message.length > 0 ? message : null;
}
export function shouldToastDesktopUpdateActionResult(result: DesktopUpdateActionResult): boolean {
return result.accepted && !result.completed;
}
export function shouldHighlightDesktopUpdateError(state: DesktopUpdateState | null): boolean {
if (!state || state.status !== "error") return false;
return state.errorContext === "download" || state.errorContext === "install";
}
@@ -0,0 +1,107 @@
import { describe, expect, it } from "vitest";
import { estimateTimelineMessageHeight } from "./timelineHeight";
describe("estimateTimelineMessageHeight", () => {
it("uses assistant sizing rules for assistant messages", () => {
expect(
estimateTimelineMessageHeight({
role: "assistant",
text: "a".repeat(144),
}),
).toBe(122);
});
it("uses assistant sizing rules for system messages", () => {
expect(
estimateTimelineMessageHeight({
role: "system",
text: "a".repeat(144),
}),
).toBe(122);
});
it("adds one attachment row for one or two user attachments", () => {
expect(
estimateTimelineMessageHeight({
role: "user",
text: "hello",
attachments: [{ id: "1" }],
}),
).toBe(346);
expect(
estimateTimelineMessageHeight({
role: "user",
text: "hello",
attachments: [{ id: "1" }, { id: "2" }],
}),
).toBe(346);
});
it("adds a second attachment row for three or four user attachments", () => {
expect(
estimateTimelineMessageHeight({
role: "user",
text: "hello",
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }],
}),
).toBe(574);
expect(
estimateTimelineMessageHeight({
role: "user",
text: "hello",
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "4" }],
}),
).toBe(574);
});
it("does not cap long user message estimates", () => {
expect(
estimateTimelineMessageHeight({
role: "user",
text: "a".repeat(56 * 120),
}),
).toBe(2736);
});
it("counts explicit newlines for user message estimates", () => {
expect(
estimateTimelineMessageHeight({
role: "user",
text: "first\nsecond\nthird",
}),
).toBe(162);
});
it("uses narrower width to increase user line wrapping", () => {
const message = {
role: "user" as const,
text: "a".repeat(52),
};
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(140);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(118);
});
it("does not clamp user wrapping too aggressively on very narrow layouts", () => {
const message = {
role: "user" as const,
text: "a".repeat(20),
};
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 100 })).toBe(184);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(118);
});
it("uses narrower width to increase assistant line wrapping", () => {
const message = {
role: "assistant" as const,
text: "a".repeat(200),
};
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(188);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(122);
});
});
+90
View File
@@ -0,0 +1,90 @@
const ASSISTANT_CHARS_PER_LINE_FALLBACK = 72;
const USER_CHARS_PER_LINE_FALLBACK = 56;
const LINE_HEIGHT_PX = 22;
const ASSISTANT_BASE_HEIGHT_PX = 78;
const USER_BASE_HEIGHT_PX = 96;
const ATTACHMENTS_PER_ROW = 2;
// Attachment thumbnails render with `max-h-[220px]` plus ~8px row gap.
const USER_ATTACHMENT_ROW_HEIGHT_PX = 228;
const USER_BUBBLE_WIDTH_RATIO = 0.8;
const USER_BUBBLE_HORIZONTAL_PADDING_PX = 32;
const ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX = 8;
const USER_MONO_AVG_CHAR_WIDTH_PX = 8.4;
const ASSISTANT_AVG_CHAR_WIDTH_PX = 7.2;
const MIN_USER_CHARS_PER_LINE = 4;
const MIN_ASSISTANT_CHARS_PER_LINE = 20;
interface TimelineMessageHeightInput {
role: "user" | "assistant" | "system";
text: string;
attachments?: ReadonlyArray<{ id: string }>;
}
interface TimelineHeightEstimateLayout {
timelineWidthPx: number | null;
}
function estimateWrappedLineCount(text: string, charsPerLine: number): number {
if (text.length === 0) return 1;
// Avoid allocating via split for long logs; iterate once and count wrapped lines.
let lines = 0;
let currentLineLength = 0;
for (let index = 0; index < text.length; index += 1) {
if (text.charCodeAt(index) === 10) {
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
currentLineLength = 0;
continue;
}
currentLineLength += 1;
}
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
return lines;
}
function isFinitePositiveNumber(value: number | null | undefined): value is number {
return typeof value === "number" && Number.isFinite(value) && value > 0;
}
function estimateCharsPerLineForUser(timelineWidthPx: number | null): number {
if (!isFinitePositiveNumber(timelineWidthPx)) return USER_CHARS_PER_LINE_FALLBACK;
const bubbleWidthPx = timelineWidthPx * USER_BUBBLE_WIDTH_RATIO;
const textWidthPx = Math.max(bubbleWidthPx - USER_BUBBLE_HORIZONTAL_PADDING_PX, 0);
return Math.max(MIN_USER_CHARS_PER_LINE, Math.floor(textWidthPx / USER_MONO_AVG_CHAR_WIDTH_PX));
}
function estimateCharsPerLineForAssistant(timelineWidthPx: number | null): number {
if (!isFinitePositiveNumber(timelineWidthPx)) return ASSISTANT_CHARS_PER_LINE_FALLBACK;
const textWidthPx = Math.max(timelineWidthPx - ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX, 0);
return Math.max(
MIN_ASSISTANT_CHARS_PER_LINE,
Math.floor(textWidthPx / ASSISTANT_AVG_CHAR_WIDTH_PX),
);
}
export function estimateTimelineMessageHeight(
message: TimelineMessageHeightInput,
layout: TimelineHeightEstimateLayout = { timelineWidthPx: null },
): number {
if (message.role === "assistant") {
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
}
if (message.role === "user") {
const charsPerLine = estimateCharsPerLineForUser(layout.timelineWidthPx);
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
const attachmentCount = message.attachments?.length ?? 0;
const attachmentRows = Math.ceil(attachmentCount / ATTACHMENTS_PER_ROW);
const attachmentHeight = attachmentRows * USER_ATTACHMENT_ROW_HEIGHT_PX;
return USER_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX + attachmentHeight;
}
// `system` messages are not rendered in the chat timeline, but keep a stable
// explicit branch in case they are present in timeline data.
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
}
+46 -1
View File
@@ -339,6 +339,7 @@ function SidebarRail({
const sidebarInstance = React.useContext(SidebarInstanceContext);
const railRef = React.useRef<HTMLButtonElement | null>(null);
const suppressClickRef = React.useRef(false);
const cleanupResizeListenersRef = React.useRef<(() => void) | null>(null);
const resizeStateRef = React.useRef<{
moved: boolean;
pointerId: number;
@@ -367,6 +368,8 @@ function SidebarRail({
if (resizeState.rafId !== null) {
window.cancelAnimationFrame(resizeState.rafId);
}
cleanupResizeListenersRef.current?.();
cleanupResizeListenersRef.current = null;
resizeState.transitionTargets.forEach((element) => {
element.style.removeProperty("transition-duration");
});
@@ -429,12 +432,46 @@ function SidebarRail({
width: initialWidth,
wrapper,
};
const stopResizeFromWindowEvent = (nativeEvent: PointerEvent) => {
const activeResizeState = resizeStateRef.current;
if (!activeResizeState || nativeEvent.pointerId !== activeResizeState.pointerId) {
return;
}
suppressClickRef.current = activeResizeState.moved;
stopResize(nativeEvent.pointerId);
};
const stopResizeFromVisibilityChange = () => {
const activeResizeState = resizeStateRef.current;
if (!activeResizeState || document.visibilityState === "visible") {
return;
}
suppressClickRef.current = activeResizeState.moved;
stopResize(activeResizeState.pointerId);
};
const stopResizeFromBlur = () => {
const activeResizeState = resizeStateRef.current;
if (!activeResizeState) {
return;
}
suppressClickRef.current = activeResizeState.moved;
stopResize(activeResizeState.pointerId);
};
window.addEventListener("pointerup", stopResizeFromWindowEvent, true);
window.addEventListener("pointercancel", stopResizeFromWindowEvent, true);
window.addEventListener("blur", stopResizeFromBlur);
document.addEventListener("visibilitychange", stopResizeFromVisibilityChange);
cleanupResizeListenersRef.current = () => {
window.removeEventListener("pointerup", stopResizeFromWindowEvent, true);
window.removeEventListener("pointercancel", stopResizeFromWindowEvent, true);
window.removeEventListener("blur", stopResizeFromBlur);
document.removeEventListener("visibilitychange", stopResizeFromVisibilityChange);
};
wrapper.style.setProperty("--sidebar-width", `${initialWidth}px`);
event.currentTarget.setPointerCapture(event.pointerId);
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
},
[onPointerDown, open, resolvedResizable, sidebarInstance?.side],
[onPointerDown, open, resolvedResizable, sidebarInstance?.side, stopResize],
);
const handlePointerMove = React.useCallback(
@@ -516,6 +553,13 @@ function SidebarRail({
[endResizeInteraction, onPointerCancel],
);
const handleLostPointerCapture = React.useCallback(() => {
const resizeState = resizeStateRef.current;
if (!resizeState) return;
suppressClickRef.current = resizeState.moved;
stopResize(resizeState.pointerId);
}, [stopResize]);
const handleClick = React.useCallback(
(event: React.MouseEvent<HTMLButtonElement>) => {
onClick?.(event);
@@ -579,6 +623,7 @@ function SidebarRail({
onClick={handleClick}
onPointerCancel={handlePointerCancel}
onPointerDown={handlePointerDown}
onLostPointerCapture={handleLostPointerCapture}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
ref={railRef}
+23 -11
View File
@@ -206,7 +206,10 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
"data-[position*=top]:after:top-full",
"data-[position*=bottom]:after:bottom-full",
// Define some variables
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Base UI exposes a shared front-most height for the collapsed stack.
// If that shared measurement is briefly stale, long content can render
// outside the card until hover expands the toast and swaps to its own height.
"[--toast-calc-height:max(var(--toast-frontmost-height,var(--toast-height)),var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Define offset-y variable
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
@@ -258,7 +261,7 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
)}
>
<div className="flex gap-2">
<div className="flex min-w-0 flex-1 gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
@@ -268,16 +271,22 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
</div>
)}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<Toast.Title
className="min-w-0 break-words font-medium"
data-slot="toast-title"
/>
<Toast.Description
className="text-muted-foreground"
className="min-w-0 break-words text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
{toast.actionProps && (
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action">
<Toast.Action
className={cn(buttonVariants({ size: "xs" }), "shrink-0")}
data-slot="toast-action"
>
{toast.actionProps.children}
</Toast.Action>
)}
@@ -341,7 +350,7 @@ function AnchoredToasts() {
</Toast.Content>
) : (
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm">
<div className="flex gap-2">
<div className="flex min-w-0 flex-1 gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
@@ -351,17 +360,20 @@ function AnchoredToasts() {
</div>
)}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<Toast.Title
className="min-w-0 break-words font-medium"
data-slot="toast-title"
/>
<Toast.Description
className="text-muted-foreground"
className="min-w-0 break-words text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
{toast.actionProps && (
<Toast.Action
className={buttonVariants({ size: "xs" })}
className={cn(buttonVariants({ size: "xs" }), "shrink-0")}
data-slot="toast-action"
>
{toast.actionProps.children}
+34
View File
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import {
detectComposerTrigger,
expandCollapsedComposerCursor,
isCollapsedCursorAdjacentToMention,
replaceTextRange,
} from "./composer-logic";
@@ -77,3 +78,36 @@ describe("expandCollapsedComposerCursor", () => {
expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
});
});
describe("isCollapsedCursorAdjacentToMention", () => {
it("returns false when no mention exists", () => {
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "left")).toBe(false);
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "right")).toBe(false);
});
it("keeps @query typing non-adjacent while no mention pill exists", () => {
const text = "hello @pac";
expect(isCollapsedCursorAdjacentToMention(text, text.length, "left")).toBe(false);
expect(isCollapsedCursorAdjacentToMention(text, text.length, "right")).toBe(false);
});
it("detects left adjacency only when cursor is directly after a mention", () => {
const text = "open @AGENTS.md next";
const mentionStart = "open ".length;
const mentionEnd = mentionStart + 1;
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "left")).toBe(true);
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "left")).toBe(false);
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd + 1, "left")).toBe(false);
});
it("detects right adjacency only when cursor is directly before a mention", () => {
const text = "open @AGENTS.md next";
const mentionStart = "open ".length;
const mentionEnd = mentionStart + 1;
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "right")).toBe(true);
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "right")).toBe(false);
expect(isCollapsedCursorAdjacentToMention(text, mentionStart - 1, "right")).toBe(false);
});
});
+46
View File
@@ -58,6 +58,52 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
return expandedCursor;
}
function collapsedSegmentLength(segment: { type: "text"; text: string } | { type: "mention" }): number {
return segment.type === "mention" ? 1 : segment.text.length;
}
function clampCollapsedComposerCursor(
segments: ReadonlyArray<{ type: "text"; text: string } | { type: "mention" }>,
cursorInput: number,
): number {
const collapsedLength = segments.reduce(
(total, segment) => total + collapsedSegmentLength(segment),
0,
);
if (!Number.isFinite(cursorInput)) {
return collapsedLength;
}
return Math.max(0, Math.min(collapsedLength, Math.floor(cursorInput)));
}
export function isCollapsedCursorAdjacentToMention(
text: string,
cursorInput: number,
direction: "left" | "right",
): boolean {
const segments = splitPromptIntoComposerSegments(text);
if (!segments.some((segment) => segment.type === "mention")) {
return false;
}
const cursor = clampCollapsedComposerCursor(segments, cursorInput);
let collapsedOffset = 0;
for (const segment of segments) {
if (segment.type === "mention") {
if (direction === "left" && cursor === collapsedOffset + 1) {
return true;
}
if (direction === "right" && cursor === collapsedOffset) {
return true;
}
}
collapsedOffset += collapsedSegmentLength(segment);
}
return false;
}
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
const cursor = clampCursor(text, cursorInput);
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
+3 -20
View File
@@ -16,8 +16,6 @@ export const gitQueryKeys = {
export const gitMutationKeys = {
init: (cwd: string | null) => ["git", "mutation", "init", cwd] as const,
checkout: (cwd: string | null) => ["git", "mutation", "checkout", cwd] as const,
createBranchAndCheckout: (cwd: string | null) =>
["git", "mutation", "create-branch-and-checkout", cwd] as const,
runStackedAction: (cwd: string | null) => ["git", "mutation", "run-stacked-action", cwd] as const,
pull: (cwd: string | null) => ["git", "mutation", "pull", cwd] as const,
};
@@ -89,24 +87,6 @@ export function gitCheckoutMutationOptions(input: {
});
}
export function gitCreateBranchAndCheckoutMutationOptions(input: {
cwd: string | null;
queryClient: QueryClient;
}) {
return mutationOptions({
mutationKey: gitMutationKeys.createBranchAndCheckout(input.cwd),
mutationFn: async (branch: string) => {
const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git branch creation is unavailable.");
await api.git.createBranch({ cwd: input.cwd, branch });
return api.git.checkout({ cwd: input.cwd, branch });
},
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
},
});
}
export function gitRunStackedActionMutationOptions(input: {
cwd: string | null;
queryClient: QueryClient;
@@ -116,9 +96,11 @@ export function gitRunStackedActionMutationOptions(input: {
mutationFn: async ({
action,
commitMessage,
featureBranch,
}: {
action: GitStackedAction;
commitMessage?: string;
featureBranch?: boolean;
}) => {
const api = ensureNativeApi();
if (!input.cwd) throw new Error("Git action is unavailable.");
@@ -126,6 +108,7 @@ export function gitRunStackedActionMutationOptions(input: {
cwd: input.cwd,
action,
...(commitMessage ? { commitMessage } : {}),
...(featureBranch ? { featureBranch } : {}),
});
},
onSettled: async () => {
+165
View File
@@ -0,0 +1,165 @@
import { describe, expect, it } from "vitest";
import { buildTurnDiffTree, summarizeTurnDiffStats } from "./turnDiffTree";
describe("summarizeTurnDiffStats", () => {
it("sums only files with numeric additions/deletions", () => {
const stat = summarizeTurnDiffStats([
{ path: "README.md", additions: 3, deletions: 1 },
{ path: "docs/notes.md" },
{ path: "src/index.ts", additions: 5, deletions: 2 },
]);
expect(stat).toEqual({ additions: 8, deletions: 3 });
});
});
describe("buildTurnDiffTree", () => {
it("builds nested directory nodes with aggregated stats", () => {
const tree = buildTurnDiffTree([
{ path: "src/index.ts", additions: 2, deletions: 1 },
{ path: "src/components/Button.tsx", additions: 4, deletions: 2 },
{ path: "README.md", additions: 1, deletions: 0 },
]);
expect(tree).toEqual([
{
kind: "directory",
name: "src",
path: "src",
stat: { additions: 6, deletions: 3 },
children: [
{
kind: "directory",
name: "components",
path: "src/components",
stat: { additions: 4, deletions: 2 },
children: [
{
kind: "file",
name: "Button.tsx",
path: "src/components/Button.tsx",
stat: { additions: 4, deletions: 2 },
},
],
},
{
kind: "file",
name: "index.ts",
path: "src/index.ts",
stat: { additions: 2, deletions: 1 },
},
],
},
{
kind: "file",
name: "README.md",
path: "README.md",
stat: { additions: 1, deletions: 0 },
},
]);
});
it("keeps files without stat values and excludes them from directory totals", () => {
const tree = buildTurnDiffTree([
{ path: "docs/notes.md" },
{ path: "docs/todo.md", additions: 1, deletions: 1 },
]);
expect(tree).toEqual([
{
kind: "directory",
name: "docs",
path: "docs",
stat: { additions: 1, deletions: 1 },
children: [
{
kind: "file",
name: "notes.md",
path: "docs/notes.md",
stat: null,
},
{
kind: "file",
name: "todo.md",
path: "docs/todo.md",
stat: { additions: 1, deletions: 1 },
},
],
},
]);
});
it("normalizes file paths with windows separators", () => {
const tree = buildTurnDiffTree([{ path: "apps\\web\\src\\index.ts", additions: 2, deletions: 1 }]);
expect(tree).toEqual([
{
kind: "directory",
name: "apps/web/src",
path: "apps/web/src",
stat: { additions: 2, deletions: 1 },
children: [
{
kind: "file",
name: "index.ts",
path: "apps/web/src/index.ts",
stat: { additions: 2, deletions: 1 },
},
],
},
]);
});
it("compacts only single-directory chains and stops at branch points", () => {
const tree = buildTurnDiffTree([
{ path: "apps/server/src/index.ts", additions: 2, deletions: 1 },
{ path: "apps/server/main.ts", additions: 4, deletions: 0 },
]);
expect(tree).toEqual([
{
kind: "directory",
name: "apps/server",
path: "apps/server",
stat: { additions: 6, deletions: 1 },
children: [
{
kind: "directory",
name: "src",
path: "apps/server/src",
stat: { additions: 2, deletions: 1 },
children: [
{
kind: "file",
name: "index.ts",
path: "apps/server/src/index.ts",
stat: { additions: 2, deletions: 1 },
},
],
},
{
kind: "file",
name: "main.ts",
path: "apps/server/main.ts",
stat: { additions: 4, deletions: 0 },
},
],
},
]);
});
it("preserves leading/trailing whitespace in path segments", () => {
const tree = buildTurnDiffTree([
{ path: "a/file.ts", additions: 1, deletions: 0 },
{ path: " a/file.ts", additions: 2, deletions: 0 },
]);
expect(tree).toHaveLength(2);
const directoryNodes = tree.filter(
(node): node is Extract<(typeof tree)[number], { kind: "directory" }> => node.kind === "directory",
);
expect(directoryNodes.map((node) => node.name).toSorted()).toEqual([" a", "a"]);
expect(directoryNodes.map((node) => node.path).toSorted()).toEqual([" a", "a"]);
});
});
+172
View File
@@ -0,0 +1,172 @@
import type { TurnDiffFileChange } from "../types";
export interface TurnDiffStat {
additions: number;
deletions: number;
}
export interface TurnDiffTreeDirectoryNode {
kind: "directory";
name: string;
path: string;
stat: TurnDiffStat;
children: TurnDiffTreeNode[];
}
export interface TurnDiffTreeFileNode {
kind: "file";
name: string;
path: string;
stat: TurnDiffStat | null;
}
export type TurnDiffTreeNode = TurnDiffTreeDirectoryNode | TurnDiffTreeFileNode;
interface MutableDirectoryNode {
name: string;
path: string;
stat: TurnDiffStat;
directories: Map<string, MutableDirectoryNode>;
files: TurnDiffTreeFileNode[];
}
const SORT_LOCALE_OPTIONS: Intl.CollatorOptions = { numeric: true, sensitivity: "base" };
function normalizePathSegments(pathValue: string): string[] {
return pathValue
.replaceAll("\\", "/")
.split("/")
.filter((segment) => segment.length > 0);
}
function compareByName(a: { name: string }, b: { name: string }): number {
return a.name.localeCompare(b.name, undefined, SORT_LOCALE_OPTIONS);
}
function readStat(file: TurnDiffFileChange): TurnDiffStat | null {
if (typeof file.additions !== "number" || typeof file.deletions !== "number") {
return null;
}
return {
additions: file.additions,
deletions: file.deletions,
};
}
function compactDirectoryNode(node: TurnDiffTreeDirectoryNode): TurnDiffTreeDirectoryNode {
const compactedChildren = node.children.map((child) =>
child.kind === "directory" ? compactDirectoryNode(child) : child,
);
let compactedNode: TurnDiffTreeDirectoryNode = {
...node,
children: compactedChildren,
};
while (compactedNode.children.length === 1 && compactedNode.children[0]?.kind === "directory") {
const onlyChild = compactedNode.children[0];
compactedNode = {
kind: "directory",
name: `${compactedNode.name}/${onlyChild.name}`,
path: onlyChild.path,
stat: onlyChild.stat,
children: onlyChild.children,
};
}
return compactedNode;
}
function toTreeNodes(directory: MutableDirectoryNode): TurnDiffTreeNode[] {
const subdirectories: TurnDiffTreeDirectoryNode[] = Array.from(directory.directories.values())
.toSorted(compareByName)
.map<TurnDiffTreeDirectoryNode>((subdirectory) => ({
kind: "directory",
name: subdirectory.name,
path: subdirectory.path,
stat: {
additions: subdirectory.stat.additions,
deletions: subdirectory.stat.deletions,
},
children: toTreeNodes(subdirectory),
}))
.map((subdirectory) => compactDirectoryNode(subdirectory));
const files = directory.files.toSorted(compareByName);
return [...subdirectories, ...files];
}
export function summarizeTurnDiffStats(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffStat {
return files.reduce(
(acc, file) => {
const stat = readStat(file);
if (!stat) return acc;
return {
additions: acc.additions + stat.additions,
deletions: acc.deletions + stat.deletions,
};
},
{ additions: 0, deletions: 0 },
);
}
export function buildTurnDiffTree(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffTreeNode[] {
const root: MutableDirectoryNode = {
name: "",
path: "",
stat: { additions: 0, deletions: 0 },
directories: new Map(),
files: [],
};
for (const file of files) {
const segments = normalizePathSegments(file.path);
if (segments.length === 0) {
continue;
}
const filePath = segments.join("/");
const fileName = segments.at(-1);
if (!fileName) {
continue;
}
const stat = readStat(file);
const ancestors: MutableDirectoryNode[] = [root];
let currentDirectory = root;
for (const segment of segments.slice(0, -1)) {
const nextPath = currentDirectory.path ? `${currentDirectory.path}/${segment}` : segment;
const existing = currentDirectory.directories.get(segment);
if (existing) {
currentDirectory = existing;
} else {
const created: MutableDirectoryNode = {
name: segment,
path: nextPath,
stat: { additions: 0, deletions: 0 },
directories: new Map(),
files: [],
};
currentDirectory.directories.set(segment, created);
currentDirectory = created;
}
ancestors.push(currentDirectory);
}
currentDirectory.files.push({
kind: "file",
name: fileName,
path: filePath,
stat,
});
if (stat) {
for (const ancestor of ancestors) {
ancestor.stat.additions += stat.additions;
ancestor.stat.deletions += stat.deletions;
}
}
}
return toTreeNodes(root);
}
+5 -25
View File
@@ -1,41 +1,21 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider } from "@tanstack/react-router";
import { createHashHistory, createRouter, createBrowserHistory } from "@tanstack/react-router";
import { StoreProvider } from "./store";
import { createHashHistory, createBrowserHistory } from "@tanstack/react-router";
import "@xterm/xterm/css/xterm.css";
import "./index.css";
import { APP_DISPLAY_NAME } from "./branding";
import { isElectron } from "./env";
import { routeTree } from "./routeTree.gen";
import { getRouter } from "./router";
import { APP_DISPLAY_NAME } from "./branding";
const history = isElectron ? createHashHistory() : createBrowserHistory();
const queryClient = new QueryClient();
const router = getRouter(history);
document.title = APP_DISPLAY_NAME;
const router = createRouter({
routeTree,
history,
context: {
queryClient,
},
Wrap: ({ children }) => (
<QueryClientProvider client={queryClient}>
<StoreProvider>{children}</StoreProvider>
</QueryClientProvider>
),
});
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<RouterProvider router={router} />
+34
View File
@@ -0,0 +1,34 @@
import { createElement } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRouter } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
import { StoreProvider } from "./store";
type RouterHistory = NonNullable<Parameters<typeof createRouter>[0]["history"]>;
export function getRouter(history: RouterHistory) {
const queryClient = new QueryClient();
return createRouter({
routeTree,
history,
context: {
queryClient,
},
Wrap: ({ children }) =>
createElement(
QueryClientProvider,
{ client: queryClient },
createElement(StoreProvider, null, children),
),
});
}
export type AppRouter = ReturnType<typeof getRouter>;
declare module "@tanstack/react-router" {
interface Register {
router: AppRouter;
}
}
+18 -9
View File
@@ -26,6 +26,9 @@ export const Route = createRootRouteWithContext<{
}>()({
component: RootRouteView,
errorComponent: RootRouteErrorView,
head: () => ({
meta: [{ name: "title", content: APP_DISPLAY_NAME }],
}),
});
function RootRouteView() {
@@ -152,9 +155,7 @@ function EventRouter() {
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
syncServerReadModel(snapshot);
const activeThreadIds = new Set(
snapshot.threads
.filter((t) => t.deletedAt === null)
.map((t) => t.id),
snapshot.threads.filter((t) => t.deletedAt === null).map((t) => t.id),
);
removeOrphanedTerminalStates(activeThreadIds);
if (pending) {
@@ -195,11 +196,13 @@ function EventRouter() {
if (hasRunningSubprocess === null) {
return;
}
useTerminalStateStore.getState().setTerminalActivity(
ThreadId.makeUnsafe(event.threadId),
event.terminalId,
hasRunningSubprocess,
);
useTerminalStateStore
.getState()
.setTerminalActivity(
ThreadId.makeUnsafe(event.threadId),
event.terminalId,
hasRunningSubprocess,
);
});
const unsubWelcome = onServerWelcome((payload) => {
void (async () => {
@@ -276,7 +279,13 @@ function EventRouter() {
unsubWelcome();
unsubServerConfigUpdated();
};
}, [navigate, queryClient, removeOrphanedTerminalStates, setProjectExpanded, syncServerReadModel]);
}, [
navigate,
queryClient,
removeOrphanedTerminalStates,
setProjectExpanded,
syncServerReadModel,
]);
return null;
}
+11 -1
View File
@@ -3,7 +3,11 @@ import { useEffect } from "react";
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
import ThreadSidebar from "../components/Sidebar";
import { Sidebar, SidebarProvider } from "~/components/ui/sidebar";
import { Sidebar, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
const THREAD_SIDEBAR_MIN_WIDTH = 16 * 16;
const THREAD_SIDEBAR_MAX_WIDTH = 40 * 16;
function ChatRouteLayout() {
const navigate = useNavigate();
@@ -30,8 +34,14 @@ function ChatRouteLayout() {
side="left"
collapsible="offcanvas"
className="border-r border-border bg-card text-foreground"
resizable={{
maxWidth: THREAD_SIDEBAR_MAX_WIDTH,
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
}}
>
<ThreadSidebar />
<SidebarRail />
</Sidebar>
<DiffWorkerPoolProvider>
<Outlet />
+1 -1
View File
@@ -1,4 +1,4 @@
export function truncateTitle(text: string, maxLength = 50): string {
export function truncateTitle(text: string, maxLength = 300): string {
const trimmed = text.trim();
if (trimmed.length <= maxLength) {
return trimmed;
+15 -1
View File
@@ -6,6 +6,7 @@ import {
ProjectId,
ThreadId,
WS_CHANNELS,
type ServerProviderStatus,
} from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -62,6 +63,16 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn
return testGlobal.window;
}
const defaultProviders: ReadonlyArray<ServerProviderStatus> = [
{
provider: "codex",
status: "ready",
available: true,
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
},
];
beforeEach(() => {
vi.resetModules();
requestMock.mockReset();
@@ -162,6 +173,7 @@ describe("wsNativeApi", () => {
message: "Entry at index 1 is invalid.",
},
],
providers: defaultProviders,
} as const;
emitPush(WS_CHANNELS.serverConfigUpdated, payload);
@@ -185,14 +197,17 @@ describe("wsNativeApi", () => {
emitPush(WS_CHANNELS.serverConfigUpdated, {
issues: [{ kind: "keybindings.invalid-entry", message: "missing index" }],
providers: defaultProviders,
});
emitPush(WS_CHANNELS.serverConfigUpdated, {
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
providers: defaultProviders,
});
expect(listener).toHaveBeenCalledTimes(1);
expect(listener).toHaveBeenCalledWith({
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
providers: defaultProviders,
});
expect(warnSpy).toHaveBeenCalledTimes(1);
});
@@ -376,5 +391,4 @@ describe("wsNativeApi", () => {
{ x: 20, y: 30 },
);
});
});
+29
View File
@@ -0,0 +1,29 @@
import { fileURLToPath } from "node:url";
import { playwright } from "@vitest/browser-playwright";
import { defineConfig, mergeConfig } from "vitest/config";
import viteConfig from "./vite.config";
const srcPath = fileURLToPath(new URL("./src", import.meta.url));
export default mergeConfig(
viteConfig,
defineConfig({
resolve: {
alias: {
"~": srcPath,
},
},
test: {
include: ["src/components/ChatView.browser.tsx"],
browser: {
enabled: true,
provider: playwright(),
instances: [{ browser: "chromium" }],
headless: true,
},
testTimeout: 30_000,
hookTimeout: 30_000,
},
}),
);
+130 -54
View File
@@ -5,35 +5,34 @@
"": {
"name": "@t3tools/monorepo",
"devDependencies": {
"@effect/platform-node": "catalog:",
"@types/node": "^24.10.13",
"effect": "catalog:",
"@types/node": "catalog:",
"oxfmt": "^0.35.0",
"oxlint": "^1.50.0",
"turbo": "^2.3.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
"vitest": "catalog:",
},
},
"apps/desktop": {
"name": "@t3tools/desktop",
"version": "0.0.0-alpha.4",
"version": "0.0.0-alpha.20",
"dependencies": {
"effect": "catalog:",
"electron": "40.6.0",
"electron-updater": "^6.6.2",
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@types/node": "^24.10.13",
"electronmon": "^2.0.2",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
"@t3tools/shared": "workspace:*",
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
"wait-on": "^8.0.2",
},
},
"apps/server": {
"name": "t3",
"version": "0.0.0-alpha.4",
"version": "0.0.0-alpha.20",
"bin": {
"t3": "./dist/index.mjs",
},
@@ -47,26 +46,28 @@
"ws": "^8.18.0",
},
"devDependencies": {
"@effect/language-service": "0.75.1",
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
},
},
"apps/web": {
"name": "@t3tools/web",
"version": "0.0.0-alpha.4",
"version": "0.0.0-alpha.20",
"dependencies": {
"@base-ui/react": "^1.2.0",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-query": "^5.90.0",
"@tanstack/react-router": "^1.160.2",
@@ -91,23 +92,59 @@
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^5.1.4",
"@vitest/browser-playwright": "^4.0.18",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"msw": "^2.12.10",
"playwright": "^1.58.2",
"tailwindcss": "^4.0.0",
"typescript": "^5.7.3",
"typescript": "catalog:",
"vite": "^8.0.0-beta.12",
"vitest": "catalog:",
"vitest-browser-react": "^2.0.5",
},
},
"packages/contracts": {
"name": "@t3tools/contracts",
"version": "0.0.0-alpha.4",
"version": "0.0.0-alpha.20",
"dependencies": {
"effect": "catalog:",
},
"devDependencies": {
"@effect/language-service": "0.75.1",
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
},
},
"packages/shared": {
"name": "@t3tools/shared",
"version": "0.0.0-alpha.1",
"dependencies": {
"effect": "catalog:",
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
},
},
"scripts": {
"name": "@t3tools/scripts",
"dependencies": {
"@effect/platform-node": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"effect": "catalog:",
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@types/bun": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
},
},
},
@@ -116,7 +153,12 @@
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b",
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b",
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
},
"packages": {
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
@@ -429,6 +471,8 @@
"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-McjTuEPuacSIcXdoI2O9W6VSHIOs9ApEHnEUwONKZnKqIo2GGv1vNg9Pr8tgBOL7lgBWNEHX5ROJ5z1X74sENQ=="],
"@polka/url": ["@polka/[email protected]", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="],
"@preact/signals-core": ["@preact/[email protected]", "", {}, "sha512-slT6XeTCAbdql61GVLlGU4x7XHI7kCZV5Um5uhE4zLX4ApgiiXc0UYFvVOKq06xcovzp7p+61l68oPi563ARKg=="],
"@quansync/fs": ["@quansync/[email protected]", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
@@ -537,6 +581,10 @@
"@t3tools/desktop": ["@t3tools/desktop@workspace:apps/desktop"],
"@t3tools/scripts": ["@t3tools/scripts@workspace:scripts"],
"@t3tools/shared": ["@t3tools/shared@workspace:packages/shared"],
"@t3tools/web": ["@t3tools/web@workspace:apps/web"],
"@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "enhanced-resolve": "^5.18.3", "jiti": "^2.6.1", "lightningcss": "1.30.2", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.1.18" } }, "sha512-DoR7U1P7iYhw16qJ49fgXUlry1t4CpXeErJHnQ44JgTSKMaZUdf17cfn5mHchfJ4KRBZRFA/Coo+MUF5+gOaCQ=="],
@@ -657,6 +705,10 @@
"@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-VIcFLdRi/VYRU8OL/puL7QXMYafHmqOnwTZY50U1JPlCNj30PxCMx65c494b1K9be9hX83KVt0+gTEwTWLqToA=="],
"@vitest/browser": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/mocker": "4.0.18", "@vitest/utils": "4.0.18", "magic-string": "^0.30.21", "pixelmatch": "7.1.0", "pngjs": "^7.0.0", "sirv": "^3.0.2", "tinyrainbow": "^3.0.3", "ws": "^8.18.3" }, "peerDependencies": { "vitest": "4.0.18" } }, "sha512-gVQqh7paBz3gC+ZdcCmNSWJMk70IUjDeVqi+5m5vYpEHsIwRgw3Y545jljtajhkekIpIp5Gg8oK7bctgY0E2Ng=="],
"@vitest/browser-playwright": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/browser": "4.0.18", "@vitest/mocker": "4.0.18", "tinyrainbow": "^3.0.3" }, "peerDependencies": { "playwright": "*", "vitest": "4.0.18" } }, "sha512-gfajTHVCiwpxRj1qh0Sh/5bbGLG4F/ZH/V9xvFVoFddpITfMta9YGow0W6ZpTTORv2vdJuz9TnrNSmjKvpOf4g=="],
"@vitest/expect": ["@vitest/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.0.18", "@vitest/utils": "4.0.18", "chai": "^6.2.1", "tinyrainbow": "^3.0.3" } }, "sha512-8sCWUyckXXYvx4opfzVY03EOiYVxyNrHS5QxX3DAIi5dpJAAkyJezHCP77VMX4HKA2LDT/Jpfo8i2r5BE3GnQQ=="],
"@vitest/mocker": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/spy": "4.0.18", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0-0" }, "optionalPeers": ["msw", "vite"] }, "sha512-HhVd0MDnzzsgevnOWCBj5Otnzobjy5wLBe4EdeeFGv8luMsGcYqDuFRMcttKWZA5vVO8RFjexVovXvAM4JoJDQ=="],
@@ -685,6 +737,8 @@
"anymatch": ["[email protected]", "", { "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw=="],
"argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
"assertion-error": ["[email protected]", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],
"ast-kit": ["[email protected]", "", { "dependencies": { "@babel/parser": "^8.0.0-beta.4", "estree-walker": "^3.0.3", "pathe": "^2.0.3" } }, "sha512-trmleAnZ2PxN/loHWVhhx1qeOHSRXq4TDsBBxq3GqeJitfk3+jTQ+v/C1km/KYq9M7wKqCewMh+/NAvVH7m+bw=="],
@@ -715,6 +769,8 @@
"buffer-crc32": ["[email protected]", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"builder-util-runtime": ["[email protected]", "", { "dependencies": { "debug": "^4.3.4", "sax": "^1.2.4" } }, "sha512-qt41tMfgHTllhResqM5DcnHyDIWNgzHvuY2jDcYP9iaGpkWxTUzV6GQjDeLnlR1/DtdlcsWQbA7sByMpmJFTLQ=="],
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg=="],
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
@@ -733,8 +789,6 @@
"chai": ["[email protected]", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="],
"chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg=="],
"character-entities": ["[email protected]", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="],
"character-entities-html4": ["[email protected]", "", {}, "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA=="],
@@ -817,7 +871,7 @@
"electron-to-chromium": ["[email protected]", "", {}, "sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A=="],
"electronmon": ["electron[email protected]", "", { "dependencies": { "chalk": "^3.0.0", "import-from": "^3.0.0", "runtime-required": "^1.1.0", "watchboy": "^0.4.3" }, "bin": { "electronmon": "bin/cli.js" } }, "sha512-u6eDrvUbqa+wsnMrhG2vHmo5neL1owLg2e5i1avGWcOb4rHsUf9lSfbs0FvfPsBNpLxxlPO98nrMhAGV+zw/fQ=="],
"electron-updater": ["electron[email protected]", "", { "dependencies": { "builder-util-runtime": "9.5.1", "fs-extra": "^10.1.0", "js-yaml": "^4.1.0", "lazy-val": "^1.0.5", "lodash.escaperegexp": "^4.1.2", "lodash.isequal": "^4.5.0", "semver": "~7.7.3", "tiny-typed-emitter": "^2.1.0" } }, "sha512-Z6sgw3jgbikWKXei1ENdqFOxBP0WlXg3TtKfz0rgw2vIZFJUyI4pD7ZN7jrkm7EoMK+tcm/qTnPUdqfZukBlBQ=="],
"emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
@@ -873,9 +927,9 @@
"form-data": ["[email protected]", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
"fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
"fs-extra": ["fs-extra@10.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="],
"fsevents": ["[email protected].3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"fsevents": ["[email protected].2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
"function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
@@ -905,8 +959,6 @@
"graphql": ["[email protected]", "", {}, "sha512-DKKrynuQRne0PNpEbzuEdHlYOMksHSUI8Zc9Unei5gTsMNA2/vMpoMz/yKba50pejK56qj98qM0SjYxAKi13gQ=="],
"has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
"has-property-descriptors": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="],
"has-symbols": ["[email protected]", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
@@ -933,8 +985,6 @@
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
"import-from": ["[email protected]", "", { "dependencies": { "resolve-from": "^5.0.0" } }, "sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ=="],
"import-without-cache": ["[email protected]", "", {}, "sha512-B6Lc2s6yApwnD2/pMzFh/d5AVjdsDXjgkeJ766FmFuJELIGHNycKRj+l3A39yZPM4CchqNCB4RITEAYB1KUM6A=="],
"ini": ["[email protected]", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="],
@@ -981,6 +1031,8 @@
"js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
"js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],
"jsesc": ["[email protected]", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
"json-buffer": ["[email protected]", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
@@ -989,12 +1041,14 @@
"json5": ["[email protected]", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
"jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
"jsonfile": ["jsonfile@6.2.0", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg=="],
"keyv": ["[email protected]", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],
"kubernetes-types": ["[email protected]", "", {}, "sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q=="],
"lazy-val": ["[email protected]", "", {}, "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q=="],
"lexical": ["[email protected]", "", {}, "sha512-pNIm5+n+hVnJHB9gYPDYsIO5Y59dNaDU9rJmPPsfqQhP2ojKFnUoPbcRnrI9FJLXB14sSumcY8LUw7Sq70TZqA=="],
"lib0": ["[email protected]", "", { "dependencies": { "isomorphic.js": "^0.2.4" }, "bin": { "0serve": "bin/0serve.js", "0gentesthtml": "bin/gentesthtml.js", "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js" } }, "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw=="],
@@ -1027,10 +1081,12 @@
"lodash.defaults": ["[email protected]", "", {}, "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ=="],
"lodash.difference": ["[email protected]", "", {}, "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA=="],
"lodash.escaperegexp": ["[email protected]", "", {}, "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw=="],
"lodash.isarguments": ["[email protected]", "", {}, "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg=="],
"lodash.isequal": ["[email protected]", "", {}, "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ=="],
"longest-streak": ["[email protected]", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="],
"lowercase-keys": ["[email protected]", "", {}, "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA=="],
@@ -1135,8 +1191,6 @@
"micromark-util-types": ["[email protected]", "", {}, "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA=="],
"micromatch": ["[email protected]", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
"mime": ["[email protected]", "", { "bin": { "mime": "bin/cli.js" } }, "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw=="],
"mime-db": ["[email protected]", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],
@@ -1147,6 +1201,8 @@
"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
"mrmime": ["[email protected]", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="],
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"msgpackr": ["[email protected]", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-bC4UGzHhVvgDNS7kn9tV8fAucIYUBuGojcaLiz7v+P63Lmtm0Xeji8B/8tYKddALXxJLpwIeBmUN3u64C4YkRA=="],
@@ -1205,7 +1261,13 @@
"picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
"pify": ["[email protected]", "", {}, "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g=="],
"pixelmatch": ["[email protected]", "", { "dependencies": { "pngjs": "^7.0.0" }, "bin": { "pixelmatch": "bin/pixelmatch" } }, "sha512-1wrVzJ2STrpmONHKBy228LM1b84msXDUoAzVEl0R8Mz4Ce6EPr+IVtxm8+yvrqLYMHswREkjYFaMxnyGnaY3Ng=="],
"playwright": ["[email protected]", "", { "dependencies": { "playwright-core": "1.58.2" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A=="],
"playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg=="],
"pngjs": ["[email protected]", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="],
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
@@ -1259,16 +1321,12 @@
"remark-stringify": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-to-markdown": "^2.0.0", "unified": "^11.0.0" } }, "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw=="],
"remove-trailing-separator": ["[email protected]", "", {}, "sha512-/hS+Y0u3aOfIETiaiirUFwDBDzmXPvO+jAfKTitUngIPzdKc6Z0LoFjM/CK5PL4C+eKwHohlHAb6H0VFfmmUsw=="],
"require-directory": ["[email protected]", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
"reselect": ["[email protected]", "", {}, "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w=="],
"resolve-alpn": ["[email protected]", "", {}, "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g=="],
"resolve-from": ["[email protected]", "", {}, "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw=="],
"resolve-pkg-maps": ["[email protected]", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="],
"responselike": ["[email protected]", "", { "dependencies": { "lowercase-keys": "^2.0.0" } }, "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw=="],
@@ -1285,10 +1343,10 @@
"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
"runtime-required": ["[email protected]", "", {}, "sha512-yX97f5E0WfNpcQnfVjap6vzQcvErkYYCx6eTK4siqGEdC8lglwypUFgZVTX7ShvIlgfkC4XGFl9O1KTYcff0pw=="],
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
"sax": ["[email protected]", "", {}, "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA=="],
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
@@ -1307,6 +1365,8 @@
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
"sirv": ["[email protected]", "", { "dependencies": { "@polka/url": "^1.0.0-next.24", "mrmime": "^2.0.0", "totalist": "^3.0.0" } }, "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g=="],
"source-map": ["[email protected]", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
@@ -1337,8 +1397,6 @@
"sumchecker": ["[email protected]", "", { "dependencies": { "debug": "^4.1.0" } }, "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg=="],
"supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
"t3": ["t3@workspace:apps/server"],
"tabbable": ["[email protected]", "", {}, "sha512-05PUHKSNE8ou2dwIxTngl4EzcnsCDZGJ/iCLtDflR/SHB/ny14rXc+qU5P4mG9JkusiV7EivzY9Mhm55AzAvCg=="],
@@ -1353,6 +1411,8 @@
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
"tiny-typed-emitter": ["[email protected]", "", {}, "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA=="],
"tiny-warning": ["[email protected]", "", {}, "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA=="],
"tinybench": ["[email protected]", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="],
@@ -1373,6 +1433,8 @@
"toml": ["[email protected]", "", {}, "sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w=="],
"totalist": ["[email protected]", "", {}, "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ=="],
"tough-cookie": ["[email protected]", "", { "dependencies": { "tldts": "^7.0.5" } }, "sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w=="],
"tree-kill": ["[email protected]", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="],
@@ -1423,9 +1485,7 @@
"unist-util-visit-parents": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="],
"universalify": ["[email protected].2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
"unixify": ["[email protected]", "", { "dependencies": { "normalize-path": "^2.1.1" } }, "sha512-6bc58dPYhCMHHuwxldQxO3RRNZ4eCogZ/st++0+fcC1nr0jiGUtAdBJ2qzmLQWSxbtz42pWt4QQMiZ9HvZf5cg=="],
"universalify": ["universalify@2.0.1", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="],
"unplugin": ["[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "acorn": "^8.15.0", "picomatch": "^4.0.3", "webpack-virtual-modules": "^0.6.2" } }, "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww=="],
@@ -1447,9 +1507,9 @@
"vitest": ["[email protected]", "", { "dependencies": { "@vitest/expect": "4.0.18", "@vitest/mocker": "4.0.18", "@vitest/pretty-format": "4.0.18", "@vitest/runner": "4.0.18", "@vitest/snapshot": "4.0.18", "@vitest/spy": "4.0.18", "@vitest/utils": "4.0.18", "es-module-lexer": "^1.7.0", "expect-type": "^1.2.2", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^3.10.0", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.0.3", "vite": "^6.0.0 || ^7.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.0.18", "@vitest/browser-preview": "4.0.18", "@vitest/browser-webdriverio": "4.0.18", "@vitest/ui": "4.0.18", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ=="],
"wait-on": ["wait-on@8.0.5", "", { "dependencies": { "axios": "^1.12.1", "joi": "^18.0.1", "lodash": "^4.17.21", "minimist": "^1.2.8", "rxjs": "^7.8.2" }, "bin": { "wait-on": "bin/wait-on" } }, "sha512-J3WlS0txVHkhLRb2FsmRg3dkMTCV1+M6Xra3Ho7HzZDHpE7DCOnoSoCJsZotrmW3uRMhvIJGSKUKrh/MeF4iag=="],
"vitest-browser-react": ["vitest-browser-react@2.0.5", "", { "peerDependencies": { "@types/react": "^18.0.0 || ^19.0.0", "@types/react-dom": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "vitest": "^4.0.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-YODQX8mHTJCyKNVYTWJrLEYrUtw+QfLl78owgvuE7C5ydgmGBq6v5s4jK2w6wdPhIZsN9PpV1rQbmAevWJjO9g=="],
"watchboy": ["wa[email protected]", "", { "dependencies": { "lodash.difference": "^4.5.0", "micromatch": "^4.0.2", "pify": "^4.0.1", "unixify": "^1.0.0" } }, "sha512-GHs1HxwvxSMBsqd/WfTOZhj5gBdMqf5HQpfgtKxDfZRxrlYPDdVLRB61LCeRzJaWANmvSIMlfmRVDwVmJFgAKA=="],
"wait-on": ["wa[email protected]", "", { "dependencies": { "axios": "^1.12.1", "joi": "^18.0.1", "lodash": "^4.17.21", "minimist": "^1.2.8", "rxjs": "^7.8.2" }, "bin": { "wait-on": "bin/wait-on" } }, "sha512-J3WlS0txVHkhLRb2FsmRg3dkMTCV1+M6Xra3Ho7HzZDHpE7DCOnoSoCJsZotrmW3uRMhvIJGSKUKrh/MeF4iag=="],
"webpack-virtual-modules": ["[email protected]", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="],
@@ -1509,6 +1569,8 @@
"@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
"@electron/get/fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
"@electron/get/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.30.2", "lightningcss-darwin-arm64": "1.30.2", "lightningcss-darwin-x64": "1.30.2", "lightningcss-freebsd-x64": "1.30.2", "lightningcss-linux-arm-gnueabihf": "1.30.2", "lightningcss-linux-arm64-gnu": "1.30.2", "lightningcss-linux-arm64-musl": "1.30.2", "lightningcss-linux-x64-gnu": "1.30.2", "lightningcss-linux-x64-musl": "1.30.2", "lightningcss-win32-arm64-msvc": "1.30.2", "lightningcss-win32-x64-msvc": "1.30.2" } }, "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ=="],
@@ -1551,14 +1613,14 @@
"babel-dead-code-elimination/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
"chokidar/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"cliui/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
"clone-response/mimic-response": ["[email protected]", "", {}, "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ=="],
"mdast-util-find-and-replace/escape-string-regexp": ["[email protected]", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
"micromatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
"parse-entities/@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
"readdirp/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
@@ -1567,9 +1629,13 @@
"rolldown-plugin-dts/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0-rc.1", "@babel/helper-validator-identifier": "^8.0.0-rc.1" } }, "sha512-ubmJ6TShyaD69VE9DQrlXcdkvJbmwWPB8qYj0H2kaJi29O7vJT9ajSdBd2W8CG34pwL9pYA74fi7RHC1qbLoVQ=="],
"rollup/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"serialize-error/type-fest": ["[email protected]", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
"unixify/normalize-path": ["[email protected]", "", { "dependencies": { "remove-trailing-separator": "^1.0.1" } }, "sha512-3pKJwH184Xo/lnH6oyP1q2pMd7HcypqqmRs91/6/i2CGtWwIKGCkOOMTm/zXbgTEWHw1uNpNi/igc3ePOYHb6w=="],
"tsx/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"vitest/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
@@ -1577,6 +1643,10 @@
"@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
"@electron/get/fs-extra/jsonfile": ["[email protected]", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
"@electron/get/fs-extra/universalify": ["[email protected]", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
"@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A=="],
"@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA=="],
@@ -1599,6 +1669,8 @@
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
"@tailwindcss/vite/vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"@types/cacheable-request/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"@types/keyv/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
@@ -1609,6 +1681,10 @@
"@types/yauzl/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"@vitejs/plugin-react/vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
"vitest/vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
}
}
+20
View File
@@ -12,9 +12,29 @@ This document covers how to run desktop releases from one tag, first without sig
- Linux `x64` AppImage
- Windows `x64` NSIS installer
- Publishes one GitHub Release with all produced files.
- Includes Electron auto-update metadata (for example `latest*.yml` and `*.blockmap`) in release assets.
- Publishes the CLI package (`apps/server`, npm package `t3`) with OIDC trusted publishing.
- Signing is optional and auto-detected per platform from secrets.
## Desktop auto-update notes
- Runtime updater: `electron-updater` in `apps/desktop/src/main.ts`.
- Update UX:
- Background checks run on startup delay + interval.
- No automatic download or install.
- The desktop UI shows a rocket update button when an update is available; click once to download, click again after download to restart/install.
- Provider: GitHub Releases (`provider: github`) configured at build time.
- Repository slug source:
- `T3CODE_DESKTOP_UPDATE_REPOSITORY` (format `owner/repo`), if set.
- otherwise `GITHUB_REPOSITORY` from GitHub Actions.
- Temporary private-repo auth workaround:
- set `T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN` (or `GH_TOKEN`) in the desktop app runtime environment.
- the app forwards it as an `Authorization: Bearer <token>` request header for updater HTTP calls.
- Required release assets for updater:
- platform installers (`.exe`, `.dmg`, `.AppImage`, plus macOS `.zip` for Squirrel.Mac update payloads)
- `latest*.yml` metadata
- `*.blockmap` files (used for differential downloads)
## 0) npm OIDC trusted publishing setup (CLI)
The workflow publishes the CLI with `bun publish` from `apps/server` after bumping
+21 -13
View File
@@ -4,22 +4,28 @@
"workspaces": {
"packages": [
"apps/*",
"packages/*"
"packages/*",
"scripts"
],
"catalog": {
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b",
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b",
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b",
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b",
"@effect/language-service": "0.75.1"
"@effect/language-service": "0.75.1",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0"
}
},
"type": "module",
"scripts": {
"dev": "bun run scripts/dev-runner.mjs dev",
"dev:server": "bun run scripts/dev-runner.mjs dev:server",
"dev:web": "bun run scripts/dev-runner.mjs dev:web",
"dev:desktop": "bun run scripts/dev-runner.mjs dev:desktop",
"dev": "node scripts/dev-runner.ts dev",
"dev:server": "node scripts/dev-runner.ts dev:server",
"dev:web": "node scripts/dev-runner.ts dev:web",
"dev:desktop": "node scripts/dev-runner.ts dev:desktop",
"start": "turbo run start --filter=t3",
"start:desktop": "turbo run start --filter=@t3tools/desktop",
"build": "turbo run build",
@@ -40,18 +46,20 @@
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
},
"devDependencies": {
"@effect/platform-node": "catalog:",
"@types/node": "^24.10.13",
"effect": "catalog:",
"@types/node": "catalog:",
"oxfmt": "^0.35.0",
"oxlint": "^1.50.0",
"turbo": "^2.3.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0"
"vitest": "catalog:"
},
"engines": {
"bun": "^1.3.9",
"node": "^24.13.1"
},
"packageManager": "[email protected]"
}
"packageManager": "[email protected]",
"msw": {
"workerDirectory": [
"apps/web/public"
]
}
}
+5 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.0-alpha.4",
"version": "0.0.0-alpha.20",
"private": true,
"files": [
"dist"
@@ -27,9 +27,10 @@
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "0.75.1",
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"tsdown": "^0.20.3",
"typescript": "^5.7.3"
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
+6
View File
@@ -13,6 +13,7 @@ export const GitPushStepStatus = Schema.Literals([
"skipped_not_requested",
"skipped_up_to_date",
]);
export const GitBranchStepStatus = Schema.Literals(["created", "skipped_not_requested"]);
export const GitPrStepStatus = Schema.Literals([
"created",
"opened_existing",
@@ -53,6 +54,7 @@ export const GitRunStackedActionInput = Schema.Struct({
cwd: TrimmedNonEmptyStringSchema,
action: GitStackedAction,
commitMessage: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(10_000))),
featureBranch: Schema.optional(Schema.Boolean),
});
export type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;
@@ -139,6 +141,10 @@ export type GitCreateWorktreeResult = typeof GitCreateWorktreeResult.Type;
export const GitRunStackedActionResult = Schema.Struct({
action: GitStackedAction,
branch: Schema.Struct({
status: GitBranchStepStatus,
name: Schema.optional(TrimmedNonEmptyStringSchema),
}),
commit: Schema.Struct({
status: GitCommitStepStatus,
commitSha: Schema.optional(TrimmedNonEmptyStringSchema),
+33
View File
@@ -43,6 +43,35 @@ export interface ContextMenuItem<T extends string = string> {
destructive?: boolean;
}
export type DesktopUpdateStatus =
| "disabled"
| "idle"
| "checking"
| "up-to-date"
| "available"
| "downloading"
| "downloaded"
| "error";
export interface DesktopUpdateState {
enabled: boolean;
status: DesktopUpdateStatus;
currentVersion: string;
availableVersion: string | null;
downloadedVersion: string | null;
downloadPercent: number | null;
checkedAt: string | null;
message: string | null;
errorContext: "check" | "download" | "install" | null;
canRetry: boolean;
}
export interface DesktopUpdateActionResult {
accepted: boolean;
completed: boolean;
state: DesktopUpdateState;
}
export interface DesktopBridge {
getWsUrl: () => string | null;
pickFolder: () => Promise<string | null>;
@@ -53,6 +82,10 @@ export interface DesktopBridge {
) => Promise<T | null>;
openExternal: (url: string) => Promise<boolean>;
onMenuAction: (listener: (action: string) => void) => () => void;
getUpdateState: () => Promise<DesktopUpdateState>;
downloadUpdate: () => Promise<DesktopUpdateActionResult>;
installUpdate: () => Promise<DesktopUpdateActionResult>;
onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;
}
export interface NativeApi {
+27 -1
View File
@@ -1,7 +1,8 @@
import { Schema } from "effect";
import { TrimmedNonEmptyString } from "./baseSchemas";
import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
import { EditorId } from "./editor";
import { ProviderKind } from "./orchestration";
export const KeybindingsMalformedConfigIssue = Schema.Struct({
kind: Schema.Literal("keybindings.malformed-config"),
@@ -25,11 +26,35 @@ export type ServerConfigIssue = typeof ServerConfigIssue.Type;
export const ServerConfigIssues = Schema.Array(ServerConfigIssue);
export type ServerConfigIssues = typeof ServerConfigIssues.Type;
export const ServerProviderStatusState = Schema.Literals(["ready", "warning", "error"]);
export type ServerProviderStatusState = typeof ServerProviderStatusState.Type;
export const ServerProviderAuthStatus = Schema.Literals([
"authenticated",
"unauthenticated",
"unknown",
]);
export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;
export const ServerProviderStatus = Schema.Struct({
provider: ProviderKind,
status: ServerProviderStatusState,
available: Schema.Boolean,
authStatus: ServerProviderAuthStatus,
checkedAt: IsoDateTime,
message: Schema.optional(TrimmedNonEmptyString),
});
export type ServerProviderStatus = typeof ServerProviderStatus.Type;
export const ServerProviderStatuses = Schema.Array(ServerProviderStatus);
export type ServerProviderStatuses = typeof ServerProviderStatuses.Type;
export const ServerConfig = Schema.Struct({
cwd: TrimmedNonEmptyString,
keybindingsConfigPath: TrimmedNonEmptyString,
keybindings: ResolvedKeybindingsConfig,
issues: ServerConfigIssues,
providers: ServerProviderStatuses,
availableEditors: Schema.Array(EditorId),
});
export type ServerConfig = typeof ServerConfig.Type;
@@ -45,5 +70,6 @@ export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.T
export const ServerConfigUpdatedPayload = Schema.Struct({
issues: ServerConfigIssues,
providers: ServerProviderStatuses,
});
export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
+35
View File
@@ -0,0 +1,35 @@
{
"name": "@t3tools/shared",
"version": "0.0.0-alpha.1",
"private": true,
"type": "module",
"exports": {
"./git": {
"types": "./src/git.ts",
"import": "./src/git.ts"
},
"./logging": {
"types": "./src/logging.ts",
"import": "./src/logging.ts"
},
"./Net": {
"types": "./src/Net.ts",
"import": "./src/Net.ts"
}
},
"scripts": {
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
+98
View File
@@ -0,0 +1,98 @@
import * as Net from "node:net";
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import { NetError, NetService } from "./Net";
const closeServer = (server: Net.Server) =>
Effect.sync(() => {
try {
server.close();
} catch {
// Ignore cleanup failures in tests.
}
});
const getPort = (server: Net.Server): number => {
const address = server.address();
return typeof address === "object" && address !== null ? address.port : 0;
};
const openServer = (host?: string): Effect.Effect<Net.Server, NetError> =>
Effect.callback<Net.Server, NetError>((resume) => {
const server = Net.createServer();
let settled = false;
const settle = (effect: Effect.Effect<Net.Server, NetError>) => {
if (settled) return;
settled = true;
resume(effect);
};
server.once("error", (cause) => {
settle(Effect.fail(new NetError({ message: "Failed to open test server", cause })));
});
if (host) {
server.listen(0, host, () => settle(Effect.succeed(server)));
} else {
server.listen(0, () => settle(Effect.succeed(server)));
}
return closeServer(server);
});
it.layer(NetService.layer)("NetService", (it) => {
describe("Net helpers", () => {
it.effect("reserveLoopbackPort returns a positive loopback port", () =>
Effect.gen(function* () {
const net = yield* NetService;
const port = yield* net.reserveLoopbackPort();
assert.ok(port > 0);
}),
);
it.effect("isPortAvailableOnLoopback reports false for an occupied port", () =>
Effect.acquireUseRelease(
openServer("127.0.0.1"),
(server) =>
Effect.gen(function* () {
const net = yield* NetService;
const port = getPort(server);
const available = yield* net.isPortAvailableOnLoopback(port);
assert.equal(available, false);
}),
closeServer,
),
);
it.effect("findAvailablePort returns preferred when it is free", () =>
Effect.gen(function* () {
const net = yield* NetService;
const preferred = yield* net.reserveLoopbackPort();
const resolved = yield* net.findAvailablePort(preferred);
assert.equal(resolved, preferred);
}),
);
it.effect("findAvailablePort falls back when preferred is occupied", () =>
Effect.acquireUseRelease(
openServer(),
(server) =>
Effect.gen(function* () {
const net = yield* NetService;
const preferred = getPort(server);
const resolved = yield* net.findAvailablePort(preferred);
assert.ok(resolved > 0);
assert.notEqual(resolved, preferred);
}),
closeServer,
),
);
});
});
+180
View File
@@ -0,0 +1,180 @@
import * as Net from "node:net";
import { Data, Effect, Layer, ServiceMap } from "effect";
export class NetError extends Data.TaggedError("NetError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
function isErrnoExceptionWithCode(cause: unknown): cause is {
readonly code: string;
} {
return (
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
typeof (cause as { readonly code: unknown }).code === "string"
);
}
const closeServer = (server: Net.Server) => {
try {
server.close();
} catch {
// Ignore close failures during cleanup.
}
};
const tryReservePort = (port: number): Effect.Effect<number, NetError> =>
Effect.callback<number, NetError>((resume) => {
const server = Net.createServer();
let settled = false;
const settle = (effect: Effect.Effect<number, NetError>) => {
if (settled) return;
settled = true;
resume(effect);
};
server.unref();
server.once("error", (cause) => {
settle(Effect.fail(new NetError({ message: "Could not find an available port.", cause })));
});
server.listen(port, () => {
const address = server.address();
const resolved = typeof address === "object" && address !== null ? address.port : 0;
server.close(() => {
if (resolved > 0) {
settle(Effect.succeed(resolved));
return;
}
settle(Effect.fail(new NetError({ message: "Could not find an available port." })));
});
});
return Effect.sync(() => {
closeServer(server);
});
});
export interface NetServiceShape {
/**
* Returns true when a TCP server can bind to {host, port}.
*/
readonly canListenOnHost: (port: number, host: string) => Effect.Effect<boolean>;
/**
* Checks loopback availability on both IPv4 and IPv6 localhost addresses.
*/
readonly isPortAvailableOnLoopback: (port: number) => Effect.Effect<boolean>;
/**
* Reserve an ephemeral loopback port and release it immediately.
*/
readonly reserveLoopbackPort: (host?: string) => Effect.Effect<number, NetError>;
/**
* Resolve an available listening port, preferring the provided port first.
*/
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
}
/**
* NetService - Service tag for startup networking helpers.
*/
export class NetService extends ServiceMap.Service<NetService, NetServiceShape>()(
"@t3tools/shared/Net/NetService",
) {
static readonly layer = Layer.sync(NetService, () => {
/**
* Returns true when a TCP server can bind to {host, port}.
* `EADDRNOTAVAIL` is treated as available so IPv6-absent hosts don't fail
* loopback availability checks.
*/
const canListenOnHost = (port: number, host: string): Effect.Effect<boolean> =>
Effect.callback<boolean>((resume) => {
const server = Net.createServer();
let settled = false;
const settle = (value: boolean) => {
if (settled) return;
settled = true;
resume(Effect.succeed(value));
};
server.unref();
server.once("error", (cause) => {
if (isErrnoExceptionWithCode(cause) && cause.code === "EADDRNOTAVAIL") {
settle(true);
return;
}
settle(false);
});
server.once("listening", () => {
server.close(() => {
settle(true);
});
});
server.listen({ host, port });
return Effect.sync(() => {
closeServer(server);
});
});
/**
* Reserve an ephemeral loopback port and release it immediately.
* Returns the reserved port number.
*/
const reserveLoopbackPort = (host = "127.0.0.1"): Effect.Effect<number, NetError> =>
Effect.callback<number, NetError>((resume) => {
const probe = Net.createServer();
let settled = false;
const settle = (effect: Effect.Effect<number, NetError>) => {
if (settled) return;
settled = true;
resume(effect);
};
probe.once("error", (cause) => {
settle(Effect.fail(new NetError({ message: "Failed to reserve loopback port", cause })));
});
probe.listen(0, host, () => {
const address = probe.address();
const port = typeof address === "object" && address !== null ? address.port : 0;
probe.close(() => {
if (port > 0) {
settle(Effect.succeed(port));
return;
}
settle(Effect.fail(new NetError({ message: "Failed to reserve loopback port" })));
});
});
return Effect.sync(() => {
closeServer(probe);
});
});
return {
canListenOnHost,
isPortAvailableOnLoopback: (port) =>
Effect.zipWith(
canListenOnHost(port, "127.0.0.1"),
canListenOnHost(port, "::1"),
(ipv4, ipv6) => ipv4 && ipv6,
),
reserveLoopbackPort,
findAvailablePort: (preferred) =>
Effect.catch(tryReservePort(preferred), () => tryReservePort(0)),
} satisfies NetServiceShape;
});
}
+61
View File
@@ -0,0 +1,61 @@
/**
* Sanitize an arbitrary string into a valid, lowercase git branch fragment.
* Strips quotes, collapses separators, limits to 64 chars.
*/
export function sanitizeBranchFragment(raw: string): string {
const normalized = raw
.trim()
.toLowerCase()
.replace(/['"`]/g, "")
.replace(/^[./\s_-]+|[./\s_-]+$/g, "");
const branchFragment = normalized
.replace(/[^a-z0-9/_-]+/g, "-")
.replace(/\/+/g, "/")
.replace(/-+/g, "-")
.replace(/^[./_-]+|[./_-]+$/g, "")
.slice(0, 64)
.replace(/[./_-]+$/g, "");
return branchFragment.length > 0 ? branchFragment : "update";
}
/**
* Sanitize a string into a `feature/…` branch name.
* Preserves an existing `feature/` prefix or slash-separated namespace.
*/
export function sanitizeFeatureBranchName(raw: string): string {
const sanitized = sanitizeBranchFragment(raw);
if (sanitized.includes("/")) {
return sanitized.startsWith("feature/") ? sanitized : `feature/${sanitized}`;
}
return `feature/${sanitized}`;
}
const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
/**
* Resolve a unique `feature/…` branch name that doesn't collide with
* any existing branch. Appends a numeric suffix when needed.
*/
export function resolveAutoFeatureBranchName(
existingBranchNames: readonly string[],
preferredBranch?: string,
): string {
const preferred = preferredBranch?.trim();
const resolvedBase = sanitizeFeatureBranchName(
preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
);
const existingNames = new Set(existingBranchNames.map((branch) => branch.toLowerCase()));
if (!existingNames.has(resolvedBase)) {
return resolvedBase;
}
let suffix = 2;
while (existingNames.has(`${resolvedBase}-${suffix}`)) {
suffix += 1;
}
return `${resolvedBase}-${suffix}`;
}
+115
View File
@@ -0,0 +1,115 @@
import fs from "node:fs";
import path from "node:path";
export interface RotatingFileSinkOptions {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly throwOnError?: boolean;
}
export class RotatingFileSink {
private readonly filePath: string;
private readonly maxBytes: number;
private readonly maxFiles: number;
private readonly throwOnError: boolean;
private currentSize = 0;
constructor(options: RotatingFileSinkOptions) {
if (options.maxBytes < 1) {
throw new Error(`maxBytes must be >= 1 (received ${options.maxBytes})`);
}
if (options.maxFiles < 1) {
throw new Error(`maxFiles must be >= 1 (received ${options.maxFiles})`);
}
this.filePath = options.filePath;
this.maxBytes = options.maxBytes;
this.maxFiles = options.maxFiles;
this.throwOnError = options.throwOnError ?? false;
fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
this.pruneOverflowBackups();
this.currentSize = this.readCurrentSize();
}
write(chunk: string | Buffer): void {
const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
if (buffer.length === 0) return;
try {
if (this.currentSize > 0 && this.currentSize + buffer.length > this.maxBytes) {
this.rotate();
}
fs.appendFileSync(this.filePath, buffer);
this.currentSize += buffer.length;
if (this.currentSize > this.maxBytes) {
this.rotate();
}
} catch {
this.currentSize = this.readCurrentSize();
if (this.throwOnError) {
throw new Error(`Failed to write log chunk to ${this.filePath}`);
}
}
}
private rotate(): void {
try {
const oldest = this.withSuffix(this.maxFiles);
if (fs.existsSync(oldest)) {
fs.rmSync(oldest, { force: true });
}
for (let index = this.maxFiles - 1; index >= 1; index -= 1) {
const source = this.withSuffix(index);
const target = this.withSuffix(index + 1);
if (fs.existsSync(source)) {
fs.renameSync(source, target);
}
}
if (fs.existsSync(this.filePath)) {
fs.renameSync(this.filePath, this.withSuffix(1));
}
this.currentSize = 0;
} catch {
this.currentSize = this.readCurrentSize();
if (this.throwOnError) {
throw new Error(`Failed to rotate log file ${this.filePath}`);
}
}
}
private pruneOverflowBackups(): void {
try {
const dir = path.dirname(this.filePath);
const baseName = path.basename(this.filePath);
for (const entry of fs.readdirSync(dir)) {
if (!entry.startsWith(`${baseName}.`)) continue;
const suffix = Number(entry.slice(baseName.length + 1));
if (!Number.isInteger(suffix) || suffix <= this.maxFiles) continue;
fs.rmSync(path.join(dir, entry), { force: true });
}
} catch {
if (this.throwOnError) {
throw new Error(`Failed to prune log backups for ${this.filePath}`);
}
}
}
private readCurrentSize(): number {
try {
return fs.statSync(this.filePath).size;
} catch {
return 0;
}
}
private withSuffix(index: number): string {
return `${this.filePath}.${index}`;
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src"]
}
+95 -53
View File
@@ -6,11 +6,13 @@ import rootPackageJson from "../package.json" with { type: "json" };
import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };
import serverPackageJson from "../apps/server/package.json" with { type: "json" };
import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Config, Data, Effect, FileSystem, Logger, Option, Path, Schema } from "effect";
import { Config, Data, Effect, FileSystem, Layer, Logger, Option, Path, Schema } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess } from "effect/unstable/process";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);
const BuildArch = Schema.Literals(["arm64", "x64", "universal"]);
@@ -21,6 +23,7 @@ const RepoRoot = Effect.service(Path.Path).pipe(
const IconSource = Effect.zipWith(RepoRoot, Effect.service(Path.Path), (repoRoot, path) =>
path.join(repoRoot, "assets/macos-icon-1024.png"),
);
const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
interface PlatformConfig {
readonly cliFlag: "--mac" | "--linux" | "--win";
@@ -134,14 +137,12 @@ const AzureTrustedSigningOptionsConfig = Config.all({
endpoint: Config.string("AZURE_TRUSTED_SIGNING_ENDPOINT"),
certificateProfileName: Config.string("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME"),
codeSigningAccountName: Config.string("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME"),
fileDigest: Config.string("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(
Config.withDefault(() => "SHA256"),
),
fileDigest: Config.string("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(Config.withDefault("SHA256")),
timestampDigest: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_DIGEST").pipe(
Config.withDefault(() => "SHA256"),
Config.withDefault("SHA256"),
),
timestampRfc3161: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_RFC3161").pipe(
Config.withDefault(() => "http://timestamp.acs.microsoft.com"),
Config.withDefault("http://timestamp.acs.microsoft.com"),
),
});
@@ -151,10 +152,10 @@ const BuildEnvConfig = Config.all({
arch: Config.schema(BuildArch, "T3CODE_DESKTOP_ARCH").pipe(Config.option),
version: Config.string("T3CODE_DESKTOP_VERSION").pipe(Config.option),
outputDir: Config.string("T3CODE_DESKTOP_OUTPUT_DIR").pipe(Config.option),
skipBuild: Config.boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(() => false)),
keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(() => false)),
signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(() => false)),
verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(() => false)),
skipBuild: Config.boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(false)),
keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(false)),
signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(false)),
verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(false)),
});
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
@@ -162,7 +163,7 @@ const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
Option.getOrElse(a, () => Option.getOrElse(b, () => defaultValue));
const resolveBuildOptions = Effect.fn(function* (input: BuildCliInput) {
const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (input: BuildCliInput) {
const path = yield* Path.Path;
const repoRoot = yield* RepoRoot;
const env = yield* BuildEnvConfig.asEffect();
@@ -208,12 +209,14 @@ const commandOutputOptions = (verbose: boolean) =>
stderr: "inherit",
}) as const;
const runCommand = Effect.fn(function* (command: ChildProcess.Command) {
const exitCode = yield* ChildProcess.exitCode(command);
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* commandSpawner.spawn(command);
const exitCode = yield* child.exitCode;
if (exitCode !== 0) {
return yield* new BuildScriptError({
message: "Command exited with non-zero exit code",
message: `Command exited with non-zero exit code (${exitCode})`,
});
}
});
@@ -288,9 +291,9 @@ function validateBundledClientAssets(clientDir: string) {
const path = yield* Path.Path;
const indexPath = path.join(clientDir, "index.html");
const indexHtml = yield* fs.readFileString(indexPath);
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map(
(match) => match[1],
);
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)]
.map((match) => match[1])
.filter((value): value is string => value !== undefined);
const missing: string[] = [];
for (const ref of refs) {
@@ -319,32 +322,47 @@ function validateBundledClientAssets(clientDir: string) {
});
}
function resolveCatalogDependencies(
dependencies: Record<string, unknown>,
function resolveDesktopRuntimeDependencies(
dependencies: Record<string, unknown> | undefined,
catalog: Record<string, unknown>,
dependencySourceLabel: string,
): Record<string, unknown> {
return Object.fromEntries(
Object.entries(dependencies).map(([dependencyName, spec]) => {
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
return [dependencyName, spec];
}
if (!dependencies || Object.keys(dependencies).length === 0) {
return {};
}
const catalogKey = spec.slice("catalog:".length).trim();
const lookupKey = catalogKey.length > 0 ? catalogKey : dependencyName;
const resolvedSpec = catalog[lookupKey];
if (typeof resolvedSpec !== "string" || resolvedSpec.length === 0) {
throw new BuildScriptError({
message: `Unable to resolve '${spec}' for ${dependencySourceLabel} dependency '${dependencyName}'. Expected key '${lookupKey}' in root workspace catalog.`,
});
}
return [dependencyName, resolvedSpec];
}),
const runtimeDependencies = Object.fromEntries(
Object.entries(dependencies).filter(([dependencyName]) => dependencyName !== "electron"),
);
return resolveCatalogDependencies(runtimeDependencies, catalog, "apps/desktop");
}
const createBuildConfig = Effect.fn(function* (
function resolveGitHubPublishConfig():
| {
readonly provider: "github";
readonly owner: string;
readonly repo: string;
readonly releaseType: "release";
}
| undefined {
const rawRepo =
process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||
process.env.GITHUB_REPOSITORY?.trim() ||
"";
if (!rawRepo) return undefined;
const [owner, repo, ...rest] = rawRepo.split("/");
if (!owner || !repo || rest.length > 0) return undefined;
return {
provider: "github",
owner,
repo,
releaseType: "release",
};
}
const createBuildConfig = Effect.fn("createBuildConfig")(function* (
platform: typeof BuildPlatform.Type,
target: string,
productName: string,
@@ -358,10 +376,14 @@ const createBuildConfig = Effect.fn(function* (
buildResources: "apps/desktop/resources",
},
};
const publishConfig = resolveGitHubPublishConfig();
if (publishConfig) {
buildConfig.publish = [publishConfig];
}
if (platform === "mac") {
buildConfig.mac = {
target: [target],
target: target === "dmg" ? [target, "zip"] : [target],
icon: "icon.icns",
category: "public.app-category.developer-tools",
};
@@ -389,7 +411,7 @@ const createBuildConfig = Effect.fn(function* (
return buildConfig;
});
const assertPlatformBuildResources = Effect.fn(function* (
const assertPlatformBuildResources = Effect.fn("assertPlatformBuildResources")(function* (
platform: typeof BuildPlatform.Type,
stageResourcesDir: string,
verbose: boolean,
@@ -422,7 +444,9 @@ const assertPlatformBuildResources = Effect.fn(function* (
}
});
const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions) {
const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
options: ResolvedBuildOptions,
) {
const repoRoot = yield* RepoRoot;
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
@@ -436,22 +460,38 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
const electronVersion = desktopPackageJson.dependencies.electron;
const dependencies = serverPackageJson.dependencies;
if (!dependencies || Object.keys(dependencies).length === 0) {
const serverDependencies = serverPackageJson.dependencies;
if (!serverDependencies || Object.keys(serverDependencies).length === 0) {
return yield* new BuildScriptError({
message: "Could not resolve production dependencies from apps/server/package.json.",
});
}
const resolvedDependencies = yield* Effect.try({
const resolvedServerDependencies = yield* Effect.try({
try: () =>
resolveCatalogDependencies(dependencies, rootPackageJson.workspaces.catalog, "apps/server"),
resolveCatalogDependencies(
serverDependencies,
rootPackageJson.workspaces.catalog,
"apps/server",
),
catch: (cause) =>
new BuildScriptError({
message: "Could not resolve production dependencies from apps/server/package.json.",
cause,
}),
});
const resolvedDesktopRuntimeDependencies = yield* Effect.try({
try: () =>
resolveDesktopRuntimeDependencies(
desktopPackageJson.dependencies,
rootPackageJson.workspaces.catalog,
),
catch: (cause) =>
new BuildScriptError({
message: "Could not resolve desktop runtime dependencies from apps/desktop/package.json.",
cause,
}),
});
const appVersion = options.version ?? serverPackageJson.version;
const commitHash = resolveGitCommitHash(repoRoot);
@@ -520,16 +560,17 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
desktopPackageJson.productName ?? "T3 Code",
options.signed,
),
dependencies: resolvedDependencies,
dependencies: {
...resolvedServerDependencies,
...resolvedDesktopRuntimeDependencies,
},
devDependencies: {
electron: electronVersion,
},
};
yield* fs.writeFileString(
path.join(stageAppDir, "package.json"),
`${JSON.stringify(stagePackageJson, null, 2)}\n`,
);
const stagePackageJsonString = yield* encodeJsonString(stagePackageJson);
yield* fs.writeFileString(path.join(stageAppDir, "package.json"), `${stagePackageJsonString}\n`);
yield* Effect.log("[desktop-artifact] Installing staged production dependencies...");
yield* runCommand(
@@ -564,7 +605,7 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
cwd: stageAppDir,
env: buildEnv,
...commandOutputOptions(options.verbose),
})`bunx electron-builder ${platformConfig.cliFlag} ${options.target} --${options.arch} --publish never`,
})`bunx electron-builder ${platformConfig.cliFlag} --${options.arch} --publish never`,
);
const stageDistDir = path.join(stageAppDir, "dist");
@@ -647,9 +688,10 @@ const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),
);
const cliRuntimeLayer = Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer);
Command.run(buildDesktopArtifactCli, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide(Logger.layer([Logger.consolePretty()])),
Effect.provide(NodeServices.layer),
Effect.provide(cliRuntimeLayer),
NodeRuntime.runMain,
);
-425
View File
@@ -1,425 +0,0 @@
import { spawn } from "node:child_process";
import net from "node:net";
import { homedir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
const MODE_ARGS = {
dev: [
"run",
"dev",
"--ui=tui",
"--filter=@t3tools/contracts",
"--filter=@t3tools/web",
"--filter=t3",
"--parallel",
],
"dev:server": ["run", "dev", "--filter=t3"],
"dev:web": ["run", "dev", "--filter=@t3tools/web"],
"dev:desktop": ["run", "dev", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "--parallel"],
};
const FORWARDED_ENV_FLAGS = {
"state-dir": { envName: "T3CODE_STATE_DIR", expectsValue: true },
"auth-token": { envName: "T3CODE_AUTH_TOKEN", expectsValue: true },
token: { envName: "T3CODE_AUTH_TOKEN", expectsValue: true },
"no-browser": { envName: "T3CODE_NO_BROWSER", expectsValue: false },
"auto-bootstrap-project-from-cwd": {
envName: "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD",
expectsValue: false,
},
"log-websocket-events": { envName: "T3CODE_LOG_WS_EVENTS", expectsValue: false },
"log-ws-events": { envName: "T3CODE_LOG_WS_EVENTS", expectsValue: false },
host: { envName: "T3CODE_HOST", expectsValue: true },
port: { envName: "T3CODE_PORT", expectsValue: true },
"dev-url": { envName: "VITE_DEV_SERVER_URL", expectsValue: true },
};
function parseInteger(value, envName) {
const parsed = Number(value);
if (!Number.isInteger(parsed)) {
throw new Error(`Invalid ${envName}: ${value}`);
}
return parsed;
}
function hashSeed(seed) {
let hash = 0x811c9dc5;
for (let i = 0; i < seed.length; i += 1) {
hash ^= seed.charCodeAt(i);
hash = Math.imul(hash, 0x01000193);
}
return hash >>> 0;
}
export function resolveOffset(env = process.env) {
const explicitOffset = env.T3CODE_PORT_OFFSET?.trim();
if (explicitOffset) {
const parsed = parseInteger(explicitOffset, "T3CODE_PORT_OFFSET");
if (parsed < 0) {
throw new Error(`Invalid T3CODE_PORT_OFFSET: ${explicitOffset}`);
}
return { offset: parsed, source: `T3CODE_PORT_OFFSET=${explicitOffset}` };
}
const seed = env.T3CODE_DEV_INSTANCE?.trim();
if (!seed) {
return { offset: 0, source: "default ports" };
}
if (/^\d+$/.test(seed)) {
return { offset: Number(seed), source: `numeric T3CODE_DEV_INSTANCE=${seed}` };
}
const offset = (hashSeed(seed) % MAX_HASH_OFFSET) + 1;
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
}
function parseLongFlag(raw) {
if (!raw.startsWith("--")) return null;
const normalized = raw.slice(2);
const equalsIndex = normalized.indexOf("=");
if (equalsIndex === -1) {
return { name: normalized, value: undefined };
}
return {
name: normalized.slice(0, equalsIndex),
value: normalized.slice(equalsIndex + 1),
};
}
function toBooleanEnvValue(value) {
if (value === undefined) return "1";
const normalized = value.trim().toLowerCase();
if (normalized === "false" || normalized === "0" || normalized === "no") return "0";
return "1";
}
export function parseDevRunnerArgs(rawArgs) {
const args = rawArgs[0] === "--" ? rawArgs.slice(1) : rawArgs.slice();
const envOverrides = {};
const turboArgs = [];
let isDryRun = false;
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
if (arg === "--dry-run") {
isDryRun = true;
continue;
}
if (arg === "--") {
turboArgs.push(...args.slice(index + 1));
break;
}
const parsedFlag = parseLongFlag(arg);
if (!parsedFlag) {
turboArgs.push(arg);
continue;
}
const definition = FORWARDED_ENV_FLAGS[parsedFlag.name];
if (!definition) {
turboArgs.push(arg);
continue;
}
if (definition.expectsValue) {
let value = parsedFlag.value;
if (value === undefined) {
const next = args[index + 1];
if (next === undefined || next === "--" || next.startsWith("-")) {
throw new Error(`Missing value for --${parsedFlag.name}`);
}
value = next;
index += 1;
}
envOverrides[definition.envName] = value;
continue;
}
envOverrides[definition.envName] = toBooleanEnvValue(parsedFlag.value);
}
return {
isDryRun,
envOverrides,
turboArgs,
};
}
function resolveStateDir(env, envOverrides) {
const overrideValue = envOverrides?.T3CODE_STATE_DIR?.trim();
if (overrideValue) {
// Resolve relative paths against cwd (monorepo root) before turbo changes directories
return path.resolve(overrideValue);
}
const envValue = env?.T3CODE_STATE_DIR?.trim();
if (envValue) {
return path.resolve(envValue);
}
return DEFAULT_DEV_STATE_DIR;
}
export function createDevRunnerEnv({ mode, env, offset, envOverrides }) {
const serverPort = BASE_SERVER_PORT + offset;
const webPort = BASE_WEB_PORT + offset;
const output = {
...env,
T3CODE_PORT: String(serverPort),
PORT: String(webPort),
ELECTRON_RENDERER_PORT: String(webPort),
VITE_WS_URL: `ws://localhost:${serverPort}`,
VITE_DEV_SERVER_URL: `http://localhost:${webPort}`,
...envOverrides,
};
output.T3CODE_STATE_DIR = resolveStateDir(env, envOverrides);
const parsedServerPort = Number(output.T3CODE_PORT);
if (!Number.isInteger(parsedServerPort) || parsedServerPort < 1 || parsedServerPort > 65535) {
throw new Error(
`Invalid T3CODE_PORT override: '${String(output.T3CODE_PORT)}'. Expected an integer between 1 and 65535.`,
);
}
output.VITE_WS_URL = `ws://localhost:${parsedServerPort}`;
if (mode === "dev" || mode === "dev:server" || mode === "dev:web") {
// Running server/web in browser mode should not inherit desktop launcher state.
output.T3CODE_MODE = "web";
if (!("T3CODE_NO_BROWSER" in envOverrides)) {
delete output.T3CODE_NO_BROWSER;
}
if (!("T3CODE_AUTH_TOKEN" in envOverrides)) {
delete output.T3CODE_AUTH_TOKEN;
}
delete output.T3CODE_DESKTOP_WS_URL;
}
if (mode === "dev" && !output.T3CODE_LOG_WS_EVENTS) {
output.T3CODE_LOG_WS_EVENTS = "1";
}
return output;
}
function portPairForOffset(offset) {
return {
serverPort: BASE_SERVER_PORT + offset,
webPort: BASE_WEB_PORT + offset,
};
}
async function canListenOnHost(port, host) {
return await new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.once("error", (error) => {
const code = error?.code;
if (code === "EADDRNOTAVAIL") {
// Host family unavailable on this machine (for example, no IPv6 loopback).
resolve(true);
return;
}
resolve(false);
});
server.once("listening", () => {
server.close(() => {
resolve(true);
});
});
server.listen({ host, port });
});
}
async function isPortAvailable(port) {
// Vite/dev traffic uses localhost loopback. Verify both IPv4 and IPv6 loopback
// so we don't pick a port that fails later on one address family.
const [ipv4, ipv6] = await Promise.all([
canListenOnHost(port, "127.0.0.1"),
canListenOnHost(port, "::1"),
]);
return ipv4 && ipv6;
}
const defaultCheckPortAvailability = isPortAvailable;
export async function findFirstAvailableOffset({
startOffset,
requireServerPort,
requireWebPort,
checkPortAvailability = defaultCheckPortAvailability,
}) {
for (let candidate = startOffset; ; candidate += 1) {
const { serverPort, webPort } = portPairForOffset(candidate);
const serverPortOutOfRange = serverPort > MAX_PORT;
const webPortOutOfRange = webPort > MAX_PORT;
if (
(requireServerPort && serverPortOutOfRange) ||
(requireWebPort && webPortOutOfRange) ||
(!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
) {
break;
}
const checks = [];
if (requireServerPort) {
checks.push(checkPortAvailability(serverPort));
}
if (requireWebPort) {
checks.push(checkPortAvailability(webPort));
}
if (checks.length === 0) {
return candidate;
}
const availability = await Promise.all(checks);
if (availability.every(Boolean)) {
return candidate;
}
}
throw new Error(
`No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
);
}
export async function resolveModePortOffsets({
mode,
startOffset,
envOverrides,
checkPortAvailability,
}) {
const hasExplicitServerPort = typeof envOverrides.T3CODE_PORT === "string";
const hasExplicitDevUrl = typeof envOverrides.VITE_DEV_SERVER_URL === "string";
if (mode === "dev:web") {
if (hasExplicitDevUrl) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const webOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: false,
requireWebPort: true,
checkPortAvailability,
});
return { serverOffset: startOffset, webOffset };
}
if (mode === "dev:server") {
if (hasExplicitServerPort) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const serverOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability,
});
return { serverOffset, webOffset: serverOffset };
}
const sharedOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: !hasExplicitServerPort,
requireWebPort: !hasExplicitDevUrl,
checkPortAvailability,
});
return { serverOffset: sharedOffset, webOffset: sharedOffset };
}
export async function runDevRunner(argv = process.argv) {
const mode = argv[2];
const parsedArgs = parseDevRunnerArgs(argv.slice(3));
if (!mode || !(mode in MODE_ARGS)) {
const supportedModes = Object.keys(MODE_ARGS).join(", ");
throw new Error(`Usage: bun scripts/dev-runner.mjs <mode>. Supported modes: ${supportedModes}`);
}
const { offset, source } = resolveOffset();
const { serverOffset, webOffset } = await resolveModePortOffsets({
mode,
startOffset: offset,
envOverrides: parsedArgs.envOverrides,
});
const mergedEnvOverrides = { ...parsedArgs.envOverrides };
if (!("VITE_DEV_SERVER_URL" in mergedEnvOverrides)) {
const { webPort } = portPairForOffset(webOffset);
mergedEnvOverrides.PORT = String(webPort);
mergedEnvOverrides.ELECTRON_RENDERER_PORT = String(webPort);
mergedEnvOverrides.VITE_DEV_SERVER_URL = `http://localhost:${webPort}`;
}
const env = createDevRunnerEnv({
mode,
env: process.env,
offset: serverOffset,
envOverrides: mergedEnvOverrides,
});
const parsedServerPort = Number(env.T3CODE_PORT);
const parsedWebPort = Number(env.PORT);
if (
!Number.isInteger(parsedServerPort) ||
parsedServerPort < 1 ||
parsedServerPort > MAX_PORT ||
!Number.isInteger(parsedWebPort) ||
parsedWebPort < 1 ||
parsedWebPort > MAX_PORT
) {
throw new Error(
`Invalid computed dev ports: server='${String(env.T3CODE_PORT)}' web='${String(env.PORT)}'.`,
);
}
const selectionSuffix =
serverOffset !== offset || webOffset !== offset
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
: "";
console.info(
`[dev-runner] mode=${mode} source=${source}${selectionSuffix} serverPort=${parsedServerPort} webPort=${parsedWebPort} stateDir=${env.T3CODE_STATE_DIR}`,
);
if (parsedArgs.isDryRun) {
return;
}
const command = process.platform === "win32" ? "turbo.cmd" : "turbo";
const child = spawn(command, [...MODE_ARGS[mode], ...parsedArgs.turboArgs], {
stdio: "inherit",
env,
});
child.on("exit", (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 0);
});
child.on("error", (error) => {
console.error("[dev-runner] failed to start turbo", error);
process.exit(1);
});
}
const entrypointPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : "";
if (import.meta.url === entrypointPath) {
runDevRunner().catch((error) => {
console.error("[dev-runner]", error);
process.exit(1);
});
}
+203 -208
View File
@@ -1,223 +1,218 @@
import { describe, expect, it } from "vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { resolve } from "node:path";
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import {
DEFAULT_DEV_STATE_DIR,
createDevRunnerEnv,
findFirstAvailableOffset,
parseDevRunnerArgs,
resolveModePortOffsets,
} from "./dev-runner.mjs";
resolveOffset,
} from "./dev-runner.ts";
describe("parseDevRunnerArgs", () => {
it("maps supported server flags to env overrides and keeps other flags for turbo", () => {
const parsed = parseDevRunnerArgs([
"--",
"--state-dir",
"~/alt-state",
"--token=abc123",
"--no-browser=false",
"--dry-run",
"--continue",
]);
it.layer(NodeServices.layer)("dev-runner", (it) => {
describe("resolveOffset", () => {
it.effect("uses explicit T3CODE_PORT_OFFSET when provided", () =>
Effect.sync(() => {
const result = resolveOffset({ portOffset: 12, devInstance: undefined });
assert.deepStrictEqual(result, {
offset: 12,
source: "T3CODE_PORT_OFFSET=12",
});
}),
);
expect(parsed.isDryRun).toBe(true);
expect(parsed.envOverrides).toEqual({
T3CODE_STATE_DIR: "~/alt-state",
T3CODE_AUTH_TOKEN: "abc123",
T3CODE_NO_BROWSER: "0",
});
expect(parsed.turboArgs).toEqual(["--continue"]);
it.effect("hashes non-numeric instance values", () =>
Effect.sync(() => {
const result = resolveOffset({ portOffset: undefined, devInstance: "feature-branch" });
assert.ok(result.offset >= 1);
assert.ok(result.offset <= 3000);
}),
);
it.effect("throws for negative port offset", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
Effect.try({
try: () => resolveOffset({ portOffset: -1, devInstance: undefined }),
catch: (cause) => String(cause),
}),
);
assert.ok(error.includes("Invalid T3CODE_PORT_OFFSET"));
}),
);
});
it("throws when a value flag is missing its value", () => {
expect(() => parseDevRunnerArgs(["--state-dir"])).toThrow("Missing value for --state-dir");
describe("createDevRunnerEnv", () => {
it.effect("defaults state dir to ~/.t3/dev when not provided", () =>
Effect.gen(function* () {
const [env, defaultStateDir] = yield* Effect.all([
createDevRunnerEnv({
mode: "dev",
baseEnv: {},
serverOffset: 0,
webOffset: 0,
stateDir: undefined,
authToken: undefined,
noBrowser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
}),
DEFAULT_DEV_STATE_DIR,
]);
assert.equal(env.T3CODE_STATE_DIR, defaultStateDir);
}),
);
it.effect("supports explicit typed overrides", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev:server",
baseEnv: {},
serverOffset: 0,
webOffset: 0,
stateDir: "/tmp/override-state",
authToken: "secret",
noBrowser: true,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
host: "0.0.0.0",
port: 4222,
devUrl: new URL("http://localhost:7331"),
});
assert.equal(env.T3CODE_STATE_DIR, resolve("/tmp/override-state"));
assert.equal(env.T3CODE_PORT, "4222");
assert.equal(env.VITE_WS_URL, "ws://localhost:4222");
assert.equal(env.T3CODE_NO_BROWSER, "1");
assert.equal(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD, "0");
assert.equal(env.T3CODE_LOG_WS_EVENTS, "1");
assert.equal(env.T3CODE_HOST, "0.0.0.0");
assert.equal(env.VITE_DEV_SERVER_URL, "http://localhost:7331/");
}),
);
});
it("throws when a value flag is followed by another flag token", () => {
expect(() => parseDevRunnerArgs(["--state-dir", "--continue"])).toThrow(
"Missing value for --state-dir",
describe("findFirstAvailableOffset", () => {
it.effect("returns the starting offset when required ports are available", () =>
Effect.gen(function* () {
const offset = yield* findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: () => Effect.succeed(true),
});
assert.equal(offset, 0);
}),
);
it.effect("advances until all required ports are available", () =>
Effect.gen(function* () {
const taken = new Set([3773, 5733, 3774, 5734]);
const offset = yield* findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
});
assert.equal(offset, 2);
}),
);
it.effect("allows offsets where only non-required ports exceed max", () =>
Effect.gen(function* () {
const offset = yield* findFirstAvailableOffset({
startOffset: 59_803,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: () => Effect.succeed(true),
});
assert.equal(offset, 59_803);
}),
);
});
describe("resolveModePortOffsets", () => {
it.effect("uses a shared fallback offset for dev mode", () =>
Effect.gen(function* () {
const taken = new Set([3773, 5733]);
const offsets = yield* resolveModePortOffsets({
mode: "dev",
startOffset: 0,
hasExplicitServerPort: false,
hasExplicitDevUrl: false,
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
});
assert.deepStrictEqual(offsets, { serverOffset: 1, webOffset: 1 });
}),
);
it.effect("keeps server offset stable for dev:web and only shifts web offset", () =>
Effect.gen(function* () {
const taken = new Set([5733]);
const offsets = yield* resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
hasExplicitServerPort: false,
hasExplicitDevUrl: false,
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
});
assert.deepStrictEqual(offsets, { serverOffset: 0, webOffset: 1 });
}),
);
it.effect("shifts only server offset for dev:server", () =>
Effect.gen(function* () {
const taken = new Set([3773]);
const offsets = yield* resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
hasExplicitServerPort: false,
hasExplicitDevUrl: false,
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
});
assert.deepStrictEqual(offsets, { serverOffset: 1, webOffset: 1 });
}),
);
it.effect("respects explicit dev-url override for dev:web", () =>
Effect.gen(function* () {
const offsets = yield* resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
hasExplicitServerPort: false,
hasExplicitDevUrl: true,
checkPortAvailability: () => Effect.succeed(false),
});
assert.deepStrictEqual(offsets, { serverOffset: 0, webOffset: 0 });
}),
);
it.effect("respects explicit server port override for dev:server", () =>
Effect.gen(function* () {
const offsets = yield* resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
hasExplicitServerPort: true,
hasExplicitDevUrl: false,
checkPortAvailability: () => Effect.succeed(false),
});
assert.deepStrictEqual(offsets, { serverOffset: 0, webOffset: 0 });
}),
);
});
});
describe("createDevRunnerEnv", () => {
it("defaults state dir to ~/.t3/dev when not provided", () => {
const env = createDevRunnerEnv({
mode: "dev",
env: {},
offset: 0,
envOverrides: {},
});
expect(env.T3CODE_STATE_DIR).toBe(DEFAULT_DEV_STATE_DIR);
});
it("uses existing env state dir when --state-dir is not provided", () => {
const env = createDevRunnerEnv({
mode: "dev:server",
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
offset: 0,
envOverrides: {},
});
expect(env.T3CODE_STATE_DIR).toBe("/tmp/existing-state");
});
it("lets --state-dir override existing env state dir", () => {
const env = createDevRunnerEnv({
mode: "dev:server",
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
offset: 0,
envOverrides: { T3CODE_STATE_DIR: "/tmp/override-state" },
});
expect(env.T3CODE_STATE_DIR).toBe("/tmp/override-state");
});
it("treats whitespace-only --state-dir as missing and falls back to env/default", () => {
const env = createDevRunnerEnv({
mode: "dev:server",
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
offset: 0,
envOverrides: { T3CODE_STATE_DIR: " " },
});
expect(env.T3CODE_STATE_DIR).toBe("/tmp/existing-state");
});
it("recomputes websocket url when port is overridden", () => {
const env = createDevRunnerEnv({
mode: "dev",
env: {},
offset: 0,
envOverrides: { T3CODE_PORT: "4222" },
});
expect(env.T3CODE_PORT).toBe("4222");
expect(env.VITE_WS_URL).toBe("ws://localhost:4222");
});
it("keeps explicitly forwarded web-mode flags", () => {
const env = createDevRunnerEnv({
mode: "dev",
env: {
T3CODE_AUTH_TOKEN: "desktop-token",
},
offset: 0,
envOverrides: {
T3CODE_NO_BROWSER: "1",
T3CODE_AUTH_TOKEN: "cli-token",
},
});
expect(env.T3CODE_NO_BROWSER).toBe("1");
expect(env.T3CODE_AUTH_TOKEN).toBe("cli-token");
});
it("fails fast for invalid port overrides", () => {
expect(() =>
createDevRunnerEnv({
mode: "dev",
env: {},
offset: 0,
envOverrides: { T3CODE_PORT: "not-a-port" },
}),
).toThrow("Invalid T3CODE_PORT override");
});
});
describe("findFirstAvailableOffset", () => {
it("returns the starting offset when required ports are available", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async () => true,
});
expect(offset).toBe(0);
});
it("advances until all required ports are available", async () => {
const taken = new Set([3773, 5733, 3774, 5734]);
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offset).toBe(2);
});
it("allows offsets where only non-required ports exceed max", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 59_803,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: async () => true,
});
expect(offset).toBe(59_803);
});
});
describe("resolveModePortOffsets", () => {
it("uses a shared fallback offset for dev mode", async () => {
const taken = new Set([3773, 5733]);
const offsets = await resolveModePortOffsets({
mode: "dev",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("keeps server offset stable for dev:web and only shifts web offset", async () => {
const taken = new Set([5733]);
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 1 });
});
it("shifts only server offset for dev:server", async () => {
const taken = new Set([3773]);
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("respects explicit dev-url override for dev:web", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: { VITE_DEV_SERVER_URL: "http://localhost:9999" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
it("respects explicit server port override for dev:server", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: { T3CODE_PORT: "4888" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
});
+507
View File
@@ -0,0 +1,507 @@
#!/usr/bin/env node
import { homedir } from "node:os";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NetService } from "@t3tools/shared/Net";
import { Config, Data, Effect, Hash, Layer, Logger, Option, Path, Schema } from "effect";
import { Argument, Command, Flag } from "effect/unstable/cli";
import { ChildProcess } from "effect/unstable/process";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
export const DEFAULT_DEV_STATE_DIR = Effect.map(Effect.service(Path.Path), (path) =>
path.join(homedir(), ".t3", "dev"),
);
const MODE_ARGS = {
dev: [
"run",
"dev",
"--ui=tui",
"--filter=@t3tools/contracts",
"--filter=@t3tools/web",
"--filter=t3",
"--parallel",
],
"dev:server": ["run", "dev", "--filter=t3"],
"dev:web": ["run", "dev", "--filter=@t3tools/web"],
"dev:desktop": ["run", "dev", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "--parallel"],
} as const satisfies Record<string, ReadonlyArray<string>>;
type DevMode = keyof typeof MODE_ARGS;
type PortAvailabilityCheck<R = never> = (port: number) => Effect.Effect<boolean, never, R>;
const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
class DevRunnerError extends Data.TaggedError("DevRunnerError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
const optionalStringConfig = (name: string): Config.Config<string | undefined> =>
Config.string(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const optionalBooleanConfig = (name: string): Config.Config<boolean | undefined> =>
Config.boolean(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const optionalPortConfig = (name: string): Config.Config<number | undefined> =>
Config.port(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
Config.int(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const optionalUrlConfig = (name: string): Config.Config<URL | undefined> =>
Config.url(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const OffsetConfig = Config.all({
portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"),
devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"),
});
export function resolveOffset(config: {
readonly portOffset: number | undefined;
readonly devInstance: string | undefined;
}): { readonly offset: number; readonly source: string } {
if (config.portOffset !== undefined) {
if (config.portOffset < 0) {
throw new Error(`Invalid T3CODE_PORT_OFFSET: ${config.portOffset}`);
}
return {
offset: config.portOffset,
source: `T3CODE_PORT_OFFSET=${config.portOffset}`,
};
}
const seed = config.devInstance?.trim();
if (!seed) {
return { offset: 0, source: "default ports" };
}
if (/^\d+$/.test(seed)) {
return { offset: Number(seed), source: `numeric T3CODE_DEV_INSTANCE=${seed}` };
}
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
}
function resolveStateDir(stateDir: string | undefined): Effect.Effect<string, never, Path.Path> {
return Effect.gen(function* () {
const path = yield* Path.Path;
const configured = stateDir?.trim();
if (configured) {
// Resolve relative paths against cwd (monorepo root) before turbo changes directories.
return path.resolve(configured);
}
return yield* DEFAULT_DEV_STATE_DIR;
});
}
interface CreateDevRunnerEnvInput {
readonly mode: DevMode;
readonly baseEnv: NodeJS.ProcessEnv;
readonly serverOffset: number;
readonly webOffset: number;
readonly stateDir: string | undefined;
readonly authToken: string | undefined;
readonly noBrowser: boolean | undefined;
readonly autoBootstrapProjectFromCwd: boolean | undefined;
readonly logWebSocketEvents: boolean | undefined;
readonly host: string | undefined;
readonly port: number | undefined;
readonly devUrl: URL | undefined;
}
export function createDevRunnerEnv({
mode,
baseEnv,
serverOffset,
webOffset,
stateDir,
authToken,
noBrowser,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
host,
port,
devUrl,
}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
return Effect.gen(function* () {
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
const webPort = BASE_WEB_PORT + webOffset;
const resolvedStateDir = yield* resolveStateDir(stateDir);
const output: NodeJS.ProcessEnv = {
...baseEnv,
T3CODE_PORT: String(serverPort),
PORT: String(webPort),
ELECTRON_RENDERER_PORT: String(webPort),
VITE_WS_URL: `ws://localhost:${serverPort}`,
VITE_DEV_SERVER_URL: devUrl?.toString() ?? `http://localhost:${webPort}`,
T3CODE_STATE_DIR: resolvedStateDir,
};
if (host !== undefined) {
output.T3CODE_HOST = host;
}
if (authToken !== undefined) {
output.T3CODE_AUTH_TOKEN = authToken;
} else {
delete output.T3CODE_AUTH_TOKEN;
}
if (noBrowser !== undefined) {
output.T3CODE_NO_BROWSER = noBrowser ? "1" : "0";
} else {
delete output.T3CODE_NO_BROWSER;
}
if (autoBootstrapProjectFromCwd !== undefined) {
output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
} else {
delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
}
if (logWebSocketEvents !== undefined) {
output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
} else {
delete output.T3CODE_LOG_WS_EVENTS;
}
if (mode === "dev") {
output.T3CODE_MODE = "web";
if (logWebSocketEvents === undefined) {
output.T3CODE_LOG_WS_EVENTS = "1";
}
delete output.T3CODE_DESKTOP_WS_URL;
}
if (mode === "dev:server" || mode === "dev:web") {
output.T3CODE_MODE = "web";
delete output.T3CODE_DESKTOP_WS_URL;
}
return output;
});
}
function portPairForOffset(offset: number): {
readonly serverPort: number;
readonly webPort: number;
} {
return {
serverPort: BASE_SERVER_PORT + offset,
webPort: BASE_WEB_PORT + offset,
};
}
const defaultCheckPortAvailability: PortAvailabilityCheck<NetService> = (port) =>
Effect.gen(function* () {
const net = yield* NetService;
return yield* net.isPortAvailableOnLoopback(port);
});
interface FindFirstAvailableOffsetInput<R = NetService> {
readonly startOffset: number;
readonly requireServerPort: boolean;
readonly requireWebPort: boolean;
readonly checkPortAvailability?: PortAvailabilityCheck<R>;
}
export function findFirstAvailableOffset<R = NetService>({
startOffset,
requireServerPort,
requireWebPort,
checkPortAvailability,
}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerError, R> {
return Effect.gen(function* () {
const checkPort = (checkPortAvailability ??
defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
for (let candidate = startOffset; ; candidate += 1) {
const { serverPort, webPort } = portPairForOffset(candidate);
const serverPortOutOfRange = serverPort > MAX_PORT;
const webPortOutOfRange = webPort > MAX_PORT;
if (
(requireServerPort && serverPortOutOfRange) ||
(requireWebPort && webPortOutOfRange) ||
(!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
) {
break;
}
const checks: Array<Effect.Effect<boolean, never, R>> = [];
if (requireServerPort) {
checks.push(checkPort(serverPort));
}
if (requireWebPort) {
checks.push(checkPort(webPort));
}
if (checks.length === 0) {
return candidate;
}
const availability = yield* Effect.all(checks);
if (availability.every(Boolean)) {
return candidate;
}
}
return yield* new DevRunnerError({
message: `No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
});
});
}
interface ResolveModePortOffsetsInput<R = NetService> {
readonly mode: DevMode;
readonly startOffset: number;
readonly hasExplicitServerPort: boolean;
readonly hasExplicitDevUrl: boolean;
readonly checkPortAvailability?: PortAvailabilityCheck<R>;
}
export function resolveModePortOffsets<R = NetService>({
mode,
startOffset,
hasExplicitServerPort,
hasExplicitDevUrl,
checkPortAvailability,
}: ResolveModePortOffsetsInput<R>): Effect.Effect<
{ readonly serverOffset: number; readonly webOffset: number },
DevRunnerError,
R
> {
return Effect.gen(function* () {
const checkPort = (checkPortAvailability ??
defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
if (mode === "dev:web") {
if (hasExplicitDevUrl) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const webOffset = yield* findFirstAvailableOffset({
startOffset,
requireServerPort: false,
requireWebPort: true,
checkPortAvailability: checkPort,
});
return { serverOffset: startOffset, webOffset };
}
if (mode === "dev:server") {
if (hasExplicitServerPort) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const serverOffset = yield* findFirstAvailableOffset({
startOffset,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: checkPort,
});
return { serverOffset, webOffset: serverOffset };
}
const sharedOffset = yield* findFirstAvailableOffset({
startOffset,
requireServerPort: !hasExplicitServerPort,
requireWebPort: !hasExplicitDevUrl,
checkPortAvailability: checkPort,
});
return { serverOffset: sharedOffset, webOffset: sharedOffset };
});
}
interface DevRunnerCliInput {
readonly mode: DevMode;
readonly stateDir: string | undefined;
readonly authToken: string | undefined;
readonly noBrowser: boolean | undefined;
readonly autoBootstrapProjectFromCwd: boolean | undefined;
readonly logWebSocketEvents: boolean | undefined;
readonly host: string | undefined;
readonly port: number | undefined;
readonly devUrl: URL | undefined;
readonly dryRun: boolean;
readonly turboArgs: ReadonlyArray<string>;
}
export function runDevRunnerWithInput(input: DevRunnerCliInput) {
return Effect.gen(function* () {
const { portOffset, devInstance } = yield* OffsetConfig.asEffect().pipe(
Effect.mapError(
(cause) =>
new DevRunnerError({
message: "Failed to read T3CODE_PORT_OFFSET/T3CODE_DEV_INSTANCE configuration.",
cause,
}),
),
);
const { offset, source } = yield* Effect.try({
try: () => resolveOffset({ portOffset, devInstance }),
catch: (cause) =>
new DevRunnerError({
message: cause instanceof Error ? cause.message : String(cause),
cause,
}),
});
const { serverOffset, webOffset } = yield* resolveModePortOffsets({
mode: input.mode,
startOffset: offset,
hasExplicitServerPort: input.port !== undefined,
hasExplicitDevUrl: input.devUrl !== undefined,
});
const env = yield* createDevRunnerEnv({
mode: input.mode,
baseEnv: process.env,
serverOffset,
webOffset,
stateDir: input.stateDir,
authToken: input.authToken,
noBrowser: input.noBrowser,
autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
logWebSocketEvents: input.logWebSocketEvents,
host: input.host,
port: input.port,
devUrl: input.devUrl,
});
const selectionSuffix =
serverOffset !== offset || webOffset !== offset
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
: "";
yield* Effect.logInfo(
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} stateDir=${String(env.T3CODE_STATE_DIR)}`,
);
if (input.dryRun) {
return;
}
const child = yield* ChildProcess.make(
"turbo",
[...MODE_ARGS[input.mode], ...input.turboArgs],
{
stdin: "inherit",
stdout: "inherit",
stderr: "inherit",
env,
extendEnv: false,
},
);
const exitCode = yield* child.exitCode;
if (exitCode !== 0) {
return yield* new DevRunnerError({
message: `turbo exited with code ${exitCode}`,
});
}
}).pipe(
Effect.mapError((cause) =>
cause instanceof DevRunnerError
? cause
: new DevRunnerError({
message: cause instanceof Error ? cause.message : "dev-runner failed",
cause,
}),
),
);
}
const devRunnerCli = Command.make("dev-runner", {
mode: Argument.choice("mode", DEV_RUNNER_MODES).pipe(
Argument.withDescription("Development mode to run."),
),
stateDir: Flag.string("state-dir").pipe(
Flag.withDescription("State directory path (forwards to T3CODE_STATE_DIR)."),
Flag.withFallbackConfig(optionalStringConfig("T3CODE_STATE_DIR")),
),
authToken: Flag.string("auth-token").pipe(
Flag.withDescription("Auth token (forwards to T3CODE_AUTH_TOKEN)."),
Flag.withAlias("token"),
Flag.withFallbackConfig(optionalStringConfig("T3CODE_AUTH_TOKEN")),
),
noBrowser: Flag.boolean("no-browser").pipe(
Flag.withDescription("Browser auto-open toggle (equivalent to T3CODE_NO_BROWSER)."),
Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_NO_BROWSER")),
),
autoBootstrapProjectFromCwd: Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
Flag.withDescription(
"Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
),
Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
),
logWebSocketEvents: Flag.boolean("log-websocket-events").pipe(
Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
Flag.withAlias("log-ws-events"),
Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
),
host: Flag.string("host").pipe(
Flag.withDescription("Server host/interface override (forwards to T3CODE_HOST)."),
Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOST")),
),
port: Flag.integer("port").pipe(
Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
Flag.withDescription("Server port override (forwards to T3CODE_PORT)."),
Flag.withFallbackConfig(optionalPortConfig("T3CODE_PORT")),
),
devUrl: Flag.string("dev-url").pipe(
Flag.withSchema(Schema.URLFromString),
Flag.withDescription("Web dev URL override (forwards to VITE_DEV_SERVER_URL)."),
Flag.withFallbackConfig(optionalUrlConfig("VITE_DEV_SERVER_URL")),
),
dryRun: Flag.boolean("dry-run").pipe(
Flag.withDescription("Resolve mode/ports/env and print, but do not spawn turbo."),
Flag.withDefault(false),
),
turboArgs: Argument.string("turbo-arg").pipe(
Argument.withDescription("Additional turbo args (pass after `--`)."),
Argument.variadic(),
),
}).pipe(
Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
Command.withHandler((input) => runDevRunnerWithInput(input)),
);
const cliRuntimeLayer = Layer.mergeAll(
Logger.layer([Logger.consolePretty()]),
NodeServices.layer,
NetService.layer,
);
const runtimeProgram = Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide(cliRuntimeLayer),
);
if (import.meta.main) {
NodeRuntime.runMain(runtimeProgram);
}
+31
View File
@@ -0,0 +1,31 @@
/**
* Resolve `catalog:` dependency specs using the workspace catalog.
*
* Pure function: returns a new record with every `catalog:…` value replaced by
* the concrete version string found in `catalog`. Throws on missing entries.
*/
export function resolveCatalogDependencies(
dependencies: Record<string, unknown>,
catalog: Record<string, unknown>,
label: string,
): Record<string, unknown> {
return Object.fromEntries(
Object.entries(dependencies).map(([name, spec]) => {
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
return [name, spec];
}
const catalogKey = spec.slice("catalog:".length).trim();
const lookupKey = catalogKey.length > 0 ? catalogKey : name;
const resolved = catalog[lookupKey];
if (typeof resolved !== "string" || resolved.length === 0) {
throw new Error(
`Unable to resolve '${spec}' for ${label} dependency '${name}'. Expected key '${lookupKey}' in root workspace catalog.`,
);
}
return [name, resolved];
}),
);
}
+23
View File
@@ -0,0 +1,23 @@
{
"name": "@t3tools/scripts",
"private": true,
"type": "module",
"scripts": {
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@types/bun": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"types": ["node", "bun"],
"lib": ["ES2023", "esnext.disposable"],
"noEmit": true,
"allowImportingTsExtensions": true,
"plugins": [
{
"name": "@effect/language-service"
}
]
},
"include": ["**/*.ts"]
}