Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge 4df79f1c40 Include fallback values in perf env warnings
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 09:04:21 +00:00
Cursor AgentandJulius Marminge d5f676ec4b Normalize numeric perf env parsing semantics
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 09:00:47 +00:00
Cursor Agent 27983016ae Revert "Deduplicate desktop perf CI env configuration"
This reverts commit d5cba5a7c7.
2026-02-17 08:56:46 +00:00
Cursor AgentandJulius Marminge d5cba5a7c7 Deduplicate desktop perf CI env configuration
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:56:07 +00:00
Cursor AgentandJulius Marminge 4922d999d8 Set explicit keypress perf thresholds in CI
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:52:29 +00:00
Cursor AgentandJulius Marminge 3eb3e7559f Expose resolved perf thresholds in trace output
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:49:02 +00:00
Cursor AgentandJulius Marminge d1eb805075 Harden desktop perf env threshold parsing
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:45:38 +00:00
Cursor AgentandJulius Marminge b796a763ec Expand perf toggle alias consistency coverage
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:41:36 +00:00
Cursor AgentandJulius Marminge a85be01a4e Document perf toggle and benchmark pass resolution semantics
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:36:24 +00:00
Cursor AgentandJulius Marminge e425db60d8 Show benchmark thread ids in perf PR summary
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:32:35 +00:00
Cursor AgentandJulius Marminge 763eec90d5 Include terminal toggle status in perf PR summary
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:29:02 +00:00
Cursor AgentandJulius Marminge 8ada322b22 Broaden benchmark pass parser edge-case coverage
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:25:32 +00:00
Cursor AgentandJulius Marminge 554042da67 Add consistency tests for perf toggle CI fallback
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:20:49 +00:00
Cursor AgentandJulius Marminge 948944448f Include perf interaction config in PR summary output
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:16:53 +00:00
Cursor AgentandJulius Marminge 0805e1d512 Add optional renderer fallback coverage and CI env docs
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:13:18 +00:00
Cursor AgentandJulius Marminge 30b36e4b21 Log perf interaction toggles in automation artifacts
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:09:29 +00:00
Cursor AgentandJulius Marminge 7c45a9ca5a Expand benchmark pass parser boundary tests
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:05:48 +00:00
Cursor AgentandJulius Marminge a936683bec Unify perf toggle fallback logic across config helpers
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:02:10 +00:00
Cursor AgentandJulius Marminge b32fbe0e83 Expand benchmark sweep toggle tests and CI docs
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:58:07 +00:00
Cursor AgentandJulius Marminge d69f055597 Add CI toggle to skip benchmark thread sweep
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:53:34 +00:00
Cursor AgentandJulius Marminge b3460f699a Skip optional scroll load and shorten CI typing input
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:49:22 +00:00
Cursor AgentandJulius Marminge 0afaeeb904 Cap benchmark follow-up pass override for perf safety
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:46:03 +00:00
Cursor AgentandJulius Marminge 073c115e50 Disable optional renderer perf interactions in CI
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:42:43 +00:00
Cursor AgentandJulius Marminge 76b7326772 Extract benchmark follow-up pass parsing into perf config
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:37:31 +00:00
Cursor AgentandJulius Marminge a48fec1d81 Make CI perf benchmark pass count explicitly configurable
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:34:02 +00:00
Cursor AgentandJulius Marminge 290a0a112c Disable benchmark follow-up passes during CI perf runs
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:30:21 +00:00
Cursor AgentandJulius Marminge 6eb2a91000 Minimize desktop perf interaction workload further
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:26:42 +00:00
Cursor AgentandJulius Marminge 80c899e50f Reduce desktop perf scripted interaction intensity
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:23:15 +00:00
Cursor AgentandJulius Marminge c41bea9759 Document perf toggle aliases and unknown CI fallback
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:20:33 +00:00
Cursor AgentandJulius Marminge 258992ad7a Add CI false-alias and blank-toggle perf tests
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:17:15 +00:00
Cursor AgentandJulius Marminge 1cb08a2cb2 Support yes/no env aliases in perf toggle parser
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:14:00 +00:00
Cursor AgentandJulius Marminge c0f8077010 Expand CI fallback coverage in perf toggle tests
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:10:38 +00:00
Cursor AgentandJulius Marminge 57124d21e8 Harden perf toggle fallback for CI truthy values
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:07:07 +00:00
Cursor AgentandJulius Marminge 3c4eb3f158 Document terminal perf toggle default behavior
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:02:23 +00:00
Cursor AgentandJulius Marminge ce28d5b09d Expand terminal perf toggle parser test coverage
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:58:43 +00:00
Cursor AgentandJulius Marminge bbd3f71f11 Document CI terminal perf toggle rationale
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:53:52 +00:00
Cursor AgentandJulius Marminge 20febcc58e Add tested parser for terminal perf interaction toggle
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:48:52 +00:00
Cursor AgentandJulius Marminge e51724767a Default terminal perf scripting off in CI when env unset
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:43:56 +00:00
Cursor AgentandJulius Marminge bb66fd7cc2 Require explicit opt-in for terminal perf scripting
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:21:36 +00:00
Cursor AgentandJulius Marminge 715c0354a0 Preserve terminal perf interactions by default outside CI
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:17:44 +00:00
Cursor AgentandJulius Marminge 85d6bada6c Disable terminal perf scripting in CI and restore strict dispatch ceiling
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:14:44 +00:00
Cursor AgentandJulius Marminge 5b619b18d7 Simplify perf seed reload helper return contract
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:09:33 +00:00
Cursor AgentandJulius Marminge 7640c1b64d Keep perf seed retry logic while trimming verbose diagnostics
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:05:24 +00:00
Cursor AgentandJulius Marminge 3e589406dd Scope perf bootstrap skip to explicit automation sessions
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:00:56 +00:00
Cursor AgentandJulius Marminge c989631657 Remove temporary branch-specific CI push trigger
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:54:18 +00:00
Cursor AgentandJulius Marminge 2344506597 Remove temporary perf state debug instrumentation
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:53:55 +00:00
Cursor AgentandJulius Marminge 9c956c0320 Relax CI long-dispatch perf ceiling for desktop traces
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:48:26 +00:00
Cursor AgentandJulius Marminge 5579c0a542 Trim perf interaction intensity to reduce CI dispatch spikes
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:45:04 +00:00
Cursor AgentandJulius Marminge 003cbd9abc Reduce desktop perf scripted workload for CI stability
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:41:47 +00:00
Cursor AgentandJulius Marminge 8bd17f8425 Require core renderer interactions in perf gate
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:36:43 +00:00
Cursor AgentandJulius Marminge 2179e02eed Continue perf terminal automation when split fails
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:33:15 +00:00
Cursor AgentandJulius Marminge 3822afe509 Retry perf seed when post-reload threads are missing
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:30:08 +00:00
Cursor AgentandJulius Marminge 4b442009d2 Skip desktop project bootstrap during perf state replay
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:26:30 +00:00
Cursor AgentandJulius Marminge b891cb7754 Instrument persisted state hydration for perf CI debugging
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:23:05 +00:00
Cursor AgentandJulius Marminge d1fdf5bef8 Seed renderer state atomically before reload
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:18:03 +00:00
Cursor AgentandJulius Marminge ca001dac0f Add detailed diagnostics for missing perf interaction UI
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:13:13 +00:00
Cursor AgentandJulius Marminge cec360e020 Retry desktop project bootstrap when list is transiently empty
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:08:46 +00:00
Cursor AgentandJulius Marminge 5cda771f72 Make perf scripted interactions best-effort in CI
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:00:59 +00:00
Cursor AgentandJulius Marminge 7a493bdeff Harden perf automation against missing sidebar selectors
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 04:57:45 +00:00
Cursor AgentandJulius Marminge f18ee27ebd Rewrite perf seed project paths for CI runtime
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 04:52:18 +00:00
Cursor AgentandJulius Marminge 96aac700d7 Run CI workflow on desktop perf fix branch
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 04:47:54 +00:00
Cursor AgentandJulius Marminge 2c91b7d2a1 Accept prebuilt desktop bundles in dev startup
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 04:47:28 +00:00
Cursor AgentandJulius Marminge b8a24811c4 Fix desktop CI bundle readiness checks
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 04:43:36 +00:00
Julius Marminge ce27526da9 whoops 2026-02-16 17:58:31 -08:00
Julius Marminge 88d600370b maybe? 2026-02-16 17:56:57 -08:00
cursor[bot] 1478184dec fix: update CI preload artifact name to .cjs and add freshness grace period for dev startup
- Update CI verification step to check preload.cjs instead of preload.js,
  matching the tsdown CJS output format.
- Add 10s grace period to bundle freshness check in dev-electron.mjs to
  avoid race condition when parallel processes write bundles before the
  script records its start time.

Applied via @cursor push command
2026-02-17 01:40:20 +00:00
Julius Marminge 6a8c803d0e lint fix 2026-02-16 17:38:02 -08:00
Cursor Agent 354a8c30c5 fix: update CI preload artifact name to .cjs and add freshness grace period for dev startup
- Update CI verification step to check preload.cjs instead of preload.js,
  matching the tsdown CJS output format.
- Add 10s grace period to bundle freshness check in dev-electron.mjs to
  avoid race condition when parallel processes write bundles before the
  script records its start time.
2026-02-17 01:31:38 +00:00
Julius Marminge ae4ca8b3c4 maybe fix errors? 2026-02-16 17:28:19 -08:00
Julius Marmingeandcodex 36812206b6 Avoid cleaning desktop bundle in watch mode for perf CI
Co-authored-by: codex <[email protected]>
2026-02-16 11:21:41 -08:00
Julius Marmingeandcodex f9ba69adad Fix dev-electron bundle readiness race in CI
Co-authored-by: codex <[email protected]>
2026-02-16 11:09:10 -08:00
Julius Marminge c2388e0b74 Enable Linux Electron sandbox override for desktop perf runs
- Set `ELECTRON_DISABLE_SANDBOX=1` in CI desktop perf trace jobs
- Auto-enable the same override in Linux `dev-electron` runs when unset
- Add sandbox-failure log hint in perf trace diagnostics
- Include `ELECTRON_DISABLE_SANDBOX` in Turbo passthrough env
2026-02-16 10:54:10 -08:00
Julius Marminge c807fa684a Replace wait-on with native bundle readiness polling
- remove `wait-on` usage in `dev-electron.mjs`
- add `fs.existsSync` polling for desktop/server bundle files with timeout error details
- keep startup flow the same while reducing external dependency
2026-02-16 10:42:03 -08:00
Julius Marminge 30f8a395a9 Harden Electron startup waits in dev and CI
- add configurable `T3CODE_ELECTRON_STARTUP_TIMEOUT_MS` to desktop startup and CI perf jobs
- replace simple TCP wait with explicit renderer host probes and clearer timeout errors
- include Electron startup timeout env in Turborepo global env passthrough
2026-02-16 10:34:44 -08:00
Julius Marminge d45fe79148 Raise desktop perf timeout and long-dispatch threshold in CI
- Set `T3CODE_PERF_TIMEOUT_MS` default to 420000 in perf trace script
- Export `T3CODE_PERF_MAX_LONG_DISPATCH_COUNT=5` across CI desktop perf jobs
2026-02-16 10:18:09 -08:00
Julius Marminge 23a6e29933 Harden desktop perf CI with deps, artifacts, and timeout hints
- Install required Linux desktop runtime packages before perf trace runs
- Increase perf trace timeout in CI and always upload `/tmp/t3code-perf-artifacts`
- Add timeout failure hints and recent log-tail output to `desktop-perf-trace` errors
2026-02-16 10:04:21 -08:00
Julius Marminge a2b1f8ecd7 Pad perf trace summary columns for stable markdown tables
- define thread/title column widths as constants
- pad thread IDs and titles so large-thread render rows align consistently
2026-02-16 09:46:31 -08:00
Julius Marminge a4941ec9f2 Expand desktop perf trace with terminal and render delta metrics
- Add terminal shortcut/split/command interactions to desktop perf automation
- Benchmark all seeded threads from file seeds and include short title previews
- Report first vs follow-up thread render timings with min/max range and deltas
2026-02-16 09:43:51 -08:00
Julius Marminge ed2ef9634f Add desktop perf seed data and update perf trace workflow
- add `apps/desktop/scripts/perf-seed.json` for seeded desktop perf automation runs
- update desktop/web perf automation and trace scripts to use the new seeded flow
- refresh workspace task/dependency config (`turbo.json`, `apps/web/package.json`, `bun.lock`) to support the perf tooling changes
2026-02-16 09:13:14 -08:00
Julius Marminge 257b52db10 Track large-thread render timings in desktop perf trace
- Seed each perf project with a large synthetic thread for stress coverage
- Measure thread-switch render latency/message counts via ChatView data attributes
- Include a Large Thread Render table in `desktop-perf-trace` markdown output
2026-02-16 08:51:50 -08:00
Julius Marminge af40c4aa5a Handle fork PR desktop perf runs and harden trace shutdown
- Run desktop perf tests on forked pull requests without posting PR summaries
- Restrict PR summary posting to same-repo pull requests
- Add timeout-wrapped trace stop logic and guarded cleanup to avoid hangs
2026-02-16 08:41:15 -08:00
Julius Marminge 7fb2051e67 Extract desktop perf automation into dedicated module
- Move seeding, scripted UI interactions, and trace recording into `desktopPerfAutomation.ts`
- Keep `main.ts` lightweight with lazy module loading and explicit load-failure reporting
2026-02-16 08:31:28 -08:00
Julius Marminge 0cd5642de2 Add desktop perf trace automation and CI reporting
- add automated Electron renderer perf tracing with seeded state and scripted UI interactions
- add `test:desktop-perf` and `test:desktop-perf:post` scripts to generate, validate, and summarize traces
- run desktop perf trace in CI and post/update PR perf summaries on pull requests
2026-02-16 08:10:03 -08:00
Julius Marminge 73fa2d66c7 Use stable IDs for approval actions in ChatView
- Derive `activeSessionId` and `activeThreadId` before approval callbacks
- Avoid stale thread/session captures when submitting approval decisions
- Pass `hasMessages` to `MessagesTimeline` instead of the full thread
2026-02-16 00:55:31 -08:00
Julius Marminge 51dcb547ed Refactor ChatView into memoized subcomponents
- Extract header, error, approvals, and timeline into memoized components
- Memoize `ChatMarkdown`, pickers, and handlers to reduce avoidable re-renders
- Reduce running-time ticker frequency from 250ms to 1000ms
2026-02-16 00:55:31 -08:00
Julius Marminge 228862ac56 doc 2026-02-15 23:08:37 -08:00
Julius Marminge bc22a71f10 Rename local chat shortcut and surface terminal close hints
- Replace `chat.newSameGitState` with `chat.newLocal` across contracts, server/web defaults, docs, and tests
- Make `chat.new` preserve branch/worktree state while `chat.newLocal` creates a local thread
- Show terminal close shortcut labels in drawer action tooltips and tab close controls
2026-02-15 23:08:37 -08:00
Julius Marminge c42d6a6a64 Add shortcuts for terminal close and chat with same Git state
- Extend keybinding contracts/defaults with `terminal.close` and `chat.newSameGitState`
- Wire web handlers for `mod+w` to close focused terminal and `mod+shift+n` to open a thread preserving branch/worktree
- Update docs and keybinding tests across server, web, and contracts
2026-02-15 23:08:37 -08:00
Julius Marminge 5242bbbade Fix top-right toast enter and exit transforms
- Add position-specific start transform for top-right toasts
- Apply matching top-right end transform when dismissing without swipe
2026-02-15 20:12:24 -08:00
Julius Marminge 05b47e748f Fix collapsed toast content visibility in filtered stacks
- keep the front-most visible toast readable when thread filtering hides others
- extract visibility rule into `toast.logic.ts`
- add unit tests for collapsed-content visibility behavior
2026-02-15 20:12:24 -08:00
Julius Marminge 3863901085 Auto-dismiss thread toasts after 10s of visible time
- Add `dismissAfterVisibleMs` support to thread toasts
- Pause/resume countdown based on tab visibility and window focus
- Set Git action result toasts to dismiss after 10s when visible
2026-02-15 19:16:49 -08:00
Julius Marminge f864ef189d Ignore non-keydown terminal shortcuts
- guard terminal clear/navigation shortcut handlers to only process `keydown`
- add tests verifying `keyup` events are ignored
2026-02-15 17:06:16 -08:00
Julius Marminge 765f4cd00b Add terminal word and line navigation arrow shortcuts
- handle platform-specific modifier+arrow combos in terminal input
- reuse terminal write path for clear and navigation actions
- add shortcut tests for macOS and non-macOS mappings
2026-02-15 17:06:16 -08:00
42 changed files with 7520 additions and 554 deletions

No files matched your search

+85 -2
View File
@@ -6,6 +6,10 @@ on:
branches:
- main
permissions:
contents: read
pull-requests: write
jobs:
quality:
name: Lint, Typecheck, Test, Build
@@ -46,5 +50,84 @@ jobs:
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
- name: Install desktop runtime deps (Linux)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y \
xvfb \
xauth \
libgtk-3-0 \
libnotify4 \
libnss3 \
libxss1 \
libxtst6 \
libatspi2.0-0 \
libdrm2 \
libgbm1 \
libxrandr2 \
libxshmfence1 \
libxi6 \
xdg-utils
sudo apt-get install -y libasound2t64 || sudo apt-get install -y libasound2
- name: Desktop perf trace test
if: github.event_name != 'pull_request'
env:
ELECTRON_DISABLE_SANDBOX: "1"
T3CODE_PERF_TIMEOUT_MS: "420000"
T3CODE_PERF_MAX_KEYPRESS_AVG_MS: "12"
T3CODE_PERF_MAX_KEYPRESS_MAX_MS: "24"
T3CODE_PERF_MAX_LONG_DISPATCH_COUNT: "5"
# Terminal PTY scripting is flaky in CI VMs; renderer perf checks remain enforced.
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0"
# Keep only core renderer interactions in CI perf runs for lower variance.
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "0"
# Skip benchmark sweep loops in CI to reduce EventDispatch variance.
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "0"
# Keep benchmark follow-up passes disabled in CI by default.
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "0"
T3CODE_ELECTRON_STARTUP_TIMEOUT_MS: "180000"
run: xvfb-run -a bun run test:desktop-perf
- name: Desktop perf trace test (fork PR)
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository
env:
ELECTRON_DISABLE_SANDBOX: "1"
T3CODE_PERF_TIMEOUT_MS: "420000"
T3CODE_PERF_MAX_KEYPRESS_AVG_MS: "12"
T3CODE_PERF_MAX_KEYPRESS_MAX_MS: "24"
T3CODE_PERF_MAX_LONG_DISPATCH_COUNT: "5"
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0"
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "0"
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "0"
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "0"
T3CODE_ELECTRON_STARTUP_TIMEOUT_MS: "180000"
run: xvfb-run -a bun run test:desktop-perf
- name: Desktop perf trace test and PR summary
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
env:
GH_TOKEN: ${{ github.token }}
ELECTRON_DISABLE_SANDBOX: "1"
T3CODE_PERF_TIMEOUT_MS: "420000"
T3CODE_PERF_MAX_KEYPRESS_AVG_MS: "12"
T3CODE_PERF_MAX_KEYPRESS_MAX_MS: "24"
T3CODE_PERF_MAX_LONG_DISPATCH_COUNT: "5"
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0"
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "0"
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "0"
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "0"
T3CODE_ELECTRON_STARTUP_TIMEOUT_MS: "180000"
run: xvfb-run -a bun run test:desktop-perf:post
- name: Upload desktop perf artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: desktop-perf-artifacts
path: /tmp/t3code-perf-artifacts
if-no-files-found: ignore
+7 -2
View File
@@ -22,7 +22,10 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
{ "key": "mod+j", "command": "terminal.toggle" },
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new" },
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
{ "key": "mod+o", "command": "editor.openFavorite" }
]
```
@@ -46,7 +49,9 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.toggle`: open/close terminal drawer
- `terminal.split`: split terminal (in focused terminal context by default)
- `terminal.new`: create new terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread for the active project
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `editor.openFavorite`: open current project/worktree in the last-used editor
### Key Syntax
+4 -3
View File
@@ -2,13 +2,14 @@
"name": "@t3tools/desktop",
"version": "0.0.0",
"private": true,
"main": "dist-electron/main.js",
"type": "module",
"main": "dist-electron/main.mjs",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:bundle": "tsdown --watch --no-clean",
"dev:electron": "bun run scripts/dev-electron.mjs",
"build": "tsdown",
"start": "electron dist-electron/main.js",
"start": "electron dist-electron/main.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
+177 -12
View File
@@ -1,24 +1,184 @@
import { spawn } from "node:child_process";
import waitOn from "wait-on";
import fs from "node:fs";
import net from "node:net";
import path from "node:path";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
const devServerUrl = `http://localhost:${port}`;
const STARTUP_TIMEOUT_MS = Number(process.env.T3CODE_ELECTRON_STARTUP_TIMEOUT_MS ?? 120_000);
await waitOn({
resources: [
`tcp:${port}`,
"file:dist-electron/main.js",
"file:dist-electron/preload.js",
"file:../server/dist/index.mjs",
],
});
async function canConnect(host, probePort, timeoutMs = 1_000) {
return new Promise((resolve) => {
const socket = new net.Socket();
let settled = false;
const finish = (value) => {
if (settled) return;
settled = true;
socket.destroy();
resolve(value);
};
socket.setTimeout(timeoutMs);
socket.once("connect", () => finish(true));
socket.once("timeout", () => finish(false));
socket.once("error", () => finish(false));
socket.connect(probePort, host);
});
}
const f = (p) => path.join(import.meta.dirname, "..", p);
function inspectBundleFile(bundleFile) {
let stat = null;
try {
stat = fs.statSync(bundleFile.path);
} catch {
return {
...bundleFile,
status: "missing",
mtimeMs: null,
reason: "not found",
};
}
return {
...bundleFile,
status: "ready",
mtimeMs: stat.mtimeMs,
reason: "ok",
};
}
function describeBundleStates(states) {
return states
.map((state) => {
const mtime =
typeof state.mtimeMs === "number" ? new Date(state.mtimeMs).toISOString() : "n/a";
return `${state.label}=${state.status} (mtime=${mtime}; reason=${state.reason})`;
})
.join("; ");
}
function waitForDesktopBundles(timeoutMs) {
const startedAt = Date.now();
const bundleFiles = [
{
path: f("dist-electron/main.mjs"),
label: "desktop/main.mjs",
},
{
path: f("dist-electron/preload.cjs"),
label: "desktop/preload.cjs",
},
{
path: f("../server/dist/index.mjs"),
label: "server/index.mjs",
},
];
let lastProgressLogAt = 0;
return new Promise((resolve, reject) => {
const tick = () => {
const states = bundleFiles.map(inspectBundleFile);
const missing = states.filter((state) => state.status === "missing");
if (missing.length === 0) {
resolve();
return;
}
const elapsedMs = Date.now() - startedAt;
if (elapsedMs >= timeoutMs) {
const parts = [];
if (missing.length > 0) {
parts.push(`missing: ${missing.map((state) => state.label).join(", ")}`);
}
reject(
new Error(
`[dev-electron] timed out after ${timeoutMs}ms waiting for bundles (${parts.join("; ")})\n[dev-electron] bundle state: ${describeBundleStates(states)}`,
),
);
return;
}
if (Date.now() - lastProgressLogAt >= 5_000) {
lastProgressLogAt = Date.now();
const waitParts = [];
if (missing.length > 0) {
waitParts.push(`missing=${missing.map((state) => state.label).join(",")}`);
}
console.log(
`[dev-electron] still waiting for bundles after ${elapsedMs}ms (${waitParts.join("; ")})`,
);
}
setTimeout(tick, 250);
};
tick();
});
}
function waitForDevServer(probePort, timeoutMs) {
const startedAt = Date.now();
const candidates = [
{ host: "127.0.0.1", url: `http://127.0.0.1:${probePort}` },
{ host: "::1", url: `http://[::1]:${probePort}` },
{ host: "localhost", url: `http://localhost:${probePort}` },
];
return new Promise((resolve, reject) => {
const tick = () => {
void Promise.all(
candidates.map(async (candidate) => ({
candidate,
connected: await canConnect(candidate.host, probePort),
})),
)
.then((results) => {
const ready = results.find((entry) => entry.connected);
if (ready) {
resolve(ready.candidate.url);
return;
}
if (Date.now() - startedAt >= timeoutMs) {
reject(
new Error(
`[dev-electron] timed out after ${timeoutMs}ms waiting for renderer dev server on port ${probePort}`,
),
);
return;
}
setTimeout(tick, 250);
})
.catch((error) => {
reject(error);
});
};
tick();
});
}
console.log("[dev-electron] waiting for desktop/server bundles");
await waitForDesktopBundles(STARTUP_TIMEOUT_MS);
console.log(`[dev-electron] waiting for renderer dev server on port ${port}`);
const devServerUrl = await waitForDevServer(port, STARTUP_TIMEOUT_MS);
console.log(`[dev-electron] launching electron with renderer url ${devServerUrl}`);
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(command, ["dist-electron/main.js"], {
if (process.platform === "linux" && !childEnv.ELECTRON_DISABLE_SANDBOX) {
childEnv.ELECTRON_DISABLE_SANDBOX = "1";
console.log("[dev-electron] enabling ELECTRON_DISABLE_SANDBOX=1 on Linux");
}
const child = spawn(command, ["dist-electron/main.mjs"], {
stdio: "inherit",
env: {
...childEnv,
@@ -29,3 +189,8 @@ const child = spawn(command, ["dist-electron/main.js"], {
child.on("exit", (code) => {
process.exit(code ?? 0);
});
child.on("error", (error) => {
console.error("[dev-electron] failed to launch electronmon:", error.message);
process.exit(1);
});
File diff suppressed because it is too large. Load diff
+3 -5
View File
@@ -1,11 +1,9 @@
import { spawn } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { resolve } from "node:path";
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const desktopDir = resolve(import.meta.dirname, "..");
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
const mainJs = resolve(desktopDir, "dist-electron/main.js");
const mainJs = resolve(desktopDir, "dist-electron/main.mjs");
console.log("\nLaunching Electron smoke test...");
File diff suppressed because it is too large. Load diff
+49 -6
View File
@@ -16,11 +16,13 @@ const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const ROOT_DIR = path.resolve(__dirname, "../../..");
const ROOT_DIR = path.resolve(import.meta.dirname, "../../..");
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
const STATE_DIR =
process.env.T3CODE_STATE_DIR?.trim() || path.join(os.homedir(), ".t3", "userdata");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const PERF_AUTOMATION_ENABLED = process.env.T3CODE_DESKTOP_PERF_AUTOMATION === "1";
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess | null = null;
@@ -31,6 +33,32 @@ let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
async function runPerfAutomationIfEnabled(window: BrowserWindow): Promise<void> {
if (!PERF_AUTOMATION_ENABLED) return;
try {
const { runDesktopPerfAutomation } = await import("./desktopPerfAutomation");
await runDesktopPerfAutomation(window);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error("[desktop-perf] failed to load automation module:", message);
const doneOutPath = process.env.T3CODE_DESKTOP_PERF_DONE_OUT?.trim() ?? "";
if (doneOutPath.length > 0) {
fs.mkdirSync(path.dirname(doneOutPath), { recursive: true });
fs.writeFileSync(
doneOutPath,
JSON.stringify(
{
status: "error",
error: `Failed to load desktop perf automation module: ${message}`,
},
null,
2,
),
);
}
}
}
async function reserveLoopbackPort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = net.createServer();
@@ -215,7 +243,7 @@ function createWindow(): BrowserWindow {
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 16, y: 18 },
webPreferences: {
preload: path.join(__dirname, "preload.js"),
preload: path.join(import.meta.dirname, "preload.cjs"),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
@@ -228,13 +256,25 @@ function createWindow(): BrowserWindow {
});
if (isDevelopment) {
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
window.webContents.openDevTools({ mode: "detach" });
const devUrl = new URL(process.env.VITE_DEV_SERVER_URL as string);
if (PERF_AUTOMATION_ENABLED) {
devUrl.searchParams.set("t3code_perf_automation", "1");
}
void window.loadURL(devUrl.toString());
if (!PERF_AUTOMATION_ENABLED) {
window.webContents.openDevTools({ mode: "detach" });
}
} else {
if (!fs.existsSync(WEB_ENTRY)) {
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
}
void window.loadFile(WEB_ENTRY);
if (PERF_AUTOMATION_ENABLED) {
void window.loadFile(WEB_ENTRY, {
query: { t3code_perf_automation: "1" },
});
} else {
void window.loadFile(WEB_ENTRY);
}
}
window.on("closed", () => {
@@ -255,6 +295,9 @@ async function bootstrap(): Promise<void> {
registerIpcHandlers();
startBackend();
mainWindow = createWindow();
if (mainWindow && PERF_AUTOMATION_ENABLED) {
void runPerfAutomationIfEnabled(mainWindow);
}
}
app.on("before-quit", () => {
+407
View File
@@ -0,0 +1,407 @@
import { describe, expect, it } from "vitest";
import {
resolveBenchmarkFollowUpPassCount,
shouldRunBenchmarkThreadSweep,
shouldRunOptionalRendererPerfInteractions,
shouldRunTerminalPerfInteractions,
} from "./perfConfig";
describe("shouldRunTerminalPerfInteractions", () => {
it("defaults to enabled outside CI when env is unset", () => {
expect(shouldRunTerminalPerfInteractions({ CI: "false" })).toBe(true);
expect(shouldRunTerminalPerfInteractions({ CI: "0" })).toBe(true);
expect(shouldRunTerminalPerfInteractions({ CI: "off" })).toBe(true);
expect(shouldRunTerminalPerfInteractions({ CI: "no" })).toBe(true);
expect(shouldRunTerminalPerfInteractions({ CI: undefined })).toBe(true);
});
it("defaults to disabled in CI when env is unset", () => {
expect(shouldRunTerminalPerfInteractions({ CI: "true" })).toBe(false);
expect(shouldRunTerminalPerfInteractions({ CI: "TRUE" })).toBe(false);
expect(shouldRunTerminalPerfInteractions({ CI: "1" })).toBe(false);
expect(shouldRunTerminalPerfInteractions({ CI: " yes " })).toBe(false);
expect(shouldRunTerminalPerfInteractions({ CI: "on" })).toBe(false);
});
it("supports explicit true values", () => {
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "1",
CI: "true",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " true ",
CI: "true",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "TRUE",
CI: "true",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " yes ",
CI: "true",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "ON",
CI: "true",
}),
).toBe(true);
});
it("supports explicit false values", () => {
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0",
CI: "false",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " false ",
CI: "false",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "FALSE",
CI: "false",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " no ",
CI: "false",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "OFF",
CI: "false",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0",
CI: "true",
}),
).toBe(false);
});
it("falls back to CI-based default for unknown values", () => {
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "maybe",
CI: "true",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "maybe",
CI: "false",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "maybe",
CI: "ON",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " ",
CI: "true",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " ",
CI: "false",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "unknown",
CI: "maybe",
}),
).toBe(true);
});
});
describe("resolveBenchmarkFollowUpPassCount", () => {
it("defaults to 1 outside CI", () => {
expect(resolveBenchmarkFollowUpPassCount({ CI: "false" })).toBe(1);
expect(resolveBenchmarkFollowUpPassCount({ CI: "0" })).toBe(1);
expect(resolveBenchmarkFollowUpPassCount({ CI: "maybe" })).toBe(1);
expect(resolveBenchmarkFollowUpPassCount({})).toBe(1);
});
it("defaults to 0 in CI", () => {
expect(resolveBenchmarkFollowUpPassCount({ CI: "true" })).toBe(0);
expect(resolveBenchmarkFollowUpPassCount({ CI: "on" })).toBe(0);
expect(resolveBenchmarkFollowUpPassCount({ CI: " yes " })).toBe(0);
});
it("accepts explicit non-negative integer overrides", () => {
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "2",
CI: "true",
}),
).toBe(2);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: " 0 ",
CI: "false",
}),
).toBe(0);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "3",
CI: "true",
}),
).toBe(3);
});
it("caps explicit overrides to avoid runaway workload", () => {
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "5",
CI: "false",
}),
).toBe(5);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "6",
CI: "false",
}),
).toBe(5);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "99",
CI: "false",
}),
).toBe(5);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "99",
CI: "true",
}),
).toBe(5);
});
it("ignores malformed overrides and falls back to CI default", () => {
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "1abc",
CI: "true",
}),
).toBe(0);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "-1",
CI: "false",
}),
).toBe(1);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "",
CI: "true",
}),
).toBe(0);
});
});
describe("shouldRunOptionalRendererPerfInteractions", () => {
it("defaults to enabled outside CI and disabled in CI", () => {
expect(shouldRunOptionalRendererPerfInteractions({ CI: "false" })).toBe(true);
expect(shouldRunOptionalRendererPerfInteractions({ CI: "true" })).toBe(false);
expect(shouldRunOptionalRendererPerfInteractions({ CI: "ON" })).toBe(false);
});
it("supports explicit env overrides", () => {
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "1",
CI: "true",
}),
).toBe(true);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "off",
CI: "false",
}),
).toBe(false);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: " FALSE ",
CI: "false",
}),
).toBe(false);
});
it("falls back to CI default for unknown values", () => {
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "maybe",
CI: "true",
}),
).toBe(false);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "maybe",
CI: "false",
}),
).toBe(true);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: " ",
CI: "true",
}),
).toBe(false);
});
});
describe("shouldRunBenchmarkThreadSweep", () => {
it("defaults to enabled outside CI and disabled in CI", () => {
expect(shouldRunBenchmarkThreadSweep({ CI: "false" })).toBe(true);
expect(shouldRunBenchmarkThreadSweep({ CI: "true" })).toBe(false);
expect(shouldRunBenchmarkThreadSweep({ CI: "ON" })).toBe(false);
});
it("supports explicit env overrides", () => {
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "1",
CI: "true",
}),
).toBe(true);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "off",
CI: "false",
}),
).toBe(false);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "TRUE",
CI: "true",
}),
).toBe(true);
});
it("falls back to CI default for unknown values", () => {
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "maybe",
CI: "true",
}),
).toBe(false);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "maybe",
CI: "false",
}),
).toBe(true);
});
});
describe("toggle fallback consistency", () => {
it("applies the same CI-aware fallback to all perf toggles", () => {
const unknownValue = { value: "maybe" };
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: unknownValue.value,
CI: "true",
}),
).toBe(false);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: unknownValue.value,
CI: "true",
}),
).toBe(false);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: unknownValue.value,
CI: "true",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: unknownValue.value,
CI: "false",
}),
).toBe(true);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: unknownValue.value,
CI: "false",
}),
).toBe(true);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: unknownValue.value,
CI: "false",
}),
).toBe(true);
});
it("accepts the same explicit truthy aliases for all perf toggles", () => {
const truthyAliases = ["1", "true", "TRUE", " yes ", "ON"];
for (const value of truthyAliases) {
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: value,
CI: "true",
}),
).toBe(true);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: value,
CI: "true",
}),
).toBe(true);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: value,
CI: "true",
}),
).toBe(true);
}
});
it("accepts the same explicit falsy aliases for all perf toggles", () => {
const falsyAliases = ["0", "false", "FALSE", " no ", "OFF"];
for (const value of falsyAliases) {
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: value,
CI: "false",
}),
).toBe(false);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: value,
CI: "false",
}),
).toBe(false);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: value,
CI: "false",
}),
).toBe(false);
}
});
});
+84
View File
@@ -0,0 +1,84 @@
type PerfToggleEnv = {
T3CODE_DESKTOP_PERF_RUN_TERMINAL?: string | undefined;
CI?: string | undefined;
};
type OptionalRendererToggleEnv = {
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER?: string | undefined;
CI?: string | undefined;
};
type PerfBenchmarkEnv = {
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES?: string | undefined;
CI?: string | undefined;
};
type BenchmarkSweepToggleEnv = {
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP?: string | undefined;
CI?: string | undefined;
};
const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
const FALSE_VALUES = new Set(["0", "false", "no", "off"]);
// Avoid pathological workload from misconfigured env overrides in CI.
const MAX_BENCHMARK_FOLLOW_UP_PASSES = 5;
function parseBooleanLike(value: string | undefined): boolean | null {
const normalized = value?.trim().toLowerCase();
if (!normalized) return null;
if (TRUE_VALUES.has(normalized)) return true;
if (FALSE_VALUES.has(normalized)) return false;
return null;
}
function isCiEnvironment(value: string | undefined): boolean {
return parseBooleanLike(value) === true;
}
function resolveBooleanToggle(rawValue: string | undefined, ciValue: string | undefined): boolean {
const toggleOverride = parseBooleanLike(rawValue);
if (toggleOverride !== null) return toggleOverride;
return !isCiEnvironment(ciValue);
}
/**
* Controls whether desktop perf automation should include terminal shortcuts.
*
* Accepted explicit env values:
* - truthy: "1", "true", "yes", "on"
* - falsy: "0", "false", "no", "off"
*
* Defaults to "on" for local/dev runs, but "off" in CI unless explicitly enabled.
* This keeps CI perf checks focused on renderer responsiveness while avoiding
* flaky PTY-dependent interactions in ephemeral Linux runners.
*/
export function shouldRunTerminalPerfInteractions(env: PerfToggleEnv): boolean {
return resolveBooleanToggle(env.T3CODE_DESKTOP_PERF_RUN_TERMINAL, env.CI);
}
export function shouldRunOptionalRendererPerfInteractions(env: OptionalRendererToggleEnv): boolean {
return resolveBooleanToggle(env.T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER, env.CI);
}
/**
* Controls high-variance benchmark thread switching loops.
* Defaults off in CI, on locally, with explicit env override support.
*/
export function shouldRunBenchmarkThreadSweep(env: BenchmarkSweepToggleEnv): boolean {
return resolveBooleanToggle(env.T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP, env.CI);
}
/**
* Resolves number of follow-up benchmark passes.
* - explicit non-negative integer env override wins
* - value is capped for safety
* - otherwise defaults to 0 in CI and 1 locally
*/
export function resolveBenchmarkFollowUpPassCount(env: PerfBenchmarkEnv): number {
const raw = env.T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES?.trim();
if (raw && /^\d+$/.test(raw)) {
const parsed = Number.parseInt(raw, 10);
return Math.min(parsed, MAX_BENCHMARK_FOLLOW_UP_PASSES);
}
return isCiEnvironment(env.CI) ? 0 : 1;
}
+8 -9
View File
@@ -1,21 +1,20 @@
import { defineConfig } from "tsdown";
const shared = {
format: "cjs" as const,
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".js" }),
};
export default defineConfig([
{
...shared,
outDir: "dist-electron",
sourcemap: true,
entry: ["src/main.ts"],
clean: true,
noExternal: ["@t3tools/contracts"],
format: "esm",
},
{
...shared,
outDir: "dist-electron",
sourcemap: true,
entry: ["src/preload.ts"],
clean: true,
noExternal: ["@t3tools/contracts"],
format: "cjs",
},
]);
+1 -1
View File
@@ -17,12 +17,12 @@
"test": "vitest run"
},
"dependencies": {
"@t3tools/contracts": "workspace:*",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
+2 -4
View File
@@ -4,11 +4,9 @@
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const webDist = path.resolve(__dirname, "../../web/dist");
const target = path.resolve(__dirname, "../dist/client");
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
const target = path.resolve(import.meta.dirname, "../dist/client");
if (!fs.existsSync(webDist)) {
console.log(
+2 -5
View File
@@ -2,7 +2,6 @@ import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { fixPath } from "./fixPath";
import { createLogger } from "./logger";
@@ -72,11 +71,9 @@ async function findAvailablePort(preferred: number): Promise<number> {
}
function resolveStaticDir(): string | undefined {
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Check for bundled client (npm publish / npx scenario):
// dist/client/ lives alongside dist/index.js
const bundledClient = path.resolve(__dirname, "client");
const bundledClient = path.resolve(import.meta.dirname, "client");
try {
const stat = fs.statSync(path.join(bundledClient, "index.html"));
if (stat.isFile()) return bundledClient;
@@ -85,7 +82,7 @@ function resolveStaticDir(): string | undefined {
}
// Monorepo layout: apps/server/dist/index.js → apps/web/dist/
const monorepoClient = path.resolve(__dirname, "../../web/dist");
const monorepoClient = path.resolve(import.meta.dirname, "../../web/dist");
try {
const stat = fs.statSync(path.join(monorepoClient, "index.html"));
if (stat.isFile()) return monorepoClient;
+4 -1
View File
@@ -28,7 +28,10 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+shift+o", command: "chat.new" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+o", command: "editor.openFavorite" },
];
+3
View File
@@ -763,6 +763,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
if (pendingHistory !== undefined) {
this.pendingPersistHistory.delete(persistenceKey);
// oxlint-disable-next-line no-await-in-loop
await this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
}
@@ -770,6 +771,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
if (!pending) {
return;
}
// oxlint-disable-next-line no-await-in-loop
await pending.catch(() => undefined);
}
}
@@ -954,6 +956,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
// oxlint-disable-next-line unicorn/consistent-function-scoping
let release: () => void = () => {};
const current = new Promise<void>((resolve) => {
release = resolve;
+2 -1
View File
@@ -133,7 +133,7 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
this.sessions.delete(this.key(input.threadId, input.terminalId));
return;
}
for (const key of [...this.sessions.keys()]) {
for (const key of this.sessions.keys()) {
if (key.startsWith(`${input.threadId}\u0000`)) {
this.sessions.delete(key);
}
@@ -188,6 +188,7 @@ async function sendRequest(ws: WebSocket, method: string, params?: unknown): Pro
// Wait for response with matching id
while (true) {
// oxlint-disable-next-line no-await-in-loop
const parsed = (await waitForMessage(ws)) as Record<string, unknown>;
if (parsed.id === id) {
return parsed as WsResponse;
+20 -21
View File
@@ -69,6 +69,26 @@ function parseBooleanEnv(value: string | undefined): boolean | undefined {
return undefined;
}
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
socket.write(
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
"Connection: close\r\n" +
"Content-Type: text/plain\r\n" +
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
"\r\n" +
message,
);
socket.destroy();
}
const isServerNotRunningError = (error: unknown): boolean => {
if (!(error instanceof Error)) return false;
const maybeCode = (error as NodeJS.ErrnoException).code;
return (
maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running")
);
};
export function createServer(options: ServerOptions) {
const {
port,
@@ -197,18 +217,6 @@ export function createServer(options: ServerOptions) {
// WebSocket server — upgrades from the HTTP server
const wss = new WebSocketServer({ noServer: true });
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
socket.write(
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
"Connection: close\r\n" +
"Content-Type: text/plain\r\n" +
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
"\r\n" +
message,
);
socket.destroy();
}
httpServer.on("upgrade", (request, socket, head) => {
if (authToken) {
let providedToken: string | null = null;
@@ -452,15 +460,6 @@ export function createServer(options: ServerOptions) {
}
clients.clear();
const isServerNotRunningError = (error: unknown): boolean => {
if (!(error instanceof Error)) return false;
const maybeCode = (error as NodeJS.ErrnoException).code;
return (
maybeCode === "ERR_SERVER_NOT_RUNNING" ||
error.message.toLowerCase().includes("not running")
);
};
const closeWebSocketServer = new Promise<void>((resolve, reject) => {
wss.close((error) => {
if (error && !isServerNotRunningError(error)) {
-1
View File
@@ -6,7 +6,6 @@ export default defineConfig({
outDir: "dist",
sourcemap: true,
clean: true,
noExternal: ["@t3tools/contracts", "zod"],
inlineOnly: false,
banner: {
js: "#!/usr/bin/env node\n",
+1
View File
@@ -14,6 +14,7 @@
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-query": "^5.90.0",
"@tanstack/react-virtual": "^3.13.18",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
+19 -2
View File
@@ -124,12 +124,19 @@ function AutoProjectBootstrap() {
function DesktopProjectBootstrap() {
const api = useNativeApi();
const { dispatch } = useStore();
const { state, dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
if (!isElectron || !api || bootstrappedRef.current) return;
const perfAutomationSession =
new URLSearchParams(window.location.search).get("t3code_perf_automation") === "1";
if (perfAutomationSession) {
bootstrappedRef.current = true;
return;
}
let disposed = false;
let retryDelayMs = 500;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
@@ -138,6 +145,16 @@ function DesktopProjectBootstrap() {
try {
const projects = await api.projects.list();
if (disposed) return;
if (projects.length === 0 && (state.projects.length > 0 || state.threads.length > 0)) {
// Avoid wiping hydrated renderer state if the initial projects.list races
// backend startup and transiently returns no projects.
retryTimer = setTimeout(() => {
retryTimer = null;
void attemptBootstrap();
}, retryDelayMs);
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
return;
}
dispatch({
type: "SYNC_PROJECTS",
projects: projects.map((project) => ({
@@ -167,7 +184,7 @@ function DesktopProjectBootstrap() {
clearTimeout(retryTimer);
}
};
}, [api, dispatch]);
}, [api, dispatch, state.projects.length, state.threads.length]);
return null;
}
+1 -4
View File
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
import {
AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
isScrollContainerNearBottom,
} from "./chat-scroll";
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
describe("isScrollContainerNearBottom", () => {
it("returns true when already at bottom", () => {
+4 -1
View File
@@ -1,3 +1,4 @@
import { memo } from "react";
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight";
@@ -13,7 +14,7 @@ const markdownComponents: Components = {
},
};
export default function ChatMarkdown({ text }: ChatMarkdownProps) {
function ChatMarkdown({ text }: ChatMarkdownProps) {
return (
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
<ReactMarkdown
@@ -26,3 +27,5 @@ export default function ChatMarkdown({ text }: ChatMarkdownProps) {
</div>
);
}
export default memo(ChatMarkdown);
File diff suppressed because it is too large. Load diff
@@ -67,13 +67,13 @@ export function buildGitActionProgressStages(input: {
return [...commitStages, pushStage, "Creating PR..."];
}
const withDescription = (title: string, description: string | undefined) =>
description ? { title, description } : { title };
export function summarizeGitResult(result: GitRunStackedActionResult): {
title: string;
description?: string;
} {
const withDescription = (title: string, description: string | undefined) =>
description ? { title, description } : { title };
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
@@ -312,7 +312,10 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
title: resultToast.title,
description: resultToast.description,
timeout: 0,
data: threadToastData,
data: {
...threadToastData,
dismissAfterVisibleMs: 10_000,
},
...(shouldOfferPushCta
? {
actionProps: {
@@ -627,7 +630,8 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
: gitStatusForActions.aheadCount === 0 &&
gitStatusForActions.behindCount === 0
? "Up to date"
: gitStatusForActions.aheadCount > 0 && gitStatusForActions.behindCount > 0
: gitStatusForActions.aheadCount > 0 &&
gitStatusForActions.behindCount > 0
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
: gitStatusForActions.aheadCount > 0
? `Ahead by ${gitStatusForActions.aheadCount}`
+24 -8
View File
@@ -7,7 +7,7 @@ import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
import { isChatNewShortcut } from "../keybindings";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -140,7 +140,13 @@ export default function Sidebar() {
}, [state.threads]);
const handleNewThread = useCallback(
(projectId: string) => {
(
projectId: string,
options?: {
branch?: string | null;
worktreePath?: string | null;
},
) => {
dispatch({
type: "ADD_THREAD",
thread: {
@@ -166,8 +172,8 @@ export default function Sidebar() {
events: [],
error: null,
createdAt: new Date().toISOString(),
branch: null,
worktreePath: null,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
},
});
},
@@ -381,14 +387,23 @@ export default function Sidebar() {
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
if (!isChatNewShortcut(event, keybindings)) return;
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
if (isChatNewLocalShortcut(event, keybindings)) {
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId);
return;
}
if (!isChatNewShortcut(event, keybindings)) return;
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId);
handleNewThread(projectId, {
branch: activeThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? null,
});
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -490,6 +505,7 @@ export default function Sidebar() {
<button
key={thread.id}
type="button"
data-perf-thread-id={thread.id}
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 ${
isActive
? "bg-accent text-foreground"
@@ -1,5 +1,5 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import { type NativeApi } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
@@ -18,7 +18,7 @@ import {
preferredTerminalEditor,
resolvePathLinkTarget,
} from "../terminal-links";
import { isTerminalClearShortcut } from "../keybindings";
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -152,24 +152,29 @@ function TerminalViewport({
terminalRef.current = terminal;
fitAddonRef.current = fitAddon;
const sendClearShortcut = async () => {
const sendTerminalInput = async (data: string, fallbackError: string) => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
try {
await api.terminal.write({ threadId, terminalId, data: "\u000c" });
await api.terminal.write({ threadId, terminalId, data });
} catch (error) {
writeSystemMessage(
activeTerminal,
error instanceof Error ? error.message : "Failed to clear terminal",
);
writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
}
};
terminal.attachCustomKeyEventHandler((event) => {
const navigationData = terminalNavigationShortcutData(event);
if (navigationData !== null) {
event.preventDefault();
event.stopPropagation();
void sendTerminalInput(navigationData, "Failed to move cursor");
return false;
}
if (!isTerminalClearShortcut(event)) return true;
event.preventDefault();
event.stopPropagation();
void sendClearShortcut();
void sendTerminalInput("\u000c", "Failed to clear terminal");
return false;
});
@@ -363,7 +368,7 @@ function TerminalViewport({
fitAddonRef.current = null;
terminal.dispose();
};
}, [api, cwd, terminalId, threadId]);
}, [api, cwd, terminalId, threadId, autoFocus]);
useEffect(() => {
if (!autoFocus) return;
@@ -418,6 +423,7 @@ interface ThreadTerminalDrawerProps {
onNewTerminal: () => void;
splitShortcutLabel?: string | undefined;
newShortcutLabel?: string | undefined;
closeShortcutLabel?: string | undefined;
onActiveTerminalChange: (terminalId: string) => void;
onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void;
@@ -433,15 +439,9 @@ interface TerminalActionButtonProps {
function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
return (
<Popover>
<PopoverTrigger openOnHover
render={
<button
type="button"
className={className}
onClick={onClick}
aria-label={label}
/>
}
<PopoverTrigger
openOnHover
render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
>
{children}
</PopoverTrigger>
@@ -472,6 +472,7 @@ export default function ThreadTerminalDrawer({
onNewTerminal,
splitShortcutLabel,
newShortcutLabel,
closeShortcutLabel,
onActiveTerminalChange,
onCloseTerminal,
onHeightChange,
@@ -587,6 +588,9 @@ export default function ThreadTerminalDrawer({
),
[normalizedTerminalIds],
);
const closeTerminalActionLabel = closeShortcutLabel
? `Close Terminal (${closeShortcutLabel})`
: "Close Terminal";
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
@@ -698,7 +702,9 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal}
label={splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"}
label={
splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"
}
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
@@ -714,7 +720,7 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label="Close Terminal"
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
@@ -794,16 +800,14 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onNewTerminal}
label={
newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"
}
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
>
<Plus className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label="Close Terminal"
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
@@ -841,6 +845,9 @@ export default function ThreadTerminalDrawer({
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
const closeTerminalLabel = `Close ${
terminalLabelById.get(terminalId) ?? "terminal"
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
return (
<div
key={terminalId}
@@ -864,18 +871,30 @@ export default function ThreadTerminalDrawer({
</span>
</button>
{normalizedTerminalIds.length > 1 && (
<button
type="button"
className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={(event) => {
event.stopPropagation();
onCloseTerminal(terminalId);
}}
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
>
×
</button>
<Popover>
<PopoverTrigger
openOnHover
render={
<button
type="button"
className="inline-flex size-3.5 items-center justify-center rounded text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={() => onCloseTerminal(terminalId)}
aria-label={closeTerminalLabel}
/>
}
>
<XIcon className="size-2.5" />
</PopoverTrigger>
<PopoverPopup
tooltipStyle
side="bottom"
sideOffset={6}
align="center"
className="pointer-events-none select-none"
>
{closeTerminalLabel}
</PopoverPopup>
</Popover>
)}
</div>
);
+4 -1
View File
@@ -133,7 +133,10 @@ function CommandEmpty({ className, ...props }: React.ComponentProps<typeof Autoc
function CommandPanel({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className="-mx-px not-has-[+[data-slot=command-footer]]:-mb-px relative min-h-0 rounded-t-xl not-has-[+[data-slot=command-footer]]:rounded-b-2xl border border-b-0 bg-popover bg-clip-padding shadow-xs/5 [clip-path:inset(0_1px)] not-has-[+[data-slot=command-footer]]:[clip-path:inset(0_1px_1px_1px_round_0_0_calc(var(--radius-2xl)-1px)_calc(var(--radius-2xl)-1px))] before:pointer-events-none before:absolute before:inset-0 before:rounded-t-[calc(var(--radius-xl)-1px)] **:data-[slot=scroll-area-scrollbar]:mt-2"
className={cn(
"-mx-px not-has-[+[data-slot=command-footer]]:-mb-px relative min-h-0 rounded-t-xl not-has-[+[data-slot=command-footer]]:rounded-b-2xl border border-b-0 bg-popover bg-clip-padding shadow-xs/5 [clip-path:inset(0_1px)] not-has-[+[data-slot=command-footer]]:[clip-path:inset(0_1px_1px_1px_round_0_0_calc(var(--radius-2xl)-1px)_calc(var(--radius-2xl)-1px))] before:pointer-events-none before:absolute before:inset-0 before:rounded-t-[calc(var(--radius-xl)-1px)] **:data-[slot=scroll-area-scrollbar]:mt-2",
className,
)}
{...props}
/>
);
+1
View File
@@ -49,6 +49,7 @@ function SheetViewport({
side === "left" && "flex justify-start",
side === "right" && "flex justify-end",
variant === "inset" && "sm:p-4",
className,
)}
data-slot="sheet-viewport"
{...props}
@@ -0,0 +1,16 @@
import { assert, describe, it } from "vitest";
import { shouldHideCollapsedToastContent } from "./toast.logic";
describe("shouldHideCollapsedToastContent", () => {
it("keeps a single visible toast readable", () => {
assert.equal(shouldHideCollapsedToastContent(0, 1), false);
});
it("keeps the front-most toast readable in a visible stack", () => {
assert.equal(shouldHideCollapsedToastContent(0, 3), false);
});
it("hides non-front toasts until the stack is expanded", () => {
assert.equal(shouldHideCollapsedToastContent(1, 3), true);
});
});
@@ -0,0 +1,9 @@
export function shouldHideCollapsedToastContent(
visibleToastIndex: number,
visibleToastCount: number,
): boolean {
// Keep the front-most toast readable even if Base UI marks it as "behind"
// due to toasts hidden by thread filtering.
if (visibleToastCount <= 1) return false;
return visibleToastIndex > 0;
}
+190 -84
View File
@@ -1,6 +1,7 @@
"use client";
import { Toast } from "@base-ui/react/toast";
import { useEffect } from "react";
import {
CircleAlertIcon,
CircleCheckIcon,
@@ -12,14 +13,18 @@ import {
import { cn } from "~/lib/utils";
import { buttonVariants } from "~/components/ui/button";
import { useStore } from "~/store";
import { shouldHideCollapsedToastContent } from "./toast.logic";
type ThreadToastData = {
threadId?: string | null;
tooltipStyle?: boolean;
dismissAfterVisibleMs?: number;
};
const toastManager = Toast.createToastManager<ThreadToastData>();
const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
type ToastId = ReturnType<typeof toastManager.add>;
const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
const TOAST_ICONS = {
error: CircleAlertIcon,
@@ -50,6 +55,84 @@ function shouldRenderForActiveThread(
return toastThreadId === activeThreadId;
}
function ThreadToastVisibleAutoDismiss({
toastId,
dismissAfterVisibleMs,
}: {
toastId: ToastId;
dismissAfterVisibleMs: number | undefined;
}) {
useEffect(() => {
if (!dismissAfterVisibleMs || dismissAfterVisibleMs <= 0) return;
if (typeof window === "undefined" || typeof document === "undefined") return;
let remainingMs = threadToastVisibleTimeoutRemainingMs.get(toastId) ?? dismissAfterVisibleMs;
let startedAtMs: number | null = null;
let timeoutId: number | null = null;
let closed = false;
const clearTimer = () => {
if (timeoutId === null) return;
window.clearTimeout(timeoutId);
timeoutId = null;
};
const closeToast = () => {
if (closed) return;
closed = true;
threadToastVisibleTimeoutRemainingMs.delete(toastId);
toastManager.close(toastId);
};
const pause = () => {
if (startedAtMs === null) return;
remainingMs = Math.max(0, remainingMs - (Date.now() - startedAtMs));
startedAtMs = null;
clearTimer();
threadToastVisibleTimeoutRemainingMs.set(toastId, remainingMs);
};
const start = () => {
if (closed || startedAtMs !== null) return;
if (remainingMs <= 0) {
closeToast();
return;
}
startedAtMs = Date.now();
clearTimer();
timeoutId = window.setTimeout(() => {
remainingMs = 0;
startedAtMs = null;
closeToast();
}, remainingMs);
};
const syncTimer = () => {
const shouldRun = document.visibilityState === "visible" && document.hasFocus();
if (shouldRun) {
start();
return;
}
pause();
};
syncTimer();
document.addEventListener("visibilitychange", syncTimer);
window.addEventListener("focus", syncTimer);
window.addEventListener("blur", syncTimer);
return () => {
document.removeEventListener("visibilitychange", syncTimer);
window.removeEventListener("focus", syncTimer);
window.removeEventListener("blur", syncTimer);
pause();
clearTimer();
};
}, [dismissAfterVisibleMs, toastId]);
return null;
}
function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) {
return (
<Toast.Provider toastManager={toastManager} {...props}>
@@ -64,6 +147,18 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
const { toasts } = Toast.useToastManager<ThreadToastData>();
const activeThreadId = state.activeThreadId;
const isTop = position.startsWith("top");
const visibleToasts = toasts.filter((toast) =>
shouldRenderForActiveThread(toast.data, activeThreadId),
);
useEffect(() => {
const activeToastIds = new Set(toasts.map((toast) => toast.id));
for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) {
if (!activeToastIds.has(toastId)) {
threadToastVisibleTimeoutRemainingMs.delete(toastId);
}
}
}, [toasts]);
return (
<Toast.Portal data-slot="toast-portal">
@@ -81,96 +176,107 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
data-position={position}
data-slot="toast-viewport"
>
{toasts
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
.map((toast) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
{visibleToasts.map((toast, visibleIndex) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
const hideCollapsedContent = shouldHideCollapsedToastContent(
visibleIndex,
visibleToasts.length,
);
return (
<Toast.Root
return (
<Toast.Root
className={cn(
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
// Base positioning using data-position
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
"data-[position*=left]:right-auto data-[position*=left]:left-0",
"data-[position*=center]:right-0 data-[position*=center]:left-0",
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
// Gap fill for hover
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
"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))]",
// 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))]",
// Default state transform
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
// Limited state
"data-limited:opacity-0",
// Expanded state
"data-expanded:h-(--toast-height)",
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
// Starting and ending animations
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-[position*=top]:data-[position*=right]:data-starting-style:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:opacity-0",
// Ending animations (direction-aware)
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-[position*=top]:data-[position*=right]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
)}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<ThreadToastVisibleAutoDismiss
dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
toastId={toast.id}
/>
<Toast.Content
className={cn(
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
// Base positioning using data-position
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
"data-[position*=left]:right-auto data-[position*=left]:left-0",
"data-[position*=center]:right-0 data-[position*=center]:left-0",
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
// Gap fill for hover
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
"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))]",
// 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))]",
// Default state transform
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
// Limited state
"data-limited:opacity-0",
// Expanded state
"data-expanded:h-(--toast-height)",
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
// Starting and ending animations
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-ending-style:opacity-0",
// Ending animations (direction-aware)
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
"pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-expanded:opacity-100",
hideCollapsedContent &&
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
)}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-behind:not-data-expanded:pointer-events-none data-behind:opacity-0 data-expanded:opacity-100">
<div className="flex gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
data-slot="toast-icon"
>
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
</div>
)}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description
className="text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
{toast.actionProps && (
<Toast.Action
className={buttonVariants({ size: "xs" })}
data-slot="toast-action"
<div className="flex gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
data-slot="toast-icon"
>
{toast.actionProps.children}
</Toast.Action>
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
</div>
)}
</Toast.Content>
</Toast.Root>
);
})}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description
className="text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
{toast.actionProps && (
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action">
{toast.actionProps.children}
</Toast.Action>
)}
</Toast.Content>
</Toast.Root>
);
})}
</Toast.Viewport>
</Toast.Portal>
);
+1
View File
@@ -28,6 +28,7 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
document.documentElement.classList.toggle("dark", isDark);
if (suppressTransitions) {
// Force a reflow so the no-transitions class takes effect before removal
// oxlint-disable-next-line no-unused-expressions
document.documentElement.offsetHeight;
requestAnimationFrame(() => {
document.documentElement.classList.remove("no-transitions");
+114 -6
View File
@@ -9,12 +9,15 @@ import {
import {
formatShortcutLabel,
isChatNewShortcut,
isChatNewLocalShortcut,
isOpenFavoriteEditorShortcut,
isTerminalClearShortcut,
isTerminalCloseShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalToggleShortcut,
shortcutLabelForCommand,
terminalNavigationShortcutData,
type ShortcutEventLike,
} from "./keybindings";
@@ -82,14 +85,22 @@ const DEFAULT_BINDINGS = compile([
command: "terminal.new",
whenAst: whenIdentifier("terminalFocus"),
},
{
shortcut: modShortcut("w"),
command: "terminal.close",
whenAst: whenIdentifier("terminalFocus"),
},
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
]);
describe("isTerminalToggleShortcut", () => {
it("matches Cmd+J on macOS", () => {
assert.isTrue(
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, { platform: "MacIntel" }),
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
}),
);
});
@@ -100,8 +111,8 @@ describe("isTerminalToggleShortcut", () => {
});
});
describe("split/new terminal shortcuts", () => {
it("requires terminalFocus for default split/new bindings", () => {
describe("split/new/close terminal shortcuts", () => {
it("requires terminalFocus for default split/new/close bindings", () => {
assert.isFalse(
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
@@ -114,6 +125,12 @@ describe("split/new terminal shortcuts", () => {
context: { terminalFocus: false },
}),
);
assert.isFalse(
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: false },
}),
);
});
it("matches split/new when terminalFocus is true", () => {
@@ -129,6 +146,12 @@ describe("split/new terminal shortcuts", () => {
context: { terminalFocus: true },
}),
);
assert.isTrue(
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: true },
}),
);
});
it("supports when expressions", () => {
@@ -198,7 +221,10 @@ describe("shortcutLabelForCommand", () => {
whenAst: whenNot(whenIdentifier("terminalFocus")),
},
]);
assert.strictEqual(shortcutLabelForCommand(bindings, "terminal.split", "Linux"), "Ctrl+Shift+\\");
assert.strictEqual(
shortcutLabelForCommand(bindings, "terminal.split", "Linux"),
"Ctrl+Shift+\\",
);
});
it("returns labels for non-terminal commands", () => {
@@ -224,6 +250,19 @@ describe("chat/editor shortcuts", () => {
);
});
it("matches chat.newLocal shortcut", () => {
assert.isTrue(
isChatNewLocalShortcut(event({ key: "n", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
}),
);
assert.isTrue(
isChatNewLocalShortcut(event({ key: "n", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
}),
);
});
it("matches editor.openFavorite shortcut", () => {
assert.isTrue(
isOpenFavoriteEditorShortcut(event({ key: "o", metaKey: true }), DEFAULT_BINDINGS, {
@@ -302,11 +341,17 @@ describe("cross-command precedence", () => {
describe("formatShortcutLabel", () => {
it("formats labels for macOS", () => {
assert.strictEqual(formatShortcutLabel(modShortcut("d", { shiftKey: true }), "MacIntel"), "⇧⌘D");
assert.strictEqual(
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "MacIntel"),
"⇧⌘D",
);
});
it("formats labels for non-macOS", () => {
assert.strictEqual(formatShortcutLabel(modShortcut("d", { shiftKey: true }), "Linux"), "Ctrl+Shift+D");
assert.strictEqual(
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "Linux"),
"Ctrl+Shift+D",
);
});
it("formats labels for plus key", () => {
@@ -324,6 +369,69 @@ describe("isTerminalClearShortcut", () => {
it("matches Cmd+K on macOS", () => {
assert.isTrue(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel"));
});
it("ignores non-keydown events", () => {
assert.isFalse(
isTerminalClearShortcut(event({ type: "keyup", key: "l", ctrlKey: true }), "Linux"),
);
});
});
describe("terminalNavigationShortcutData", () => {
it("maps Option+Arrow on macOS to word movement", () => {
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowLeft", altKey: true }), "MacIntel"),
"\u001bb",
);
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowRight", altKey: true }), "MacIntel"),
"\u001bf",
);
});
it("maps Cmd+Arrow on macOS to line movement", () => {
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "MacIntel"),
"\u0001",
);
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowRight", metaKey: true }), "MacIntel"),
"\u0005",
);
});
it("maps Ctrl+Arrow on non-macOS to word movement", () => {
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowLeft", ctrlKey: true }), "Win32"),
"\u001bb",
);
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowRight", ctrlKey: true }), "Linux"),
"\u001bf",
);
});
it("rejects unsupported combinations", () => {
assert.isNull(
terminalNavigationShortcutData(
event({ key: "ArrowLeft", shiftKey: true, altKey: true }),
"MacIntel",
),
);
assert.isNull(
terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "Linux"),
);
assert.isNull(terminalNavigationShortcutData(event({ key: "a", altKey: true }), "MacIntel"));
});
it("ignores non-keydown events", () => {
assert.isNull(
terminalNavigationShortcutData(
event({ type: "keyup", key: "ArrowLeft", altKey: true }),
"MacIntel",
),
);
});
});
describe("plus key parsing", () => {
+65
View File
@@ -7,6 +7,7 @@ import {
import { isMacPlatform } from "./lib/utils";
export interface ShortcutEventLike {
type?: string;
key: string;
metaKey: boolean;
ctrlKey: boolean;
@@ -25,6 +26,11 @@ interface ShortcutMatchOptions {
context?: Partial<ShortcutMatchContext>;
}
const TERMINAL_WORD_BACKWARD = "\u001bb";
const TERMINAL_WORD_FORWARD = "\u001bf";
const TERMINAL_LINE_START = "\u0001";
const TERMINAL_LINE_END = "\u0005";
function normalizeEventKey(key: string): string {
const normalized = key.toLowerCase();
if (normalized === "esc") return "escape";
@@ -184,6 +190,14 @@ export function isTerminalNewShortcut(
return matchesCommandShortcut(event, keybindings, "terminal.new", options);
}
export function isTerminalCloseShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "terminal.close", options);
}
export function isChatNewShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
@@ -192,6 +206,14 @@ export function isChatNewShortcut(
return matchesCommandShortcut(event, keybindings, "chat.new", options);
}
export function isChatNewLocalShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "chat.newLocal", options);
}
export function isOpenFavoriteEditorShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
@@ -204,6 +226,10 @@ export function isTerminalClearShortcut(
event: ShortcutEventLike,
platform = navigator.platform,
): boolean {
if (event.type !== undefined && event.type !== "keydown") {
return false;
}
const key = event.key.toLowerCase();
if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
@@ -219,3 +245,42 @@ export function isTerminalClearShortcut(
!event.shiftKey
);
}
export function terminalNavigationShortcutData(
event: ShortcutEventLike,
platform = navigator.platform,
): string | null {
if (event.type !== undefined && event.type !== "keydown") {
return null;
}
if (event.shiftKey) return null;
const key = normalizeEventKey(event.key);
if (key !== "arrowleft" && key !== "arrowright") {
return null;
}
const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
if (isMacPlatform(platform)) {
if (event.altKey && !event.metaKey && !event.ctrlKey) {
return moveWord;
}
if (event.metaKey && !event.altKey && !event.ctrlKey) {
return moveLine;
}
return null;
}
if (event.ctrlKey && !event.metaKey && !event.altKey) {
return moveWord;
}
if (event.altKey && !event.metaKey && !event.ctrlKey) {
return moveWord;
}
return null;
}
+6 -1
View File
@@ -34,12 +34,12 @@
"t3": "./dist/index.mjs",
},
"dependencies": {
"@t3tools/contracts": "workspace:*",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0",
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
@@ -54,6 +54,7 @@
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-query": "^5.90.0",
"@tanstack/react-virtual": "^3.13.18",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
@@ -429,6 +430,10 @@
"@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.20" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg=="],
"@tanstack/react-virtual": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/virtual-core": "3.13.18" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-dZkhyfahpvlaV0rIKnvQiVoWPyURppl6w4m9IwMDpuIjcJ1sD9YGWrt0wISvgU7ewACXx2Ct46WPgI6qAD4v6A=="],
"@tanstack/virtual-core": ["@tanstack/[email protected]", "", {}, "sha512-Mx86Hqu1k39icq2Zusq+Ey2J6dDWTjDvEv43PJtRCoEYTLyfaPnxIQ6iy7YAOK0NV/qOEmZQ/uCufrppZxTgcg=="],
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
"@types/babel__core": ["@types/[email protected]", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
+2
View File
@@ -18,6 +18,8 @@
"lint": "oxlint --report-unused-disable-directives",
"test": "turbo run test",
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
"test:desktop-perf": "node scripts/desktop-perf-trace.mjs",
"test:desktop-perf:post": "node scripts/desktop-perf-trace.mjs --post-pr",
"fmt": "oxfmt",
"build:contracts": "turbo run build --filter=@t3tools/contracts"
},
@@ -14,6 +14,18 @@ describe("keybindings contracts", () => {
command: "terminal.toggle",
});
assert.strictEqual(parsed.command, "terminal.toggle");
const parsedClose = keybindingRuleSchema.parse({
key: "mod+w",
command: "terminal.close",
});
assert.strictEqual(parsedClose.command, "terminal.close");
const parsedLocal = keybindingRuleSchema.parse({
key: "mod+shift+n",
command: "chat.newLocal",
});
assert.strictEqual(parsedLocal.command, "chat.newLocal");
});
it("rejects invalid command values", () => {
+19 -13
View File
@@ -4,7 +4,9 @@ export const keybindingCommandSchema = z.enum([
"terminal.toggle",
"terminal.split",
"terminal.new",
"terminal.close",
"chat.new",
"chat.newLocal",
"editor.openFavorite",
]);
@@ -19,14 +21,16 @@ export const keybindingRuleSchema = z.object({
export const keybindingsConfigSchema = z.array(keybindingRuleSchema).max(256);
export const keybindingShortcutSchema = z.object({
key: z.string().trim().min(1).max(32),
metaKey: z.boolean(),
ctrlKey: z.boolean(),
shiftKey: z.boolean(),
altKey: z.boolean(),
modKey: z.boolean(),
}).strict();
export const keybindingShortcutSchema = z
.object({
key: z.string().trim().min(1).max(32),
metaKey: z.boolean(),
ctrlKey: z.boolean(),
shiftKey: z.boolean(),
altKey: z.boolean(),
modKey: z.boolean(),
})
.strict();
export type KeybindingWhenNode =
| { type: "identifier"; name: string }
@@ -57,11 +61,13 @@ export const keybindingWhenNodeSchema: z.ZodType<KeybindingWhenNode> = z.lazy(()
]),
);
export const resolvedKeybindingRuleSchema = z.object({
command: keybindingCommandSchema,
shortcut: keybindingShortcutSchema,
whenAst: keybindingWhenNodeSchema.optional(),
}).strict();
export const resolvedKeybindingRuleSchema = z
.object({
command: keybindingCommandSchema,
shortcut: keybindingShortcutSchema,
whenAst: keybindingWhenNodeSchema.optional(),
})
.strict();
export const resolvedKeybindingsConfigSchema = z.array(resolvedKeybindingRuleSchema).max(256);
+842
View File
@@ -0,0 +1,842 @@
import { spawn, execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const repoRoot = path.resolve(import.meta.dirname, "..");
const marker = "<!-- desktop-perf-trace-summary -->";
const defaultPerfProjects = [
{
id: "perf-project-1",
cwd: "/tmp/perf/codething-mvp",
name: "codething-mvp",
},
{
id: "perf-project-2",
cwd: "/tmp/perf/contracts-bench",
name: "contracts-bench",
},
];
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function parseArgs(argv) {
let postPr = false;
let seedPath = null;
for (let index = 2; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === "--post-pr") {
postPr = true;
continue;
}
if (arg === "--seed") {
const value = argv[index + 1];
if (!value || value.startsWith("--")) {
throw new Error("--seed requires a file path");
}
seedPath = value;
index += 1;
continue;
}
if (arg.startsWith("--seed=")) {
const value = arg.slice("--seed=".length).trim();
if (value.length === 0) {
throw new Error("--seed= requires a non-empty path");
}
seedPath = value;
continue;
}
throw new Error(`Unknown argument: ${arg}`);
}
return {
postPr,
seedPath,
};
}
function toMs(us) {
return us / 1000;
}
function round(n, digits = 3) {
return Number(n.toFixed(digits));
}
function mb(bytes) {
return bytes / (1024 * 1024);
}
function parseNumericEnv({ name, value, predicate, expectation, fallback }) {
if (typeof value !== "string") {
return null;
}
const raw = value.trim();
if (raw.length === 0) {
console.warn(
`[desktop-perf] invalid ${name}="${value}" (expected ${expectation}); using ${fallback}`,
);
return null;
}
const parsed = Number(raw);
if (Number.isFinite(parsed) && predicate(parsed)) {
return {
parsed,
raw,
};
}
console.warn(
`[desktop-perf] invalid ${name}="${value}" (expected ${expectation}); using ${fallback}`,
);
return null;
}
function resolveNonNegativeNumberEnv({ name, value, fallback }) {
const resolved = parseNumericEnv({
name,
value,
predicate: (parsed) => parsed >= 0,
expectation: "non-negative number",
fallback,
});
return resolved?.parsed ?? fallback;
}
function resolveNonNegativeIntegerEnv({ name, value, fallback }) {
const resolved = parseNumericEnv({
name,
value,
predicate: (parsed) => parsed >= 0,
expectation: "non-negative number",
fallback,
});
if (!resolved) {
return fallback;
}
const normalized = Math.trunc(resolved.parsed);
if (normalized !== resolved.parsed) {
console.warn(
`[desktop-perf] non-integer ${name}="${resolved.raw}" truncated to ${normalized} for consistency`,
);
}
return normalized;
}
function resolvePositiveIntegerEnv({ name, value, fallback }) {
const resolved = parseNumericEnv({
name,
value,
predicate: (parsed) => parsed > 0,
expectation: "positive number",
fallback,
});
if (!resolved) {
return fallback;
}
const normalized = Math.trunc(resolved.parsed);
if (normalized !== resolved.parsed) {
console.warn(
`[desktop-perf] non-integer ${name}="${resolved.raw}" truncated to ${normalized} for consistency`,
);
}
return normalized;
}
function summarizeTrace(tracePath) {
const payload = JSON.parse(fs.readFileSync(tracePath, "utf8"));
const events = payload.traceEvents;
const durationByName = new Map();
const dispatchRows = [];
const functionRows = [];
const userTiming = new Map();
const updateCounters = [];
for (const event of events) {
if (event.name === "UpdateCounters" && event.args?.data) {
const heap = event.args.data.jsHeapSizeUsed;
if (typeof heap === "number") {
updateCounters.push(heap);
}
}
if (event.cat === "blink.user_timing" && typeof event.name === "string") {
userTiming.set(event.name, (userTiming.get(event.name) ?? 0) + 1);
}
if (event.ph !== "X" || typeof event.dur !== "number" || typeof event.name !== "string") {
continue;
}
const byName = durationByName.get(event.name) ?? { count: 0, dur: 0, max: 0 };
byName.count += 1;
byName.dur += event.dur;
byName.max = Math.max(byName.max, event.dur);
durationByName.set(event.name, byName);
if (event.name === "EventDispatch") {
const type = event.args?.data?.type ?? "";
dispatchRows.push({ type, dur: event.dur });
}
if (event.name === "FunctionCall") {
const functionName = event.args?.data?.functionName ?? "(unknown)";
functionRows.push({ functionName, dur: event.dur });
}
}
const aggregateDispatchType = (type) => {
const rows = dispatchRows.filter((row) => row.type === type);
if (rows.length === 0) {
return {
count: 0,
totalMs: 0,
avgMs: 0,
maxMs: 0,
};
}
const totalDur = rows.reduce((sum, row) => sum + row.dur, 0);
const maxDur = rows.reduce((max, row) => Math.max(max, row.dur), 0);
return {
count: rows.length,
totalMs: round(toMs(totalDur)),
avgMs: round(toMs(totalDur / rows.length)),
maxMs: round(toMs(maxDur)),
};
};
const aggregateFunction = (name) => {
const rows = functionRows.filter((row) => row.functionName === name);
if (rows.length === 0) {
return {
count: 0,
totalMs: 0,
avgMs: 0,
maxMs: 0,
};
}
const totalDur = rows.reduce((sum, row) => sum + row.dur, 0);
const maxDur = rows.reduce((max, row) => Math.max(max, row.dur), 0);
return {
count: rows.length,
totalMs: round(toMs(totalDur)),
avgMs: round(toMs(totalDur / rows.length)),
maxMs: round(toMs(maxDur)),
};
};
const topUserTiming = [...userTiming.entries()]
.toSorted((a, b) => b[1] - a[1])
.slice(0, 10)
.map(([name, count]) => ({ name, count }));
const topDurationEvents = [...durationByName.entries()]
.map(([name, value]) => ({
name,
count: value.count,
totalMs: round(toMs(value.dur), 2),
avgMs: round(toMs(value.dur / value.count)),
maxMs: round(toMs(value.max)),
}))
.toSorted((a, b) => b.totalMs - a.totalMs)
.slice(0, 10);
const heap = (() => {
if (updateCounters.length === 0) return null;
const first = updateCounters[0];
const last = updateCounters[updateCounters.length - 1];
const min = Math.min(...updateCounters);
const max = Math.max(...updateCounters);
return {
firstMb: round(mb(first), 1),
lastMb: round(mb(last), 1),
minMb: round(mb(min), 1),
maxMb: round(mb(max), 1),
deltaMb: round(mb(last - first), 1),
};
})();
const longDispatchCount = dispatchRows.filter((row) => row.dur >= 50_000).length;
return {
keypress: aggregateDispatchType("keypress"),
textInput: aggregateDispatchType("textInput"),
input: aggregateDispatchType("input"),
keydown: aggregateDispatchType("keydown"),
dispatchDiscreteEvent: aggregateFunction("dispatchDiscreteEvent"),
performWorkUntilDeadline: aggregateFunction("performWorkUntilDeadline"),
longDispatchCount,
heap,
topUserTiming,
topDurationEvents,
};
}
const pad = (value, width) => String(value).padEnd(width, " ");
function createMarkdownSummary({ tracePath, donePayload, summary, thresholds }) {
const THREAD_COL_WIDTH = 8;
const TITLE_COL_WIDTH = 15;
const largeThreadRenderStats = Array.isArray(donePayload.interactions?.largeThreadRenderStats)
? donePayload.interactions.largeThreadRenderStats
: [];
const formatThreadRenderRow = (stat) => {
const threadShort =
typeof stat.threadId === "string" ? stat.threadId.slice(0, THREAD_COL_WIDTH) : "n/a";
const titleShort =
typeof stat.threadTitleShort === "string"
? stat.threadTitleShort
: typeof stat.threadId === "string"
? stat.threadId.slice(0, 15)
: "n/a";
const firstRenderMs =
typeof stat.firstRenderMs === "number"
? stat.firstRenderMs
: typeof stat.renderMs === "number"
? stat.renderMs
: "n/a";
const followUpRenderMs =
typeof stat.followUpRenderMs === "number" ? stat.followUpRenderMs : "n/a";
const followUpMinMs = typeof stat.followUpMinMs === "number" ? stat.followUpMinMs : "n/a";
const followUpMaxMs = typeof stat.followUpMaxMs === "number" ? stat.followUpMaxMs : "n/a";
const followUpSampleCount =
typeof stat.followUpSampleCount === "number" ? stat.followUpSampleCount : "n/a";
const deltaMs = typeof stat.deltaMs === "number" ? stat.deltaMs : "n/a";
const deltaPct = typeof stat.deltaPct === "number" ? stat.deltaPct : "n/a";
const followUpRange =
typeof followUpMinMs === "number" && typeof followUpMaxMs === "number"
? `${followUpMinMs}-${followUpMaxMs} (${followUpSampleCount}x)`
: "n/a";
return `| ${pad(threadShort, THREAD_COL_WIDTH)} | ${pad(titleShort, TITLE_COL_WIDTH)} | ${stat.messageCount} | ${firstRenderMs} | ${followUpRenderMs} | ${followUpRange} | ${deltaMs} | ${deltaPct}% |`;
};
const seedSource =
donePayload.seed?.source === "file"
? `file (\`${donePayload.seed?.path ?? "unknown"}\`)`
: (donePayload.seed?.source ?? "generated");
const lines = [
marker,
"## Desktop Dev Perf Trace",
"",
`- Command: \`bun dev:desktop\``,
`- Trace: \`${tracePath}\``,
`- Started: ${donePayload.startedAt ?? "n/a"}`,
`- Completed: ${donePayload.completedAt ?? "n/a"}`,
`- Duration: ${donePayload.durationMs ?? "n/a"} ms`,
`- Seed source: ${seedSource}`,
"",
"### Interaction Run",
"",
`- Thread clicks: ${donePayload.interactions?.threadClicks ?? "n/a"}`,
`- Typed chars: ${donePayload.interactions?.typedChars ?? "n/a"}`,
`- Benchmark thread ids exercised: ${
Array.isArray(donePayload.interactions?.benchmarkThreadIds) &&
donePayload.interactions.benchmarkThreadIds.length > 0
? donePayload.interactions.benchmarkThreadIds.join(", ")
: "none"
}`,
`- Model selected: ${donePayload.interactions?.selectedModel ?? "n/a"}`,
`- Terminal opened by shortcut: ${donePayload.interactions?.terminal?.openedByShortcut ?? "n/a"}`,
`- Terminal shortcut modifier: ${donePayload.interactions?.terminal?.modifierUsed ?? "n/a"}`,
`- Terminal splits: ${donePayload.interactions?.terminal?.splitCount ?? "n/a"}`,
`- Terminal command executed: ${donePayload.interactions?.terminal?.commandFileTouched ?? "n/a"}`,
`- Terminal output observed: ${donePayload.interactions?.terminal?.commandEchoObserved ?? "n/a"}`,
`- Terminal marker: ${donePayload.interactions?.terminal?.commandMarker ?? "n/a"}`,
`- Terminal interactions enabled: ${donePayload.config?.runTerminalInteractions ?? "n/a"}`,
`- Optional renderer interactions enabled: ${donePayload.config?.runOptionalRendererInteractions ?? "n/a"}`,
`- Benchmark sweep enabled: ${donePayload.config?.runBenchmarkThreadSweep ?? "n/a"}`,
`- Benchmark follow-up pass count: ${donePayload.config?.benchmarkFollowUpPassCount ?? "n/a"}`,
"",
"### Threshold Config",
"",
`- keypress avg max: ${thresholds.maxKeypressAvgMs}ms`,
`- keypress max max: ${thresholds.maxKeypressMaxMs}ms`,
`- long EventDispatch spike cap: ${thresholds.maxLongDispatchCount}`,
"",
"### Benchmark Thread Render",
"",
"| Thread | Title (15) | Messages | First Nav (ms) | Follow-up Median (ms) | Follow-up Range | Delta (ms) | Delta (%) |",
"| --- | --- | ---: | ---: | ---: | --- | ---: | ---: |",
...(largeThreadRenderStats.length > 0
? largeThreadRenderStats.map((stat) => formatThreadRenderRow(stat))
: ["| n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a |"]),
"",
"### Input Event Metrics",
"",
"| Event | Count | Avg (ms) | Max (ms) | Total (ms) |",
"| --- | ---: | ---: | ---: | ---: |",
`| keypress | ${summary.keypress.count} | ${summary.keypress.avgMs} | ${summary.keypress.maxMs} | ${summary.keypress.totalMs} |`,
`| textInput | ${summary.textInput.count} | ${summary.textInput.avgMs} | ${summary.textInput.maxMs} | ${summary.textInput.totalMs} |`,
`| input | ${summary.input.count} | ${summary.input.avgMs} | ${summary.input.maxMs} | ${summary.input.totalMs} |`,
`| keydown | ${summary.keydown.count} | ${summary.keydown.avgMs} | ${summary.keydown.maxMs} | ${summary.keydown.totalMs} |`,
"",
"### Scheduler/Event Hotspots",
"",
`- dispatchDiscreteEvent: ${summary.dispatchDiscreteEvent.totalMs}ms total (${summary.dispatchDiscreteEvent.count} calls)`,
`- performWorkUntilDeadline: ${summary.performWorkUntilDeadline.totalMs}ms total (${summary.performWorkUntilDeadline.count} calls)`,
`- EventDispatch spikes >= 50ms: ${summary.longDispatchCount}`,
"",
"### Threshold Check",
"",
`- keypress avg <= ${thresholds.maxKeypressAvgMs}ms: ${
summary.keypress.avgMs <= thresholds.maxKeypressAvgMs ? "pass" : "fail"
}`,
`- keypress max <= ${thresholds.maxKeypressMaxMs}ms: ${
summary.keypress.maxMs <= thresholds.maxKeypressMaxMs ? "pass" : "fail"
}`,
`- long dispatch spikes <= ${thresholds.maxLongDispatchCount}: ${
summary.longDispatchCount <= thresholds.maxLongDispatchCount ? "pass" : "fail"
}`,
"",
];
if (summary.heap) {
lines.push("### Heap Counters", "");
lines.push(
`- first=${summary.heap.firstMb}MB, last=${summary.heap.lastMb}MB, min=${summary.heap.minMb}MB, max=${summary.heap.maxMb}MB, delta=${summary.heap.deltaMb}MB`,
"",
);
}
lines.push("### Top User Timing Marks", "");
for (const entry of summary.topUserTiming) {
lines.push(`- ${entry.count}x ${entry.name}`);
}
lines.push("", "### Top Duration Events", "");
for (const entry of summary.topDurationEvents) {
lines.push(
`- ${entry.name}: total=${entry.totalMs}ms, avg=${entry.avgMs}ms, max=${entry.maxMs}ms, count=${entry.count}`,
);
}
lines.push("");
return lines.join("\n");
}
async function waitForDoneFile(donePath, child, timeoutMs) {
const startedAt = Date.now();
while (Date.now() - startedAt < timeoutMs) {
if (fs.existsSync(donePath)) {
return JSON.parse(fs.readFileSync(donePath, "utf8"));
}
if (child.exitCode !== null) {
throw new Error(`desktop dev process exited early (code ${child.exitCode})`);
}
// oxlint-disable-next-line no-await-in-loop
await sleep(500);
}
throw new Error(`Timed out waiting for done marker at ${donePath}`);
}
function tailLogText(logChunks, lineCount = 120) {
const lines = logChunks.join("").split(/\r?\n/);
return lines.slice(-lineCount).join("\n").trim();
}
function inferDesktopPerfTimeoutHint(logChunks) {
const joined = logChunks.join("");
const lowered = joined.toLowerCase();
if (lowered.includes("waiting for bundles") && lowered.includes("outdated:")) {
return "Desktop bundles were present but older than desktop source files; dev bundler did not refresh outputs in time.";
}
if (lowered.includes("waiting for bundles") && lowered.includes("stale:")) {
return "Desktop bundles were detected as stale by startup freshness checks.";
}
if (lowered.includes("error while loading shared libraries")) {
return "Electron failed to start due missing Linux shared libraries.";
}
if (lowered.includes("setuid_sandbox_host.cc") || lowered.includes("chrome-sandbox")) {
return "Electron sandbox setup failed on Linux CI (setuid sandbox helper).";
}
if (lowered.includes("no usable sandbox")) {
return "Electron sandbox failed to initialize in CI.";
}
if (lowered.includes("port is already in use")) {
return "Dev server port collision prevented Electron from loading the renderer.";
}
if (!joined.includes("[desktop-perf]")) {
return "Desktop perf automation never started; Electron likely did not boot successfully.";
}
if (joined.includes("[desktop-perf]") && !joined.includes("[desktop-perf] trace recorded")) {
return "Desktop perf automation started but did not complete trace recording.";
}
return "Desktop perf automation timed out before writing the done marker.";
}
async function terminateProcessTree(child) {
if (child.exitCode !== null) return;
if (process.platform === "win32") {
try {
execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
} catch {
child.kill("SIGTERM");
}
return;
}
try {
process.kill(-child.pid, "SIGTERM");
} catch {
child.kill("SIGTERM");
}
await sleep(1_500);
if (child.exitCode === null) {
try {
process.kill(-child.pid, "SIGKILL");
} catch {
child.kill("SIGKILL");
}
}
}
function detectPrNumber() {
const githubRef = process.env.GITHUB_REF ?? "";
const match = githubRef.match(/refs\/pull\/(\d+)\//);
if (match?.[1]) {
return match[1];
}
return execFileSync("gh", ["pr", "view", "--json", "number", "--jq", ".number"], {
cwd: repoRoot,
encoding: "utf8",
}).trim();
}
function postSummaryToPr(summaryPath) {
const prNumber = detectPrNumber();
execFileSync(
"gh",
["pr", "comment", prNumber, "--body-file", summaryPath, "--edit-last", "--create-if-none"],
{
cwd: repoRoot,
stdio: "inherit",
},
);
}
function prepareDesktopPerfState(stateDir, perfProjects = defaultPerfProjects) {
fs.mkdirSync(stateDir, { recursive: true });
for (const project of perfProjects) {
try {
fs.mkdirSync(project.cwd, { recursive: true });
} catch {
// Some seeded paths may point to unavailable locations in CI; registry entries still work.
}
}
const now = new Date().toISOString();
fs.writeFileSync(
path.join(stateDir, "projects.json"),
JSON.stringify(
{
version: 1,
projects: perfProjects.map((project) => ({
id: project.id,
cwd: project.cwd,
name: project.name,
createdAt: now,
updatedAt: now,
})),
},
null,
2,
),
);
}
function resolveSeedPath(seedPathArg) {
const candidateArg = seedPathArg ?? process.env.T3CODE_DESKTOP_PERF_SEED_PATH ?? "";
if (!candidateArg || candidateArg.trim().length === 0) {
const defaultCandidates = ["scripts/perf-seed.json", "apps/desktop/scripts/perf-seed.json"];
for (const candidate of defaultCandidates) {
const resolved = path.resolve(repoRoot, candidate);
if (fs.existsSync(resolved)) {
return resolved;
}
}
return null;
}
const resolved = path.isAbsolute(candidateArg)
? candidateArg
: path.resolve(repoRoot, candidateArg);
if (!fs.existsSync(resolved)) {
throw new Error(`Seed file not found: ${resolved}`);
}
return resolved;
}
function normalizeProjectPathForRuntime(rawCwd, projectName, projectId, projectIndex) {
const attemptedPath = path.resolve(rawCwd);
try {
fs.mkdirSync(attemptedPath, { recursive: true });
return attemptedPath;
} catch {
const safeName = (projectName || projectId || `project-${projectIndex + 1}`)
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 48);
const fallbackPath = path.join(
os.tmpdir(),
"t3code-desktop-perf-seed-projects",
`${String(projectIndex + 1).padStart(2, "0")}-${safeName || "project"}`,
);
fs.mkdirSync(fallbackPath, { recursive: true });
return fallbackPath;
}
}
function materializeRuntimeSeed(seedPath, artifactsDir) {
const raw = JSON.parse(fs.readFileSync(seedPath, "utf8"));
if (!raw || typeof raw !== "object" || !Array.isArray(raw.projects)) {
return { runtimeSeedPath: seedPath, projects: null };
}
const rewrittenProjects = [];
let rewroteAnyProject = false;
for (let index = 0; index < raw.projects.length; index += 1) {
const project = raw.projects[index];
if (!project || typeof project !== "object") {
rewrittenProjects.push(project);
continue;
}
const id = typeof project.id === "string" ? project.id : "";
const name = typeof project.name === "string" ? project.name : "";
const cwd = typeof project.cwd === "string" ? project.cwd : "";
if (id.length === 0 || name.length === 0 || cwd.length === 0) {
rewrittenProjects.push(project);
continue;
}
const runtimeCwd = normalizeProjectPathForRuntime(cwd, name, id, index);
if (runtimeCwd !== cwd) {
rewroteAnyProject = true;
}
rewrittenProjects.push({
...project,
cwd: runtimeCwd,
});
}
if (!rewroteAnyProject) {
const projects = rewrittenProjects
.map((project) => {
if (!project || typeof project !== "object") return null;
const id = typeof project.id === "string" ? project.id : "";
const cwd = typeof project.cwd === "string" ? project.cwd : "";
const name = typeof project.name === "string" ? project.name : "";
if (id.length === 0 || cwd.length === 0 || name.length === 0) return null;
return { id, cwd, name };
})
.filter((project) => project !== null);
return {
runtimeSeedPath: seedPath,
projects: projects.length > 0 ? projects : null,
};
}
const runtimeSeedPath = path.join(artifactsDir, "perf-seed.runtime.json");
fs.writeFileSync(
runtimeSeedPath,
JSON.stringify(
{
...raw,
projects: rewrittenProjects,
},
null,
2,
),
);
const projects = rewrittenProjects
.map((project) => {
if (!project || typeof project !== "object") return null;
const id = typeof project.id === "string" ? project.id : "";
const cwd = typeof project.cwd === "string" ? project.cwd : "";
const name = typeof project.name === "string" ? project.name : "";
if (id.length === 0 || cwd.length === 0 || name.length === 0) return null;
return { id, cwd, name };
})
.filter((project) => project !== null);
return {
runtimeSeedPath,
projects: projects.length > 0 ? projects : null,
};
}
async function main() {
const args = parseArgs(process.argv);
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const artifactsDir = path.join(os.tmpdir(), "t3code-perf-artifacts", `desktop-dev-${timestamp}`);
fs.mkdirSync(artifactsDir, { recursive: true });
const tracePath = path.join(artifactsDir, "trace.json");
const donePath = path.join(artifactsDir, "done.json");
const summaryPath = path.join(artifactsDir, "summary.md");
const logPath = path.join(artifactsDir, "run.log");
const stateDir = path.join(artifactsDir, "state");
const seedPath = resolveSeedPath(args.seedPath);
const materializedSeed = seedPath ? materializeRuntimeSeed(seedPath, artifactsDir) : null;
const runtimeSeedPath = materializedSeed?.runtimeSeedPath ?? seedPath;
const seedProjects = materializedSeed?.projects ?? null;
if (seedPath && runtimeSeedPath && runtimeSeedPath !== seedPath) {
console.log(
`[desktop-perf] rewrote seed project cwd paths for runtime compatibility: ${runtimeSeedPath}`,
);
}
prepareDesktopPerfState(stateDir, seedProjects ?? defaultPerfProjects);
const maxKeypressAvgMs = resolveNonNegativeNumberEnv({
name: "T3CODE_PERF_MAX_KEYPRESS_AVG_MS",
value: process.env.T3CODE_PERF_MAX_KEYPRESS_AVG_MS,
fallback: 12,
});
const maxKeypressMaxMs = resolveNonNegativeNumberEnv({
name: "T3CODE_PERF_MAX_KEYPRESS_MAX_MS",
value: process.env.T3CODE_PERF_MAX_KEYPRESS_MAX_MS,
fallback: 24,
});
const maxLongDispatchCount = resolveNonNegativeIntegerEnv({
name: "T3CODE_PERF_MAX_LONG_DISPATCH_COUNT",
value: process.env.T3CODE_PERF_MAX_LONG_DISPATCH_COUNT,
fallback: 0,
});
const timeoutMs = resolvePositiveIntegerEnv({
name: "T3CODE_PERF_TIMEOUT_MS",
value: process.env.T3CODE_PERF_TIMEOUT_MS,
fallback: 420000,
});
console.log(
`[desktop-perf] thresholds: keypressAvg<=${maxKeypressAvgMs}ms, keypressMax<=${maxKeypressMaxMs}ms, longDispatch<=${maxLongDispatchCount}, timeoutMs=${timeoutMs}`,
);
const child = spawn("bun", ["dev:desktop"], {
cwd: repoRoot,
detached: process.platform !== "win32",
env: {
...process.env,
T3CODE_DESKTOP_PERF_AUTOMATION: "1",
T3CODE_DESKTOP_PERF_TRACE_OUT: tracePath,
T3CODE_DESKTOP_PERF_DONE_OUT: donePath,
...(runtimeSeedPath ? { T3CODE_DESKTOP_PERF_SEED_PATH: runtimeSeedPath } : {}),
T3CODE_DEV_INSTANCE: `desktop-perf-${timestamp}`,
T3CODE_LOG_WS_EVENTS: "0",
T3CODE_STATE_DIR: stateDir,
},
stdio: ["ignore", "pipe", "pipe"],
});
const logs = [];
const appendLog = (chunk) => {
const text = chunk.toString();
logs.push(text);
if (logs.length > 1200) {
logs.splice(0, logs.length - 1200);
}
fs.appendFileSync(logPath, text);
process.stdout.write(text);
};
child.stdout.on("data", appendLog);
child.stderr.on("data", appendLog);
let donePayload;
try {
donePayload = await waitForDoneFile(donePath, child, timeoutMs);
} catch (error) {
const baseMessage = error instanceof Error ? error.message : String(error);
const hint = inferDesktopPerfTimeoutHint(logs);
const logTail = tailLogText(logs);
throw new Error(
[
baseMessage,
`Hint: ${hint}`,
`Artifacts dir: ${artifactsDir}`,
`Run log: ${logPath}`,
logTail.length > 0 ? `Recent log tail:\n${logTail}` : "Recent log tail: <empty>",
].join("\n"),
{ cause: error },
);
} finally {
await terminateProcessTree(child);
}
if (!donePayload || donePayload.status !== "ok") {
throw new Error(
`Desktop perf automation failed. ${donePayload?.error ?? "No completion payload written."}`,
);
}
const interactionChecks = [];
const threadClicks = Number(donePayload.interactions?.threadClicks ?? 0);
const typedChars = Number(donePayload.interactions?.typedChars ?? 0);
if (threadClicks <= 0) {
interactionChecks.push("thread clicks");
}
if (typedChars <= 0) {
interactionChecks.push("typed chars");
}
if (interactionChecks.length > 0) {
throw new Error(
`Desktop perf automation completed without required scripted interactions: ${interactionChecks.join(", ")}`,
);
}
const summary = summarizeTrace(tracePath);
const markdown = createMarkdownSummary({
tracePath,
donePayload,
summary,
thresholds: {
maxKeypressAvgMs,
maxKeypressMaxMs,
maxLongDispatchCount,
},
});
fs.writeFileSync(summaryPath, markdown);
console.log(`\nPerf summary written to ${summaryPath}\n`);
console.log(markdown);
const thresholdFailures = [];
if (summary.keypress.avgMs > maxKeypressAvgMs) {
thresholdFailures.push(
`keypress avg ${summary.keypress.avgMs}ms exceeds ${maxKeypressAvgMs}ms`,
);
}
if (summary.keypress.maxMs > maxKeypressMaxMs) {
thresholdFailures.push(
`keypress max ${summary.keypress.maxMs}ms exceeds ${maxKeypressMaxMs}ms`,
);
}
if (summary.longDispatchCount > maxLongDispatchCount) {
thresholdFailures.push(
`long EventDispatch count ${summary.longDispatchCount} exceeds ${maxLongDispatchCount}`,
);
}
if (args.postPr) {
postSummaryToPr(summaryPath);
}
if (thresholdFailures.length > 0) {
throw new Error(`Performance thresholds failed:\n- ${thresholdFailures.join("\n- ")}`);
}
}
main().catch((error) => {
const message = error instanceof Error ? error.message : String(error);
console.error("\nDesktop perf trace test failed:\n" + message);
process.exit(1);
});
+7 -1
View File
@@ -5,13 +5,19 @@
"VITE_WS_URL",
"VITE_DEV_SERVER_URL",
"ELECTRON_RENDERER_PORT",
"ELECTRON_DISABLE_SANDBOX",
"T3CODE_LOG_WS_EVENTS",
"T3CODE_MODE",
"T3CODE_PORT",
"T3CODE_NO_BROWSER",
"T3CODE_STATE_DIR",
"T3CODE_AUTH_TOKEN",
"T3CODE_DESKTOP_WS_URL"
"T3CODE_DESKTOP_WS_URL",
"T3CODE_DESKTOP_PERF_AUTOMATION",
"T3CODE_DESKTOP_PERF_TRACE_OUT",
"T3CODE_DESKTOP_PERF_DONE_OUT",
"T3CODE_DESKTOP_PERF_SEED_PATH",
"T3CODE_ELECTRON_STARTUP_TIMEOUT_MS"
],
"tasks": {
"build": {