Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a535ae07c | ||
|
|
1377b3760f | ||
|
|
f7f5408814 |
No files matched your search
@@ -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
-1
@@ -5,9 +5,9 @@ node_modules
|
||||
*.log
|
||||
*.tsbuildinfo
|
||||
apps/*/dist
|
||||
apps/*/dist-electron
|
||||
packages/*/dist
|
||||
.env
|
||||
.env.local
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
+1
-8
@@ -1,13 +1,6 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts"
|
||||
],
|
||||
"ignorePatterns": ["dist", "dist-electron", "node_modules", "bun.lock", "*.tsbuildinfo"],
|
||||
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
|
||||
"categories": {
|
||||
"correctness": "warn",
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
```
|
||||
@@ -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
|
||||
@@ -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.
|
||||
-101
@@ -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.
|
||||
@@ -1,121 +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
|
||||
|
||||
# Build a shareable macOS .dmg (arm64 by default)
|
||||
bun run dist:desktop:dmg
|
||||
|
||||
# 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.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
|
||||
### Desktop `.dmg` packaging notes
|
||||
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
|
||||
### 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.
|
||||
@@ -1,25 +1,4 @@
|
||||
# TODO
|
||||
## TODO
|
||||
|
||||
## Small things
|
||||
|
||||
- [ ] Plan mode
|
||||
- [ ] Submitting new messages should scroll to bottom
|
||||
- [ ] 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)
|
||||
- [x] 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,2 +0,0 @@
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
@@ -1,28 +1,30 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"name": "@acme/desktop",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"productName": "T3 Code (Alpha)",
|
||||
"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",
|
||||
"start": "bun run scripts/start-electron.mjs",
|
||||
"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": "40.6.0"
|
||||
"@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"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 279 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 313 KiB |
@@ -1,73 +1,23 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import electronmon from "electronmon";
|
||||
import waitOn from "wait-on";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
|
||||
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 childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const monitor = await electronmon({
|
||||
cwd: desktopDir,
|
||||
args: ["dist-electron/main.js"],
|
||||
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
|
||||
const child = spawn(command, ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
...childEnv,
|
||||
...process.env,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
electronPath: resolveElectronPath(),
|
||||
});
|
||||
|
||||
let shuttingDown = false;
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
async function shutdown(exitCode) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
|
||||
try {
|
||||
await Promise.race([
|
||||
monitor.destroy(),
|
||||
new Promise((resolve) => setTimeout(resolve, 1_500)),
|
||||
]);
|
||||
} catch {
|
||||
// Best effort only; fallback process kill below handles stubborn children.
|
||||
}
|
||||
|
||||
killChildTree("TERM");
|
||||
setTimeout(() => {
|
||||
killChildTree("KILL");
|
||||
}, 1_200).unref();
|
||||
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
void shutdown(130);
|
||||
});
|
||||
process.once("SIGTERM", () => {
|
||||
void shutdown(143);
|
||||
});
|
||||
process.once("SIGHUP", () => {
|
||||
void shutdown(129);
|
||||
child.on("exit", (code) => {
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
@@ -1,173 +0,0 @@
|
||||
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
copyFileSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_BUNDLE_ID = "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 1;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const desktopDir = resolve(__dirname, "..");
|
||||
|
||||
function setPlistString(plistPath, key, value) {
|
||||
const replaceResult = spawnSync(
|
||||
"plutil",
|
||||
["-replace", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (replaceResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertResult = spawnSync(
|
||||
"plutil",
|
||||
["-insert", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (insertResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const details = [replaceResult.stderr, insertResult.stderr]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
throw new Error(
|
||||
`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
|
||||
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
|
||||
|
||||
const resourcesDir = join(appBundlePath, "Contents", "Resources");
|
||||
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
|
||||
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
|
||||
}
|
||||
|
||||
function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
|
||||
if (!existsSync(frameworksDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
|
||||
continue;
|
||||
}
|
||||
if (!entry.name.startsWith("Electron Helper")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const helperPlistPath = join(
|
||||
frameworksDir,
|
||||
entry.name,
|
||||
"Contents",
|
||||
"Info.plist",
|
||||
);
|
||||
if (!existsSync(helperPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const suffix = entry.name
|
||||
.replace("Electron Helper", "")
|
||||
.replace(".app", "")
|
||||
.trim();
|
||||
const helperName = suffix
|
||||
? `${APP_DISPLAY_NAME} Helper ${suffix}`
|
||||
: `${APP_DISPLAY_NAME} Helper`;
|
||||
const helperIdSuffix = suffix
|
||||
.replace(/[()]/g, "")
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, "-");
|
||||
const helperBundleId = helperIdSuffix
|
||||
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
|
||||
: `${APP_BUNDLE_ID}.helper`;
|
||||
|
||||
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
const sourceAppBundlePath = resolve(electronBinaryPath, "../../..");
|
||||
const runtimeDir = join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = join(
|
||||
targetAppBundlePath,
|
||||
"Contents",
|
||||
"MacOS",
|
||||
"Electron",
|
||||
);
|
||||
const iconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const metadataPath = join(runtimeDir, "metadata.json");
|
||||
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
const expectedMetadata = {
|
||||
launcherVersion: LAUNCHER_VERSION,
|
||||
sourceAppBundlePath,
|
||||
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
|
||||
iconMtimeMs: statSync(iconPath).mtimeMs,
|
||||
};
|
||||
|
||||
const currentMetadata = readJson(metadataPath);
|
||||
if (
|
||||
existsSync(targetBinaryPath) &&
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
export function resolveElectronPath() {
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
return buildMacLauncher(electronBinaryPath);
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
process.kill(process.pid, signal);
|
||||
return;
|
||||
}
|
||||
process.exit(code ?? 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");
|
||||
});
|
||||
});
|
||||
+61
-227
@@ -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;
|
||||
@@ -65,16 +67,6 @@ interface JsonRpcNotification {
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
export interface CodexThreadTurnSnapshot {
|
||||
id: string;
|
||||
items: unknown[];
|
||||
}
|
||||
|
||||
export interface CodexThreadSnapshot {
|
||||
threadId: string;
|
||||
turns: CodexThreadTurnSnapshot[];
|
||||
}
|
||||
|
||||
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
|
||||
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
|
||||
const CODEX_STDERR_LOG_REGEX =
|
||||
@@ -83,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,
|
||||
@@ -129,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];
|
||||
}
|
||||
@@ -148,52 +123,44 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const sessionId = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
let context: CodexSessionContext | undefined;
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
status: "connecting",
|
||||
model: normalizeCodexModelSlug(input.model),
|
||||
cwd: input.cwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const child = spawn("codex", ["app-server"], {
|
||||
cwd: input.cwd,
|
||||
env: process.env,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
const context: CodexSessionContext = {
|
||||
session,
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
|
||||
try {
|
||||
const resolvedCwd = input.cwd ?? process.cwd();
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
status: "connecting",
|
||||
model: normalizeCodexModelSlug(input.model),
|
||||
cwd: resolvedCwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const codexBinaryPath = input.codexBinaryPath?.trim() || "codex";
|
||||
const codexHomePath = input.codexHomePath?.trim();
|
||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
context = {
|
||||
session,
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
|
||||
await this.sendRequest(context, "initialize", {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
name: "codething_desktop",
|
||||
title: "CodeThing Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
@@ -203,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, {
|
||||
@@ -259,24 +191,12 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return { ...context.session };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to start Codex session.";
|
||||
if (context) {
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "session/startFailed", message);
|
||||
this.stopSession(sessionId);
|
||||
} else {
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "session/startFailed",
|
||||
message,
|
||||
});
|
||||
}
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "session/startFailed", message);
|
||||
this.stopSession(sessionId);
|
||||
throw new Error(message, { cause: error });
|
||||
}
|
||||
}
|
||||
@@ -287,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) {
|
||||
@@ -361,41 +263,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
async readThread(sessionId: string): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const threadId = context.session.threadId;
|
||||
if (!threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "thread/read", {
|
||||
threadId,
|
||||
includeTurns: true,
|
||||
});
|
||||
return this.parseThreadSnapshot("thread/read", response);
|
||||
}
|
||||
|
||||
async rollbackThread(sessionId: string, numTurns: number): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const threadId = context.session.threadId;
|
||||
if (!threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
throw new Error("numTurns must be an integer >= 1.");
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "thread/rollback", {
|
||||
threadId,
|
||||
numTurns,
|
||||
});
|
||||
this.updateSession(context, {
|
||||
status: "ready",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
return this.parseThreadSnapshot("thread/rollback", response);
|
||||
}
|
||||
|
||||
async respondToRequest(
|
||||
sessionId: string,
|
||||
requestId: string,
|
||||
@@ -795,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";
|
||||
}
|
||||
@@ -807,31 +676,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private parseThreadSnapshot(method: string, response: unknown): CodexThreadSnapshot {
|
||||
const responseRecord = this.readObject(response);
|
||||
const thread = this.readObject(responseRecord, "thread");
|
||||
const threadId = this.readString(thread, "id") ?? this.readString(responseRecord, "threadId");
|
||||
if (!threadId) {
|
||||
throw new Error(`${method} response did not include a thread id.`);
|
||||
}
|
||||
|
||||
const turnsRaw = this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? [];
|
||||
const turns = turnsRaw.map((turnValue, index) => {
|
||||
const turn = this.readObject(turnValue);
|
||||
const turnId = this.readString(turn, "id") ?? `${threadId}:turn:${index + 1}`;
|
||||
const items = this.readArray(turn, "items") ?? [];
|
||||
return {
|
||||
id: turnId,
|
||||
items,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
threadId,
|
||||
turns,
|
||||
};
|
||||
}
|
||||
|
||||
private isServerRequest(value: unknown): value is JsonRpcRequest {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
@@ -913,16 +757,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return target as Record<string, unknown>;
|
||||
}
|
||||
|
||||
private readArray(value: unknown, key?: string): unknown[] | undefined {
|
||||
const target =
|
||||
key === undefined
|
||||
? value
|
||||
: value && typeof value === "object"
|
||||
? (value as Record<string, unknown>)[key]
|
||||
: undefined;
|
||||
return Array.isArray(target) ? target : undefined;
|
||||
}
|
||||
|
||||
private readString(value: unknown, key: string): string | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
@@ -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?",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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
-499
@@ -1,456 +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,
|
||||
type MenuItemConstructorOptions,
|
||||
protocol,
|
||||
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 MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
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);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
|
||||
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;
|
||||
let desktopProtocolRegistered = 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");
|
||||
}
|
||||
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
return [agentSessionIdSchema.parse(sessionId), data];
|
||||
},
|
||||
]);
|
||||
|
||||
function resolveAppRoot(): string {
|
||||
if (!app.isPackaged) {
|
||||
return ROOT_DIR;
|
||||
}
|
||||
return app.getAppPath();
|
||||
}
|
||||
|
||||
function resolveBackendEntry(): string {
|
||||
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||
}
|
||||
|
||||
function resolveBackendCwd(): string {
|
||||
if (!app.isPackaged) {
|
||||
return resolveAppRoot();
|
||||
}
|
||||
return os.homedir();
|
||||
}
|
||||
|
||||
function resolveDesktopStaticDir(): string | null {
|
||||
const appRoot = resolveAppRoot();
|
||||
const candidates = [
|
||||
path.join(appRoot, "apps/server/dist/client"),
|
||||
path.join(appRoot, "apps/web/dist"),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(path.join(candidate, "index.html"))) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
|
||||
const url = new URL(requestUrl);
|
||||
const rawPath = decodeURIComponent(url.pathname);
|
||||
const normalizedPath = path.posix.normalize(rawPath).replace(/^\/+/, "");
|
||||
if (normalizedPath.includes("..")) {
|
||||
return path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
|
||||
const resolvedPath = path.join(staticRoot, requestedPath);
|
||||
|
||||
if (path.extname(resolvedPath)) {
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
const nestedIndex = path.join(resolvedPath, "index.html");
|
||||
if (fs.existsSync(nestedIndex)) {
|
||||
return nestedIndex;
|
||||
}
|
||||
|
||||
return path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
function isStaticAssetRequest(requestUrl: string): boolean {
|
||||
try {
|
||||
const url = new URL(requestUrl);
|
||||
return path.extname(url.pathname).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function registerDesktopProtocol(): void {
|
||||
if (isDevelopment || desktopProtocolRegistered) return;
|
||||
|
||||
const staticRoot = resolveDesktopStaticDir();
|
||||
if (!staticRoot) {
|
||||
throw new Error("Desktop static bundle missing. Build apps/server (with bundled client) first.");
|
||||
}
|
||||
|
||||
const staticRootResolved = path.resolve(staticRoot);
|
||||
const staticRootPrefix = `${staticRootResolved}${path.sep}`;
|
||||
const fallbackIndex = path.join(staticRootResolved, "index.html");
|
||||
|
||||
protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
|
||||
try {
|
||||
const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
|
||||
const resolvedCandidate = path.resolve(candidate);
|
||||
const isInRoot =
|
||||
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
|
||||
const isAssetRequest = isStaticAssetRequest(request.url);
|
||||
|
||||
if (!isInRoot || !fs.existsSync(resolvedCandidate)) {
|
||||
if (isAssetRequest) {
|
||||
callback({ error: -6 });
|
||||
return;
|
||||
}
|
||||
callback({ path: fallbackIndex });
|
||||
return;
|
||||
}
|
||||
|
||||
callback({ path: resolvedCandidate });
|
||||
} catch {
|
||||
callback({ path: fallbackIndex });
|
||||
}
|
||||
});
|
||||
|
||||
desktopProtocolRegistered = true;
|
||||
}
|
||||
|
||||
function dispatchMenuAction(action: string): void {
|
||||
const existingWindow = BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
|
||||
const targetWindow = existingWindow ?? createWindow();
|
||||
if (!existingWindow) {
|
||||
mainWindow = targetWindow;
|
||||
}
|
||||
|
||||
const send = () => {
|
||||
if (targetWindow.isDestroyed()) return;
|
||||
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
|
||||
if (!targetWindow.isVisible()) {
|
||||
targetWindow.show();
|
||||
}
|
||||
targetWindow.focus();
|
||||
};
|
||||
|
||||
if (targetWindow.webContents.isLoadingMainFrame()) {
|
||||
targetWindow.webContents.once("did-finish-load", send);
|
||||
return;
|
||||
}
|
||||
|
||||
send();
|
||||
}
|
||||
|
||||
function configureApplicationMenu(): void {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
template.push({
|
||||
label: app.name,
|
||||
submenu: [
|
||||
{ role: "about" },
|
||||
{
|
||||
label: "Settings...",
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
click: () => dispatchMenuAction("open-settings"),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{ role: "services" },
|
||||
{ type: "separator" },
|
||||
{ role: "hide" },
|
||||
{ role: "hideOthers" },
|
||||
{ role: "unhide" },
|
||||
{ type: "separator" },
|
||||
{ role: "quit" },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
template.push(
|
||||
{
|
||||
label: "File",
|
||||
submenu: [
|
||||
...(process.platform === "darwin"
|
||||
? []
|
||||
: [
|
||||
{
|
||||
label: "Settings...",
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
click: () => dispatchMenuAction("open-settings"),
|
||||
},
|
||||
{ type: "separator" as const },
|
||||
]),
|
||||
{ role: process.platform === "darwin" ? "close" : "quit" },
|
||||
],
|
||||
},
|
||||
{ role: "editMenu" },
|
||||
{ role: "viewMenu" },
|
||||
{ role: "windowMenu" },
|
||||
);
|
||||
|
||||
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||
}
|
||||
|
||||
function resolveResourcePath(fileName: string): string | null {
|
||||
const candidates = [
|
||||
path.join(__dirname, "../resources", fileName),
|
||||
path.join(process.resourcesPath, "resources", fileName),
|
||||
path.join(process.resourcesPath, fileName),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
|
||||
return resolveResourcePath(`icon.${ext}`);
|
||||
}
|
||||
|
||||
function configureAppIdentity(): void {
|
||||
app.setName(APP_DISPLAY_NAME);
|
||||
app.setAboutPanelOptions({
|
||||
applicationName: APP_DISPLAY_NAME,
|
||||
});
|
||||
|
||||
if (process.platform === "win32") {
|
||||
app.setAppUserModelId(APP_USER_MODEL_ID);
|
||||
}
|
||||
|
||||
if (process.platform === "darwin" && app.dock) {
|
||||
const iconPath = resolveIconPath("png");
|
||||
if (iconPath) {
|
||||
app.dock.setIcon(iconPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
const backendEntry = resolveBackendEntry();
|
||||
if (!fs.existsSync(backendEntry)) {
|
||||
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const child = spawn(process.execPath, [backendEntry], {
|
||||
cwd: resolveBackendCwd(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
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.exitCode === null && child.signalCode === null) {
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getIconOption(): { icon: string } | Record<string, never> {
|
||||
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = process.platform === "win32" ? "ico" : "png";
|
||||
const iconPath = resolveIconPath(ext);
|
||||
return iconPath ? { icon: iconPath } : {};
|
||||
}
|
||||
};
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
@@ -460,8 +50,6 @@ function createWindow(): BrowserWindow {
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
webPreferences: {
|
||||
@@ -473,62 +61,285 @@ function createWindow(): BrowserWindow {
|
||||
});
|
||||
|
||||
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
|
||||
window.on("page-title-updated", (event) => {
|
||||
event.preventDefault();
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
});
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
});
|
||||
|
||||
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 {
|
||||
void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
|
||||
return window;
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
if (mainWindow === window) {
|
||||
mainWindow = null;
|
||||
}
|
||||
});
|
||||
|
||||
void window.loadFile(path.join(__dirname, "../../renderer/dist/index.html"));
|
||||
return window;
|
||||
}
|
||||
|
||||
configureAppIdentity();
|
||||
function registerIpcHandlers(): void {
|
||||
// Todo handlers
|
||||
ipcMain.handle(IPC_CHANNELS.todosList, async () => {
|
||||
return todoStore.list();
|
||||
});
|
||||
|
||||
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;
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.todosAdd,
|
||||
withParsedPayload(newTodoInputSchema, async (_event, payload) => {
|
||||
return todoStore.add(payload);
|
||||
}),
|
||||
);
|
||||
|
||||
registerIpcHandlers();
|
||||
startBackend();
|
||||
mainWindow = createWindow();
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
isQuitting = true;
|
||||
stopBackend();
|
||||
});
|
||||
async function runTerminalCommand(input: TerminalCommandInput): Promise<TerminalCommandResult> {
|
||||
const shellPath =
|
||||
process.platform === "win32"
|
||||
? (process.env.ComSpec ?? "cmd.exe")
|
||||
: (process.env.SHELL ?? "/bin/sh");
|
||||
|
||||
app.whenReady().then(() => {
|
||||
configureAppIdentity();
|
||||
configureApplicationMenu();
|
||||
registerDesktopProtocol();
|
||||
void bootstrap();
|
||||
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> {
|
||||
setupCSP();
|
||||
|
||||
todoStore = new TodoStore(path.join(app.getPath("userData"), "todos.json"));
|
||||
await todoStore.init();
|
||||
|
||||
registerIpcHandlers();
|
||||
createWindow();
|
||||
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow();
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
processManager.killAll();
|
||||
providerManager.stopAll();
|
||||
providerManager.dispose();
|
||||
});
|
||||
|
||||
app.whenReady().then(() => {
|
||||
void bootstrap();
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
@@ -536,19 +347,3 @@ app.on("window-all-closed", () => {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
if (process.platform !== "win32") {
|
||||
process.on("SIGINT", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
stopBackend();
|
||||
app.quit();
|
||||
});
|
||||
|
||||
process.on("SIGTERM", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
stopBackend();
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
+51
-24
@@ -1,28 +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 MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
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>,
|
||||
onMenuAction: (listener: (action: string) => void) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
if (typeof action !== "string") return;
|
||||
listener(action);
|
||||
};
|
||||
|
||||
ipcRenderer.on(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
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);
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ProviderManager } from "./providerManager";
|
||||
|
||||
describe("ProviderManager", () => {
|
||||
it("detaches provider event listener and ends thread log streams on dispose", () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: { listenerCount: (event: string) => number };
|
||||
onCodexEvent: (event: {
|
||||
id: string;
|
||||
kind: "notification";
|
||||
provider: "codex";
|
||||
sessionId: string;
|
||||
createdAt: string;
|
||||
method: string;
|
||||
threadId: string;
|
||||
}) => void;
|
||||
threadLogStreams: Map<
|
||||
string,
|
||||
{ writableEnded: boolean; destroyed: boolean }
|
||||
>;
|
||||
};
|
||||
internals.onCodexEvent({
|
||||
id: "evt-1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "thread/started",
|
||||
threadId: "thread-1",
|
||||
});
|
||||
const stream = internals.threadLogStreams.get("thread-1");
|
||||
expect(stream).toBeDefined();
|
||||
if (!stream) return;
|
||||
|
||||
expect(internals.codex.listenerCount("event")).toBe(1);
|
||||
manager.dispose();
|
||||
|
||||
expect(internals.codex.listenerCount("event")).toBe(0);
|
||||
expect(stream.writableEnded || stream.destroyed).toBe(true);
|
||||
expect(internals.threadLogStreams.size).toBe(0);
|
||||
});
|
||||
|
||||
it("allows multiple dispose calls", () => {
|
||||
const manager = new ProviderManager();
|
||||
|
||||
manager.dispose();
|
||||
expect(() => manager.dispose()).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects request responses for unknown sessions", async () => {
|
||||
const manager = new ProviderManager();
|
||||
|
||||
await expect(
|
||||
manager.respondToRequest({
|
||||
sessionId: "missing-session",
|
||||
requestId: "req-1",
|
||||
decision: "accept",
|
||||
}),
|
||||
).rejects.toThrow("Unknown provider session: missing-session");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
type ProviderEvent,
|
||||
type ProviderInterruptTurnInput,
|
||||
type ProviderRespondToRequestInput,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderStopSessionInput,
|
||||
type ProviderTurnStartResult,
|
||||
providerInterruptTurnInputSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
} from "@acme/contracts";
|
||||
import { CodexAppServerManager } from "./codexAppServerManager";
|
||||
|
||||
export interface ProviderManagerEvents {
|
||||
event: [event: ProviderEvent];
|
||||
}
|
||||
|
||||
export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
private readonly codex = new CodexAppServerManager();
|
||||
private readonly threadLogsDir: string;
|
||||
private readonly threadLogStreams = new Map<string, fs.WriteStream>();
|
||||
private readonly sessionThreadIds = new Map<string, string>();
|
||||
private readonly pendingEventsBySession = new Map<string, ProviderEvent[]>();
|
||||
private disposed = false;
|
||||
private readonly onCodexEvent = (event: ProviderEvent) => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.routeEventToThreadLog(event);
|
||||
this.emit("event", event);
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
const logsDir = path.resolve(process.cwd(), ".logs");
|
||||
this.threadLogsDir = path.join(logsDir, "threads");
|
||||
fs.mkdirSync(this.threadLogsDir, { recursive: true });
|
||||
|
||||
this.codex.on("event", this.onCodexEvent);
|
||||
}
|
||||
|
||||
async startSession(raw: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const input = providerSessionStartInputSchema.parse(raw);
|
||||
if (input.provider !== "codex") {
|
||||
throw new Error(`Provider '${input.provider}' is not implemented yet.`);
|
||||
}
|
||||
|
||||
const session = await this.codex.startSession(input);
|
||||
if (session.threadId) {
|
||||
this.sessionThreadIds.set(session.sessionId, session.threadId);
|
||||
this.flushPendingSessionEvents(session.sessionId, session.threadId);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
async sendTurn(raw: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
const input = providerSendTurnInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
return this.codex.sendTurn(input);
|
||||
}
|
||||
|
||||
async interruptTurn(raw: ProviderInterruptTurnInput): Promise<void> {
|
||||
const input = providerInterruptTurnInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
await this.codex.interruptTurn(input.sessionId, input.turnId);
|
||||
}
|
||||
|
||||
async respondToRequest(raw: ProviderRespondToRequestInput): Promise<void> {
|
||||
const input = providerRespondToRequestInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
await this.codex.respondToRequest(
|
||||
input.sessionId,
|
||||
input.requestId,
|
||||
input.decision,
|
||||
);
|
||||
}
|
||||
|
||||
stopSession(raw: ProviderStopSessionInput): void {
|
||||
const input = providerStopSessionInputSchema.parse(raw);
|
||||
this.codex.stopSession(input.sessionId);
|
||||
this.sessionThreadIds.delete(input.sessionId);
|
||||
this.pendingEventsBySession.delete(input.sessionId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
return this.codex.listSessions();
|
||||
}
|
||||
|
||||
stopAll(): void {
|
||||
this.codex.stopAll();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.disposed = true;
|
||||
this.codex.off("event", this.onCodexEvent);
|
||||
for (const stream of this.threadLogStreams.values()) {
|
||||
stream.end();
|
||||
}
|
||||
this.threadLogStreams.clear();
|
||||
this.sessionThreadIds.clear();
|
||||
this.pendingEventsBySession.clear();
|
||||
}
|
||||
|
||||
private routeEventToThreadLog(event: ProviderEvent): void {
|
||||
const threadId = this.resolveThreadId(event);
|
||||
if (!threadId) {
|
||||
const pending = this.pendingEventsBySession.get(event.sessionId) ?? [];
|
||||
pending.push(event);
|
||||
this.pendingEventsBySession.set(event.sessionId, pending.slice(-100));
|
||||
return;
|
||||
}
|
||||
|
||||
this.flushPendingSessionEvents(event.sessionId, threadId);
|
||||
this.writeThreadEvent(threadId, event);
|
||||
}
|
||||
|
||||
private flushPendingSessionEvents(sessionId: string, threadId: string): void {
|
||||
const pending = this.pendingEventsBySession.get(sessionId);
|
||||
if (!pending || pending.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const event of pending) {
|
||||
this.writeThreadEvent(threadId, event);
|
||||
}
|
||||
this.pendingEventsBySession.delete(sessionId);
|
||||
}
|
||||
|
||||
private resolveThreadId(event: ProviderEvent): string | undefined {
|
||||
const fromPayload = this.readThreadIdFromPayload(event.payload);
|
||||
const threadId =
|
||||
event.threadId ??
|
||||
fromPayload ??
|
||||
this.sessionThreadIds.get(event.sessionId);
|
||||
|
||||
if (threadId) {
|
||||
this.sessionThreadIds.set(event.sessionId, threadId);
|
||||
}
|
||||
|
||||
return threadId;
|
||||
}
|
||||
|
||||
private readThreadIdFromPayload(payload: unknown): string | undefined {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const record = payload as Record<string, unknown>;
|
||||
const direct = record.threadId;
|
||||
if (typeof direct === "string" && direct.length > 0) {
|
||||
return direct;
|
||||
}
|
||||
|
||||
const thread = record.thread;
|
||||
if (!thread || typeof thread !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const nested = (thread as Record<string, unknown>).id;
|
||||
if (typeof nested === "string" && nested.length > 0) {
|
||||
return nested;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private writeThreadEvent(threadId: string, event: ProviderEvent): void {
|
||||
const stream = this.getOrCreateThreadLogStream(threadId);
|
||||
stream.write(`${JSON.stringify(event)}\n`);
|
||||
}
|
||||
|
||||
private getOrCreateThreadLogStream(threadId: string): fs.WriteStream {
|
||||
const cached = this.threadLogStreams.get(threadId);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const safeThreadId = threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
const stream = fs.createWriteStream(
|
||||
path.join(this.threadLogsDir, `${safeThreadId}.events.ndjson`),
|
||||
{ flags: "a" },
|
||||
);
|
||||
this.threadLogStreams.set(threadId, stream);
|
||||
return stream;
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
@@ -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"]
|
||||
}
|
||||
@@ -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"],
|
||||
},
|
||||
]);
|
||||
@@ -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"],
|
||||
});
|
||||
@@ -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"
|
||||
@@ -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,18 +11,12 @@
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"@tanstack/react-virtual": "^3.13.18",
|
||||
"@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",
|
||||
@@ -33,13 +27,12 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.0.0",
|
||||
"@tanstack/router-plugin": "^1.161.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"
|
||||
}
|
||||
}
|
||||
@@ -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,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);
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useStore } from "../store";
|
||||
|
||||
export default function DiffPanel() {
|
||||
const { dispatch } = useStore();
|
||||
|
||||
return (
|
||||
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
|
||||
{/* Header */}
|
||||
<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"
|
||||
className="text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground"
|
||||
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
|
||||
>
|
||||
<span className="text-sm">×</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Placeholder content */}
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<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>
|
||||
</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>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-center text-[10px] text-muted-foreground/30">
|
||||
Diff integration coming soon
|
||||
</p>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
+39
-13
@@ -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}
|
||||
/>
|
||||
+67
-30
@@ -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 };
|
||||
+3
-5
@@ -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,
|
||||
};
|
||||
+77
-35
@@ -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}
|
||||
>
|
||||
+57
-16
@@ -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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
+23
-10
@@ -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,
|
||||
};
|
||||
+5
-4
@@ -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 (
|
||||
+14
-10
@@ -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(
|
||||
+9
-15
@@ -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
-3
@@ -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 (
|
||||
+7
-5
@@ -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"
|
||||
>
|
||||
+34
-81
@@ -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,
|
||||
+6
-2
@@ -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;
|
||||
|
||||
@@ -60,18 +58,16 @@ function SheetPopup({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
keepMounted = false,
|
||||
side = "right",
|
||||
variant = "default",
|
||||
...props
|
||||
}: SheetPrimitive.Popup.Props & {
|
||||
showCloseButton?: boolean;
|
||||
keepMounted?: boolean;
|
||||
side?: "right" | "left" | "top" | "bottom";
|
||||
variant?: "default" | "inset";
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal keepMounted={keepMounted}>
|
||||
<SheetPortal>
|
||||
<SheetBackdrop />
|
||||
<SheetViewport side={side} variant={variant}>
|
||||
<SheetPrimitive.Popup
|
||||
@@ -146,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
-1
@@ -1,4 +1,4 @@
|
||||
import { cn } from "~/lib/utils";
|
||||
import { cn } from "#/lib/utils";
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
+5
-2
@@ -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"
|
||||
/>
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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,
|
||||
};
|
||||
+9
-5
@@ -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)}
|
||||
@@ -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> = [];
|
||||
@@ -28,7 +28,6 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
|
||||
document.documentElement.classList.toggle("dark", isDark);
|
||||
if (suppressTransitions) {
|
||||
// Force a reflow so the no-transitions class takes effect before removal
|
||||
// oxlint-disable-next-line no-unused-expressions
|
||||
document.documentElement.offsetHeight;
|
||||
requestAnimationFrame(() => {
|
||||
document.documentElement.classList.remove("no-transitions");
|
||||
@@ -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,43 +240,6 @@ input {
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
|
||||
.turn-chip-strip {
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
overscroll-behavior-x: contain;
|
||||
}
|
||||
|
||||
.turn-chip-strip::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* 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;
|
||||
@@ -261,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 {
|
||||
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import "highlight.js/styles/github-dark.css";
|
||||
|
||||
import App from "./App";
|
||||
import "./index.css";
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
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";
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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,12 +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,
|
||||
deriveTurnDiffFilesFromUnifiedDiff,
|
||||
deriveTurnDiffSummaries,
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
evolveSession,
|
||||
@@ -137,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({
|
||||
@@ -157,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", () => {
|
||||
@@ -263,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", () => {
|
||||
@@ -325,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(
|
||||
[
|
||||
@@ -395,306 +283,6 @@ describe("deriveWorkLogEntries", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTurnDiffSummaries", () => {
|
||||
it("tracks completed turns and links them to assistant message completion", () => {
|
||||
const summaries = deriveTurnDiffSummaries([
|
||||
makeEvent({
|
||||
id: "evt-turn-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-file-change",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-file-change",
|
||||
type: "fileChange",
|
||||
status: "completed",
|
||||
changes: [
|
||||
{
|
||||
path: "src/a.ts",
|
||||
kind: "modified",
|
||||
diff: "diff --git a/src/a.ts b/src/a.ts\n@@ -1 +1 @@\n-old\n+new\n",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-diff-updated",
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
threadId: "thr-1",
|
||||
turnId: "turn-1",
|
||||
diff: [
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"diff --git a/src/b.ts b/src/b.ts",
|
||||
"@@ -0,0 +1 @@",
|
||||
"+created",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-agent-msg",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:03.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "msg-1",
|
||||
type: "agentMessage",
|
||||
text: "Done",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-completed",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:04.000Z",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-2-file-change",
|
||||
method: "item/completed",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-file-change-2",
|
||||
type: "fileChange",
|
||||
status: "completed",
|
||||
changes: [
|
||||
{
|
||||
path: "src/unfinished.ts",
|
||||
kind: "modified",
|
||||
diff: "diff --git a/src/unfinished.ts b/src/unfinished.ts",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.turnId).toBe("turn-1");
|
||||
expect(summaries[0]?.assistantMessageId).toBe("msg-1");
|
||||
expect(summaries[0]?.files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
||||
expect(summaries[0]?.files[0]?.kind).toBe("modified");
|
||||
expect(summaries[0]?.files[0]?.additions).toBe(1);
|
||||
expect(summaries[0]?.files[0]?.deletions).toBe(1);
|
||||
expect(summaries[0]).not.toHaveProperty("unifiedDiff");
|
||||
});
|
||||
|
||||
it("includes completed turns even when no fileChange tool events were emitted", () => {
|
||||
const summaries = deriveTurnDiffSummaries([
|
||||
makeEvent({
|
||||
id: "evt-turn-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-completed",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.turnId).toBe("turn-1");
|
||||
expect(summaries[0]?.files).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps newest diff data when older events provide stale values", () => {
|
||||
const summaries = deriveTurnDiffSummaries([
|
||||
makeEvent({
|
||||
id: "evt-turn-diff-old",
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: {
|
||||
diff: [
|
||||
"diff --git a/src/example.ts b/src/example.ts",
|
||||
"@@ -1 +1,2 @@",
|
||||
"-old",
|
||||
"+older",
|
||||
"+extra",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-diff-new",
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
diff: [
|
||||
"diff --git a/src/example.ts b/src/example.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+newest",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-completed",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:03.000Z",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.files[0]?.path).toBe("src/example.ts");
|
||||
expect(summaries[0]?.files[0]?.additions).toBe(1);
|
||||
expect(summaries[0]?.files[0]?.deletions).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTurnDiffFilesFromUnifiedDiff", () => {
|
||||
it("splits a multi-file patch into sorted per-file entries", () => {
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
||||
[
|
||||
"diff --git a/src/b.ts b/src/b.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-b",
|
||||
"+new-b",
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-a",
|
||||
"+new-a",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
||||
expect(files[0]?.additions).toBe(1);
|
||||
expect(files[0]?.deletions).toBe(1);
|
||||
});
|
||||
|
||||
it("parses git headers when file paths include ` b/`", () => {
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
||||
[
|
||||
"diff --git a/subdir b/example.ts b/subdir b/example.ts",
|
||||
"--- a/subdir b/example.ts",
|
||||
"+++ b/subdir b/example.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(files).toHaveLength(1);
|
||||
expect(files[0]?.path).toBe("subdir b/example.ts");
|
||||
});
|
||||
|
||||
it("parses git header fallback for binary diffs with ` b/` in path", () => {
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
||||
[
|
||||
"diff --git a/subdir b/image.png b/subdir b/image.png",
|
||||
"Binary files a/subdir b/image.png and b/subdir b/image.png differ",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(files).toHaveLength(1);
|
||||
expect(files[0]?.path).toBe("subdir b/image.png");
|
||||
});
|
||||
});
|
||||
|
||||
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 { ChatMessage, SessionPhase, TurnDiffFileChange, TurnDiffSummary } from "./types";
|
||||
import { createWsNativeApi } from "./wsNativeApi";
|
||||
import type { ProviderEvent, ProviderKind, ProviderSession } from "@acme/contracts";
|
||||
import type { ChatMessage, SessionPhase } from "./types";
|
||||
|
||||
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 {
|
||||
@@ -33,18 +20,10 @@ export function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asArray(value: unknown): unknown[] | undefined {
|
||||
return Array.isArray(value) ? value : undefined;
|
||||
}
|
||||
|
||||
export function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function asNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
export function formatTimestamp(isoDate: string): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
@@ -86,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;
|
||||
@@ -107,60 +79,12 @@ export type TimelineEntry =
|
||||
entry: WorkLogEntry;
|
||||
};
|
||||
|
||||
export type { TurnDiffFileChange, TurnDiffSummary } from "./types";
|
||||
|
||||
function normalizeDetail(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
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
|
||||
@@ -172,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;
|
||||
}
|
||||
|
||||
@@ -180,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 {
|
||||
@@ -203,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),
|
||||
@@ -237,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));
|
||||
@@ -255,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",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -307,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;
|
||||
@@ -320,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;
|
||||
@@ -375,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);
|
||||
@@ -433,7 +328,7 @@ export function deriveWorkLogEntries(
|
||||
continue;
|
||||
}
|
||||
|
||||
const fromNotification = entryFromNotification(event);
|
||||
const fromNotification = entryFromNotification(event, turnStartedAt);
|
||||
if (fromNotification) {
|
||||
entries.push(fromNotification);
|
||||
continue;
|
||||
@@ -448,272 +343,6 @@ export function deriveWorkLogEntries(
|
||||
return entries;
|
||||
}
|
||||
|
||||
interface MutableTurnDiffSummary {
|
||||
turnId: string;
|
||||
completedAt: string | undefined;
|
||||
status: string | undefined;
|
||||
assistantMessageId: string | undefined;
|
||||
hasTurnDiffUpdate: boolean;
|
||||
filesByPath: Map<string, TurnDiffFileChange>;
|
||||
}
|
||||
|
||||
function parseFileChangeEntriesFromEvent(event: ProviderEvent): TurnDiffFileChange[] {
|
||||
if (event.method !== "item/completed") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const item = asObject(asObject(event.payload)?.item);
|
||||
const itemType = normalizeItemType(asString(item?.type));
|
||||
if (itemType !== "file change") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const changes = asArray(item?.changes) ?? [];
|
||||
const parsed: TurnDiffFileChange[] = [];
|
||||
for (const rawChange of changes) {
|
||||
const change = asObject(rawChange);
|
||||
if (!change) continue;
|
||||
|
||||
const diff = normalizeDetail(asString(change.diff));
|
||||
const path = normalizeDetail(asString(change.path)) ?? (diff ? parsePathFromDiff(diff) : undefined);
|
||||
if (!path) continue;
|
||||
|
||||
const additions = asNumber(change.additions);
|
||||
const deletions = asNumber(change.deletions);
|
||||
const stat = additions !== undefined && deletions !== undefined ? null : diff ? countDiffStat(diff) : null;
|
||||
const kind = normalizeDetail(asString(change.kind));
|
||||
parsed.push({
|
||||
path,
|
||||
...(kind ? { kind } : {}),
|
||||
...(additions !== undefined ? { additions } : stat ? { additions: stat.additions } : {}),
|
||||
...(deletions !== undefined ? { deletions } : stat ? { deletions: stat.deletions } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function mergeTurnDiffFileChange(
|
||||
byPath: Map<string, TurnDiffFileChange>,
|
||||
incoming: TurnDiffFileChange,
|
||||
): void {
|
||||
const existing = byPath.get(incoming.path);
|
||||
if (!existing) {
|
||||
byPath.set(incoming.path, incoming);
|
||||
return;
|
||||
}
|
||||
|
||||
if (existing.kind === undefined && incoming.kind !== undefined) {
|
||||
existing.kind = incoming.kind;
|
||||
}
|
||||
if (existing.additions === undefined && incoming.additions !== undefined) {
|
||||
existing.additions = incoming.additions;
|
||||
}
|
||||
if (existing.deletions === undefined && incoming.deletions !== undefined) {
|
||||
existing.deletions = incoming.deletions;
|
||||
}
|
||||
}
|
||||
|
||||
function parsePathFromDiff(diff: string): string | undefined {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
const bPath = normalized.match(/^\+\+\+ b\/(.+)$/m);
|
||||
if (bPath && bPath[1]) return bPath[1];
|
||||
const gitHeader = normalized.match(/^diff --git a\/(.+) b\/\1$/m);
|
||||
if (gitHeader && gitHeader[1]) return gitHeader[1];
|
||||
const direct = normalized.match(/^\+\+\+ (.+)$/m);
|
||||
if (!direct || !direct[1] || direct[1] === "/dev/null") {
|
||||
return undefined;
|
||||
}
|
||||
return direct[1];
|
||||
}
|
||||
|
||||
export function splitUnifiedDiffByFile(diff: string): Map<string, string> {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
const byPath = new Map<string, string>();
|
||||
const headerMatches = [...normalized.matchAll(/^diff --git .+$/gm)];
|
||||
|
||||
if (headerMatches.length === 0) {
|
||||
const path = parsePathFromDiff(normalized);
|
||||
if (path) {
|
||||
byPath.set(path, normalized.trim());
|
||||
}
|
||||
return byPath;
|
||||
}
|
||||
|
||||
for (let index = 0; index < headerMatches.length; index += 1) {
|
||||
const match = headerMatches[index];
|
||||
if (!match) continue;
|
||||
const start = match.index ?? 0;
|
||||
const nextStart = headerMatches[index + 1]?.index ?? normalized.length;
|
||||
const segment = normalized.slice(start, nextStart).trim();
|
||||
const path = parsePathFromDiff(segment);
|
||||
if (!path || segment.length === 0) continue;
|
||||
byPath.set(path, segment);
|
||||
}
|
||||
|
||||
return byPath;
|
||||
}
|
||||
|
||||
export function deriveTurnDiffFilesFromUnifiedDiff(diff: string): TurnDiffFileChange[] {
|
||||
const fileDiffsByPath = splitUnifiedDiffByFile(diff);
|
||||
return Array.from(fileDiffsByPath.entries())
|
||||
.map(([path, fileDiff]) => {
|
||||
const stat = countDiffStat(fileDiff);
|
||||
return {
|
||||
path,
|
||||
additions: stat.additions,
|
||||
deletions: stat.deletions,
|
||||
};
|
||||
})
|
||||
.toSorted((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
|
||||
export function inferCheckpointTurnCountByTurnId(
|
||||
summaries: TurnDiffSummary[],
|
||||
): Record<string, number> {
|
||||
if (summaries.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const sorted = [...summaries].toSorted((a, b) => {
|
||||
const aTime = Date.parse(a.completedAt);
|
||||
const bTime = Date.parse(b.completedAt);
|
||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
||||
return a.completedAt.localeCompare(b.completedAt);
|
||||
}
|
||||
return aTime - bTime;
|
||||
});
|
||||
|
||||
const next: Record<string, number> = {};
|
||||
let fallbackTurnCount = 1;
|
||||
for (const summary of sorted) {
|
||||
if (typeof summary.checkpointTurnCount === "number") {
|
||||
next[summary.turnId] = summary.checkpointTurnCount;
|
||||
fallbackTurnCount = Math.max(fallbackTurnCount, summary.checkpointTurnCount + 1);
|
||||
continue;
|
||||
}
|
||||
next[summary.turnId] = fallbackTurnCount;
|
||||
fallbackTurnCount += 1;
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
export function countDiffStat(patch: string | undefined): { additions: number; deletions: number } {
|
||||
if (!patch) {
|
||||
return { additions: 0, deletions: 0 };
|
||||
}
|
||||
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
for (const line of patch.replace(/\r\n/g, "\n").split("\n")) {
|
||||
if (line.startsWith("+++ ") || line.startsWith("--- ")) continue;
|
||||
if (line.startsWith("+")) {
|
||||
additions += 1;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("-")) {
|
||||
deletions += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return { additions, deletions };
|
||||
}
|
||||
|
||||
export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummary[] {
|
||||
const firstEventAt = Date.parse(events[0]?.createdAt ?? "");
|
||||
const lastEventAt = Date.parse(events.at(-1)?.createdAt ?? "");
|
||||
const ordered =
|
||||
events.length < 2 ||
|
||||
Number.isNaN(firstEventAt) ||
|
||||
Number.isNaN(lastEventAt) ||
|
||||
firstEventAt >= lastEventAt
|
||||
? events
|
||||
: [...events].toReversed();
|
||||
const byTurnId = new Map<string, MutableTurnDiffSummary>();
|
||||
|
||||
const ensureSummary = (turnId: string): MutableTurnDiffSummary => {
|
||||
const existing = byTurnId.get(turnId);
|
||||
if (existing) return existing;
|
||||
const next: MutableTurnDiffSummary = {
|
||||
turnId,
|
||||
completedAt: undefined,
|
||||
status: undefined,
|
||||
assistantMessageId: undefined,
|
||||
hasTurnDiffUpdate: false,
|
||||
filesByPath: new Map<string, TurnDiffFileChange>(),
|
||||
};
|
||||
byTurnId.set(turnId, next);
|
||||
return next;
|
||||
};
|
||||
|
||||
for (const event of ordered) {
|
||||
const turnId = eventTurnId(event);
|
||||
if (!turnId) continue;
|
||||
const summary = ensureSummary(turnId);
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
if (summary.completedAt === undefined) {
|
||||
summary.completedAt = event.createdAt;
|
||||
}
|
||||
const turn = asObject(asObject(event.payload)?.turn);
|
||||
if (summary.status === undefined) {
|
||||
summary.status = normalizeDetail(asString(turn?.status));
|
||||
}
|
||||
}
|
||||
|
||||
if (event.method === "item/completed") {
|
||||
const item = asObject(asObject(event.payload)?.item);
|
||||
if (asString(item?.type) === "agentMessage") {
|
||||
const itemId = normalizeDetail(asString(item?.id));
|
||||
if (itemId && summary.assistantMessageId === undefined) {
|
||||
summary.assistantMessageId = itemId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (event.method === "turn/diff/updated" && !summary.hasTurnDiffUpdate) {
|
||||
summary.hasTurnDiffUpdate = true;
|
||||
const diff = normalizeDetail(asString(asObject(event.payload)?.diff));
|
||||
if (diff) {
|
||||
for (const file of deriveTurnDiffFilesFromUnifiedDiff(diff)) {
|
||||
mergeTurnDiffFileChange(summary.filesByPath, file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const file of parseFileChangeEntriesFromEvent(event)) {
|
||||
mergeTurnDiffFileChange(summary.filesByPath, file);
|
||||
}
|
||||
}
|
||||
|
||||
const summaries: TurnDiffSummary[] = [];
|
||||
for (const summary of byTurnId.values()) {
|
||||
if (!summary.completedAt) continue;
|
||||
|
||||
summaries.push({
|
||||
turnId: summary.turnId,
|
||||
completedAt: summary.completedAt,
|
||||
...(summary.status ? { status: summary.status } : {}),
|
||||
files: Array.from(summary.filesByPath.values()).toSorted((a, b) =>
|
||||
a.path.localeCompare(b.path),
|
||||
),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
summaries.sort((a, b) => {
|
||||
const aTime = Date.parse(a.completedAt);
|
||||
const bTime = Date.parse(b.completedAt);
|
||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
||||
return b.completedAt.localeCompare(a.completedAt);
|
||||
}
|
||||
return bTime - aTime;
|
||||
});
|
||||
|
||||
return summaries;
|
||||
}
|
||||
|
||||
function toTimestamp(isoDate: string): number {
|
||||
const parsed = Date.parse(isoDate);
|
||||
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Vendored
+9
@@ -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"]
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
@@ -1,35 +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": {
|
||||
"@t3tools/core": "workspace:*",
|
||||
"@t3tools/infra-sqlite": "workspace:*",
|
||||
"effect": "^3.18.4",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user