Merge origin/main into statemachine

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-03-09 11:22:43 -07:00
commit bbb88d1f6b
50 files changed
+2180 -562

No files matched your search

+180
View File
@@ -0,0 +1,180 @@
# Encyclopedia
This is a living glossary for T3 Code. It explains what common terms mean in this codebase.
## Table of contents
- [Project and workspace](#project-and-workspace)
- [Thread timeline](#thread-timeline)
- [Orchestration](#orchestration)
- [Provider runtime](#provider-runtime)
- [Checkpointing](#checkpointing)
## Concepts
### Project and workspace
#### Project
The top-level workspace record in the app. In [the orchestration contracts][1], a project has a `workspaceRoot`, a title, and one or more threads. See [workspace-layout.md][2].
#### Workspace root
The root filesystem path for a project. In [the orchestration model][1], it is the base directory for branches and optional worktrees. See [workspace-layout.md][2].
#### Worktree
A Git worktree used as an isolated workspace for a thread. If a thread has a `worktreePath` in [the contracts][1], it runs there instead of in the main working tree. Git operations live in [GitCore.ts][3].
### Thread timeline
#### Thread
The main durable unit of conversation and workspace history. In [the orchestration contracts][1], a thread holds messages, activities, checkpoints, and session-related state. See [projector.ts][4].
#### Turn
A single user-to-assistant work cycle inside a thread. It starts with user input and ends when follow-up work like checkpointing settles. See [the contracts][1], [ProviderRuntimeIngestion.ts][5], and [CheckpointReactor.ts][6].
#### Activity
A user-visible log item attached to a thread. In [the contracts][1], activities cover important non-message events like approvals, tool actions, and failures. They are projected into thread state in [projector.ts][4].
### Orchestration
Orchestration is the server-side domain layer that turns runtime activity into stable app state. The main entry point is [OrchestrationEngine.ts][7], with core logic in [decider.ts][8] and [projector.ts][4].
#### Aggregate
The domain object a command or event belongs to. In [the contracts][1], that is usually `project` or `thread`. See [decider.ts][8].
#### Command
A typed request to change domain state. In [the contracts][1], commands are validated in [commandInvariants.ts][9] and turned into events by [decider.ts][8].
Examples include `thread.create`, `thread.turn.start`, and `thread.checkpoint.revert`.
#### Domain Event
A persisted fact that something already happened. In [the contracts][1], events are the source of truth, and [projector.ts][4] shows how they are applied.
Examples include `thread.created`, `thread.message-sent`, and `thread.turn-diff-completed`.
#### Decider
The pure orchestration logic that turns commands plus current state into events. The core implementation is in [decider.ts][8], with preconditions in [commandInvariants.ts][9].
#### Projection
A read-optimized view derived from events. See [projector.ts][4], [ProjectionPipeline.ts][11], and [ProjectionSnapshotQuery.ts][10].
#### Projector
The logic that applies domain events to the read model or projection tables. See [projector.ts][4] and [ProjectionPipeline.ts][11].
#### Read model
The current materialized view of orchestration state. In [the contracts][1], it holds projects, threads, messages, activities, checkpoints, and session state. See [ProjectionSnapshotQuery.ts][10] and [OrchestrationEngine.ts][7].
#### Reactor
A side-effecting service that handles follow-up work after events or runtime signals. Examples include [CheckpointReactor.ts][6], [ProviderCommandReactor.ts][12], and [ProviderRuntimeIngestion.ts][5].
#### Receipt
A lightweight typed runtime signal emitted when an async milestone completes. See [RuntimeReceiptBus.ts][13].
Examples include `checkpoint.baseline.captured`, `checkpoint.diff.finalized`, and `turn.processing.quiesced`, which are emitted by flows such as [CheckpointReactor.ts][6].
#### Quiesced
"Quiesced" means a turn has gone quiet and stable. In [the receipt schema][13], it means the follow-up work has settled, including work in [CheckpointReactor.ts][6].
### Provider runtime
The live backend agent implementation and its event stream. The main service is [ProviderService.ts][14], the adapter contract is [ProviderAdapter.ts][15], and the overview is in [provider-architecture.md][16].
#### Provider
The backend agent runtime that actually performs work. See [ProviderService.ts][14], [ProviderAdapter.ts][15], and [CodexAdapter.ts][17].
#### Session
The live provider-backed runtime attached to a thread. Session shape is in [the orchestration contracts][1], and lifecycle is managed in [ProviderService.ts][14].
#### Runtime mode
The safety/access mode for a thread or session. In [the contracts][1], the main values are `approval-required` and `full-access`. See [runtime-modes.md][18].
#### Interaction mode
The agent interaction style for a thread. In [the contracts][1], the main values are `default` and `plan`. See [runtime-modes.md][18].
#### Assistant delivery mode
Controls how assistant text reaches the thread timeline. In [the contracts][1], `streaming` updates incrementally and `buffered` delivers a completed result. See [ProviderService.ts][14].
#### Snapshot
A point-in-time view of state. The word is used in multiple layers, including orchestration, provider, and checkpointing. See [ProjectionSnapshotQuery.ts][10], [ProviderAdapter.ts][15], and [CheckpointStore.ts][19].
### Checkpointing
Checkpointing captures workspace state over time so the app can diff turns and restore earlier points. The main pieces are [CheckpointStore.ts][19], [CheckpointDiffQuery.ts][20], and [CheckpointReactor.ts][6].
#### Checkpoint
A saved snapshot of a thread workspace at a particular turn. In practice it is a hidden Git ref in [CheckpointStore.ts][19] plus a projected summary from [ProjectionCheckpoints.ts][21]. Capture and lifecycle work happen in [CheckpointReactor.ts][6].
#### Checkpoint ref
The durable identifier for a filesystem checkpoint, stored as a Git ref. It is typed in [the contracts][1], constructed in [Utils.ts][22], and used by [CheckpointStore.ts][19].
#### Checkpoint baseline
The starting checkpoint for diffing a thread timeline. This flow is surfaced through [RuntimeReceiptBus.ts][13], coordinated in [CheckpointReactor.ts][6], and supported by [Utils.ts][22].
#### Checkpoint diff
The patch difference between two checkpoints. Query logic lives in [CheckpointDiffQuery.ts][20], diff parsing lives in [Diffs.ts][23], and finalization is coordinated by [CheckpointReactor.ts][6].
#### Turn diff
The file patch and changed-file summary for one turn. It is usually computed in [CheckpointDiffQuery.ts][20], represented in [the contracts][1], and recorded into thread state by [projector.ts][4].
## Practical Shortcuts
- If you see `requested`, think "intent recorded".
- If you see `completed`, think "result applied".
- If you see `receipt`, think "async milestone signal".
- If you see `checkpoint`, think "workspace snapshot for diff/restore".
- If you see `quiesced`, think "all relevant follow-up work has gone idle".
## Related Docs
- [architecture.md][24]
- [provider-architecture.md][16]
- [runtime-modes.md][18]
- [workspace-layout.md][2]
[1]: ../packages/contracts/src/orchestration.ts
[2]: ./workspace-layout.md
[3]: ../apps/server/src/git/Layers/GitCore.ts
[4]: ../apps/server/src/orchestration/projector.ts
[5]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
[6]: ../apps/server/src/orchestration/Layers/CheckpointReactor.ts
[7]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
[8]: ../apps/server/src/orchestration/decider.ts
[9]: ../apps/server/src/orchestration/commandInvariants.ts
[10]: ../apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
[11]: ../apps/server/src/orchestration/Layers/ProjectionPipeline.ts
[12]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
[13]: ../apps/server/src/orchestration/Services/RuntimeReceiptBus.ts
[14]: ../apps/server/src/provider/Layers/ProviderService.ts
[15]: ../apps/server/src/provider/Services/ProviderAdapter.ts
[16]: ./provider-architecture.md
[17]: ../apps/server/src/provider/Layers/CodexAdapter.ts
[18]: ./runtime-modes.md
[19]: ../apps/server/src/checkpointing/Services/CheckpointStore.ts
[20]: ../apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts
[21]: ../apps/server/src/persistence/Services/ProjectionCheckpoints.ts
[22]: ../apps/server/src/checkpointing/Utils.ts
[23]: ../apps/server/src/checkpointing/Diffs.ts
[24]: ./architecture.md
+28
View File
@@ -0,0 +1,28 @@
# Trust list for this repository.
#
# External contributors listed here are treated as trusted by the vouch
# workflow. Collaborators with write access are automatically trusted and
# do not need to be duplicated in this file.
#
# Syntax:
# github:username
# -github:username reason for denouncement
#
# Keep entries sorted alphabetically.
github:adityavardhansharma
github:binbandit
github:chuks-qua
github:cursoragent
github:gbarros-dev
github:github-actions[bot]
github:hwanseoc
github:jamesx0416
github:jasonLaster
github:JoeEverest
github:nmggithub
github:Noojuno
github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
+33
View File
@@ -0,0 +1,33 @@
<!--
⚠️ READ BEFORE OPENING ⚠️
We are not actively accepting contributions right now.
You can still open a PR, but please do so knowing there is a high chance
we may close it without merging it, or never review it.
- Small, focused PRs are strongly preferred. Bug fixes are most likely to be merged.
- New features will most likely just annoy us.
- 1,000+ line PRs with a bunch of new features will probably get you banned from the repo.
-->
## What Changed
<!-- Describe the change clearly and keep scope tight. -->
## Why
<!-- Explain the problem being solved and why this approach is the right one. -->
## UI Changes
<!-- If this PR changes UI, include clear before/after screenshots.
If the change involves motion or interaction, include a short video.
Delete this section if not applicable. -->
## Checklist
- [ ] This PR is small and focused
- [ ] I explained what changed and why
- [ ] I included before/after screenshots for any UI changes
- [ ] I included a video for animation/interaction changes
+20
View File
@@ -69,3 +69,23 @@ jobs:
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
release_smoke:
name: Release Smoke
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+175
View File
@@ -0,0 +1,175 @@
name: PR Vouch
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
issue_comment:
types: [created]
push:
branches:
- main
paths:
- .github/VOUCHED.td
- .github/workflows/pr-vouch.yml
permissions:
contents: read
issues: write
pull-requests: write
jobs:
collect-targets:
name: Collect PR targets
runs-on: ubuntu-24.04
outputs:
targets: ${{ steps.collect.outputs.targets }}
steps:
- id: collect
uses: actions/github-script@v7
with:
script: |
if (context.eventName === "pull_request_target") {
const pr = context.payload.pull_request;
core.setOutput("targets", JSON.stringify([{ number: pr.number, user: pr.user.login }]));
return;
}
if (context.eventName === "issue_comment") {
const issue = context.payload.issue;
const body = context.payload.comment?.body ?? "";
if (!issue?.pull_request || !body.includes("/recheck-vouch")) {
core.setOutput("targets", "[]");
return;
}
core.setOutput(
"targets",
JSON.stringify([{ number: issue.number, user: issue.user.login }]),
);
return;
}
const pulls = await github.paginate(github.rest.pulls.list, {
owner: context.repo.owner,
repo: context.repo.repo,
state: "open",
per_page: 100,
});
const targets = pulls.map((pull) => ({
number: pull.number,
user: pull.user.login,
}));
core.setOutput("targets", JSON.stringify(targets));
label:
name: Label PR ${{ matrix.target.number }}
needs: collect-targets
if: ${{ needs.collect-targets.outputs.targets != '[]' }}
runs-on: ubuntu-24.04
concurrency:
group: pr-vouch-${{ matrix.target.number }}
cancel-in-progress: true
strategy:
fail-fast: false
matrix:
target: ${{ fromJson(needs.collect-targets.outputs.targets) }}
steps:
- id: vouch
name: Check PR author trust
uses: mitchellh/vouch/action/check-user@v1
with:
user: ${{ matrix.target.user }}
allow-fail: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Sync PR labels
uses: actions/github-script@v7
env:
PR_NUMBER: ${{ matrix.target.number }}
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
with:
script: |
const issueNumber = Number(process.env.PR_NUMBER);
const status = process.env.VOUCH_STATUS;
const managedLabels = [
{
name: "vouch:trusted",
color: "1f883d",
description: "PR author is trusted by repo permissions or the VOUCHED list.",
},
{
name: "vouch:unvouched",
color: "fbca04",
description: "PR author is not yet trusted in the VOUCHED list.",
},
{
name: "vouch:denounced",
color: "d1242f",
description: "PR author is explicitly blocked by the VOUCHED list.",
},
];
const managedLabelNames = managedLabels.map((label) => label.name);
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
const nextLabelName =
status === "denounced"
? "vouch:denounced"
: ["bot", "collaborator", "vouched"].includes(status)
? "vouch:trusted"
: "vouch:unvouched";
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
});
const preservedLabels = currentLabels
.map((label) => label.name)
.filter((name) => !managedLabelNames.includes(name));
await github.rest.issues.setLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [...preservedLabels, nextLabelName],
});
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
+12 -28
View File
@@ -255,6 +255,16 @@ jobs:
needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Download all desktop artifacts
uses: actions/download-artifact@v4
with:
@@ -312,33 +322,7 @@ jobs:
name: Update version strings
env:
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
run: |
node --input-type=module -e '
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
const files = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
];
let changed = false;
for (const file of files) {
const packageJson = JSON.parse(readFileSync(file, "utf8"));
if (packageJson.version !== process.env.RELEASE_VERSION) {
packageJson.version = process.env.RELEASE_VERSION;
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
changed = true;
}
}
if (!changed) {
console.log("All package.json versions already match release version.");
}
appendFileSync(process.env.GITHUB_OUTPUT, `changed=${changed}\n`);
'
run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
@@ -346,7 +330,7 @@ jobs:
- name: Refresh lockfile
if: steps.update_versions.outputs.changed == 'true'
run: bun install
run: bun install --lockfile-only --ignore-scripts
- name: Commit and push version bump
if: steps.update_versions.outputs.changed == 'true'
+65
View File
@@ -0,0 +1,65 @@
# Contributing
## Read This First
We are not actively accepting contributions right now.
You can still open an issue or PR, but please do so knowing there is a high chance we close it, defer it forever, or never look at it.
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
PRs are automatically labeled with a `vouch:*` trust status.
If you are an external contributor, expect `vouch:unvouched` until we explicitly add you to [.github/VOUCHED.td](.github/VOUCHED.td).
## What We Are Most Likely To Accept
Small, focused bug fixes.
Small reliability fixes.
Small performance improvements.
Tightly scoped maintenance work that clearly improves the project without changing its direction.
## What We Are Least Likely To Accept
Large PRs.
Drive-by feature work.
Opinionated rewrites.
Anything that expands product scope without us asking for it first.
If you open a 1,000+ line PR full of new features, we will probably close it quickly and remember that you ignored the clearly written instructions.
## If You Still Want To Open A PR
Keep it small.
Explain exactly what changed.
Explain exactly why the change should exist.
Do not mix unrelated fixes together.
If the PR makes anything resembling a UI change, include clear before/after images.
If the change depends on motion, timing, transitions, or interaction details, include a short video.
If we have to guess what changed, we are much less likely to review it.
## Issues First
If you are thinking about a non-trivial change, open an issue first.
That still does not mean we will want the PR, but it gives you a chance to avoid wasting your time.
## Be Realistic
Opening a PR does not create an obligation on our side.
We may close it. We may ignore it. We may ask you to shrink it. We may reimplement the idea ourselves later.
If you are fine with that, proceed.
+4
View File
@@ -21,4 +21,8 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
## If you REALLY want to contribute still.... read this first
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.5",
"version": "0.0.9",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+110 -16
View File
@@ -31,6 +31,7 @@ import {
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
fixPath();
@@ -50,6 +51,8 @@ const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code";
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
const COMMIT_HASH_DISPLAY_LENGTH = 12;
const LOG_DIR = Path.join(STATE_DIR, "logs");
@@ -78,7 +81,13 @@ let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const initialUpdateState = (): DesktopUpdateState => createInitialDesktopUpdateState(app.getVersion());
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
platform: process.platform,
processArch: process.arch,
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
function logTimestamp(): string {
return new Date().toISOString();
@@ -112,6 +121,25 @@ function formatErrorMessage(error: unknown): string {
return String(error);
}
function getSafeExternalUrl(rawUrl: unknown): string | null {
if (typeof rawUrl !== "string" || rawUrl.length === 0) {
return null;
}
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return null;
}
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
return null;
}
return parsedUrl.toString();
}
function writeDesktopStreamChunk(
streamName: "stdout" | "stderr",
chunk: unknown,
@@ -574,6 +602,34 @@ function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
return resolveResourcePath(`icon.${ext}`);
}
/**
* Resolve the Electron userData directory path.
*
* Electron derives the default userData path from `productName` in
* package.json, which currently produces directories with spaces and
* parentheses (e.g. `~/.config/T3 Code (Alpha)` on Linux). This is
* unfriendly for shell usage and violates Linux naming conventions.
*
* We override it to a clean lowercase name (`t3code`). If the legacy
* directory already exists we keep using it so existing users don't
* lose their Chromium profile data (localStorage, cookies, sessions).
*/
function resolveUserDataPath(): string {
const appDataBase =
process.platform === "win32"
? process.env.APPDATA || Path.join(OS.homedir(), "AppData", "Roaming")
: process.platform === "darwin"
? Path.join(OS.homedir(), "Library", "Application Support")
: process.env.XDG_CONFIG_HOME || Path.join(OS.homedir(), ".config");
const legacyPath = Path.join(appDataBase, LEGACY_USER_DATA_DIR_NAME);
if (FS.existsSync(legacyPath)) {
return legacyPath;
}
return Path.join(appDataBase, USER_DATA_DIR_NAME);
}
function configureAppIdentity(): void {
app.setName(APP_DISPLAY_NAME);
const commitHash = resolveAboutCommitHash();
@@ -659,6 +715,7 @@ async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed
}
updateDownloadInFlight = true;
setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState));
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
console.info("[desktop-updater] Downloading update...");
try {
@@ -697,7 +754,7 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
function configureAutoUpdater(): void {
const enabled = shouldEnableAutoUpdates();
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion()),
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled,
status: enabled ? "idle" : "disabled",
});
@@ -731,8 +788,15 @@ function configureAutoUpdater(): void {
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
autoUpdater.allowDowngrade = false;
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
let lastLoggedDownloadMilestone = -1;
if (isArm64HostRunningIntelBuild(desktopRuntimeInfo)) {
console.info(
"[desktop-updater] Apple Silicon host detected while running Intel build; updates will switch to arm64 packages.",
);
}
autoUpdater.on("checking-for-update", () => {
console.info("[desktop-updater] Looking for updates...");
});
@@ -1033,23 +1097,13 @@ function registerIpcHandlers(): void {
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:") {
const externalUrl = getSafeExternalUrl(rawUrl);
if (!externalUrl) {
return false;
}
try {
await shell.openExternal(parsedUrl.toString());
await shell.openExternal(externalUrl);
return true;
} catch {
return false;
@@ -1114,7 +1168,42 @@ function createWindow(): BrowserWindow {
},
});
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
window.webContents.on("context-menu", (event, params) => {
event.preventDefault();
const menuTemplate: MenuItemConstructorOptions[] = [];
if (params.misspelledWord) {
for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
menuTemplate.push({
label: suggestion,
click: () => window.webContents.replaceMisspelling(suggestion),
});
}
if (params.dictionarySuggestions.length === 0) {
menuTemplate.push({ label: "No suggestions", enabled: false });
}
menuTemplate.push({ type: "separator" });
}
menuTemplate.push(
{ role: "cut", enabled: params.editFlags.canCut },
{ role: "copy", enabled: params.editFlags.canCopy },
{ role: "paste", enabled: params.editFlags.canPaste },
{ role: "selectAll", enabled: params.editFlags.canSelectAll },
);
Menu.buildFromTemplate(menuTemplate).popup({ window });
});
window.webContents.setWindowOpenHandler(({ url }) => {
const externalUrl = getSafeExternalUrl(url);
if (externalUrl) {
void shell.openExternal(externalUrl);
}
return { action: "deny" };
});
window.on("page-title-updated", (event) => {
event.preventDefault();
window.setTitle(APP_DISPLAY_NAME);
@@ -1143,6 +1232,11 @@ function createWindow(): BrowserWindow {
return window;
}
// Override Electron's userData path before the `ready` event so that
// Chromium session data uses a filesystem-friendly directory name.
// Must be called synchronously at the top level — before `app.whenReady()`.
app.setPath("userData", resolveUserDataPath());
configureAppIdentity();
async function bootstrap(): Promise<void> {
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
describe("resolveDesktopRuntimeInfo", () => {
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "darwin",
processArch: "x64",
runningUnderArm64Translation: true,
});
expect(runtimeInfo).toEqual({
hostArch: "arm64",
appArch: "x64",
runningUnderArm64Translation: true,
});
expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(true);
});
it("detects native Apple Silicon builds", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "darwin",
processArch: "arm64",
runningUnderArm64Translation: false,
});
expect(runtimeInfo).toEqual({
hostArch: "arm64",
appArch: "arm64",
runningUnderArm64Translation: false,
});
expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(false);
});
it("passes through non-mac builds without translation", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "linux",
processArch: "x64",
runningUnderArm64Translation: true,
});
expect(runtimeInfo).toEqual({
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
});
});
});
+40
View File
@@ -0,0 +1,40 @@
import type { DesktopRuntimeArch, DesktopRuntimeInfo } from "@t3tools/contracts";
interface ResolveDesktopRuntimeInfoInput {
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly runningUnderArm64Translation: boolean;
}
function normalizeDesktopArch(arch: string): DesktopRuntimeArch {
if (arch === "arm64") return "arm64";
if (arch === "x64") return "x64";
return "other";
}
export function resolveDesktopRuntimeInfo(
input: ResolveDesktopRuntimeInfoInput,
): DesktopRuntimeInfo {
const appArch = normalizeDesktopArch(input.processArch);
if (input.platform !== "darwin") {
return {
hostArch: appArch,
appArch,
runningUnderArm64Translation: false,
};
}
const hostArch =
appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
return {
hostArch,
appArch,
runningUnderArm64Translation: input.runningUnderArm64Translation,
};
}
export function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
}
+12 -6
View File
@@ -13,11 +13,17 @@ import {
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
const runtimeInfo = {
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
} as const;
describe("updateMachine", () => {
it("clears transient errors when a check starts", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "error",
message: "network",
@@ -36,7 +42,7 @@ describe("updateMachine", () => {
it("records a check failure without exposing an action", () => {
const state = reduceDesktopUpdateStateOnCheckFailure(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "checking",
},
@@ -52,7 +58,7 @@ describe("updateMachine", () => {
it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -70,7 +76,7 @@ describe("updateMachine", () => {
it("transitions to downloaded and then preserves install retry state", () => {
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -89,7 +95,7 @@ describe("updateMachine", () => {
it("clears stale download state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "error",
availableVersion: "1.1.0",
@@ -111,7 +117,7 @@ describe("updateMachine", () => {
it("tracks available, download start, and progress cleanly", () => {
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "checking",
},
+8 -3
View File
@@ -1,12 +1,18 @@
import type { DesktopUpdateState } from "@t3tools/contracts";
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
export function createInitialDesktopUpdateState(currentVersion: string): DesktopUpdateState {
export function createInitialDesktopUpdateState(
currentVersion: string,
runtimeInfo: DesktopRuntimeInfo,
): DesktopUpdateState {
return {
enabled: false,
status: "disabled",
currentVersion,
hostArch: runtimeInfo.hostArch,
appArch: runtimeInfo.appArch,
runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
@@ -152,4 +158,3 @@ export function reduceDesktopUpdateStateOnInstallFailure(
canRetry: true,
};
}
+3
View File
@@ -12,6 +12,9 @@ const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
+1 -3
View File
@@ -77,12 +77,10 @@
const ua = navigator.userAgent;
if (/Win/i.test(ua)) return { os: "win", label: "Download for Windows" };
if (/Mac/i.test(ua)) {
const isArm =
/arm|aarch/i.test(navigator.platform ?? "") || ua.includes("ARM");
return {
os: "mac",
label: `Download for macOS`,
arch: isArm ? "arm64" : "x64",
arch: "arm64",
};
}
if (/Linux/i.test(ua)) return { os: "linux", label: "Download for Linux" };
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.5",
"version": "0.0.9",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
+2
View File
@@ -132,6 +132,7 @@ const buildCmd = Command.make(
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun tsdown`,
);
@@ -226,6 +227,7 @@ const publishCmd = Command.make(
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
}),
);
@@ -5,7 +5,6 @@ import {
type OrchestrationEvent,
type ProviderModelOptions,
type ProviderKind,
type ProviderServiceTier,
type ProviderStartOptions,
type OrchestrationSession,
ThreadId,
@@ -206,7 +205,6 @@ const make = Effect.gen(function* () {
readonly provider?: ProviderKind;
readonly model?: string;
readonly modelOptions?: ProviderModelOptions;
readonly serviceTier?: ProviderServiceTier | null;
readonly providerOptions?: ProviderStartOptions;
},
) {
@@ -242,7 +240,6 @@ const make = Effect.gen(function* () {
: {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(desiredModel ? { model: desiredModel } : {}),
...(options?.serviceTier !== undefined ? { serviceTier: options.serviceTier } : {}),
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
...(options?.providerOptions !== undefined ? { providerOptions: options.providerOptions } : {}),
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
@@ -328,7 +325,6 @@ const make = Effect.gen(function* () {
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly provider?: ProviderKind;
readonly model?: string;
readonly serviceTier?: ProviderServiceTier | null;
readonly modelOptions?: ProviderModelOptions;
readonly providerOptions?: ProviderStartOptions;
readonly interactionMode?: "default" | "plan";
@@ -344,7 +340,6 @@ const make = Effect.gen(function* () {
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
@@ -366,7 +361,6 @@ const make = Effect.gen(function* () {
...(normalizedInput ? { input: normalizedInput } : {}),
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
});
@@ -481,9 +475,6 @@ const make = Effect.gen(function* () {
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.serviceTier !== undefined
? { serviceTier: event.payload.serviceTier }
: {}),
...(event.payload.modelOptions !== undefined
? { modelOptions: event.payload.modelOptions }
: {}),
-1
View File
@@ -301,7 +301,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
messageId: command.message.messageId,
...(command.provider !== undefined ? { provider: command.provider } : {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.serviceTier !== undefined ? { serviceTier: command.serviceTier } : {}),
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
...(command.providerOptions !== undefined ? { providerOptions: command.providerOptions } : {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
@@ -1354,7 +1354,6 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
threadId: input.threadId,
...(input.input !== undefined ? { input: input.input } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions?.codex?.reasoningEffort !== undefined
? { effort: input.modelOptions.codex.reasoningEffort }
: {}),
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.5",
"version": "0.0.9",
"private": true,
"type": "module",
"scripts": {
-21
View File
@@ -4,8 +4,6 @@ import {
getAppModelOptions,
getSlashModelOptions,
normalizeCustomModelSlugs,
resolveAppServiceTier,
shouldShowFastTierIcon,
resolveAppModelSelection,
} from "./appSettings";
@@ -84,22 +82,3 @@ describe("getSlashModelOptions", () => {
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
});
});
describe("resolveAppServiceTier", () => {
it("maps automatic to no override", () => {
expect(resolveAppServiceTier("auto")).toBeNull();
});
it("preserves explicit service tier overrides", () => {
expect(resolveAppServiceTier("fast")).toBe("fast");
expect(resolveAppServiceTier("flex")).toBe("flex");
});
});
describe("shouldShowFastTierIcon", () => {
it("shows the fast-tier icon only for gpt-5.4 on fast tier", () => {
expect(shouldShowFastTierIcon("gpt-5.4", "fast")).toBe(true);
expect(shouldShowFastTierIcon("gpt-5.4", "auto")).toBe(false);
expect(shouldShowFastTierIcon("gpt-5.3-codex", "fast")).toBe(false);
});
});
+1 -38
View File
@@ -1,31 +1,11 @@
import { useCallback, useSyncExternalStore } from "react";
import { Option, Schema } from "effect";
import { type ProviderKind, type ProviderServiceTier } from "@t3tools/contracts";
import { type ProviderKind } from "@t3tools/contracts";
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
export const APP_SERVICE_TIER_OPTIONS = [
{
value: "auto",
label: "Automatic",
description: "Use Codex defaults without forcing a service tier.",
},
{
value: "fast",
label: "Fast",
description: "Request the fast service tier when the model supports it.",
},
{
value: "flex",
label: "Flex",
description: "Request the flex service tier when the model supports it.",
},
] as const;
export type AppServiceTier = (typeof APP_SERVICE_TIER_OPTIONS)[number]["value"];
const AppServiceTierSchema = Schema.Literals(["auto", "fast", "flex"]);
const MODELS_WITH_FAST_SUPPORT = new Set(["gpt-5.4"]);
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
};
@@ -41,7 +21,6 @@ const AppSettingsSchema = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.pipe(
Schema.withConstructorDefault(() => Option.some(false)),
),
codexServiceTier: AppServiceTierSchema.pipe(Schema.withConstructorDefault(() => Option.some("auto"))),
customCodexModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
@@ -53,22 +32,6 @@ export interface AppModelOption {
isCustom: boolean;
}
export function resolveAppServiceTier(serviceTier: AppServiceTier): ProviderServiceTier | null {
return serviceTier === "auto" ? null : serviceTier;
}
export function shouldShowFastTierIcon(
model: string | null | undefined,
serviceTier: AppServiceTier,
): boolean {
const normalizedModel = normalizeModelSlug(model);
return (
resolveAppServiceTier(serviceTier) === "fast" &&
normalizedModel !== null &&
MODELS_WITH_FAST_SUPPORT.has(normalizedModel)
);
}
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
let listeners: Array<() => void> = [];
+270 -112
View File
@@ -92,6 +92,8 @@ import {
buildPlanImplementationThreadTitle,
buildPlanImplementationPrompt,
buildProposedPlanMarkdownFilename,
downloadPlanAsTextFile,
normalizePlanMarkdownForExport,
proposedPlanTitle,
resolvePlanFollowUpSubmission,
} from "../proposedPlan";
@@ -122,8 +124,9 @@ import {
shortcutLabelForCommand,
} from "../keybindings";
import ChatMarkdown from "./ChatMarkdown";
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { Alert, AlertDescription, AlertTitle } from "./ui/alert";
import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
import {
BotIcon,
ChevronDownIcon,
@@ -135,13 +138,13 @@ import {
DiffIcon,
EllipsisIcon,
FolderClosedIcon,
ListTodoIcon,
LockIcon,
LockOpenIcon,
Undo2Icon,
XIcon,
CopyIcon,
CheckIcon,
ZapIcon,
} from "lucide-react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
@@ -201,9 +204,6 @@ import { readNativeApi } from "~/nativeApi";
import {
getAppModelOptions,
resolveAppModelSelection,
resolveAppServiceTier,
shouldShowFastTierIcon,
type AppServiceTier,
useAppSettings,
} from "../appSettings";
import {
@@ -291,21 +291,7 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
return "text-muted-foreground/40";
}
function normalizePlanMarkdownForExport(planMarkdown: string): string {
return `${planMarkdown.trimEnd()}\n`;
}
function downloadTextFile(filename: string, contents: string): void {
const blob = new Blob([contents], { type: "text/markdown;charset=utf-8" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = filename;
anchor.click();
window.setTimeout(() => {
URL.revokeObjectURL(url);
}, 0);
}
interface ExpandedImageItem {
src: string;
@@ -420,7 +406,6 @@ type ComposerCommandItem =
model: ModelSlug;
label: string;
description: string;
showFastBadge: boolean;
};
type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
@@ -531,9 +516,6 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
</Badge>
) : null}
<span className="flex min-w-0 items-center gap-1.5 truncate">
{props.item.type === "model" && props.item.showFastBadge ? (
<ZapIcon className="size-3.5 shrink-0 text-amber-500" />
) : null}
<span className="truncate">{props.item.label}</span>
</span>
<span className="truncate text-muted-foreground/70 text-xs">{props.item.description}</span>
@@ -656,6 +638,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
useState<Record<string, number>>({});
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
const [planSidebarOpen, setPlanSidebarOpen] = useState(false);
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
// When set, the thread-change reset effect will open the sidebar instead of closing it.
// Used by "Implement in new thread" to carry the sidebar-open intent across navigation.
const planSidebarOpenOnNextThreadRef = useRef(false);
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
@@ -757,11 +745,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
composerDraft.interactionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE;
const isServerThread = serverThread !== undefined;
const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
const diffSearch = useMemo(
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
[rawSearch],
);
const diffOpen = diffSearch.diff === "1";
const diffOpen = rawSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const activeLatestTurn = activeThread?.latestTurn ?? null;
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
@@ -793,8 +777,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeThread.messages.length > 0 ||
activeThread.session !== null),
);
const selectedServiceTierSetting = settings.codexServiceTier;
const selectedServiceTier = resolveAppServiceTier(selectedServiceTierSetting);
const lockedProvider: ProviderKind | null = hasThreadStarted
? (sessionProvider ?? selectedProviderByThreadId ?? null)
: null;
@@ -1262,10 +1244,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
model: slug,
label: name,
description: `${providerLabel} · ${slug}`,
showFastBadge:
provider === "codex" && shouldShowFastTierIcon(slug, selectedServiceTierSetting),
}));
}, [composerTrigger, searchableModelOptions, selectedServiceTierSetting, workspaceEntries]);
}, [composerTrigger, searchableModelOptions, workspaceEntries]);
const composerMenuOpen = Boolean(composerTrigger);
const activeComposerMenuItem = useMemo(
() =>
@@ -1621,6 +1601,36 @@ export default function ChatView({ threadId }: ChatViewProps) {
},
[activeProject, persistProjectScripts],
);
const deleteProjectScript = useCallback(
async (scriptId: string) => {
if (!activeProject) return;
const nextScripts = activeProject.scripts.filter((script) => script.id !== scriptId);
const deletedName = activeProject.scripts.find((s) => s.id === scriptId)?.name;
try {
await persistProjectScripts({
projectId: activeProject.id,
projectCwd: activeProject.cwd,
previousScripts: activeProject.scripts,
nextScripts,
keybinding: null,
keybindingCommand: commandForProjectScript(scriptId),
});
toastManager.add({
type: "success",
title: `Deleted action "${deletedName ?? "Unknown"}"`,
});
} catch (error) {
toastManager.add({
type: "error",
title: "Could not delete action",
description: error instanceof Error ? error.message : "An unexpected error occurred.",
});
}
},
[activeProject, persistProjectScripts],
);
const handleRuntimeModeChange = useCallback(
(mode: RuntimeMode) => {
@@ -1763,6 +1773,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
"button, summary, [role='button'], [data-scroll-anchor-target]",
);
if (!trigger || !scrollContainer.contains(trigger)) return;
if (trigger.closest("[data-scroll-anchor-ignore]")) return;
pendingInteractionAnchorRef.current = {
element: trigger,
@@ -1911,8 +1922,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => {
setExpandedWorkGroups({});
if (planSidebarOpenOnNextThreadRef.current) {
planSidebarOpenOnNextThreadRef.current = false;
setPlanSidebarOpen(true);
} else {
setPlanSidebarOpen(false);
}
planSidebarDismissedForTurnRef.current = null;
}, [activeThread?.id]);
useEffect(() => {
if (!composerMenuOpen) {
setComposerHighlightedItemId(null);
@@ -2633,7 +2653,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
attachments: turnAttachments,
},
model: selectedModel || undefined,
serviceTier: selectedServiceTier,
...(selectedModelOptionsForDispatch
? { modelOptions: selectedModelOptionsForDispatch }
: {}),
@@ -2925,6 +2944,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
interactionMode: nextInteractionMode,
createdAt: messageCreatedAt,
});
// Optimistically open the plan sidebar when implementing (not refining).
// "default" mode here means the agent is executing the plan, which produces
// step-tracking activities that the sidebar will display.
if (nextInteractionMode === "default") {
planSidebarDismissedForTurnRef.current = null;
setPlanSidebarOpen(true);
}
sendInFlightRef.current = false;
} catch (err) {
setOptimisticUserMessages((existing) =>
@@ -3033,6 +3059,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
.then(() => api.orchestration.getSnapshot())
.then((snapshot) => {
syncServerReadModel(snapshot);
// Signal that the plan sidebar should open on the new thread.
planSidebarOpenOnNextThreadRef.current = true;
return navigate({
to: "/$threadId",
params: { threadId: nextThreadId },
@@ -3428,14 +3456,21 @@ export default function ChatView({ threadId }: ChatViewProps) {
}}
onAddProjectScript={saveProjectScript}
onUpdateProjectScript={updateProjectScript}
onDeleteProjectScript={deleteProjectScript}
onToggleDiff={onToggleDiff}
/>
</header>
{/* Error banner */}
<ProviderHealthBanner status={activeProviderStatus} />
<ThreadErrorBanner error={activeThread.error} />
<PlanModePanel activePlan={activePlan} />
<ThreadErrorBanner
error={activeThread.error}
onDismiss={() => setThreadError(activeThread.id, null)}
/>
{/* Main content area with optional plan sidebar */}
<div className="flex min-h-0 flex-1">
{/* Chat column */}
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
{/* Messages */}
<div
@@ -3509,6 +3544,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
answers={activePendingDraftAnswers}
questionIndex={activePendingQuestionIndex}
onSelectOption={onSelectActivePendingUserInputOption}
onAdvance={onAdvanceActivePendingUserInput}
/>
</div>
) : showPlanFollowUpPrompt && activeProposedPlan ? (
@@ -3651,7 +3687,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
model={selectedModelForPickerWithCustomFallback}
lockedProvider={lockedProvider}
modelOptionsByProvider={modelOptionsByProvider}
serviceTierSetting={selectedServiceTierSetting}
onProviderModelChange={onProviderModelSelect}
/>
@@ -3715,6 +3750,43 @@ export default function ChatView({ threadId }: ChatViewProps) {
{runtimeMode === "full-access" ? "Full access" : "Supervised"}
</span>
</Button>
{/* Plan sidebar toggle */}
{(activePlan || activeProposedPlan || planSidebarOpen) ? (
<>
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
<Button
variant="ghost"
className={cn(
"shrink-0 whitespace-nowrap px-2 sm:px-3",
planSidebarOpen
? "text-blue-400 hover:text-blue-300"
: "text-muted-foreground/70 hover:text-foreground/80",
)}
size="sm"
type="button"
onClick={() => {
setPlanSidebarOpen((open) => {
if (open) {
// Closing: track dismissal for current turn
const turnKey = activePlan?.turnId ?? activeProposedPlan?.turnId ?? null;
if (turnKey) {
planSidebarDismissedForTurnRef.current = turnKey;
}
} else {
// Re-opening: clear dismissal tracking
planSidebarDismissedForTurnRef.current = null;
}
return !open;
});
}}
title={planSidebarOpen ? "Hide plan sidebar" : "Show plan sidebar"}
>
<ListTodoIcon />
<span className="sr-only sm:not-sr-only">Plan</span>
</Button>
</>
) : null}
</div>
{/* Right side: send / stop button */}
@@ -3881,6 +3953,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
</form>
</div>
</div>{/* end chat column */}
{/* Plan sidebar */}
{planSidebarOpen ? (
<PlanSidebar
activePlan={activePlan}
activeProposedPlan={activeProposedPlan}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeProject?.cwd ?? undefined}
onClose={() => {
setPlanSidebarOpen(false);
// Track that the user explicitly dismissed for this turn so auto-open won't fight them.
const turnKey = activePlan?.turnId ?? activeProposedPlan?.turnId ?? null;
if (turnKey) {
planSidebarDismissedForTurnRef.current = turnKey;
}
}}
/>
) : null}
</div>{/* end horizontal flex container */}
{isGitRepo && (
<BranchToolbar
threadId={activeThread.id}
@@ -4005,6 +4098,7 @@ interface ChatHeaderProps {
onRunProjectScript: (script: ProjectScript) => void;
onAddProjectScript: (input: NewProjectScriptInput) => Promise<void>;
onUpdateProjectScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void>;
onDeleteProjectScript: (scriptId: string) => Promise<void>;
onToggleDiff: () => void;
}
@@ -4024,6 +4118,7 @@ const ChatHeader = memo(function ChatHeader({
onRunProjectScript,
onAddProjectScript,
onUpdateProjectScript,
onDeleteProjectScript,
onToggleDiff,
}: ChatHeaderProps) {
return (
@@ -4056,6 +4151,7 @@ const ChatHeader = memo(function ChatHeader({
onRunScript={onRunProjectScript}
onAddScript={onAddProjectScript}
onUpdateScript={onUpdateProjectScript}
onDeleteScript={onDeleteProjectScript}
/>
)}
{activeProjectName && (
@@ -4095,7 +4191,13 @@ const ChatHeader = memo(function ChatHeader({
);
});
const ThreadErrorBanner = memo(function ThreadErrorBanner({ error }: { error: string | null }) {
const ThreadErrorBanner = memo(function ThreadErrorBanner({
error,
onDismiss,
}: {
error: string | null;
onDismiss?: () => void;
}) {
if (!error) return null;
return (
<div className="pt-3 mx-auto max-w-3xl">
@@ -4104,6 +4206,18 @@ const ThreadErrorBanner = memo(function ThreadErrorBanner({ error }: { error: st
<AlertDescription className="line-clamp-3" title={error}>
{error}
</AlertDescription>
{onDismiss && (
<AlertAction>
<button
type="button"
aria-label="Dismiss error"
className="inline-flex size-6 items-center justify-center rounded-md text-destructive/60 transition-colors hover:text-destructive"
onClick={onDismiss}
>
<XIcon className="size-3.5" />
</button>
</AlertAction>
)}
</Alert>
</div>
);
@@ -4219,61 +4333,13 @@ const ComposerPendingApprovalActions = memo(function ComposerPendingApprovalActi
);
});
interface PlanModePanelProps {
activePlan: ReturnType<typeof deriveActivePlanState>;
}
const PlanModePanel = memo(function PlanModePanel({ activePlan }: PlanModePanelProps) {
if (!activePlan) return null;
return (
<div className="pt-3 mx-auto max-w-3xl">
<div className="rounded-xl border border-border/70 bg-muted/30 p-4">
<div className="flex items-center gap-2">
<Badge variant="secondary">Plan</Badge>
<span className="text-xs text-muted-foreground">
Updated {formatTimestamp(activePlan.createdAt)}
</span>
</div>
{activePlan.explanation ? (
<p className="mt-2 text-sm text-muted-foreground">{activePlan.explanation}</p>
) : null}
<div className="mt-3 space-y-2">
{activePlan.steps.map((step) => (
<div
key={`${step.status}:${step.step}`}
className="flex items-start gap-3 rounded-lg border border-border/60 bg-background/80 px-3 py-2"
>
<Badge
variant={
step.status === "completed"
? "default"
: step.status === "inProgress"
? "secondary"
: "outline"
}
>
{step.status === "inProgress"
? "In progress"
: step.status === "completed"
? "Done"
: "Pending"}
</Badge>
<div className="min-w-0 flex-1 text-sm">{step.step}</div>
</div>
))}
</div>
</div>
</div>
);
});
interface PendingUserInputPanelProps {
pendingUserInputs: PendingUserInput[];
respondingRequestIds: ApprovalRequestId[];
answers: Record<string, PendingUserInputDraftAnswer>;
questionIndex: number;
onSelectOption: (questionId: string, optionLabel: string) => void;
onAdvance: () => void;
}
const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
@@ -4282,6 +4348,7 @@ const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPane
answers,
questionIndex,
onSelectOption,
onAdvance,
}: PendingUserInputPanelProps) {
if (pendingUserInputs.length === 0) return null;
const activePrompt = pendingUserInputs[0];
@@ -4295,6 +4362,7 @@ const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPane
answers={answers}
questionIndex={questionIndex}
onSelectOption={onSelectOption}
onAdvance={onAdvance}
/>
);
});
@@ -4305,42 +4373,135 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
answers,
questionIndex,
onSelectOption,
onAdvance,
}: {
prompt: PendingUserInput;
isResponding: boolean;
answers: Record<string, PendingUserInputDraftAnswer>;
questionIndex: number;
onSelectOption: (questionId: string, optionLabel: string) => void;
onAdvance: () => void;
}) {
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
const activeQuestion = progress.activeQuestion;
const autoAdvanceTimerRef = useRef<number | null>(null);
// Clear auto-advance timer on unmount
useEffect(() => {
return () => {
if (autoAdvanceTimerRef.current !== null) {
window.clearTimeout(autoAdvanceTimerRef.current);
}
};
}, []);
const selectOptionAndAutoAdvance = useCallback(
(questionId: string, optionLabel: string) => {
onSelectOption(questionId, optionLabel);
if (autoAdvanceTimerRef.current !== null) {
window.clearTimeout(autoAdvanceTimerRef.current);
}
autoAdvanceTimerRef.current = window.setTimeout(() => {
autoAdvanceTimerRef.current = null;
onAdvance();
}, 200);
},
[onSelectOption, onAdvance],
);
// Keyboard shortcut: number keys 1-9 select corresponding option and auto-advance.
// Works even when the Lexical composer (contenteditable) has focus — the composer
// doubles as a custom-answer field during user input, and when it's empty the digit
// keys should pick options instead of typing into the editor.
useEffect(() => {
if (!activeQuestion || isResponding) return;
const handler = (event: globalThis.KeyboardEvent) => {
if (event.metaKey || event.ctrlKey || event.altKey) return;
const target = event.target;
if (
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement
) {
return;
}
// If the user has started typing a custom answer in the contenteditable
// composer, let digit keys pass through so they can type numbers.
if (target instanceof HTMLElement && target.isContentEditable) {
const hasCustomText = progress.customAnswer.length > 0;
if (hasCustomText) return;
}
const digit = Number.parseInt(event.key, 10);
if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
const optionIndex = digit - 1;
if (optionIndex >= activeQuestion.options.length) return;
const option = activeQuestion.options[optionIndex];
if (!option) return;
event.preventDefault();
selectOptionAndAutoAdvance(activeQuestion.id, option.label);
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
}, [activeQuestion, isResponding, selectOptionAndAutoAdvance, progress.customAnswer.length]);
if (!activeQuestion) {
return null;
}
return (
<div className="px-4 py-4 sm:px-5">
<div className="flex gap-2">
<span className="uppercase text-sm tracking-[0.2em]">
{questionIndex + 1}/{prompt.questions.length} {activeQuestion.header}
</span>
<div className="text-sm font-medium">{activeQuestion.question}</div>
<div className="px-4 py-3 sm:px-5">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
{prompt.questions.length > 1 ? (
<span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-[10px] font-medium tabular-nums text-muted-foreground/60">
{questionIndex + 1}/{prompt.questions.length}
</span>
) : null}
<span className="text-[11px] font-semibold tracking-widest text-muted-foreground/50 uppercase">
{activeQuestion.header}
</span>
</div>
</div>
<div className="mt-3 flex flex-wrap gap-2">
{activeQuestion.options.map((option) => {
<p className="mt-1.5 text-sm text-foreground/90">{activeQuestion.question}</p>
<div className="mt-3 space-y-1">
{activeQuestion.options.map((option, index) => {
const isSelected = progress.selectedOptionLabel === option.label;
const shortcutKey = index < 9 ? index + 1 : null;
return (
<Button
<button
key={`${activeQuestion.id}:${option.label}`}
size="sm"
variant={isSelected ? "default" : "outline"}
type="button"
disabled={isResponding}
onClick={() => onSelectOption(activeQuestion.id, option.label)}
title={option.description}
onClick={() => selectOptionAndAutoAdvance(activeQuestion.id, option.label)}
className={cn(
"group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left transition-all duration-150",
isSelected
? "border-blue-500/40 bg-blue-500/8 text-foreground"
: "border-transparent bg-muted/20 text-foreground/80 hover:bg-muted/40 hover:border-border/40",
isResponding && "opacity-50 cursor-not-allowed",
)}
>
{option.label}
</Button>
{shortcutKey !== null ? (
<kbd
className={cn(
"flex size-5 shrink-0 items-center justify-center rounded text-[11px] font-medium tabular-nums transition-colors duration-150",
isSelected
? "bg-blue-500/20 text-blue-400"
: "bg-muted/40 text-muted-foreground/50 group-hover:bg-muted/60 group-hover:text-muted-foreground/70",
)}
>
{shortcutKey}
</kbd>
) : null}
<div className="min-w-0 flex-1">
<span className="text-sm font-medium">{option.label}</span>
{option.description && option.description !== option.label ? (
<span className="ml-2 text-xs text-muted-foreground/50">{option.description}</span>
) : null}
</div>
{isSelected ? (
<CheckIcon className="size-3.5 shrink-0 text-blue-400" />
) : null}
</button>
);
})}
</div>
@@ -4554,7 +4715,7 @@ const ProposedPlanCard = memo(function ProposedPlanCard({
const saveContents = normalizePlanMarkdownForExport(planMarkdown);
const handleDownload = () => {
downloadTextFile(downloadFilename, saveContents);
downloadPlanAsTextFile(downloadFilename, saveContents);
};
const openSaveDialog = () => {
@@ -4646,7 +4807,12 @@ const ProposedPlanCard = memo(function ProposedPlanCard({
</div>
{canCollapse ? (
<div className="mt-4 flex justify-center">
<Button size="sm" variant="outline" onClick={() => setExpanded((value) => !value)}>
<Button
size="sm"
variant="outline"
data-scroll-anchor-ignore
onClick={() => setExpanded((value) => !value)}
>
{expanded ? "Collapse plan" : "Expand plan"}
</Button>
</div>
@@ -5368,7 +5534,6 @@ const ProviderModelPicker = memo(function ProviderModelPicker(props: {
model: ModelSlug;
lockedProvider: ProviderKind | null;
modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>>;
serviceTierSetting: AppServiceTier;
disabled?: boolean;
onProviderModelChange: (provider: ProviderKind, model: ModelSlug) => void;
}) {
@@ -5401,9 +5566,6 @@ const ProviderModelPicker = memo(function ProviderModelPicker(props: {
>
<span className="flex min-w-0 items-center gap-2">
<ProviderIcon aria-hidden="true" className="size-4 shrink-0 text-muted-foreground/70" />
{props.provider === "codex" && shouldShowFastTierIcon(props.model, props.serviceTierSetting) ? (
<ZapIcon className="size-3.5 shrink-0 text-amber-500" />
) : null}
<span className="truncate">{selectedModelLabel}</span>
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
</span>
@@ -5446,10 +5608,6 @@ const ProviderModelPicker = memo(function ProviderModelPicker(props: {
value={modelOption.slug}
onClick={() => setIsMenuOpen(false)}
>
{option.value === "codex" &&
shouldShowFastTierIcon(modelOption.slug, props.serviceTierSetting) ? (
<ZapIcon className="size-3.5 shrink-0 text-amber-500" />
) : null}
{modelOption.name}
</MenuRadioItem>
))}
+267
View File
@@ -0,0 +1,267 @@
import { memo, useState, useCallback } from "react";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { ScrollArea } from "./ui/scroll-area";
import ChatMarkdown from "./ChatMarkdown";
import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
EllipsisIcon,
LoaderIcon,
PanelRightCloseIcon,
} from "lucide-react";
import { cn } from "~/lib/utils";
import { formatTimestamp } from "../session-logic";
import type { ActivePlanState } from "../session-logic";
import type { LatestProposedPlanState } from "../session-logic";
import {
proposedPlanTitle,
buildProposedPlanMarkdownFilename,
normalizePlanMarkdownForExport,
downloadPlanAsTextFile,
} from "../proposedPlan";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
import { readNativeApi } from "~/nativeApi";
import { toastManager } from "./ui/toast";
function stepStatusIcon(status: string): React.ReactNode {
if (status === "completed") {
return (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-emerald-500/15 text-emerald-500">
<CheckIcon className="size-3" />
</span>
);
}
if (status === "inProgress") {
return (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-blue-500/15 text-blue-400">
<LoaderIcon className="size-3 animate-spin" />
</span>
);
}
return (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full border border-border/60 bg-muted/30">
<span className="size-1.5 rounded-full bg-muted-foreground/30" />
</span>
);
}
interface PlanSidebarProps {
activePlan: ActivePlanState | null;
activeProposedPlan: LatestProposedPlanState | null;
markdownCwd: string | undefined;
workspaceRoot: string | undefined;
onClose: () => void;
}
const PlanSidebar = memo(function PlanSidebar({
activePlan,
activeProposedPlan,
markdownCwd,
workspaceRoot,
onClose,
}: PlanSidebarProps) {
const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false);
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
const [copied, setCopied] = useState(false);
const planMarkdown = activeProposedPlan?.planMarkdown ?? null;
const planTitle = planMarkdown ? proposedPlanTitle(planMarkdown) : null;
const handleCopyPlan = useCallback(() => {
if (!planMarkdown) return;
void navigator.clipboard.writeText(planMarkdown);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}, [planMarkdown]);
const handleDownload = useCallback(() => {
if (!planMarkdown) return;
const filename = buildProposedPlanMarkdownFilename(planMarkdown);
downloadPlanAsTextFile(filename, normalizePlanMarkdownForExport(planMarkdown));
}, [planMarkdown]);
const handleSaveToWorkspace = useCallback(() => {
const api = readNativeApi();
if (!api || !workspaceRoot || !planMarkdown) return;
const filename = buildProposedPlanMarkdownFilename(planMarkdown);
setIsSavingToWorkspace(true);
void api.projects
.writeFile({
cwd: workspaceRoot,
relativePath: filename,
contents: normalizePlanMarkdownForExport(planMarkdown),
})
.then((result) => {
toastManager.add({
type: "success",
title: "Plan saved",
description: result.relativePath,
});
})
.catch((error) => {
toastManager.add({
type: "error",
title: "Could not save plan",
description:
error instanceof Error ? error.message : "An error occurred.",
});
})
.then(
() => setIsSavingToWorkspace(false),
() => setIsSavingToWorkspace(false),
);
}, [planMarkdown, workspaceRoot]);
return (
<div className="flex h-full w-[340px] shrink-0 flex-col border-l border-border/70 bg-card/50">
{/* Header */}
<div className="flex h-12 shrink-0 items-center justify-between border-b border-border/60 px-3">
<div className="flex items-center gap-2">
<Badge
variant="secondary"
className="rounded-md bg-blue-500/10 px-1.5 py-0 text-[10px] font-semibold tracking-wide text-blue-400 uppercase"
>
Plan
</Badge>
{activePlan ? (
<span className="text-[11px] text-muted-foreground/60">
{formatTimestamp(activePlan.createdAt)}
</span>
) : null}
</div>
<div className="flex items-center gap-1">
{planMarkdown ? (
<Menu>
<MenuTrigger
render={
<Button
size="icon-xs"
variant="ghost"
className="text-muted-foreground/50 hover:text-foreground/70"
aria-label="Plan actions"
/>
}
>
<EllipsisIcon className="size-3.5" />
</MenuTrigger>
<MenuPopup align="end">
<MenuItem onClick={handleCopyPlan}>
{copied ? "Copied!" : "Copy to clipboard"}
</MenuItem>
<MenuItem onClick={handleDownload}>Download as markdown</MenuItem>
<MenuItem
onClick={handleSaveToWorkspace}
disabled={!workspaceRoot || isSavingToWorkspace}
>
Save to workspace
</MenuItem>
</MenuPopup>
</Menu>
) : null}
<Button
size="icon-xs"
variant="ghost"
onClick={onClose}
aria-label="Close plan sidebar"
className="text-muted-foreground/50 hover:text-foreground/70"
>
<PanelRightCloseIcon className="size-3.5" />
</Button>
</div>
</div>
{/* Content */}
<ScrollArea className="min-h-0 flex-1">
<div className="p-3 space-y-4">
{/* Explanation */}
{activePlan?.explanation ? (
<p className="text-[13px] leading-relaxed text-muted-foreground/80">
{activePlan.explanation}
</p>
) : null}
{/* Plan Steps */}
{activePlan && activePlan.steps.length > 0 ? (
<div className="space-y-1">
<p className="mb-2 text-[10px] font-semibold tracking-widest text-muted-foreground/40 uppercase">
Steps
</p>
{activePlan.steps.map((step) => (
<div
key={`${step.status}:${step.step}`}
className={cn(
"flex items-start gap-2.5 rounded-lg px-2.5 py-2 transition-colors duration-200",
step.status === "inProgress" && "bg-blue-500/5",
step.status === "completed" && "bg-emerald-500/5",
)}
>
<div className="mt-0.5">
{stepStatusIcon(step.status)}
</div>
<p
className={cn(
"text-[13px] leading-snug",
step.status === "completed"
? "text-muted-foreground/50 line-through decoration-muted-foreground/20"
: step.status === "inProgress"
? "text-foreground/90"
: "text-muted-foreground/70",
)}
>
{step.step}
</p>
</div>
))}
</div>
) : null}
{/* Proposed Plan Markdown */}
{planMarkdown ? (
<div className="space-y-2">
<button
type="button"
className="group flex w-full items-center gap-1.5 text-left"
onClick={() => setProposedPlanExpanded((v) => !v)}
>
{proposedPlanExpanded ? (
<ChevronDownIcon className="size-3 shrink-0 text-muted-foreground/40 transition-transform" />
) : (
<ChevronRightIcon className="size-3 shrink-0 text-muted-foreground/40 transition-transform" />
)}
<span className="text-[10px] font-semibold tracking-widest text-muted-foreground/40 uppercase group-hover:text-muted-foreground/60">
{planTitle ?? "Full Plan"}
</span>
</button>
{proposedPlanExpanded ? (
<div className="rounded-lg border border-border/50 bg-background/50 p-3">
<ChatMarkdown
text={planMarkdown}
cwd={markdownCwd}
isStreaming={false}
/>
</div>
) : null}
</div>
) : null}
{/* Empty state */}
{!activePlan && !planMarkdown ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-[13px] text-muted-foreground/40">
No active plan yet.
</p>
<p className="mt-1 text-[11px] text-muted-foreground/30">
Plans will appear here when generated.
</p>
</div>
) : null}
</div>
</ScrollArea>
</div>
);
});
export default PlanSidebar;
export type { PlanSidebarProps };
@@ -14,7 +14,7 @@ import {
SettingsIcon,
WrenchIcon,
} from "lucide-react";
import React, { type FormEvent, type KeyboardEvent, useMemo, useState } from "react";
import React, { type FormEvent, type KeyboardEvent, useCallback, useMemo, useState } from "react";
import {
keybindingValueForCommand,
@@ -27,6 +27,15 @@ import {
} from "~/projectScripts";
import { shortcutLabelForCommand } from "~/keybindings";
import { isMacPlatform } from "~/lib/utils";
import {
AlertDialog,
AlertDialogClose,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogPopup,
AlertDialogTitle,
} from "./ui/alert-dialog";
import { Button } from "./ui/button";
import {
Dialog,
@@ -84,6 +93,7 @@ interface ProjectScriptsControlProps {
onRunScript: (script: ProjectScript) => void;
onAddScript: (input: NewProjectScriptInput) => Promise<void> | void;
onUpdateScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void> | void;
onDeleteScript: (scriptId: string) => Promise<void> | void;
}
function normalizeShortcutKeyToken(key: string): string | null {
@@ -144,6 +154,7 @@ export default function ProjectScriptsControl({
onRunScript,
onAddScript,
onUpdateScript,
onDeleteScript,
}: ProjectScriptsControlProps) {
const addScriptFormId = React.useId();
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
@@ -155,6 +166,7 @@ export default function ProjectScriptsControl({
const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
const [keybinding, setKeybinding] = useState("");
const [validationError, setValidationError] = useState<string | null>(null);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const primaryScript = useMemo(() => {
if (preferredScriptId) {
@@ -247,6 +259,13 @@ export default function ProjectScriptsControl({
setDialogOpen(true);
};
const confirmDeleteScript = useCallback(() => {
if (!editingScriptId) return;
setDeleteConfirmOpen(false);
setDialogOpen(false);
void onDeleteScript(editingScriptId);
}, [editingScriptId, onDeleteScript]);
return (
<>
{primaryScript ? (
@@ -440,6 +459,16 @@ export default function ProjectScriptsControl({
</form>
</DialogPanel>
<DialogFooter>
{isEditing && (
<Button
type="button"
variant="destructive-outline"
className="mr-auto"
onClick={() => setDeleteConfirmOpen(true)}
>
Delete
</Button>
)}
<Button
type="button"
variant="outline"
@@ -455,6 +484,21 @@ export default function ProjectScriptsControl({
</DialogFooter>
</DialogPopup>
</Dialog>
<AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Delete action "{name}"?</AlertDialogTitle>
<AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button variant="destructive" onClick={confirmDeleteScript}>
Delete action
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
</>
);
}
@@ -0,0 +1,124 @@
import { describe, expect, it } from "vitest";
import { hasUnseenCompletion, resolveThreadStatusPill } from "./Sidebar.logic";
function makeLatestTurn(overrides?: {
completedAt?: string | null;
startedAt?: string | null;
}): Parameters<typeof hasUnseenCompletion>[0]["latestTurn"] {
return {
turnId: "turn-1" as never,
state: "completed",
assistantMessageId: null,
requestedAt: "2026-03-09T10:00:00.000Z",
startedAt: overrides?.startedAt ?? "2026-03-09T10:00:00.000Z",
completedAt: overrides?.completedAt ?? "2026-03-09T10:05:00.000Z",
};
}
describe("hasUnseenCompletion", () => {
it("returns true when a thread completed after its last visit", () => {
expect(
hasUnseenCompletion({
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: "2026-03-09T10:04:00.000Z",
proposedPlans: [],
session: null,
}),
).toBe(true);
});
});
describe("resolveThreadStatusPill", () => {
const baseThread = {
interactionMode: "plan" as const,
latestTurn: null,
lastVisitedAt: undefined,
proposedPlans: [],
session: {
provider: "codex" as const,
status: "running" as const,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:00:00.000Z",
orchestrationStatus: "running" as const,
},
};
it("shows pending approval before all other statuses", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: true,
hasPendingUserInput: true,
}),
).toMatchObject({ label: "Pending Approval", pulse: false });
});
it("shows awaiting input when plan mode is blocked on user answers", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: true,
}),
).toMatchObject({ label: "Awaiting Input", pulse: false });
});
it("falls back to working when the thread is actively running without blockers", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Working", pulse: true });
});
it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
latestTurn: makeLatestTurn(),
proposedPlans: [
{
id: "plan-1" as never,
turnId: "turn-1" as never,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
planMarkdown: "# Plan",
},
],
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Plan Ready", pulse: false });
});
it("shows completed when there is an unseen completion and no active blocker", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: "2026-03-09T10:04:00.000Z",
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Completed", pulse: false });
});
});
+100
View File
@@ -0,0 +1,100 @@
import type { Thread } from "../types";
import { findLatestProposedPlan, isLatestTurnSettled } from "../session-logic";
export interface ThreadStatusPill {
label:
| "Working"
| "Connecting"
| "Completed"
| "Pending Approval"
| "Awaiting Input"
| "Plan Ready";
colorClass: string;
dotClass: string;
pulse: boolean;
}
type ThreadStatusInput = Pick<
Thread,
"interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session"
>;
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
if (!thread.latestTurn?.completedAt) return false;
const completedAt = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(completedAt)) return false;
if (!thread.lastVisitedAt) return true;
const lastVisitedAt = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAt)) return true;
return completedAt > lastVisitedAt;
}
export function resolveThreadStatusPill(input: {
thread: ThreadStatusInput;
hasPendingApprovals: boolean;
hasPendingUserInput: boolean;
}): ThreadStatusPill | null {
const { hasPendingApprovals, hasPendingUserInput, thread } = input;
if (hasPendingApprovals) {
return {
label: "Pending Approval",
colorClass: "text-amber-600 dark:text-amber-300/90",
dotClass: "bg-amber-500 dark:bg-amber-300/90",
pulse: false,
};
}
if (hasPendingUserInput) {
return {
label: "Awaiting Input",
colorClass: "text-indigo-600 dark:text-indigo-300/90",
dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
pulse: false,
};
}
if (thread.session?.status === "running") {
return {
label: "Working",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (thread.session?.status === "connecting") {
return {
label: "Connecting",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
const hasPlanReadyPrompt =
!hasPendingUserInput &&
thread.interactionMode === "plan" &&
isLatestTurnSettled(thread.latestTurn, thread.session) &&
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null) !== null;
if (hasPlanReadyPrompt) {
return {
label: "Plan Ready",
colorClass: "text-violet-600 dark:text-violet-300/90",
dotClass: "bg-violet-500 dark:bg-violet-300/90",
pulse: false,
};
}
if (hasUnseenCompletion(thread)) {
return {
label: "Completed",
colorClass: "text-emerald-600 dark:text-emerald-300/90",
dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
pulse: false,
};
}
return null;
}
+204 -129
View File
@@ -1,10 +1,14 @@
import {
ArrowLeftIcon,
ChevronRightIcon,
FolderIcon,
GitPullRequestIcon,
PlusIcon,
RocketIcon,
SettingsIcon,
SquarePenIcon,
TerminalIcon,
TriangleAlertIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
@@ -17,15 +21,14 @@ import {
type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
import { useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
import { type Thread } from "../types";
import { derivePendingApprovals } from "../session-logic";
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
@@ -33,14 +36,18 @@ import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraft
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { toastManager } from "./ui/toast";
import {
getArm64IntelBuildWarningDescription,
getDesktopUpdateActionError,
getDesktopUpdateButtonTooltip,
isDesktopUpdateButtonDisabled,
resolveDesktopUpdateButtonAction,
shouldShowArm64IntelBuildWarning,
shouldHighlightDesktopUpdateError,
shouldShowDesktopUpdateButton,
shouldToastDesktopUpdateActionResult,
} from "./desktopUpdate.logic";
import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
import { Button } from "./ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import {
@@ -60,6 +67,7 @@ import {
} from "./ui/sidebar";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { isNonEmpty as isNonEmptyString } from "effect/String";
import { resolveThreadStatusPill } from "./Sidebar.logic";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
@@ -81,13 +89,6 @@ function formatRelativeTime(iso: string): string {
return `${Math.floor(hours / 24)}d ago`;
}
interface ThreadStatusPill {
label: "Working" | "Connecting" | "Completed" | "Pending Approval";
colorClass: string;
dotClass: string;
pulse: boolean;
}
interface TerminalStatusIndicator {
label: "Terminal process running";
colorClass: string;
@@ -103,57 +104,6 @@ interface PrStatusIndicator {
type ThreadPr = GitStatusResult["pr"];
function hasUnseenCompletion(thread: Thread): boolean {
if (!thread.latestTurn?.completedAt) return false;
const completedAt = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(completedAt)) return false;
if (!thread.lastVisitedAt) return true;
const lastVisitedAt = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAt)) return true;
return completedAt > lastVisitedAt;
}
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
if (hasPendingApprovals) {
return {
label: "Pending Approval",
colorClass: "text-amber-600 dark:text-amber-300/90",
dotClass: "bg-amber-500 dark:bg-amber-300/90",
pulse: false,
};
}
if (thread.session?.status === "running") {
return {
label: "Working",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (thread.session?.status === "connecting") {
return {
label: "Connecting",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (hasUnseenCompletion(thread)) {
return {
label: "Completed",
colorClass: "text-emerald-600 dark:text-emerald-300/90",
dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
pulse: false,
};
}
return null;
}
function terminalStatusFromRunningIds(
runningTerminalIds: string[],
): TerminalStatusIndicator | null {
@@ -278,6 +228,7 @@ export default function Sidebar() {
(store) => store.clearProjectDraftThreadById,
);
const navigate = useNavigate();
const isOnSettings = useLocation({ select: (loc) => loc.pathname === "/settings" });
const { settings: appSettings } = useAppSettings();
const routeThreadId = useParams({
strict: false,
@@ -293,6 +244,8 @@ export default function Sidebar() {
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const [isAddingProject, setIsAddingProject] = useState(false);
const [addProjectError, setAddProjectError] = useState<string | null>(null);
const addProjectInputRef = useRef<HTMLInputElement | null>(null);
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
@@ -301,6 +254,8 @@ export default function Sidebar() {
const renamingCommittedRef = useRef(false);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const [desktopUpdateState, setDesktopUpdateState] = useState<DesktopUpdateState | null>(null);
const shouldBrowseForProjectImmediately = isElectron;
const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately;
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<ThreadId, boolean>();
for (const thread of threads) {
@@ -308,6 +263,13 @@ export default function Sidebar() {
}
return map;
}, [threads]);
const pendingUserInputByThreadId = useMemo(() => {
const map = new Map<ThreadId, boolean>();
for (const thread of threads) {
map.set(thread.id, derivePendingUserInputs(thread.activities).length > 0);
}
return map;
}, [threads]);
const projectCwdById = useMemo(
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
[projects],
@@ -486,6 +448,7 @@ export default function Sidebar() {
const finishAddingProject = () => {
setIsAddingProject(false);
setNewCwd("");
setAddProjectError(null);
setAddingProject(false);
};
@@ -511,18 +474,29 @@ export default function Sidebar() {
});
await handleNewThread(projectId).catch(() => undefined);
} catch (error) {
const description =
error instanceof Error ? error.message : "An error occurred while adding the project.";
setIsAddingProject(false);
toastManager.add({
type: "error",
title: "Unable to add project",
description:
error instanceof Error ? error.message : "An error occurred while adding the project.",
});
if (shouldBrowseForProjectImmediately) {
toastManager.add({
type: "error",
title: "Failed to add project",
description,
});
} else {
setAddProjectError(description);
}
return;
}
finishAddingProject();
},
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
[
focusMostRecentThreadForProject,
handleNewThread,
isAddingProject,
projects,
shouldBrowseForProjectImmediately,
],
);
const handleAddProject = () => {
@@ -541,10 +515,21 @@ export default function Sidebar() {
}
if (pickedPath) {
await addProjectFromPath(pickedPath);
} else if (!shouldBrowseForProjectImmediately) {
addProjectInputRef.current?.focus();
}
setIsPickingFolder(false);
};
const handleStartAddProject = () => {
setAddProjectError(null);
if (shouldBrowseForProjectImmediately) {
void handlePickFolder();
return;
}
setAddingProject((prev) => !prev);
};
const cancelRename = useCallback(() => {
setRenamingThreadId(null);
renamingInputRef.current = null;
@@ -881,6 +866,12 @@ export default function Sidebar() {
const desktopUpdateButtonAction = desktopUpdateState
? resolveDesktopUpdateButtonAction(desktopUpdateState)
: "none";
const showArm64IntelBuildWarning =
isElectron && shouldShowArm64IntelBuildWarning(desktopUpdateState);
const arm64IntelBuildWarningDescription =
desktopUpdateState && showArm64IntelBuildWarning
? getArm64IntelBuildWarningDescription(desktopUpdateState)
: null;
const desktopUpdateButtonInteractivityClasses = desktopUpdateButtonDisabled
? "cursor-not-allowed opacity-60"
: "hover:bg-accent hover:text-foreground";
@@ -978,7 +969,7 @@ export default function Sidebar() {
const wordmark = (
<div className="flex items-center gap-2">
<SidebarTrigger className="shrink-0 md:hidden" />
<div className="flex min-w-0 flex-1 items-center gap-1 mt-2 ml-1">
<div className="flex min-w-0 flex-1 items-center gap-1 mt-1.5 ml-1">
<T3Wordmark />
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
Code
@@ -994,7 +985,7 @@ export default function Sidebar() {
<>
{isElectron ? (
<>
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[90px]">
{wordmark}
{showDesktopUpdateButton && (
<Tooltip>
@@ -1005,7 +996,7 @@ export default function Sidebar() {
aria-label={desktopUpdateTooltip}
aria-disabled={desktopUpdateButtonDisabled || undefined}
disabled={desktopUpdateButtonDisabled}
className={`inline-flex size-7 ml-auto mt-2 items-center justify-center rounded-md text-muted-foreground transition-colors ${desktopUpdateButtonInteractivityClasses} ${desktopUpdateButtonClasses}`}
className={`inline-flex size-7 ml-auto mt-1.5 items-center justify-center rounded-md text-muted-foreground transition-colors ${desktopUpdateButtonInteractivityClasses} ${desktopUpdateButtonClasses}`}
onClick={handleDesktopUpdateButtonClick}
>
<RocketIcon className="size-3.5" />
@@ -1024,7 +1015,121 @@ export default function Sidebar() {
)}
<SidebarContent className="gap-0">
{showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? (
<SidebarGroup className="px-2 pt-2 pb-0">
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8">
<TriangleAlertIcon />
<AlertTitle>Intel build on Apple Silicon</AlertTitle>
<AlertDescription>{arm64IntelBuildWarningDescription}</AlertDescription>
{desktopUpdateButtonAction !== "none" ? (
<AlertAction>
<Button
size="xs"
variant="outline"
disabled={desktopUpdateButtonDisabled}
onClick={handleDesktopUpdateButtonClick}
>
{desktopUpdateButtonAction === "download"
? "Download ARM build"
: "Install ARM build"}
</Button>
</AlertAction>
) : null}
</Alert>
</SidebarGroup>
) : null}
<SidebarGroup className="px-2 py-2">
<div className="mb-1 flex items-center justify-between px-2">
<span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
Projects
</span>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label="Add project"
aria-pressed={shouldShowProjectPathEntry}
className="inline-flex size-5 items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
onClick={handleStartAddProject}
/>
}
>
<PlusIcon
className={`size-3.5 transition-transform duration-150 ${
shouldShowProjectPathEntry ? "rotate-45" : "rotate-0"
}`}
/>
</TooltipTrigger>
<TooltipPopup side="right">Add project</TooltipPopup>
</Tooltip>
</div>
{shouldShowProjectPathEntry && (
<div className="mb-2 px-1">
{isElectron && (
<button
type="button"
className="mb-1.5 flex w-full items-center justify-center gap-2 rounded-md border border-border bg-secondary py-1.5 text-xs text-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => void handlePickFolder()}
disabled={isPickingFolder || isAddingProject}
>
<FolderIcon className="size-3.5" />
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
</button>
)}
<div className="flex gap-1.5">
<input
ref={addProjectInputRef}
className={`min-w-0 flex-1 rounded-md border bg-secondary px-2 py-1 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:outline-none ${
addProjectError
? "border-red-500/70 focus:border-red-500"
: "border-border focus:border-ring"
}`}
placeholder="/path/to/project"
value={newCwd}
onChange={(event) => {
setNewCwd(event.target.value);
setAddProjectError(null);
}}
onKeyDown={(event) => {
if (event.key === "Enter") handleAddProject();
if (event.key === "Escape") {
setAddingProject(false);
setAddProjectError(null);
}
}}
autoFocus
/>
<button
type="button"
className="shrink-0 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90 disabled:opacity-60"
onClick={handleAddProject}
disabled={isAddingProject}
>
{isAddingProject ? "Adding..." : "Add"}
</button>
</div>
{addProjectError && (
<p className="mt-1 px-0.5 text-[11px] leading-tight text-red-400">
{addProjectError}
</p>
)}
<div className="mt-1.5 px-0.5">
<button
type="button"
className="text-[11px] text-muted-foreground/50 transition-colors hover:text-muted-foreground"
onClick={() => {
setAddingProject(false);
setAddProjectError(null);
}}
>
Cancel
</button>
</div>
</div>
)}
<SidebarMenu>
{projects.map((project) => {
const projectThreads = threads
@@ -1112,10 +1217,11 @@ export default function Sidebar() {
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
{visibleThreads.map((thread) => {
const isActive = routeThreadId === thread.id;
const threadStatus = threadStatusPill(
const threadStatus = resolveThreadStatusPill({
thread,
pendingApprovalByThreadId.get(thread.id) === true,
);
hasPendingApprovals: pendingApprovalByThreadId.get(thread.id) === true,
hasPendingUserInput: pendingUserInputByThreadId.get(thread.id) === true,
});
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusFromRunningIds(
selectThreadTerminalState(terminalStateByThreadId, thread.id)
@@ -1286,70 +1392,39 @@ export default function Sidebar() {
})}
</SidebarMenu>
{projects.length === 0 && !addingProject && (
{projects.length === 0 && !shouldShowProjectPathEntry && (
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
No projects yet.
<br />
Add one to get started.
No projects yet
</div>
)}
</SidebarGroup>
</SidebarContent>
<SidebarSeparator />
<SidebarFooter className="gap-0 p-3">
{addingProject ? (
<>
<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={(event) => setNewCwd(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") handleAddProject();
if (event.key === "Escape") setAddingProject(false);
}}
/>
{isElectron && (
<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 || isAddingProject}
<SidebarFooter className="p-2">
<SidebarMenu>
<SidebarMenuItem>
{isOnSettings ? (
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
onClick={() => window.history.back()}
>
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
</button>
<ArrowLeftIcon className="size-3.5" />
<span className="text-xs">Back</span>
</SidebarMenuButton>
) : (
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
onClick={() => void navigate({ to: "/settings" })}
>
<SettingsIcon className="size-3.5" />
<span className="text-xs">Settings</span>
</SidebarMenuButton>
)}
<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}
disabled={isAddingProject}
>
{isAddingProject ? "Adding..." : "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>
</>
) : (
<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>
)}
</SidebarMenuItem>
</SidebarMenu>
</SidebarFooter>
</>
);
@@ -2,11 +2,13 @@ import { describe, expect, it } from "vitest";
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
import {
getArm64IntelBuildWarningDescription,
getDesktopUpdateActionError,
getDesktopUpdateButtonTooltip,
isDesktopUpdateButtonDisabled,
resolveDesktopUpdateButtonAction,
shouldHighlightDesktopUpdateError,
shouldShowArm64IntelBuildWarning,
shouldShowDesktopUpdateButton,
shouldToastDesktopUpdateActionResult,
} from "./desktopUpdate.logic";
@@ -15,6 +17,9 @@ const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
@@ -171,4 +176,30 @@ describe("desktop update UI helpers", () => {
}),
).toBe(false);
});
it("shows an Apple Silicon warning for Intel builds under Rosetta", () => {
const state: DesktopUpdateState = {
...baseState,
hostArch: "arm64",
appArch: "x64",
runningUnderArm64Translation: true,
};
expect(shouldShowArm64IntelBuildWarning(state)).toBe(true);
expect(getArm64IntelBuildWarningDescription(state)).toContain("Apple Silicon");
expect(getArm64IntelBuildWarningDescription(state)).toContain("Intel build");
});
it("changes the warning copy when a native build update is ready to download", () => {
const state: DesktopUpdateState = {
...baseState,
hostArch: "arm64",
appArch: "x64",
runningUnderArm64Translation: true,
status: "available",
availableVersion: "1.1.0",
};
expect(getArm64IntelBuildWarningDescription(state)).toContain("Download the available update");
});
});
@@ -32,10 +32,29 @@ export function shouldShowDesktopUpdateButton(state: DesktopUpdateState | null):
return resolveDesktopUpdateButtonAction(state) !== "none";
}
export function shouldShowArm64IntelBuildWarning(state: DesktopUpdateState | null): boolean {
return state?.hostArch === "arm64" && state.appArch === "x64";
}
export function isDesktopUpdateButtonDisabled(state: DesktopUpdateState | null): boolean {
return state?.status === "downloading";
}
export function getArm64IntelBuildWarningDescription(state: DesktopUpdateState): string {
if (!shouldShowArm64IntelBuildWarning(state)) {
return "This install is using the correct architecture.";
}
const action = resolveDesktopUpdateButtonAction(state);
if (action === "download") {
return "This Mac has Apple Silicon, but T3 Code is still running the Intel build under Rosetta. Download the available update to switch to the native Apple Silicon build.";
}
if (action === "install") {
return "This Mac has Apple Silicon, but T3 Code is still running the Intel build under Rosetta. Restart to install the downloaded Apple Silicon build.";
}
return "This Mac has Apple Silicon, but T3 Code is still running the Intel build under Rosetta. The next app update will replace it with the native Apple Silicon build.";
}
export function getDesktopUpdateButtonTooltip(state: DesktopUpdateState): string {
if (state.status === "available") {
return `Update ${state.availableVersion ?? "available"} ready to download`;
+2 -1
View File
@@ -566,7 +566,8 @@ function SidebarRail({
<button
aria-label={railLabel}
className={cn(
"-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex",
/* disable pointer events only when offcanvas sidebar is collapsed, that's when the rail sits over the native scrollbar on windows and linux. icon mode stays fully clickable. */
"-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex [[data-collapsible=offcanvas][data-state=collapsed]_&]:pointer-events-none",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
+40 -1
View File
@@ -1,5 +1,5 @@
import { assert, describe, it } from "vitest";
import { shouldHideCollapsedToastContent } from "./toast.logic";
import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
describe("shouldHideCollapsedToastContent", () => {
it("keeps a single visible toast readable", () => {
@@ -14,3 +14,42 @@ describe("shouldHideCollapsedToastContent", () => {
assert.equal(shouldHideCollapsedToastContent(1, 3), true);
});
});
describe("buildVisibleToastLayout", () => {
it("computes indices and offsets from the visible subset", () => {
const visibleToasts = [{ id: "a", height: 48 }, { id: "b", height: 72 }, { id: "c", height: 24 }];
const layout = buildVisibleToastLayout(visibleToasts);
assert.equal(layout.frontmostHeight, 48);
assert.deepEqual(
layout.items.map(({ toast, visibleIndex, offsetY }) => ({
id: toast.id,
visibleIndex,
offsetY,
})),
[
{ id: "a", visibleIndex: 0, offsetY: 0 },
{ id: "b", visibleIndex: 1, offsetY: 48 },
{ id: "c", visibleIndex: 2, offsetY: 120 },
],
);
});
it("treats missing heights as zero", () => {
const layout = buildVisibleToastLayout([{ id: "a" }, { id: "b", height: undefined }, { id: "c", height: 30 }]);
assert.equal(layout.frontmostHeight, 0);
assert.deepEqual(
layout.items.map(({ toast, offsetY }) => ({
id: toast.id,
offsetY,
})),
[
{ id: "a", offsetY: 0 },
{ id: "b", offsetY: 0 },
{ id: "c", offsetY: 0 },
],
);
});
});
+37
View File
@@ -7,3 +7,40 @@ export function shouldHideCollapsedToastContent(
if (visibleToastCount <= 1) return false;
return visibleToastIndex > 0;
}
type ToastWithHeight = {
height?: number | null | undefined;
};
type VisibleToastLayoutItem<TToast extends object> = {
toast: TToast;
visibleIndex: number;
offsetY: number;
};
export function buildVisibleToastLayout<TToast extends object>(
visibleToasts: readonly (TToast & ToastWithHeight)[],
): {
frontmostHeight: number;
items: VisibleToastLayoutItem<TToast & ToastWithHeight>[];
} {
let offsetY = 0;
return {
frontmostHeight: normalizeToastHeight(visibleToasts[0]?.height),
items: visibleToasts.map((toast, visibleIndex) => {
const item = {
toast,
visibleIndex,
offsetY,
};
offsetY += normalizeToastHeight(toast.height);
return item;
}),
};
}
function normalizeToastHeight(height: number | null | undefined): number {
return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : 0;
}
+16 -4
View File
@@ -1,7 +1,7 @@
"use client";
import { Toast } from "@base-ui/react/toast";
import { useEffect } from "react";
import { useEffect, type CSSProperties } from "react";
import { useParams } from "@tanstack/react-router";
import { ThreadId } from "@t3tools/contracts";
import {
@@ -14,7 +14,7 @@ import {
import { cn } from "~/lib/utils";
import { buttonVariants } from "~/components/ui/button";
import { shouldHideCollapsedToastContent } from "./toast.logic";
import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
type ThreadToastData = {
threadId?: ThreadId | null;
@@ -158,6 +158,7 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
const visibleToasts = toasts.filter((toast) =>
shouldRenderForActiveThread(toast.data, activeThreadId),
);
const visibleToastLayout = buildVisibleToastLayout(visibleToasts);
useEffect(() => {
const activeToastIds = new Set(toasts.map((toast) => toast.id));
@@ -183,12 +184,17 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
)}
data-position={position}
data-slot="toast-viewport"
style={
{
"--toast-frontmost-height": `${visibleToastLayout.frontmostHeight}px`,
} as CSSProperties
}
>
{visibleToasts.map((toast, visibleIndex) => {
{visibleToastLayout.items.map(({ toast, visibleIndex, offsetY }) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
const hideCollapsedContent = shouldHideCollapsedToastContent(
visibleIndex,
visibleToasts.length,
visibleToastLayout.items.length,
);
return (
@@ -241,6 +247,12 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
)}
data-position={position}
key={toast.id}
style={
{
"--toast-index": visibleIndex,
"--toast-offset-y": `${offsetY}px`,
} as CSSProperties
}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
+16
View File
@@ -49,3 +49,19 @@ export function buildProposedPlanMarkdownFilename(planMarkdown: string): string
const title = proposedPlanTitle(planMarkdown);
return `${sanitizePlanFileSegment(title ?? "plan")}.md`;
}
export function normalizePlanMarkdownForExport(planMarkdown: string): string {
return `${planMarkdown.trimEnd()}\n`;
}
export function downloadPlanAsTextFile(filename: string, contents: string): void {
const blob = new Blob([contents], { type: "text/markdown;charset=utf-8" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = filename;
anchor.click();
window.setTimeout(() => {
URL.revokeObjectURL(url);
}, 0);
}
+4 -54
View File
@@ -3,14 +3,8 @@ import { useQuery } from "@tanstack/react-query";
import { useCallback, useState } from "react";
import { type ProviderKind } from "@t3tools/contracts";
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
import { ZapIcon } from "lucide-react";
import {
APP_SERVICE_TIER_OPTIONS,
MAX_CUSTOM_MODEL_LENGTH,
shouldShowFastTierIcon,
useAppSettings,
} from "../appSettings";
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
@@ -18,7 +12,6 @@ import { ensureNativeApi } from "../nativeApi";
import { preferredTerminalEditor } from "../terminal-links";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../components/ui/select";
import { Switch } from "../components/ui/switch";
import { SidebarInset } from "~/components/ui/sidebar";
@@ -103,7 +96,6 @@ function SettingsRouteView() {
const codexBinaryPath = settings.codexBinaryPath;
const codexHomePath = settings.codexHomePath;
const codexServiceTier = settings.codexServiceTier;
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
const openKeybindingsFile = useCallback(() => {
@@ -310,43 +302,6 @@ function SettingsRouteView() {
</div>
<div className="space-y-5">
<label className="block space-y-1">
<span className="text-xs font-medium text-foreground">Default service tier</span>
<Select
items={APP_SERVICE_TIER_OPTIONS.map((option) => ({
label: option.label,
value: option.value,
}))}
value={codexServiceTier}
onValueChange={(value) => {
if (!value) return;
updateSettings({ codexServiceTier: value });
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectPopup alignItemWithTrigger={false}>
{APP_SERVICE_TIER_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
<div className="flex min-w-0 items-center gap-2">
{option.value === "fast" ? (
<ZapIcon className="size-3.5 text-amber-500" />
) : (
<span className="size-3.5 shrink-0" aria-hidden="true" />
)}
<span className="truncate">{option.label}</span>
</div>
</SelectItem>
))}
</SelectPopup>
</Select>
<span className="text-xs text-muted-foreground">
{APP_SERVICE_TIER_OPTIONS.find((option) => option.value === codexServiceTier)
?.description ?? "Use Codex defaults without forcing a service tier."}
</span>
</label>
{MODEL_PROVIDER_SETTINGS.map((providerSettings) => {
const provider = providerSettings.provider;
const customModels = getCustomModelsForProvider(settings, provider);
@@ -445,14 +400,9 @@ function SettingsRouteView() {
key={`${provider}:${slug}`}
className="flex items-center justify-between gap-3 rounded-lg border border-border bg-background px-3 py-2"
>
<div className="flex min-w-0 flex-1 items-center gap-2">
{provider === "codex" && shouldShowFastTierIcon(slug, codexServiceTier) ? (
<ZapIcon className="size-3.5 shrink-0 text-amber-500" />
) : null}
<code className="min-w-0 flex-1 truncate text-xs text-foreground">
{slug}
</code>
</div>
<code className="min-w-0 flex-1 truncate text-xs text-foreground">
{slug}
</code>
<Button
size="xs"
variant="ghost"
+1
View File
@@ -25,6 +25,7 @@ export interface AppState {
const PERSISTED_STATE_KEY = "t3code:renderer-state:v8";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v7",
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
+9
View File
@@ -4,6 +4,14 @@ import { tanstackRouter } from "@tanstack/router-plugin/vite";
import { defineConfig } from "vite";
const port = Number(process.env.PORT ?? 5733);
const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
const buildSourcemap =
sourcemapEnv === "0" || sourcemapEnv === "false"
? false
: sourcemapEnv === "hidden"
? "hidden"
: true;
export default defineConfig({
plugins: [
@@ -42,5 +50,6 @@ export default defineConfig({
build: {
outDir: "dist",
emptyOutDir: true,
sourcemap: buildSourcemap,
},
});
+4 -4
View File
@@ -14,7 +14,7 @@
},
"apps/desktop": {
"name": "@t3tools/desktop",
"version": "0.0.5",
"version": "0.0.9",
"dependencies": {
"effect": "catalog:",
"electron": "40.6.0",
@@ -43,7 +43,7 @@
},
"apps/server": {
"name": "t3",
"version": "0.0.5",
"version": "0.0.9",
"bin": {
"t3": "./dist/index.mjs",
},
@@ -72,7 +72,7 @@
},
"apps/web": {
"name": "@t3tools/web",
"version": "0.0.5",
"version": "0.0.9",
"dependencies": {
"@base-ui/react": "^1.2.0",
"@lexical/react": "^0.41.0",
@@ -116,7 +116,7 @@
},
"packages/contracts": {
"name": "@t3tools/contracts",
"version": "0.0.5",
"version": "0.0.9",
"dependencies": {
"effect": "catalog:",
},
+1
View File
@@ -45,6 +45,7 @@
"dist:desktop:dmg:x64": "node scripts/build-desktop-artifact.ts --platform mac --target dmg --arch x64",
"dist:desktop:linux": "node scripts/build-desktop-artifact.ts --platform linux --target AppImage --arch x64",
"dist:desktop:win": "node scripts/build-desktop-artifact.ts --platform win --target nsis --arch x64",
"release:smoke": "node scripts/release-smoke.ts",
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo",
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.5",
"version": "0.0.9",
"private": true,
"files": [
"dist"
+11
View File
@@ -58,10 +58,21 @@ export type DesktopUpdateStatus =
| "downloaded"
| "error";
export type DesktopRuntimeArch = "arm64" | "x64" | "other";
export interface DesktopRuntimeInfo {
hostArch: DesktopRuntimeArch;
appArch: DesktopRuntimeArch;
runningUnderArm64Translation: boolean;
}
export interface DesktopUpdateState {
enabled: boolean;
status: DesktopUpdateStatus;
currentVersion: string;
hostArch: DesktopRuntimeArch;
appArch: DesktopRuntimeArch;
runningUnderArm64Translation: boolean;
availableVersion: string | null;
downloadedVersion: string | null;
downloadPercent: number | null;
-123
View File
@@ -42,8 +42,6 @@ export const ProviderSandboxMode = Schema.Literals([
"danger-full-access",
]);
export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
export const ProviderServiceTier = Schema.Literals(["fast", "flex"]);
export type ProviderServiceTier = typeof ProviderServiceTier.Type;
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
const CodexProviderStartOptions = Schema.Struct({
binaryPath: Schema.optional(TrimmedNonEmptyString),
@@ -371,7 +369,6 @@ export const ThreadTurnStartCommand = Schema.Struct({
}),
provider: Schema.optional(ProviderKind),
model: Schema.optional(TrimmedNonEmptyString),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
modelOptions: Schema.optional(ProviderModelOptions),
providerOptions: Schema.optional(ProviderStartOptions),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
@@ -394,7 +391,6 @@ const ClientThreadTurnStartCommand = Schema.Struct({
}),
provider: Schema.optional(ProviderKind),
model: Schema.optional(TrimmedNonEmptyString),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
modelOptions: Schema.optional(ProviderModelOptions),
providerOptions: Schema.optional(ProviderStartOptions),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
@@ -675,7 +671,6 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
messageId: MessageId,
provider: Schema.optional(ProviderKind),
model: Schema.optional(TrimmedNonEmptyString),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
modelOptions: Schema.optional(ProviderModelOptions),
providerOptions: Schema.optional(ProviderStartOptions),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
@@ -769,20 +764,6 @@ const EventBaseFields = {
metadata: OrchestrationEventMetadata,
} as const;
const PersistedEventBaseFields = {
sequence: NonNegativeInt,
eventId: EventId,
aggregateKind: OrchestrationAggregateKind,
streamId: Schema.Union([ProjectId, ThreadId]),
streamVersion: NonNegativeInt,
occurredAt: IsoDateTime,
commandId: Schema.NullOr(CommandId),
causationEventId: Schema.NullOr(EventId),
correlationId: Schema.NullOr(CommandId),
actorKind: OrchestrationActorKind,
metadata: OrchestrationEventMetadata,
} as const;
export const OrchestrationEvent = Schema.Union([
Schema.Struct({
...EventBaseFields,
@@ -887,110 +868,6 @@ export const OrchestrationEvent = Schema.Union([
]);
export type OrchestrationEvent = typeof OrchestrationEvent.Type;
export const OrchestrationPersistedEvent = Schema.Union([
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("project.created"),
payload: ProjectCreatedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("project.meta-updated"),
payload: ProjectMetaUpdatedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("project.deleted"),
payload: ProjectDeletedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.created"),
payload: ThreadCreatedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.deleted"),
payload: ThreadDeletedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.meta-updated"),
payload: ThreadMetaUpdatedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.runtime-mode-set"),
payload: ThreadRuntimeModeSetPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.interaction-mode-set"),
payload: ThreadInteractionModeSetPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.message-sent"),
payload: ThreadMessageSentPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.turn-start-requested"),
payload: ThreadTurnStartRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.turn-interrupt-requested"),
payload: ThreadTurnInterruptRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.approval-response-requested"),
payload: ThreadApprovalResponseRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.user-input-response-requested"),
payload: ThreadUserInputResponseRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.checkpoint-revert-requested"),
payload: ThreadCheckpointRevertRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.reverted"),
payload: ThreadRevertedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.session-stop-requested"),
payload: ThreadSessionStopRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.session-set"),
payload: ThreadSessionSetPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.proposed-plan-upserted"),
payload: ThreadProposedPlanUpsertedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.turn-diff-completed"),
payload: ThreadTurnDiffCompletedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.activity-appended"),
payload: ThreadActivityAppendedPayload,
}),
]);
export type OrchestrationPersistedEvent = typeof OrchestrationPersistedEvent.Type;
export const OrchestrationCommandReceiptStatus = Schema.Literals(["accepted", "rejected"]);
export type OrchestrationCommandReceiptStatus = typeof OrchestrationCommandReceiptStatus.Type;
-3
View File
@@ -19,7 +19,6 @@ import {
ProviderKind,
ProviderRequestKind,
ProviderSandboxMode,
ProviderServiceTier,
ProviderUserInputAnswers,
RuntimeMode,
} from "./orchestration";
@@ -65,7 +64,6 @@ export const ProviderSessionStartInput = Schema.Struct({
model: Schema.optional(TrimmedNonEmptyStringSchema),
modelOptions: Schema.optional(ProviderModelOptions),
resumeCursor: Schema.optional(Schema.Unknown),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
approvalPolicy: Schema.optional(ProviderApprovalPolicy),
sandboxMode: Schema.optional(ProviderSandboxMode),
providerOptions: Schema.optional(ProviderStartOptions),
@@ -82,7 +80,6 @@ export const ProviderSendTurnInput = Schema.Struct({
Schema.Array(ChatAttachment).check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS)),
),
model: Schema.optional(TrimmedNonEmptyStringSchema),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
modelOptions: Schema.optional(ProviderModelOptions),
interactionMode: Schema.optional(ProviderInteractionMode),
});
+6
View File
@@ -580,6 +580,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
ChildProcess.make({
cwd: repoRoot,
...commandOutputOptions(options.verbose),
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun run build:desktop`,
);
}
@@ -642,6 +644,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
ChildProcess.make({
cwd: stageAppDir,
...commandOutputOptions(options.verbose),
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun install --production`,
);
@@ -680,6 +684,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
cwd: stageAppDir,
env: buildEnv,
...commandOutputOptions(options.verbose),
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
})`bunx electron-builder ${platformConfig.cliFlag} --${options.arch} --publish never`,
);
+2
View File
@@ -455,6 +455,8 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
stderr: "inherit",
env,
extendEnv: false,
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
// Keep turbo in the same process group so terminal signals (Ctrl+C)
// reach it directly. Effect defaults to detached: true on non-Windows,
// which would put turbo in a new group and require manual forwarding.
+113
View File
@@ -0,0 +1,113 @@
import { execFileSync } from "node:child_process";
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const workspaceFiles = [
"package.json",
"bun.lock",
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"apps/marketing/package.json",
"packages/contracts/package.json",
"packages/shared/package.json",
"scripts/package.json",
] as const;
function copyWorkspaceManifestFixture(targetRoot: string): void {
for (const relativePath of workspaceFiles) {
const sourcePath = resolve(repoRoot, relativePath);
const destinationPath = resolve(targetRoot, relativePath);
mkdirSync(dirname(destinationPath), { recursive: true });
cpSync(sourcePath, destinationPath);
}
}
function writeMacManifestFixtures(targetRoot: string): { arm64Path: string; x64Path: string } {
const assetDirectory = resolve(targetRoot, "release-assets");
mkdirSync(assetDirectory, { recursive: true });
const arm64Path = resolve(assetDirectory, "latest-mac.yml");
const x64Path = resolve(assetDirectory, "latest-mac-x64.yml");
writeFileSync(
arm64Path,
`version: 9.9.9-smoke.0
files:
- url: T3-Code-9.9.9-smoke.0-arm64.zip
sha512: arm64zip
size: 125621344
- url: T3-Code-9.9.9-smoke.0-arm64.dmg
sha512: arm64dmg
size: 131754935
path: T3-Code-9.9.9-smoke.0-arm64.zip
sha512: arm64zip
releaseDate: '2026-03-08T10:32:14.587Z'
`,
);
writeFileSync(
x64Path,
`version: 9.9.9-smoke.0
files:
- url: T3-Code-9.9.9-smoke.0-x64.zip
sha512: x64zip
size: 132000112
- url: T3-Code-9.9.9-smoke.0-x64.dmg
sha512: x64dmg
size: 138148807
path: T3-Code-9.9.9-smoke.0-x64.zip
sha512: x64zip
releaseDate: '2026-03-08T10:36:07.540Z'
`,
);
return { arm64Path, x64Path };
}
function assertContains(haystack: string, needle: string, message: string): void {
if (!haystack.includes(needle)) {
throw new Error(message);
}
}
const tempRoot = mkdtempSync(join(tmpdir(), "t3-release-smoke-"));
try {
copyWorkspaceManifestFixture(tempRoot);
execFileSync(
process.execPath,
[resolve(repoRoot, "scripts/update-release-package-versions.ts"), "9.9.9-smoke.0", "--root", tempRoot],
{
cwd: repoRoot,
stdio: "inherit",
},
);
execFileSync("bun", ["install", "--lockfile-only", "--ignore-scripts"], {
cwd: tempRoot,
stdio: "inherit",
});
const lockfile = readFileSync(resolve(tempRoot, "bun.lock"), "utf8");
assertContains(lockfile, `"version": "9.9.9-smoke.0"`, "Expected bun.lock to contain the smoke version.");
const { arm64Path, x64Path } = writeMacManifestFixtures(tempRoot);
execFileSync(process.execPath, [resolve(repoRoot, "scripts/merge-mac-update-manifests.ts"), arm64Path, x64Path], {
cwd: repoRoot,
stdio: "inherit",
});
const mergedManifest = readFileSync(arm64Path, "utf8");
assertContains(mergedManifest, "T3-Code-9.9.9-smoke.0-arm64.zip", "Merged manifest is missing the arm64 asset.");
assertContains(mergedManifest, "T3-Code-9.9.9-smoke.0-x64.zip", "Merged manifest is missing the x64 asset.");
console.log("Release smoke checks passed.");
} finally {
rmSync(tempRoot, { recursive: true, force: true });
}
+111
View File
@@ -0,0 +1,111 @@
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
export const releasePackageFiles = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
] as const;
interface UpdateReleasePackageVersionsOptions {
readonly rootDir?: string;
}
interface MutablePackageJson {
version?: string;
[key: string]: unknown;
}
export function updateReleasePackageVersions(
version: string,
options: UpdateReleasePackageVersionsOptions = {},
): { changed: boolean } {
const rootDir = resolve(options.rootDir ?? process.cwd());
let changed = false;
for (const relativePath of releasePackageFiles) {
const filePath = resolve(rootDir, relativePath);
const packageJson = JSON.parse(readFileSync(filePath, "utf8")) as MutablePackageJson;
if (packageJson.version === version) {
continue;
}
packageJson.version = version;
writeFileSync(filePath, `${JSON.stringify(packageJson, null, 2)}\n`);
changed = true;
}
return { changed };
}
function parseArgs(argv: ReadonlyArray<string>): {
version: string;
rootDir: string | undefined;
writeGithubOutput: boolean;
} {
let version: string | undefined;
let rootDir: string | undefined;
let writeGithubOutput = false;
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
if (argument === undefined) {
continue;
}
if (argument === "--github-output") {
writeGithubOutput = true;
continue;
}
if (argument === "--root") {
rootDir = argv[index + 1];
if (!rootDir) {
throw new Error("Missing value for --root.");
}
index += 1;
continue;
}
if (argument.startsWith("--")) {
throw new Error(`Unknown argument: ${argument}`);
}
if (version !== undefined) {
throw new Error("Only one release version can be provided.");
}
version = argument;
}
if (!version) {
throw new Error(
"Usage: node scripts/update-release-package-versions.ts <version> [--root <path>] [--github-output]",
);
}
return { version, rootDir, writeGithubOutput };
}
const isMain = process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isMain) {
const { version, rootDir, writeGithubOutput } = parseArgs(process.argv.slice(2));
const { changed } = updateReleasePackageVersions(
version,
rootDir === undefined ? {} : { rootDir },
);
if (!changed) {
console.log("All package.json versions already match release version.");
}
if (writeGithubOutput) {
const githubOutputPath = process.env.GITHUB_OUTPUT;
if (!githubOutputPath) {
throw new Error("GITHUB_OUTPUT is required when --github-output is set.");
}
appendFileSync(githubOutputPath, `changed=${changed}\n`);
}
}