Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea505a2d53 | ||
|
|
d62ffa7560 | ||
|
|
59e2944fb7 | ||
|
|
17942787aa | ||
|
|
5815ba24e2 | ||
|
|
5de8e9d1ae | ||
|
|
96e1e3db5e | ||
|
|
5dd36bc5ad | ||
|
|
6271b989bc | ||
|
|
57aa6bf16c | ||
|
|
40a7f4b4b1 | ||
|
|
cba0f23a9e | ||
|
|
a7ec0179fb | ||
|
|
c97c6b7836 | ||
|
|
59b0527c38 | ||
|
|
b74c7a79ab | ||
|
|
f772720d8c | ||
|
|
0763a35fbc | ||
|
|
e1c33dcd33 | ||
|
|
0a902790ca | ||
|
|
0837c8b639 | ||
|
|
5a90b6be9c | ||
|
|
42675571c9 | ||
|
|
e9f00f65ca | ||
|
|
04b95e37c5 | ||
|
|
5820e1b6ff | ||
|
|
8c904ffe34 | ||
|
|
9fa9cb4b31 |
No files matched your search
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: btca-cli
|
||||
description: btca is a cli for getting information from other git repositories by querying them with natural language. Spawns an external subagent to explore external codebases (i.e. a github repo) and answer questions about them. Great when integrating complex libraries, frameworks, or tools.
|
||||
---
|
||||
|
||||
btca is a cli for asking questions about various folders, primarily git repositories. It's built to give you the exact information you need without bloating your context window. btca uses agents under the hood to answer your question, so prompt it the way you would prompt a tool similar to yourself.
|
||||
|
||||
For example, assuming you have a resource named `codex`, you can ask questions like:
|
||||
|
||||
```bash
|
||||
btca ask -r codex -q "What is the return format for Codex App Server responses? Are there any edge cases worth knowing?"
|
||||
```
|
||||
|
||||
Your prompt may include specific names for resources to use, if they do then you should try those first. If you need to check available resources, you can use the `btca resources` command.
|
||||
|
||||
New resources can be created if the ones you need do not yet exist.
|
||||
|
||||
```bash
|
||||
btca add -n svelte-dev https://github.com/sveltejs/svelte.dev
|
||||
```
|
||||
@@ -1,3 +0,0 @@
|
||||
interface:
|
||||
display_name: "BTCA CLI"
|
||||
short_description: "Help with BTCA CLI setup and usage workflows"
|
||||
@@ -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
|
||||
@@ -22,6 +22,8 @@ jobs:
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
|
||||
make_latest: ${{ steps.release_meta.outputs.make_latest }}
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -45,6 +47,13 @@ jobs:
|
||||
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -239,7 +248,7 @@ jobs:
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
@@ -253,6 +262,13 @@ jobs:
|
||||
merge-multiple: true
|
||||
path: release-assets
|
||||
|
||||
- name: Merge macOS updater manifests
|
||||
run: |
|
||||
node scripts/merge-mac-update-manifests.ts \
|
||||
release-assets/latest-mac.yml \
|
||||
release-assets/latest-mac-x64.yml
|
||||
rm -f release-assets/latest-mac-x64.yml
|
||||
|
||||
- name: Publish release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
@@ -260,7 +276,8 @@ jobs:
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
make_latest: true
|
||||
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
|
||||
make_latest: ${{ needs.preflight.outputs.make_latest }}
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
# 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.
|
||||
|
||||
## 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.
|
||||
@@ -8,10 +8,10 @@ T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Clau
|
||||
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||
|
||||
```bash
|
||||
npx t3@alpha
|
||||
npx t3
|
||||
```
|
||||
|
||||
Use can also just install the desktop app (it's cooler).
|
||||
You can also just install the desktop app. It's cooler.
|
||||
|
||||
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||
|
||||
@@ -21,4 +21,8 @@ We are very very early in this project. Expect bugs.
|
||||
|
||||
We are not accepting contributions yet.
|
||||
|
||||
Discord link coming soon.
|
||||
## 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).
|
||||
@@ -2,24 +2,12 @@
|
||||
|
||||
## Small things
|
||||
|
||||
- [ ] Plan mode
|
||||
- [ ] Submitting new messages should scroll to bottom
|
||||
- [ ] 1 click copy in codeblocks
|
||||
- [x] Pasting/adding images to submit with prompts
|
||||
- [ ] Only show last 10 threads for a given project
|
||||
- [ ] Thread archiving
|
||||
- [x] Selecting folder should instantly create project
|
||||
- [ ] New projects should go on top
|
||||
- [ ] Projects should be sorted by latest thread update
|
||||
- [x] "Response" bar should ONLY appear on work completed
|
||||
- [x] "Response" bar should ONLY appear above the FINAL message in a series
|
||||
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
|
||||
- [x] Insta focus input on new thread creation
|
||||
- [x] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
||||
- [x] Making new thread should auto-focus input box
|
||||
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
|
||||
|
||||
## Bigger things
|
||||
|
||||
- [ ] Queueing messages
|
||||
- [x] External runners (i.e. running the cli on a mac mini)
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.5",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import * as ChildProcess from "node:child_process";
|
||||
import { readPathFromLoginShell } from "@t3tools/shared/shell";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
const result = readPathFromLoginShell(shell);
|
||||
if (result) {
|
||||
process.env.PATH = result;
|
||||
}
|
||||
|
||||
@@ -58,6 +58,8 @@ const LOG_FILE_MAX_FILES = 10;
|
||||
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
|
||||
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
|
||||
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
|
||||
@@ -725,7 +727,10 @@ function configureAutoUpdater(): void {
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
autoUpdater.allowPrerelease = app.getVersion().includes("-");
|
||||
// Keep alpha branding, but force all installs onto the stable update track.
|
||||
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
|
||||
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
|
||||
autoUpdater.allowDowngrade = false;
|
||||
let lastLoggedDownloadMilestone = -1;
|
||||
|
||||
autoUpdater.on("checking-for-update", () => {
|
||||
@@ -1109,6 +1114,32 @@ function createWindow(): BrowserWindow {
|
||||
},
|
||||
});
|
||||
|
||||
window.webContents.on("context-menu", (_event, params) => {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
|
||||
if (params.misspelledWord) {
|
||||
for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
|
||||
template.push({
|
||||
label: suggestion,
|
||||
click: () => window.webContents.replaceMisspelling(suggestion),
|
||||
});
|
||||
}
|
||||
if (params.dictionarySuggestions.length === 0) {
|
||||
template.push({ label: "No suggestions", enabled: false });
|
||||
}
|
||||
template.push({ type: "separator" });
|
||||
}
|
||||
|
||||
template.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(template).popup({ window });
|
||||
});
|
||||
|
||||
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
|
||||
window.on("page-title-updated", (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 414 B |
Binary file not shown.
|
After Width: | Height: | Size: 662 B |
Binary file not shown.
|
Before Width: | Height: | Size: 279 KiB After Width: | Height: | Size: 9.9 KiB |
@@ -12,8 +12,10 @@
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<link rel="icon" type="image/png" href="/icon.png" />
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
|
||||
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<title>T3 Code</title>
|
||||
</head>
|
||||
<body>
|
||||
@@ -37,12 +39,14 @@
|
||||
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
|
||||
|
||||
<a
|
||||
id="download-btn"
|
||||
href="https://github.com/pingdotgg/t3code/releases"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="hero-button"
|
||||
>
|
||||
Download now
|
||||
<svg class="hero-button-icon hero-button-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
|
||||
<svg class="hero-button-icon hero-button-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
|
||||
<svg class="hero-button-icon hero-button-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
|
||||
<span id="download-label">Download now</span>
|
||||
</a>
|
||||
|
||||
<div class="screenshot-wrap">
|
||||
@@ -62,6 +66,90 @@
|
||||
</body>
|
||||
</html>
|
||||
|
||||
<script>
|
||||
const REPO = "pingdotgg/t3code";
|
||||
const RELEASES_URL = `https://github.com/${REPO}/releases`;
|
||||
const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
|
||||
|
||||
type Platform = { os: "mac" | "win" | "linux"; label: string; arch?: string };
|
||||
|
||||
function detectPlatform(): Platform | null {
|
||||
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",
|
||||
};
|
||||
}
|
||||
if (/Linux/i.test(ua)) return { os: "linux", label: "Download for Linux" };
|
||||
return null;
|
||||
}
|
||||
|
||||
function pickAsset(
|
||||
assets: Array<{ name: string; browser_download_url: string }>,
|
||||
platform: Platform,
|
||||
): string | null {
|
||||
if (platform.os === "win") {
|
||||
return (
|
||||
assets.find((a) => a.name.endsWith("-x64.exe"))
|
||||
?.browser_download_url ?? null
|
||||
);
|
||||
}
|
||||
if (platform.os === "mac") {
|
||||
const preferred = assets.find((a) =>
|
||||
a.name.endsWith(`-${platform.arch}.dmg`),
|
||||
);
|
||||
const fallback = assets.find((a) => a.name.endsWith(".dmg"));
|
||||
return (preferred ?? fallback)?.browser_download_url ?? null;
|
||||
}
|
||||
if (platform.os === "linux") {
|
||||
return (
|
||||
assets.find((a) => a.name.endsWith(".AppImage"))
|
||||
?.browser_download_url ?? null
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function init() {
|
||||
const btn = document.getElementById("download-btn") as HTMLAnchorElement | null;
|
||||
const label = document.getElementById("download-label");
|
||||
if (!btn || !label) return;
|
||||
|
||||
const platform = detectPlatform();
|
||||
if (!platform) return;
|
||||
|
||||
document.documentElement.dataset.platform = platform.os;
|
||||
label.textContent = platform.label;
|
||||
|
||||
try {
|
||||
const cached = sessionStorage.getItem("t3code-latest-release");
|
||||
const data = cached
|
||||
? JSON.parse(cached)
|
||||
: await fetch(API_URL).then((r) => r.json());
|
||||
|
||||
if (!cached && data?.assets) {
|
||||
sessionStorage.setItem("t3code-latest-release", JSON.stringify(data));
|
||||
}
|
||||
|
||||
const url = pickAsset(data.assets ?? [], platform);
|
||||
if (url) {
|
||||
btn.href = url;
|
||||
btn.removeAttribute("target");
|
||||
btn.removeAttribute("rel");
|
||||
}
|
||||
} catch {
|
||||
btn.href = RELEASES_URL;
|
||||
}
|
||||
}
|
||||
|
||||
init();
|
||||
</script>
|
||||
|
||||
<style>
|
||||
:root {
|
||||
--bg: #09090b;
|
||||
@@ -196,7 +284,9 @@
|
||||
/* ── Hero button ── */
|
||||
|
||||
.hero-button {
|
||||
display: inline-block;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
background: #fafafa;
|
||||
color: #09090b;
|
||||
padding: 0.75rem 2rem;
|
||||
@@ -218,6 +308,25 @@
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.hero-button-icon {
|
||||
display: none;
|
||||
width: 1em;
|
||||
height: 1em;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
:global([data-platform="mac"]) .hero-button-icon--apple {
|
||||
display: block;
|
||||
}
|
||||
|
||||
:global([data-platform="win"]) .hero-button-icon--windows {
|
||||
display: block;
|
||||
}
|
||||
|
||||
:global([data-platform="linux"]) .hero-button-icon--linux {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* ── Screenshot ── */
|
||||
|
||||
.screenshot-wrap {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.5",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
|
||||
@@ -132,6 +132,7 @@ const buildCmd = Command.make(
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
shell: process.platform === "win32",
|
||||
})`bun tsdown`,
|
||||
);
|
||||
|
||||
@@ -225,6 +226,7 @@ const publishCmd = Command.make(
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -316,6 +316,59 @@ describe("startSession", () => {
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it("fails fast with an upgrade message when codex is below the minimum supported version", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
method: event.method,
|
||||
kind: event.kind,
|
||||
...(event.message ? { message: event.message } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const versionCheck = vi
|
||||
.spyOn(
|
||||
manager as unknown as {
|
||||
assertSupportedCodexCliVersion: (input: {
|
||||
binaryPath: string;
|
||||
cwd: string;
|
||||
homePath?: string;
|
||||
}) => void;
|
||||
},
|
||||
"assertSupportedCodexCliVersion",
|
||||
)
|
||||
.mockImplementation(() => {
|
||||
throw new Error(
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
);
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
);
|
||||
expect(versionCheck).toHaveBeenCalledTimes(1);
|
||||
expect(events).toEqual([
|
||||
{
|
||||
method: "session/startFailed",
|
||||
kind: "error",
|
||||
message:
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
versionCheck.mockRestore();
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendTurn", () => {
|
||||
|
||||
@@ -22,6 +22,12 @@ import {
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { Effect, ServiceMap } from "effect";
|
||||
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "./provider/codexCliVersion";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
interface PendingRequest {
|
||||
@@ -138,6 +144,8 @@ export interface CodexThreadSnapshot {
|
||||
turns: CodexThreadTurnSnapshot[];
|
||||
}
|
||||
|
||||
const CODEX_VERSION_CHECK_TIMEOUT_MS = 4_000;
|
||||
|
||||
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
|
||||
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
|
||||
const CODEX_STDERR_LOG_REGEX =
|
||||
@@ -535,6 +543,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const codexOptions = readCodexProviderOptions(input);
|
||||
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
|
||||
const codexHomePath = codexOptions.homePath;
|
||||
this.assertSupportedCodexCliVersion({
|
||||
binaryPath: codexBinaryPath,
|
||||
cwd: resolvedCwd,
|
||||
...(codexHomePath ? { homePath: codexHomePath } : {}),
|
||||
});
|
||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
@@ -1320,6 +1333,14 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
this.emit("event", event);
|
||||
}
|
||||
|
||||
private assertSupportedCodexCliVersion(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly homePath?: string;
|
||||
}): void {
|
||||
assertSupportedCodexCliVersion(input);
|
||||
}
|
||||
|
||||
private updateSession(context: CodexSessionContext, updates: Partial<ProviderSession>): void {
|
||||
context.session = {
|
||||
...context.session,
|
||||
@@ -1500,6 +1521,51 @@ function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
|
||||
};
|
||||
}
|
||||
|
||||
function assertSupportedCodexCliVersion(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly homePath?: string;
|
||||
}): void {
|
||||
const result = spawnSync(input.binaryPath, ["--version"], {
|
||||
cwd: input.cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
|
||||
},
|
||||
encoding: "utf8",
|
||||
shell: process.platform === "win32",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
timeout: CODEX_VERSION_CHECK_TIMEOUT_MS,
|
||||
maxBuffer: 1024 * 1024,
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
const lower = result.error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("enoent") ||
|
||||
lower.includes("command not found") ||
|
||||
lower.includes("not found")
|
||||
) {
|
||||
throw new Error(`Codex CLI (${input.binaryPath}) is not installed or not executable.`);
|
||||
}
|
||||
throw new Error(
|
||||
`Failed to execute Codex CLI version check: ${result.error.message || String(result.error)}`,
|
||||
);
|
||||
}
|
||||
|
||||
const stdout = result.stdout ?? "";
|
||||
const stderr = result.stderr ?? "";
|
||||
if (result.status !== 0) {
|
||||
const detail = stderr.trim() || stdout.trim() || `Command exited with code ${result.status}.`;
|
||||
throw new Error(`Codex CLI version check failed. ${detail}`);
|
||||
}
|
||||
|
||||
const parsedVersion = parseCodexCliVersion(`${stdout}\n${stderr}`);
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
throw new Error(formatCodexCliUpgradeMessage(parsedVersion));
|
||||
}
|
||||
}
|
||||
|
||||
function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
|
||||
if (!resumeCursor || typeof resumeCursor !== "object" || Array.isArray(resumeCursor)) {
|
||||
return undefined;
|
||||
|
||||
@@ -654,7 +654,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
const realGitService = yield* GitService;
|
||||
let fetchStarted = false;
|
||||
let releaseFetch: () => void = () => undefined;
|
||||
let releaseFetch!: () => void;
|
||||
const waitForReleasePromise = new Promise<void>((resolve) => {
|
||||
releaseFetch = resolve;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function isGitRepository(cwd: string): boolean {
|
||||
return existsSync(join(cwd, ".git"));
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { CheckpointReactor, type CheckpointReactorShape } from "../Services/Chec
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { isGitRepository } from "../../git/isRepo.ts";
|
||||
|
||||
type ReactorInput =
|
||||
| {
|
||||
@@ -144,6 +145,8 @@ const make = Effect.gen(function* () {
|
||||
return Option.none();
|
||||
});
|
||||
|
||||
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
|
||||
|
||||
const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
|
||||
) {
|
||||
@@ -184,6 +187,14 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(checkpointCwd)) {
|
||||
yield* Effect.logDebug("checkpoint capture skipped for non-git workspace", {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
cwd: checkpointCwd,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
@@ -319,6 +330,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(checkpointCwd)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
@@ -378,6 +392,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(checkpointCwd)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
@@ -425,6 +442,15 @@ const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(sessionRuntime.value.cwd)) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: "Checkpoints are unavailable because this project is not a git repository.",
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type ProviderModelOptions,
|
||||
type ProviderKind,
|
||||
type ProviderServiceTier,
|
||||
type ProviderStartOptions,
|
||||
type OrchestrationSession,
|
||||
ThreadId,
|
||||
type ProviderSession,
|
||||
@@ -144,6 +145,8 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const threadProviderOptions = new Map<string, ProviderStartOptions>();
|
||||
|
||||
const appendProviderFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly kind:
|
||||
@@ -203,6 +206,7 @@ const make = Effect.gen(function* () {
|
||||
readonly model?: string;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly serviceTier?: ProviderServiceTier | null;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
},
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -239,6 +243,7 @@ const make = Effect.gen(function* () {
|
||||
...(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 } : {}),
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
});
|
||||
@@ -325,6 +330,7 @@ const make = Effect.gen(function* () {
|
||||
readonly model?: string;
|
||||
readonly serviceTier?: ProviderServiceTier | null;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
readonly interactionMode?: "default" | "plan";
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
@@ -332,11 +338,15 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
if (input.providerOptions !== undefined) {
|
||||
threadProviderOptions.set(input.threadId, input.providerOptions);
|
||||
}
|
||||
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 } : {}),
|
||||
});
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
@@ -472,6 +482,7 @@ const make = Effect.gen(function* () {
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.serviceTier !== undefined ? { serviceTier: event.payload.serviceTier } : {}),
|
||||
...(event.payload.modelOptions !== undefined ? { modelOptions: event.payload.modelOptions } : {}),
|
||||
...(event.payload.providerOptions !== undefined ? { providerOptions: event.payload.providerOptions } : {}),
|
||||
interactionMode: event.payload.interactionMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
@@ -627,7 +638,10 @@ const make = Effect.gen(function* () {
|
||||
if (!thread?.session || thread.session.status === "stopped") {
|
||||
return;
|
||||
}
|
||||
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt);
|
||||
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
|
||||
...(cachedProviderOptions !== undefined ? { providerOptions: cachedProviderOptions } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "thread.turn-start-requested":
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { OrchestrationReadModel, ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -112,6 +116,13 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
@@ -122,9 +133,14 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
async function createHarness() {
|
||||
const workspaceRoot = makeTempDir("t3-provider-project-");
|
||||
fs.mkdirSync(path.join(workspaceRoot, ".git"));
|
||||
const provider = createProviderServiceHarness();
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -152,7 +168,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
commandId: CommandId.makeUnsafe("cmd-provider-project-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
@@ -818,6 +834,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "completed",
|
||||
detail: "hello live",
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Ref, Stream } from "effect";
|
||||
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { isGitRepository } from "../../git/isRepo.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ProviderRuntimeIngestionService,
|
||||
@@ -507,6 +509,22 @@ const make = Effect.gen(function* () {
|
||||
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
|
||||
});
|
||||
|
||||
const isGitRepoForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
return false;
|
||||
}
|
||||
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
if (!workspaceCwd) {
|
||||
return false;
|
||||
}
|
||||
return isGitRepository(workspaceCwd);
|
||||
});
|
||||
|
||||
const rememberAssistantMessageId = (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
@@ -933,6 +951,10 @@ const make = Effect.gen(function* () {
|
||||
if (assistantCompletion) {
|
||||
const assistantMessageId = assistantCompletion.messageId;
|
||||
const turnId = toTurnId(event.turnId);
|
||||
const existingAssistantMessage = thread.messages.find((entry) => entry.id === assistantMessageId);
|
||||
const shouldApplyFallbackCompletionText =
|
||||
!existingAssistantMessage ||
|
||||
existingAssistantMessage.text.length === 0;
|
||||
if (turnId) {
|
||||
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
|
||||
}
|
||||
@@ -945,7 +967,7 @@ const make = Effect.gen(function* () {
|
||||
createdAt: now,
|
||||
commandTag: "assistant-complete",
|
||||
finalDeltaCommandTag: "assistant-delta-finalize",
|
||||
...(assistantCompletion.fallbackText !== undefined
|
||||
...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText
|
||||
? { fallbackText: assistantCompletion.fallbackText }
|
||||
: {}),
|
||||
});
|
||||
@@ -1041,7 +1063,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (event.type === "turn.diff.updated") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
if (turnId && (yield* isGitRepoForThread(thread.id))) {
|
||||
const assistantMessageId = MessageId.makeUnsafe(
|
||||
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
|
||||
);
|
||||
|
||||
@@ -303,6 +303,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
...(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,
|
||||
runtimeMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readPathFromLoginShell } from "@t3tools/shared/shell";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
const result = readPathFromLoginShell(shell);
|
||||
if (result) {
|
||||
process.env.PATH = result;
|
||||
}
|
||||
@@ -20,12 +17,12 @@ export function fixPath(): void {
|
||||
}
|
||||
|
||||
export const expandHomePath = Effect.fn(function* (input: string) {
|
||||
const { join, sep } = yield* Path.Path;
|
||||
const { join } = yield* Path.Path;
|
||||
if (input === "~") {
|
||||
return OS.homedir();
|
||||
}
|
||||
if (input.startsWith(`~${sep}`)) {
|
||||
return join(OS.homedir(), input.slice(sep.length));
|
||||
if (input.startsWith("~/") || input.startsWith("~\\")) {
|
||||
return join(OS.homedir(), input.slice(2));
|
||||
}
|
||||
return input;
|
||||
});
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
type CodexAppServerSendTurnInput,
|
||||
} from "../../codexAppServerManager.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
||||
|
||||
@@ -85,6 +85,28 @@ it.effect("returns unavailable when codex is missing", () =>
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is below the minimum supported version", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
|
||||
@@ -16,6 +16,11 @@ import type {
|
||||
import { Effect, Layer, Option, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "../codexCliVersion";
|
||||
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
@@ -247,6 +252,18 @@ export const checkCodexProviderStatus: Effect.Effect<
|
||||
};
|
||||
}
|
||||
|
||||
const parsedVersion = parseCodexCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: formatCodexCliUpgradeMessage(parsedVersion),
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
|
||||
@@ -86,15 +86,30 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
|
||||
}
|
||||
}
|
||||
|
||||
function toRuntimePayloadFromSession(session: ProviderSession): Record<string, unknown> {
|
||||
function toRuntimePayloadFromSession(
|
||||
session: ProviderSession,
|
||||
extra?: { readonly providerOptions?: unknown },
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
cwd: session.cwd ?? null,
|
||||
model: session.model ?? null,
|
||||
activeTurnId: session.activeTurnId ?? null,
|
||||
lastError: session.lastError ?? null,
|
||||
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function readPersistedProviderOptions(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
): Record<string, unknown> | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
}
|
||||
const raw = "providerOptions" in runtimePayload ? runtimePayload.providerOptions : undefined;
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
|
||||
return raw as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function readPersistedCwd(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
): string | undefined {
|
||||
@@ -137,6 +152,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const upsertSessionBinding = (
|
||||
session: ProviderSession,
|
||||
threadId: ThreadId,
|
||||
extra?: { readonly providerOptions?: unknown },
|
||||
) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
@@ -144,7 +160,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
runtimeMode: session.runtimeMode,
|
||||
status: toRuntimeStatus(session),
|
||||
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
|
||||
runtimePayload: toRuntimePayloadFromSession(session),
|
||||
runtimePayload: toRuntimePayloadFromSession(session, extra),
|
||||
});
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
@@ -197,11 +213,13 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
|
||||
|
||||
const resumed = yield* adapter.startSession({
|
||||
threadId: input.binding.threadId,
|
||||
provider: input.binding.provider,
|
||||
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
runtimeMode: input.binding.runtimeMode ?? "full-access",
|
||||
});
|
||||
@@ -273,7 +291,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
);
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(session, threadId);
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||
});
|
||||
yield* analytics.record("provider.session.started", {
|
||||
provider: session.provider,
|
||||
runtimeMode: input.runtimeMode,
|
||||
@@ -436,13 +456,17 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
return session;
|
||||
}
|
||||
|
||||
return {
|
||||
...session,
|
||||
...(session.resumeCursor === undefined && binding.resumeCursor !== undefined
|
||||
? { resumeCursor: binding.resumeCursor }
|
||||
: {}),
|
||||
...(binding.runtimeMode !== undefined ? { runtimeMode: binding.runtimeMode } : {}),
|
||||
};
|
||||
const overrides: {
|
||||
resumeCursor?: ProviderSession["resumeCursor"];
|
||||
runtimeMode?: ProviderSession["runtimeMode"];
|
||||
} = {};
|
||||
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
|
||||
overrides.resumeCursor = binding.resumeCursor;
|
||||
}
|
||||
if (binding.runtimeMode !== undefined) {
|
||||
overrides.runtimeMode = binding.runtimeMode;
|
||||
}
|
||||
return Object.assign({}, session, overrides);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/;
|
||||
|
||||
export const MINIMUM_CODEX_CLI_VERSION = "0.37.0";
|
||||
|
||||
interface ParsedSemver {
|
||||
readonly major: number;
|
||||
readonly minor: number;
|
||||
readonly patch: number;
|
||||
readonly prerelease: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
function normalizeCodexVersion(version: string): string {
|
||||
const [main, prerelease] = version.trim().split("-", 2);
|
||||
const segments = (main ?? "")
|
||||
.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0);
|
||||
|
||||
if (segments.length === 2) {
|
||||
segments.push("0");
|
||||
}
|
||||
|
||||
return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
|
||||
}
|
||||
|
||||
function parseSemver(version: string): ParsedSemver | null {
|
||||
const normalized = normalizeCodexVersion(version);
|
||||
const [main = "", prerelease] = normalized.split("-", 2);
|
||||
const segments = main.split(".");
|
||||
if (segments.length !== 3) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [majorSegment, minorSegment, patchSegment] = segments;
|
||||
if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const major = Number.parseInt(majorSegment, 10);
|
||||
const minor = Number.parseInt(minorSegment, 10);
|
||||
const patch = Number.parseInt(patchSegment, 10);
|
||||
if (![major, minor, patch].every(Number.isInteger)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
prerelease:
|
||||
prerelease
|
||||
?.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0) ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function comparePrereleaseIdentifier(left: string, right: string): number {
|
||||
const leftNumeric = /^\d+$/.test(left);
|
||||
const rightNumeric = /^\d+$/.test(right);
|
||||
|
||||
if (leftNumeric && rightNumeric) {
|
||||
return Number.parseInt(left, 10) - Number.parseInt(right, 10);
|
||||
}
|
||||
if (leftNumeric) {
|
||||
return -1;
|
||||
}
|
||||
if (rightNumeric) {
|
||||
return 1;
|
||||
}
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
export function compareCodexCliVersions(left: string, right: string): number {
|
||||
const parsedLeft = parseSemver(left);
|
||||
const parsedRight = parseSemver(right);
|
||||
if (!parsedLeft || !parsedRight) {
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
if (parsedLeft.major !== parsedRight.major) {
|
||||
return parsedLeft.major - parsedRight.major;
|
||||
}
|
||||
if (parsedLeft.minor !== parsedRight.minor) {
|
||||
return parsedLeft.minor - parsedRight.minor;
|
||||
}
|
||||
if (parsedLeft.patch !== parsedRight.patch) {
|
||||
return parsedLeft.patch - parsedRight.patch;
|
||||
}
|
||||
|
||||
if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
if (parsedLeft.prerelease.length === 0) {
|
||||
return 1;
|
||||
}
|
||||
if (parsedRight.prerelease.length === 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
const leftIdentifier = parsedLeft.prerelease[index];
|
||||
const rightIdentifier = parsedRight.prerelease[index];
|
||||
if (leftIdentifier === undefined) {
|
||||
return -1;
|
||||
}
|
||||
if (rightIdentifier === undefined) {
|
||||
return 1;
|
||||
}
|
||||
const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
|
||||
if (comparison !== 0) {
|
||||
return comparison;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function parseCodexCliVersion(output: string): string | null {
|
||||
const match = CODEX_VERSION_PATTERN.exec(output);
|
||||
if (!match?.[1]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = parseSemver(match[1]);
|
||||
if (!parsed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeCodexVersion(match[1]);
|
||||
}
|
||||
|
||||
export function isCodexCliVersionSupported(version: string): boolean {
|
||||
return compareCodexCliVersions(version, MINIMUM_CODEX_CLI_VERSION) >= 0;
|
||||
}
|
||||
|
||||
export function formatCodexCliUpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Codex CLI ${versionLabel} is too old for T3 Code. Upgrade to v${MINIMUM_CODEX_CLI_VERSION} or newer and restart T3 Code.`;
|
||||
}
|
||||
@@ -1150,7 +1150,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
|
||||
private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
|
||||
const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
|
||||
let release: () => void = () => {};
|
||||
let release!: () => void;
|
||||
const current = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
|
||||
@@ -1108,13 +1108,14 @@ describe("WebSocket Server", () => {
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const workspaceRoot = makeTempDir("t3code-ws-diff-project-");
|
||||
const createdAt = new Date().toISOString();
|
||||
const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "project.create",
|
||||
commandId: "cmd-diff-project-create",
|
||||
projectId: "project-diff",
|
||||
title: "Diff Project",
|
||||
workspaceRoot: "/tmp/ws-diff-project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
@@ -1186,13 +1187,14 @@ describe("WebSocket Server", () => {
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const workspaceRoot = makeTempDir("t3code-ws-project-");
|
||||
const createdAt = new Date().toISOString();
|
||||
const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "project.create",
|
||||
commandId: "cmd-ws-project-create",
|
||||
projectId: "project-1",
|
||||
title: "WS Project",
|
||||
workspaceRoot: "/tmp/ws-project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -72,6 +72,7 @@ import {
|
||||
} from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { expandHomePath } from "./os-jank.ts";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
@@ -194,6 +195,13 @@ function stripRequestTag<T extends { _tag: string }>(body: T) {
|
||||
return Struct.omit(body, ["_tag"]);
|
||||
}
|
||||
|
||||
function messageFromCause(cause: Cause.Cause<unknown>): string {
|
||||
const squashed = Cause.squash(cause);
|
||||
const message =
|
||||
squashed instanceof Error ? squashed.message.trim() : String(squashed).trim();
|
||||
return message.length > 0 ? message : Cause.pretty(cause);
|
||||
}
|
||||
|
||||
export type ServerCoreRuntimeServices =
|
||||
| OrchestrationEngineService
|
||||
| ProjectionSnapshotQuery
|
||||
@@ -298,6 +306,41 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
|
||||
readonly command: ClientOrchestrationCommand;
|
||||
}) {
|
||||
const normalizeProjectWorkspaceRoot = Effect.fnUntraced(function* (workspaceRoot: string) {
|
||||
const normalizedWorkspaceRoot = path.resolve(yield* expandHomePath(workspaceRoot.trim()));
|
||||
const workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!workspaceStat) {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Project directory does not exist: ${normalizedWorkspaceRoot}`,
|
||||
});
|
||||
}
|
||||
if (workspaceStat.type !== "Directory") {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Project path is not a directory: ${normalizedWorkspaceRoot}`,
|
||||
});
|
||||
}
|
||||
return normalizedWorkspaceRoot;
|
||||
});
|
||||
|
||||
if (input.command.type === "project.create") {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (
|
||||
input.command.type === "project.meta.update" &&
|
||||
input.command.workspaceRoot !== undefined
|
||||
) {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (input.command.type !== "thread.turn.start") {
|
||||
return input.command as OrchestrationCommand;
|
||||
}
|
||||
@@ -658,7 +701,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
);
|
||||
}
|
||||
|
||||
const runPromise = yield* Effect.map(Effect.services<never>(), Effect.runPromiseWith);
|
||||
const runtimeServices = yield* Effect.services<
|
||||
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
>();
|
||||
const runPromise = Effect.runPromiseWith(runtimeServices);
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
|
||||
(event) => void Effect.runPromise(onTerminalEvent(event)),
|
||||
@@ -873,7 +919,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
if (request._tag === "Failure") {
|
||||
const errorResponse = yield* encodeResponse({
|
||||
id: "unknown",
|
||||
error: { message: `Invalid request format: ${Cause.pretty(request.cause)}` },
|
||||
error: { message: `Invalid request format: ${messageFromCause(request.cause)}` },
|
||||
});
|
||||
ws.send(errorResponse);
|
||||
return;
|
||||
@@ -883,7 +929,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
if (result._tag === "Failure") {
|
||||
const errorResponse = yield* encodeResponse({
|
||||
id: request.value.id,
|
||||
error: { message: Cause.pretty(result.cause) },
|
||||
error: { message: messageFromCause(result.cause) },
|
||||
});
|
||||
ws.send(errorResponse);
|
||||
return;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
type SupportedLanguages,
|
||||
} from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
import React, {
|
||||
Children,
|
||||
Suspense,
|
||||
isValidElement,
|
||||
@@ -28,6 +28,27 @@ import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
|
||||
class CodeHighlightErrorBoundary extends React.Component<
|
||||
{ fallback: ReactNode; children: ReactNode },
|
||||
{ hasError: boolean }
|
||||
> {
|
||||
constructor(props: { fallback: ReactNode; children: ReactNode }) {
|
||||
super(props);
|
||||
this.state = { hasError: false };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
override render() {
|
||||
if (this.state.hasError) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
interface ChatMarkdownProps {
|
||||
text: string;
|
||||
cwd: string | undefined;
|
||||
@@ -99,6 +120,14 @@ function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
||||
langs: [language as SupportedLanguages],
|
||||
preferredHighlighter: "shiki-js",
|
||||
}).catch((err) => {
|
||||
highlighterPromiseCache.delete(language);
|
||||
if (language === "text") {
|
||||
// "text" itself failed — Shiki cannot initialize at all, surface the error
|
||||
throw err;
|
||||
}
|
||||
// Language not supported by Shiki — fall back to "text"
|
||||
return getHighlighterPromise("text");
|
||||
});
|
||||
highlighterPromiseCache.set(language, promise);
|
||||
return promise;
|
||||
@@ -179,10 +208,14 @@ function SuspenseShikiCodeBlock({
|
||||
}
|
||||
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(
|
||||
() => highlighter.codeToHtml(code, { lang: language, theme: themeName }),
|
||||
[code, highlighter, language, themeName],
|
||||
);
|
||||
const highlightedHtml = useMemo(() => {
|
||||
try {
|
||||
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
|
||||
} catch {
|
||||
// If highlighting fails for this language, render as plain text
|
||||
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
|
||||
}
|
||||
}, [code, highlighter, language, themeName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming) {
|
||||
@@ -235,14 +268,16 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
|
||||
return (
|
||||
<MarkdownCodeBlock code={codeBlock.code}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
<CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</CodeHighlightErrorBoundary>
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
|
||||
@@ -67,6 +67,7 @@ import {
|
||||
derivePendingUserInputs,
|
||||
derivePhase,
|
||||
deriveTimelineEntries,
|
||||
deriveActiveWorkStartedAt,
|
||||
deriveActivePlanState,
|
||||
findLatestProposedPlan,
|
||||
type PendingApproval,
|
||||
@@ -122,7 +123,7 @@ import {
|
||||
} from "../keybindings";
|
||||
import ChatMarkdown from "./ChatMarkdown";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import { Alert, AlertDescription, AlertTitle } from "./ui/alert";
|
||||
import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
|
||||
import {
|
||||
BotIcon,
|
||||
ChevronDownIcon,
|
||||
@@ -223,6 +224,29 @@ function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
return `${formatTimestamp(createdAt)} • ${duration}`;
|
||||
}
|
||||
|
||||
function formatWorkingTimer(startIso: string, endIso: string): string | null {
|
||||
const startedAtMs = Date.parse(startIso);
|
||||
const endedAtMs = Date.parse(endIso);
|
||||
if (!Number.isFinite(startedAtMs) || !Number.isFinite(endedAtMs)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
|
||||
if (elapsedSeconds < 60) {
|
||||
return `${elapsedSeconds}s`;
|
||||
}
|
||||
|
||||
const hours = Math.floor(elapsedSeconds / 3600);
|
||||
const minutes = Math.floor((elapsedSeconds % 3600) / 60);
|
||||
const seconds = elapsedSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
|
||||
}
|
||||
|
||||
return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
|
||||
}
|
||||
|
||||
const LAST_EDITOR_KEY = "t3code:last-editor";
|
||||
const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
@@ -619,6 +643,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
Record<ThreadId, string | null>
|
||||
>({});
|
||||
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
|
||||
const [sendStartedAt, setSendStartedAt] = useState<string | null>(null);
|
||||
const [isConnecting, _setIsConnecting] = useState(false);
|
||||
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
||||
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
|
||||
@@ -805,6 +830,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
};
|
||||
return Object.keys(codexOptions).length > 0 ? { codex: codexOptions } : undefined;
|
||||
}, [selectedCodexFastModeEnabled, selectedEffort, selectedProvider, supportsReasoningEffort]);
|
||||
const providerOptionsForDispatch = useMemo(() => {
|
||||
if (!settings.codexBinaryPath && !settings.codexHomePath) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
codex: {
|
||||
...(settings.codexBinaryPath ? { binaryPath: settings.codexBinaryPath } : {}),
|
||||
...(settings.codexHomePath ? { homePath: settings.codexHomePath } : {}),
|
||||
},
|
||||
};
|
||||
}, [settings.codexBinaryPath, settings.codexHomePath]);
|
||||
const selectedModelForPicker = selectedModel;
|
||||
const modelOptionsByProvider = useMemo(
|
||||
() => getCustomModelOptionsByProvider(settings),
|
||||
@@ -838,6 +874,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const isPreparingWorktree = sendPhase === "preparing-worktree";
|
||||
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const activeWorkStartedAt = deriveActiveWorkStartedAt(
|
||||
activeLatestTurn,
|
||||
activeThread?.session ?? null,
|
||||
sendStartedAt,
|
||||
);
|
||||
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
|
||||
@@ -1943,6 +1984,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return [];
|
||||
});
|
||||
setSendPhase("idle");
|
||||
setSendStartedAt(null);
|
||||
setComposerHighlightedItemId(null);
|
||||
setComposerCursor(promptRef.current.length);
|
||||
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
|
||||
@@ -2082,6 +2124,37 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
};
|
||||
}, [phase]);
|
||||
|
||||
const beginSendPhase = useCallback((nextPhase: Exclude<SendPhase, "idle">) => {
|
||||
setSendStartedAt((current) => current ?? new Date().toISOString());
|
||||
setSendPhase(nextPhase);
|
||||
}, []);
|
||||
|
||||
const resetSendPhase = useCallback(() => {
|
||||
setSendPhase("idle");
|
||||
setSendStartedAt(null);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (sendPhase === "idle") {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
phase === "running" ||
|
||||
activePendingApproval !== null ||
|
||||
activePendingUserInput !== null ||
|
||||
activeThread?.error
|
||||
) {
|
||||
resetSendPhase();
|
||||
}
|
||||
}, [
|
||||
activePendingApproval,
|
||||
activePendingUserInput,
|
||||
activeThread?.error,
|
||||
phase,
|
||||
resetSendPhase,
|
||||
sendPhase,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) return;
|
||||
const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false;
|
||||
@@ -2391,7 +2464,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
setSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
|
||||
beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
|
||||
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
const messageIdForSend = newMessageId();
|
||||
@@ -2442,7 +2515,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
await (async () => {
|
||||
// On first message: lock in branch + create worktree if needed.
|
||||
if (baseBranchForWorktree) {
|
||||
setSendPhase("preparing-worktree");
|
||||
beginSendPhase("preparing-worktree");
|
||||
const newBranch = buildTemporaryWorktreeBranchName();
|
||||
const result = await createWorktreeMutation.mutateAsync({
|
||||
cwd: activeProject.cwd,
|
||||
@@ -2547,7 +2620,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
}
|
||||
|
||||
setSendPhase("sending-turn");
|
||||
beginSendPhase("sending-turn");
|
||||
const turnAttachments = await turnAttachmentsPromise;
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.turn.start",
|
||||
@@ -2564,6 +2637,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
...(selectedModelOptionsForDispatch
|
||||
? { modelOptions: selectedModelOptionsForDispatch }
|
||||
: {}),
|
||||
...(providerOptionsForDispatch
|
||||
? { providerOptions: providerOptionsForDispatch }
|
||||
: {}),
|
||||
provider: selectedProvider,
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
runtimeMode,
|
||||
@@ -2609,7 +2685,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
});
|
||||
sendInFlightRef.current = false;
|
||||
setSendPhase("idle");
|
||||
if (!turnStartSucceeded) {
|
||||
resetSendPhase();
|
||||
}
|
||||
};
|
||||
|
||||
const onInterrupt = async () => {
|
||||
@@ -2796,7 +2874,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
setSendPhase("sending-turn");
|
||||
beginSendPhase("sending-turn");
|
||||
setThreadError(threadIdForSend, null);
|
||||
setOptimisticUserMessages((existing) => [
|
||||
...existing,
|
||||
@@ -2839,13 +2917,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
...(selectedModelOptionsForDispatch
|
||||
? { modelOptions: selectedModelOptionsForDispatch }
|
||||
: {}),
|
||||
...(providerOptionsForDispatch
|
||||
? { providerOptions: providerOptionsForDispatch }
|
||||
: {}),
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
runtimeMode,
|
||||
interactionMode: nextInteractionMode,
|
||||
createdAt: messageCreatedAt,
|
||||
});
|
||||
sendInFlightRef.current = false;
|
||||
setSendPhase("idle");
|
||||
} catch (err) {
|
||||
setOptimisticUserMessages((existing) =>
|
||||
existing.filter((message) => message.id !== messageIdForSend),
|
||||
@@ -2855,19 +2935,22 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
err instanceof Error ? err.message : "Failed to send plan follow-up.",
|
||||
);
|
||||
sendInFlightRef.current = false;
|
||||
setSendPhase("idle");
|
||||
resetSendPhase();
|
||||
}
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
beginSendPhase,
|
||||
forceStickToBottom,
|
||||
isConnecting,
|
||||
isSendBusy,
|
||||
isServerThread,
|
||||
persistThreadSettingsForNextTurn,
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
providerOptionsForDispatch,
|
||||
selectedProvider,
|
||||
setComposerDraftInteractionMode,
|
||||
setThreadError,
|
||||
@@ -2902,10 +2985,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
setSendPhase("sending-turn");
|
||||
beginSendPhase("sending-turn");
|
||||
const finish = () => {
|
||||
sendInFlightRef.current = false;
|
||||
setSendPhase("idle");
|
||||
resetSendPhase();
|
||||
};
|
||||
|
||||
await api.orchestration
|
||||
@@ -2922,8 +3005,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
worktreePath: activeThread.worktreePath,
|
||||
createdAt,
|
||||
})
|
||||
.then(() =>
|
||||
api.orchestration.dispatchCommand({
|
||||
.then(() => {
|
||||
return api.orchestration.dispatchCommand({
|
||||
type: "thread.turn.start",
|
||||
commandId: newCommandId(),
|
||||
threadId: nextThreadId,
|
||||
@@ -2938,12 +3021,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
...(selectedModelOptionsForDispatch
|
||||
? { modelOptions: selectedModelOptionsForDispatch }
|
||||
: {}),
|
||||
...(providerOptionsForDispatch
|
||||
? { providerOptions: providerOptionsForDispatch }
|
||||
: {}),
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
runtimeMode,
|
||||
interactionMode: "default",
|
||||
createdAt,
|
||||
}),
|
||||
)
|
||||
});
|
||||
})
|
||||
.then(() => api.orchestration.getSnapshot())
|
||||
.then((snapshot) => {
|
||||
syncServerReadModel(snapshot);
|
||||
@@ -2978,13 +3064,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeProject,
|
||||
activeProposedPlan,
|
||||
activeThread,
|
||||
beginSendPhase,
|
||||
isConnecting,
|
||||
isSendBusy,
|
||||
isServerThread,
|
||||
navigate,
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
providerOptionsForDispatch,
|
||||
selectedProvider,
|
||||
settings.enableAssistantStreaming,
|
||||
syncServerReadModel,
|
||||
@@ -3323,6 +3412,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeThreadId={activeThread.id}
|
||||
activeThreadTitle={activeThread.title}
|
||||
activeProjectName={activeProject?.name}
|
||||
isGitRepo={isGitRepo}
|
||||
openInCwd={activeThread.worktreePath ?? activeProject?.cwd ?? null}
|
||||
activeProjectScripts={activeProject?.scripts}
|
||||
preferredScriptId={
|
||||
@@ -3344,7 +3434,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
{/* Error banner */}
|
||||
<ProviderHealthBanner status={activeProviderStatus} />
|
||||
<ThreadErrorBanner error={activeThread.error} />
|
||||
<ThreadErrorBanner
|
||||
error={activeThread.error}
|
||||
onDismiss={() => setThreadError(activeThread.id, null)}
|
||||
/>
|
||||
<PlanModePanel activePlan={activePlan} />
|
||||
|
||||
{/* Messages */}
|
||||
@@ -3366,8 +3459,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
key={activeThread.id}
|
||||
hasMessages={timelineEntries.length > 0}
|
||||
isWorking={isWorking}
|
||||
activeTurnInProgress={!latestTurnSettled}
|
||||
activeTurnStartedAt={activeLatestTurn?.startedAt ?? null}
|
||||
activeTurnInProgress={isWorking || !latestTurnSettled}
|
||||
activeTurnStartedAt={activeWorkStartedAt}
|
||||
scrollContainer={messagesScrollElement}
|
||||
timelineEntries={timelineEntries}
|
||||
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
|
||||
@@ -3396,7 +3489,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
data-chat-composer-form="true"
|
||||
>
|
||||
<div
|
||||
className={`group rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring ${
|
||||
className={`group rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring/45 ${
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border"
|
||||
}`}
|
||||
onDragEnter={onComposerDragEnter}
|
||||
@@ -3903,6 +3996,7 @@ interface ChatHeaderProps {
|
||||
activeThreadId: ThreadId;
|
||||
activeThreadTitle: string;
|
||||
activeProjectName: string | undefined;
|
||||
isGitRepo: boolean;
|
||||
openInCwd: string | null;
|
||||
activeProjectScripts: ProjectScript[] | undefined;
|
||||
preferredScriptId: string | null;
|
||||
@@ -3921,6 +4015,7 @@ const ChatHeader = memo(function ChatHeader({
|
||||
activeThreadId,
|
||||
activeThreadTitle,
|
||||
activeProjectName,
|
||||
isGitRepo,
|
||||
openInCwd,
|
||||
activeProjectScripts,
|
||||
preferredScriptId,
|
||||
@@ -3949,6 +4044,11 @@ const ChatHeader = memo(function ChatHeader({
|
||||
{activeProjectName}
|
||||
</Badge>
|
||||
)}
|
||||
{activeProjectName && !isGitRepo && (
|
||||
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
|
||||
No Git
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center justify-end gap-2 @sm/header-actions:gap-3">
|
||||
{activeProjectScripts && (
|
||||
@@ -3979,15 +4079,18 @@ const ChatHeader = memo(function ChatHeader({
|
||||
aria-label="Toggle diff panel"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={!isGitRepo}
|
||||
>
|
||||
<DiffIcon className="size-3" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{diffToggleShortcutLabel
|
||||
? `Toggle diff panel (${diffToggleShortcutLabel})`
|
||||
: "Toggle diff panel"}
|
||||
{!isGitRepo
|
||||
? "Diff panel is unavailable because this project is not a git repository."
|
||||
: diffToggleShortcutLabel
|
||||
? `Toggle diff panel (${diffToggleShortcutLabel})`
|
||||
: "Toggle diff panel"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
@@ -3995,7 +4098,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">
|
||||
@@ -4004,6 +4113,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>
|
||||
);
|
||||
@@ -4919,23 +5040,43 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
{visibleEntries.map((workEntry) => (
|
||||
<div key={`work-row:${workEntry.id}`} className="flex items-start gap-2 py-0.5">
|
||||
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
||||
<p
|
||||
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
|
||||
>
|
||||
{workEntry.detail ? (
|
||||
<>
|
||||
{workEntry.label}
|
||||
<span
|
||||
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
|
||||
<div className="min-w-0 flex-1 py-[2px]">
|
||||
<p className={`text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}>
|
||||
{workEntry.label}
|
||||
</p>
|
||||
{workEntry.command && (
|
||||
<pre className="mt-1 overflow-x-auto rounded-md border border-border/70 bg-background/80 px-2 py-1 font-mono text-[11px] leading-relaxed text-foreground/80">
|
||||
{workEntry.command}
|
||||
</pre>
|
||||
)}
|
||||
{workEntry.changedFiles && workEntry.changedFiles.length > 0 && (
|
||||
<div className="mt-1 flex flex-wrap gap-1">
|
||||
{workEntry.changedFiles.slice(0, 6).map((filePath) => (
|
||||
<span
|
||||
key={`${workEntry.id}:${filePath}`}
|
||||
className="rounded-md border border-border/70 bg-background/65 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/85"
|
||||
title={filePath}
|
||||
>
|
||||
{filePath}
|
||||
</span>
|
||||
))}
|
||||
{workEntry.changedFiles.length > 6 && (
|
||||
<span className="px-1 text-[10px] text-muted-foreground/65">
|
||||
+{workEntry.changedFiles.length - 6} more
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{workEntry.detail &&
|
||||
(!workEntry.command || workEntry.detail !== workEntry.command) && (
|
||||
<p
|
||||
className="mt-1 text-[11px] leading-relaxed text-muted-foreground/75"
|
||||
title={workEntry.detail}
|
||||
>
|
||||
{workEntry.detail}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
workEntry.label
|
||||
)}
|
||||
</p>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -5119,14 +5260,18 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
)}
|
||||
|
||||
{row.kind === "working" && (
|
||||
<div className="flex items-center gap-2 py-0.5 pl-1.5">
|
||||
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
||||
<div className="flex items-center pt-1">
|
||||
<div className="py-0.5 pl-1.5">
|
||||
<div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70">
|
||||
<span className="inline-flex items-center gap-[3px]">
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
|
||||
</span>
|
||||
<span>
|
||||
{row.createdAt
|
||||
? `Working for ${formatWorkingTimer(row.createdAt, nowIso) ?? "0s"}`
|
||||
: "Working..."}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import { type WheelEvent as ReactWheelEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
@@ -175,6 +176,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
|
||||
);
|
||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null));
|
||||
const isGitRepo = gitBranchesQuery.data?.isRepo ?? true;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
@@ -250,6 +253,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
|
||||
enabled: isGitRepo,
|
||||
}),
|
||||
);
|
||||
const selectedTurnCheckpointDiff = selectedTurn
|
||||
@@ -530,6 +534,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Select a thread to inspect turn diffs.
|
||||
</div>
|
||||
) : !isGitRepo ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Turn diffs are unavailable because this project is not a git repository.
|
||||
</div>
|
||||
) : orderedTurnDiffSummaries.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
No completed turns yet.
|
||||
|
||||
@@ -42,7 +42,7 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, { kind: "open_pr", label: "Open PR", disabled: false });
|
||||
assert.deepInclude(quick, { kind: "open_pr", label: "View PR", disabled: false });
|
||||
});
|
||||
|
||||
it("buildMenuItems disables commit/push and enables open PR", () => {
|
||||
@@ -78,7 +78,7 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
},
|
||||
{
|
||||
id: "pr",
|
||||
label: "Open PR",
|
||||
label: "View PR",
|
||||
disabled: false,
|
||||
icon: "pr",
|
||||
kind: "open_pr",
|
||||
@@ -199,7 +199,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
},
|
||||
{
|
||||
id: "pr",
|
||||
label: "Open PR",
|
||||
label: "View PR",
|
||||
disabled: false,
|
||||
icon: "pr",
|
||||
kind: "open_pr",
|
||||
@@ -547,7 +547,7 @@ describe("when: branch has no upstream configured", () => {
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "open_pr",
|
||||
label: "Open PR",
|
||||
label: "View PR",
|
||||
disabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -151,7 +151,7 @@ export function buildMenuItems(
|
||||
hasOpenPr
|
||||
? {
|
||||
id: "pr",
|
||||
label: "Open PR",
|
||||
label: "View PR",
|
||||
disabled: !canOpenPr,
|
||||
icon: "pr",
|
||||
kind: "open_pr",
|
||||
@@ -216,7 +216,7 @@ export function resolveQuickAction(
|
||||
if (!gitStatus.hasUpstream) {
|
||||
if (!isAhead) {
|
||||
if (hasOpenPr) {
|
||||
return { label: "Open PR", disabled: false, kind: "open_pr" };
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
return {
|
||||
label: "Push",
|
||||
@@ -266,7 +266,7 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (hasOpenPr && gitStatus.hasUpstream) {
|
||||
return { label: "Open PR", disabled: false, kind: "open_pr" };
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -98,7 +98,7 @@ function getMenuActionDisabledReason(
|
||||
}
|
||||
|
||||
if (hasOpenPr) {
|
||||
return "Open PR is currently unavailable.";
|
||||
return "View PR is currently unavailable.";
|
||||
}
|
||||
if (!hasBranch) {
|
||||
return "Detached HEAD: checkout a branch before creating a PR.";
|
||||
@@ -374,12 +374,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
},
|
||||
}
|
||||
: shouldOfferOpenPrCta
|
||||
? {
|
||||
actionProps: {
|
||||
children: "Open PR",
|
||||
onClick: () => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
? {
|
||||
actionProps: {
|
||||
children: "View PR",
|
||||
onClick: () => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
closeResultToast();
|
||||
void api.shell.openExternal(prUrl);
|
||||
},
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import {
|
||||
ArrowLeftIcon,
|
||||
ChevronRightIcon,
|
||||
FolderIcon,
|
||||
GitPullRequestIcon,
|
||||
PlusIcon,
|
||||
RocketIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
TerminalIcon,
|
||||
} from "lucide-react";
|
||||
@@ -17,7 +20,7 @@ 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";
|
||||
@@ -225,7 +228,7 @@ function getServerHttpOrigin(): string {
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `ws://${window.location.hostname}:${window.location.port}`;
|
||||
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`;
|
||||
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
|
||||
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
|
||||
try {
|
||||
@@ -278,6 +281,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 +297,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<
|
||||
@@ -486,6 +492,7 @@ export default function Sidebar() {
|
||||
const finishAddingProject = () => {
|
||||
setIsAddingProject(false);
|
||||
setNewCwd("");
|
||||
setAddProjectError(null);
|
||||
setAddingProject(false);
|
||||
};
|
||||
|
||||
@@ -499,8 +506,8 @@ export default function Sidebar() {
|
||||
const projectId = newProjectId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
||||
const projectCreated = await api.orchestration
|
||||
.dispatchCommand({
|
||||
try {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "project.create",
|
||||
commandId: newCommandId(),
|
||||
projectId,
|
||||
@@ -508,11 +515,14 @@ export default function Sidebar() {
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
createdAt,
|
||||
})
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
if (projectCreated) {
|
||||
});
|
||||
await handleNewThread(projectId).catch(() => undefined);
|
||||
} catch (error) {
|
||||
setIsAddingProject(false);
|
||||
setAddProjectError(
|
||||
error instanceof Error ? error.message : "An error occurred while adding the project.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
finishAddingProject();
|
||||
},
|
||||
@@ -535,6 +545,8 @@ export default function Sidebar() {
|
||||
}
|
||||
if (pickedPath) {
|
||||
await addProjectFromPath(pickedPath);
|
||||
} else {
|
||||
addProjectInputRef.current?.focus();
|
||||
}
|
||||
setIsPickingFolder(false);
|
||||
};
|
||||
@@ -1019,6 +1031,95 @@ export default function Sidebar() {
|
||||
|
||||
<SidebarContent className="gap-0">
|
||||
<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"
|
||||
className="inline-flex size-5 items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
|
||||
onClick={() => {
|
||||
setAddingProject((prev) => !prev);
|
||||
setAddProjectError(null);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PlusIcon className="size-3.5" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">Add project</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{addingProject && (
|
||||
<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
|
||||
@@ -1282,68 +1383,37 @@ export default function Sidebar() {
|
||||
|
||||
{projects.length === 0 && !addingProject && (
|
||||
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
|
||||
No projects yet.
|
||||
<br />
|
||||
Add one to get started.
|
||||
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>
|
||||
</>
|
||||
);
|
||||
|
||||
+22
-1
@@ -263,9 +263,30 @@ label:has(> select#reasoning-effort) select {
|
||||
margin: 0.65rem 0;
|
||||
}
|
||||
|
||||
.chat-markdown ul,
|
||||
.chat-markdown ul {
|
||||
padding-left: 1.25rem;
|
||||
list-style-type: disc;
|
||||
}
|
||||
|
||||
.chat-markdown ol {
|
||||
padding-left: 1.25rem;
|
||||
list-style-type: decimal;
|
||||
}
|
||||
|
||||
.chat-markdown ul ul {
|
||||
list-style-type: circle;
|
||||
}
|
||||
|
||||
.chat-markdown ul ul ul {
|
||||
list-style-type: square;
|
||||
}
|
||||
|
||||
.chat-markdown ol ol {
|
||||
list-style-type: lower-alpha;
|
||||
}
|
||||
|
||||
.chat-markdown ol ol ol {
|
||||
list-style-type: lower-roman;
|
||||
}
|
||||
|
||||
.chat-markdown li + li {
|
||||
|
||||
@@ -12,6 +12,7 @@ interface CheckpointDiffQueryInput {
|
||||
fromTurnCount: number | null;
|
||||
toTurnCount: number | null;
|
||||
cacheScope?: string | null;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export const providerQueryKeys = {
|
||||
@@ -52,6 +53,33 @@ function asCheckpointErrorMessage(error: unknown): string {
|
||||
return "";
|
||||
}
|
||||
|
||||
function normalizeCheckpointErrorMessage(error: unknown): string {
|
||||
const message = asCheckpointErrorMessage(error).trim();
|
||||
if (message.length === 0) {
|
||||
return "Failed to load checkpoint diff.";
|
||||
}
|
||||
|
||||
const lower = message.toLowerCase();
|
||||
if (lower.includes("not a git repository")) {
|
||||
return "Turn diffs are unavailable because this project is not a git repository.";
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("checkpoint unavailable for thread") ||
|
||||
lower.includes("checkpoint invariant violation")
|
||||
) {
|
||||
const separatorIndex = message.indexOf(":");
|
||||
if (separatorIndex >= 0) {
|
||||
const detail = message.slice(separatorIndex + 1).trim();
|
||||
if (detail.length > 0) {
|
||||
return detail;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
function isCheckpointTemporarilyUnavailable(error: unknown): boolean {
|
||||
const message = asCheckpointErrorMessage(error).toLowerCase();
|
||||
return (
|
||||
@@ -71,12 +99,16 @@ export function checkpointDiffQueryOptions(input: CheckpointDiffQueryInput) {
|
||||
if (!input.threadId || decodedRequest._tag === "None") {
|
||||
throw new Error("Checkpoint diff is unavailable.");
|
||||
}
|
||||
if (decodedRequest.value.kind === "fullThreadDiff") {
|
||||
return api.orchestration.getFullThreadDiff(decodedRequest.value.input);
|
||||
try {
|
||||
if (decodedRequest.value.kind === "fullThreadDiff") {
|
||||
return await api.orchestration.getFullThreadDiff(decodedRequest.value.input);
|
||||
}
|
||||
return await api.orchestration.getTurnDiff(decodedRequest.value.input);
|
||||
} catch (error) {
|
||||
throw new Error(normalizeCheckpointErrorMessage(error), { cause: error });
|
||||
}
|
||||
return api.orchestration.getTurnDiff(decodedRequest.value.input);
|
||||
},
|
||||
enabled: !!input.threadId && decodedRequest._tag === "Some",
|
||||
enabled: (input.enabled ?? true) && !!input.threadId && decodedRequest._tag === "Some",
|
||||
staleTime: Infinity,
|
||||
retry: (failureCount, error) => {
|
||||
if (isCheckpointTemporarilyUnavailable(error)) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { EventId, MessageId, TurnId, type OrchestrationThreadActivity } from "@t
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
deriveActiveWorkStartedAt,
|
||||
deriveActivePlanState,
|
||||
PROVIDER_OPTIONS,
|
||||
derivePendingApprovals,
|
||||
@@ -430,6 +431,54 @@ describe("deriveWorkLogEntries", () => {
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["first", "second"]);
|
||||
});
|
||||
|
||||
it("extracts command text for command tool activities", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "command-tool",
|
||||
kind: "tool.completed",
|
||||
summary: "Command run complete",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
data: {
|
||||
item: {
|
||||
command: ["bun", "run", "lint"],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entry?.command).toBe("bun run lint");
|
||||
});
|
||||
|
||||
it("extracts changed file paths for file-change tool activities", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "file-tool",
|
||||
kind: "tool.completed",
|
||||
summary: "File change complete",
|
||||
payload: {
|
||||
itemType: "file_change",
|
||||
data: {
|
||||
item: {
|
||||
changes: [
|
||||
{ path: "apps/web/src/components/ChatView.tsx" },
|
||||
{ filename: "apps/web/src/session-logic.ts" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entry?.changedFiles).toEqual([
|
||||
"apps/web/src/components/ChatView.tsx",
|
||||
"apps/web/src/session-logic.ts",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTimelineEntries", () => {
|
||||
@@ -542,6 +591,54 @@ describe("isLatestTurnSettled", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveActiveWorkStartedAt", () => {
|
||||
const latestTurn = {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
startedAt: "2026-02-27T21:10:00.000Z",
|
||||
completedAt: "2026-02-27T21:10:06.000Z",
|
||||
} as const;
|
||||
|
||||
it("prefers the in-flight turn start when the latest turn is not settled", () => {
|
||||
expect(
|
||||
deriveActiveWorkStartedAt(
|
||||
latestTurn,
|
||||
{
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
},
|
||||
"2026-02-27T21:11:00.000Z",
|
||||
),
|
||||
).toBe("2026-02-27T21:10:00.000Z");
|
||||
});
|
||||
|
||||
it("falls back to sendStartedAt once the latest turn is settled", () => {
|
||||
expect(
|
||||
deriveActiveWorkStartedAt(
|
||||
latestTurn,
|
||||
{
|
||||
orchestrationStatus: "ready",
|
||||
activeTurnId: undefined,
|
||||
},
|
||||
"2026-02-27T21:11:00.000Z",
|
||||
),
|
||||
).toBe("2026-02-27T21:11:00.000Z");
|
||||
});
|
||||
|
||||
it("uses sendStartedAt for a fresh send after the prior turn completed", () => {
|
||||
expect(
|
||||
deriveActiveWorkStartedAt(
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
startedAt: "2026-02-27T21:10:00.000Z",
|
||||
completedAt: "2026-02-27T21:10:06.000Z",
|
||||
},
|
||||
null,
|
||||
"2026-02-27T21:11:00.000Z",
|
||||
),
|
||||
).toBe("2026-02-27T21:11:00.000Z");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PROVIDER_OPTIONS", () => {
|
||||
it("keeps Claude Code and Cursor visible as unavailable placeholders in the stack base", () => {
|
||||
const claude = PROVIDER_OPTIONS.find((option) => option.value === "claudeCode");
|
||||
|
||||
@@ -27,6 +27,8 @@ export interface WorkLogEntry {
|
||||
createdAt: string;
|
||||
label: string;
|
||||
detail?: string;
|
||||
command?: string;
|
||||
changedFiles?: ReadonlyArray<string>;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
}
|
||||
|
||||
@@ -111,9 +113,12 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str
|
||||
return formatDuration(endedAt - startedAt);
|
||||
}
|
||||
|
||||
type LatestTurnTiming = Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt">;
|
||||
type SessionActivityState = Pick<ThreadSession, "orchestrationStatus" | "activeTurnId">;
|
||||
|
||||
export function isLatestTurnSettled(
|
||||
latestTurn: Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt"> | null,
|
||||
session: Pick<ThreadSession, "orchestrationStatus" | "activeTurnId"> | null,
|
||||
latestTurn: LatestTurnTiming | null,
|
||||
session: SessionActivityState | null,
|
||||
): boolean {
|
||||
if (!latestTurn?.startedAt) return false;
|
||||
if (!latestTurn.completedAt) return false;
|
||||
@@ -122,6 +127,17 @@ export function isLatestTurnSettled(
|
||||
return true;
|
||||
}
|
||||
|
||||
export function deriveActiveWorkStartedAt(
|
||||
latestTurn: LatestTurnTiming | null,
|
||||
session: SessionActivityState | null,
|
||||
sendStartedAt: string | null,
|
||||
): string | null {
|
||||
if (!isLatestTurnSettled(latestTurn, session)) {
|
||||
return latestTurn?.startedAt ?? sendStartedAt;
|
||||
}
|
||||
return sendStartedAt;
|
||||
}
|
||||
|
||||
function requestKindFromRequestType(
|
||||
requestType: unknown,
|
||||
): PendingApproval["requestKind"] | null {
|
||||
@@ -401,6 +417,8 @@ export function deriveWorkLogEntries(
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const command = extractToolCommand(payload);
|
||||
const changedFiles = extractChangedFiles(payload);
|
||||
const entry: WorkLogEntry = {
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
@@ -410,10 +428,125 @@ export function deriveWorkLogEntries(
|
||||
if (payload && typeof payload.detail === "string" && payload.detail.length > 0) {
|
||||
entry.detail = payload.detail;
|
||||
}
|
||||
if (command) {
|
||||
entry.command = command;
|
||||
}
|
||||
if (changedFiles.length > 0) {
|
||||
entry.changedFiles = changedFiles;
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
|
||||
}
|
||||
|
||||
function asTrimmedString(value: unknown): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeCommandValue(value: unknown): string | null {
|
||||
const direct = asTrimmedString(value);
|
||||
if (direct) {
|
||||
return direct;
|
||||
}
|
||||
if (!Array.isArray(value)) {
|
||||
return null;
|
||||
}
|
||||
const parts = value
|
||||
.map((entry) => asTrimmedString(entry))
|
||||
.filter((entry): entry is string => entry !== null);
|
||||
return parts.length > 0 ? parts.join(" ") : null;
|
||||
}
|
||||
|
||||
function extractToolCommand(payload: Record<string, unknown> | null): string | null {
|
||||
const data = asRecord(payload?.data);
|
||||
const item = asRecord(data?.item);
|
||||
const itemResult = asRecord(item?.result);
|
||||
const itemInput = asRecord(item?.input);
|
||||
const candidates = [
|
||||
normalizeCommandValue(item?.command),
|
||||
normalizeCommandValue(itemInput?.command),
|
||||
normalizeCommandValue(itemResult?.command),
|
||||
normalizeCommandValue(data?.command),
|
||||
];
|
||||
return candidates.find((candidate) => candidate !== null) ?? null;
|
||||
}
|
||||
|
||||
function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {
|
||||
const normalized = asTrimmedString(value);
|
||||
if (!normalized || seen.has(normalized)) {
|
||||
return;
|
||||
}
|
||||
seen.add(normalized);
|
||||
target.push(normalized);
|
||||
}
|
||||
|
||||
function collectChangedFiles(
|
||||
value: unknown,
|
||||
target: string[],
|
||||
seen: Set<string>,
|
||||
depth: number,
|
||||
) {
|
||||
if (depth > 4 || target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
collectChangedFiles(entry, target, seen, depth + 1);
|
||||
if (target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const record = asRecord(value);
|
||||
if (!record) {
|
||||
return;
|
||||
}
|
||||
|
||||
pushChangedFile(target, seen, record.path);
|
||||
pushChangedFile(target, seen, record.filePath);
|
||||
pushChangedFile(target, seen, record.relativePath);
|
||||
pushChangedFile(target, seen, record.filename);
|
||||
pushChangedFile(target, seen, record.newPath);
|
||||
pushChangedFile(target, seen, record.oldPath);
|
||||
|
||||
for (const nestedKey of [
|
||||
"item",
|
||||
"result",
|
||||
"input",
|
||||
"data",
|
||||
"changes",
|
||||
"files",
|
||||
"edits",
|
||||
"patch",
|
||||
"patches",
|
||||
"operations",
|
||||
]) {
|
||||
if (!(nestedKey in record)) {
|
||||
continue;
|
||||
}
|
||||
collectChangedFiles(record[nestedKey], target, seen, depth + 1);
|
||||
if (target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function extractChangedFiles(payload: Record<string, unknown> | null): string[] {
|
||||
const data = asRecord(payload?.data);
|
||||
const changedFiles: string[] = [];
|
||||
collectChangedFiles(data, changedFiles, new Set<string>(), 0);
|
||||
return changedFiles;
|
||||
}
|
||||
|
||||
function compareActivitiesByOrder(
|
||||
left: OrchestrationThreadActivity,
|
||||
right: OrchestrationThreadActivity,
|
||||
|
||||
@@ -44,7 +44,7 @@ export class WsTransport {
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `ws://${window.location.hostname}:${window.location.port}`);
|
||||
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`);
|
||||
this.connect();
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
},
|
||||
"apps/desktop": {
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.5",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
@@ -43,7 +43,7 @@
|
||||
},
|
||||
"apps/server": {
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.5",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
@@ -72,7 +72,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.5",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@lexical/react": "^0.41.0",
|
||||
@@ -116,7 +116,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.5",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
},
|
||||
|
||||
@@ -12,6 +12,8 @@ This document covers how to run desktop releases from one tag, first without sig
|
||||
- Linux `x64` AppImage
|
||||
- Windows `x64` NSIS installer
|
||||
- Publishes one GitHub Release with all produced files.
|
||||
- Versions with a suffix after `X.Y.Z` (for example `1.2.3-alpha.1`) are published as GitHub prereleases.
|
||||
- Only plain `X.Y.Z` releases are marked as the repository's latest release.
|
||||
- Includes Electron auto-update metadata (for example `latest*.yml` and `*.blockmap`) in release assets.
|
||||
- Publishes the CLI package (`apps/server`, npm package `t3`) with OIDC trusted publishing.
|
||||
- Signing is optional and auto-detected per platform from secrets.
|
||||
@@ -34,6 +36,9 @@ This document covers how to run desktop releases from one tag, first without sig
|
||||
- platform installers (`.exe`, `.dmg`, `.AppImage`, plus macOS `.zip` for Squirrel.Mac update payloads)
|
||||
- `latest*.yml` metadata
|
||||
- `*.blockmap` files (used for differential downloads)
|
||||
- macOS metadata note:
|
||||
- `electron-updater` reads `latest-mac.yml` for both Intel and Apple Silicon.
|
||||
- The workflow merges the per-arch mac manifests into one `latest-mac.yml` before publishing the GitHub Release.
|
||||
|
||||
## 0) npm OIDC trusted publishing setup (CLI)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"version": "0.0.5",
|
||||
"private": true,
|
||||
"files": [
|
||||
"dist"
|
||||
|
||||
@@ -45,6 +45,13 @@ 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),
|
||||
homePath: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
const ProviderStartOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexProviderStartOptions),
|
||||
});
|
||||
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
|
||||
export type RuntimeMode = typeof RuntimeMode.Type;
|
||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
@@ -366,6 +373,7 @@ export const ThreadTurnStartCommand = Schema.Struct({
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
|
||||
modelOptions: Schema.optional(ProviderModelOptions),
|
||||
providerOptions: Schema.optional(ProviderStartOptions),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
@@ -388,6 +396,7 @@ const ClientThreadTurnStartCommand = Schema.Struct({
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
|
||||
modelOptions: Schema.optional(ProviderModelOptions),
|
||||
providerOptions: Schema.optional(ProviderStartOptions),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
@@ -668,6 +677,7 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
|
||||
modelOptions: Schema.optional(ProviderModelOptions),
|
||||
providerOptions: Schema.optional(ProviderStartOptions),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
|
||||
@@ -53,9 +53,10 @@ const CodexProviderStartOptions = Schema.Struct({
|
||||
homePath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
|
||||
const ProviderStartOptions = Schema.Struct({
|
||||
export const ProviderStartOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexProviderStartOptions),
|
||||
});
|
||||
export type ProviderStartOptions = typeof ProviderStartOptions.Type;
|
||||
|
||||
export const ProviderSessionStartInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
"types": "./src/logging.ts",
|
||||
"import": "./src/logging.ts"
|
||||
},
|
||||
"./shell": {
|
||||
"types": "./src/shell.ts",
|
||||
"import": "./src/shell.ts"
|
||||
},
|
||||
"./Net": {
|
||||
"types": "./src/Net.ts",
|
||||
"import": "./src/Net.ts"
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { extractPathFromShellOutput, readPathFromLoginShell } from "./shell";
|
||||
|
||||
describe("extractPathFromShellOutput", () => {
|
||||
it("extracts the path between capture markers", () => {
|
||||
expect(
|
||||
extractPathFromShellOutput("__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\n"),
|
||||
).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("ignores shell startup noise around the capture markers", () => {
|
||||
expect(
|
||||
extractPathFromShellOutput(
|
||||
"Welcome to fish\n__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\nBye\n",
|
||||
),
|
||||
).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("returns null when the markers are missing", () => {
|
||||
expect(extractPathFromShellOutput("/opt/homebrew/bin /usr/bin")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("readPathFromLoginShell", () => {
|
||||
it("uses a shell-agnostic printenv PATH probe", () => {
|
||||
const execFile = vi.fn<
|
||||
(
|
||||
file: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: { encoding: "utf8"; timeout: number },
|
||||
) => string
|
||||
>(() => "__T3CODE_PATH_START__\n/a:/b\n__T3CODE_PATH_END__\n");
|
||||
|
||||
expect(readPathFromLoginShell("/opt/homebrew/bin/fish", execFile)).toBe("/a:/b");
|
||||
expect(execFile).toHaveBeenCalledTimes(1);
|
||||
|
||||
const firstCall = execFile.mock.calls[0] as
|
||||
| [string, ReadonlyArray<string>, { encoding: "utf8"; timeout: number }]
|
||||
| undefined;
|
||||
expect(firstCall).toBeDefined();
|
||||
if (!firstCall) {
|
||||
throw new Error("Expected execFile to be called");
|
||||
}
|
||||
|
||||
const [shell, args, options] = firstCall;
|
||||
expect(shell).toBe("/opt/homebrew/bin/fish");
|
||||
expect(args).toHaveLength(2);
|
||||
expect(args?.[0]).toBe("-ilc");
|
||||
expect(args?.[1]).toContain("printenv PATH");
|
||||
expect(args?.[1]).toContain("__T3CODE_PATH_START__");
|
||||
expect(args?.[1]).toContain("__T3CODE_PATH_END__");
|
||||
expect(options).toEqual({ encoding: "utf8", timeout: 5000 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
const PATH_CAPTURE_START = "__T3CODE_PATH_START__";
|
||||
const PATH_CAPTURE_END = "__T3CODE_PATH_END__";
|
||||
const PATH_CAPTURE_COMMAND = [
|
||||
`printf '%s\n' '${PATH_CAPTURE_START}'`,
|
||||
"printenv PATH",
|
||||
`printf '%s\n' '${PATH_CAPTURE_END}'`,
|
||||
].join("; ");
|
||||
|
||||
type ExecFileSyncLike = (
|
||||
file: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: { encoding: "utf8"; timeout: number },
|
||||
) => string;
|
||||
|
||||
export function extractPathFromShellOutput(output: string): string | null {
|
||||
const startIndex = output.indexOf(PATH_CAPTURE_START);
|
||||
if (startIndex === -1) return null;
|
||||
|
||||
const valueStartIndex = startIndex + PATH_CAPTURE_START.length;
|
||||
const endIndex = output.indexOf(PATH_CAPTURE_END, valueStartIndex);
|
||||
if (endIndex === -1) return null;
|
||||
|
||||
const pathValue = output.slice(valueStartIndex, endIndex).trim();
|
||||
return pathValue.length > 0 ? pathValue : null;
|
||||
}
|
||||
|
||||
export function readPathFromLoginShell(
|
||||
shell: string,
|
||||
execFile: ExecFileSyncLike = execFileSync,
|
||||
): string | undefined {
|
||||
const output = execFile(shell, ["-ilc", PATH_CAPTURE_COMMAND], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
return extractPathFromShellOutput(output) ?? undefined;
|
||||
}
|
||||
@@ -455,6 +455,11 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
stderr: "inherit",
|
||||
env,
|
||||
extendEnv: false,
|
||||
// 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.
|
||||
detached: false,
|
||||
forceKillAfter: "1500 millis",
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
mergeMacUpdateManifests,
|
||||
parseMacUpdateManifest,
|
||||
serializeMacUpdateManifest,
|
||||
} from "./merge-mac-update-manifests.ts";
|
||||
|
||||
describe("merge-mac-update-manifests", () => {
|
||||
it("merges arm64 and x64 macOS update manifests into one multi-arch manifest", () => {
|
||||
const arm64 = parseMacUpdateManifest(
|
||||
`version: 0.0.4
|
||||
files:
|
||||
- url: T3-Code-0.0.4-arm64.zip
|
||||
sha512: arm64zip
|
||||
size: 125621344
|
||||
- url: T3-Code-0.0.4-arm64.dmg
|
||||
sha512: arm64dmg
|
||||
size: 131754935
|
||||
path: T3-Code-0.0.4-arm64.zip
|
||||
sha512: arm64zip
|
||||
releaseDate: '2026-03-07T10:32:14.587Z'
|
||||
`,
|
||||
"latest-mac.yml",
|
||||
);
|
||||
|
||||
const x64 = parseMacUpdateManifest(
|
||||
`version: 0.0.4
|
||||
files:
|
||||
- url: T3-Code-0.0.4-x64.zip
|
||||
sha512: x64zip
|
||||
size: 132000112
|
||||
- url: T3-Code-0.0.4-x64.dmg
|
||||
sha512: x64dmg
|
||||
size: 138148807
|
||||
path: T3-Code-0.0.4-x64.zip
|
||||
sha512: x64zip
|
||||
releaseDate: '2026-03-07T10:36:07.540Z'
|
||||
`,
|
||||
"latest-mac-x64.yml",
|
||||
);
|
||||
|
||||
const merged = mergeMacUpdateManifests(arm64, x64);
|
||||
|
||||
assert.equal(merged.version, "0.0.4");
|
||||
assert.equal(merged.releaseDate, "2026-03-07T10:36:07.540Z");
|
||||
assert.deepStrictEqual(
|
||||
merged.files.map((file) => file.url),
|
||||
[
|
||||
"T3-Code-0.0.4-arm64.zip",
|
||||
"T3-Code-0.0.4-arm64.dmg",
|
||||
"T3-Code-0.0.4-x64.zip",
|
||||
"T3-Code-0.0.4-x64.dmg",
|
||||
],
|
||||
);
|
||||
|
||||
const serialized = serializeMacUpdateManifest(merged);
|
||||
assert.ok(!serialized.includes("path:"));
|
||||
assert.equal((serialized.match(/- url:/g) ?? []).length, 4);
|
||||
});
|
||||
|
||||
it("rejects mismatched manifest versions", () => {
|
||||
const arm64 = parseMacUpdateManifest(
|
||||
`version: 0.0.4
|
||||
files:
|
||||
- url: T3-Code-0.0.4-arm64.zip
|
||||
sha512: arm64zip
|
||||
size: 1
|
||||
releaseDate: '2026-03-07T10:32:14.587Z'
|
||||
`,
|
||||
"latest-mac.yml",
|
||||
);
|
||||
|
||||
const x64 = parseMacUpdateManifest(
|
||||
`version: 0.0.5
|
||||
files:
|
||||
- url: T3-Code-0.0.5-x64.zip
|
||||
sha512: x64zip
|
||||
size: 1
|
||||
releaseDate: '2026-03-07T10:36:07.540Z'
|
||||
`,
|
||||
"latest-mac-x64.yml",
|
||||
);
|
||||
|
||||
assert.throws(() => mergeMacUpdateManifests(arm64, x64), /different versions/);
|
||||
});
|
||||
|
||||
it("preserves quoted scalars as strings", () => {
|
||||
const manifest = parseMacUpdateManifest(
|
||||
`version: '1.0'
|
||||
files:
|
||||
- url: T3-Code-1.0-x64.zip
|
||||
sha512: zipsha
|
||||
size: 1
|
||||
releaseName: 'true'
|
||||
minimumSystemVersion: '13.0'
|
||||
stagingPercentage: 50
|
||||
releaseDate: '2026-03-07T10:36:07.540Z'
|
||||
`,
|
||||
"latest-mac.yml",
|
||||
);
|
||||
|
||||
assert.equal(manifest.version, "1.0");
|
||||
assert.equal(manifest.extras.releaseName, "true");
|
||||
assert.equal(manifest.extras.minimumSystemVersion, "13.0");
|
||||
assert.equal(manifest.extras.stagingPercentage, 50);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,287 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
interface MacUpdateFile {
|
||||
readonly url: string;
|
||||
readonly sha512: string;
|
||||
readonly size: number;
|
||||
}
|
||||
|
||||
type MacUpdateScalar = string | number | boolean;
|
||||
|
||||
interface MacUpdateManifest {
|
||||
readonly version: string;
|
||||
readonly releaseDate: string;
|
||||
readonly files: ReadonlyArray<MacUpdateFile>;
|
||||
readonly extras: Readonly<Record<string, MacUpdateScalar>>;
|
||||
}
|
||||
|
||||
interface MutableMacUpdateFile {
|
||||
url?: string;
|
||||
sha512?: string;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
function stripSingleQuotes(value: string): string {
|
||||
if (value.startsWith("'") && value.endsWith("'")) {
|
||||
return value.slice(1, -1).replace(/''/g, "'");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseFileRecord(
|
||||
currentFile: MutableMacUpdateFile | null,
|
||||
sourcePath: string,
|
||||
lineNumber: number,
|
||||
): MacUpdateFile | null {
|
||||
if (currentFile === null) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
typeof currentFile.url !== "string" ||
|
||||
typeof currentFile.sha512 !== "string" ||
|
||||
typeof currentFile.size !== "number"
|
||||
) {
|
||||
throw new Error(
|
||||
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: incomplete file entry.`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
url: currentFile.url,
|
||||
sha512: currentFile.sha512,
|
||||
size: currentFile.size,
|
||||
};
|
||||
}
|
||||
|
||||
function parseScalarValue(rawValue: string): MacUpdateScalar {
|
||||
const trimmed = rawValue.trim();
|
||||
const isQuoted = trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2;
|
||||
const value = isQuoted ? trimmed.slice(1, -1).replace(/''/g, "'") : trimmed;
|
||||
if (isQuoted) return value;
|
||||
if (value === "true") return true;
|
||||
if (value === "false") return false;
|
||||
if (/^-?\d+(?:\.\d+)?$/.test(value)) {
|
||||
return Number(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function parseMacUpdateManifest(raw: string, sourcePath: string): MacUpdateManifest {
|
||||
const lines = raw.split(/\r?\n/);
|
||||
const files: MacUpdateFile[] = [];
|
||||
const extras: Record<string, MacUpdateScalar> = {};
|
||||
let version: string | null = null;
|
||||
let releaseDate: string | null = null;
|
||||
let inFiles = false;
|
||||
let currentFile: MutableMacUpdateFile | null = null;
|
||||
|
||||
for (const [index, rawLine] of lines.entries()) {
|
||||
const lineNumber = index + 1;
|
||||
const line = rawLine.trimEnd();
|
||||
if (line.length === 0) continue;
|
||||
|
||||
const fileUrlMatch = line.match(/^ - url:\s*(.+)$/);
|
||||
if (fileUrlMatch?.[1]) {
|
||||
const finalized = parseFileRecord(currentFile, sourcePath, lineNumber);
|
||||
if (finalized) files.push(finalized);
|
||||
currentFile = { url: stripSingleQuotes(fileUrlMatch[1].trim()) };
|
||||
inFiles = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
const fileShaMatch = line.match(/^ sha512:\s*(.+)$/);
|
||||
if (fileShaMatch?.[1]) {
|
||||
if (currentFile === null) {
|
||||
throw new Error(
|
||||
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: sha512 without a file entry.`,
|
||||
);
|
||||
}
|
||||
currentFile.sha512 = stripSingleQuotes(fileShaMatch[1].trim());
|
||||
continue;
|
||||
}
|
||||
|
||||
const fileSizeMatch = line.match(/^ size:\s*(\d+)$/);
|
||||
if (fileSizeMatch?.[1]) {
|
||||
if (currentFile === null) {
|
||||
throw new Error(
|
||||
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: size without a file entry.`,
|
||||
);
|
||||
}
|
||||
currentFile.size = Number(fileSizeMatch[1]);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line === "files:") {
|
||||
inFiles = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inFiles && currentFile !== null) {
|
||||
const finalized = parseFileRecord(currentFile, sourcePath, lineNumber);
|
||||
if (finalized) files.push(finalized);
|
||||
currentFile = null;
|
||||
}
|
||||
inFiles = false;
|
||||
|
||||
const topLevelMatch = line.match(/^([A-Za-z][A-Za-z0-9]*):\s*(.+)$/);
|
||||
if (!topLevelMatch?.[1] || topLevelMatch[2] === undefined) {
|
||||
throw new Error(
|
||||
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: unsupported line '${line}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
const [, key, rawValue] = topLevelMatch;
|
||||
const value = parseScalarValue(rawValue);
|
||||
|
||||
if (key === "version") {
|
||||
if (typeof value !== "string") {
|
||||
throw new Error(
|
||||
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: version must be a string.`,
|
||||
);
|
||||
}
|
||||
version = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (key === "releaseDate") {
|
||||
if (typeof value !== "string") {
|
||||
throw new Error(
|
||||
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: releaseDate must be a string.`,
|
||||
);
|
||||
}
|
||||
releaseDate = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (key === "path" || key === "sha512") {
|
||||
continue;
|
||||
}
|
||||
|
||||
extras[key] = value;
|
||||
}
|
||||
|
||||
const finalized = parseFileRecord(currentFile, sourcePath, lines.length);
|
||||
if (finalized) files.push(finalized);
|
||||
|
||||
if (!version) {
|
||||
throw new Error(`Invalid macOS update manifest at ${sourcePath}: missing version.`);
|
||||
}
|
||||
if (!releaseDate) {
|
||||
throw new Error(`Invalid macOS update manifest at ${sourcePath}: missing releaseDate.`);
|
||||
}
|
||||
if (files.length === 0) {
|
||||
throw new Error(`Invalid macOS update manifest at ${sourcePath}: missing files.`);
|
||||
}
|
||||
|
||||
return {
|
||||
version,
|
||||
releaseDate,
|
||||
files,
|
||||
extras,
|
||||
};
|
||||
}
|
||||
|
||||
function mergeExtras(
|
||||
primary: Readonly<Record<string, MacUpdateScalar>>,
|
||||
secondary: Readonly<Record<string, MacUpdateScalar>>,
|
||||
): Record<string, MacUpdateScalar> {
|
||||
const merged: Record<string, MacUpdateScalar> = { ...primary };
|
||||
|
||||
for (const [key, value] of Object.entries(secondary)) {
|
||||
const existing = merged[key];
|
||||
if (existing !== undefined && existing !== value) {
|
||||
throw new Error(
|
||||
`Cannot merge macOS update manifests: conflicting '${key}' values ('${existing}' vs '${value}').`,
|
||||
);
|
||||
}
|
||||
merged[key] = value;
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
export function mergeMacUpdateManifests(
|
||||
primary: MacUpdateManifest,
|
||||
secondary: MacUpdateManifest,
|
||||
): MacUpdateManifest {
|
||||
if (primary.version !== secondary.version) {
|
||||
throw new Error(
|
||||
`Cannot merge macOS update manifests with different versions (${primary.version} vs ${secondary.version}).`,
|
||||
);
|
||||
}
|
||||
|
||||
const filesByUrl = new Map<string, MacUpdateFile>();
|
||||
for (const file of [...primary.files, ...secondary.files]) {
|
||||
const existing = filesByUrl.get(file.url);
|
||||
if (existing && (existing.sha512 !== file.sha512 || existing.size !== file.size)) {
|
||||
throw new Error(
|
||||
`Cannot merge macOS update manifests: conflicting file entry for ${file.url}.`,
|
||||
);
|
||||
}
|
||||
filesByUrl.set(file.url, file);
|
||||
}
|
||||
|
||||
return {
|
||||
version: primary.version,
|
||||
releaseDate:
|
||||
primary.releaseDate >= secondary.releaseDate ? primary.releaseDate : secondary.releaseDate,
|
||||
files: [...filesByUrl.values()],
|
||||
extras: mergeExtras(primary.extras, secondary.extras),
|
||||
};
|
||||
}
|
||||
|
||||
function quoteYamlString(value: string): string {
|
||||
return `'${value.replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
function serializeScalarValue(value: MacUpdateScalar): string {
|
||||
if (typeof value === "string") {
|
||||
return quoteYamlString(value);
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
export function serializeMacUpdateManifest(manifest: MacUpdateManifest): string {
|
||||
const lines = [`version: ${manifest.version}`, "files:"];
|
||||
|
||||
for (const file of manifest.files) {
|
||||
lines.push(` - url: ${file.url}`);
|
||||
lines.push(` sha512: ${file.sha512}`);
|
||||
lines.push(` size: ${file.size}`);
|
||||
}
|
||||
|
||||
for (const key of Object.keys(manifest.extras).toSorted()) {
|
||||
const value = manifest.extras[key];
|
||||
if (value === undefined) {
|
||||
throw new Error(`Cannot serialize macOS update manifest: missing value for '${key}'.`);
|
||||
}
|
||||
lines.push(`${key}: ${serializeScalarValue(value)}`);
|
||||
}
|
||||
|
||||
lines.push(`releaseDate: ${quoteYamlString(manifest.releaseDate)}`);
|
||||
lines.push("");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function main(args: ReadonlyArray<string>): void {
|
||||
const [arm64PathArg, x64PathArg, outputPathArg] = args;
|
||||
if (!arm64PathArg || !x64PathArg) {
|
||||
throw new Error(
|
||||
"Usage: node scripts/merge-mac-update-manifests.ts <latest-mac.yml> <latest-mac-x64.yml> [output-path]",
|
||||
);
|
||||
}
|
||||
|
||||
const arm64Path = resolve(arm64PathArg);
|
||||
const x64Path = resolve(x64PathArg);
|
||||
const outputPath = resolve(outputPathArg ?? arm64PathArg);
|
||||
|
||||
const arm64Manifest = parseMacUpdateManifest(readFileSync(arm64Path, "utf8"), arm64Path);
|
||||
const x64Manifest = parseMacUpdateManifest(readFileSync(x64Path, "utf8"), x64Path);
|
||||
const merged = mergeMacUpdateManifests(arm64Manifest, x64Manifest);
|
||||
writeFileSync(outputPath, serializeMacUpdateManifest(merged));
|
||||
}
|
||||
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
main(process.argv.slice(2));
|
||||
}
|
||||
Reference in new issue
Block a user