Compare commits

..
Author SHA1 Message Date
Julius MarmingeandClaude Opus 4.6 0a535ae07c Fix select trigger styling in dark mode and add open state highlight
Remove dark mode background bleed on select triggers and add accent
background when popup is open.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-09 01:13:25 -08:00
Julius Marminge 1377b3760f use them 2026-02-09 01:13:25 -08:00
Julius Marminge f7f5408814 init components 2026-02-09 01:12:01 -08:00
199 changed files with 4520 additions and 25254 deletions

No files matched your search

+2 -10
View File
@@ -8,7 +8,7 @@ on:
jobs:
quality:
name: Lint, Typecheck, Test, Build
name: Lint, Typecheck, Test
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -17,7 +17,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.3.9
bun-version: 1.1.38
- name: Cache Bun and Turbo
uses: actions/cache@v4
@@ -40,11 +40,3 @@ jobs:
- name: Test
run: bun run test
- name: Build desktop pipeline
run: bun run build:desktop
- 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
+1
View File
@@ -5,6 +5,7 @@ node_modules
*.log
*.tsbuildinfo
apps/*/dist
apps/*/dist-electron
packages/*/dist
.env
.env.local
@@ -1,74 +0,0 @@
# Branch/Environment Picker in ChatView Input
## Summary
Add a secondary toolbar below the ChatView input area (similar to Codex UI) that lets users select the target branch and environment mode (Local vs New worktree) before sending their first message.
## UX
- A toolbar appears **below** the input form (always visible when it's a git repo)
- Two controls:
1. **Environment mode** (left side): toggles between "Local" and "New worktree" — **locked after first message** (no longer clickable, just shows current mode as label)
2. **Branch picker** (right side): dropdown showing local branches — **always changeable**, even after messages are sent
- If not a git repo, the toolbar is hidden entirely (thread uses project cwd as-is)
## Changes
### 0. Install `@tanstack/react-query` in `apps/renderer`
Add dependency + wrap app in `QueryClientProvider`.
### 1. `apps/renderer/src/store.ts` — MODIFY
Add a new action to the reducer:
```ts
| { type: "SET_THREAD_BRANCH"; threadId: string; branch: string | null; worktreePath: string | null }
```
Reducer case updates `branch` and `worktreePath` on the thread.
### 2. `apps/renderer/src/components/ChatView.tsx` — MODIFY
**Fetch branches** via `useQuery`:
```ts
const branchQuery = useQuery({
queryKey: ["git-branches", activeProject?.cwd],
queryFn: () => api.git.listBranches({ cwd: activeProject!.cwd }),
enabled: !!activeProject,
});
```
**Local state:**
- `envMode: "local" | "worktree"` — environment mode (local component state)
**UI:** Below the `<form>`, render a toolbar bar (hidden if `!branchQuery.data?.isRepo`):
- Left side: env mode button ("Local" / "New worktree") — disabled after first message (locked in)
- Right side: branch dropdown from `branchQuery.data.branches`
- Both styled like existing model picker (small text, chevron, dropdown menus)
**Behavior:**
- Branch picker is always active — changing branch dispatches `SET_THREAD_BRANCH` immediately
- Env mode is only clickable when `activeThread.messages.length === 0`. After first message, it becomes a static label showing the locked-in mode
- On first send (`onSend`): if `envMode === "worktree"` and a branch is selected, call `api.git.createWorktree` before starting the session, then dispatch `SET_THREAD_BRANCH` with the worktreePath
- `ensureSession` already uses `activeThread.worktreePath ?? activeProject.cwd`
### Files to modify
1. `apps/renderer/package.json` — add `@tanstack/react-query`
2. `apps/renderer/src/main.tsx` (or App entry) — wrap in `QueryClientProvider`
3. `apps/renderer/src/store.ts` — add `SET_THREAD_BRANCH` action
4. `apps/renderer/src/components/ChatView.tsx` — branch/env picker UI with `useQuery`
## Verification
1. `turbo build` — compiles
2. Create a new thread → branch bar appears below input with "Local" + current branch
3. Change branch in dropdown → branch updates on thread
4. Toggle "New worktree" → send message → worktree created, session uses worktree cwd
5. After first message: env mode label locks to "Worktree" (not clickable), branch picker still works
6. Non-git project → no branch bar shown
-99
View File
@@ -1,99 +0,0 @@
# Git Flows Integration Tests
## Overview
Real integration tests that run actual git commands against temporary repos. No mocking.
## Step 1: Extract git functions into `apps/desktop/src/git.ts`
The git functions (`listGitBranches`, `createGitWorktree`, `removeGitWorktree`, `createGitBranch`, `checkoutGitBranch`, `initGitRepo`) and their helper `runTerminalCommand` are currently private in `main.ts`. Extract them into a new `apps/desktop/src/git.ts` module with named exports.
`main.ts` will import and re-use them — no behavior change, just moving code.
**Files modified:**
- `apps/desktop/src/git.ts` — new file with all git functions exported
- `apps/desktop/src/main.ts` — import from `./git` instead of defining inline
## Step 2: Create `apps/desktop/src/git.test.ts`
Integration tests using real temp git repos. Each test group creates a fresh temp directory with `git init`, makes commits, creates branches as needed, and cleans up after.
### Setup/teardown pattern
```ts
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
listGitBranches,
createGitBranch,
checkoutGitBranch,
createGitWorktree,
removeGitWorktree,
initGitRepo,
} from "./git";
// Helper: run a raw git command in a dir (for test setup, not under test)
// Helper: create an initial commit (git needs at least one commit for branches)
```
### Test groups
**1. initGitRepo**
- Creates a valid git repo in a temp dir
- listGitBranches reports `isRepo: true` after init
**2. listGitBranches**
- Returns `isRepo: false` for non-git directory
- Returns the current branch with `current: true`
- Sorts current branch first
- Lists multiple branches after creating them
- `isDefault` is false when no remote (no origin/HEAD)
**3. checkoutGitBranch**
- Checks out an existing branch (current flag moves)
- Throws when branch doesn't exist
- Throws when checkout would overwrite uncommitted changes (dirty working tree)
**4. createGitBranch**
- Creates a new branch (appears in listGitBranches)
- Throws when branch already exists
**5. createGitWorktree + removeGitWorktree**
- Creates a worktree directory at the expected path
- Worktree has the correct branch checked out
- Throws when branch is already checked out in another worktree
- removeGitWorktree cleans up the worktree
**6. Full flow: local branch checkout**
- init → commit → create branch → checkout → verify current
**7. Full flow: worktree creation from selected branch**
- init → commit → create branch → create worktree → verify worktree dir exists and has correct branch
**8. Full flow: thread switching simulation**
- init → commit → create branch-a, branch-b → checkout a → checkout b → checkout a → verify current matches
**9. Full flow: checkout conflict**
- init → commit → create branch → modify file (unstaged) → checkout other branch → expect error
## Verification
```bash
# Run the git integration tests
cd apps/desktop && bun run test
# Or just the git test file
npx vitest run apps/desktop/src/git.test.ts
```
-103
View File
@@ -1,103 +0,0 @@
# Git Flows Test Plan
## Overview
Add tests for git branch/worktree flows. Two files:
1. **Extend** `apps/renderer/src/store.test.ts` — reducer tests for `SET_THREAD_BRANCH`
2. **Create** `apps/renderer/src/git-flows.test.ts` — flow logic tests
All tests are pure Vitest unit tests (no React rendering). They test the reducer directly and simulate handler logic via sequential reducer dispatches + mocked API calls.
## File 1: `apps/renderer/src/store.test.ts` (extend)
Add `describe("SET_THREAD_BRANCH reducer")` with 6 tests:
- Sets branch + worktreePath atomically
- Clears both to null
- Updates branch while preserving worktreePath
- Does not affect other threads (multi-thread state)
- No-op for nonexistent thread id
- Does not mutate messages, error, or session fields
Uses existing `makeThread`, `makeState` factories.
## File 2: `apps/renderer/src/git-flows.test.ts` (new)
### Factories
- `makeThread()`, `makeState()`, `makeSession()` — same pattern as store.test.ts
- `makeBranch()` — creates `GitBranch` objects
- `makeMessage()` — creates `ChatMessage` objects
- `makeGitApi()` — returns `{ checkout, createWorktree, createBranch, listBranches }` with `vi.fn()` mocks
### Test groups (~30 tests total)
**1. Local branch checkout flow** (2 tests)
- Successful checkout → SET_THREAD_BRANCH updates branch
- Checkout failure → SET_ERROR, branch unchanged
**2. Thread branch conflict on send** (3 tests)
- Two threads maintain independent branch state after SET_ACTIVE_THREAD
- Branch state preserved through multiple thread switches + updates
- Checkout failure on thread switch sets error only on target thread
**3. Worktree creation on send** (5 tests)
- First message in worktree mode → createWorktree → SET_THREAD_BRANCH with worktreePath
- No worktree when messages already exist
- No worktree in local envMode
- No worktree when worktreePath already set
- createWorktree failure → SET_ERROR, send aborted, no messages pushed
**4. Env mode locking** (4 tests)
- envLocked=false when no messages
- envLocked=true with messages
- Transitions false→true after PUSH_USER_MESSAGE
- Remains true after SET_ERROR and UPDATE_SESSION
**5. Auto-fill current branch** (3 tests)
- Dispatches SET_THREAD_BRANCH when thread has no branch and current branch exists
- Does not overwrite existing branch
- No-op when no branch is marked current
**6. Default branch detection** (2 tests)
- isDefault flag on branch objects
- current and isDefault can be on different branches
**7. Branch creation + checkout** (3 tests)
- Successful create + checkout updates branch
- createBranch failure → error, branch unchanged
- checkout failure after successful create → error, branch unchanged
**8. Session CWD resolution** (3 tests)
- Uses worktreePath when available
- cwdOverride takes precedence over worktreePath
- Falls back to project cwd when no worktree
**9. Error handling patterns** (4 tests)
- SET_ERROR sets error on correct thread
- SET_ERROR with null clears error
- Error on one thread doesn't affect others
- Error cleared before successful branch operations
## Verification
```bash
# Run all renderer tests
cd apps/renderer && bun run test
# Run just the new test file
npx vitest run apps/renderer/src/git-flows.test.ts
# Run just the store tests
npx vitest run apps/renderer/src/store.test.ts
```
@@ -1,115 +0,0 @@
# Git Integration: Branch Picker + Worktrees
## Summary
Add git integration to let users start new threads from a specific branch, optionally creating a git worktree for isolated agent work.
## UX Flow
- **Left click** "+ New thread" → immediately creates a thread (current behavior, unchanged)
- **Right click** "+ New thread" → opens a context menu with git options:
- List of local branches → clicking one creates a thread on that branch (uses project cwd)
- Each branch has a "worktree" sub-option → creates a worktree, then creates thread with worktree as cwd
- When thread has a worktree, the agent session uses the worktree path as its cwd
- If git fails (not a repo), context menu shows "Not a git repository" disabled item
## Changes
### 1. `packages/contracts/src/git.ts` — CREATE
New Zod schemas and types:
- `gitListBranchesInputSchema` — `{ cwd: string }`
- `gitCreateWorktreeInputSchema` — `{ cwd: string, branch: string, path?: string }`
- `gitRemoveWorktreeInputSchema` — `{ cwd: string, path: string }`
- `gitBranchSchema` — `{ name: string, current: boolean }`
- Result types for each
### 2. `packages/contracts/src/ipc.ts` — MODIFY
- Add 3 IPC channels: `git:list-branches`, `git:create-worktree`, `git:remove-worktree`
- Add `git` namespace to `NativeApi` with `listBranches`, `createWorktree`, `removeWorktree`
### 3. `packages/contracts/src/index.ts` — MODIFY
- Add `export * from "./git"`
### 4. `apps/desktop/src/main.ts` — MODIFY
Add 3 IPC handlers + helper functions:
- `listGitBranches()` — runs `git branch --no-color`, parses output into `{ name, current }[]`
- `createGitWorktree()` — runs `git worktree add <path> <branch>`, defaults path to `../{repo}-worktrees/{branch}`
- `removeGitWorktree()` — runs `git worktree remove <path>`
Reuses existing `runTerminalCommand()`.
### 5. `apps/desktop/src/preload.ts` — MODIFY
Add `git` namespace with 3 `ipcRenderer.invoke` calls.
### 6. `apps/renderer/src/types.ts` — MODIFY
Add to `Thread`:
```
branch: string | null
worktreePath: string | null
```
### 7. `apps/renderer/src/persistenceSchema.ts` — MODIFY
- Add optional `branch`/`worktreePath` to persisted thread schema (`.nullable().optional()` for backwards compat)
- Add V3 schema, update union
- Update `hydrateThread` to default new fields to `null`
- Update `toPersistedState` to serialize new fields
### 8. `apps/renderer/src/store.ts` — MODIFY
- Update persisted state key to v3, keep v2 as legacy fallback
### 9. `apps/renderer/src/components/Sidebar.tsx` — MODIFY (main UI work)
- Keep existing left-click `handleNewThread` unchanged (immediate thread creation)
- Add `onContextMenu` handler to "+ New thread" buttons (both global and per-project)
- On right-click: fetch branches via `api.git.listBranches`, show a custom context menu
- Context menu items: branch names, each with a nested option to create with worktree
- Clicking a branch → creates thread with `branch` set, title = branch name
- Clicking "with worktree" → calls `api.git.createWorktree` first, then creates thread with `worktreePath`
- Show branch badge on thread list items
- If not a git repo, show "Not a git repository" as disabled menu item
Context menu component: a positioned `<div>` with `position: fixed` anchored to the click position, dismissed on click-outside or Escape. Follows the existing dropdown pattern from ChatView's model picker.
### 10. `apps/renderer/src/components/ChatView.tsx` — MODIFY
- Line 157: use `activeThread.worktreePath ?? activeProject.cwd` as session cwd
- Show branch/worktree badge in header bar
## Implementation Order
1. `packages/contracts/src/git.ts` (new schemas)
2. `packages/contracts/src/ipc.ts` + `index.ts` (wire up channels)
3. `apps/desktop/src/main.ts` (git command handlers)
4. `apps/desktop/src/preload.ts` (bridge methods)
5. `apps/renderer/src/types.ts` (Thread type update)
6. `apps/renderer/src/persistenceSchema.ts` + `store.ts` (persistence migration)
7. `apps/renderer/src/components/Sidebar.tsx` (branch picker UI)
8. `apps/renderer/src/components/ChatView.tsx` (worktree cwd + badge)
## Edge Cases
- **Not a git repo**: `git branch` fails → context menu shows "Not a git repository" disabled item
- **Branch has slashes**: `feature/foo` → worktree dir becomes `feature-foo`
- **Worktree exists**: git error surfaces to user via inline error message in context menu
- **No persistence breakage**: `.nullable().optional()` fields parse fine with old data
## Verification
1. `turbo build` — confirm contracts/desktop/renderer all compile
2. Launch app, add a project pointing to a git repo
3. Click "+ New thread" → verify branch list loads
4. Select a branch, click Start → thread created with branch in title
5. Enable worktree checkbox, pick branch, Start → verify worktree directory created on disk
6. Send a message in worktree thread → verify agent runs in worktree cwd
7. Add a non-git project → verify graceful error, can still create thread
-43
View File
@@ -1,43 +0,0 @@
# CLAUDE.md
## Project Snapshot
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
## Core Priorities
1. Performance first.
2. Reliability first.
3. Keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).
If a tradeoff is required, choose correctness and robustness over short-term convenience.
## Package Roles
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## Codex App Server (Important)
T3 Code is currently Codex-first. The server starts `codex app-server` (JSON-RPC over stdio) per provider session, then streams structured events to the browser through WebSocket push messages.
How we use it in this codebase:
- Session startup/resume and turn lifecycle are brokered in `apps/server/src/codexAppServerManager.ts`.
- Provider dispatch and thread event logging are coordinated in `apps/server/src/providerManager.ts`.
- WebSocket server routes NativeApi methods in `apps/server/src/wsServer.ts`.
- Web app consumes provider event streams via WebSocket push on channel `providers.event`.
Docs:
- Codex App Server docs: https://developers.openai.com/codex/sdk/#app-server
## Reference Repos
- Open-source Codex repo: https://github.com/openai/codex
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
-1
View File
@@ -1 +0,0 @@
AGENTS.md
-101
View File
@@ -1,101 +0,0 @@
# Keybindings
T3 Code reads keybindings from:
- `~/.t3/keybindings.json`
The file must be a JSON array of rules:
```json
[
{ "key": "mod+g", "command": "terminal.toggle" },
{ "key": "mod+shift+g", "command": "terminal.new", "when": "terminalFocus" }
]
```
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
## Defaults
```json
[
{ "key": "mod+j", "command": "terminal.toggle" },
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "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" }
]
```
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
## Configuration
### Rule Shape
Each entry supports:
- `key` (required): shortcut string, like `mod+j`, `ctrl+k`, `cmd+shift+d`
- `command` (required): action ID
- `when` (optional): boolean expression controlling when the shortcut is active
Invalid rules are ignored. Invalid config files are ignored. Warnings are logged by the server.
### Available Commands
- `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)
- `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
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
### Key Syntax
Supported modifiers:
- `mod` (`cmd` on macOS, `ctrl` on non-macOS)
- `cmd` / `meta`
- `ctrl` / `control`
- `shift`
- `alt` / `option`
Examples:
- `mod+j`
- `mod+shift+d`
- `ctrl+l`
- `cmd+k`
### `when` Conditions
Currently available context keys:
- `terminalFocus`
- `terminalOpen`
Supported operators:
- `!` (not)
- `&&` (and)
- `||` (or)
- parentheses: `(` `)`
Examples:
- `"when": "terminalFocus"`
- `"when": "terminalOpen && !terminalFocus"`
- `"when": "terminalFocus || terminalOpen"`
Unknown condition keys evaluate to `false`.
### Precedence
- Rules are evaluated in array order.
- For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins.
- That means precedence is across commands, not only within the same command.
+44 -84
View File
@@ -1,107 +1,67 @@
# T3 Code
# CodeThing (Electron + Vite + Bun)
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
CodeThing is a desktop shell for coding agents. This first implementation is:
Run `npx t3` in any project directory to launch the web interface.
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
## Architecture
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
1. Codex-first: connects to `codex app-server` and streams turn/item events.
2. Provider-ready: renderer speaks a provider abstraction so Claude Code can plug in later.
3. Typed end-to-end: contracts validate payloads at preload/main boundaries.
## Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
- `/apps/desktop`: Electron main + preload process, includes provider and Codex session managers.
- `/apps/renderer`: React + Vite UI for session control, conversation, and protocol event stream.
- `/packages/contracts`: shared Zod schemas + TypeScript types for IPC and provider events.
## Codex prerequisites
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
- Authenticate Codex before running CodeThing (for example via API key or ChatGPT auth supported by Codex).
- CodeThing starts the server via `codex app-server` per session.
## Quick start
## Security and boundary model
```bash
# Development (with hot reload)
bun run dev
- `nodeIntegration: false`
- `contextIsolation: true`
- `sandbox: true`
- Renderer talks only to `window.nativeApi` exposed by preload.
- Preload and main both validate inputs using shared Zod schemas.
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
bun run build
bun run start
# Or from any project directory after publishing:
npx t3
```
## Scripts
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
### Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5173`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
`sandbox: true` above is Electron renderer sandboxing. It is separate from Codex execution sandbox policy (`read-only`, `workspace-write`, `danger-full-access`) used when starting provider sessions.
## Runtime modes
T3 Code has a global runtime mode switch in the chat toolbar:
CodeThing has a global runtime mode switch in the sidebar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
- `Full access` (default): starts new sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- `Approval required`: starts new sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
## Provider architecture
Mode changes apply across all threads. Existing live sessions are restarted so old and new threads use the selected mode.
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
## Scripts
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for streaming provider events
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`, `providers.listSessions`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
- `bun run dev`: starts contract build/watch, renderer dev server, and Electron process.
- `bun run build`: builds contracts, renderer, and desktop bundles through Turbo.
- `bun run typecheck`: strict TypeScript checks for all packages.
- `bun run test`: runs workspace tests.
## CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
Optional:
- `ELECTRON_RENDERER_PORT=5180 bun run dev` if `5173` is already in use.
## Provider architecture
The renderer now depends on `nativeApi.providers.*`:
1. `startSession`
2. `sendTurn`
3. `interruptTurn`
4. `respondToRequest`
5. `stopSession`
6. `listSessions`
7. `onEvent`
Codex is the only implemented provider right now. `claudeCode` is reserved in contracts/UI but returns a not-implemented error in main-process dispatch.
+2 -21
View File
@@ -1,23 +1,4 @@
# TODO
## Small things
## TODO
- [ ] 1 click copy in codeblocks
- [x] Pasting/adding images to submit with prompts
- [ ] Only show last 10 threads for a given project
- [ ] Thread archiving
- [x] Selecting folder should instantly create project
- [ ] New projects should go on top
- [ ] Projects should be sorted by latest thread update
- [x] "Response" bar should ONLY appear on work completed
- [x] "Response" bar should ONLY appear above the FINAL message in a series
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
- [ ] Insta focus input on new thread creation
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
- [x] Making new thread should auto-focus input box
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
## Bigger things
- [ ] Queueing messages
- [ ] External runners (i.e. running the cli on a mac mini)
- [ ] Pasting/adding images to submit with prompts
-1
View File
@@ -1 +0,0 @@
dist-electron/
+10 -7
View File
@@ -1,27 +1,30 @@
{
"name": "@t3tools/desktop",
"name": "@acme/desktop",
"version": "0.0.0",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:bundle": "tsup --watch",
"dev:electron": "bun run scripts/dev-electron.mjs",
"build": "tsdown",
"build": "tsup",
"start": "electron dist-electron/main.js",
"postinstall": "electron-rebuild",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"test": "vitest run",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"electron": "33.4.11"
"@acme/contracts": "workspace:*",
"electron": "33.4.11",
"node-pty": "^1.0.0"
},
"devDependencies": {
"@electron/rebuild": "^3.7.0",
"@types/node": "^22.10.2",
"electronmon": "^2.0.2",
"tsdown": "^0.20.3",
"tsup": "^8.3.5",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
"wait-on": "^8.0.2"
}
}
+2 -10
View File
@@ -6,22 +6,14 @@ const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
const devServerUrl = `http://localhost:${port}`;
await waitOn({
resources: [
`tcp:${port}`,
"file:dist-electron/main.js",
"file:dist-electron/preload.js",
"file:../server/dist/index.mjs",
],
resources: [`tcp:${port}`, "file:dist-electron/main.js", "file:dist-electron/preload.js"],
});
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"], {
stdio: "inherit",
env: {
...childEnv,
...process.env,
VITE_DEV_SERVER_URL: devServerUrl,
},
});
+44 -17
View File
@@ -1,57 +1,84 @@
import { spawn } from "node:child_process";
/**
* Smoke test: builds desktop + renderer, launches Electron against the
* production bundle, waits for the renderer to confirm it loaded, then exits.
*
* Catches the two categories of regression we've hit:
* 1. Module resolution failures (preload can't find @acme/contracts, etc.)
* 2. CSP / script blocking (React fails to mount)
*
* The test works by injecting a tiny check via ELECTRON_ENABLE_LOGGING —
* Electron forwards renderer console.log to the main process stdout when
* that env var is set. We look for React's "Download the React DevTools"
* message as proof that React successfully mounted (it only fires after
* the first render). For production mode (no React DevTools message), we
* instead check that no fatal errors appeared.
*/
import { execSync, spawn } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, "../../..");
const desktopDir = resolve(__dirname, "..");
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
const mainJs = resolve(desktopDir, "dist-electron/main.js");
console.log("\nLaunching Electron smoke test...");
// ── Build first ──────────────────────────────────────────────────────
console.log("Building contracts + renderer + desktop...");
execSync("bun run build", { cwd: root, stdio: "inherit" });
// ── Launch Electron (production mode — no VITE_DEV_SERVER_URL) ──────
console.log("\nLaunching Electron (production mode)...");
const child = spawn(electronBin, [mainJs], {
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
VITE_DEV_SERVER_URL: "",
VITE_DEV_SERVER_URL: "", // ensure production path
ELECTRON_ENABLE_LOGGING: "1",
},
});
let output = "";
child.stdout.on("data", (chunk) => {
output += chunk.toString();
child.stdout.on("data", (d) => {
output += d.toString();
});
child.stderr.on("data", (chunk) => {
output += chunk.toString();
child.stderr.on("data", (d) => {
output += d.toString();
});
const timeout = setTimeout(() => {
const TIMEOUT_MS = 8_000;
const timer = setTimeout(() => {
child.kill();
}, 8_000);
}, TIMEOUT_MS);
child.on("exit", () => {
clearTimeout(timeout);
clearTimeout(timer);
// Fatal patterns that indicate broken builds
const fatalPatterns = [
"Cannot find module",
"MODULE_NOT_FOUND",
"Refused to execute",
"Refused to execute", // CSP blocking scripts
"can't detect preamble", // @vitejs/plugin-react failure
"Uncaught Error",
"Uncaught TypeError",
"Uncaught ReferenceError",
];
const failures = fatalPatterns.filter((pattern) => output.includes(pattern));
const failures = fatalPatterns.filter((p) => output.includes(p));
if (failures.length > 0) {
console.error("\nDesktop smoke test failed:");
for (const failure of failures) {
console.error(` - ${failure}`);
console.error("\n❌ Smoke test FAILED. Matched fatal patterns:");
for (const f of failures) {
console.error(` • ${f}`);
}
console.error("\nFull output:\n" + output);
console.error(`\nFull output:\n${output}`);
process.exit(1);
}
console.log("Desktop smoke test passed.");
console.log("✅ Smoke test passed — no fatal errors detected");
process.exit(0);
});
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";
import { classifyCodexStderrLine, normalizeCodexModelSlug } from "./codexAppServerManager";
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
});
it("ignores non-error structured codex logs", () => {
const line =
"2026-02-08T04:24:19.241256Z WARN codex_core::features: unknown feature key in config: skills";
expect(classifyCodexStderrLine(line)).toBeNull();
});
it("ignores known benign rollout path errors", () => {
const line =
"\u001b[2m2026-02-08T04:24:20.085687Z\u001b[0m \u001b[31mERROR\u001b[0m \u001b[2mcodex_core::rollout::list\u001b[0m: state db missing rollout path for thread 019c3b6c-46b8-7b70-ad23-82f824d161fb";
expect(classifyCodexStderrLine(line)).toBeNull();
});
it("keeps unknown structured errors", () => {
const line = "2026-02-08T04:24:20.085687Z ERROR codex_core::runtime: unrecoverable failure";
expect(classifyCodexStderrLine(line)).toEqual({
message: line,
});
});
it("keeps plain stderr messages", () => {
const line = "fatal: permission denied";
expect(classifyCodexStderrLine(line)).toEqual({
message: line,
});
});
});
describe("normalizeCodexModelSlug", () => {
it("maps 5.3 aliases to gpt-5.3-codex", () => {
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
expect(normalizeCodexModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
});
it("prefers codex id when model differs", () => {
expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe("gpt-5.3-codex");
});
it("keeps non-aliased models as-is", () => {
expect(normalizeCodexModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2");
});
});
@@ -11,8 +11,8 @@ import type {
ProviderSession,
ProviderSessionStartInput,
ProviderTurnStartResult,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/contracts";
} from "@acme/contracts";
import { normalizeModelSlug } from "@acme/contracts";
type PendingRequestKey = string;
@@ -26,7 +26,9 @@ interface PendingRequest {
interface PendingApprovalRequest {
requestId: string;
jsonRpcId: string | number;
method: "item/commandExecution/requestApproval" | "item/fileChange/requestApproval";
method:
| "item/commandExecution/requestApproval"
| "item/fileChange/requestApproval";
requestKind: ProviderRequestKind;
threadId?: string;
turnId?: string;
@@ -73,14 +75,6 @@ const BENIGN_ERROR_LOG_SNIPPETS = [
"state db missing rollout path for thread",
"state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
];
const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"not found",
"missing thread",
"no such thread",
"unknown thread",
"does not exist",
];
export function normalizeCodexModelSlug(
model: string | undefined | null,
preferredId?: string,
@@ -119,15 +113,6 @@ export function classifyCodexStderrLine(rawLine: string): { message: string } |
return { message: line };
}
export function isRecoverableThreadResumeError(error: unknown): boolean {
const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
if (!message.includes("thread/resume")) {
return false;
}
return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
}
export interface CodexAppServerManagerEvents {
event: [event: ProviderEvent];
}
@@ -174,8 +159,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
try {
await this.sendRequest(context, "initialize", {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
name: "codething_desktop",
title: "CodeThing Desktop",
version: "0.1.0",
},
capabilities: {
@@ -185,52 +170,17 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
this.writeMessage(context, { method: "initialized" });
const normalizedModel = normalizeCodexModelSlug(input.model);
const sessionOverrides = {
model: normalizedModel ?? null,
const threadStart = await this.sendRequest(context, "thread/start", {
model: null,
cwd: input.cwd ?? null,
approvalPolicy: input.approvalPolicy,
sandbox: input.sandboxMode,
};
const threadStartParams = {
...sessionOverrides,
experimentalRawEvents: false,
};
});
let threadOpenMethod: "thread/start" | "thread/resume" = "thread/start";
let threadOpenResponse: unknown;
if (input.resumeThreadId) {
try {
threadOpenMethod = "thread/resume";
threadOpenResponse = await this.sendRequest(context, "thread/resume", {
...sessionOverrides,
threadId: input.resumeThreadId,
});
} catch (error) {
if (!isRecoverableThreadResumeError(error)) {
throw error;
}
threadOpenMethod = "thread/start";
this.emitLifecycleEvent(
context,
"session/threadResumeFallback",
`Could not resume thread ${input.resumeThreadId}; started a new thread instead.`,
);
threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
}
} else {
threadOpenMethod = "thread/start";
threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
}
const threadOpenRecord = this.readObject(threadOpenResponse);
const threadId =
this.readString(this.readObject(threadOpenRecord, "thread"), "id") ??
this.readString(threadOpenRecord, "threadId");
const threadId = this.readString(this.readObject(threadStart)?.thread, "id");
if (!threadId) {
throw new Error(`${threadOpenMethod} response did not include a thread id.`);
throw new Error("thread/start response did not include a thread id.");
}
this.updateSession(context, {
@@ -257,38 +207,20 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
throw new Error("Session is missing a thread id.");
}
const turnInput: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
type: "text",
text: input.input,
text_elements: [],
});
}
for (const attachment of input.attachments ?? []) {
if (attachment.type === "image") {
turnInput.push({
type: "image",
url: attachment.dataUrl,
});
}
}
if (turnInput.length === 0) {
throw new Error("Turn input must include text or attachments.");
}
const turnStartParams: {
threadId: string;
input: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
input: Array<{ type: "text"; text: string; text_elements: [] }>;
model?: string;
effort?: string;
} = {
threadId: context.session.threadId,
input: turnInput,
input: [
{
type: "text",
text: input.input,
text_elements: [],
},
],
};
const normalizedModel = normalizeCodexModelSlug(input.model);
if (normalizedModel) {
@@ -730,7 +662,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
};
}
private requestKindForMethod(method: string): ProviderRequestKind | undefined {
private requestKindForMethod(
method: string,
): ProviderRequestKind | undefined {
if (method === "item/commandExecution/requestApproval") {
return "command";
}
-57
View File
@@ -1,57 +0,0 @@
import type { BrowserWindow } from "electron";
import { beforeEach, describe, expect, it, vi } from "vitest";
const { showMessageBoxMock } = vi.hoisted(() => ({
showMessageBoxMock: vi.fn(),
}));
vi.mock("electron", () => ({
dialog: {
showMessageBox: showMessageBoxMock,
},
}));
import { showDesktopConfirmDialog } from "./confirmDialog";
describe("showDesktopConfirmDialog", () => {
beforeEach(() => {
showMessageBoxMock.mockReset();
});
it("returns false and does not open a dialog for empty messages", async () => {
const result = await showDesktopConfirmDialog(" ", null);
expect(result).toBe(false);
expect(showMessageBoxMock).not.toHaveBeenCalled();
});
it("opens a dialog for the focused window and returns true on confirm", async () => {
const ownerWindow = { id: 1 } as BrowserWindow;
showMessageBoxMock.mockResolvedValue({ response: 1 });
const result = await showDesktopConfirmDialog("Delete worktree?", ownerWindow);
expect(result).toBe(true);
expect(showMessageBoxMock).toHaveBeenCalledWith(
ownerWindow,
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
it("opens an app-level dialog when there is no focused window", async () => {
showMessageBoxMock.mockResolvedValue({ response: 0 });
const result = await showDesktopConfirmDialog("Delete worktree?", null);
expect(result).toBe(false);
expect(showMessageBoxMock).toHaveBeenCalledWith(
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
});
-26
View File
@@ -1,26 +0,0 @@
import { type BrowserWindow, dialog } from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export async function showDesktopConfirmDialog(
message: string,
ownerWindow: BrowserWindow | null,
): Promise<boolean> {
const normalizedMessage = message.trim();
if (normalizedMessage.length === 0) {
return false;
}
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: CONFIRM_BUTTON_INDEX,
cancelId: 0,
noLink: true,
message: normalizedMessage,
};
const result = ownerWindow
? await dialog.showMessageBox(ownerWindow, options)
: await dialog.showMessageBox(options);
return result.response === CONFIRM_BUTTON_INDEX;
}
+1 -1
View File
@@ -13,6 +13,6 @@ export function fixPath(): void {
process.env.PATH = result;
}
} catch {
// Keep inherited PATH if shell lookup fails.
// Silently ignore — keep default PATH
}
}
+104
View File
@@ -0,0 +1,104 @@
import { describe, expect, it, vi } from "vitest";
import { withParsedArgs, withParsedPayload } from "./ipcHelpers";
describe("withParsedPayload", () => {
it("parses payload and passes typed input to handler", async () => {
const handler = vi.fn(async (_event: unknown, payload: { value: string }) =>
payload.value.toUpperCase(),
);
const wrapped = withParsedPayload(
{
parse(payload: unknown): { value: string } {
if (
!payload ||
typeof payload !== "object" ||
typeof (payload as { value?: unknown }).value !== "string"
) {
throw new Error("Invalid payload");
}
return { value: (payload as { value: string }).value };
},
},
handler,
);
const result = await wrapped({}, { value: "hello" });
expect(result).toBe("HELLO");
expect(handler).toHaveBeenCalledWith({}, { value: "hello" });
});
it("throws and does not call handler on invalid payload", async () => {
const handler = vi.fn(async () => "ok");
const wrapped = withParsedPayload(
{
parse(payload: unknown): { value: string } {
if (
!payload ||
typeof payload !== "object" ||
typeof (payload as { value?: unknown }).value !== "string"
) {
throw new Error("Invalid payload");
}
return { value: (payload as { value: string }).value };
},
},
handler,
);
expect(() => wrapped({}, { value: 123 })).toThrow();
expect(handler).not.toHaveBeenCalled();
});
});
describe("withParsedArgs", () => {
it("parses tuple arguments before invoking handler", () => {
const handler = vi.fn((_event: unknown, sessionId: string, data: string) => {
return `${sessionId}:${data}`;
});
const wrapped = withParsedArgs(
{
parse(args: unknown[]): [string, string] {
const [sessionId, data] = args;
if (typeof sessionId !== "string" || sessionId.length === 0) {
throw new Error("Invalid sessionId");
}
if (typeof data !== "string") {
throw new Error("Invalid data");
}
return [sessionId, data];
},
},
handler,
);
expect(wrapped({}, "abc", "input")).toBe("abc:input");
expect(handler).toHaveBeenCalledWith({}, "abc", "input");
});
it("throws and does not call handler when args are invalid", () => {
const handler = vi.fn();
const wrapped = withParsedArgs(
{
parse(args: unknown[]): [string, string] {
const [sessionId, data] = args;
if (typeof sessionId !== "string" || sessionId.length === 0) {
throw new Error("Invalid sessionId");
}
if (typeof data !== "string") {
throw new Error("Invalid data");
}
return [sessionId, data];
},
},
handler,
);
expect(() => wrapped({}, 123, "input")).toThrow();
expect(handler).not.toHaveBeenCalled();
});
});
+24
View File
@@ -0,0 +1,24 @@
type MaybePromise<T> = T | Promise<T>;
type Parser<T> = {
parse: (value: unknown) => T;
};
type ArgsParser<T extends unknown[]> = {
parse: (value: unknown[]) => T;
};
export function withParsedPayload<TPayload, TResult>(
schema: Parser<TPayload>,
handler: (event: unknown, payload: TPayload) => MaybePromise<TResult>,
): (event: unknown, payload: unknown) => MaybePromise<TResult> {
return (event, payload) => handler(event, schema.parse(payload));
}
export function withParsedArgs<TArgs extends unknown[], TResult>(
schema: ArgsParser<TArgs>,
handler: (event: unknown, ...args: TArgs) => MaybePromise<TResult>,
): (event: unknown, ...args: unknown[]) => MaybePromise<TResult> {
return (event, ...args) => {
const parsedArgs = schema.parse(args);
return handler(event, ...parsedArgs);
};
}
+294 -224
View File
@@ -1,208 +1,46 @@
import { spawn, type ChildProcess } from "node:child_process";
import { randomBytes } from "node:crypto";
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
fixPath();
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 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");
import { spawn } from "node:child_process";
import path from "node:path";
import { BrowserWindow, app, dialog, ipcMain, session, shell } from "electron";
import {
EDITORS,
IPC_CHANNELS,
type TerminalCommandInput,
type TerminalCommandResult,
agentConfigSchema,
agentSessionIdSchema,
newTodoInputSchema,
providerInterruptTurnInputSchema,
providerRespondToRequestInputSchema,
providerSendTurnInputSchema,
providerSessionStartInputSchema,
providerStopSessionInputSchema,
terminalCommandInputSchema,
todoIdSchema,
} from "@acme/contracts";
import { withParsedArgs, withParsedPayload } from "./ipcHelpers";
import { ProcessManager } from "./processManager";
import { ProviderManager } from "./providerManager";
import { TodoStore } from "./todoStore";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess | null = null;
let backendPort = 0;
let backendAuthToken = "";
let backendWsUrl = "";
let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
async function reserveLoopbackPort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.listen(0, "127.0.0.1", () => {
const address = probe.address();
const port = typeof address === "object" && address !== null ? address.port : 0;
probe.close(() => {
if (port > 0) {
resolve(port);
return;
}
reject(new Error("Failed to reserve backend port"));
});
});
probe.on("error", reject);
});
}
function backendEnv(): NodeJS.ProcessEnv {
return {
...process.env,
T3CODE_MODE: "desktop",
T3CODE_NO_BROWSER: "1",
T3CODE_PORT: String(backendPort),
T3CODE_STATE_DIR: STATE_DIR,
T3CODE_AUTH_TOKEN: backendAuthToken,
};
}
function scheduleBackendRestart(reason: string): void {
if (isQuitting || restartTimer) return;
const delayMs = Math.min(500 * 2 ** restartAttempt, 10_000);
restartAttempt += 1;
console.error(`[desktop] backend exited unexpectedly (${reason}); restarting in ${delayMs}ms`);
restartTimer = setTimeout(() => {
restartTimer = null;
startBackend();
}, delayMs);
}
function startBackend(): void {
if (isQuitting || backendProcess) return;
if (!fs.existsSync(BACKEND_ENTRY)) {
scheduleBackendRestart(`missing server entry at ${BACKEND_ENTRY}`);
return;
}
const child = spawn(process.execPath, [BACKEND_ENTRY], {
cwd: ROOT_DIR,
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
stdio: "inherit",
});
backendProcess = child;
child.once("spawn", () => {
restartAttempt = 0;
});
child.on("error", (error) => {
if (backendProcess === child) {
backendProcess = null;
}
scheduleBackendRestart(error.message);
});
child.on("exit", (code, signal) => {
if (backendProcess === child) {
backendProcess = null;
}
if (isQuitting) return;
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
scheduleBackendRestart(reason);
});
}
function stopBackend(): void {
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = null;
}
const child = backendProcess;
backendProcess = null;
if (!child) return;
if (!child.killed) {
child.kill("SIGTERM");
setTimeout(() => {
if (!child.killed) {
child.kill("SIGKILL");
}
}, 2_000).unref();
}
}
function registerIpcHandlers(): void {
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
const result = owner
? await dialog.showOpenDialog(owner, {
properties: ["openDirectory", "createDirectory"],
})
: await dialog.showOpenDialog({
properties: ["openDirectory", "createDirectory"],
});
if (result.canceled) return null;
return result.filePaths[0] ?? null;
});
ipcMain.removeHandler(CONFIRM_CHANNEL);
ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
if (typeof message !== "string") {
return false;
let todoStore: TodoStore;
const processManager = new ProcessManager();
const providerManager = new ProviderManager();
const agentWriteArgsParser = {
parse(args: unknown[]): [string, string] {
const [sessionId, data] = args;
if (typeof data !== "string") {
throw new Error("agent:write data must be a string");
}
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
return showDesktopConfirmDialog(message, owner);
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
if (!window) return null;
return new Promise<string | null>((resolve) => {
const menu = Menu.buildFromTemplate(
items.map((item) => ({
label: item.label,
click: () => resolve(item.id),
})),
);
menu.popup({
window,
callback: () => resolve(null),
});
});
});
ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
if (typeof rawUrl !== "string" || rawUrl.length === 0) {
return false;
}
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return false;
}
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
return false;
}
try {
await shell.openExternal(parsedUrl.toString());
return true;
} catch {
return false;
}
});
}
return [agentSessionIdSchema.parse(sessionId), data];
},
};
function createWindow(): BrowserWindow {
const window = new BrowserWindow({
@@ -223,53 +61,285 @@ function createWindow(): BrowserWindow {
});
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
window.once("ready-to-show", () => {
window.show();
});
setupEventForwarding(window);
if (isDevelopment) {
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
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);
return window;
}
window.on("closed", () => {
if (mainWindow === window) {
mainWindow = null;
}
});
void window.loadFile(path.join(__dirname, "../../renderer/dist/index.html"));
return window;
}
function registerIpcHandlers(): void {
// Todo handlers
ipcMain.handle(IPC_CHANNELS.todosList, async () => {
return todoStore.list();
});
ipcMain.handle(
IPC_CHANNELS.todosAdd,
withParsedPayload(newTodoInputSchema, async (_event, payload) => {
return todoStore.add(payload);
}),
);
ipcMain.handle(
IPC_CHANNELS.todosToggle,
withParsedPayload(todoIdSchema, async (_event, id) => {
return todoStore.toggle(id);
}),
);
ipcMain.handle(
IPC_CHANNELS.todosRemove,
withParsedPayload(todoIdSchema, async (_event, id) => {
return todoStore.remove(id);
}),
);
ipcMain.handle(IPC_CHANNELS.dialogPickFolder, async () => {
const owner = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];
const result = owner
? await dialog.showOpenDialog(owner, {
properties: ["openDirectory", "createDirectory"],
})
: await dialog.showOpenDialog({
properties: ["openDirectory", "createDirectory"],
});
if (result.canceled) return null;
return result.filePaths[0] ?? null;
});
// Terminal handlers
ipcMain.handle(
IPC_CHANNELS.terminalRun,
withParsedPayload(terminalCommandInputSchema, async (_event, payload) => {
return runTerminalCommand(payload);
}),
);
// Shell handlers
ipcMain.handle(
IPC_CHANNELS.shellOpenInEditor,
async (_event, cwd: string, editor: string) => {
if (!cwd) throw new Error("cwd is required");
const editorDef = EDITORS.find((e) => e.id === editor);
if (!editorDef) throw new Error(`Unknown editor: ${editor}`);
if (!editorDef.command) {
const error = await shell.openPath(cwd);
if (error) throw new Error(error);
return;
}
const child = spawn(editorDef.command, [cwd], {
detached: true,
stdio: "ignore",
});
child.on("error", () => {
/* ignore spawn failures for detached editors */
});
child.unref();
},
);
// Agent handlers
ipcMain.handle(
IPC_CHANNELS.agentSpawn,
withParsedPayload(agentConfigSchema, async (_event, config) => {
return processManager.spawn(config);
}),
);
ipcMain.handle(
IPC_CHANNELS.agentKill,
withParsedPayload(agentSessionIdSchema, async (_event, sessionId) => {
processManager.kill(sessionId);
}),
);
ipcMain.handle(
IPC_CHANNELS.agentWrite,
withParsedArgs(agentWriteArgsParser, async (_event, sessionId, data) => {
processManager.write(sessionId, data);
}),
);
// Provider handlers
ipcMain.handle(
IPC_CHANNELS.providerSessionStart,
withParsedPayload(providerSessionStartInputSchema, async (_event, payload) => {
return providerManager.startSession(payload);
}),
);
ipcMain.handle(
IPC_CHANNELS.providerTurnStart,
withParsedPayload(providerSendTurnInputSchema, async (_event, payload) => {
return providerManager.sendTurn(payload);
}),
);
ipcMain.handle(
IPC_CHANNELS.providerTurnInterrupt,
withParsedPayload(providerInterruptTurnInputSchema, async (_event, payload) => {
await providerManager.interruptTurn(payload);
}),
);
ipcMain.handle(
IPC_CHANNELS.providerRequestRespond,
withParsedPayload(
providerRespondToRequestInputSchema,
async (_event, payload) => {
await providerManager.respondToRequest(payload);
},
),
);
ipcMain.handle(
IPC_CHANNELS.providerSessionStop,
withParsedPayload(providerStopSessionInputSchema, async (_event, payload) => {
providerManager.stopSession(payload);
}),
);
ipcMain.handle(IPC_CHANNELS.providerSessionList, async () => {
return providerManager.listSessions();
});
}
async function runTerminalCommand(input: TerminalCommandInput): Promise<TerminalCommandResult> {
const shellPath =
process.platform === "win32"
? (process.env.ComSpec ?? "cmd.exe")
: (process.env.SHELL ?? "/bin/sh");
const args =
process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
return new Promise((resolve, reject) => {
const child = spawn(shellPath, args, {
cwd: input.cwd,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let timedOut = false;
const timeout = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
setTimeout(() => {
if (!child.killed) {
child.kill("SIGKILL");
}
}, 1_000).unref();
}, input.timeoutMs ?? 30_000);
child.stdout?.on("data", (chunk: Buffer) => {
stdout += chunk.toString();
});
child.stderr?.on("data", (chunk: Buffer) => {
stderr += chunk.toString();
});
child.on("error", (error) => {
clearTimeout(timeout);
reject(error);
});
child.on("close", (code, signal) => {
clearTimeout(timeout);
resolve({
stdout,
stderr,
code: code ?? null,
signal: signal ?? null,
timedOut,
});
});
});
}
function setupEventForwarding(window: BrowserWindow): void {
const onOutput = (chunk: unknown) => {
if (!window.isDestroyed()) {
window.webContents.send(IPC_CHANNELS.agentOutput, chunk);
}
};
const onExit = (exit: unknown) => {
if (!window.isDestroyed()) {
window.webContents.send(IPC_CHANNELS.agentExit, exit);
}
};
const onProviderEvent = (event: unknown) => {
if (!window.isDestroyed()) {
window.webContents.send(IPC_CHANNELS.providerEvent, event);
}
};
processManager.on("output", onOutput);
processManager.on("exit", onExit);
providerManager.on("event", onProviderEvent);
window.on("closed", () => {
processManager.off("output", onOutput);
processManager.off("exit", onExit);
providerManager.off("event", onProviderEvent);
});
}
function setupCSP(): void {
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
const csp = isDevelopment
? "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws://localhost:* http://localhost:*"
: "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'";
callback({
responseHeaders: {
...details.responseHeaders,
"Content-Security-Policy": [csp],
},
});
});
}
async function bootstrap(): Promise<void> {
backendPort = await reserveLoopbackPort();
backendAuthToken = randomBytes(24).toString("hex");
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
setupCSP();
todoStore = new TodoStore(path.join(app.getPath("userData"), "todos.json"));
await todoStore.init();
registerIpcHandlers();
startBackend();
mainWindow = createWindow();
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
}
app.on("before-quit", () => {
isQuitting = true;
stopBackend();
processManager.killAll();
providerManager.stopAll();
providerManager.dispose();
});
app.whenReady().then(() => {
void bootstrap();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
mainWindow = createWindow();
}
});
});
app.on("window-all-closed", () => {
+52 -13
View File
@@ -1,16 +1,55 @@
import { contextBridge, ipcRenderer } from "electron";
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 wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
import { IPC_CHANNELS, type NativeApi } from "@acme/contracts";
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
confirm: (message: string) => ipcRenderer.invoke(CONFIRM_CHANNEL, message) as Promise<boolean>,
showContextMenu: (items: { id: string; label: string }[]) =>
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
});
const nativeApi: NativeApi = {
todos: {
list: () => ipcRenderer.invoke(IPC_CHANNELS.todosList),
add: (input) => ipcRenderer.invoke(IPC_CHANNELS.todosAdd, input),
toggle: (id) => ipcRenderer.invoke(IPC_CHANNELS.todosToggle, id),
remove: (id) => ipcRenderer.invoke(IPC_CHANNELS.todosRemove, id),
},
dialogs: {
pickFolder: () => ipcRenderer.invoke(IPC_CHANNELS.dialogPickFolder),
},
terminal: {
run: (input) => ipcRenderer.invoke(IPC_CHANNELS.terminalRun, input),
},
agent: {
spawn: (config) => ipcRenderer.invoke(IPC_CHANNELS.agentSpawn, config),
kill: (sessionId) => ipcRenderer.invoke(IPC_CHANNELS.agentKill, sessionId),
write: (sessionId, data) => ipcRenderer.invoke(IPC_CHANNELS.agentWrite, sessionId, data),
onOutput: (callback) => {
const listener = (_event: Electron.IpcRendererEvent, chunk: unknown) =>
callback(chunk as Parameters<typeof callback>[0]);
ipcRenderer.on(IPC_CHANNELS.agentOutput, listener);
return () => ipcRenderer.removeListener(IPC_CHANNELS.agentOutput, listener);
},
onExit: (callback) => {
const listener = (_event: Electron.IpcRendererEvent, exit: unknown) =>
callback(exit as Parameters<typeof callback>[0]);
ipcRenderer.on(IPC_CHANNELS.agentExit, listener);
return () => ipcRenderer.removeListener(IPC_CHANNELS.agentExit, listener);
},
},
providers: {
startSession: (input) => ipcRenderer.invoke(IPC_CHANNELS.providerSessionStart, input),
sendTurn: (input) => ipcRenderer.invoke(IPC_CHANNELS.providerTurnStart, input),
interruptTurn: (input) => ipcRenderer.invoke(IPC_CHANNELS.providerTurnInterrupt, input),
respondToRequest: (input) => ipcRenderer.invoke(IPC_CHANNELS.providerRequestRespond, input),
stopSession: (input) => ipcRenderer.invoke(IPC_CHANNELS.providerSessionStop, input),
listSessions: () => ipcRenderer.invoke(IPC_CHANNELS.providerSessionList),
onEvent: (callback) => {
const listener = (_event: Electron.IpcRendererEvent, payload: unknown) =>
callback(payload as Parameters<typeof callback>[0]);
ipcRenderer.on(IPC_CHANNELS.providerEvent, listener);
return () => ipcRenderer.removeListener(IPC_CHANNELS.providerEvent, listener);
},
},
shell: {
openInEditor: (cwd: string, editor: string) =>
ipcRenderer.invoke(IPC_CHANNELS.shellOpenInEditor, cwd, editor),
},
};
contextBridge.exposeInMainWorld("nativeApi", nativeApi);
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { ProcessManager } from "./processManager";
describe("ProcessManager", () => {
it("can be instantiated", () => {
const pm = new ProcessManager();
expect(pm).toBeInstanceOf(ProcessManager);
});
it("spawns a process and receives output", async () => {
const pm = new ProcessManager();
const chunks: string[] = [];
const done = new Promise<void>((resolve) => {
pm.on("output", (chunk) => {
chunks.push(chunk.data);
});
pm.on("exit", () => {
resolve();
});
});
const sessionId = pm.spawn({ command: "echo", args: ["hello"] });
expect(typeof sessionId).toBe("string");
expect(sessionId.length).toBeGreaterThan(0);
await done;
expect(chunks.join("").trim()).toBe("hello");
});
it("can kill a spawned process", async () => {
const pm = new ProcessManager();
const exited = new Promise<number | null>((resolve) => {
pm.on("exit", (exit) => {
resolve(exit.code);
});
});
const sessionId = pm.spawn({ command: "sleep", args: ["10"] });
pm.kill(sessionId);
const code = await exited;
expect(code).not.toBe(0);
});
});
+144
View File
@@ -0,0 +1,144 @@
import { type ChildProcess, spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { EventEmitter } from "node:events";
import {
type AgentConfig,
type AgentExit,
type OutputChunk,
agentConfigSchema,
} from "@acme/contracts";
import type { IPty } from "node-pty";
export interface ProcessManagerEvents {
output: [chunk: OutputChunk];
exit: [exit: AgentExit];
}
export class ProcessManager extends EventEmitter<ProcessManagerEvents> {
private sessions = new Map<string, ChildProcess>();
private ptySessions = new Map<string, IPty>();
spawn(raw: AgentConfig): string {
const config = agentConfigSchema.parse(raw);
const sessionId = randomUUID();
if (config.usePty) {
return this.spawnPty(sessionId, config);
}
return this.spawnProcess(sessionId, config);
}
private spawnProcess(sessionId: string, config: AgentConfig): string {
const child = spawn(config.command, config.args, {
cwd: config.cwd,
env: config.env ? { ...process.env, ...config.env } : process.env,
stdio: ["pipe", "pipe", "pipe"],
});
this.sessions.set(sessionId, child);
child.stdout?.on("data", (data: Buffer) => {
this.emit("output", {
sessionId,
stream: "stdout",
data: data.toString(),
});
});
child.stderr?.on("data", (data: Buffer) => {
this.emit("output", {
sessionId,
stream: "stderr",
data: data.toString(),
});
});
child.on("exit", (code, signal) => {
this.sessions.delete(sessionId);
this.emit("exit", {
sessionId,
code: code ?? null,
signal: signal ?? null,
});
});
return sessionId;
}
private spawnPty(sessionId: string, config: AgentConfig): string {
const pty = require("node-pty") as typeof import("node-pty");
const ptyProcess = pty.spawn(config.command, config.args, {
name: "xterm-256color",
cols: 120,
rows: 30,
cwd: config.cwd ?? process.cwd(),
env: (config.env ? { ...process.env, ...config.env } : process.env) as Record<string, string>,
});
this.ptySessions.set(sessionId, ptyProcess);
ptyProcess.onData((data) => {
this.emit("output", {
sessionId,
stream: "stdout",
data,
});
});
ptyProcess.onExit(({ exitCode, signal }) => {
this.ptySessions.delete(sessionId);
this.emit("exit", {
sessionId,
code: exitCode,
signal: signal !== undefined ? String(signal) : null,
});
});
return sessionId;
}
write(sessionId: string, data: string): void {
const child = this.sessions.get(sessionId);
if (child) {
child.stdin?.write(data);
return;
}
const pty = this.ptySessions.get(sessionId);
if (pty) {
pty.write(data);
return;
}
throw new Error(`No session: ${sessionId}`);
}
kill(sessionId: string): void {
const child = this.sessions.get(sessionId);
if (child) {
child.kill();
return;
}
const pty = this.ptySessions.get(sessionId);
if (pty) {
pty.kill();
return;
}
}
killAll(): void {
for (const child of this.sessions.values()) {
child.kill();
}
this.sessions.clear();
for (const pty of this.ptySessions.values()) {
pty.kill();
}
this.ptySessions.clear();
}
}
@@ -16,7 +16,10 @@ describe("ProviderManager", () => {
method: string;
threadId: string;
}) => void;
threadLogStreams: Map<string, { writableEnded: boolean; destroyed: boolean }>;
threadLogStreams: Map<
string,
{ writableEnded: boolean; destroyed: boolean }
>;
};
internals.onCodexEvent({
id: "evt-1",
@@ -16,7 +16,7 @@ import {
providerSendTurnInputSchema,
providerSessionStartInputSchema,
providerStopSessionInputSchema,
} from "@t3tools/contracts";
} from "@acme/contracts";
import { CodexAppServerManager } from "./codexAppServerManager";
export interface ProviderManagerEvents {
@@ -87,7 +87,11 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
await this.codex.respondToRequest(input.sessionId, input.requestId, input.decision);
await this.codex.respondToRequest(
input.sessionId,
input.requestId,
input.decision,
);
}
stopSession(raw: ProviderStopSessionInput): void {
@@ -147,7 +151,10 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
private resolveThreadId(event: ProviderEvent): string | undefined {
const fromPayload = this.readThreadIdFromPayload(event.payload);
const threadId = event.threadId ?? fromPayload ?? this.sessionThreadIds.get(event.sessionId);
const threadId =
event.threadId ??
fromPayload ??
this.sessionThreadIds.get(event.sessionId);
if (threadId) {
this.sessionThreadIds.set(event.sessionId, threadId);
+106
View File
@@ -0,0 +1,106 @@
import { randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
import path from "node:path";
import {
type NewTodoInput,
type Todo,
newTodoInputSchema,
todoIdSchema,
todoListSchema,
} from "@acme/contracts";
export class TodoStore {
private todos: Todo[] = [];
private queue: Promise<void> = Promise.resolve();
public constructor(private readonly filePath: string) {}
public async init(): Promise<void> {
return this.runExclusive(async () => {
await fs.mkdir(path.dirname(this.filePath), { recursive: true });
try {
const raw = await fs.readFile(this.filePath, "utf8");
const parsed = todoListSchema.safeParse(JSON.parse(raw));
if (parsed.success) {
this.todos = parsed.data;
return;
}
} catch (error) {
if (!isNotFoundError(error)) {
throw error;
}
}
this.todos = [];
await this.persist();
});
}
public async list(): Promise<Todo[]> {
return this.runExclusive(async () => [...this.todos]);
}
public async add(input: NewTodoInput): Promise<Todo[]> {
return this.runExclusive(async () => {
const { title } = newTodoInputSchema.parse(input);
const todo: Todo = {
id: randomUUID(),
title,
completed: false,
createdAt: new Date().toISOString(),
};
this.todos = [todo, ...this.todos];
await this.persist();
return [...this.todos];
});
}
public async toggle(id: string): Promise<Todo[]> {
return this.runExclusive(async () => {
const parsedId = todoIdSchema.parse(id);
this.todos = this.todos.map((todo) =>
todo.id === parsedId ? { ...todo, completed: !todo.completed } : todo,
);
await this.persist();
return [...this.todos];
});
}
public async remove(id: string): Promise<Todo[]> {
return this.runExclusive(async () => {
const parsedId = todoIdSchema.parse(id);
this.todos = this.todos.filter((todo) => todo.id !== parsedId);
await this.persist();
return [...this.todos];
});
}
private async persist(): Promise<void> {
await fs.writeFile(this.filePath, JSON.stringify(this.todos, null, 2), "utf8");
}
private async runExclusive<T>(operation: () => Promise<T>): Promise<T> {
const next = this.queue.then(operation, operation);
this.queue = next.then(
() => undefined,
() => undefined,
);
return next;
}
}
function isNotFoundError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"code" in error &&
(error as { code?: string }).code === "ENOENT"
);
}
+2 -2
View File
@@ -3,7 +3,7 @@
"compilerOptions": {
"composite": true,
"types": ["node", "electron"],
"lib": ["ES2023", "DOM", "esnext.disposable"]
"lib": ["ES2023", "DOM"]
},
"include": ["src", "tsdown.config.ts"]
"include": ["src", "tsup.config.ts"]
}
-21
View File
@@ -1,21 +0,0 @@
import { defineConfig } from "tsdown";
const shared = {
format: "cjs" as const,
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".js" }),
};
export default defineConfig([
{
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: ["@t3tools/contracts"],
},
{
...shared,
entry: ["src/preload.ts"],
},
]);
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/main.ts", "src/preload.ts"],
format: "cjs",
outDir: "dist-electron",
sourcemap: true,
clean: true,
noExternal: ["@acme/contracts"],
});
-24
View File
@@ -1,24 +0,0 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist-electron/**"],
},
"dev": {
"dependsOn": ["t3#build"],
"persistent": true,
},
"start": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"persistent": true,
},
"smoke-test": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"outputs": [],
},
},
}
@@ -1,6 +1,6 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-mira",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
@@ -12,14 +12,12 @@
},
"iconLibrary": "lucide",
"rtl": false,
"menuColor": "default",
"menuAccent": "bold",
"aliases": {
"components": "~/components",
"utils": "~/lib/utils",
"ui": "~/components/ui",
"lib": "~/lib",
"hooks": "~/hooks"
"components": "#/components",
"utils": "#/lib/utils",
"ui": "#/components/ui",
"lib": "#/lib",
"hooks": "#/hooks"
},
"registries": {
"@coss": "https://coss.com/ui/r/{name}.json"
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Electron Todo</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
@@ -1,5 +1,5 @@
{
"name": "@t3tools/web",
"name": "@acme/renderer",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -11,15 +11,12 @@
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-query": "^5.90.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"@acme/contracts": "workspace:*",
"@base-ui/react": "^1.1.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"highlight.js": "^11.11.1",
"lucide-react": "^0.564.0",
"lucide-react": "^0.563.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
@@ -32,10 +29,10 @@
"@tailwindcss/vite": "^4.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^5.1.4",
"@vitejs/plugin-react": "^4.3.4",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"tailwindcss": "^4.0.0",
"typescript": "^5.7.3",
"vite": "^8.0.0-beta.12"
"vite": "^6.0.5"
}
}
+61
View File
@@ -0,0 +1,61 @@
import { useEffect, useMemo, useRef } from "react";
import ChatView from "./components/ChatView";
import DiffPanel from "./components/DiffPanel";
import Sidebar from "./components/Sidebar";
import { readNativeApi } from "./session-logic";
import { StoreProvider, useStore } from "./store";
function EventRouter() {
const api = useMemo(() => readNativeApi(), []);
const { dispatch } = useStore();
const activeAssistantItemRef = useRef<string | null>(null);
useEffect(() => {
if (!api) return;
return api.providers.onEvent((event) => {
dispatch({
type: "APPLY_EVENT",
event,
activeAssistantItemRef,
});
});
}, [api, dispatch]);
return null;
}
function Layout() {
const api = useMemo(() => readNativeApi(), []);
const { state } = useStore();
if (!api) {
return (
<div className="flex h-screen flex-col bg-background text-foreground">
<div className="drag-region h-[52px] shrink-0" />
<div className="flex flex-1 items-center justify-center">
<p className="text-sm text-muted-foreground">
Native bridge unavailable. Launch through Electron.
</p>
</div>
</div>
);
}
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<EventRouter />
<Sidebar />
<ChatView />
{state.diffOpen && <DiffPanel />}
</div>
);
}
export default function App() {
return (
<StoreProvider>
<Layout />
</StoreProvider>
);
}
@@ -1,4 +1,3 @@
import { memo } from "react";
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight";
@@ -14,7 +13,7 @@ const markdownComponents: Components = {
},
};
function ChatMarkdown({ text }: ChatMarkdownProps) {
export default function ChatMarkdown({ text }: ChatMarkdownProps) {
return (
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
<ReactMarkdown
@@ -27,5 +26,3 @@ function ChatMarkdown({ text }: ChatMarkdownProps) {
</div>
);
}
export default memo(ChatMarkdown);
+530
View File
@@ -0,0 +1,530 @@
import { ArrowUpIcon, LoaderCircleIcon, SquareIcon } from "lucide-react";
import {
type FormEvent,
type KeyboardEvent,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
DEFAULT_MODEL,
DEFAULT_REASONING,
MODEL_OPTIONS,
REASONING_OPTIONS,
resolveModelSlug,
} from "../model-logic";
import {
derivePhase,
deriveTimelineEntries,
deriveWorkLogEntries,
formatElapsed,
formatTimestamp,
readNativeApi,
} from "../session-logic";
import { useStore } from "../store";
import ChatMarkdown from "./ChatMarkdown";
import { Button } from "./ui/button";
import {
InputGroup,
InputGroupAddon,
InputGroupText,
InputGroupTextarea,
} from "./ui/input-group";
import {
Select,
SelectItem,
SelectPopup,
SelectTrigger,
SelectValue,
} from "./ui/select";
function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt);
return `${formatTimestamp(createdAt)} • ${duration}`;
}
function statusLabel(phase: string): string {
if (phase === "running") return "Thinking / working";
if (phase === "connecting") return "Connecting";
if (phase === "ready") return "Ready";
return "Disconnected";
}
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
if (tone === "error") return "text-destructive/50";
if (tone === "tool") return "text-muted-foreground";
if (tone === "thinking") return "text-muted-foreground/70";
return "text-muted-foreground/60";
}
export default function ChatView() {
const { state, dispatch } = useStore();
const api = useMemo(() => readNativeApi(), []);
const [prompt, setPrompt] = useState("");
const [isSending, setIsSending] = useState(false);
const [isConnecting, setIsConnecting] = useState(false);
const [selectedEffort, setSelectedEffort] =
useState<string>(DEFAULT_REASONING);
const [nowTick, setNowTick] = useState(() => Date.now());
const messagesEndRef = useRef<HTMLDivElement>(null);
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const activeProject = state.projects.find(
(p) => p.id === activeThread?.projectId,
);
const selectedModel = resolveModelSlug(
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
);
const phase = derivePhase(activeThread?.session ?? null);
const isWorking = phase === "running" || isSending || isConnecting;
const activeTurnId = activeThread?.session?.activeTurnId;
const nowIso = new Date(nowTick).toISOString();
const modelOptions = MODEL_OPTIONS;
const workLogEntries = useMemo(
() => deriveWorkLogEntries(activeThread?.events ?? [], activeTurnId),
[activeThread?.events, activeTurnId],
);
const assistantCompletionByItemId = useMemo(() => {
const map = new Map<string, string>();
const ordered = [...(activeThread?.events ?? [])].reverse();
for (const event of ordered) {
if (event.method !== "item/completed") continue;
if (!event.itemId) continue;
map.set(event.itemId, event.createdAt);
}
return map;
}, [activeThread?.events]);
const timelineEntries = useMemo(
() =>
deriveTimelineEntries(
activeThread?.messages ?? [],
isWorking ? workLogEntries : [],
),
[activeThread?.messages, isWorking, workLogEntries],
);
// Auto-scroll on new messages
const messageCount = activeThread?.messages.length ?? 0;
const workLogCount = workLogEntries.length;
// biome-ignore lint/correctness/useExhaustiveDependencies: trigger on message count change
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messageCount]);
// biome-ignore lint/correctness/useExhaustiveDependencies: auto-scroll while active work-log events stream in
useEffect(() => {
if (phase !== "running") return;
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [phase, workLogCount]);
useEffect(() => {
if (phase !== "running") return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 250);
return () => {
window.clearInterval(timer);
};
}, [phase]);
const ensureSession = async (): Promise<string | null> => {
if (!api || !activeThread || !activeProject) return null;
if (activeThread.session && activeThread.session.status !== "closed") {
return activeThread.session.sessionId;
}
setIsConnecting(true);
try {
const session = await api.providers.startSession({
provider: "codex",
cwd: activeProject.cwd || undefined,
model: selectedModel || undefined,
});
dispatch({
type: "UPDATE_SESSION",
threadId: activeThread.id,
session,
});
return session.sessionId;
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to connect.",
});
return null;
} finally {
setIsConnecting(false);
}
};
const onSend = async (e: FormEvent) => {
e.preventDefault();
if (!api || !activeThread || isSending || isConnecting) return;
const trimmed = prompt.trim();
if (!trimmed) return;
// Auto-title from first message
if (activeThread.messages.length === 0) {
const title =
trimmed.length > 50 ? `${trimmed.slice(0, 50)}...` : trimmed;
dispatch({
type: "SET_THREAD_TITLE",
threadId: activeThread.id,
title,
});
}
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: null,
});
dispatch({
type: "PUSH_USER_MESSAGE",
threadId: activeThread.id,
id: crypto.randomUUID(),
text: trimmed,
});
setPrompt("");
const sessionId = await ensureSession();
if (!sessionId) return;
setIsSending(true);
try {
await api.providers.sendTurn({
sessionId,
input: trimmed,
model: selectedModel || undefined,
effort: selectedEffort || undefined,
});
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to send message.",
});
} finally {
setIsSending(false);
}
};
const onInterrupt = async () => {
if (!api || !activeThread?.session) return;
await api.providers.interruptTurn({
sessionId: activeThread.session.sessionId,
turnId: activeThread.session.activeTurnId,
});
};
const onModelSelect = (model: string) => {
if (!activeThread) return;
dispatch({
type: "SET_THREAD_MODEL",
threadId: activeThread.id,
model: resolveModelSlug(model),
});
};
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void onSend(e as unknown as FormEvent);
}
};
// Empty state: no active thread
if (!activeThread) {
return (
<div className="flex flex-1 flex-col bg-background text-muted-foreground/60">
<div className="drag-region h-[52px] shrink-0" />
<div className="flex flex-1 items-center justify-center">
<div className="text-center">
<p className="text-sm">
Select a thread or create a new one to get started.
</p>
</div>
</div>
</div>
);
}
return (
<div className="flex flex-1 flex-col bg-background">
{/* Top bar */}
<header className="drag-region flex items-center justify-between border-b px-5 pt-[28px] pb-3">
<div className="flex items-center gap-3">
<h2 className="text-sm font-medium text-foreground">
{activeThread.title}
</h2>
{activeProject && (
<span className="rounded-full bg-accent px-2 py-0.5 text-[10px] text-muted-foreground/70">
{activeProject.name}
</span>
)}
</div>
<div className="flex items-center gap-3">
{/* Status indicator */}
<div
className={`inline-flex items-center gap-2 rounded-full border px-2.5 py-1 text-[10px] ${
phase === "running"
? "border-sky-400/35 bg-sky-500/8 text-sky-700 dark:text-sky-100"
: phase === "connecting"
? "border-amber-400/35 bg-amber-500/8 text-amber-700 dark:text-amber-100"
: phase === "ready"
? "border-emerald-400/35 bg-emerald-500/8 text-emerald-700 dark:text-emerald-100"
: "border-border bg-secondary text-muted-foreground"
}`}
>
<span className="relative inline-flex h-2.5 w-2.5">
{(phase === "running" || phase === "connecting") && (
<span
className={`absolute inline-flex h-full w-full animate-ping rounded-full ${
phase === "running" ? "bg-sky-300/70" : "bg-amber-300/70"
}`}
/>
)}
<span
className={`relative inline-flex h-2.5 w-2.5 rounded-full ${
phase === "running"
? "bg-sky-200"
: phase === "connecting"
? "bg-amber-200"
: phase === "ready"
? "bg-emerald-200"
: "bg-muted-foreground/40"
}`}
/>
</span>
<span>{statusLabel(phase)}</span>
</div>
{/* Diff toggle */}
<button
type="button"
className={`rounded-md px-2 py-1 text-[10px] transition-colors duration-150 ${
state.diffOpen
? "bg-accent text-accent-foreground"
: "text-muted-foreground/60 hover:text-muted-foreground"
}`}
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
Diff
</button>
</div>
</header>
{/* Error banner */}
{activeThread.error && (
<div className="mx-4 mt-3 rounded-lg border border-destructive/20 bg-destructive/10 px-3 py-2 text-xs text-destructive-foreground">
{activeThread.error}
</div>
)}
{/* Messages */}
<div className="flex-1 overflow-y-auto px-5 py-4">
{activeThread.messages.length === 0 && !isWorking ? (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/40">
Send a message to start the conversation.
</p>
</div>
) : (
<div className="mx-auto max-w-3xl space-y-4">
{timelineEntries.map((timelineEntry) =>
timelineEntry.kind === "work" ? (
<div
key={timelineEntry.id}
className="border-l-2 border-border/60 pl-4 py-1"
>
<p
className={`py-[2px] text-[12px] leading-relaxed ${workToneClass(timelineEntry.entry.tone)}`}
>
{timelineEntry.entry.detail ? (
<>
{timelineEntry.entry.label}
<span className="ml-1.5 font-mono text-[11px] opacity-60">
{timelineEntry.entry.detail}
</span>
</>
) : (
timelineEntry.entry.label
)}
</p>
</div>
) : (
<div key={timelineEntry.id}>
{timelineEntry.message.role === "user" ? (
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-accent px-4 py-3">
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
{timelineEntry.message.text}
</pre>
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/40">
{formatTimestamp(timelineEntry.message.createdAt)}
</p>
</div>
</div>
) : (
<div className="border-l-2 border-border pl-4">
<ChatMarkdown
text={
timelineEntry.message.text ||
(timelineEntry.message.streaming
? ""
: "(empty response)")
}
/>
{timelineEntry.message.streaming && (
<div className="pt-1.5">
<span className="inline-flex items-center gap-2 rounded-full border border-sky-400/25 bg-sky-500/8 px-2 py-0.5 text-[10px] text-sky-700/90 dark:text-sky-100/90">
<span className="inline-flex gap-1">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-500/80 dark:bg-sky-100/80" />
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-500/80 dark:bg-sky-100/80 [animation-delay:150ms]" />
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-500/80 dark:bg-sky-100/80 [animation-delay:300ms]" />
</span>
<span>Thinking</span>
</span>
</div>
)}
<p className="mt-1.5 text-[10px] text-muted-foreground/40">
{formatMessageMeta(
timelineEntry.message.createdAt,
timelineEntry.message.streaming
? formatElapsed(
timelineEntry.message.createdAt,
nowIso,
)
: formatElapsed(
timelineEntry.message.createdAt,
assistantCompletionByItemId.get(
timelineEntry.message.id,
),
),
)}
</p>
</div>
)}
</div>
),
)}
{isWorking && (
<div className="border-l-2 border-border/60 pl-4 py-1">
<div className="flex items-center pt-1">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-foreground/20 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-foreground/20 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-foreground/20 animate-pulse [animation-delay:400ms]" />
</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
)}
</div>
{/* Input bar */}
<div className="px-5 pb-4 pt-2">
<form onSubmit={onSend} className="mx-auto max-w-3xl">
<InputGroup className="rounded-[20px] before:rounded-[19px] **:[textarea]:max-h-[200px]">
<InputGroupTextarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
onKeyDown={onKeyDown}
placeholder={
phase === "disconnected"
? "Ask for follow-up changes"
: "Ask anything..."
}
disabled={isSending || isConnecting}
rows={2}
className="font-sans!"
/>
<InputGroupAddon align="block-end">
{/* Model picker */}
<Select
value={selectedModel}
onValueChange={(val) => val && onModelSelect(val)}
>
<SelectTrigger
size="sm"
className="w-auto min-w-0 border-0 shadow-none bg-transparent dark:bg-transparent before:hidden data-[popup-open]:bg-accent dark:data-[popup-open]:bg-accent"
>
<SelectValue />
</SelectTrigger>
<SelectPopup side="top" align="start">
{modelOptions.map((model) => (
<SelectItem key={model} value={model}>
{model}
</SelectItem>
))}
</SelectPopup>
</Select>
{/* Reasoning effort */}
<Select
value={selectedEffort}
onValueChange={(val) => val && setSelectedEffort(val)}
>
<SelectTrigger
size="sm"
className="w-auto min-w-0 border-0 shadow-none bg-transparent dark:bg-transparent before:hidden data-[popup-open]:bg-accent dark:data-[popup-open]:bg-accent capitalize"
>
<SelectValue />
</SelectTrigger>
<SelectPopup side="top" align="start">
{REASONING_OPTIONS.map((effort) => (
<SelectItem key={effort} value={effort}>
{effort.charAt(0).toUpperCase() + effort.slice(1)}
{effort === DEFAULT_REASONING ? " (default)" : ""}
</SelectItem>
))}
</SelectPopup>
</Select>
{activeProject && (
<InputGroupText className="ml-auto text-muted-foreground/40">
{activeProject.name}
</InputGroupText>
)}
{phase === "running" ? (
<Button
variant="destructive"
size="icon-sm"
className="rounded-full"
onClick={() => void onInterrupt()}
aria-label="Stop generation"
>
<SquareIcon className="size-3" />
</Button>
) : (
<Button
type="submit"
size="icon-sm"
className="rounded-full"
disabled={isSending || isConnecting || !prompt.trim()}
aria-label={
isConnecting
? "Connecting"
: isSending
? "Sending"
: "Send message"
}
>
{isConnecting || isSending ? (
<LoaderCircleIcon className="animate-spin" />
) : (
<ArrowUpIcon />
)}
</Button>
)}
</InputGroupAddon>
</InputGroup>
</form>
</div>
</div>
);
}
@@ -1,7 +1,4 @@
import { XIcon } from "lucide-react";
import { isElectron } from "../env";
import { useStore } from "../store";
import { Button } from "./ui/button";
export default function DiffPanel() {
const { dispatch } = useStore();
@@ -9,18 +6,17 @@ export default function DiffPanel() {
return (
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
{/* Header */}
<div
className={`flex items-center justify-between border-b border-border px-4 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
>
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
<Button
<div className="drag-region flex items-center justify-between border-b border-border px-4 pt-[28px] pb-3">
<h3 className="text-xs font-medium text-foreground">
Uncommitted changes
</h3>
<button
type="button"
size="icon-xs"
variant="ghost"
className="text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground"
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
<XIcon />
</Button>
<span className="text-sm">&times;</span>
</button>
</div>
{/* Placeholder content */}
@@ -31,11 +27,15 @@ export default function DiffPanel() {
<span className="rounded bg-emerald-500/20 px-1.5 py-0.5 text-[9px] font-medium text-emerald-400">
M
</span>
<span className="font-mono text-xs text-muted-foreground/80">src/App.tsx</span>
<span className="font-mono text-xs text-muted-foreground/80">
src/App.tsx
</span>
</div>
<div className="space-y-0.5 font-mono text-[11px]">
<div className="text-red-400/60">- const oldValue = "hello";</div>
<div className="text-emerald-400/60">+ const newValue = "world";</div>
<div className="text-emerald-400/60">
+ const newValue = "world";
</div>
</div>
</div>
@@ -44,7 +44,9 @@ export default function DiffPanel() {
<span className="rounded bg-blue-500/20 px-1.5 py-0.5 text-[9px] font-medium text-blue-400">
A
</span>
<span className="font-mono text-xs text-muted-foreground/80">src/utils.ts</span>
<span className="font-mono text-xs text-muted-foreground/80">
src/utils.ts
</span>
</div>
</div>
</div>
+279
View File
@@ -0,0 +1,279 @@
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
import { useMemo, useState } from "react";
import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL, MODEL_OPTIONS, resolveModelSlug } from "../model-logic";
import { readNativeApi } from "../session-logic";
import { useStore } from "../store";
import type { Project } from "../types";
function formatRelativeTime(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const minutes = Math.floor(diff / 60_000);
if (minutes < 1) return "just now";
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
export default function Sidebar() {
const { state, dispatch } = useStore();
const api = useMemo(() => readNativeApi(), []);
const { theme, setTheme } = useTheme();
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [newModel, setNewModel] = useState(DEFAULT_MODEL);
const [isPickingFolder, setIsPickingFolder] = useState(false);
const handleAddProject = () => {
const cwd = newCwd.trim();
if (!cwd) return;
const name = cwd.split("/").filter(Boolean).pop() ?? "project";
const normalizedModel = resolveModelSlug(newModel);
const project: Project = {
id: crypto.randomUUID(),
name,
cwd,
model: normalizedModel,
expanded: true,
};
dispatch({ type: "ADD_PROJECT", project });
setNewCwd("");
setNewModel(DEFAULT_MODEL);
setAddingProject(false);
};
const handleNewThread = (projectId: string) => {
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
projectId,
title: "New thread",
model:
state.projects.find((p) => p.id === projectId)?.model ??
DEFAULT_MODEL,
session: null,
messages: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
},
});
};
const handlePickFolder = async () => {
if (!api || isPickingFolder) return;
setIsPickingFolder(true);
try {
const pickedPath = await api.dialogs.pickFolder();
if (!pickedPath) return;
setNewCwd(pickedPath);
} finally {
setIsPickingFolder(false);
}
};
return (
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
{/* Drag region / traffic light space */}
<div className="drag-region h-[52px] shrink-0" />
{/* Branding */}
<div className="flex items-center gap-2 px-4 pb-4">
<div className="flex h-7 w-7 items-center justify-center rounded-lg bg-primary text-xs font-bold text-primary-foreground">
CT
</div>
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
CodeThing
</span>
<button
type="button"
className="rounded-md p-1.5 text-muted-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-muted-foreground"
onClick={() => setTheme(THEME_CYCLE[theme])}
aria-label={`Theme: ${theme}`}
title={`Theme: ${theme}`}
>
{theme === "system" ? (
<MonitorIcon className="size-3.5" />
) : theme === "light" ? (
<SunIcon className="size-3.5" />
) : (
<MoonIcon className="size-3.5" />
)}
</button>
</div>
{/* New thread (global) */}
<div className="px-3 pb-3">
<button
type="button"
className="flex w-full items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent"
onClick={() => {
if (state.projects.length === 0) {
setAddingProject(true);
return;
}
const firstProject = state.projects[0];
if (firstProject) handleNewThread(firstProject.id);
}}
>
<span className="text-foreground">+</span>
New thread
</button>
</div>
{/* Project list */}
<nav className="flex-1 overflow-y-auto px-2">
{state.projects.map((project) => {
const threads = state.threads.filter(
(t) => t.projectId === project.id,
);
return (
<div key={project.id} className="mb-1">
{/* Project header */}
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"
onClick={() =>
dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })
}
>
<span className="text-[10px] text-muted-foreground/70">
{project.expanded ? "▼" : "▶"}
</span>
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
<span className="text-[10px] text-muted-foreground/60">
{threads.length}
</span>
</button>
{/* Threads */}
{project.expanded && (
<div className="ml-2 border-l border-border/80 pl-2">
{threads.map((thread) => {
const isActive = state.activeThreadId === thread.id;
return (
<button
key={thread.id}
type="button"
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"
: "text-muted-foreground hover:bg-secondary"
}`}
onClick={() =>
dispatch({
type: "SET_ACTIVE_THREAD",
threadId: thread.id,
})
}
>
<span className="flex-1 truncate text-xs">
{thread.title}
</span>
<span className="shrink-0 text-[10px] text-muted-foreground/40">
{formatRelativeTime(thread.createdAt)}
</span>
</button>
);
})}
{/* New thread within project */}
<button
type="button"
className="flex w-full items-center gap-1 px-2 py-1 text-[10px] text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground/80"
onClick={() => handleNewThread(project.id)}
>
<span>+</span> New thread
</button>
</div>
)}
</div>
);
})}
{state.projects.length === 0 && !addingProject && (
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
No projects yet.
<br />
Add one to get started.
</div>
)}
</nav>
{/* Add project form */}
{addingProject ? (
<div className="border-t border-border p-3">
<p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">
Add project
</p>
<input
className="mb-2 w-full rounded-md border border-border bg-secondary px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:border-ring focus:outline-none"
placeholder="/path/to/project"
value={newCwd}
onChange={(e) => setNewCwd(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleAddProject();
if (e.key === "Escape") setAddingProject(false);
}}
/>
{api && (
<button
type="button"
className="mb-2 flex w-full items-center justify-center rounded-md border border-border px-2 py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => void handlePickFolder()}
disabled={isPickingFolder}
>
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
</button>
)}
<select
className="mb-2 w-full rounded-md border border-border bg-secondary px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:border-ring focus:outline-none"
value={newModel}
onChange={(e) => setNewModel(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleAddProject();
if (e.key === "Escape") setAddingProject(false);
}}
>
{MODEL_OPTIONS.map((model) => (
<option key={model} value={model} className="bg-card">
{model}
</option>
))}
</select>
<div className="flex gap-2">
<button
type="button"
className="flex-1 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90"
onClick={handleAddProject}
>
Add
</button>
<button
type="button"
className="flex-1 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground/80 transition-colors duration-150 hover:bg-secondary"
onClick={() => setAddingProject(false)}
>
Cancel
</button>
</div>
</div>
) : (
<div className="border-t border-border p-3">
<button
type="button"
className="flex w-full items-center justify-center gap-1 rounded-md border border-dashed border-border py-2 text-xs text-muted-foreground/70 transition-colors duration-150 hover:border-ring hover:text-muted-foreground"
onClick={() => setAddingProject(true)}
>
+ Add project
</button>
</div>
)}
</aside>
);
}
@@ -0,0 +1,67 @@
import { Accordion as AccordionPrimitive } from "@base-ui/react/accordion";
import { ChevronDownIcon } from "lucide-react";
import { cn } from "#/lib/utils";
function Accordion(props: AccordionPrimitive.Root.Props) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />;
}
function AccordionItem({ className, ...props }: AccordionPrimitive.Item.Props) {
return (
<AccordionPrimitive.Item
className={cn("border-b last:border-b-0", className)}
data-slot="accordion-item"
{...props}
/>
);
}
function AccordionTrigger({
className,
children,
...props
}: AccordionPrimitive.Trigger.Props) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
className={cn(
"flex flex-1 cursor-pointer items-start justify-between gap-4 rounded-md py-4 text-left font-medium text-sm outline-none transition-all focus-visible:ring-[3px] focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-64 data-panel-open:*:data-[slot=accordion-indicator]:rotate-180",
className,
)}
data-slot="accordion-trigger"
{...props}
>
{children}
<ChevronDownIcon
className="pointer-events-none size-4 shrink-0 translate-y-0.5 opacity-80 transition-transform duration-200 ease-in-out"
data-slot="accordion-indicator"
/>
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
);
}
function AccordionPanel({
className,
children,
...props
}: AccordionPrimitive.Panel.Props) {
return (
<AccordionPrimitive.Panel
className="h-(--accordion-panel-height) overflow-hidden text-muted-foreground text-sm transition-[height] duration-200 ease-in-out data-ending-style:h-0 data-starting-style:h-0"
data-slot="accordion-panel"
{...props}
>
<div className={cn("pt-0 pb-4", className)}>{children}</div>
</AccordionPrimitive.Panel>
);
}
export {
Accordion,
AccordionItem,
AccordionTrigger,
AccordionPanel,
AccordionPanel as AccordionContent,
};
@@ -1,8 +1,6 @@
"use client";
import { AlertDialog as AlertDialogPrimitive } from "@base-ui/react/alert-dialog";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
const AlertDialogCreateHandle = AlertDialogPrimitive.createHandle;
@@ -11,10 +9,15 @@ const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
function AlertDialogTrigger(props: AlertDialogPrimitive.Trigger.Props) {
return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />;
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
);
}
function AlertDialogBackdrop({ className, ...props }: AlertDialogPrimitive.Backdrop.Props) {
function AlertDialogBackdrop({
className,
...props
}: AlertDialogPrimitive.Backdrop.Props) {
return (
<AlertDialogPrimitive.Backdrop
className={cn(
@@ -27,7 +30,10 @@ function AlertDialogBackdrop({ className, ...props }: AlertDialogPrimitive.Backd
);
}
function AlertDialogViewport({ className, ...props }: AlertDialogPrimitive.Viewport.Props) {
function AlertDialogViewport({
className,
...props
}: AlertDialogPrimitive.Viewport.Props) {
return (
<AlertDialogPrimitive.Viewport
className={cn(
@@ -51,7 +57,10 @@ function AlertDialogPopup({
<AlertDialogPortal>
<AlertDialogBackdrop />
<AlertDialogViewport
className={cn(bottomStickOnMobile && "max-sm:grid-rows-[1fr_auto] max-sm:p-0 max-sm:pt-12")}
className={cn(
bottomStickOnMobile &&
"max-sm:grid-rows-[1fr_auto] max-sm:p-0 max-sm:pt-12",
)}
>
<AlertDialogPrimitive.Popup
className={cn(
@@ -68,10 +77,16 @@ function AlertDialogPopup({
);
}
function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">) {
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
className={cn("flex flex-col gap-2 p-6 text-center max-sm:pb-4 sm:text-left", className)}
className={cn(
"flex flex-col gap-2 p-6 text-center max-sm:pb-4 sm:text-left",
className,
)}
data-slot="alert-dialog-header"
{...props}
/>
@@ -99,17 +114,26 @@ function AlertDialogFooter({
);
}
function AlertDialogTitle({ className, ...props }: AlertDialogPrimitive.Title.Props) {
function AlertDialogTitle({
className,
...props
}: AlertDialogPrimitive.Title.Props) {
return (
<AlertDialogPrimitive.Title
className={cn("font-heading font-semibold text-xl leading-none", className)}
className={cn(
"font-heading font-semibold text-xl leading-none",
className,
)}
data-slot="alert-dialog-title"
{...props}
/>
);
}
function AlertDialogDescription({ className, ...props }: AlertDialogPrimitive.Description.Props) {
function AlertDialogDescription({
className,
...props
}: AlertDialogPrimitive.Description.Props) {
return (
<AlertDialogPrimitive.Description
className={cn("text-muted-foreground text-sm", className)}
@@ -120,7 +144,9 @@ function AlertDialogDescription({ className, ...props }: AlertDialogPrimitive.De
}
function AlertDialogClose(props: AlertDialogPrimitive.Close.Props) {
return <AlertDialogPrimitive.Close data-slot="alert-dialog-close" {...props} />;
return (
<AlertDialogPrimitive.Close data-slot="alert-dialog-close" {...props} />
);
}
export {
@@ -1,7 +1,7 @@
import { cva, type VariantProps } from "class-variance-authority";
import { type VariantProps, cva } from "class-variance-authority";
import type * as React from "react";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
const alertVariants = cva(
"relative grid w-full items-start gap-x-2 gap-y-0.5 rounded-xl border px-3.5 py-3 text-card-foreground text-sm has-[>svg]:has-data-[slot=alert-action]:grid-cols-[calc(var(--spacing)*4)_1fr_auto] has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-data-[slot=alert-action]:grid-cols-[1fr_auto] has-[>svg]:gap-x-2 [&>svg]:h-lh [&>svg]:w-4",
@@ -11,8 +11,10 @@ const alertVariants = cva(
},
variants: {
variant: {
default: "bg-transparent dark:bg-input/32 [&>svg]:text-muted-foreground",
error: "border-destructive/32 bg-destructive/4 [&>svg]:text-destructive",
default:
"bg-transparent dark:bg-input/32 [&>svg]:text-muted-foreground",
error:
"border-destructive/32 bg-destructive/4 [&>svg]:text-destructive",
info: "border-info/32 bg-info/4 [&>svg]:text-info",
success: "border-success/32 bg-success/4 [&>svg]:text-success",
warning: "border-warning/32 bg-warning/4 [&>svg]:text-warning",
@@ -46,10 +48,16 @@ function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
);
}
function AlertDescription({ className, ...props }: React.ComponentProps<"div">) {
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
className={cn("flex flex-col gap-2.5 text-muted-foreground [svg~&]:col-start-2", className)}
className={cn(
"flex flex-col gap-2.5 text-muted-foreground [svg~&]:col-start-2",
className,
)}
data-slot="alert-description"
{...props}
/>
@@ -1,11 +1,9 @@
"use client";
import { Autocomplete as AutocompletePrimitive } from "@base-ui/react/autocomplete";
import { ChevronsUpDownIcon, XIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { Input } from "~/components/ui/input";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Input } from "#/components/ui/input";
import { ScrollArea } from "#/components/ui/scroll-area";
import { cn } from "#/lib/utils";
const Autocomplete = AutocompletePrimitive.Root;
@@ -56,9 +54,7 @@ function AutocompleteInput({
sizeValue === "sm" ? "end-0" : "end-0.5",
)}
>
<AutocompletePrimitive.Icon data-slot="autocomplete-icon">
<ChevronsUpDownIcon />
</AutocompletePrimitive.Icon>
<ChevronsUpDownIcon />
</AutocompleteTrigger>
)}
{showClear && (
@@ -82,21 +78,18 @@ function AutocompletePopup({
sideOffset = 4,
alignOffset,
align = "start",
anchor,
...props
}: AutocompletePrimitive.Popup.Props & {
align?: AutocompletePrimitive.Positioner.Props["align"];
sideOffset?: AutocompletePrimitive.Positioner.Props["sideOffset"];
alignOffset?: AutocompletePrimitive.Positioner.Props["alignOffset"];
side?: AutocompletePrimitive.Positioner.Props["side"];
anchor?: AutocompletePrimitive.Positioner.Props["anchor"];
}) {
return (
<AutocompletePrimitive.Portal>
<AutocompletePrimitive.Positioner
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="z-50 select-none"
data-slot="autocomplete-positioner"
side={side}
@@ -121,7 +114,11 @@ function AutocompletePopup({
);
}
function AutocompleteItem({ className, children, ...props }: AutocompletePrimitive.Item.Props) {
function AutocompleteItem({
className,
children,
...props
}: AutocompletePrimitive.Item.Props) {
return (
<AutocompletePrimitive.Item
className={cn(
@@ -136,7 +133,10 @@ function AutocompleteItem({ className, children, ...props }: AutocompletePrimiti
);
}
function AutocompleteSeparator({ className, ...props }: AutocompletePrimitive.Separator.Props) {
function AutocompleteSeparator({
className,
...props
}: AutocompletePrimitive.Separator.Props) {
return (
<AutocompletePrimitive.Separator
className={cn("mx-2 my-1 h-px bg-border last:hidden", className)}
@@ -146,7 +146,10 @@ function AutocompleteSeparator({ className, ...props }: AutocompletePrimitive.Se
);
}
function AutocompleteGroup({ className, ...props }: AutocompletePrimitive.Group.Props) {
function AutocompleteGroup({
className,
...props
}: AutocompletePrimitive.Group.Props) {
return (
<AutocompletePrimitive.Group
className={cn("[[role=group]+&]:mt-1.5", className)}
@@ -156,17 +159,26 @@ function AutocompleteGroup({ className, ...props }: AutocompletePrimitive.Group.
);
}
function AutocompleteGroupLabel({ className, ...props }: AutocompletePrimitive.GroupLabel.Props) {
function AutocompleteGroupLabel({
className,
...props
}: AutocompletePrimitive.GroupLabel.Props) {
return (
<AutocompletePrimitive.GroupLabel
className={cn("px-2 py-1.5 font-medium text-muted-foreground text-xs", className)}
className={cn(
"px-2 py-1.5 font-medium text-muted-foreground text-xs",
className,
)}
data-slot="autocomplete-group-label"
{...props}
/>
);
}
function AutocompleteEmpty({ className, ...props }: AutocompletePrimitive.Empty.Props) {
function AutocompleteEmpty({
className,
...props
}: AutocompletePrimitive.Empty.Props) {
return (
<AutocompletePrimitive.Empty
className={cn(
@@ -179,21 +191,36 @@ function AutocompleteEmpty({ className, ...props }: AutocompletePrimitive.Empty.
);
}
function AutocompleteRow({ className, ...props }: AutocompletePrimitive.Row.Props) {
function AutocompleteRow({
className,
...props
}: AutocompletePrimitive.Row.Props) {
return (
<AutocompletePrimitive.Row className={className} data-slot="autocomplete-row" {...props} />
<AutocompletePrimitive.Row
className={className}
data-slot="autocomplete-row"
{...props}
/>
);
}
function AutocompleteValue({ ...props }: AutocompletePrimitive.Value.Props) {
return <AutocompletePrimitive.Value data-slot="autocomplete-value" {...props} />;
return (
<AutocompletePrimitive.Value data-slot="autocomplete-value" {...props} />
);
}
function AutocompleteList({ className, ...props }: AutocompletePrimitive.List.Props) {
function AutocompleteList({
className,
...props
}: AutocompletePrimitive.List.Props) {
return (
<ScrollArea scrollbarGutter scrollFade>
<AutocompletePrimitive.List
className={cn("not-empty:scroll-py-1 not-empty:p-1 in-data-has-overflow-y:pe-3", className)}
className={cn(
"not-empty:scroll-py-1 not-empty:p-1 in-data-has-overflow-y:pe-3",
className,
)}
data-slot="autocomplete-list"
{...props}
/>
@@ -201,7 +228,10 @@ function AutocompleteList({ className, ...props }: AutocompletePrimitive.List.Pr
);
}
function AutocompleteClear({ className, ...props }: AutocompletePrimitive.Clear.Props) {
function AutocompleteClear({
className,
...props
}: AutocompletePrimitive.Clear.Props) {
return (
<AutocompletePrimitive.Clear
className={cn(
@@ -216,7 +246,10 @@ function AutocompleteClear({ className, ...props }: AutocompletePrimitive.Clear.
);
}
function AutocompleteStatus({ className, ...props }: AutocompletePrimitive.Status.Props) {
function AutocompleteStatus({
className,
...props
}: AutocompletePrimitive.Status.Props) {
return (
<AutocompletePrimitive.Status
className={cn(
@@ -229,13 +262,19 @@ function AutocompleteStatus({ className, ...props }: AutocompletePrimitive.Statu
);
}
function AutocompleteCollection({ ...props }: AutocompletePrimitive.Collection.Props) {
return <AutocompletePrimitive.Collection data-slot="autocomplete-collection" {...props} />;
function AutocompleteCollection({
...props
}: AutocompletePrimitive.Collection.Props) {
return (
<AutocompletePrimitive.Collection
data-slot="autocomplete-collection"
{...props}
/>
);
}
function AutocompleteTrigger({
className,
children,
...props
}: AutocompletePrimitive.Trigger.Props) {
return (
@@ -243,9 +282,7 @@ function AutocompleteTrigger({
className={className}
data-slot="autocomplete-trigger"
{...props}
>
{children}
</AutocompletePrimitive.Trigger>
/>
);
}
@@ -0,0 +1,44 @@
import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar";
import { cn } from "#/lib/utils";
function Avatar({ className, ...props }: AvatarPrimitive.Root.Props) {
return (
<AvatarPrimitive.Root
className={cn(
"inline-flex size-8 shrink-0 select-none items-center justify-center overflow-hidden rounded-full bg-background align-middle font-medium text-xs",
className,
)}
data-slot="avatar"
{...props}
/>
);
}
function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {
return (
<AvatarPrimitive.Image
className={cn("size-full object-cover", className)}
data-slot="avatar-image"
{...props}
/>
);
}
function AvatarFallback({
className,
...props
}: AvatarPrimitive.Fallback.Props) {
return (
<AvatarPrimitive.Fallback
className={cn(
"flex size-full items-center justify-center rounded-full bg-muted",
className,
)}
data-slot="avatar-fallback"
{...props}
/>
);
}
export { Avatar, AvatarImage, AvatarFallback };
@@ -1,13 +1,11 @@
"use client";
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import { cva, type VariantProps } from "class-variance-authority";
import { type VariantProps, cva } from "class-variance-authority";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
const badgeVariants = cva(
"relative inline-flex shrink-0 items-center justify-center gap-1 whitespace-nowrap rounded-sm border border-transparent font-medium outline-none transition-shadow focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-3.5 sm:[&_svg:not([class*='size-'])]:size-3 [&_svg]:pointer-events-none [&_svg]:shrink-0 [button&,a&]:cursor-pointer [button&,a&]:pointer-coarse:after:absolute [button&,a&]:pointer-coarse:after:size-full [button&,a&]:pointer-coarse:after:min-h-11 [button&,a&]:pointer-coarse:after:min-w-11",
"relative inline-flex shrink-0 items-center justify-center gap-1 whitespace-nowrap rounded-sm border border-transparent font-medium outline-none transition-shadow focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-3.5 sm:[&_svg:not([class*='size-'])]:size-3 [&_svg]:pointer-events-none [&_svg]:shrink-0 [button,a&]:cursor-pointer [button,a&]:pointer-coarse:after:absolute [button,a&]:pointer-coarse:after:size-full [button,a&]:pointer-coarse:after:min-h-11 [button,a&]:pointer-coarse:after:min-w-11",
{
defaultVariants: {
size: "default",
@@ -18,16 +16,20 @@ const badgeVariants = cva(
default:
"h-5.5 min-w-5.5 px-[calc(--spacing(1)-1px)] text-sm sm:h-4.5 sm:min-w-4.5 sm:text-xs",
lg: "h-6.5 min-w-6.5 px-[calc(--spacing(1.5)-1px)] text-base sm:h-5.5 sm:min-w-5.5 sm:text-sm",
sm: "h-5 min-w-5 rounded-[.25rem] px-[calc(--spacing(1)-1px)] text-xs sm:h-4 sm:min-w-4 sm:text-[.625rem]",
sm: "h-5 min-w-5 rounded-[calc(var(--radius-sm)-2px)] px-[calc(--spacing(1)-1px)] text-xs sm:h-4 sm:min-w-4 sm:text-[.625rem]",
},
variant: {
default: "bg-primary text-primary-foreground [button&,a&]:hover:bg-primary/90",
destructive: "bg-destructive text-white [button&,a&]:hover:bg-destructive/90",
error: "bg-destructive/8 text-destructive-foreground dark:bg-destructive/16",
default:
"bg-primary text-primary-foreground [button,a&]:hover:bg-primary/90",
destructive:
"bg-destructive text-white [button,a&]:hover:bg-destructive/90",
error:
"bg-destructive/8 text-destructive-foreground dark:bg-destructive/16",
info: "bg-info/8 text-info-foreground dark:bg-info/16",
outline:
"border-input bg-background text-foreground dark:bg-input/32 [button&,a&]:hover:bg-accent/50 dark:[button&,a&]:hover:bg-input/48",
secondary: "bg-secondary text-secondary-foreground [button&,a&]:hover:bg-secondary/90",
"border-input bg-background text-foreground dark:bg-input/32 [button,a&]:hover:bg-accent/50 dark:[button,a&]:hover:bg-input/48",
secondary:
"bg-secondary text-secondary-foreground [button,a&]:hover:bg-secondary/90",
success: "bg-success/8 text-success-foreground dark:bg-success/16",
warning: "bg-warning/8 text-warning-foreground dark:bg-warning/16",
},
@@ -1,11 +1,9 @@
"use client";
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import { cva, type VariantProps } from "class-variance-authority";
import { type VariantProps, cva } from "class-variance-authority";
import type * as React from "react";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
const buttonVariants = cva(
"[&_svg]:-mx-0.5 relative inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-lg border font-medium text-base outline-none transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 sm:text-sm [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
@@ -54,9 +52,8 @@ interface ButtonProps extends useRender.ComponentProps<"button"> {
}
function Button({ className, variant, size, render, ...props }: ButtonProps) {
const typeValue: React.ButtonHTMLAttributes<HTMLButtonElement>["type"] = render
? undefined
: "button";
const typeValue: React.ButtonHTMLAttributes<HTMLButtonElement>["type"] =
render ? undefined : "button";
const defaultProps = {
className: cn(buttonVariants({ className, size, variant })),
@@ -1,11 +1,13 @@
"use client";
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Card({ className, render, ...props }: useRender.ComponentProps<"div">) {
function Card({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn(
"relative flex flex-col rounded-2xl border bg-card not-dark:bg-clip-padding text-card-foreground shadow-xs/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
@@ -21,10 +23,14 @@ function Card({ className, render, ...props }: useRender.ComponentProps<"div">)
});
}
function CardFrame({ className, render, ...props }: useRender.ComponentProps<"div">) {
function CardFrame({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn(
"[--clip-top:-1rem] [--clip-bottom:-1rem] *:data-[slot=card]:first:[--clip-top:1px] *:data-[slot=card]:last:[--clip-bottom:1px] flex flex-col relative rounded-2xl border bg-card before:bg-muted/72 not-dark:bg-clip-padding text-card-foreground shadow-xs/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)] *:data-[slot=card]:-m-px *:not-last:data-[slot=card]:rounded-b-xl *:not-last:data-[slot=card]:before:rounded-b-[calc(var(--radius-xl)-1px)] *:not-first:data-[slot=card]:rounded-t-xl *:not-first:data-[slot=card]:before:rounded-t-[calc(var(--radius-xl)-1px)] *:data-[slot=card]:[clip-path:inset(var(--clip-top)_1px_var(--clip-bottom)_1px_round_calc(var(--radius-2xl)-1px))] *:data-[slot=card]:shadow-none *:data-[slot=card]:before:hidden *:data-[slot=card]:bg-clip-padding",
"flex flex-col relative rounded-2xl border bg-card before:bg-muted/72 not-dark:bg-clip-padding text-card-foreground shadow-xs/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)] *:data-[slot=card]:-m-px *:not-last:data-[slot=card]:rounded-b-xl *:not-last:data-[slot=card]:before:rounded-b-[calc(var(--radius-xl)-1px)] *:not-first:data-[slot=card]:rounded-t-xl *:not-first:data-[slot=card]:before:rounded-t-[calc(var(--radius-xl)-1px)] *:data-[slot=card]:[clip-path:inset(-1rem_1px)] *:data-[slot=card]:first:[clip-path:inset(1px_1px_-1rem_1px_round_calc(var(--radius-2xl)-1px))] *:data-[slot=card]:last:[clip-path:inset(-1rem_1px_1px_1px_round_calc(var(--radius-2xl)-1px))] *:data-[slot=card]:shadow-none *:data-[slot=card]:before:hidden *:data-[slot=card]:bg-clip-padding",
className,
),
"data-slot": "card-frame",
@@ -37,7 +43,11 @@ function CardFrame({ className, render, ...props }: useRender.ComponentProps<"di
});
}
function CardFrameHeader({ className, render, ...props }: useRender.ComponentProps<"div">) {
function CardFrameHeader({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn("relative flex flex-col px-6 py-4", className),
"data-slot": "card-frame-header",
@@ -50,7 +60,11 @@ function CardFrameHeader({ className, render, ...props }: useRender.ComponentPro
});
}
function CardFrameTitle({ className, render, ...props }: useRender.ComponentProps<"div">) {
function CardFrameTitle({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn("font-semibold text-sm", className),
"data-slot": "card-frame-title",
@@ -63,7 +77,11 @@ function CardFrameTitle({ className, render, ...props }: useRender.ComponentProp
});
}
function CardFrameDescription({ className, render, ...props }: useRender.ComponentProps<"div">) {
function CardFrameDescription({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn("text-muted-foreground text-sm", className),
"data-slot": "card-frame-description",
@@ -76,7 +94,11 @@ function CardFrameDescription({ className, render, ...props }: useRender.Compone
});
}
function CardFrameFooter({ className, render, ...props }: useRender.ComponentProps<"div">) {
function CardFrameFooter({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn("px-6 py-4", className),
"data-slot": "card-frame-footer",
@@ -89,7 +111,11 @@ function CardFrameFooter({ className, render, ...props }: useRender.ComponentPro
});
}
function CardHeader({ className, render, ...props }: useRender.ComponentProps<"div">) {
function CardHeader({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn(
"grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 p-6 in-[[data-slot=card]:has(>[data-slot=card-panel])]:pb-4 has-data-[slot=card-action]:grid-cols-[1fr_auto]",
@@ -105,7 +131,11 @@ function CardHeader({ className, render, ...props }: useRender.ComponentProps<"d
});
}
function CardTitle({ className, render, ...props }: useRender.ComponentProps<"div">) {
function CardTitle({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn("font-semibold text-lg leading-none", className),
"data-slot": "card-title",
@@ -118,7 +148,11 @@ function CardTitle({ className, render, ...props }: useRender.ComponentProps<"di
});
}
function CardDescription({ className, render, ...props }: useRender.ComponentProps<"div">) {
function CardDescription({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn("text-muted-foreground text-sm", className),
"data-slot": "card-description",
@@ -131,7 +165,11 @@ function CardDescription({ className, render, ...props }: useRender.ComponentPro
});
}
function CardAction({ className, render, ...props }: useRender.ComponentProps<"div">) {
function CardAction({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end inline-flex",
@@ -147,7 +185,11 @@ function CardAction({ className, render, ...props }: useRender.ComponentProps<"d
});
}
function CardPanel({ className, render, ...props }: useRender.ComponentProps<"div">) {
function CardPanel({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn(
"flex-1 p-6 in-[[data-slot=card]:has(>[data-slot=card-header]:not(.border-b))]:pt-0 in-[[data-slot=card]:has(>[data-slot=card-footer]:not(.border-t))]:pb-0",
@@ -163,7 +205,11 @@ function CardPanel({ className, render, ...props }: useRender.ComponentProps<"di
});
}
function CardFooter({ className, render, ...props }: useRender.ComponentProps<"div">) {
function CardFooter({
className,
render,
...props
}: useRender.ComponentProps<"div">) {
const defaultProps = {
className: cn(
"flex items-center p-6 in-[[data-slot=card]:has(>[data-slot=card-panel])]:pt-4",
@@ -0,0 +1,14 @@
import { CheckboxGroup as CheckboxGroupPrimitive } from "@base-ui/react/checkbox-group";
import { cn } from "#/lib/utils";
function CheckboxGroup({ className, ...props }: CheckboxGroupPrimitive.Props) {
return (
<CheckboxGroupPrimitive
className={cn("flex flex-col items-start gap-3", className)}
{...props}
/>
);
}
export { CheckboxGroup };
@@ -1,21 +1,19 @@
"use client";
import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
return (
<CheckboxPrimitive.Root
className={cn(
"relative inline-flex size-4.5 shrink-0 items-center justify-center rounded-[.25rem] border border-input bg-background not-dark:bg-clip-padding shadow-xs/5 outline-none ring-ring transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[3px] not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-offset-background aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/48 data-disabled:opacity-64 sm:size-4 dark:not-data-checked:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)] [[data-disabled],[data-checked],[aria-invalid]]:shadow-none",
"relative inline-flex size-4.5 shrink-0 items-center justify-center rounded-[4px] border border-input bg-background not-dark:bg-clip-padding shadow-xs/5 outline-none ring-ring transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[3px] not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-offset-background aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/48 data-disabled:opacity-64 sm:size-4 dark:not-data-checked:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)] [[data-disabled],[data-checked],[aria-invalid]]:shadow-none",
className,
)}
data-slot="checkbox"
{...props}
>
<CheckboxPrimitive.Indicator
className="-inset-px absolute flex items-center justify-center rounded-[.25rem] text-primary-foreground data-unchecked:hidden data-checked:bg-primary data-indeterminate:text-foreground"
className="-inset-px absolute flex items-center justify-center rounded-[4px] text-primary-foreground data-unchecked:hidden data-checked:bg-primary data-indeterminate:text-foreground"
data-slot="checkbox-indicator"
render={(props, state) => (
<span {...props}>
@@ -0,0 +1,43 @@
import { Collapsible as CollapsiblePrimitive } from "@base-ui/react/collapsible";
import { cn } from "#/lib/utils";
function Collapsible({ ...props }: CollapsiblePrimitive.Root.Props) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;
}
function CollapsibleTrigger({
className,
...props
}: CollapsiblePrimitive.Trigger.Props) {
return (
<CollapsiblePrimitive.Trigger
className={cn("cursor-pointer", className)}
data-slot="collapsible-trigger"
{...props}
/>
);
}
function CollapsiblePanel({
className,
...props
}: CollapsiblePrimitive.Panel.Props) {
return (
<CollapsiblePrimitive.Panel
className={cn(
"h-(--collapsible-panel-height) overflow-hidden transition-[height] duration-200 data-ending-style:h-0 data-starting-style:h-0",
className,
)}
data-slot="collapsible-panel"
{...props}
/>
);
}
export {
Collapsible,
CollapsibleTrigger,
CollapsiblePanel,
CollapsiblePanel as CollapsibleContent,
};
@@ -1,12 +1,10 @@
"use client";
import { Combobox as ComboboxPrimitive } from "@base-ui/react/combobox";
import { CheckIcon, ChevronsUpDownIcon, XIcon } from "lucide-react";
import { ChevronsUpDownIcon, XIcon } from "lucide-react";
import * as React from "react";
import { cn } from "~/lib/utils";
import { Input } from "~/components/ui/input";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Input } from "#/components/ui/input";
import { ScrollArea } from "#/components/ui/scroll-area";
import { cn } from "#/lib/utils";
const ComboboxContext = React.createContext<{
chipsRef: React.RefObject<Element | null> | null;
@@ -18,7 +16,7 @@ const ComboboxContext = React.createContext<{
function Combobox<Value, Multiple extends boolean | undefined = false>(
props: ComboboxPrimitive.Root.Props<Value, Multiple>,
) {
): React.JSX.Element {
const chipsRef = React.useRef<Element | null>(null);
return (
<ComboboxContext.Provider value={{ chipsRef, multiple: !!props.multiple }}>
@@ -54,14 +52,12 @@ function ComboboxChipsInput({
function ComboboxInput({
className,
inputClassName,
showTrigger = true,
showClear = false,
startAddon,
size,
...props
}: Omit<ComboboxPrimitive.Input.Props, "size"> & {
inputClassName?: string;
showTrigger?: boolean;
showClear?: boolean;
startAddon?: React.ReactNode;
@@ -93,7 +89,7 @@ function ComboboxInput({
data-slot="combobox-input"
render={
<Input
className={cn("has-disabled:opacity-100", inputClassName)}
className="has-disabled:opacity-100"
nativeInput
size={sizeValue}
/>
@@ -107,9 +103,7 @@ function ComboboxInput({
sizeValue === "sm" ? "end-0" : "end-0.5",
)}
>
<ComboboxPrimitive.Icon data-slot="combobox-icon">
<ChevronsUpDownIcon />
</ComboboxPrimitive.Icon>
<ChevronsUpDownIcon />
</ComboboxTrigger>
)}
{showClear && (
@@ -126,11 +120,16 @@ function ComboboxInput({
);
}
function ComboboxTrigger({ className, children, ...props }: ComboboxPrimitive.Trigger.Props) {
function ComboboxTrigger({
className,
...props
}: ComboboxPrimitive.Trigger.Props) {
return (
<ComboboxPrimitive.Trigger className={className} data-slot="combobox-trigger" {...props}>
{children}
</ComboboxPrimitive.Trigger>
<ComboboxPrimitive.Trigger
className={className}
data-slot="combobox-trigger"
{...props}
/>
);
}
@@ -141,24 +140,21 @@ function ComboboxPopup({
sideOffset = 4,
alignOffset,
align = "start",
anchor: anchorProp,
...props
}: ComboboxPrimitive.Popup.Props & {
align?: ComboboxPrimitive.Positioner.Props["align"];
sideOffset?: ComboboxPrimitive.Positioner.Props["sideOffset"];
alignOffset?: ComboboxPrimitive.Positioner.Props["alignOffset"];
side?: ComboboxPrimitive.Positioner.Props["side"];
anchor?: ComboboxPrimitive.Positioner.Props["anchor"];
}) {
const { chipsRef } = React.useContext(ComboboxContext);
const anchor = anchorProp ?? chipsRef;
return (
<ComboboxPrimitive.Portal>
<ComboboxPrimitive.Positioner
align={align}
alignOffset={alignOffset}
anchor={anchor}
anchor={chipsRef}
className="z-50 select-none"
data-slot="combobox-positioner"
side={side}
@@ -186,11 +182,8 @@ function ComboboxPopup({
function ComboboxItem({
className,
children,
hideIndicator = false,
...props
}: ComboboxPrimitive.Item.Props & {
hideIndicator?: boolean;
}) {
}: ComboboxPrimitive.Item.Props) {
return (
<ComboboxPrimitive.Item
className={cn(
@@ -200,15 +193,30 @@ function ComboboxItem({
data-slot="combobox-item"
{...props}
>
<ComboboxPrimitive.ItemIndicator className={cn("col-start-1", hideIndicator && "hidden")}>
<CheckIcon />
<ComboboxPrimitive.ItemIndicator className="col-start-1">
<svg
fill="none"
height="24"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/1500/svg"
>
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
</svg>
</ComboboxPrimitive.ItemIndicator>
<div className={hideIndicator ? "col-start-1 col-span-full" : "col-start-2"}>{children}</div>
<div className="col-start-2">{children}</div>
</ComboboxPrimitive.Item>
);
}
function ComboboxSeparator({ className, ...props }: ComboboxPrimitive.Separator.Props) {
function ComboboxSeparator({
className,
...props
}: ComboboxPrimitive.Separator.Props) {
return (
<ComboboxPrimitive.Separator
className={cn("mx-2 my-1 h-px bg-border last:hidden", className)}
@@ -228,10 +236,16 @@ function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) {
);
}
function ComboboxGroupLabel({ className, ...props }: ComboboxPrimitive.GroupLabel.Props) {
function ComboboxGroupLabel({
className,
...props
}: ComboboxPrimitive.GroupLabel.Props) {
return (
<ComboboxPrimitive.GroupLabel
className={cn("px-2 py-1.5 font-medium text-muted-foreground text-xs", className)}
className={cn(
"px-2 py-1.5 font-medium text-muted-foreground text-xs",
className,
)}
data-slot="combobox-group-label"
{...props}
/>
@@ -252,7 +266,13 @@ function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
}
function ComboboxRow({ className, ...props }: ComboboxPrimitive.Row.Props) {
return <ComboboxPrimitive.Row className={className} data-slot="combobox-row" {...props} />;
return (
<ComboboxPrimitive.Row
className={className}
data-slot="combobox-row"
{...props}
/>
);
}
function ComboboxValue({ ...props }: ComboboxPrimitive.Value.Props) {
@@ -275,10 +295,19 @@ function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
}
function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
return <ComboboxPrimitive.Clear className={className} data-slot="combobox-clear" {...props} />;
return (
<ComboboxPrimitive.Clear
className={className}
data-slot="combobox-clear"
{...props}
/>
);
}
function ComboboxStatus({ className, ...props }: ComboboxPrimitive.Status.Props) {
function ComboboxStatus({
className,
...props
}: ComboboxPrimitive.Status.Props) {
return (
<ComboboxPrimitive.Status
className={cn(
@@ -292,7 +321,9 @@ function ComboboxStatus({ className, ...props }: ComboboxPrimitive.Status.Props)
}
function ComboboxCollection(props: ComboboxPrimitive.Collection.Props) {
return <ComboboxPrimitive.Collection data-slot="combobox-collection" {...props} />;
return (
<ComboboxPrimitive.Collection data-slot="combobox-collection" {...props} />
);
}
function ComboboxChips({
@@ -312,6 +343,17 @@ function ComboboxChips({
className,
)}
data-slot="combobox-chips"
onMouseDown={(e) => {
const target = e.target as HTMLElement;
const isChip = target.closest('[data-slot="combobox-chip"]');
if (isChip || !chipsRef?.current) return;
e.preventDefault();
const input: HTMLInputElement | null =
chipsRef.current.querySelector("input");
if (input && !chipsRef.current.querySelector("input:focus")) {
input.focus();
}
}}
ref={chipsRef as React.Ref<HTMLDivElement> | null}
{...props}
>
@@ -1,9 +1,6 @@
"use client";
import { Dialog as CommandDialogPrimitive } from "@base-ui/react/dialog";
import { SearchIcon } from "lucide-react";
import type * as React from "react";
import { cn } from "~/lib/utils";
import {
Autocomplete,
AutocompleteCollection,
@@ -14,7 +11,8 @@ import {
AutocompleteItem,
AutocompleteList,
AutocompleteSeparator,
} from "~/components/ui/autocomplete";
} from "#/components/ui/autocomplete";
import { cn } from "#/lib/utils";
const CommandDialog = CommandDialogPrimitive.Root;
@@ -23,10 +21,18 @@ const CommandDialogPortal = CommandDialogPrimitive.Portal;
const CommandCreateHandle = CommandDialogPrimitive.createHandle;
function CommandDialogTrigger(props: CommandDialogPrimitive.Trigger.Props) {
return <CommandDialogPrimitive.Trigger data-slot="command-dialog-trigger" {...props} />;
return (
<CommandDialogPrimitive.Trigger
data-slot="command-dialog-trigger"
{...props}
/>
);
}
function CommandDialogBackdrop({ className, ...props }: CommandDialogPrimitive.Backdrop.Props) {
function CommandDialogBackdrop({
className,
...props
}: CommandDialogPrimitive.Backdrop.Props) {
return (
<CommandDialogPrimitive.Backdrop
className={cn(
@@ -39,7 +45,10 @@ function CommandDialogBackdrop({ className, ...props }: CommandDialogPrimitive.B
);
}
function CommandDialogViewport({ className, ...props }: CommandDialogPrimitive.Viewport.Props) {
function CommandDialogViewport({
className,
...props
}: CommandDialogPrimitive.Viewport.Props) {
return (
<CommandDialogPrimitive.Viewport
className={cn(
@@ -52,7 +61,11 @@ function CommandDialogViewport({ className, ...props }: CommandDialogPrimitive.V
);
}
function CommandDialogPopup({ className, children, ...props }: CommandDialogPrimitive.Popup.Props) {
function CommandDialogPopup({
className,
children,
...props
}: CommandDialogPrimitive.Popup.Props) {
return (
<CommandDialogPortal>
<CommandDialogBackdrop />
@@ -110,7 +123,10 @@ function CommandInput({
);
}
function CommandList({ className, ...props }: React.ComponentProps<typeof AutocompleteList>) {
function CommandList({
className,
...props
}: React.ComponentProps<typeof AutocompleteList>) {
return (
<AutocompleteList
className={cn("not-empty:scroll-py-2 not-empty:p-2", className)}
@@ -120,7 +136,10 @@ function CommandList({ className, ...props }: React.ComponentProps<typeof Autoco
);
}
function CommandEmpty({ className, ...props }: React.ComponentProps<typeof AutocompleteEmpty>) {
function CommandEmpty({
className,
...props
}: React.ComponentProps<typeof AutocompleteEmpty>) {
return (
<AutocompleteEmpty
className={cn("not-empty:py-6", className)}
@@ -139,8 +158,17 @@ function CommandPanel({ className, ...props }: React.ComponentProps<"div">) {
);
}
function CommandGroup({ className, ...props }: React.ComponentProps<typeof AutocompleteGroup>) {
return <AutocompleteGroup className={className} data-slot="command-group" {...props} />;
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof AutocompleteGroup>) {
return (
<AutocompleteGroup
className={className}
data-slot="command-group"
{...props}
/>
);
}
function CommandGroupLabel({
@@ -148,17 +176,30 @@ function CommandGroupLabel({
...props
}: React.ComponentProps<typeof AutocompleteGroupLabel>) {
return (
<AutocompleteGroupLabel className={className} data-slot="command-group-label" {...props} />
<AutocompleteGroupLabel
className={className}
data-slot="command-group-label"
{...props}
/>
);
}
function CommandCollection({ ...props }: React.ComponentProps<typeof AutocompleteCollection>) {
function CommandCollection({
...props
}: React.ComponentProps<typeof AutocompleteCollection>) {
return <AutocompleteCollection data-slot="command-collection" {...props} />;
}
function CommandItem({ className, ...props }: React.ComponentProps<typeof AutocompleteItem>) {
function CommandItem({
className,
...props
}: React.ComponentProps<typeof AutocompleteItem>) {
return (
<AutocompleteItem className={cn("py-1.5", className)} data-slot="command-item" {...props} />
<AutocompleteItem
className={cn("py-1.5", className)}
data-slot="command-item"
{...props}
/>
);
}
@@ -1,10 +1,8 @@
"use client";
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
import { XIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { Button } from "~/components/ui/button";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Button } from "#/components/ui/button";
import { ScrollArea } from "#/components/ui/scroll-area";
import { cn } from "#/lib/utils";
const DialogCreateHandle = DialogPrimitive.createHandle;
@@ -20,7 +18,10 @@ function DialogClose(props: DialogPrimitive.Close.Props) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogBackdrop({ className, ...props }: DialogPrimitive.Backdrop.Props) {
function DialogBackdrop({
className,
...props
}: DialogPrimitive.Backdrop.Props) {
return (
<DialogPrimitive.Backdrop
className={cn(
@@ -33,7 +34,10 @@ function DialogBackdrop({ className, ...props }: DialogPrimitive.Backdrop.Props)
);
}
function DialogViewport({ className, ...props }: DialogPrimitive.Viewport.Props) {
function DialogViewport({
className,
...props
}: DialogPrimitive.Viewport.Props) {
return (
<DialogPrimitive.Viewport
className={cn(
@@ -60,7 +64,10 @@ function DialogPopup({
<DialogPortal>
<DialogBackdrop />
<DialogViewport
className={cn(bottomStickOnMobile && "max-sm:grid-rows-[1fr_auto] max-sm:p-0 max-sm:pt-12")}
className={cn(
bottomStickOnMobile &&
"max-sm:grid-rows-[1fr_auto] max-sm:p-0 max-sm:pt-12",
)}
>
<DialogPrimitive.Popup
className={cn(
@@ -126,14 +133,20 @@ function DialogFooter({
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
return (
<DialogPrimitive.Title
className={cn("font-heading font-semibold text-xl leading-none", className)}
className={cn(
"font-heading font-semibold text-xl leading-none",
className,
)}
data-slot="dialog-title"
{...props}
/>
);
}
function DialogDescription({ className, ...props }: DialogPrimitive.Description.Props) {
function DialogDescription({
className,
...props
}: DialogPrimitive.Description.Props) {
return (
<DialogPrimitive.Description
className={cn("text-muted-foreground text-sm", className)}
@@ -1,6 +1,6 @@
import { cva, type VariantProps } from "class-variance-authority";
import { type VariantProps, cva } from "class-variance-authority";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Empty({ className, ...props }: React.ComponentProps<"div">) {
return (
@@ -18,7 +18,10 @@ function Empty({ className, ...props }: React.ComponentProps<"div">) {
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("flex max-w-sm flex-col items-center text-center", className)}
className={cn(
"flex max-w-sm flex-col items-center text-center",
className,
)}
data-slot="empty-header"
{...props}
/>
@@ -70,7 +73,10 @@ function EmptyMedia({
/>
</>
)}
<div className={cn(emptyMediaVariants({ className, variant }))} {...props} />
<div
className={cn(emptyMediaVariants({ className, variant }))}
{...props}
/>
</div>
);
}
@@ -111,4 +117,11 @@ function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
);
}
export { Empty, EmptyHeader, EmptyTitle, EmptyDescription, EmptyContent, EmptyMedia };
export {
Empty,
EmptyHeader,
EmptyTitle,
EmptyDescription,
EmptyContent,
EmptyMedia,
};
@@ -1,8 +1,6 @@
"use client";
import { Field as FieldPrimitive } from "@base-ui/react/field";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Field({ className, ...props }: FieldPrimitive.Root.Props) {
return (
@@ -29,11 +27,18 @@ function FieldLabel({ className, ...props }: FieldPrimitive.Label.Props) {
function FieldItem({ className, ...props }: FieldPrimitive.Item.Props) {
return (
<FieldPrimitive.Item className={cn("flex", className)} data-slot="field-item" {...props} />
<FieldPrimitive.Item
className={cn("flex", className)}
data-slot="field-item"
{...props}
/>
);
}
function FieldDescription({ className, ...props }: FieldPrimitive.Description.Props) {
function FieldDescription({
className,
...props
}: FieldPrimitive.Description.Props) {
return (
<FieldPrimitive.Description
className={cn("text-muted-foreground text-xs", className)}
@@ -56,4 +61,12 @@ function FieldError({ className, ...props }: FieldPrimitive.Error.Props) {
const FieldControl = FieldPrimitive.Control;
const FieldValidity = FieldPrimitive.Validity;
export { Field, FieldLabel, FieldDescription, FieldError, FieldControl, FieldItem, FieldValidity };
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldControl,
FieldItem,
FieldValidity,
};
@@ -1,8 +1,6 @@
"use client";
import { Fieldset as FieldsetPrimitive } from "@base-ui/react/fieldset";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Fieldset({ className, ...props }: FieldsetPrimitive.Root.Props) {
return (
@@ -13,7 +11,10 @@ function Fieldset({ className, ...props }: FieldsetPrimitive.Root.Props) {
/>
);
}
function FieldsetLegend({ className, ...props }: FieldsetPrimitive.Legend.Props) {
function FieldsetLegend({
className,
...props
}: FieldsetPrimitive.Legend.Props) {
return (
<FieldsetPrimitive.Legend
className={cn("font-semibold text-foreground", className)}
@@ -1,8 +1,6 @@
"use client";
import { Form as FormPrimitive } from "@base-ui/react/form";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Form({ className, ...props }: FormPrimitive.Props) {
return (
@@ -1,11 +1,9 @@
"use client";
import { cva, type VariantProps } from "class-variance-authority";
import { type VariantProps, cva } from "class-variance-authority";
import type * as React from "react";
import { cn } from "~/lib/utils";
import { Input, type InputProps } from "~/components/ui/input";
import { Textarea, type TextareaProps } from "~/components/ui/textarea";
import { Input, type InputProps } from "#/components/ui/input";
import { Textarea, type TextareaProps } from "#/components/ui/textarea";
import { cn } from "#/lib/utils";
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
@@ -60,9 +58,9 @@ function InputGroupAddon({
if (isInteractive) return;
e.preventDefault();
const parent = e.currentTarget.parentElement;
const input = parent?.querySelector<HTMLInputElement | HTMLTextAreaElement>(
"input, textarea",
);
const input = parent?.querySelector<
HTMLInputElement | HTMLTextAreaElement
>("input, textarea");
if (input && !parent?.querySelector("input:focus, textarea:focus")) {
input.focus();
}
@@ -92,4 +90,10 @@ function InputGroupTextarea({ className, ...props }: TextareaProps) {
return <Textarea className={className} unstyled {...props} />;
}
export { InputGroup, InputGroupAddon, InputGroupText, InputGroupInput, InputGroupTextarea };
export {
InputGroup,
InputGroupAddon,
InputGroupText,
InputGroupInput,
InputGroupTextarea,
};
@@ -1,11 +1,12 @@
"use client";
import { Input as InputPrimitive } from "@base-ui/react/input";
import type * as React from "react";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
type InputProps = Omit<InputPrimitive.Props & React.RefAttributes<HTMLInputElement>, "size"> & {
type InputProps = Omit<
InputPrimitive.Props & React.RefAttributes<HTMLInputElement>,
"size"
> & {
size?: "sm" | "default" | "lg" | number;
unstyled?: boolean;
nativeInput?: boolean;
@@ -20,7 +21,8 @@ function Input({
}: InputProps) {
const inputClassName = cn(
"h-8.5 w-full min-w-0 rounded-[inherit] px-[calc(--spacing(3)-1px)] leading-8.5 outline-none placeholder:text-muted-foreground/72 sm:h-7.5 sm:leading-7.5 [transition:background-color_5000000s_ease-in-out_0s]",
size === "sm" && "h-7.5 px-[calc(--spacing(2.5)-1px)] leading-7.5 sm:h-6.5 sm:leading-6.5",
size === "sm" &&
"h-7.5 px-[calc(--spacing(2.5)-1px)] leading-7.5 sm:h-6.5 sm:leading-6.5",
size === "lg" && "h-9.5 leading-9.5 sm:h-8.5 sm:leading-8.5",
props.type === "search" &&
"[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none [&::-webkit-search-results-button]:appearance-none [&::-webkit-search-results-decoration]:appearance-none",
@@ -1,6 +1,6 @@
import type * as React from "react";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
return (
@@ -1,11 +1,13 @@
"use client";
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Label({ className, render, ...props }: useRender.ComponentProps<"label">) {
function Label({
className,
render,
...props
}: useRender.ComponentProps<"label">) {
const defaultProps = {
className: cn(
"inline-flex items-center gap-2 text-base/4.5 sm:text-sm/4 font-medium text-foreground",
@@ -1,10 +1,7 @@
"use client";
import { Menu as MenuPrimitive } from "@base-ui/react/menu";
import { ChevronRightIcon } from "lucide-react";
import type * as React from "react";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
const MenuCreateHandle = MenuPrimitive.createHandle;
@@ -12,12 +9,8 @@ const Menu = MenuPrimitive.Root;
const MenuPortal = MenuPrimitive.Portal;
function MenuTrigger({ className, children, ...props }: MenuPrimitive.Trigger.Props) {
return (
<MenuPrimitive.Trigger className={className} data-slot="menu-trigger" {...props}>
{children}
</MenuPrimitive.Trigger>
);
function MenuTrigger(props: MenuPrimitive.Trigger.Props) {
return <MenuPrimitive.Trigger data-slot="menu-trigger" {...props} />;
}
function MenuPopup({
@@ -27,21 +20,18 @@ function MenuPopup({
align = "center",
alignOffset,
side = "bottom",
anchor,
...props
}: MenuPrimitive.Popup.Props & {
align?: MenuPrimitive.Positioner.Props["align"];
sideOffset?: MenuPrimitive.Positioner.Props["sideOffset"];
alignOffset?: MenuPrimitive.Positioner.Props["alignOffset"];
side?: MenuPrimitive.Positioner.Props["side"];
anchor?: MenuPrimitive.Positioner.Props["anchor"];
}) {
return (
<MenuPrimitive.Portal>
<MenuPrimitive.Positioner
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="z-50"
data-slot="menu-positioner"
side={side}
@@ -55,7 +45,9 @@ function MenuPopup({
data-slot="menu-popup"
{...props}
>
<div className="max-h-(--available-height) w-full overflow-y-auto p-1">{children}</div>
<div className="max-h-(--available-height) w-full overflow-y-auto p-1">
{children}
</div>
</MenuPrimitive.Popup>
</MenuPrimitive.Positioner>
</MenuPrimitive.Portal>
@@ -103,7 +95,9 @@ function MenuCheckboxItem({
checked={checked}
className={cn(
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default items-center gap-2 rounded-sm py-1 ps-2 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
variant === "switch" ? "grid-cols-[1fr_auto] gap-4 pe-1.5" : "grid-cols-[1rem_1fr] pe-4",
variant === "switch"
? "grid-cols-[1fr_auto] gap-4 pe-1.5"
: "grid-cols-[1rem_1fr] pe-4",
className,
)}
data-slot="menu-checkbox-item"
@@ -147,7 +141,11 @@ function MenuRadioGroup(props: MenuPrimitive.RadioGroup.Props) {
return <MenuPrimitive.RadioGroup data-slot="menu-radio-group" {...props} />;
}
function MenuRadioItem({ className, children, ...props }: MenuPrimitive.RadioItem.Props) {
function MenuRadioItem({
className,
children,
...props
}: MenuPrimitive.RadioItem.Props) {
return (
<MenuPrimitive.RadioItem
className={cn(
@@ -1,19 +1,13 @@
"use client";
import { Popover as PopoverPrimitive } from "@base-ui/react/popover";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
const PopoverCreateHandle = PopoverPrimitive.createHandle;
const Popover = PopoverPrimitive.Root;
function PopoverTrigger({ className, children, ...props }: PopoverPrimitive.Trigger.Props) {
return (
<PopoverPrimitive.Trigger className={className} data-slot="popover-trigger" {...props}>
{children}
</PopoverPrimitive.Trigger>
);
function PopoverTrigger(props: PopoverPrimitive.Trigger.Props) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
}
function PopoverPopup({
@@ -24,7 +18,6 @@ function PopoverPopup({
sideOffset = 4,
alignOffset = 0,
tooltipStyle = false,
anchor,
...props
}: PopoverPrimitive.Popup.Props & {
side?: PopoverPrimitive.Positioner.Props["side"];
@@ -32,14 +25,12 @@ function PopoverPopup({
sideOffset?: PopoverPrimitive.Positioner.Props["sideOffset"];
alignOffset?: PopoverPrimitive.Positioner.Props["alignOffset"];
tooltipStyle?: boolean;
anchor?: PopoverPrimitive.Positioner.Props["anchor"];
}) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Positioner
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="z-50 h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none"
data-slot="popover-positioner"
side={side}
@@ -47,7 +38,7 @@ function PopoverPopup({
>
<PopoverPrimitive.Popup
className={cn(
"relative flex h-(--popup-height,auto) w-(--popup-width,auto) origin-(--transform-origin) rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 outline-none transition-[width,height,scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] has-data-[slot=calendar]:rounded-xl has-data-[slot=calendar]:before:rounded-[calc(var(--radius-xl)-1px)] data-starting-style:scale-98 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
"relative flex h-(--popup-height,auto) w-(--popup-width,auto) origin-(--transform-origin) rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 transition-[width,height,scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-starting-style:scale-98 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
tooltipStyle &&
"w-fit text-balance rounded-md text-xs shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]",
className,
@@ -57,7 +48,7 @@ function PopoverPopup({
>
<PopoverPrimitive.Viewport
className={cn(
"relative size-full max-h-(--available-height) overflow-clip px-(--viewport-inline-padding) py-4 [--viewport-inline-padding:--spacing(4)] has-data-[slot=calendar]:p-2 data-instant:transition-none **:data-current:data-ending-style:opacity-0 **:data-current:data-starting-style:opacity-0 **:data-previous:data-ending-style:opacity-0 **:data-previous:data-starting-style:opacity-0 **:data-current:w-[calc(var(--popup-width)-2*var(--viewport-inline-padding)-2px)] **:data-previous:w-[calc(var(--popup-width)-2*var(--viewport-inline-padding)-2px)] **:data-current:opacity-100 **:data-previous:opacity-100 **:data-current:transition-opacity **:data-previous:transition-opacity",
"relative size-full max-h-(--available-height) overflow-clip px-(--viewport-inline-padding) py-4 outline-none [--viewport-inline-padding:--spacing(4)] data-instant:transition-none **:data-current:data-ending-style:opacity-0 **:data-current:data-starting-style:opacity-0 **:data-previous:data-ending-style:opacity-0 **:data-previous:data-starting-style:opacity-0 **:data-current:w-[calc(var(--popup-width)-2*var(--viewport-inline-padding)-2px)] **:data-previous:w-[calc(var(--popup-width)-2*var(--viewport-inline-padding)-2px)] **:data-current:opacity-100 **:data-previous:opacity-100 **:data-current:transition-opacity **:data-previous:transition-opacity",
tooltipStyle
? "py-1 [--viewport-inline-padding:--spacing(2)]"
: "not-data-transitioning:overflow-y-auto",
@@ -86,7 +77,10 @@ function PopoverTitle({ className, ...props }: PopoverPrimitive.Title.Props) {
);
}
function PopoverDescription({ className, ...props }: PopoverPrimitive.Description.Props) {
function PopoverDescription({
className,
...props
}: PopoverPrimitive.Description.Props) {
return (
<PopoverPrimitive.Description
className={cn("text-muted-foreground text-sm", className)}
@@ -0,0 +1,79 @@
import { Progress as ProgressPrimitive } from "@base-ui/react/progress";
import { cn } from "#/lib/utils";
function Progress({
className,
children,
...props
}: ProgressPrimitive.Root.Props) {
return (
<ProgressPrimitive.Root
className={cn("flex w-full flex-col gap-2", className)}
data-slot="progress"
{...props}
>
{children ? (
children
) : (
<ProgressTrack>
<ProgressIndicator />
</ProgressTrack>
)}
</ProgressPrimitive.Root>
);
}
function ProgressLabel({ className, ...props }: ProgressPrimitive.Label.Props) {
return (
<ProgressPrimitive.Label
className={cn("font-medium text-sm", className)}
data-slot="progress-label"
{...props}
/>
);
}
function ProgressTrack({ className, ...props }: ProgressPrimitive.Track.Props) {
return (
<ProgressPrimitive.Track
className={cn(
"block h-1.5 w-full overflow-hidden rounded-full bg-input",
className,
)}
data-slot="progress-track"
{...props}
/>
);
}
function ProgressIndicator({
className,
...props
}: ProgressPrimitive.Indicator.Props) {
return (
<ProgressPrimitive.Indicator
className={cn("bg-primary transition-all duration-500", className)}
data-slot="progress-indicator"
{...props}
/>
);
}
function ProgressValue({ className, ...props }: ProgressPrimitive.Value.Props) {
return (
<ProgressPrimitive.Value
className={cn("text-sm tabular-nums", className)}
data-slot="progress-value"
{...props}
/>
);
}
export {
Progress,
ProgressLabel,
ProgressTrack,
ProgressIndicator,
ProgressValue,
};
@@ -1,9 +1,7 @@
"use client";
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
import { RadioGroup as RadioGroupPrimitive } from "@base-ui/react/radio-group";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function RadioGroup({ className, ...props }: RadioGroupPrimitive.Props) {
return (
@@ -1,8 +1,6 @@
"use client";
import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function ScrollArea({
className,
@@ -15,13 +13,17 @@ function ScrollArea({
scrollbarGutter?: boolean;
}) {
return (
<ScrollAreaPrimitive.Root className={cn("size-full min-h-0", className)} {...props}>
<ScrollAreaPrimitive.Root
className={cn("size-full min-h-0", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
className={cn(
"h-full overscroll-contain rounded-[inherit] outline-none transition-shadows focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain",
scrollFade &&
"mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] [--fade-size:1.5rem]",
scrollbarGutter && "data-has-overflow-y:pe-2.5 data-has-overflow-x:pb-2.5",
scrollbarGutter &&
"data-has-overflow-y:pe-2.5 data-has-overflow-x:pb-2.5",
)}
data-slot="scroll-area-viewport"
>
@@ -1,92 +1,37 @@
"use client";
import { mergeProps } from "@base-ui/react/merge-props";
import { Select as SelectPrimitive } from "@base-ui/react/select";
import { useRender } from "@base-ui/react/use-render";
import { cva, type VariantProps } from "class-variance-authority";
import { ChevronDownIcon, ChevronsUpDownIcon, ChevronUpIcon } from "lucide-react";
import type * as React from "react";
import {
ChevronDownIcon,
ChevronUpIcon,
ChevronsUpDownIcon,
} from "lucide-react";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
const Select = SelectPrimitive.Root;
const selectTriggerVariants = cva(
"relative inline-flex select-none items-center justify-between gap-2 border rounded-lg text-left text-base outline-none transition-[color,box-shadow,background-color] data-disabled:pointer-events-none data-disabled:opacity-64 sm:text-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4",
{
defaultVariants: {
size: "default",
variant: "default",
},
variants: {
variant: {
default:
"w-full min-w-36 border-input bg-background not-dark:bg-clip-padding text-foreground shadow-xs/5 ring-ring/24 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 focus-visible:border-ring focus-visible:ring-[3px] aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/16 dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='opacity-'])]:opacity-80 [[data-disabled],:focus-visible,[aria-invalid],[data-pressed]]:shadow-none",
ghost:
"border-transparent text-muted-foreground/70 focus-visible:ring-2 focus-visible:ring-ring data-pressed:bg-accent [:hover,[data-pressed]]:bg-accent [:hover,[data-pressed]]:text-foreground/80",
},
size: {
default: "min-h-9 px-[calc(--spacing(3)-1px)] sm:min-h-8",
lg: "min-h-10 px-[calc(--spacing(3)-1px)] sm:min-h-9",
sm: "min-h-8 gap-1.5 px-[calc(--spacing(2.5)-1px)] sm:min-h-7",
},
},
},
);
const selectTriggerIconClassName = "-me-1 size-4.5 opacity-80 sm:size-4";
interface SelectButtonProps extends useRender.ComponentProps<"button"> {
size?: VariantProps<typeof selectTriggerVariants>["size"];
variant?: VariantProps<typeof selectTriggerVariants>["variant"];
}
function SelectButton({ className, size, variant, render, children, ...props }: SelectButtonProps) {
const typeValue: React.ButtonHTMLAttributes<HTMLButtonElement>["type"] = render
? undefined
: "button";
const defaultProps = {
children: (
<>
<span className="flex-1 truncate in-data-placeholder:text-muted-foreground/72">
{children}
</span>
{variant === "ghost" ? (
<ChevronDownIcon className="size-3 opacity-50" />
) : (
<ChevronsUpDownIcon className={selectTriggerIconClassName} />
)}
</>
),
className: cn(selectTriggerVariants({ size, variant }), "min-w-none", className),
"data-slot": "select-button",
type: typeValue,
};
return useRender({
defaultTagName: "button",
props: mergeProps<"button">(defaultProps, props),
render,
});
}
function SelectTrigger({
className,
size = "default",
variant = "default",
children,
...props
}: SelectPrimitive.Trigger.Props & VariantProps<typeof selectTriggerVariants>) {
}: SelectPrimitive.Trigger.Props & {
size?: "sm" | "default" | "lg";
}) {
return (
<SelectPrimitive.Trigger
className={cn(selectTriggerVariants({ size, variant }), className)}
className={cn(
"relative inline-flex min-h-9 w-full min-w-36 select-none items-center justify-center gap-2 rounded-lg border border-input bg-background not-dark:bg-clip-padding px-[calc(--spacing(3)-1px)] text-left text-base text-foreground shadow-xs/5 outline-none ring-ring/24 transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 focus-visible:border-ring focus-visible:ring-[3px] aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/16 data-disabled:pointer-events-none data-disabled:opacity-64 sm:min-h-8 sm:text-sm dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0 [[data-disabled],:focus-visible,[aria-invalid],[data-pressed]]:shadow-none",
size === "sm" &&
"min-h-8 gap-1.5 px-[calc(--spacing(2.5)-1px)] sm:min-h-7",
size === "lg" && "min-h-10 sm:min-h-9",
className,
)}
data-slot="select-trigger"
{...props}
>
{children}
<SelectPrimitive.Icon data-slot="select-icon">
<ChevronDownIcon className="size-3 opacity-50" />
<ChevronsUpDownIcon className="-me-1 size-4.5 opacity-80 sm:size-4" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
);
@@ -95,7 +40,10 @@ function SelectTrigger({
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
return (
<SelectPrimitive.Value
className={cn("flex-1 truncate data-placeholder:text-muted-foreground", className)}
className={cn(
"flex-1 truncate data-placeholder:text-muted-foreground",
className,
)}
data-slot="select-value"
{...props}
/>
@@ -110,7 +58,6 @@ function SelectPopup({
align = "start",
alignOffset = 0,
alignItemWithTrigger = true,
anchor,
...props
}: SelectPrimitive.Popup.Props & {
side?: SelectPrimitive.Positioner.Props["side"];
@@ -118,7 +65,6 @@ function SelectPopup({
align?: SelectPrimitive.Positioner.Props["align"];
alignOffset?: SelectPrimitive.Positioner.Props["alignOffset"];
alignItemWithTrigger?: SelectPrimitive.Positioner.Props["alignItemWithTrigger"];
anchor?: SelectPrimitive.Positioner.Props["anchor"];
}) {
return (
<SelectPrimitive.Portal>
@@ -126,7 +72,6 @@ function SelectPopup({
align={align}
alignItemWithTrigger={alignItemWithTrigger}
alignOffset={alignOffset}
anchor={anchor}
className="z-50 select-none"
data-slot="select-positioner"
side={side}
@@ -145,7 +90,10 @@ function SelectPopup({
</SelectPrimitive.ScrollUpArrow>
<div className="relative h-full min-w-(--anchor-width) rounded-lg border bg-popover not-dark:bg-clip-padding shadow-lg/5 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%)]">
<SelectPrimitive.List
className={cn("max-h-(--available-height) overflow-y-auto p-1", className)}
className={cn(
"max-h-(--available-height) overflow-y-auto p-1",
className,
)}
data-slot="select-list"
>
{children}
@@ -163,7 +111,11 @@ function SelectPopup({
);
}
function SelectItem({ className, children, ...props }: SelectPrimitive.Item.Props) {
function SelectItem({
className,
children,
...props
}: SelectPrimitive.Item.Props) {
return (
<SelectPrimitive.Item
className={cn(
@@ -195,7 +147,10 @@ function SelectItem({ className, children, ...props }: SelectPrimitive.Item.Prop
);
}
function SelectSeparator({ className, ...props }: SelectPrimitive.Separator.Props) {
function SelectSeparator({
className,
...props
}: SelectPrimitive.Separator.Props) {
return (
<SelectPrimitive.Separator
className={cn("mx-2 my-1 h-px bg-border", className)}
@@ -222,8 +177,6 @@ function SelectGroupLabel(props: SelectPrimitive.GroupLabel.Props) {
export {
Select,
SelectTrigger,
SelectButton,
selectTriggerVariants,
SelectValue,
SelectPopup,
SelectPopup as SelectContent,
@@ -1,8 +1,12 @@
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Separator({ className, orientation = "horizontal", ...props }: SeparatorPrimitive.Props) {
function Separator({
className,
orientation = "horizontal",
...props
}: SeparatorPrimitive.Props) {
return (
<SeparatorPrimitive
className={cn(
@@ -1,10 +1,8 @@
"use client";
import { Dialog as SheetPrimitive } from "@base-ui/react/dialog";
import { XIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { Button } from "~/components/ui/button";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Button } from "#/components/ui/button";
import { ScrollArea } from "#/components/ui/scroll-area";
import { cn } from "#/lib/utils";
const Sheet = SheetPrimitive.Root;
@@ -144,14 +142,20 @@ function SheetFooter({
function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) {
return (
<SheetPrimitive.Title
className={cn("font-heading font-semibold text-xl leading-none", className)}
className={cn(
"font-heading font-semibold text-xl leading-none",
className,
)}
data-slot="sheet-title"
{...props}
/>
);
}
function SheetDescription({ className, ...props }: SheetPrimitive.Description.Props) {
function SheetDescription({
className,
...props
}: SheetPrimitive.Description.Props) {
return (
<SheetPrimitive.Description
className={cn("text-muted-foreground text-sm", className)}
@@ -1,4 +1,4 @@
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
@@ -1,7 +1,10 @@
import { Loader2Icon } from "lucide-react";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Spinner({ className, ...props }: React.ComponentProps<typeof Loader2Icon>) {
function Spinner({
className,
...props
}: React.ComponentProps<typeof Loader2Icon>) {
return (
<Loader2Icon
aria-label="Loading"
@@ -1,8 +1,6 @@
"use client";
import { Switch as SwitchPrimitive } from "@base-ui/react/switch";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
function Switch({ className, ...props }: SwitchPrimitive.Root.Props) {
return (
@@ -16,7 +14,7 @@ function Switch({ className, ...props }: SwitchPrimitive.Root.Props) {
>
<SwitchPrimitive.Thumb
className={cn(
"pointer-events-none block aspect-square h-full origin-left in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:not-data-disabled:scale-x-110 in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:rounded-[var(--thumb-size)/calc(var(--thumb-size)*1.1)] rounded-(--thumb-size) bg-background shadow-sm/5 will-change-transform [transition:translate_.15s,border-radius_.15s,scale_.1s_.1s,transform-origin_.15s] data-checked:origin-[var(--thumb-size)_50%] data-checked:translate-x-[calc(var(--thumb-size)-4px)]",
"pointer-events-none block aspect-square h-full origin-left in-[[role=switch]:active,[data-slot=label]:active]:not-data-disabled:scale-x-110 in-[[role=switch]:active,[data-slot=label]:active]:rounded-[var(--thumb-size)/calc(var(--thumb-size)*1.1)] rounded-(--thumb-size) bg-background shadow-sm/5 will-change-transform [transition:translate_.15s,border-radius_.15s,scale_.1s_.1s,transform-origin_.15s] data-checked:origin-[var(--thumb-size)_50%] data-checked:translate-x-[calc(var(--thumb-size)-4px)]",
)}
data-slot="switch-thumb"
/>
+126
View File
@@ -0,0 +1,126 @@
import type * as React from "react";
import { cn } from "#/lib/utils";
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
className="relative w-full overflow-x-auto"
data-slot="table-container"
>
<table
className={cn(
"w-full caption-bottom in-data-[slot=frame]:border-separate in-data-[slot=frame]:border-spacing-0 text-sm",
className,
)}
data-slot="table"
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
className={cn(
"[&_tr]:border-b in-data-[slot=frame]:**:[th]:h-9 in-data-[slot=frame]:*:[tr]:border-none in-data-[slot=frame]:*:[tr]:hover:bg-transparent",
className,
)}
data-slot="table-header"
{...props}
/>
);
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
className={cn(
"relative in-data-[slot=frame]:rounded-xl in-data-[slot=frame]:shadow-xs/5 before:pointer-events-none before:absolute before:inset-px not-in-data-[slot=frame]:before:hidden before:rounded-[calc(var(--radius-xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/8%)] [&_tr:last-child]:border-0 in-data-[slot=frame]:*:[tr]:border-0 in-data-[slot=frame]:*:[tr]:*:[td]:border-b in-data-[slot=frame]:*:[tr]:*:[td]:bg-background in-data-[slot=frame]:*:[tr]:*:[td]:bg-clip-padding in-data-[slot=frame]:*:[tr]:first:*:[td]:first:rounded-ss-xl in-data-[slot=frame]:*:[tr]:*:[td]:first:border-s in-data-[slot=frame]:*:[tr]:first:*:[td]:border-t in-data-[slot=frame]:*:[tr]:last:*:[td]:last:rounded-ee-xl in-data-[slot=frame]:*:[tr]:*:[td]:last:border-e in-data-[slot=frame]:*:[tr]:first:*:[td]:last:rounded-se-xl in-data-[slot=frame]:*:[tr]:last:*:[td]:first:rounded-es-xl in-data-[slot=frame]:*:[tr]:hover:*:[td]:bg-transparent in-data-[slot=frame]:*:[tr]:data-[state=selected]:*:[td]:bg-muted/72",
className,
)}
data-slot="table-body"
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
className={cn(
"border-t in-data-[slot=frame]:border-none bg-muted/72 in-data-[slot=frame]:bg-transparent font-medium [&>tr]:last:border-b-0 in-data-[slot=frame]:*:[tr]:hover:bg-transparent",
className,
)}
data-slot="table-footer"
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
className={cn(
"border-b transition-colors hover:bg-muted/72 in-data-[slot=frame]:hover:bg-transparent data-[state=selected]:bg-muted/72 in-data-[slot=frame]:data-[state=selected]:bg-transparent",
className,
)}
data-slot="table-row"
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
className={cn(
"h-10 whitespace-nowrap px-2.5 text-left align-middle font-medium text-muted-foreground leading-none has-[[role=checkbox]]:w-px has-[[role=checkbox]]:pe-0",
className,
)}
data-slot="table-head"
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
className={cn(
"whitespace-nowrap p-2.5 align-middle leading-none in-data-[slot=frame]:first:p-[calc(--spacing(2.5)-1px)] in-data-[slot=frame]:last:p-[calc(--spacing(2.5)-1px)] has-[[role=checkbox]]:pe-0",
className,
)}
data-slot="table-cell"
{...props}
/>
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
className={cn(
"in-data-[slot=frame]:my-4 mt-4 text-muted-foreground text-sm",
className,
)}
data-slot="table-caption"
{...props}
/>
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};
+85
View File
@@ -0,0 +1,85 @@
import { Tabs as TabsPrimitive } from "@base-ui/react/tabs";
import { cn } from "#/lib/utils";
type TabsVariant = "default" | "underline";
function Tabs({ className, ...props }: TabsPrimitive.Root.Props) {
return (
<TabsPrimitive.Root
className={cn(
"flex flex-col gap-2 data-[orientation=vertical]:flex-row",
className,
)}
data-slot="tabs"
{...props}
/>
);
}
function TabsList({
variant = "default",
className,
children,
...props
}: TabsPrimitive.List.Props & {
variant?: TabsVariant;
}) {
return (
<TabsPrimitive.List
className={cn(
"relative z-0 flex w-fit items-center justify-center gap-x-0.5 text-muted-foreground",
"data-[orientation=vertical]:flex-col",
variant === "default"
? "rounded-lg bg-muted p-0.5 text-muted-foreground/72"
: "data-[orientation=vertical]:px-1 data-[orientation=horizontal]:py-1 *:data-[slot=tabs-tab]:hover:bg-accent",
className,
)}
data-slot="tabs-list"
{...props}
>
{children}
<TabsPrimitive.Indicator
className={cn(
"-translate-y-(--active-tab-bottom) absolute bottom-0 left-0 h-(--active-tab-height) w-(--active-tab-width) translate-x-(--active-tab-left) transition-[width,translate] duration-200 ease-in-out",
variant === "underline"
? "data-[orientation=vertical]:-translate-x-px z-10 bg-primary data-[orientation=horizontal]:h-0.5 data-[orientation=vertical]:w-0.5 data-[orientation=horizontal]:translate-y-px"
: "-z-1 rounded-md bg-background shadow-sm/5 dark:bg-input",
)}
data-slot="tab-indicator"
/>
</TabsPrimitive.List>
);
}
function TabsTab({ className, ...props }: TabsPrimitive.Tab.Props) {
return (
<TabsPrimitive.Tab
className={cn(
"[&_svg]:-mx-0.5 relative flex h-9 shrink-0 grow cursor-pointer items-center justify-center gap-1.5 whitespace-nowrap rounded-md border border-transparent px-[calc(--spacing(2.5)-1px)] font-medium text-base outline-none transition-[color,background-color,box-shadow] hover:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring data-disabled:pointer-events-none data-[orientation=vertical]:w-full data-[orientation=vertical]:justify-start data-active:text-foreground data-disabled:opacity-64 sm:h-8 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
className,
)}
data-slot="tabs-tab"
{...props}
/>
);
}
function TabsPanel({ className, ...props }: TabsPrimitive.Panel.Props) {
return (
<TabsPrimitive.Panel
className={cn("flex-1 outline-none", className)}
data-slot="tabs-content"
{...props}
/>
);
}
export {
Tabs,
TabsList,
TabsTab,
TabsTab as TabsTrigger,
TabsPanel,
TabsPanel as TabsContent,
};
@@ -1,17 +1,20 @@
"use client";
import { Field as FieldPrimitive } from "@base-ui/react/field";
import { mergeProps } from "@base-ui/react/merge-props";
import type * as React from "react";
import { cn } from "~/lib/utils";
import { cn } from "#/lib/utils";
type TextareaProps = React.ComponentProps<"textarea"> & {
size?: "sm" | "default" | "lg" | number;
unstyled?: boolean;
};
function Textarea({ className, size = "default", unstyled = false, ...props }: TextareaProps) {
function Textarea({
className,
size = "default",
unstyled = false,
...props
}: TextareaProps) {
return (
<span
className={
@@ -31,7 +34,8 @@ function Textarea({ className, size = "default", unstyled = false, ...props }: T
"field-sizing-content min-h-17.5 w-full rounded-[inherit] px-[calc(--spacing(3)-1px)] py-[calc(--spacing(1.5)-1px)] outline-none max-sm:min-h-20.5",
size === "sm" &&
"min-h-16.5 px-[calc(--spacing(2.5)-1px)] py-[calc(--spacing(1)-1px)] max-sm:min-h-19.5",
size === "lg" && "min-h-18.5 py-[calc(--spacing(2)-1px)] max-sm:min-h-21.5",
size === "lg" &&
"min-h-18.5 py-[calc(--spacing(2)-1px)] max-sm:min-h-21.5",
)}
data-slot="textarea"
{...mergeProps(defaultProps, props)}
+267
View File
@@ -0,0 +1,267 @@
import { Toast } from "@base-ui/react/toast";
import {
CircleAlertIcon,
CircleCheckIcon,
InfoIcon,
LoaderCircleIcon,
TriangleAlertIcon,
} from "lucide-react";
import { buttonVariants } from "#/components/ui/button";
import { cn } from "#/lib/utils";
const toastManager = Toast.createToastManager();
const anchoredToastManager = Toast.createToastManager();
const TOAST_ICONS = {
error: CircleAlertIcon,
info: InfoIcon,
loading: LoaderCircleIcon,
success: CircleCheckIcon,
warning: TriangleAlertIcon,
} as const;
type ToastPosition =
| "top-left"
| "top-center"
| "top-right"
| "bottom-left"
| "bottom-center"
| "bottom-right";
interface ToastProviderProps extends Toast.Provider.Props {
position?: ToastPosition;
}
function ToastProvider({
children,
position = "bottom-right",
...props
}: ToastProviderProps) {
return (
<Toast.Provider toastManager={toastManager} {...props}>
{children}
<Toasts position={position} />
</Toast.Provider>
);
}
function Toasts({ position = "bottom-right" }: { position: ToastPosition }) {
const { toasts } = Toast.useToastManager();
const isTop = position.startsWith("top");
return (
<Toast.Portal data-slot="toast-portal">
<Toast.Viewport
className={cn(
"fixed z-50 mx-auto flex w-[calc(100%-var(--toast-inset)*2)] max-w-90 [--toast-inset:--spacing(4)] sm:[--toast-inset:--spacing(8)]",
// Vertical positioning
"data-[position*=top]:top-(--toast-inset)",
"data-[position*=bottom]:bottom-(--toast-inset)",
// Horizontal positioning
"data-[position*=left]:left-(--toast-inset)",
"data-[position*=right]:right-(--toast-inset)",
"data-[position*=center]:-translate-x-1/2 data-[position*=center]:left-1/2",
)}
data-position={position}
data-slot="toast-viewport"
>
{toasts.map((toast) => {
const Icon = toast.type
? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS]
: null;
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-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)))]",
)}
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"
>
{toast.actionProps.children}
</Toast.Action>
)}
</Toast.Content>
</Toast.Root>
);
})}
</Toast.Viewport>
</Toast.Portal>
);
}
function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
return (
<Toast.Provider toastManager={anchoredToastManager} {...props}>
{children}
<AnchoredToasts />
</Toast.Provider>
);
}
function AnchoredToasts() {
const { toasts } = Toast.useToastManager();
return (
<Toast.Portal data-slot="toast-portal-anchored">
<Toast.Viewport
className="outline-none"
data-slot="toast-viewport-anchored"
>
{toasts.map((toast) => {
const Icon = toast.type
? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS]
: null;
const tooltipStyle =
(toast.data as { tooltipStyle?: boolean })?.tooltipStyle ?? false;
const positionerProps = toast.positionerProps;
if (!positionerProps?.anchor) {
return null;
}
return (
<Toast.Positioner
className="z-50 max-w-[min(--spacing(64),var(--available-width))]"
data-slot="toast-positioner"
key={toast.id}
sideOffset={positionerProps.sideOffset ?? 4}
toast={toast}
>
<Toast.Root
className={cn(
"relative text-balance border bg-popover not-dark:bg-clip-padding text-popover-foreground text-xs transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
tooltipStyle
? "rounded-md shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]"
: "rounded-lg shadow-lg/5 before:rounded-[calc(var(--radius-lg)-1px)]",
)}
data-slot="toast-popup"
toast={toast}
>
{tooltipStyle ? (
<Toast.Content className="pointer-events-auto px-2 py-1">
<Toast.Title data-slot="toast-title" />
</Toast.Content>
) : (
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm">
<div className="flex gap-2">
{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"
>
{toast.actionProps.children}
</Toast.Action>
)}
</Toast.Content>
)}
</Toast.Root>
</Toast.Positioner>
);
})}
</Toast.Viewport>
</Toast.Portal>
);
}
export {
ToastProvider,
type ToastPosition,
toastManager,
AnchoredToastProvider,
anchoredToastManager,
};
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useSyncExternalStore } from "react";
type Theme = "light" | "dark" | "system";
const STORAGE_KEY = "t3code:theme";
const STORAGE_KEY = "codething:theme";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
let listeners: Array<() => void> = [];
@@ -11,6 +11,19 @@
--color-info-foreground: var(--info-foreground);
--color-info: var(--info);
--color-destructive-foreground: var(--destructive-foreground);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
@@ -48,7 +61,7 @@
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground relative;
@apply bg-background text-foreground;
}
}
@@ -70,18 +83,35 @@
--card-foreground: var(--color-neutral-800);
--popover: var(--color-white);
--popover-foreground: var(--color-neutral-800);
--primary: oklch(0.488 0.217 264);
--primary-foreground: var(--color-white);
--primary: var(--color-neutral-800);
--primary-foreground: var(--color-neutral-50);
--secondary: --alpha(var(--color-black) / 4%);
--secondary-foreground: var(--color-neutral-800);
--muted: --alpha(var(--color-black) / 4%);
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-black));
--muted-foreground: color-mix(
in srgb,
var(--color-neutral-500) 90%,
var(--color-black)
);
--accent: --alpha(var(--color-black) / 4%);
--accent-foreground: var(--color-neutral-800);
--destructive: var(--color-red-500);
--border: --alpha(var(--color-black) / 8%);
--input: --alpha(var(--color-black) / 10%);
--ring: oklch(0.488 0.217 264);
--ring: var(--color-neutral-400);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.141 0.005 285.823);
--sidebar-primary: oklch(0.21 0.006 285.885);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.967 0.001 286.375);
--sidebar-accent-foreground: oklch(0.21 0.006 285.885);
--sidebar-border: oklch(0.92 0.004 286.32);
--sidebar-ring: oklch(0.705 0.015 286.067);
--destructive-foreground: var(--color-red-700);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-700);
@@ -92,24 +122,49 @@
@variant dark {
color-scheme: dark;
--background: color-mix(in srgb, var(--color-neutral-950) 95%, var(--color-white));
--background: color-mix(
in srgb,
var(--color-neutral-950) 95%,
var(--color-white)
);
--foreground: var(--color-neutral-100);
--card: color-mix(in srgb, var(--background) 98%, var(--color-white));
--card-foreground: var(--color-neutral-100);
--popover: color-mix(in srgb, var(--background) 98%, var(--color-white));
--popover-foreground: var(--color-neutral-100);
--primary: oklch(0.588 0.217 264);
--primary-foreground: var(--color-white);
--primary: var(--color-neutral-100);
--primary-foreground: var(--color-neutral-800);
--secondary: --alpha(var(--color-white) / 4%);
--secondary-foreground: var(--color-neutral-100);
--muted: --alpha(var(--color-white) / 4%);
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-white));
--muted-foreground: color-mix(
in srgb,
var(--color-neutral-500) 90%,
var(--color-white)
);
--accent: --alpha(var(--color-white) / 4%);
--accent-foreground: var(--color-neutral-100);
--destructive: color-mix(in srgb, var(--color-red-500) 90%, var(--color-white));
--destructive: color-mix(
in srgb,
var(--color-red-500) 90%,
var(--color-white)
);
--border: --alpha(var(--color-white) / 6%);
--input: --alpha(var(--color-white) / 8%);
--ring: oklch(0.588 0.217 264);
--ring: var(--color-neutral-500);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.21 0.006 285.885);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.274 0.006 286.033);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.552 0.016 285.938);
--destructive-foreground: var(--color-red-400);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-400);
@@ -122,12 +177,7 @@
body {
font-family:
"DM Sans",
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
system-ui,
sans-serif;
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
margin: 0;
padding: 0;
min-height: 100vh;
@@ -190,33 +240,6 @@ input {
background: rgba(255, 255, 255, 0.18);
}
/* Terminal drawer scrollbar parity with chat */
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical {
width: 6px !important;
}
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar > .slider {
border-radius: 3px;
}
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical > .slider {
width: 6px !important;
left: 0 !important;
}
/* Reasoning select -- clickable label surface */
label:has(> select#reasoning-effort) {
position: relative;
}
label:has(> select#reasoning-effort) select {
position: absolute;
inset: 0;
opacity: 0;
cursor: pointer;
width: 100%;
height: 100%;
}
/* Chat markdown rendering */
.chat-markdown {
overflow-wrap: anywhere;
@@ -251,7 +274,11 @@ label:has(> select#reasoning-effort) select {
.chat-markdown a {
color: var(--info-foreground);
text-decoration: underline;
text-decoration-color: color-mix(in srgb, var(--info-foreground) 40%, transparent);
text-decoration-color: color-mix(
in srgb,
var(--info-foreground) 40%,
transparent
);
}
.chat-markdown a:hover {
+6
View File
@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
@@ -1,6 +1,5 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "@xterm/xterm/css/xterm.css";
import "highlight.js/styles/github-dark.css";
import App from "./App";
File renamed without changes.
@@ -3,8 +3,7 @@ export {
MODEL_OPTIONS,
normalizeModelSlug,
resolveModelSlug,
} from "@t3tools/contracts";
} from "@acme/contracts";
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
export type ReasoningEffort = (typeof REASONING_OPTIONS)[number];
export const DEFAULT_REASONING: ReasoningEffort = "high";
export const DEFAULT_REASONING = "high";
+168
View File
@@ -0,0 +1,168 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import type { Thread } from "./types";
describe("hydratePersistedState", () => {
it("returns null for invalid payloads", () => {
expect(hydratePersistedState('{"projects":"bad"}', false)).toBeNull();
expect(hydratePersistedState("not-json", false)).toBeNull();
});
it("migrates the legacy default model to the current default", () => {
const payload = JSON.stringify({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.2-codex",
expanded: true,
},
],
threads: [
{
id: "t-1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.2-codex",
messages: [
{
id: "m-1",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: true,
},
],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, true);
expect(hydrated).not.toBeNull();
expect(hydrated?.projects[0]?.model).toBe(DEFAULT_MODEL);
expect(hydrated?.threads[0]?.model).toBe(DEFAULT_MODEL);
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
expect(hydrated?.runtimeMode).toBe("full-access");
});
it("filters unknown project references and repairs active thread", () => {
const payload = JSON.stringify({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
},
],
threads: [
{
id: "t-1",
projectId: "p-1",
title: "Valid thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
{
id: "t-2",
projectId: "p-missing",
title: "Dangling thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-2",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated).not.toBeNull();
expect(hydrated?.threads.map((thread) => thread.id)).toEqual(["t-1"]);
expect(hydrated?.activeThreadId).toBe("t-1");
expect(hydrated?.runtimeMode).toBe("full-access");
});
it("hydrates runtime mode from v3 payload", () => {
const payload = JSON.stringify({
version: 3,
runtimeMode: "approval-required",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
},
],
threads: [],
activeThreadId: null,
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.runtimeMode).toBe("approval-required");
});
});
describe("toPersistedState", () => {
it("writes v3 payload and strips non-persisted thread fields", () => {
const thread: Thread = {
id: "t-1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
session: null,
messages: [
{
id: "m-1",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
events: [],
error: "boom",
createdAt: "2026-02-08T10:00:00.000Z",
};
const persisted = toPersistedState({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [thread],
activeThreadId: "t-1",
runtimeMode: "full-access",
});
expect(persisted.version).toBe(3);
expect(persisted.runtimeMode).toBe("full-access");
expect(persisted.threads[0]).toEqual({
id: "t-1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
messages: thread.messages,
createdAt: thread.createdAt,
});
const persistedThread = persisted.threads[0];
expect(persistedThread).toBeDefined();
if (!persistedThread) return;
expect("error" in persistedThread).toBe(false);
expect("session" in persistedThread).toBe(false);
});
});
+168
View File
@@ -0,0 +1,168 @@
import { z } from "zod";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import {
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
type Thread,
} from "./types";
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
const persistedProjectSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
cwd: z.string().min(1),
model: z.string().min(1),
expanded: z.boolean(),
});
const persistedMessageSchema = z.object({
id: z.string().min(1),
role: z.enum(["user", "assistant"]),
text: z.string(),
createdAt: z.string().min(1),
streaming: z.boolean(),
});
const persistedThreadSchema = z.object({
id: z.string().min(1),
projectId: z.string().min(1),
title: z.string().min(1),
model: z.string().min(1),
messages: z.array(persistedMessageSchema),
createdAt: z.string().min(1),
});
const persistedStateBodySchema = z.object({
projects: z.array(persistedProjectSchema),
threads: z.array(persistedThreadSchema),
activeThreadId: z.string().min(1).nullable(),
});
const runtimeModeSchema = z.enum(["approval-required", "full-access"]);
export const persistedStateV1Schema = persistedStateBodySchema.extend({
version: z.literal(1).optional(),
});
export const persistedStateV2Schema = persistedStateBodySchema.extend({
version: z.literal(2).optional(),
});
export const persistedStateV3Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(3).optional(),
});
const persistedStateSchema = z.union([
persistedStateV3Schema,
persistedStateV2Schema,
persistedStateV1Schema,
]);
export interface PersistedStoreSnapshot {
projects: Project[];
threads: Thread[];
activeThreadId: string | null;
runtimeMode: RuntimeMode;
}
function maybeMigrateLegacyModel(model: string, isLegacyPayload: boolean): string {
if (!isLegacyPayload) {
return model;
}
return model === LEGACY_DEFAULT_MODEL ? DEFAULT_MODEL : model;
}
function hydrateProject(
project: z.infer<typeof persistedProjectSchema>,
isLegacyPayload: boolean,
): Project {
return {
...project,
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
};
}
function hydrateThread(
thread: z.infer<typeof persistedThreadSchema>,
isLegacyPayload: boolean,
): Thread {
return {
id: thread.id,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
session: null,
messages: thread.messages.map((message) => ({
...message,
streaming: false,
})),
events: [],
error: null,
createdAt: thread.createdAt,
};
}
export function hydratePersistedState(
raw: string,
isLegacyPayload: boolean,
): PersistedStoreSnapshot | null {
let parsedJson: unknown;
try {
parsedJson = JSON.parse(raw);
} catch {
return null;
}
const parsedState = persistedStateSchema.safeParse(parsedJson);
if (!parsedState.success) {
return null;
}
const projects = parsedState.data.projects.map((project) =>
hydrateProject(project, isLegacyPayload),
);
const projectIds = new Set(projects.map((project) => project.id));
const threads = parsedState.data.threads
.map((thread) => hydrateThread(thread, isLegacyPayload))
.filter((thread) => projectIds.has(thread.projectId));
const hasActiveThread = Boolean(
parsedState.data.activeThreadId &&
threads.some((thread) => thread.id === parsedState.data.activeThreadId),
);
return {
projects,
threads,
activeThreadId: hasActiveThread
? parsedState.data.activeThreadId
: (threads[0]?.id ?? null),
runtimeMode:
"runtimeMode" in parsedState.data
? parsedState.data.runtimeMode
: DEFAULT_RUNTIME_MODE,
};
}
export function toPersistedState(
state: PersistedStoreSnapshot,
): z.infer<typeof persistedStateV3Schema> {
return {
version: 3,
projects: state.projects,
threads: state.threads.map((thread) => ({
id: thread.id,
projectId: thread.projectId,
title: thread.title,
model: thread.model,
messages: thread.messages,
createdAt: thread.createdAt,
})),
activeThreadId: state.activeThreadId,
runtimeMode: state.runtimeMode,
};
}
@@ -1,10 +1,9 @@
import { describe, expect, it } from "vitest";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import {
type WorkLogEntry,
applyEventToMessages,
derivePendingApprovals,
deriveTimelineEntries,
deriveWorkLogEntries,
evolveSession,
@@ -135,7 +134,7 @@ describe("deriveWorkLogEntries", () => {
expect(entries[0]?.label).toBe("Tool call");
});
it("does not surface successful turn completion as a work-log row", () => {
it("logs turn completion with elapsed time", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
@@ -155,38 +154,7 @@ describe("deriveWorkLogEntries", () => {
"turn-1",
);
expect(entries).toHaveLength(0);
});
it("shows failed turn completion in the work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:10.000Z",
payload: {
turn: {
id: "turn-1",
status: "failed",
error: { message: "sandbox denied" },
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Turn failed");
expect(entries[0]?.detail).toBe("sandbox denied");
expect(entries[0]?.label).toBe("Turn complete in 10s");
});
it("hides reasoning and agent-message noise from the visible work log", () => {
@@ -261,45 +229,11 @@ describe("deriveWorkLogEntries", () => {
"turn-1",
);
expect(entries.map((entry) => entry.label)).toEqual(["Tool call"]);
});
it("coalesces command start/completed lifecycle into one entry", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-command-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
makeEvent({
id: "evt-command-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Command run");
expect(entries[0]?.detail).toBe("git status --short");
expect(entries.map((entry) => entry.label)).toEqual([
"Turn complete in 8.0s",
"Tool call complete",
"Tool call",
]);
});
it("preserves full tool-call detail text without data truncation", () => {
@@ -323,50 +257,6 @@ describe("deriveWorkLogEntries", () => {
expect(entries[0]?.detail).toBe(longCommand);
});
it("hides generic tool-call rows that have no identifying detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call" },
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(0);
});
it("includes collab tool-call rows with tool name detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-collab-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: {
id: "item-collab",
type: "collabAgentToolCall",
tool: "spawnAgent",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Tool call");
expect(entries[0]?.detail).toBe("spawnAgent");
});
it("can derive work-log entries across all turns when not scoped", () => {
const entries = deriveWorkLogEntries(
[
@@ -393,73 +283,6 @@ describe("deriveWorkLogEntries", () => {
});
});
describe("derivePendingApprovals", () => {
it("returns pending command/file-change approvals", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { command: "git commit -m 'msg'" },
}),
]);
expect(approvals).toEqual([
{
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
detail: "git commit -m 'msg'",
},
]);
});
it("removes approvals after a decision event", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-decision",
method: "item/requestApproval/decision",
requestId: "req-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/fileChange/requestApproval",
requestId: "req-1",
requestKind: "file-change",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
it("clears pending approvals after turn completion", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
});
describe("evolveSession", () => {
it("updates thread id when thread starts", () => {
const previous = makeSession();
@@ -1,6 +1,5 @@
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@t3tools/contracts";
import type { ProviderEvent, ProviderKind, ProviderSession } from "@acme/contracts";
import type { ChatMessage, SessionPhase } from "./types";
import { createWsNativeApi } from "./wsNativeApi";
export const PROVIDER_OPTIONS: Array<{
value: ProviderKind;
@@ -11,21 +10,9 @@ export const PROVIDER_OPTIONS: Array<{
{ value: "claudeCode", label: "Claude Code (soon)", available: false },
];
let cachedApi: NativeApi | undefined;
export function readNativeApi(): NativeApi | undefined {
export function readNativeApi() {
if (typeof window === "undefined") return undefined;
if (cachedApi) return cachedApi;
// Prefer Electron preload bridge if available
if (window.nativeApi) {
cachedApi = window.nativeApi;
return cachedApi;
}
// Fall back to WebSocket transport
cachedApi = createWsNativeApi();
return cachedApi;
return window.nativeApi;
}
export function asObject(value: unknown): Record<string, unknown> | undefined {
@@ -78,13 +65,6 @@ export interface WorkLogEntry {
tone: "thinking" | "tool" | "info" | "error";
}
export interface PendingApproval {
requestId: string;
requestKind: "command" | "file-change";
createdAt: string;
detail?: string;
}
export type TimelineEntry =
| {
id: string;
@@ -105,52 +85,6 @@ function normalizeDetail(value: string | undefined): string | undefined {
return trimmed.length > 0 ? trimmed : undefined;
}
function approvalDetail(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const command = asString(payload?.command);
if (command) return command;
return asString(payload?.reason);
}
export function derivePendingApprovals(events: ProviderEvent[]): PendingApproval[] {
const pending = new Map<string, PendingApproval>();
const ordered = [...events].toReversed();
for (const event of ordered) {
if (
event.method === "session/closed" ||
event.method === "session/exited" ||
event.method === "turn/completed"
) {
pending.clear();
continue;
}
const requestId = event.requestId ?? asString(asObject(event.payload)?.requestId);
if (!requestId) continue;
if (
event.kind === "request" &&
(event.requestKind === "command" || event.requestKind === "file-change")
) {
const detail = approvalDetail(event);
pending.set(requestId, {
requestId,
requestKind: event.requestKind,
createdAt: event.createdAt,
...(detail ? { detail } : {}),
});
continue;
}
if (event.method === "item/requestApproval/decision") {
pending.delete(requestId);
}
}
return Array.from(pending.values());
}
function normalizeItemType(raw: string | undefined): string {
if (!raw) return "item";
return raw
@@ -162,7 +96,11 @@ function normalizeItemType(raw: string | undefined): string {
}
function shouldDropItemType(type: string): boolean {
if (type.includes("preamble") || type.includes("reasoning") || type.includes("thought")) {
if (
type.includes("preamble") ||
type.includes("reasoning") ||
type.includes("thought")
) {
return true;
}
@@ -170,7 +108,11 @@ function shouldDropItemType(type: string): boolean {
}
function shouldShowItemLifecycle(type: string): boolean {
return type.includes("tool") || type.includes("command") || type.includes("file change");
return (
type.includes("tool") ||
type.includes("command") ||
type.includes("file change")
);
}
function shouldDropMethod(method: string): boolean {
@@ -193,28 +135,15 @@ function itemTypeMeta(type: string): {
return { label: "Work item", tone: "info" };
}
interface ItemLifecycleCandidate {
id: string;
itemId?: string;
createdAt: string;
label: string;
detail?: string;
tone: WorkLogEntry["tone"];
phase: "started" | "completed";
}
function extractDetail(
payload: Record<string, unknown> | undefined,
item: Record<string, unknown> | undefined,
): string | undefined {
const candidates = [
asString(item?.command),
asString(item?.tool),
asString(item?.name),
asString(item?.title),
asString(item?.summary),
asString(item?.text),
asString(item?.prompt),
asString(item?.command),
asString(payload?.message),
asString(payload?.prompt),
asString(payload?.command),
@@ -227,7 +156,7 @@ function extractDetail(
return undefined;
}
function lifecycleCandidateFromItemEvent(event: ProviderEvent): ItemLifecycleCandidate | null {
function entryFromItemLifecycle(event: ProviderEvent): WorkLogEntry | null {
const payload = asObject(event.payload);
const item = asObject(payload?.item);
const normalizedType = normalizeItemType(asString(item?.type));
@@ -245,16 +174,14 @@ function lifecycleCandidateFromItemEvent(event: ProviderEvent): ItemLifecycleCan
return null;
}
const label = isCompleted ? `${meta.label} complete` : meta.label;
const detail = extractDetail(payload, item);
const itemId = event.itemId ?? asString(item?.id);
return {
id: event.id,
...(itemId ? { itemId } : {}),
createdAt: event.createdAt,
label: meta.label,
label,
...(detail ? { detail } : {}),
tone: meta.tone,
phase: isCompleted ? "completed" : "started",
};
}
@@ -297,7 +224,10 @@ function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
};
}
function entryFromNotification(event: ProviderEvent): WorkLogEntry | null {
function entryFromNotification(
event: ProviderEvent,
turnStartedAt: number,
): WorkLogEntry | null {
if (event.kind !== "notification") return null;
if (shouldDropMethod(event.method)) return null;
if (event.method === "item/agentMessage/delta") return null;
@@ -310,22 +240,34 @@ function entryFromNotification(event: ProviderEvent): WorkLogEntry | null {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
if (status !== "failed") {
return null;
}
const turnError = asObject(turn?.error);
const turnErrorMessage = asString(turnError?.message);
const turnErrorDetail = normalizeDetail(turnErrorMessage);
const eventAt = Date.parse(event.createdAt);
const durationMs =
Number.isNaN(turnStartedAt) ||
Number.isNaN(eventAt) ||
eventAt < turnStartedAt
? undefined
: eventAt - turnStartedAt;
return {
id: event.id,
createdAt: event.createdAt,
label: "Turn failed",
label:
status === "failed"
? "Turn failed"
: durationMs !== undefined
? `Turn complete in ${formatDuration(durationMs)}`
: "Turn complete",
...(turnErrorDetail ? { detail: turnErrorDetail } : {}),
tone: "error",
tone: status === "failed" ? "error" : "info",
};
}
const lifecycleEntry = entryFromItemLifecycle(event);
if (lifecycleEntry) return lifecycleEntry;
if (event.method.startsWith("item/")) return null;
return null;
@@ -365,56 +307,19 @@ export function deriveWorkLogEntries(
: undefined;
const turnStartedAt = turnStartedAtIso ? Date.parse(turnStartedAtIso) : Number.NaN;
const shouldIncludeEvent = (event: ProviderEvent): boolean => {
if (!turnId) return true;
const scopedTurnId = eventTurnId(event);
if (scopedTurnId && scopedTurnId !== turnId) {
return false;
}
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
const eventAt = Date.parse(event.createdAt);
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
return false;
}
}
return true;
};
const completedLifecycleItemIds = new Set<string>();
for (const event of ordered) {
if (!shouldIncludeEvent(event)) continue;
const candidate = lifecycleCandidateFromItemEvent(event);
if (candidate?.phase === "completed" && candidate.itemId) {
completedLifecycleItemIds.add(candidate.itemId);
}
}
for (const event of ordered) {
if (!shouldIncludeEvent(event)) continue;
const lifecycleCandidate = lifecycleCandidateFromItemEvent(event);
if (lifecycleCandidate) {
if (
lifecycleCandidate.phase === "started" &&
lifecycleCandidate.itemId &&
completedLifecycleItemIds.has(lifecycleCandidate.itemId)
) {
continue;
}
if (lifecycleCandidate.label === "Tool call" && !lifecycleCandidate.detail) {
if (turnId) {
const scopedTurnId = eventTurnId(event);
if (scopedTurnId && scopedTurnId !== turnId) {
continue;
}
entries.push({
id: lifecycleCandidate.id,
createdAt: lifecycleCandidate.createdAt,
label: lifecycleCandidate.label,
...(lifecycleCandidate.detail ? { detail: lifecycleCandidate.detail } : {}),
tone: lifecycleCandidate.tone,
});
continue;
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
const eventAt = Date.parse(event.createdAt);
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
continue;
}
}
}
const fromRequest = entryFromRequest(event);
@@ -423,7 +328,7 @@ export function deriveWorkLogEntries(
continue;
}
const fromNotification = entryFromNotification(event);
const fromNotification = entryFromNotification(event, turnStartedAt);
if (fromNotification) {
entries.push(fromNotification);
continue;
+330
View File
@@ -0,0 +1,330 @@
import {
type Dispatch,
type ReactNode,
createContext,
createElement,
useContext,
useEffect,
useReducer,
} from "react";
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import {
applyEventToMessages,
asObject,
asString,
evolveSession,
} from "./session-logic";
import {
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
type Thread,
} from "./types";
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "ADD_PROJECT"; project: Project }
| { type: "TOGGLE_PROJECT"; projectId: string }
| { type: "ADD_THREAD"; thread: Thread }
| { type: "SET_ACTIVE_THREAD"; threadId: string }
| { type: "TOGGLE_DIFF" }
| {
type: "APPLY_EVENT";
event: ProviderEvent;
activeAssistantItemRef: { current: string | null };
}
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
| { type: "PUSH_USER_MESSAGE"; threadId: string; id: string; text: string }
| { type: "SET_ERROR"; threadId: string; error: string | null }
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
// ── State ────────────────────────────────────────────────────────────
export interface AppState {
projects: Project[];
threads: Thread[];
activeThreadId: string | null;
runtimeMode: RuntimeMode;
diffOpen: boolean;
}
const PERSISTED_STATE_KEY = "codething:renderer-state:v3";
const LEGACY_PERSISTED_STATE_KEYS = [
"codething:renderer-state:v2",
"codething:renderer-state:v1",
] as const;
const initialState: AppState = {
projects: [],
threads: [],
activeThreadId: null,
runtimeMode: DEFAULT_RUNTIME_MODE,
diffOpen: false,
};
// ── Helpers ──────────────────────────────────────────────────────────
function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
try {
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
const [legacyV2Key, legacyV1Key] = LEGACY_PERSISTED_STATE_KEYS;
const rawLegacyV2 = window.localStorage.getItem(legacyV2Key);
const rawLegacyV1 = window.localStorage.getItem(legacyV1Key);
const raw = rawCurrent ?? rawLegacyV2 ?? rawLegacyV1;
if (!raw) return initialState;
const hydrated = hydratePersistedState(
raw,
!rawCurrent && !rawLegacyV2 && Boolean(rawLegacyV1),
);
if (!hydrated) return initialState;
return { ...hydrated, diffOpen: false };
} catch {
return initialState;
}
}
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
PERSISTED_STATE_KEY,
JSON.stringify(toPersistedState(state)),
);
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
}
}
function updateThread(
threads: Thread[],
threadId: string,
updater: (t: Thread) => Thread,
): Thread[] {
return threads.map((t) => (t.id === threadId ? updater(t) : t));
}
function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
return threads.find((t) => t.session?.sessionId === sessionId);
}
function getEventTurnId(event: ProviderEvent): string | undefined {
if (event.turnId) return event.turnId;
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return asString(turn?.id);
}
function durationMs(startIso: string, endIso: string): number | undefined {
const start = Date.parse(startIso);
const end = Date.parse(endIso);
if (Number.isNaN(start) || Number.isNaN(end) || end < start) {
return undefined;
}
return end - start;
}
function updateTurnFields(
thread: Thread,
event: ProviderEvent,
): Partial<Thread> {
if (event.method === "turn/started") {
return {
latestTurnId: getEventTurnId(event) ?? thread.latestTurnId,
latestTurnStartedAt: event.createdAt,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
};
}
if (event.method === "turn/completed") {
const completedTurnId = getEventTurnId(event) ?? thread.latestTurnId;
const startedAt =
completedTurnId && completedTurnId === thread.latestTurnId
? thread.latestTurnStartedAt
: undefined;
const elapsed =
startedAt && startedAt.length > 0
? durationMs(startedAt, event.createdAt)
: undefined;
return {
latestTurnId: completedTurnId ?? thread.latestTurnId,
latestTurnCompletedAt: event.createdAt,
latestTurnDurationMs: elapsed,
};
}
return {};
}
// ── Reducer ──────────────────────────────────────────────────────────
function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "ADD_PROJECT":
return {
...state,
projects: [
...state.projects,
{
...action.project,
model: resolveModelSlug(action.project.model),
},
],
};
case "TOGGLE_PROJECT":
return {
...state,
projects: state.projects.map((p) =>
p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
),
};
case "ADD_THREAD":
return {
...state,
threads: [
...state.threads,
{
...action.thread,
model: resolveModelSlug(action.thread.model),
},
],
activeThreadId: action.thread.id,
};
case "SET_ACTIVE_THREAD":
return { ...state, activeThreadId: action.threadId };
case "TOGGLE_DIFF":
return { ...state, diffOpen: !state.diffOpen };
case "APPLY_EVENT": {
const { event, activeAssistantItemRef } = action;
const target = findThreadBySessionId(state.threads, event.sessionId);
if (!target) return state;
return {
...state,
threads: updateThread(state.threads, target.id, (t) => ({
...t,
session: t.session ? evolveSession(t.session, event) : t.session,
messages: applyEventToMessages(
t.messages,
event,
activeAssistantItemRef,
),
events: [event, ...t.events],
error:
event.kind === "error" && event.message ? event.message : t.error,
...updateTurnFields(t, event),
})),
};
}
case "UPDATE_SESSION":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
session: action.session,
events: [],
error: null,
latestTurnId: undefined,
latestTurnStartedAt: undefined,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
})),
};
case "PUSH_USER_MESSAGE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
messages: [
...t.messages,
{
id: action.id,
role: "user" as const,
text: action.text,
createdAt: new Date().toISOString(),
streaming: false,
},
],
})),
};
case "SET_ERROR":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
error: action.error,
})),
};
case "SET_THREAD_TITLE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
title: action.title,
})),
};
case "SET_THREAD_MODEL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
model: resolveModelSlug(action.model),
})),
};
case "SET_RUNTIME_MODE":
return {
...state,
runtimeMode: action.mode,
};
default:
return state;
}
}
// ── Context ──────────────────────────────────────────────────────────
const StoreContext = createContext<{
state: AppState;
dispatch: Dispatch<Action>;
}>({ state: initialState, dispatch: () => {} });
export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
useEffect(() => {
persistState(state);
}, [state]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
}
export function useStore() {
return useContext(StoreContext);
}
+37
View File
@@ -0,0 +1,37 @@
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
export type RuntimeMode = "approval-required" | "full-access";
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export interface ChatMessage {
id: string;
role: "user" | "assistant";
text: string;
createdAt: string;
streaming: boolean;
}
export interface Project {
id: string;
name: string;
cwd: string;
model: string;
expanded: boolean;
}
export interface Thread {
id: string;
projectId: string;
title: string;
model: string;
session: ProviderSession | null;
messages: ChatMessage[];
events: ProviderEvent[];
error: string | null;
createdAt: string;
latestTurnId?: string | undefined;
latestTurnStartedAt?: string | undefined;
latestTurnCompletedAt?: string | undefined;
latestTurnDurationMs?: number | undefined;
}
+9
View File
@@ -0,0 +1,9 @@
/// <reference types="vite/client" />
import type { NativeApi } from "@acme/contracts";
declare global {
interface Window {
nativeApi?: NativeApi;
}
}
@@ -4,9 +4,10 @@
"composite": true,
"jsx": "react-jsx",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"exactOptionalPropertyTypes": false,
"types": ["vite/client"],
"paths": {
"~/*": ["./src/*"]
"#/*": ["./src/*"]
}
},
"include": ["src", "vite.config.ts"]
+28
View File
@@ -0,0 +1,28 @@
import path from "node:path";
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [
react({
babel: {
plugins: [["babel-plugin-react-compiler", { target: "19" }]],
},
}),
tailwindcss(),
],
resolve: {
alias: {
"#": path.resolve(__dirname, "src"),
},
},
server: {
port: Number(process.env.ELECTRON_RENDERER_PORT ?? 5173),
strictPort: true,
},
build: {
outDir: "dist",
emptyOutDir: true,
},
});
-32
View File
@@ -1,32 +0,0 @@
{
"name": "t3",
"version": "0.1.0",
"bin": {
"t3": "./dist/index.mjs"
},
"files": [
"dist"
],
"type": "module",
"main": "./dist/index.mjs",
"scripts": {
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5173} bun run src/index.ts",
"build": "tsdown && node scripts/bundle-client.mjs",
"start": "node dist/index.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"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",
"tsdown": "^0.20.3",
"typescript": "^5.7.3"
}
}
-21
View File
@@ -1,21 +0,0 @@
/**
* Copies the built web app into dist/client/ so the published npm package
* includes the web UI. This runs as a post-build step.
*/
import 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");
if (!fs.existsSync(webDist)) {
console.log(
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
);
process.exit(0);
}
fs.cpSync(webDist, target, { recursive: true });
console.log("✓ Bundled web app into dist/client");
@@ -1,200 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import {
CodexAppServerManager,
classifyCodexStderrLine,
isRecoverableThreadResumeError,
normalizeCodexModelSlug,
} from "./codexAppServerManager";
function createSendTurnHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
const requireSession = vi
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
},
});
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, requireSession, sendRequest, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
});
it("ignores non-error structured codex logs", () => {
const line =
"2026-02-08T04:24:19.241256Z WARN codex_core::features: unknown feature key in config: skills";
expect(classifyCodexStderrLine(line)).toBeNull();
});
it("ignores known benign rollout path errors", () => {
const line =
"\u001b[2m2026-02-08T04:24:20.085687Z\u001b[0m \u001b[31mERROR\u001b[0m \u001b[2mcodex_core::rollout::list\u001b[0m: state db missing rollout path for thread 019c3b6c-46b8-7b70-ad23-82f824d161fb";
expect(classifyCodexStderrLine(line)).toBeNull();
});
it("keeps unknown structured errors", () => {
const line = "2026-02-08T04:24:20.085687Z ERROR codex_core::runtime: unrecoverable failure";
expect(classifyCodexStderrLine(line)).toEqual({
message: line,
});
});
it("keeps plain stderr messages", () => {
const line = "fatal: permission denied";
expect(classifyCodexStderrLine(line)).toEqual({
message: line,
});
});
});
describe("normalizeCodexModelSlug", () => {
it("maps 5.3 aliases to gpt-5.3-codex", () => {
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
expect(normalizeCodexModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
});
it("prefers codex id when model differs", () => {
expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe("gpt-5.3-codex");
});
it("keeps non-aliased models as-is", () => {
expect(normalizeCodexModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2");
});
});
describe("isRecoverableThreadResumeError", () => {
it("matches not-found resume errors", () => {
expect(
isRecoverableThreadResumeError(new Error("thread/resume failed: thread not found")),
).toBe(true);
});
it("ignores non-resume errors", () => {
expect(
isRecoverableThreadResumeError(new Error("thread/start failed: permission denied")),
).toBe(false);
});
it("ignores non-recoverable resume errors", () => {
expect(
isRecoverableThreadResumeError(
new Error("thread/resume failed: timed out waiting for server"),
),
).toBe(false);
});
});
describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();
const result = await manager.sendTurn({
sessionId: "sess_1",
input: "Inspect this image",
attachments: [
{
type: "image",
name: "error.png",
mimeType: "image/png",
sizeBytes: 1_024,
dataUrl: "data:image/png;base64,AAAA",
},
],
model: "gpt-5.3",
effort: "high",
});
expect(result).toEqual({
threadId: "thread_1",
turnId: "turn_1",
});
expect(requireSession).toHaveBeenCalledWith("sess_1");
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "text",
text: "Inspect this image",
text_elements: [],
},
{
type: "image",
url: "data:image/png;base64,AAAA",
},
],
model: "gpt-5.3-codex",
effort: "high",
});
expect(updateSession).toHaveBeenCalledWith(context, {
status: "running",
activeTurnId: "turn_1",
});
});
it("supports image-only turns", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
await manager.sendTurn({
sessionId: "sess_1",
attachments: [
{
type: "image",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 256,
dataUrl: "data:image/png;base64,BBBB",
},
],
});
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "image",
url: "data:image/png;base64,BBBB",
},
],
});
});
it("rejects empty turn input", async () => {
const { manager } = createSendTurnHarness();
await expect(
manager.sendTurn({
sessionId: "sess_1",
}),
).rejects.toThrow("Turn input must include text or attachments.");
});
});
-252
View File
@@ -1,252 +0,0 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type {
CommitMessageGenerationInput,
CommitMessageGenerationResult,
PrContentGenerationInput,
PrContentGenerationResult,
TextGenerationService,
} from "./coreServices";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
type ProcessRunner = (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const COMMIT_OUTPUT_SCHEMA_JSON = {
type: "object",
properties: {
subject: { type: "string" },
body: { type: "string" },
},
required: ["subject", "body"],
additionalProperties: false,
} as const;
const PR_OUTPUT_SCHEMA_JSON = {
type: "object",
properties: {
title: { type: "string" },
body: { type: "string" },
},
required: ["title", "body"],
additionalProperties: false,
} as const;
function parseCommitOutput(raw: unknown): { subject: string; body: string } {
if (!raw || typeof raw !== "object") {
throw new Error("Codex returned a non-object commit message payload.");
}
const record = raw as Record<string, unknown>;
const subject = typeof record.subject === "string" ? record.subject.trim() : "";
const body = typeof record.body === "string" ? record.body : "";
if (subject.length === 0) {
throw new Error("Codex returned an empty commit subject.");
}
return { subject, body };
}
function parsePrOutput(raw: unknown): { title: string; body: string } {
if (!raw || typeof raw !== "object") {
throw new Error("Codex returned a non-object PR payload.");
}
const record = raw as Record<string, unknown>;
const title = typeof record.title === "string" ? record.title.trim() : "";
const body = typeof record.body === "string" ? record.body.trim() : "";
if (title.length === 0 || body.length === 0) {
throw new Error("Codex returned an invalid PR title/body payload.");
}
return { title, body };
}
function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
async function writeTempFile(prefix: string, content: string): Promise<string> {
const filePath = path.join(os.tmpdir(), `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
await fs.writeFile(filePath, content, "utf8");
return filePath;
}
async function safeUnlink(filePath: string): Promise<void> {
try {
await fs.unlink(filePath);
} catch {
// Best-effort cleanup.
}
}
function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
async function runCodexJson<T>({
cwd,
prompt,
outputSchemaJson,
parse,
run,
}: {
cwd: string;
prompt: string;
outputSchemaJson: object;
parse: (raw: unknown) => T;
run: ProcessRunner;
}): Promise<T> {
const schemaPath = await writeTempFile("codex-schema", JSON.stringify(outputSchemaJson));
let outputPath: string | null = null;
try {
outputPath = await writeTempFile("codex-output", "");
await run(
"codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
CODEX_MODEL,
"--config",
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
"-",
],
{
cwd,
timeoutMs: 180_000,
stdin: prompt,
},
);
const rawOutput = (await fs.readFile(outputPath, "utf8")).trim();
if (rawOutput.length === 0) {
throw new Error("Codex returned an empty response.");
}
let parsedJson: unknown;
try {
parsedJson = JSON.parse(rawOutput);
} catch {
throw new Error("Codex returned invalid JSON output.");
}
return parse(parsedJson);
} finally {
await Promise.all([safeUnlink(schemaPath), ...(outputPath ? [safeUnlink(outputPath)] : [])]);
}
}
interface CodexTextGeneratorDeps {
runProcess?: ProcessRunner;
}
export class CodexTextGenerator implements TextGenerationService {
private readonly run: ProcessRunner;
constructor(deps: CodexTextGeneratorDeps = {}) {
this.run = deps.runProcess ?? runProcess;
}
async generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult> {
const prompt = [
"You write concise git commit messages.",
"Return a JSON object with keys: subject, body.",
"Rules:",
"- subject must be imperative, <= 72 chars, and no trailing period",
"- body can be empty string or short bullet points",
"- capture the primary user-visible or developer-visible change",
"",
`Branch: ${input.branch ?? "(detached)"}`,
"",
"Staged files:",
limitSection(input.stagedSummary, 6_000),
"",
"Staged patch:",
limitSection(input.stagedPatch, 40_000),
].join("\n");
const generated = await runCodexJson({
cwd: input.cwd,
prompt,
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
parse: (raw) => parseCommitOutput(raw),
run: this.run,
});
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
};
}
async generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult> {
const prompt = [
"You write GitHub pull request content.",
"Return a JSON object with keys: title, body.",
"Rules:",
"- title should be concise and specific",
"- body must be markdown and include headings '## Summary' and '## Testing'",
"- under Summary, provide short bullet points",
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
"",
`Base branch: ${input.baseBranch}`,
`Head branch: ${input.headBranch}`,
"",
"Commits:",
limitSection(input.commitSummary, 12_000),
"",
"Diff stat:",
limitSection(input.diffSummary, 12_000),
"",
"Diff patch:",
limitSection(input.diffPatch, 40_000),
].join("\n");
const generated = await runCodexJson({
cwd: input.cwd,
prompt,
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
parse: (raw) => parsePrOutput(raw),
run: this.run,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
}
}
-32
View File
@@ -1,32 +0,0 @@
export interface CommitMessageGenerationInput {
cwd: string;
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}
export interface CommitMessageGenerationResult {
subject: string;
body: string;
}
export interface PrContentGenerationInput {
cwd: string;
baseBranch: string;
headBranch: string;
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
export interface PrContentGenerationResult {
title: string;
body: string;
}
export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}
-18
View File
@@ -1,18 +0,0 @@
import { execFileSync } from "node:child_process";
export function fixPath(): void {
if (process.platform !== "darwin") return;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
encoding: "utf8",
timeout: 5000,
});
if (result) {
process.env.PATH = result;
}
} catch {
// Silently ignore — keep default PATH
}
}
-886
View File
@@ -1,886 +0,0 @@
import { existsSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import {
GitCoreService,
checkoutGitBranch,
createGitBranch,
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
runTerminalCommand,
} from "./git";
// ── Helpers ──
/** Run a raw git command for test setup (not under test). */
async function git(cwd: string, command: string): Promise<string> {
const result = await runTerminalCommand({
command: `git ${command}`,
cwd,
timeoutMs: 10_000,
});
if (result.code !== 0) {
throw new Error(`git ${command} failed: ${result.stderr}`);
}
return result.stdout.trim();
}
/** Create a disposable temp directory that cleans up automatically. */
async function makeTmpDir() {
const dir = await mkdtemp(path.join(tmpdir(), "git-test-"));
return {
path: dir,
[Symbol.asyncDispose]: async () => {
await rm(dir, { recursive: true, force: true });
},
};
}
/** Create a repo with an initial commit so branches work. */
async function initRepoWithCommit(cwd: string): Promise<void> {
await initGitRepo({ cwd });
await git(cwd, "config user.email '[email protected]'");
await git(cwd, "config user.name 'Test'");
await writeFile(path.join(cwd, "README.md"), "# test\n");
await git(cwd, "add .");
await git(cwd, "commit -m 'initial commit'");
}
async function commitWithDate(
cwd: string,
fileName: string,
fileContents: string,
dateIsoString: string,
message: string,
): Promise<void> {
await writeFile(path.join(cwd, fileName), fileContents);
await git(cwd, `add ${fileName}`);
const commitResult = await runTerminalCommand({
command: `GIT_AUTHOR_DATE="${dateIsoString}" GIT_COMMITTER_DATE="${dateIsoString}" git commit -m "${message}"`,
cwd,
timeoutMs: 10_000,
});
if (commitResult.code !== 0) {
throw new Error(`git dated commit failed: ${commitResult.stderr}`);
}
}
// ── Tests ──
describe("git integration", () => {
describe("runTerminalCommand", () => {
it("caps captured output when maxOutputBytes is exceeded", async () => {
const result = await runTerminalCommand({
command: `node -e "process.stdout.write('x'.repeat(2000))"`,
cwd: process.cwd(),
timeoutMs: 10_000,
maxOutputBytes: 128,
});
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
expect(result.stderr).toContain("output truncated");
});
});
// ── initGitRepo ──
describe("initGitRepo", () => {
it("creates a valid git repo", async () => {
await using tmp = await makeTmpDir();
await initGitRepo({ cwd: tmp.path });
expect(existsSync(path.join(tmp.path, ".git"))).toBe(true);
});
it("listGitBranches reports isRepo: true after init + commit", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const result = await listGitBranches({ cwd: tmp.path });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThanOrEqual(1);
});
});
// ── listGitBranches ──
describe("listGitBranches", () => {
it("returns isRepo: false for non-git directory", async () => {
await using tmp = await makeTmpDir();
const result = await listGitBranches({ cwd: tmp.path });
expect(result.isRepo).toBe(false);
expect(result.branches).toEqual([]);
});
it("returns the current branch with current: true", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const result = await listGitBranches({ cwd: tmp.path });
const current = result.branches.find((b) => b.current);
expect(current).toBeDefined();
expect(current!.current).toBe(true);
});
it("keeps current branch first and sorts the remaining branches by recency", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(branch) => branch.current,
)!.name;
await createGitBranch({ cwd: tmp.path, branch: "older-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
await commitWithDate(
tmp.path,
"older.txt",
"older branch change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"older branch change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await commitWithDate(
tmp.path,
"newer.txt",
"newer branch change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer branch change",
);
// Switch away to show current branch is pinned, then remaining branches are recency-sorted.
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.name).toBe("older-branch");
expect(result.branches[1]!.name).toBe("newer-branch");
});
it("keeps default branch right after current branch", async () => {
await using tmp = await makeTmpDir();
await using remote = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(remote.path, "init --bare");
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(tmp.path, `push -u origin ${defaultBranch}`);
await git(tmp.path, `remote set-head origin ${defaultBranch}`);
await createGitBranch({ cwd: tmp.path, branch: "current-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
await commitWithDate(
tmp.path,
"current.txt",
"current change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"current change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await commitWithDate(
tmp.path,
"newer.txt",
"newer change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.name).toBe("current-branch");
expect(result.branches[1]!.name).toBe(defaultBranch);
expect(result.branches[2]!.name).toBe("newer-branch");
});
it("lists multiple branches after creating them", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "feature-a" });
await createGitBranch({ cwd: tmp.path, branch: "feature-b" });
const result = await listGitBranches({ cwd: tmp.path });
const names = result.branches.map((b) => b.name);
expect(names).toContain("feature-a");
expect(names).toContain("feature-b");
});
it("isDefault is false when no remote exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
});
});
// ── checkoutGitBranch ──
describe("checkoutGitBranch", () => {
it("checks out an existing branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "feature" });
await checkoutGitBranch({ cwd: tmp.path, branch: "feature" });
const result = await listGitBranches({ cwd: tmp.path });
const current = result.branches.find((b) => b.current);
expect(current!.name).toBe("feature");
});
it("refreshes upstream behind count after checkout when remote branch advanced", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${defaultBranch}`);
const featureBranch = "feature-behind";
await createGitBranch({ cwd: source.path, branch: featureBranch });
await checkoutGitBranch({ cwd: source.path, branch: featureBranch });
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
await git(source.path, "add feature.txt");
await git(source.path, "commit -m 'feature base'");
await git(source.path, `push -u origin ${featureBranch}`);
await checkoutGitBranch({ cwd: source.path, branch: defaultBranch });
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email '[email protected]'");
await git(clone.path, "config user.name 'Test'");
await git(clone.path, `checkout -b ${featureBranch} --track origin/${featureBranch}`);
await writeFile(path.join(clone.path, "feature.txt"), "feature from remote\n");
await git(clone.path, "add feature.txt");
await git(clone.path, "commit -m 'remote feature update'");
await git(clone.path, `push origin ${featureBranch}`);
await checkoutGitBranch({ cwd: source.path, branch: featureBranch });
const core = new GitCoreService();
await vi.waitFor(async () => {
const details = await core.statusDetails(source.path);
expect(details.branch).toBe(featureBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
});
});
it("keeps checkout successful when upstream refresh fails", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${defaultBranch}`);
const featureBranch = "feature-refresh-failure";
await git(source.path, `branch ${featureBranch}`);
await git(source.path, `checkout ${featureBranch}`);
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
await git(source.path, "add feature.txt");
await git(source.path, "commit -m 'feature base'");
await git(source.path, `push -u origin ${featureBranch}`);
await git(source.path, `checkout ${defaultBranch}`);
class RefreshFailingGitCoreService extends GitCoreService {
refreshFetchAttempts = 0;
override async git(
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Promise<void> {
if (args[0] === "fetch") {
this.refreshFetchAttempts += 1;
throw new Error("simulated fetch timeout");
}
await super.git(cwd, args, allowNonZeroExit);
}
}
const core = new RefreshFailingGitCoreService();
await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
undefined,
);
await vi.waitFor(() => {
expect(core.refreshFetchAttempts).toBe(1);
});
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
});
it("refresh fetch is scoped to the checked out branch upstream refspec", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${defaultBranch}`);
const featureBranch = "feature/scoped-fetch";
await git(source.path, `checkout -b ${featureBranch}`);
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
await git(source.path, "add feature.txt");
await git(source.path, "commit -m 'feature base'");
await git(source.path, `push -u origin ${featureBranch}`);
await git(source.path, `checkout ${defaultBranch}`);
class FetchRecordingGitCoreService extends GitCoreService {
fetchArgs: readonly string[] | null = null;
override async git(
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Promise<void> {
if (args[0] === "fetch") {
this.fetchArgs = args;
return;
}
await super.git(cwd, args, allowNonZeroExit);
}
}
const core = new FetchRecordingGitCoreService();
await core.checkoutBranch({ cwd: source.path, branch: featureBranch });
await vi.waitFor(() => {
expect(core.fetchArgs).not.toBeNull();
});
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
expect(core.fetchArgs).toEqual([
"fetch",
"--quiet",
"--no-tags",
"origin",
`+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
]);
});
it("returns checkout result before background upstream refresh completes", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${defaultBranch}`);
const featureBranch = "feature/background-refresh";
await git(source.path, `checkout -b ${featureBranch}`);
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
await git(source.path, "add feature.txt");
await git(source.path, "commit -m 'feature base'");
await git(source.path, `push -u origin ${featureBranch}`);
await git(source.path, `checkout ${defaultBranch}`);
class SlowRefreshGitCoreService extends GitCoreService {
fetchStarted = false;
private readonly waitForReleasePromise: Promise<void>;
private releaseWait: () => void = () => undefined;
constructor() {
super();
this.waitForReleasePromise = new Promise<void>((resolve) => {
this.releaseWait = resolve;
});
}
releaseFetch(): void {
this.releaseWait();
}
override async git(
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Promise<void> {
if (args[0] === "fetch") {
this.fetchStarted = true;
await this.waitForReleasePromise;
return;
}
await super.git(cwd, args, allowNonZeroExit);
}
}
const core = new SlowRefreshGitCoreService();
await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
undefined,
);
await vi.waitFor(() => {
expect(core.fetchStarted).toBe(true);
});
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
core.releaseFetch();
});
it("throws when branch does not exist", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "nonexistent" })).rejects.toThrow();
});
it("throws when checkout would overwrite uncommitted changes", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "other" });
// Create a conflicting change: modify README on current branch
await writeFile(path.join(tmp.path, "README.md"), "modified\n");
await git(tmp.path, "add README.md");
// First, checkout other branch cleanly
await git(tmp.path, "stash");
await checkoutGitBranch({ cwd: tmp.path, branch: "other" });
await writeFile(path.join(tmp.path, "README.md"), "other content\n");
await git(tmp.path, "add .");
await git(tmp.path, "commit -m 'other change'");
// Go back to default branch
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => !b.current,
)!.name;
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
// Make uncommitted changes to the same file
await writeFile(path.join(tmp.path, "README.md"), "conflicting local\n");
// Checkout should fail due to uncommitted changes
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "other" })).rejects.toThrow();
});
});
// ── createGitBranch ──
describe("createGitBranch", () => {
it("creates a new branch visible in listGitBranches", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "new-feature" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches.some((b) => b.name === "new-feature")).toBe(true);
});
it("throws when branch already exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "dupe" });
await expect(createGitBranch({ cwd: tmp.path, branch: "dupe" })).rejects.toThrow();
});
});
// ── createGitWorktree + removeGitWorktree ──
describe("createGitWorktree", () => {
it("creates a worktree with a new branch from the base branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "worktree-out");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
const result = await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "wt-branch",
path: wtPath,
});
expect(result.worktree.path).toBe(wtPath);
expect(result.worktree.branch).toBe("wt-branch");
expect(existsSync(wtPath)).toBe(true);
expect(existsSync(path.join(wtPath, "README.md"))).toBe(true);
// Clean up worktree before tmp dir disposal
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
it("worktree has the new branch checked out", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "wt-check-dir");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "wt-check",
path: wtPath,
});
// Verify the worktree is on the new branch
const branchOutput = await git(wtPath, "branch --show-current");
expect(branchOutput).toBe("wt-check");
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
it("throws when new branch name already exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "existing" });
const wtPath = path.join(tmp.path, "wt-conflict");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await expect(
createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "existing",
path: wtPath,
}),
).rejects.toThrow();
});
it("listGitBranches from worktree cwd reports worktree branch as current", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "wt-list-dir");
const mainBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await createGitWorktree({
cwd: tmp.path,
branch: mainBranch,
newBranch: "wt-list",
path: wtPath,
});
// listGitBranches from the worktree should show wt-list as current
const wtBranches = await listGitBranches({ cwd: wtPath });
expect(wtBranches.isRepo).toBe(true);
const wtCurrent = wtBranches.branches.find((b) => b.current);
expect(wtCurrent!.name).toBe("wt-list");
// Main repo should still show the original branch as current
const mainBranches = await listGitBranches({ cwd: tmp.path });
const mainCurrent = mainBranches.branches.find((b) => b.current);
expect(mainCurrent!.name).toBe(mainBranch);
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
it("removeGitWorktree cleans up the worktree", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "wt-remove-dir");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "wt-remove",
path: wtPath,
});
expect(existsSync(wtPath)).toBe(true);
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
expect(existsSync(wtPath)).toBe(false);
});
});
// ── Full flow: local branch checkout ──
describe("full flow: local branch checkout", () => {
it("init → commit → create branch → checkout → verify current", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "feature-login" });
await checkoutGitBranch({ cwd: tmp.path, branch: "feature-login" });
const result = await listGitBranches({ cwd: tmp.path });
const current = result.branches.find((b) => b.current);
expect(current!.name).toBe("feature-login");
});
});
// ── Full flow: worktree creation from base branch ──
describe("full flow: worktree creation", () => {
it("creates worktree with new branch from current branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
const wtPath = path.join(tmp.path, "my-worktree");
const result = await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "feature-wt",
path: wtPath,
});
// Worktree exists
expect(existsSync(result.worktree.path)).toBe(true);
// Main repo still on original branch
const mainBranches = await listGitBranches({ cwd: tmp.path });
const mainCurrent = mainBranches.branches.find((b) => b.current);
expect(mainCurrent!.name).toBe(currentBranch);
// Worktree is on the new branch
const wtBranch = await git(wtPath, "branch --show-current");
expect(wtBranch).toBe("feature-wt");
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
});
// ── Full flow: thread switching simulation ──
describe("full flow: thread switching (checkout toggling)", () => {
it("checkout a → checkout b → checkout a → current matches", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "branch-a" });
await createGitBranch({ cwd: tmp.path, branch: "branch-b" });
// Simulate switching to thread A's branch
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" });
let branches = await listGitBranches({ cwd: tmp.path });
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
// Simulate switching to thread B's branch
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-b" });
branches = await listGitBranches({ cwd: tmp.path });
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-b");
// Switch back to thread A
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" });
branches = await listGitBranches({ cwd: tmp.path });
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
});
});
// ── Full flow: checkout conflict ──
describe("full flow: checkout conflict", () => {
it("uncommitted changes prevent checkout to a diverged branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "diverged" });
// Make diverged branch have different file content
await checkoutGitBranch({ cwd: tmp.path, branch: "diverged" });
await writeFile(path.join(tmp.path, "README.md"), "diverged content\n");
await git(tmp.path, "add .");
await git(tmp.path, "commit -m 'diverge'");
// Actually, let's just get back to the initial branch explicitly
const allBranches = await listGitBranches({ cwd: tmp.path });
const initialBranch = allBranches.branches.find((b) => b.name !== "diverged")!.name;
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
// Make local uncommitted changes to the same file
await writeFile(path.join(tmp.path, "README.md"), "local uncommitted\n");
// Attempt checkout should fail
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "diverged" })).rejects.toThrow();
// Current branch should still be the initial one
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch);
});
});
describe("GitCoreService", () => {
it("supports branch lifecycle operations through the service API", async () => {
await using tmp = await makeTmpDir();
const core = new GitCoreService();
await core.initRepo({ cwd: tmp.path });
await git(tmp.path, "config user.email '[email protected]'");
await git(tmp.path, "config user.name 'Test'");
await writeFile(path.join(tmp.path, "README.md"), "# test\n");
await git(tmp.path, "add .");
await git(tmp.path, "commit -m 'initial commit'");
await core.createBranch({ cwd: tmp.path, branch: "feature/service-api" });
await core.checkoutBranch({ cwd: tmp.path, branch: "feature/service-api" });
const branches = await core.listBranches({ cwd: tmp.path });
expect(branches.isRepo).toBe(true);
expect(branches.branches.find((branch) => branch.current)?.name).toBe("feature/service-api");
});
it("reports status details and dirty state", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
const clean = await core.status({ cwd: tmp.path });
expect(clean.hasWorkingTreeChanges).toBe(false);
expect(clean.branch).toBeTruthy();
await writeFile(path.join(tmp.path, "README.md"), "updated\n");
const dirty = await core.statusDetails(tmp.path);
expect(dirty.hasWorkingTreeChanges).toBe(true);
});
it("refreshes upstream before statusDetails so behind count reflects remote updates", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email '[email protected]'");
await git(clone.path, "config user.name 'Test'");
await git(clone.path, `checkout -B ${initialBranch} --track origin/${initialBranch}`);
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);
const core = new GitCoreService();
const details = await core.statusDetails(source.path);
expect(details.branch).toBe(initialBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
});
it("prepares commit context by auto-staging and creates commit", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
await writeFile(path.join(tmp.path, "README.md"), "new content\n");
const context = await core.prepareCommitContext(tmp.path);
expect(context).not.toBeNull();
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
it("pushes with upstream setup and then skips when up to date", async () => {
await using tmp = await makeTmpDir();
await using remote = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await git(remote.path, "init --bare");
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
await createGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
await checkoutGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
await writeFile(path.join(tmp.path, "feature.txt"), "push me\n");
const core = new GitCoreService();
const context = await core.prepareCommitContext(tmp.path);
expect(context).not.toBeNull();
await core.commit(tmp.path, "Add feature file", "");
const pushed = await core.pushCurrentBranch(tmp.path, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(await git(tmp.path, "rev-parse --abbrev-ref @{upstream}")).toBe(
"origin/feature/core-push",
);
const skipped = await core.pushCurrentBranch(tmp.path, null);
expect(skipped.status).toBe("skipped_up_to_date");
});
it("pulls behind branch and then reports up-to-date", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email '[email protected]'");
await git(clone.path, "config user.name 'Test'");
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);
const core = new GitCoreService();
const pulled = await core.pullCurrentBranch(source.path);
expect(pulled.status).toBe("pulled");
expect((await core.statusDetails(source.path)).behindCount).toBe(0);
const skipped = await core.pullCurrentBranch(source.path);
expect(skipped.status).toBe("skipped_up_to_date");
});
it("top-level pullGitBranch rejects when no upstream exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
});
it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
const recencySpy = vi
.spyOn(core as any, "readBranchRecency")
.mockRejectedValueOnce(new Error("timeout"));
const result = await core.listBranches({ cwd: tmp.path });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThan(0);
expect(result.branches[0]?.current).toBe(true);
recencySpy.mockRestore();
});
});
});
Loaded 100 of 199 files, more files were not shown because too many files have changed in this diff. Show more