Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4419ba0e0c | ||
|
|
8c4d76f7eb | ||
|
|
4f0f24f055 | ||
|
|
d1e85c4e8f | ||
|
|
ea20e80021 | ||
|
|
9e632f5cec | ||
|
|
4120e94598 | ||
|
|
34bb18c8cf | ||
|
|
90eea047a9 | ||
|
|
f92e1e1b06 | ||
|
|
556c42452c | ||
|
|
7e20b23e7e | ||
|
|
b83e9c95e4 | ||
|
|
a41f4895ce | ||
|
|
d15909af15 |
No files matched your search
@@ -124,6 +124,9 @@ jobs:
|
||||
group: pr-size-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
# This pull_request_target job may fetch untrusted PR commits only as passive
|
||||
# git data. Do not add dependency installs, build/test scripts, or cache
|
||||
# actions here; use pull_request plus workflow_run for that pattern instead.
|
||||
- name: Checkout base repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
|
||||
@@ -23,8 +23,8 @@ on:
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
contents: read
|
||||
id-token: none
|
||||
|
||||
jobs:
|
||||
check_changes:
|
||||
@@ -420,6 +420,9 @@ jobs:
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
@@ -23,5 +23,6 @@ __screenshots__/
|
||||
.tanstack
|
||||
squashfs-root/
|
||||
.vercel
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.23",
|
||||
"version": "0.0.24",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
@@ -16,6 +16,10 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/ssh": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
"electron": "41.5.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
@@ -23,13 +27,7 @@
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/ssh": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as NodeOS from "node:os";
|
||||
import {
|
||||
createAdvertisedEndpoint,
|
||||
type CreateAdvertisedEndpointInput,
|
||||
} from "@t3tools/client-runtime";
|
||||
} from "@t3tools/shared/advertisedEndpoint";
|
||||
import type {
|
||||
AdvertisedEndpoint,
|
||||
AdvertisedEndpointProvider,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createAdvertisedEndpoint } from "@t3tools/client-runtime";
|
||||
import { createAdvertisedEndpoint } from "@t3tools/shared/advertisedEndpoint";
|
||||
import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts";
|
||||
import {
|
||||
buildTailscaleHttpsBaseUrl,
|
||||
|
||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
|
After Width: | Height: | Size: 244 B |
|
After Width: | Height: | Size: 358 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="257" preserveAspectRatio="xMidYMid" viewBox="0 0 256 257"><path fill="#D97757" d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
@@ -0,0 +1 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 649 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="260" preserveAspectRatio="xMidYMid" viewBox="0 0 256 260"><path fill="#fff" d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512"><svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="512" height="512" fill="#131010"></rect><path d="M320 224V352H192V224H320Z" fill="#5A5858"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M384 416H128V96H384V416ZM320 160H192V352H320V160Z" fill="white"></path></svg></svg>
|
||||
|
After Width: | Height: | Size: 464 B |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 7.3 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
|
After Width: | Height: | Size: 6.6 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 138 B |
|
After Width: | Height: | Size: 5.2 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 7.4 KiB |
|
After Width: | Height: | Size: 4.9 KiB |
|
After Width: | Height: | Size: 8.1 KiB |
|
After Width: | Height: | Size: 5.7 KiB |
|
After Width: | Height: | Size: 5.5 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 6.0 KiB |
|
Before Width: | Height: | Size: 652 KiB |
|
After Width: | Height: | Size: 123 KiB |
|
After Width: | Height: | Size: 110 KiB |
@@ -0,0 +1,53 @@
|
||||
---
|
||||
interface Props {
|
||||
class?: string;
|
||||
idPrefix: string;
|
||||
}
|
||||
|
||||
const { class: className, idPrefix } = Astro.props;
|
||||
---
|
||||
|
||||
<svg
|
||||
class={className}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 256 295"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id={`${idPrefix}0`} 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={`${idPrefix}6`} 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={`${idPrefix}8`} 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={`${idPrefix}c`} 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={`${idPrefix}e`} 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={`${idPrefix}i`} 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(#${idPrefix}6)`} 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(#${idPrefix}8)`} 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(#${idPrefix}c)`} 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(#${idPrefix}e)`} 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(#${idPrefix}i)`} 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>
|
||||
@@ -6,7 +6,7 @@ interface Props {
|
||||
|
||||
const {
|
||||
title = "T3 Code",
|
||||
description = "T3 Code — The best way to code with AI.",
|
||||
description = "T3 Code — The open-source control plane for coding agents.",
|
||||
} = Astro.props;
|
||||
---
|
||||
|
||||
@@ -18,7 +18,7 @@ const {
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&family=JetBrains+Mono:wght@400;500&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
@@ -30,18 +30,25 @@ const {
|
||||
<body>
|
||||
<div class="page">
|
||||
<nav class="nav">
|
||||
<a href="/" class="nav-brand">
|
||||
<img src="/icon.png" alt="T3" class="nav-icon" />
|
||||
</a>
|
||||
<a
|
||||
href="https://github.com/pingdotgg/t3code"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="nav-github"
|
||||
>
|
||||
GitHub
|
||||
<span class="nav-github-arrow" aria-hidden="true">↗</span>
|
||||
</a>
|
||||
<div class="nav-inner">
|
||||
<a href="/" class="nav-brand" aria-label="T3 Code home">
|
||||
<span class="nav-brand-name">T3 Code</span>
|
||||
</a>
|
||||
<div class="nav-right">
|
||||
<a
|
||||
class="nav-gh"
|
||||
href="https://github.com/pingdotgg/t3code"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
|
||||
</svg>
|
||||
<span>GitHub</span>
|
||||
</a>
|
||||
<a class="btn btn-primary" href="/#download">Download</a>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<main class="main">
|
||||
@@ -49,23 +56,54 @@ const {
|
||||
</main>
|
||||
|
||||
<footer class="footer">
|
||||
<span class="footer-copy">© {new Date().getFullYear()} T3 Tools Inc</span>
|
||||
<div class="footer-links">
|
||||
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
|
||||
<div class="footer-inner">
|
||||
<div class="footer-brand">
|
||||
<img src="/icon.webp" alt="" />
|
||||
<span>© {new Date().getFullYear()} T3 Tools Inc · MIT licensed</span>
|
||||
</div>
|
||||
<div class="footer-links">
|
||||
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
|
||||
<a href="/download">Download</a>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const nav = document.querySelector(".nav");
|
||||
const onScroll = () => {
|
||||
if (!nav) return;
|
||||
if (window.scrollY > 12) nav.classList.add("is-scrolled");
|
||||
else nav.classList.remove("is-scrolled");
|
||||
};
|
||||
window.addEventListener("scroll", onScroll, { passive: true });
|
||||
onScroll();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
<style is:global>
|
||||
:root {
|
||||
--bg: #09090b;
|
||||
--bg-elev: #0c0c0e;
|
||||
--bg-card: #111113;
|
||||
--fg: #fafafa;
|
||||
--fg-muted: #a1a1aa;
|
||||
--fg-dim: #71717a;
|
||||
--fg-faint: #52525b;
|
||||
--border: rgba(255, 255, 255, 0.08);
|
||||
--border-strong: rgba(255, 255, 255, 0.14);
|
||||
--accent-h: 250;
|
||||
--accent: oklch(0.68 0.17 var(--accent-h));
|
||||
--accent-dim: oklch(0.68 0.17 var(--accent-h) / 0.15);
|
||||
--ok: oklch(0.72 0.16 150);
|
||||
--warn: oklch(0.76 0.15 75);
|
||||
--font-sans: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
|
||||
--font-mono: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, monospace;
|
||||
--radius: 12px;
|
||||
--radius-sm: 8px;
|
||||
--radius-lg: 16px;
|
||||
}
|
||||
|
||||
* {
|
||||
@@ -76,16 +114,19 @@ const {
|
||||
|
||||
html {
|
||||
color-scheme: dark;
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
|
||||
font-family: var(--font-sans);
|
||||
font-feature-settings: "ss01", "ss02";
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
min-height: 100vh;
|
||||
overflow-x: hidden;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
body::after {
|
||||
@@ -105,11 +146,103 @@ const {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
img {
|
||||
button {
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
img,
|
||||
svg {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.14em;
|
||||
text-transform: uppercase;
|
||||
color: var(--fg-dim);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.display {
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.035em;
|
||||
line-height: 1.05;
|
||||
}
|
||||
|
||||
.container {
|
||||
width: 100%;
|
||||
max-width: 1240px;
|
||||
margin: 0 auto;
|
||||
padding: 0 32px;
|
||||
}
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
font-weight: 500;
|
||||
font-size: 14px;
|
||||
padding: 10px 18px;
|
||||
border-radius: 8px;
|
||||
transition: transform 0.18s ease, background 0.18s ease,
|
||||
border-color 0.18s ease, color 0.18s ease;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--fg);
|
||||
color: #09090b;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
transform: translateY(-1px);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.btn-primary:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.btn-ghost {
|
||||
color: var(--fg-muted);
|
||||
border: 1px solid var(--border);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.btn-ghost:hover {
|
||||
color: var(--fg);
|
||||
border-color: var(--border-strong);
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
.btn-lg {
|
||||
padding: 14px 22px;
|
||||
font-size: 15px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.tile {
|
||||
position: relative;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: linear-gradient(180deg, rgba(255, 255, 255, 0.015), rgba(255, 255, 255, 0));
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
@keyframes fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
@@ -120,11 +253,26 @@ const {
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
50% { opacity: 0.4; }
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
@keyframes floatDrift {
|
||||
0%, 100% { translate: 0 0; }
|
||||
50% { translate: 0 -10px; }
|
||||
}
|
||||
|
||||
@keyframes blink {
|
||||
50% { opacity: 0; }
|
||||
}
|
||||
</style>
|
||||
|
||||
<style>
|
||||
/* ── Page ── */
|
||||
|
||||
.page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
@@ -132,97 +280,131 @@ const {
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
/* ── Navbar ── */
|
||||
|
||||
.nav {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 50;
|
||||
backdrop-filter: blur(18px);
|
||||
-webkit-backdrop-filter: blur(18px);
|
||||
background: color-mix(in srgb, var(--bg) 75%, transparent);
|
||||
border-bottom: 1px solid transparent;
|
||||
transition: border-color 0.3s ease;
|
||||
}
|
||||
|
||||
.nav.is-scrolled {
|
||||
border-bottom-color: var(--border);
|
||||
}
|
||||
|
||||
.nav-inner {
|
||||
max-width: 1240px;
|
||||
margin: 0 auto;
|
||||
padding: 12px 32px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1.5rem 2.5rem;
|
||||
opacity: 0.5;
|
||||
transition: opacity 0.4s ease;
|
||||
}
|
||||
|
||||
.nav:hover {
|
||||
opacity: 1;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.nav-brand {
|
||||
display: flex;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.nav-icon {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.nav-github {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
color: var(--fg-muted);
|
||||
font-size: 0.875rem;
|
||||
transition: color 0.3s ease;
|
||||
}
|
||||
|
||||
.nav-github:hover {
|
||||
color: var(--fg);
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
|
||||
.nav-github-arrow {
|
||||
display: inline-block;
|
||||
transition: transform 0.3s ease;
|
||||
.nav-brand:hover {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.nav-github:hover .nav-github-arrow {
|
||||
transform: translateX(2px) translateY(-1px);
|
||||
.nav-brand-name {
|
||||
font-size: 16px;
|
||||
font-weight: 650;
|
||||
letter-spacing: -0.025em;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
/* ── Main content ── */
|
||||
.nav-right {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.nav-gh {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 7px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
color: var(--fg-muted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease;
|
||||
}
|
||||
|
||||
.nav-gh:hover {
|
||||
color: var(--fg);
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* ── Footer ── */
|
||||
|
||||
.footer {
|
||||
margin-top: auto;
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 40px 0 32px;
|
||||
}
|
||||
|
||||
.footer-inner {
|
||||
max-width: 1240px;
|
||||
margin: 0 auto;
|
||||
padding: 0 32px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 24px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1.5rem 2.5rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.footer-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 13px;
|
||||
color: var(--fg-dim);
|
||||
}
|
||||
|
||||
.footer-brand img {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.footer-links {
|
||||
display: flex;
|
||||
gap: 1.25rem;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.footer-links a {
|
||||
font-size: 13px;
|
||||
color: var(--fg-dim);
|
||||
transition: color 0.3s ease;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
|
||||
.footer-links a:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
/* ── Mobile ── */
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.nav {
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.footer {
|
||||
padding: 1.25rem;
|
||||
@media (max-width: 820px) {
|
||||
.nav-inner,
|
||||
.footer-inner {
|
||||
padding-left: 20px;
|
||||
padding-right: 20px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,123 @@
|
||||
export type Tweet = {
|
||||
handle: string;
|
||||
content: string;
|
||||
excerpt?: string;
|
||||
link: string;
|
||||
};
|
||||
|
||||
export const tweets = [
|
||||
{
|
||||
handle: "Shay_Benshabtay",
|
||||
content:
|
||||
"T3 code is not perfect, but it's damn good. Open and fun , I can make my own fork for my uses and use the great tooling with my own needs.",
|
||||
link: "https://x.com/Shay_Benshabtay/status/2054668503857156326",
|
||||
},
|
||||
{
|
||||
handle: "teja2495",
|
||||
content:
|
||||
"I’ve completely switched to T3 Code for all my workflows. I just switch between different subscriptions and harnesses depending on what I need.",
|
||||
excerpt: "I’ve completely switched to T3 Code for all my workflows.",
|
||||
link: "https://x.com/teja2495/status/2052420254991581623",
|
||||
},
|
||||
{
|
||||
handle: "developedbyed",
|
||||
content: "might say alpha but T3 code is pretty awesome, really fast too",
|
||||
link: "https://x.com/developedbyed/status/2030627970532921605",
|
||||
},
|
||||
{
|
||||
handle: "tannerlinsley",
|
||||
content:
|
||||
"The minute T3 Code supports Claude Code, it could potentially become my daily driver. There's something special there.",
|
||||
link: "https://x.com/tannerlinsley/status/2031102771529920966",
|
||||
},
|
||||
{
|
||||
handle: "aronprins",
|
||||
content:
|
||||
"I already loved T3 Code by @theo and @jullerino, but their Connections implementation is next level epic and for this they should both earn maximum repect 🔥🫡",
|
||||
excerpt: "I already loved T3 Code, but their Connections implementation is next level epic.",
|
||||
link: "https://x.com/aronprins/status/2045102518196183109",
|
||||
},
|
||||
{
|
||||
handle: "BennettBuhner",
|
||||
content:
|
||||
"T3 Code is literally Codex but better; all your favorite models and harnesses, accessible anywhere! The app is great but the website is even greater, so instead of needing to SSH into a machine, T3 IS my SSH!",
|
||||
excerpt:
|
||||
"T3 Code is literally Codex but better; all your favorite models and harnesses, accessible anywhere.",
|
||||
link: "https://x.com/BennettBuhner/status/2054667115697754387",
|
||||
},
|
||||
{
|
||||
handle: "ex0t1clol",
|
||||
content: "T3 Code is proof electron apps don't have to suck",
|
||||
link: "https://x.com/ex0t1clol/status/2054666870008021197",
|
||||
},
|
||||
{
|
||||
handle: "Josikinz",
|
||||
content:
|
||||
"T3 code is better because it’s like if the codex Mac app didn’t make my computer run like shit 😋",
|
||||
link: "https://x.com/Josikinz/status/2030367951694745870",
|
||||
},
|
||||
{
|
||||
handle: "jetpackjoe_",
|
||||
content: "T3 code is pretty alright I guess",
|
||||
link: "https://x.com/jetpackjoe_/status/2054666792933404959",
|
||||
},
|
||||
{
|
||||
handle: "mil000",
|
||||
content: "T3 code saved my relationship!",
|
||||
link: "https://x.com/mil000/status/2030120041451246071",
|
||||
},
|
||||
{
|
||||
handle: "_winter_wonders",
|
||||
content: "Heartbreaking: AI-hater has to admit T3 Code is really good.",
|
||||
link: "https://x.com/_winter_wonders/status/2052350198764970434",
|
||||
},
|
||||
{
|
||||
handle: "kostyniuk00",
|
||||
content:
|
||||
"I was not expecting a year ago, that my anti-AI colleagues would thank me a year later, for persuading them to try T3 Code Beta, that really helped them with organizing their workflows. \n\nFantastic product by @jullerino and @theo. Go try it out if you haven’t yet!",
|
||||
excerpt:
|
||||
"My anti-AI colleagues thanked me for persuading them to try T3 Code Beta. Fantastic product.",
|
||||
link: "https://x.com/kostyniuk00/status/2052041388179468521",
|
||||
},
|
||||
{
|
||||
handle: "gnukeith",
|
||||
content:
|
||||
"I tried T3 Code it actually fixed issues that Opus couldn’t solve in Claude Code + Theo has replied with “UwU” under my post. Dario has not.",
|
||||
link: "https://x.com/gnukeith/status/2054670073579630730",
|
||||
},
|
||||
{
|
||||
handle: "peculiarnewbie",
|
||||
content: "T3 Code is iOS and other harnesses are androids",
|
||||
link: "https://x.com/peculiarnewbie/status/2054671685027233827",
|
||||
},
|
||||
{
|
||||
handle: "leodev",
|
||||
content:
|
||||
"T3 Code is probably the first coding gui that didn't suck performance wise and had a smart team behind it.",
|
||||
link: "https://x.com/leodev/status/2054679746353537042",
|
||||
},
|
||||
{
|
||||
handle: "pocarles",
|
||||
content:
|
||||
"Only using Codex and T3 now.\n\nI thought all AI coding harnesses had roughly the same impact. Using T3 Code taught me how wrong I was. The interface between you and the model changes everything.",
|
||||
excerpt:
|
||||
"Using T3 Code taught me how wrong I was. The interface between you and the model changes everything.",
|
||||
link: "https://x.com/pocarles/status/2054673964274758046",
|
||||
},
|
||||
{
|
||||
handle: "DavidKPiano",
|
||||
content: "It's like Claude Code if they didn't vibe-code the entire thing",
|
||||
link: "https://x.com/DavidKPiano/status/2054682983504719930",
|
||||
},
|
||||
{
|
||||
handle: "iamkaffe",
|
||||
content: "T3Code was the first one to truly care about Linux users.",
|
||||
link: "https://x.com/iamkaffe/status/2054675539311411280",
|
||||
},
|
||||
{
|
||||
handle: "uwunetes",
|
||||
content:
|
||||
"claude code make me go *whine whine whine* and t3 code make me go woof woof awooooo!!!",
|
||||
link: "https://x.com/uwunetes/status/2054683356022120640",
|
||||
},
|
||||
] satisfies Tweet[];
|
||||
@@ -4,6 +4,7 @@ import { RELEASES_URL } from "../lib/releases";
|
||||
---
|
||||
|
||||
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
|
||||
<div class="download-page">
|
||||
<h1 class="heading">Download T3 Code</h1>
|
||||
<p class="subheading">
|
||||
<span id="version-label">Loading latest release…</span>
|
||||
@@ -64,6 +65,7 @@ import { RELEASES_URL } from "../lib/releases";
|
||||
GitHub releases page<span aria-hidden="true"> ↗</span>
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
@@ -111,7 +113,11 @@ import { RELEASES_URL } from "../lib/releases";
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.main {
|
||||
.download-page {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 8vh 1.5rem 4rem;
|
||||
}
|
||||
|
||||
@@ -257,7 +263,7 @@ import { RELEASES_URL } from "../lib/releases";
|
||||
/* ── Mobile ── */
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.main {
|
||||
.download-page {
|
||||
padding: 5vh 1.25rem 4rem;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
https://x.com/Shay_Benshabtay/status/2054668503857156326
|
||||
https://x.com/teja2495/status/2052420254991581623
|
||||
https://x.com/developedbyed/status/2030627970532921605
|
||||
https://x.com/tannerlinsley/status/2031102771529920966
|
||||
https://x.com/aronprins/status/2045102518196183109
|
||||
https://x.com/BennettBuhner/status/2054667115697754387
|
||||
https://x.com/ex0t1clol/status/2054666870008021197
|
||||
https://x.com/Josikinz/status/2030367951694745870
|
||||
https://x.com/jetpackjoe_/status/2054666792933404959
|
||||
https://x.com/mil000/status/2030120041451246071
|
||||
https://x.com/_winter_wonders/status/2052350198764970434
|
||||
https://x.com/kostyniuk00/status/2052041388179468521
|
||||
https://x.com/gnukeith/status/2054670073579630730
|
||||
https://x.com/peculiarnewbie/status/2054671685027233827
|
||||
https://x.com/leodev/status/2054679746353537042
|
||||
https://x.com/pocarles/status/2054673964274758046
|
||||
https://x.com/DavidKPiano/status/2054682983504719930
|
||||
https://x.com/iamkaffe/status/2054675539311411280
|
||||
https://x.com/uwunetes/status/2054683356022120640
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.23",
|
||||
"version": "0.0.24",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -20,19 +20,18 @@
|
||||
"build:bundle": "tsdown",
|
||||
"start": "node dist/bin.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/platform-node-shared": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0"
|
||||
"node-pty": "^1.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
|
||||
@@ -15,7 +15,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
interface ProcessRow {
|
||||
export interface ProcessRow {
|
||||
readonly pid: number;
|
||||
readonly ppid: number;
|
||||
readonly pgid: number | null;
|
||||
@@ -186,7 +186,7 @@ function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
}
|
||||
}
|
||||
|
||||
function buildDescendantEntries(
|
||||
export function buildDescendantEntries(
|
||||
rows: ReadonlyArray<ProcessRow>,
|
||||
serverPid: number,
|
||||
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
|
||||
@@ -230,7 +230,7 @@ function buildDescendantEntries(
|
||||
return entries;
|
||||
}
|
||||
|
||||
function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
|
||||
export function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
|
||||
if (row.ppid !== serverPid) return false;
|
||||
|
||||
const command = row.command.trim();
|
||||
@@ -370,7 +370,7 @@ function readWindowsProcessRows(): Effect.Effect<
|
||||
);
|
||||
}
|
||||
|
||||
const readProcessRows = (platform = process.platform) =>
|
||||
export const readProcessRows = (platform = process.platform) =>
|
||||
platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
|
||||
|
||||
export function aggregateProcessDiagnostics(input: {
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import {
|
||||
aggregateProcessResourceHistory,
|
||||
collectMonitoredSamples,
|
||||
} from "./ProcessResourceMonitor.ts";
|
||||
|
||||
describe("ProcessResourceMonitor", () => {
|
||||
it.effect("samples the server root process and descendants", () =>
|
||||
Effect.sync(() => {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const samples = collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 2,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 10,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "00:20",
|
||||
command: "codex app-server",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 50,
|
||||
rssBytes: 3_000,
|
||||
elapsed: "00:05",
|
||||
command: "rg needle",
|
||||
},
|
||||
{
|
||||
pid: 200,
|
||||
ppid: 1,
|
||||
pgid: 200,
|
||||
status: "R",
|
||||
cpuPercent: 99,
|
||||
rssBytes: 9_000,
|
||||
elapsed: "00:05",
|
||||
command: "unrelated",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(samples.map((sample) => sample.pid)).toEqual([100, 101, 102]);
|
||||
expect(samples.map((sample) => sample.depth)).toEqual([0, 1, 2]);
|
||||
expect(samples[0]?.isServerRoot).toBe(true);
|
||||
expect(samples[1]?.isServerRoot).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rolls samples up by process and CPU time", () =>
|
||||
Effect.sync(() => {
|
||||
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.000Z");
|
||||
const samples = [
|
||||
...collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: firstAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(firstAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 10,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
...collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: secondAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(secondAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 30,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "01:05",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const result = aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastError: null,
|
||||
});
|
||||
|
||||
expect(Option.isNone(result.error)).toBe(true);
|
||||
expect(result.topProcesses).toHaveLength(1);
|
||||
expect(result.topProcesses[0]?.avgCpuPercent).toBe(20);
|
||||
expect(result.topProcesses[0]?.maxCpuPercent).toBe(30);
|
||||
expect(result.topProcesses[0]?.cpuSecondsApprox).toBe(2);
|
||||
expect(result.totalCpuSecondsApprox).toBe(2);
|
||||
expect(result.buckets.some((bucket) => bucket.maxCpuPercent === 30)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a process grouped when elapsed time drifts between samples", () =>
|
||||
Effect.sync(() => {
|
||||
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.400Z");
|
||||
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.900Z");
|
||||
const samples = [
|
||||
...collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: firstAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(firstAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
...collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: secondAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(secondAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 2,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "01:06",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const result = aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastError: null,
|
||||
});
|
||||
|
||||
expect(result.topProcesses).toHaveLength(1);
|
||||
expect(result.topProcesses[0]?.isServerRoot).toBe(true);
|
||||
expect(result.topProcesses[0]?.sampleCount).toBe(2);
|
||||
expect(result.topProcesses[0]?.maxRssBytes).toBe(2_000);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns all process summaries in the selected window", () =>
|
||||
Effect.sync(() => {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const samples = collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
...Array.from({ length: 35 }, (_, index) => ({
|
||||
pid: 200 + index,
|
||||
ppid: index === 0 ? 100 : 199 + index,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 35 - index,
|
||||
rssBytes: 2_000 + index,
|
||||
elapsed: "00:10",
|
||||
command: `worker ${index}`,
|
||||
})),
|
||||
],
|
||||
});
|
||||
|
||||
const result = aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: sampledAt,
|
||||
readAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastError: null,
|
||||
});
|
||||
|
||||
expect(result.topProcesses).toHaveLength(36);
|
||||
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,300 @@
|
||||
import type {
|
||||
ServerProcessResourceHistoryBucket,
|
||||
ServerProcessResourceHistoryInput,
|
||||
ServerProcessResourceHistoryResult,
|
||||
ServerProcessResourceHistorySummary,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
buildDescendantEntries,
|
||||
isDiagnosticsQueryProcess,
|
||||
type ProcessRow,
|
||||
readProcessRows,
|
||||
} from "./ProcessDiagnostics.ts";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 5_000;
|
||||
const SAMPLE_INTERVAL = Duration.millis(SAMPLE_INTERVAL_MS);
|
||||
const RETENTION_MS = 60 * 60_000;
|
||||
const MAX_RETAINED_SAMPLES = 20_000;
|
||||
|
||||
export interface ProcessResourceSample {
|
||||
readonly sampledAt: DateTime.Utc;
|
||||
readonly sampledAtMs: number;
|
||||
readonly processKey: string;
|
||||
readonly pid: number;
|
||||
readonly ppid: number;
|
||||
readonly command: string;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly depth: number;
|
||||
readonly isServerRoot: boolean;
|
||||
}
|
||||
|
||||
interface MonitorState {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly lastError: string | null;
|
||||
}
|
||||
|
||||
export interface ProcessResourceMonitorShape {
|
||||
readonly readHistory: (
|
||||
input: ServerProcessResourceHistoryInput,
|
||||
) => Effect.Effect<ServerProcessResourceHistoryResult>;
|
||||
}
|
||||
|
||||
export class ProcessResourceMonitor extends Context.Service<
|
||||
ProcessResourceMonitor,
|
||||
ProcessResourceMonitorShape
|
||||
>()("t3/diagnostics/ProcessResourceMonitor") {}
|
||||
|
||||
function dateTimeFromMillis(ms: number): DateTime.Utc {
|
||||
return DateTime.makeUnsafe(ms);
|
||||
}
|
||||
|
||||
function sampleKey(row: Pick<ProcessRow, "pid" | "command">): string {
|
||||
return `${row.pid}:${row.command}`;
|
||||
}
|
||||
|
||||
function findServerRootRow(rows: ReadonlyArray<ProcessRow>, serverPid: number): ProcessRow | null {
|
||||
return rows.find((row) => row.pid === serverPid) ?? null;
|
||||
}
|
||||
|
||||
export function collectMonitoredSamples(input: {
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly serverPid: number;
|
||||
readonly sampledAt: DateTime.Utc;
|
||||
readonly sampledAtMs: number;
|
||||
}): ReadonlyArray<ProcessResourceSample> {
|
||||
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
|
||||
const root = findServerRootRow(rows, input.serverPid);
|
||||
const descendants = buildDescendantEntries(rows, input.serverPid);
|
||||
const samples: ProcessResourceSample[] = [];
|
||||
|
||||
if (root) {
|
||||
samples.push({
|
||||
sampledAt: input.sampledAt,
|
||||
sampledAtMs: input.sampledAtMs,
|
||||
processKey: sampleKey(root),
|
||||
pid: root.pid,
|
||||
ppid: root.ppid,
|
||||
command: root.command,
|
||||
cpuPercent: root.cpuPercent,
|
||||
rssBytes: root.rssBytes,
|
||||
depth: 0,
|
||||
isServerRoot: true,
|
||||
});
|
||||
}
|
||||
|
||||
for (const process of descendants) {
|
||||
samples.push({
|
||||
sampledAt: input.sampledAt,
|
||||
sampledAtMs: input.sampledAtMs,
|
||||
processKey: sampleKey(process),
|
||||
pid: process.pid,
|
||||
ppid: process.ppid,
|
||||
command: process.command,
|
||||
cpuPercent: process.cpuPercent,
|
||||
rssBytes: process.rssBytes,
|
||||
depth: process.depth + 1,
|
||||
isServerRoot: false,
|
||||
});
|
||||
}
|
||||
|
||||
return samples;
|
||||
}
|
||||
|
||||
function trimSamples(
|
||||
samples: ReadonlyArray<ProcessResourceSample>,
|
||||
nowMs: number,
|
||||
): ReadonlyArray<ProcessResourceSample> {
|
||||
const minSampledAtMs = nowMs - RETENTION_MS;
|
||||
const retained = samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
|
||||
return retained.length <= MAX_RETAINED_SAMPLES
|
||||
? retained
|
||||
: retained.slice(retained.length - MAX_RETAINED_SAMPLES);
|
||||
}
|
||||
|
||||
function summarizeProcesses(
|
||||
samples: ReadonlyArray<ProcessResourceSample>,
|
||||
): ReadonlyArray<ServerProcessResourceHistorySummary> {
|
||||
const groups = new Map<string, ProcessResourceSample[]>();
|
||||
for (const sample of samples) {
|
||||
const processSamples = groups.get(sample.processKey) ?? [];
|
||||
processSamples.push(sample);
|
||||
groups.set(sample.processKey, processSamples);
|
||||
}
|
||||
|
||||
return [...groups.entries()]
|
||||
.map(([processKey, processSamples]) => {
|
||||
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
|
||||
const first = sorted[0]!;
|
||||
const latest = sorted[sorted.length - 1]!;
|
||||
const cpuPercentTotal = sorted.reduce((total, sample) => total + sample.cpuPercent, 0);
|
||||
const maxCpuPercent = Math.max(...sorted.map((sample) => sample.cpuPercent));
|
||||
const maxRssBytes = Math.max(...sorted.map((sample) => sample.rssBytes));
|
||||
const cpuSecondsApprox = sorted.reduce(
|
||||
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
|
||||
0,
|
||||
);
|
||||
|
||||
return {
|
||||
processKey,
|
||||
pid: latest.pid,
|
||||
ppid: latest.ppid,
|
||||
command: latest.command,
|
||||
depth: latest.depth,
|
||||
isServerRoot: latest.isServerRoot,
|
||||
firstSeenAt: first.sampledAt,
|
||||
lastSeenAt: latest.sampledAt,
|
||||
currentCpuPercent: latest.cpuPercent,
|
||||
avgCpuPercent: cpuPercentTotal / sorted.length,
|
||||
maxCpuPercent,
|
||||
cpuSecondsApprox,
|
||||
currentRssBytes: latest.rssBytes,
|
||||
maxRssBytes,
|
||||
sampleCount: sorted.length,
|
||||
} satisfies ServerProcessResourceHistorySummary;
|
||||
})
|
||||
.toSorted((left, right) => right.cpuSecondsApprox - left.cpuSecondsApprox);
|
||||
}
|
||||
|
||||
function buildBuckets(input: {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly nowMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
}): ReadonlyArray<ServerProcessResourceHistoryBucket> {
|
||||
const bucketMs = Math.max(1_000, input.bucketMs);
|
||||
const windowStartMs = input.nowMs - input.windowMs;
|
||||
const buckets: ServerProcessResourceHistoryBucket[] = [];
|
||||
|
||||
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += bucketMs) {
|
||||
const endedAtMs = Math.min(input.nowMs, startedAtMs + bucketMs);
|
||||
const bucketSamples = input.samples.filter(
|
||||
(sample) =>
|
||||
sample.sampledAtMs >= startedAtMs &&
|
||||
(endedAtMs === input.nowMs
|
||||
? sample.sampledAtMs <= endedAtMs
|
||||
: sample.sampledAtMs < endedAtMs),
|
||||
);
|
||||
const samplesByRead = new Map<number, ProcessResourceSample[]>();
|
||||
for (const sample of bucketSamples) {
|
||||
const samplesAtTime = samplesByRead.get(sample.sampledAtMs) ?? [];
|
||||
samplesAtTime.push(sample);
|
||||
samplesByRead.set(sample.sampledAtMs, samplesAtTime);
|
||||
}
|
||||
|
||||
const readTotals = [...samplesByRead.values()].map((samplesAtTime) => ({
|
||||
cpuPercent: samplesAtTime.reduce((total, sample) => total + sample.cpuPercent, 0),
|
||||
rssBytes: samplesAtTime.reduce((total, sample) => total + sample.rssBytes, 0),
|
||||
processCount: samplesAtTime.length,
|
||||
}));
|
||||
const avgCpuPercent =
|
||||
readTotals.length === 0
|
||||
? 0
|
||||
: readTotals.reduce((total, read) => total + read.cpuPercent, 0) / readTotals.length;
|
||||
|
||||
buckets.push({
|
||||
startedAt: dateTimeFromMillis(startedAtMs),
|
||||
endedAt: dateTimeFromMillis(endedAtMs),
|
||||
avgCpuPercent,
|
||||
maxCpuPercent: readTotals.length ? Math.max(...readTotals.map((read) => read.cpuPercent)) : 0,
|
||||
maxRssBytes: readTotals.length ? Math.max(...readTotals.map((read) => read.rssBytes)) : 0,
|
||||
maxProcessCount: readTotals.length
|
||||
? Math.max(...readTotals.map((read) => read.processCount))
|
||||
: 0,
|
||||
});
|
||||
}
|
||||
|
||||
return buckets;
|
||||
}
|
||||
|
||||
export function aggregateProcessResourceHistory(input: {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly readAtMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
readonly lastError: string | null;
|
||||
}): ServerProcessResourceHistoryResult {
|
||||
const windowMs = Math.max(1_000, input.windowMs);
|
||||
const bucketMs = Math.max(1_000, input.bucketMs);
|
||||
const minSampledAtMs = input.readAtMs - windowMs;
|
||||
const samples = input.samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
|
||||
const topProcesses = summarizeProcesses(samples);
|
||||
const totalCpuSecondsApprox = samples.reduce(
|
||||
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
|
||||
0,
|
||||
);
|
||||
|
||||
return {
|
||||
readAt: input.readAt,
|
||||
windowMs,
|
||||
bucketMs,
|
||||
sampleIntervalMs: SAMPLE_INTERVAL_MS,
|
||||
retainedSampleCount: input.samples.length,
|
||||
totalCpuSecondsApprox,
|
||||
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
|
||||
topProcesses,
|
||||
error: input.lastError ? Option.some({ message: input.lastError }) : Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: null });
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
|
||||
const rows = yield* readProcessRows().pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
const samples = collectMonitoredSamples({
|
||||
rows,
|
||||
serverPid: process.pid,
|
||||
sampledAt,
|
||||
sampledAtMs,
|
||||
});
|
||||
yield* Ref.update(state, (current) => ({
|
||||
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
|
||||
lastError: null,
|
||||
}));
|
||||
}).pipe(
|
||||
Effect.catch((error: unknown) =>
|
||||
Ref.update(state, (current) => ({
|
||||
...current,
|
||||
lastError: error instanceof Error ? error.message : "Failed to sample process resources.",
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
yield* sampleOnce.pipe(Effect.repeat(Schedule.spaced(SAMPLE_INTERVAL)), Effect.forkScoped);
|
||||
|
||||
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const readAtMs = DateTime.toEpochMillis(readAt);
|
||||
const current = yield* Ref.get(state);
|
||||
return aggregateProcessResourceHistory({
|
||||
samples: current.samples,
|
||||
readAt,
|
||||
readAtMs,
|
||||
windowMs: input.windowMs,
|
||||
bucketMs: input.bucketMs,
|
||||
lastError: current.lastError,
|
||||
});
|
||||
});
|
||||
|
||||
return ProcessResourceMonitor.of({ readHistory });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessResourceMonitor, make());
|
||||
@@ -18,6 +18,7 @@ const DEFAULT_RPC_SPAN_ATTRIBUTES = {
|
||||
const RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet<string> = new Set([
|
||||
WS_METHODS.serverGetTraceDiagnostics,
|
||||
WS_METHODS.serverGetProcessDiagnostics,
|
||||
WS_METHODS.serverGetProcessResourceHistory,
|
||||
WS_METHODS.serverSignalProcess,
|
||||
]);
|
||||
|
||||
|
||||
@@ -1,241 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
/**
|
||||
* Open - Browser/editor launch service interface.
|
||||
*
|
||||
* Owns process launch helpers for opening URLs in a browser and workspace
|
||||
* paths in a configured editor.
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
|
||||
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
// ==============================
|
||||
|
||||
export { OpenError };
|
||||
export { isCommandAvailable } from "@t3tools/shared/shell";
|
||||
|
||||
export interface OpenInEditorInput {
|
||||
readonly cwd: string;
|
||||
readonly editor: EditorId;
|
||||
}
|
||||
|
||||
interface EditorLaunch {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
|
||||
|
||||
function parseTargetPathAndPosition(target: string): {
|
||||
path: string;
|
||||
line: string | undefined;
|
||||
column: string | undefined;
|
||||
} | null {
|
||||
const match = TARGET_WITH_POSITION_PATTERN.exec(target);
|
||||
if (!match?.[1] || !match[2]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
path: match[1],
|
||||
line: match[2],
|
||||
column: match[3],
|
||||
};
|
||||
}
|
||||
|
||||
function resolveCommandEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const parsedTarget = parseTargetPathAndPosition(target);
|
||||
|
||||
switch (editor.launchStyle) {
|
||||
case "direct-path":
|
||||
return [target];
|
||||
case "goto":
|
||||
return parsedTarget ? ["--goto", target] : [target];
|
||||
case "line-column": {
|
||||
if (!parsedTarget) {
|
||||
return [target];
|
||||
}
|
||||
|
||||
const { path, line, column } = parsedTarget;
|
||||
return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
|
||||
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
|
||||
}
|
||||
|
||||
function resolveAvailableCommand(
|
||||
commands: ReadonlyArray<string>,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): string | null {
|
||||
for (const command of commands) {
|
||||
if (isCommandAvailable(command, options)) {
|
||||
return command;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return "open";
|
||||
case "win32":
|
||||
return "explorer";
|
||||
default:
|
||||
return "xdg-open";
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
if (editor.commands === null) {
|
||||
const command = fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const command = resolveAvailableCommand(editor.commands, { platform, env });
|
||||
if (command !== null) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenShape - Service API for browser and editor launch actions.
|
||||
*/
|
||||
export interface OpenShape {
|
||||
/**
|
||||
* Open a URL target in the default browser.
|
||||
*/
|
||||
readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
|
||||
|
||||
/**
|
||||
* Open a workspace path in a selected editor integration.
|
||||
*
|
||||
* Launches the editor as a detached process so server startup is not blocked.
|
||||
*/
|
||||
readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open - Service tag for browser/editor launch operations.
|
||||
*/
|
||||
export class Open extends Context.Service<Open, OpenShape>()("t3/open") {}
|
||||
|
||||
// ==============================
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
input: OpenInEditorInput,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Effect.fn.Return<EditorLaunch, OpenError> {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"open.editor": input.editor,
|
||||
"open.cwd": input.cwd,
|
||||
"open.platform": platform,
|
||||
});
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
if (editorDef.commands) {
|
||||
const command =
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
|
||||
return {
|
||||
command,
|
||||
args: resolveEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
const isWin32 = process.platform === "win32";
|
||||
child = spawn(
|
||||
launch.command,
|
||||
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
|
||||
{
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: isWin32,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
}
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const open = yield* Effect.tryPromise({
|
||||
try: () => import("open"),
|
||||
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
|
||||
});
|
||||
|
||||
return {
|
||||
openBrowser: (target) =>
|
||||
Effect.tryPromise({
|
||||
try: () => open.default(target),
|
||||
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
||||
}),
|
||||
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
||||
} satisfies OpenShape;
|
||||
});
|
||||
|
||||
export const OpenLive = Layer.effect(Open, make);
|
||||
@@ -2,16 +2,52 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Random from "effect/Random";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
launchBrowser,
|
||||
launchEditorProcess,
|
||||
resolveAvailableEditors,
|
||||
resolveBrowserLaunch,
|
||||
resolveEditorLaunch,
|
||||
} from "./open.ts";
|
||||
} from "./externalLauncher.ts";
|
||||
|
||||
function encodeUtf16LeBase64(input: string): string {
|
||||
const bytes = new Uint8Array(input.length * 2);
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
const code = input.charCodeAt(index);
|
||||
bytes[index * 2] = code & 0xff;
|
||||
bytes[index * 2 + 1] = code >>> 8;
|
||||
}
|
||||
return Encoding.encodeBase64(bytes);
|
||||
}
|
||||
|
||||
function makeMockDetachedHandle(onUnref: () => void = () => undefined) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
|
||||
isRunning: Effect.succeed(true),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.sync(() => {
|
||||
onUnref();
|
||||
return Effect.void;
|
||||
}),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
it.effect("returns commands for command-based editors", () =>
|
||||
@@ -216,70 +252,70 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
});
|
||||
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "cursor" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const traeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "trae" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(traeLineAndColumn, {
|
||||
command: "trae",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const kiroLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "kiro" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLineAndColumn, {
|
||||
command: "kiro",
|
||||
args: ["ide", "--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["ide", "--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLineAndColumn, {
|
||||
command: "code-insiders",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLineAndColumn, {
|
||||
command: "codium",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineOnly = yield* resolveEditorLaunch(
|
||||
@@ -302,102 +338,102 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
});
|
||||
|
||||
const ideaLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "idea" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "idea" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(ideaLineAndColumn, {
|
||||
command: "idea",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const aquaLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "aqua" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "aqua" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(aquaLineAndColumn, {
|
||||
command: "aqua",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const clionLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "clion" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "clion" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(clionLineAndColumn, {
|
||||
command: "clion",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const datagripLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "datagrip" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "datagrip" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(datagripLineAndColumn, {
|
||||
command: "datagrip",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const dataspellLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "dataspell" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "dataspell" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(dataspellLineAndColumn, {
|
||||
command: "dataspell",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const golandLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "goland" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "goland" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(golandLineAndColumn, {
|
||||
command: "goland",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const phpstormLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "phpstorm" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "phpstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(phpstormLineAndColumn, {
|
||||
command: "phpstorm",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const pycharmLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "pycharm" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "pycharm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(pycharmLineAndColumn, {
|
||||
command: "pycharm",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const riderLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rider" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rider" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(riderLineAndColumn, {
|
||||
command: "rider",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const rubymineLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rubymine" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rubymine" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rubymineLineAndColumn, {
|
||||
command: "rubymine",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const rustroverLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rustrover" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rustrover" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rustroverLineAndColumn, {
|
||||
command: "rustrover",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const webstormLineOnly = yield* resolveEditorLaunch(
|
||||
@@ -415,7 +451,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "zeditor"), "#!/bin/sh\nexit 0\n");
|
||||
yield* fs.chmod(path.join(dir, "zeditor"), 0o755);
|
||||
|
||||
@@ -477,23 +513,147 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("launchDetached", (it) => {
|
||||
it.effect("resolves when command can be spawned", () =>
|
||||
it("resolveBrowserLaunch maps default browser launchers by platform", () => {
|
||||
const target = "https://example.com/some path?name=o'hara";
|
||||
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "darwin").command, "open");
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "darwin").args, [target]);
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "darwin").options, {
|
||||
detached: true,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
});
|
||||
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "linux", {}).command, "xdg-open");
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "linux", {}).args, [target]);
|
||||
|
||||
const windows = resolveBrowserLaunch(target, "win32", {
|
||||
SYSTEMROOT: "C:\\Windows",
|
||||
});
|
||||
assert.equal(windows.command, "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
|
||||
assert.deepEqual(windows.args, [
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-EncodedCommand",
|
||||
encodeUtf16LeBase64(
|
||||
"$ProgressPreference = 'SilentlyContinue'; Start 'https://example.com/some path?name=o''hara'",
|
||||
),
|
||||
]);
|
||||
assert.deepEqual(windows.options, {
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveBrowserLaunch opens through Windows from WSL when not remote", () => {
|
||||
const launch = resolveBrowserLaunch("https://example.com", "linux", {
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
});
|
||||
assert.equal(launch.command, "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe");
|
||||
assert.equal(launch.options.detached, true);
|
||||
});
|
||||
|
||||
it("resolveBrowserLaunch keeps xdg-open for WSL over SSH", () => {
|
||||
const launch = resolveBrowserLaunch("https://example.com", "linux", {
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
SSH_CONNECTION: "client server",
|
||||
});
|
||||
assert.equal(launch.command, "xdg-open");
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("launchBrowser", (it) => {
|
||||
it.effect("spawns through the ChildProcessSpawner service and unrefs the handle", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.exit(0)"],
|
||||
}).pipe(Effect.result);
|
||||
let spawnedCommand: ChildProcess.StandardCommand | undefined;
|
||||
let didUnref = false;
|
||||
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: (command) =>
|
||||
Effect.sync(() => {
|
||||
assert.equal(ChildProcess.isStandardCommand(command), true);
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
throw new Error("Expected a standard command");
|
||||
}
|
||||
spawnedCommand = command;
|
||||
return makeMockDetachedHandle(() => {
|
||||
didUnref = true;
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
const result = yield* launchBrowser("https://example.com").pipe(
|
||||
Effect.provide(spawnerLayer),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
assertSuccess(result, undefined);
|
||||
assert.ok(spawnedCommand);
|
||||
const expectedLaunch = resolveBrowserLaunch("https://example.com");
|
||||
assert.equal(spawnedCommand.command, expectedLaunch.command);
|
||||
assert.deepEqual(spawnedCommand.args, expectedLaunch.args);
|
||||
assert.deepEqual(spawnedCommand.options, expectedLaunch.options);
|
||||
assert.equal(didUnref, true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("launchEditorProcess", (it) => {
|
||||
it.effect("spawns through the ChildProcessSpawner service and unrefs the handle", () =>
|
||||
Effect.gen(function* () {
|
||||
let spawnedCommand: ChildProcess.StandardCommand | undefined;
|
||||
let didUnref = false;
|
||||
const expectedArgs = ["-e", "process.exit(0)"];
|
||||
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: (command) =>
|
||||
Effect.sync(() => {
|
||||
assert.equal(ChildProcess.isStandardCommand(command), true);
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
throw new Error("Expected a standard command");
|
||||
}
|
||||
spawnedCommand = command;
|
||||
return makeMockDetachedHandle(() => {
|
||||
didUnref = true;
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
const result = yield* launchEditorProcess({
|
||||
command: process.execPath,
|
||||
args: expectedArgs,
|
||||
}).pipe(Effect.provide(spawnerLayer), Effect.result);
|
||||
|
||||
assertSuccess(result, undefined);
|
||||
assert.ok(spawnedCommand);
|
||||
assert.equal(spawnedCommand.command, process.execPath);
|
||||
assert.deepEqual(
|
||||
spawnedCommand.args,
|
||||
process.platform === "win32" ? expectedArgs.map((arg) => `"${arg}"`) : expectedArgs,
|
||||
);
|
||||
assert.deepEqual(spawnedCommand.options, {
|
||||
detached: true,
|
||||
shell: process.platform === "win32",
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
});
|
||||
assert.equal(didUnref, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects when command does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {});
|
||||
const result = yield* launchEditorProcess({
|
||||
command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
|
||||
args: [],
|
||||
}).pipe(Effect.result);
|
||||
}).pipe(Effect.provide(spawnerLayer), Effect.result);
|
||||
assert.equal(result._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
@@ -504,7 +664,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
@@ -526,7 +686,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
@@ -540,7 +700,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
@@ -554,8 +714,8 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
|
||||
const env = {
|
||||
@@ -0,0 +1,364 @@
|
||||
/**
|
||||
* ExternalLauncher - external application launch service interface.
|
||||
*
|
||||
* Owns process launch helpers for browser URLs and workspace paths
|
||||
* in configured editor integrations.
|
||||
*
|
||||
* @module ExternalLauncher
|
||||
*/
|
||||
import {
|
||||
EDITORS,
|
||||
ExternalLauncherError,
|
||||
type EditorId,
|
||||
type LaunchEditorInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
// ==============================
|
||||
|
||||
export { ExternalLauncherError };
|
||||
export type { LaunchEditorInput };
|
||||
export { isCommandAvailable } from "@t3tools/shared/shell";
|
||||
|
||||
interface EditorLaunch {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
interface ProcessLaunch {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly options: ChildProcess.CommandOptions;
|
||||
}
|
||||
|
||||
interface TargetPathAndPosition {
|
||||
readonly path: string;
|
||||
readonly line: string;
|
||||
readonly column: Option.Option<string>;
|
||||
}
|
||||
|
||||
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
|
||||
const POWERSHELL_ARGUMENTS_PREFIX = [
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-EncodedCommand",
|
||||
] as const;
|
||||
|
||||
const DETACHED_IGNORE_STDIO_OPTIONS = {
|
||||
detached: true,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
} as const satisfies ChildProcess.CommandOptions;
|
||||
|
||||
function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
|
||||
const match = TARGET_WITH_POSITION_PATTERN.exec(target);
|
||||
if (!match?.[1] || !match[2]) {
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
return Option.some({
|
||||
path: match[1],
|
||||
line: match[2],
|
||||
column: Option.fromUndefinedOr(match[3]),
|
||||
});
|
||||
}
|
||||
|
||||
function resolveCommandEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const parsedTarget = parseTargetPathAndPosition(target);
|
||||
|
||||
switch (editor.launchStyle) {
|
||||
case "direct-path":
|
||||
return [target];
|
||||
case "goto":
|
||||
return Option.isSome(parsedTarget) ? ["--goto", target] : [target];
|
||||
case "line-column":
|
||||
return Option.match(parsedTarget, {
|
||||
onNone: () => [target],
|
||||
onSome: ({ path, line, column }) => [
|
||||
"--line",
|
||||
line,
|
||||
...Option.match(column, {
|
||||
onNone: () => [],
|
||||
onSome: (value) => ["--column", value],
|
||||
}),
|
||||
path,
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
|
||||
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
|
||||
}
|
||||
|
||||
function resolveAvailableCommand(
|
||||
commands: ReadonlyArray<string>,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): Option.Option<string> {
|
||||
for (const command of commands) {
|
||||
if (isCommandAvailable(command, options)) {
|
||||
return Option.some(command);
|
||||
}
|
||||
}
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
function encodeUtf16LeBase64(input: string): string {
|
||||
const bytes = new Uint8Array(input.length * 2);
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
const code = input.charCodeAt(index);
|
||||
bytes[index * 2] = code & 0xff;
|
||||
bytes[index * 2 + 1] = code >>> 8;
|
||||
}
|
||||
return Encoding.encodeBase64(bytes);
|
||||
}
|
||||
|
||||
function escapePowerShellStringLiteral(input: string): string {
|
||||
return `'${input.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
function resolvePowerShellPath(env: NodeJS.ProcessEnv = process.env): string {
|
||||
return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
|
||||
}
|
||||
|
||||
function resolveWslPowerShellPath(): string {
|
||||
return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
|
||||
}
|
||||
|
||||
function shouldUseWindowsBrowserFromWsl(
|
||||
platform: NodeJS.Platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): boolean {
|
||||
return (
|
||||
platform === "linux" &&
|
||||
(env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
|
||||
env.SSH_CONNECTION === undefined &&
|
||||
env.SSH_TTY === undefined &&
|
||||
env.container === undefined
|
||||
);
|
||||
}
|
||||
|
||||
function resolveWindowsBrowserLaunch(target: string, command: string): ProcessLaunch {
|
||||
const encodedCommand = encodeUtf16LeBase64(
|
||||
`$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
|
||||
);
|
||||
return {
|
||||
command,
|
||||
args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
|
||||
options: {
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return "open";
|
||||
case "win32":
|
||||
return "explorer";
|
||||
default:
|
||||
return "xdg-open";
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveBrowserLaunch(
|
||||
target: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ProcessLaunch {
|
||||
if (platform === "darwin") {
|
||||
return {
|
||||
command: "open",
|
||||
args: [target],
|
||||
options: DETACHED_IGNORE_STDIO_OPTIONS,
|
||||
};
|
||||
}
|
||||
|
||||
if (platform === "win32") {
|
||||
return resolveWindowsBrowserLaunch(target, resolvePowerShellPath(env));
|
||||
}
|
||||
|
||||
if (shouldUseWindowsBrowserFromWsl(platform, env)) {
|
||||
return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath());
|
||||
}
|
||||
|
||||
return {
|
||||
command: "xdg-open",
|
||||
args: [target],
|
||||
options: DETACHED_IGNORE_STDIO_OPTIONS,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
if (editor.commands === null) {
|
||||
const command = fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const command = resolveAvailableCommand(editor.commands, { platform, env });
|
||||
if (Option.isSome(command)) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
}
|
||||
|
||||
/**
|
||||
* ExternalLauncherShape - Service API for browser and editor launch actions.
|
||||
*/
|
||||
export interface ExternalLauncherShape {
|
||||
/**
|
||||
* Launch a URL target in the default browser.
|
||||
*/
|
||||
readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
|
||||
|
||||
/**
|
||||
* Launch a workspace path in a selected editor integration.
|
||||
*
|
||||
* Launches the editor as a detached process so server startup is not blocked.
|
||||
*/
|
||||
readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ExternalLauncher - Service tag for browser/editor launch operations.
|
||||
*/
|
||||
export class ExternalLauncher extends Context.Service<ExternalLauncher, ExternalLauncherShape>()(
|
||||
"t3/process/ExternalLauncher",
|
||||
) {}
|
||||
|
||||
// ==============================
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
input: LaunchEditorInput,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Effect.fn.Return<EditorLaunch, ExternalLauncherError> {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"externalLauncher.editor": input.editor,
|
||||
"externalLauncher.cwd": input.cwd,
|
||||
"externalLauncher.platform": platform,
|
||||
});
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new ExternalLauncherError({ message: `Unknown editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
if (editorDef.commands) {
|
||||
const command = Option.getOrElse(
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }),
|
||||
() => editorDef.commands[0],
|
||||
);
|
||||
return {
|
||||
command,
|
||||
args: resolveEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new ExternalLauncherError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
});
|
||||
|
||||
const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
|
||||
launch: ProcessLaunch,
|
||||
errorMessage: string,
|
||||
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make(launch.command, launch.args, launch.options);
|
||||
|
||||
yield* spawner.spawn(command).pipe(
|
||||
Effect.flatMap((handle) => handle.unref),
|
||||
Effect.asVoid,
|
||||
Effect.scoped,
|
||||
Effect.mapError((cause) => new ExternalLauncherError({ message: errorMessage, cause })),
|
||||
);
|
||||
});
|
||||
|
||||
export const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
|
||||
target: string,
|
||||
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
return yield* launchAndUnref(resolveBrowserLaunch(target), "Browser auto-open failed");
|
||||
});
|
||||
|
||||
export const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
|
||||
launch: EditorLaunch,
|
||||
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new ExternalLauncherError({
|
||||
message: `Editor command not found: ${launch.command}`,
|
||||
});
|
||||
}
|
||||
|
||||
const isWin32 = process.platform === "win32";
|
||||
yield* launchAndUnref(
|
||||
{
|
||||
command: launch.command,
|
||||
args: isWin32 ? launch.args.map((arg) => `"${arg}"`) : [...launch.args],
|
||||
options: {
|
||||
detached: true,
|
||||
shell: isWin32,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
},
|
||||
"failed to spawn detached process",
|
||||
);
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
return {
|
||||
launchBrowser: (target) =>
|
||||
launchBrowser(target).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
),
|
||||
launchEditor: (input) =>
|
||||
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
|
||||
launchEditorProcess(launch).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
),
|
||||
),
|
||||
} satisfies ExternalLauncherShape;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ExternalLauncher, make);
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
GitCommandError,
|
||||
KeybindingRule,
|
||||
MessageId,
|
||||
OpenError,
|
||||
ExternalLauncherError,
|
||||
type OrchestrationThreadShell,
|
||||
TerminalNotRunningError,
|
||||
type OrchestrationCommand,
|
||||
@@ -63,7 +63,7 @@ import {
|
||||
} from "./checkpointing/Services/CheckpointDiffQuery.ts";
|
||||
import { GitManager, type GitManagerShape } from "./git/GitManager.ts";
|
||||
import { Keybindings, type KeybindingsShape } from "./keybindings.ts";
|
||||
import { Open, type OpenShape } from "./open.ts";
|
||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
@@ -115,6 +115,7 @@ import * as SourceControlRepositoryService from "./sourceControl/SourceControlRe
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
import * as Data from "effect/Data";
|
||||
|
||||
@@ -319,7 +320,7 @@ const buildAppUnderTest = (options?: {
|
||||
keybindings?: Partial<KeybindingsShape>;
|
||||
providerRegistry?: Partial<ProviderRegistryShape>;
|
||||
serverSettings?: Partial<ServerSettingsShape>;
|
||||
open?: Partial<OpenShape>;
|
||||
externalLauncher?: Partial<ExternalLauncher.ExternalLauncherShape>;
|
||||
vcsDriver?: Partial<VcsDriver.VcsDriverShape>;
|
||||
vcsDriverRegistry?: Partial<VcsDriverRegistry.VcsDriverRegistryShape>;
|
||||
gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
|
||||
@@ -540,8 +541,8 @@ const buildAppUnderTest = (options?: {
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(Open)({
|
||||
...options?.layers?.open,
|
||||
Layer.mock(ExternalLauncher.ExternalLauncher)({
|
||||
...options?.layers?.externalLauncher,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
@@ -564,6 +565,22 @@ const buildAppUnderTest = (options?: {
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ProcessResourceMonitor.ProcessResourceMonitor)({
|
||||
readHistory: (input) =>
|
||||
Effect.succeed({
|
||||
readAt: TEST_EPOCH,
|
||||
windowMs: input.windowMs,
|
||||
bucketMs: input.bucketMs,
|
||||
sampleIntervalMs: 5_000,
|
||||
retainedSampleCount: 0,
|
||||
totalCpuSecondsApprox: 0,
|
||||
buckets: [],
|
||||
topProcesses: [],
|
||||
error: Option.none(),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(TraceDiagnostics.TraceDiagnostics)({
|
||||
read: () =>
|
||||
@@ -2517,8 +2534,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
let openedInput: { cwd: string; editor: EditorId } | null = null;
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
open: {
|
||||
openInEditor: (input) =>
|
||||
externalLauncher: {
|
||||
launchEditor: (input) =>
|
||||
Effect.sync(() => {
|
||||
openedInput = input;
|
||||
}),
|
||||
@@ -2542,11 +2559,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
it.effect("routes websocket rpc shell.openInEditor errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const openError = new OpenError({ message: "Editor command not found: cursor" });
|
||||
const externalLauncherError = new ExternalLauncherError({
|
||||
message: "Editor command not found: cursor",
|
||||
});
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
open: {
|
||||
openInEditor: () => Effect.fail(openError),
|
||||
externalLauncher: {
|
||||
launchEditor: () => Effect.fail(externalLauncherError),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -2561,7 +2580,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
).pipe(Effect.result),
|
||||
);
|
||||
|
||||
assertFailure(result, openError);
|
||||
assertFailure(result, externalLauncherError);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from "./http.ts";
|
||||
import { fixPath } from "./os-jank.ts";
|
||||
import { websocketRpcRouteLayer } from "./ws.ts";
|
||||
import { OpenLive } from "./open.ts";
|
||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
|
||||
import { ServerLifecycleEventsLive } from "./serverLifecycleEvents.ts";
|
||||
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService.ts";
|
||||
@@ -76,6 +76,7 @@ import {
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import {
|
||||
@@ -280,9 +281,10 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
|
||||
// Misc.
|
||||
Layer.provideMerge(ProcessDiagnostics.layer),
|
||||
Layer.provideMerge(ProcessResourceMonitor.layer),
|
||||
Layer.provideMerge(TraceDiagnostics.layer),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(ExternalLauncher.layer),
|
||||
Layer.provideMerge(ServerLifecycleEventsLive),
|
||||
Layer.provide(NetService.layer),
|
||||
);
|
||||
|
||||
@@ -23,7 +23,7 @@ import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { Keybindings } from "./keybindings.ts";
|
||||
import { Open } from "./open.ts";
|
||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor.ts";
|
||||
@@ -261,9 +261,9 @@ const maybeOpenBrowser = (target: string) =>
|
||||
if (serverConfig.noBrowser) {
|
||||
return;
|
||||
}
|
||||
const { openBrowser } = yield* Open;
|
||||
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
|
||||
|
||||
yield* openBrowser(target).pipe(
|
||||
yield* externalLauncher.launchBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
hint: `Open ${target} in your browser.`,
|
||||
|
||||
@@ -67,4 +67,24 @@ describe("VcsProjectConfig", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("falls back to auto when config is invalid", (it) => {
|
||||
it.effect("returns auto", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-vcs-config-test-",
|
||||
});
|
||||
const configDir = path.join(root, ".t3code");
|
||||
yield* fileSystem.makeDirectory(configDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(path.join(configDir, "vcs.json"), "{");
|
||||
|
||||
const config = yield* VcsProjectConfig.VcsProjectConfig;
|
||||
const kind = yield* config.resolveKind({ cwd: root });
|
||||
|
||||
assert.equal(kind, "auto");
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
@@ -15,16 +16,9 @@ const ProjectVcsConfig = Schema.Struct({
|
||||
),
|
||||
vcsKind: Schema.optional(VcsDriverKind),
|
||||
});
|
||||
const isProjectVcsConfig = Schema.is(ProjectVcsConfig);
|
||||
type ProjectVcsConfigFile = Schema.Schema.Type<typeof ProjectVcsConfig>;
|
||||
|
||||
interface ProjectVcsConfigFile {
|
||||
readonly vcs?:
|
||||
| {
|
||||
readonly kind?: VcsDriverKindType | undefined;
|
||||
}
|
||||
| undefined;
|
||||
readonly vcsKind?: VcsDriverKindType | undefined;
|
||||
}
|
||||
const decodeProjectVcsConfig = Schema.decodeUnknownEffect(Schema.fromJsonString(ProjectVcsConfig));
|
||||
|
||||
export interface VcsProjectConfigResolveInput {
|
||||
readonly cwd: string;
|
||||
@@ -45,15 +39,6 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
|
||||
return config.vcs?.kind ?? config.vcsKind ?? "auto";
|
||||
}
|
||||
|
||||
function parseConfig(raw: string): ProjectVcsConfigFile | null {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
return isProjectVcsConfig(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeVcsProjectConfig")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -63,12 +48,12 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
|
||||
while (true) {
|
||||
const candidate = path.join(current, ".t3code", "vcs.json");
|
||||
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return candidate;
|
||||
return Option.some(candidate);
|
||||
}
|
||||
|
||||
const parent = path.dirname(current);
|
||||
if (parent === current) {
|
||||
return null;
|
||||
return Option.none<string>();
|
||||
}
|
||||
current = parent;
|
||||
}
|
||||
@@ -78,26 +63,27 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
|
||||
configPath: string,
|
||||
) {
|
||||
const raw = yield* fileSystem.readFileString(configPath).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to read VCS project config", {
|
||||
configPath,
|
||||
error,
|
||||
}).pipe(Effect.as(null)),
|
||||
}).pipe(Effect.as(Option.none<string>())),
|
||||
),
|
||||
);
|
||||
if (raw === null) {
|
||||
if (Option.isNone(raw)) {
|
||||
return "auto" as const;
|
||||
}
|
||||
|
||||
const parsed = parseConfig(raw);
|
||||
if (parsed === null) {
|
||||
const parsed = yield* decodeProjectVcsConfig(raw.value).pipe(Effect.option);
|
||||
if (Option.isNone(parsed)) {
|
||||
yield* Effect.logWarning("invalid VCS project config", {
|
||||
configPath,
|
||||
});
|
||||
return "auto" as const;
|
||||
}
|
||||
|
||||
return configuredKind(parsed);
|
||||
return configuredKind(parsed.value);
|
||||
});
|
||||
|
||||
const resolveKind: VcsProjectConfigShape["resolveKind"] = Effect.fn(
|
||||
@@ -108,11 +94,10 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
|
||||
}
|
||||
|
||||
const configPath = yield* findConfigPath(input.cwd);
|
||||
if (configPath === null) {
|
||||
return "auto";
|
||||
}
|
||||
|
||||
return yield* readConfiguredKind(configPath);
|
||||
return yield* Option.match(configPath, {
|
||||
onNone: () => Effect.succeed("auto" as const),
|
||||
onSome: readConfiguredKind,
|
||||
});
|
||||
});
|
||||
|
||||
return VcsProjectConfig.of({
|
||||
|
||||
@@ -310,6 +310,29 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
|
||||
assert.equal(
|
||||
Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
|
||||
30_000,
|
||||
);
|
||||
assert.equal(
|
||||
Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(2, Duration.seconds(1))),
|
||||
60_000,
|
||||
);
|
||||
assert.equal(
|
||||
Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(3, Duration.seconds(1))),
|
||||
120_000,
|
||||
);
|
||||
assert.equal(
|
||||
Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.minutes(5))),
|
||||
300_000,
|
||||
);
|
||||
assert.equal(
|
||||
Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(20, Duration.seconds(1))),
|
||||
900_000,
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
|
||||
@@ -7,6 +7,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
@@ -23,6 +24,8 @@ import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
|
||||
|
||||
const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
|
||||
const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
|
||||
const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);
|
||||
|
||||
interface VcsStatusChange {
|
||||
readonly cwd: string;
|
||||
@@ -48,6 +51,20 @@ interface StreamStatusOptions {
|
||||
readonly automaticRemoteRefreshInterval?: Effect.Effect<Duration.Duration, never>;
|
||||
}
|
||||
|
||||
export function remoteRefreshFailureDelay(
|
||||
consecutiveFailures: number,
|
||||
configuredInterval: Duration.Duration,
|
||||
) {
|
||||
const exponent = Math.max(0, consecutiveFailures - 1);
|
||||
const backoffMs =
|
||||
Duration.toMillis(VCS_STATUS_REFRESH_FAILURE_BASE_DELAY) * Math.pow(2, exponent);
|
||||
const cappedBackoff = Duration.min(
|
||||
Duration.millis(backoffMs),
|
||||
VCS_STATUS_REFRESH_FAILURE_MAX_DELAY,
|
||||
);
|
||||
return Duration.max(configuredInterval, cappedBackoff);
|
||||
}
|
||||
|
||||
export interface VcsStatusBroadcasterShape {
|
||||
readonly getStatus: (
|
||||
input: VcsStatusInput,
|
||||
@@ -241,32 +258,46 @@ export const layer = Layer.effect(
|
||||
cwd: string,
|
||||
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
|
||||
) => {
|
||||
const logRefreshFailure = (error: GitManagerServiceError) =>
|
||||
Effect.logWarning("VCS remote status refresh failed", {
|
||||
cwd,
|
||||
detail: error.message,
|
||||
});
|
||||
const refreshRemoteStatusIfEnabled = automaticRemoteRefreshInterval.pipe(
|
||||
Effect.flatMap((interval) =>
|
||||
Duration.isZero(interval) ? Effect.void : refreshRemoteStatus(cwd).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
const sleepForConfiguredInterval = automaticRemoteRefreshInterval.pipe(
|
||||
Effect.flatMap((interval) =>
|
||||
Effect.sleep(Duration.isZero(interval) ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL : interval),
|
||||
),
|
||||
);
|
||||
return Effect.gen(function* () {
|
||||
const consecutiveFailuresRef = yield* Ref.make(0);
|
||||
const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
|
||||
const configuredInterval = yield* automaticRemoteRefreshInterval;
|
||||
const activeInterval = Duration.isZero(configuredInterval)
|
||||
? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
|
||||
: configuredInterval;
|
||||
if (Duration.isZero(configuredInterval)) {
|
||||
return activeInterval;
|
||||
}
|
||||
|
||||
return refreshRemoteStatusIfEnabled.pipe(
|
||||
Effect.catch(logRefreshFailure),
|
||||
Effect.andThen(
|
||||
Effect.forever(
|
||||
sleepForConfiguredInterval.pipe(
|
||||
Effect.andThen(refreshRemoteStatusIfEnabled.pipe(Effect.catch(logRefreshFailure))),
|
||||
const exit = yield* refreshRemoteStatus(cwd).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(exit)) {
|
||||
yield* Ref.set(consecutiveFailuresRef, 0);
|
||||
return activeInterval;
|
||||
}
|
||||
|
||||
const consecutiveFailures = yield* Ref.updateAndGet(
|
||||
consecutiveFailuresRef,
|
||||
(count) => count + 1,
|
||||
);
|
||||
const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
|
||||
yield* Effect.logWarning("VCS remote status refresh failed", {
|
||||
cwd,
|
||||
detail: exit.cause.toString(),
|
||||
consecutiveFailures,
|
||||
nextDelayMs: Duration.toMillis(nextDelay),
|
||||
});
|
||||
return nextDelay;
|
||||
});
|
||||
|
||||
return yield* refreshRemoteStatusIfEnabled.pipe(
|
||||
Effect.repeat(
|
||||
Schedule.identity<Duration.Duration>().pipe(
|
||||
Schedule.addDelay((delay) => Effect.succeed(delay)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
Effect.asVoid,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
|
||||
|
||||
@@ -40,7 +40,7 @@ import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
|
||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery.ts";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { Keybindings } from "./keybindings.ts";
|
||||
import { Open, resolveAvailableEditors } from "./open.ts";
|
||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
@@ -66,6 +66,7 @@ import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentit
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
import * as SourceControlDiscoveryLayer from "./sourceControl/SourceControlDiscovery.ts";
|
||||
import { SourceControlRepositoryService } from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
@@ -163,7 +164,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const checkpointDiffQuery = yield* CheckpointDiffQuery;
|
||||
const keybindings = yield* Keybindings;
|
||||
const open = yield* Open;
|
||||
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsProvisioning = yield* VcsProvisioningService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
@@ -193,6 +194,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
|
||||
const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;
|
||||
const serverCommandId = (tag: string) =>
|
||||
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
@@ -583,7 +585,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
keybindings: keybindingsConfig.keybindings,
|
||||
issues: keybindingsConfig.issues,
|
||||
providers,
|
||||
availableEditors: resolveAvailableEditors(),
|
||||
availableEditors: ExternalLauncher.resolveAvailableEditors(),
|
||||
observability: {
|
||||
logsDirectoryPath: config.logsDir,
|
||||
localTracingEnabled: true,
|
||||
@@ -909,6 +911,14 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
observeRpcEffect(WS_METHODS.serverGetProcessDiagnostics, processDiagnostics.read, {
|
||||
"rpc.aggregate": "server",
|
||||
}),
|
||||
[WS_METHODS.serverGetProcessResourceHistory]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverGetProcessResourceHistory,
|
||||
processResourceMonitor.readHistory(input),
|
||||
{
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverSignalProcess]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.serverSignalProcess, processDiagnostics.signal(input), {
|
||||
"rpc.aggregate": "server",
|
||||
@@ -970,7 +980,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.shellOpenInEditor]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
|
||||
observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {
|
||||
"rpc.aggregate": "workspace",
|
||||
}),
|
||||
[WS_METHODS.filesystemBrowse]: (input) =>
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import { defineConfig } from "tsdown";
|
||||
|
||||
const internalPackagePrefixes = ["@t3tools/", "effect-acp", "effect-codex-app-server"];
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/bin.ts"],
|
||||
format: ["esm", "cjs"],
|
||||
checks: {
|
||||
legacyCjs: false,
|
||||
},
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
|
||||
noExternal: (id) => internalPackagePrefixes.some((prefix) => id.startsWith(prefix)),
|
||||
inlineOnly: false,
|
||||
banner: {
|
||||
js: "#!/usr/bin/env node\n",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.23",
|
||||
"version": "0.0.24",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -35,8 +35,8 @@
|
||||
"effect": "catalog:",
|
||||
"lexical": "^0.41.0",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6",
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
@@ -48,12 +48,12 @@
|
||||
"@tailwindcss/vite": "^4.0.0",
|
||||
"@tanstack/router-plugin": "^1.161.0",
|
||||
"@types/babel__core": "^7.20.5",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@types/react": "~19.2.14",
|
||||
"@types/react-dom": "~19.2.3",
|
||||
"@vercel/config": "^0.3.0",
|
||||
"@vitejs/plugin-react": "^6.0.0",
|
||||
"@vitest/browser-playwright": "^4.0.18",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"babel-plugin-react-compiler": "1.0.0",
|
||||
"msw": "2.12.11",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
|
||||
@@ -3607,7 +3607,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
<div className="relative z-10">
|
||||
<ChatComposer
|
||||
ref={composerRef}
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
|
||||
@@ -364,12 +364,12 @@ export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
}, [keybindings, terminalOpen, toggleOpen]);
|
||||
|
||||
return (
|
||||
<ComposerHandleContext.Provider value={composerHandleRef}>
|
||||
<ComposerHandleContext value={composerHandleRef}>
|
||||
<CommandDialog open={open} onOpenChange={setOpen}>
|
||||
{children}
|
||||
<CommandPaletteDialog />
|
||||
</CommandDialog>
|
||||
</ComposerHandleContext.Provider>
|
||||
</ComposerHandleContext>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -38,17 +38,14 @@ import {
|
||||
} from "lexical";
|
||||
import {
|
||||
createContext,
|
||||
forwardRef,
|
||||
use,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useEffectEvent,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ClipboardEventHandler,
|
||||
type ReactElement,
|
||||
type Ref,
|
||||
} from "react";
|
||||
|
||||
import {
|
||||
@@ -160,7 +157,7 @@ function ComposerMentionDecorator(props: { path: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
class ComposerMentionNode extends DecoratorNode<ReactElement> {
|
||||
class ComposerMentionNode extends DecoratorNode<React.ReactElement> {
|
||||
__path: string;
|
||||
|
||||
static override getType(): string {
|
||||
@@ -208,7 +205,7 @@ class ComposerMentionNode extends DecoratorNode<ReactElement> {
|
||||
return true;
|
||||
}
|
||||
|
||||
override decorate(): ReactElement {
|
||||
override decorate(): React.ReactElement {
|
||||
return <ComposerMentionDecorator path={this.__path} />;
|
||||
}
|
||||
}
|
||||
@@ -278,7 +275,7 @@ function ComposerSkillDecorator(props: { skillLabel: string; skillDescription: s
|
||||
);
|
||||
}
|
||||
|
||||
class ComposerSkillNode extends DecoratorNode<ReactElement> {
|
||||
class ComposerSkillNode extends DecoratorNode<React.ReactElement> {
|
||||
__skillName: string;
|
||||
__skillLabel: string;
|
||||
__skillDescription: string | null;
|
||||
@@ -346,7 +343,7 @@ class ComposerSkillNode extends DecoratorNode<ReactElement> {
|
||||
return true;
|
||||
}
|
||||
|
||||
override decorate(): ReactElement {
|
||||
override decorate(): React.ReactElement {
|
||||
return (
|
||||
<ComposerSkillDecorator
|
||||
skillLabel={this.__skillLabel}
|
||||
@@ -368,7 +365,7 @@ function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft
|
||||
return <ComposerPendingTerminalContextChip context={props.context} />;
|
||||
}
|
||||
|
||||
class ComposerTerminalContextNode extends DecoratorNode<ReactElement> {
|
||||
class ComposerTerminalContextNode extends DecoratorNode<React.ReactElement> {
|
||||
__context: TerminalContextDraft;
|
||||
|
||||
static override getType(): string {
|
||||
@@ -417,7 +414,7 @@ class ComposerTerminalContextNode extends DecoratorNode<ReactElement> {
|
||||
return true;
|
||||
}
|
||||
|
||||
override decorate(): ReactElement {
|
||||
override decorate(): React.ReactElement {
|
||||
return <ComposerTerminalContextDecorator context={this.__context} />;
|
||||
}
|
||||
}
|
||||
@@ -900,11 +897,8 @@ interface ComposerPromptEditorProps {
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent,
|
||||
) => boolean;
|
||||
onPaste: ClipboardEventHandler<HTMLElement>;
|
||||
}
|
||||
|
||||
interface ComposerPromptEditorInnerProps extends ComposerPromptEditorProps {
|
||||
editorRef: Ref<ComposerPromptEditorHandle>;
|
||||
onPaste: React.ClipboardEventHandler<HTMLElement>;
|
||||
editorRef: React.RefObject<ComposerPromptEditorHandle | null>;
|
||||
}
|
||||
|
||||
function ComposerCommandKeyPlugin(props: {
|
||||
@@ -1059,7 +1053,7 @@ function ComposerInlineTokenSelectionNormalizePlugin() {
|
||||
|
||||
function ComposerInlineTokenBackspacePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const { onRemoveTerminalContext } = useContext(ComposerTerminalContextActionsContext);
|
||||
const { onRemoveTerminalContext } = use(ComposerTerminalContextActionsContext);
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerCommand(
|
||||
@@ -1150,68 +1144,65 @@ function ComposerSurroundSelectionPlugin(props: {
|
||||
skillMetadataRef.current = skillMetadataByName(props.skills);
|
||||
}, [props.skills]);
|
||||
|
||||
const applySurroundInsertion = useCallback(
|
||||
(inputData: string): boolean => {
|
||||
const surroundCloseSymbol = SURROUND_SYMBOLS_MAP.get(inputData);
|
||||
const pendingSurroundSelection = pendingSurroundSelectionRef.current;
|
||||
if (!surroundCloseSymbol) {
|
||||
pendingSurroundSelectionRef.current = null;
|
||||
return false;
|
||||
const applySurroundInsertion = useEffectEvent((inputData: string): boolean => {
|
||||
const surroundCloseSymbol = SURROUND_SYMBOLS_MAP.get(inputData);
|
||||
const pendingSurroundSelection = pendingSurroundSelectionRef.current;
|
||||
if (!surroundCloseSymbol) {
|
||||
pendingSurroundSelectionRef.current = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
let handled = false;
|
||||
editor.update(() => {
|
||||
const selectionSnapshot =
|
||||
pendingSurroundSelection ??
|
||||
(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || selection.isCollapsed()) {
|
||||
return null;
|
||||
}
|
||||
if ($selectionTouchesInlineToken(selection)) {
|
||||
return null;
|
||||
}
|
||||
const range = getSelectionRangeForExpandedComposerOffsets(selection);
|
||||
if (!range || range.start === range.end) {
|
||||
return null;
|
||||
}
|
||||
const value = $getRoot().getTextContent();
|
||||
if (selectionTouchesMentionBoundary(value, range.start, range.end)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
value,
|
||||
expandedStart: range.start,
|
||||
expandedEnd: range.end,
|
||||
};
|
||||
})();
|
||||
|
||||
if (!selectionSnapshot || !surroundCloseSymbol) {
|
||||
return;
|
||||
}
|
||||
|
||||
let handled = false;
|
||||
editor.update(() => {
|
||||
const selectionSnapshot =
|
||||
pendingSurroundSelection ??
|
||||
(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || selection.isCollapsed()) {
|
||||
return null;
|
||||
}
|
||||
if ($selectionTouchesInlineToken(selection)) {
|
||||
return null;
|
||||
}
|
||||
const range = getSelectionRangeForExpandedComposerOffsets(selection);
|
||||
if (!range || range.start === range.end) {
|
||||
return null;
|
||||
}
|
||||
const value = $getRoot().getTextContent();
|
||||
if (selectionTouchesMentionBoundary(value, range.start, range.end)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
value,
|
||||
expandedStart: range.start,
|
||||
expandedEnd: range.end,
|
||||
};
|
||||
})();
|
||||
const selectedText = selectionSnapshot.value.slice(
|
||||
selectionSnapshot.expandedStart,
|
||||
selectionSnapshot.expandedEnd,
|
||||
);
|
||||
const nextValue = `${selectionSnapshot.value.slice(0, selectionSnapshot.expandedStart)}${inputData}${selectedText}${surroundCloseSymbol}${selectionSnapshot.value.slice(selectionSnapshot.expandedEnd)}`;
|
||||
$setComposerEditorPrompt(nextValue, terminalContextsRef.current, skillMetadataRef.current);
|
||||
const selectionStart = collapseExpandedComposerCursor(
|
||||
nextValue,
|
||||
selectionSnapshot.expandedStart,
|
||||
);
|
||||
$setSelectionRangeAtComposerOffsets(
|
||||
selectionStart + inputData.length,
|
||||
selectionStart + inputData.length + selectedText.length,
|
||||
);
|
||||
handled = true;
|
||||
pendingSurroundSelectionRef.current = null;
|
||||
});
|
||||
|
||||
if (!selectionSnapshot || !surroundCloseSymbol) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedText = selectionSnapshot.value.slice(
|
||||
selectionSnapshot.expandedStart,
|
||||
selectionSnapshot.expandedEnd,
|
||||
);
|
||||
const nextValue = `${selectionSnapshot.value.slice(0, selectionSnapshot.expandedStart)}${inputData}${selectedText}${surroundCloseSymbol}${selectionSnapshot.value.slice(selectionSnapshot.expandedEnd)}`;
|
||||
$setComposerEditorPrompt(nextValue, terminalContextsRef.current, skillMetadataRef.current);
|
||||
const selectionStart = collapseExpandedComposerCursor(
|
||||
nextValue,
|
||||
selectionSnapshot.expandedStart,
|
||||
);
|
||||
$setSelectionRangeAtComposerOffsets(
|
||||
selectionStart + inputData.length,
|
||||
selectionStart + inputData.length + selectedText.length,
|
||||
);
|
||||
handled = true;
|
||||
pendingSurroundSelectionRef.current = null;
|
||||
});
|
||||
|
||||
return handled;
|
||||
},
|
||||
[editor],
|
||||
);
|
||||
return handled;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
@@ -1388,7 +1379,7 @@ function ComposerSurroundSelectionPlugin(props: {
|
||||
}
|
||||
unregisterRootListener();
|
||||
};
|
||||
}, [applySurroundInsertion, editor]);
|
||||
}, [editor]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1406,7 +1397,7 @@ function ComposerPromptEditorInner({
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
editorRef,
|
||||
}: ComposerPromptEditorInnerProps) {
|
||||
}: ComposerPromptEditorProps) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const onChangeRef = useRef(onChange);
|
||||
const initialCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
@@ -1614,13 +1605,13 @@ function ComposerPromptEditorInner({
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ComposerTerminalContextActionsContext.Provider value={terminalContextActions}>
|
||||
<ComposerTerminalContextActionsContext value={terminalContextActions}>
|
||||
<div className="relative">
|
||||
<PlainTextPlugin
|
||||
contentEditable={
|
||||
<ContentEditable
|
||||
className={cn(
|
||||
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap wrap-break-word bg-transparent text-[16px] leading-relaxed text-foreground focus:outline-none sm:text-[14px]",
|
||||
"block max-h-50 min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap wrap-break-word bg-transparent text-[16px] leading-relaxed text-foreground focus:outline-none sm:text-[14px]",
|
||||
className,
|
||||
)}
|
||||
data-testid="composer-editor"
|
||||
@@ -1646,29 +1637,24 @@ function ComposerPromptEditorInner({
|
||||
<ComposerInlineTokenBackspacePlugin />
|
||||
<HistoryPlugin />
|
||||
</div>
|
||||
</ComposerTerminalContextActionsContext.Provider>
|
||||
</ComposerTerminalContextActionsContext>
|
||||
);
|
||||
}
|
||||
|
||||
export const ComposerPromptEditor = forwardRef<
|
||||
ComposerPromptEditorHandle,
|
||||
ComposerPromptEditorProps
|
||||
>(function ComposerPromptEditor(
|
||||
{
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
skills,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onRemoveTerminalContext,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
export function ComposerPromptEditor({
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
skills,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onRemoveTerminalContext,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
editorRef,
|
||||
}: ComposerPromptEditorProps) {
|
||||
const initialValueRef = useRef(value);
|
||||
const initialTerminalContextsRef = useRef(terminalContexts);
|
||||
const initialSkillMetadataRef = useRef(skillMetadataByName(skills));
|
||||
@@ -1703,10 +1689,10 @@ export const ComposerPromptEditor = forwardRef<
|
||||
onRemoveTerminalContext={onRemoveTerminalContext}
|
||||
onChange={onChange}
|
||||
onPaste={onPaste}
|
||||
editorRef={ref}
|
||||
editorRef={editorRef}
|
||||
{...(onCommandKeyDown ? { onCommandKeyDown } : {})}
|
||||
{...(className ? { className } : {})}
|
||||
/>
|
||||
</LexicalComposer>
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ReactNode, useEffect, useEffectEvent, useRef } from "react";
|
||||
import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
|
||||
|
||||
import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
|
||||
import {
|
||||
@@ -147,12 +147,7 @@ export function shouldRestartStalledReconnect(
|
||||
|
||||
export function WebSocketConnectionCoordinator() {
|
||||
const status = useWsConnectionStatus();
|
||||
useWebSocketConnectionCoordinatorEffects(status);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function useWebSocketConnectionCoordinatorEffects(status: WsConnectionStatus) {
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
const lastForcedReconnectAtRef = useRef(0);
|
||||
const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
|
||||
const toastResetTimerRef = useRef<number | null>(null);
|
||||
@@ -206,7 +201,73 @@ function useWebSocketConnectionCoordinatorEffects(status: WsConnectionStatus) {
|
||||
runReconnect(false);
|
||||
});
|
||||
|
||||
const syncConnectionToast = useEffectEvent((nowMs: number) => {
|
||||
useEffect(() => {
|
||||
const handleOnline = () => {
|
||||
triggerAutoReconnect("online");
|
||||
};
|
||||
const handleFocus = () => {
|
||||
triggerAutoReconnect("focus");
|
||||
};
|
||||
|
||||
syncBrowserOnlineStatus();
|
||||
window.addEventListener("online", handleOnline);
|
||||
window.addEventListener("offline", syncBrowserOnlineStatus);
|
||||
window.addEventListener("focus", handleFocus);
|
||||
return () => {
|
||||
window.removeEventListener("online", handleOnline);
|
||||
window.removeEventListener("offline", syncBrowserOnlineStatus);
|
||||
window.removeEventListener("focus", handleFocus);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
setNowMs(Date.now());
|
||||
const intervalId = window.setInterval(() => {
|
||||
setNowMs(Date.now());
|
||||
}, 1_000);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(intervalId);
|
||||
};
|
||||
}, [status.nextRetryAt, status.reconnectPhase]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
status.reconnectPhase !== "waiting" ||
|
||||
status.nextRetryAt === null ||
|
||||
!status.online ||
|
||||
!status.hasConnected
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextRetryAt = status.nextRetryAt;
|
||||
const timeoutMs = Math.max(0, new Date(nextRetryAt).getTime() - Date.now()) + 1_500;
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
const currentStatus = getWsConnectionStatus();
|
||||
if (!shouldRestartStalledReconnect(currentStatus, nextRetryAt)) {
|
||||
return;
|
||||
}
|
||||
|
||||
runReconnect(false);
|
||||
}, timeoutMs);
|
||||
|
||||
return () => {
|
||||
window.clearTimeout(timeoutId);
|
||||
};
|
||||
}, [
|
||||
status.hasConnected,
|
||||
status.nextRetryAt,
|
||||
status.online,
|
||||
status.reconnectAttemptCount,
|
||||
status.reconnectPhase,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
const uiState = getWsConnectionUiState(status);
|
||||
const previousUiState = previousUiStateRef.current;
|
||||
const previousDisconnectedAt = previousDisconnectedAtRef.current;
|
||||
@@ -304,76 +365,7 @@ function useWebSocketConnectionCoordinatorEffects(status: WsConnectionStatus) {
|
||||
|
||||
previousUiStateRef.current = uiState;
|
||||
previousDisconnectedAtRef.current = status.disconnectedAt;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const handleOnline = () => {
|
||||
triggerAutoReconnect("online");
|
||||
};
|
||||
const handleFocus = () => {
|
||||
triggerAutoReconnect("focus");
|
||||
};
|
||||
|
||||
syncBrowserOnlineStatus();
|
||||
window.addEventListener("online", handleOnline);
|
||||
window.addEventListener("offline", syncBrowserOnlineStatus);
|
||||
window.addEventListener("focus", handleFocus);
|
||||
return () => {
|
||||
window.removeEventListener("online", handleOnline);
|
||||
window.removeEventListener("offline", syncBrowserOnlineStatus);
|
||||
window.removeEventListener("focus", handleFocus);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const intervalId = window.setInterval(() => {
|
||||
syncConnectionToast(Date.now());
|
||||
}, 1_000);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(intervalId);
|
||||
};
|
||||
}, [status.nextRetryAt, status.reconnectPhase]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
status.reconnectPhase !== "waiting" ||
|
||||
status.nextRetryAt === null ||
|
||||
!status.online ||
|
||||
!status.hasConnected
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextRetryAt = status.nextRetryAt;
|
||||
const timeoutMs = Math.max(0, new Date(nextRetryAt).getTime() - Date.now()) + 1_500;
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
const currentStatus = getWsConnectionStatus();
|
||||
if (!shouldRestartStalledReconnect(currentStatus, nextRetryAt)) {
|
||||
return;
|
||||
}
|
||||
|
||||
runReconnect(false);
|
||||
}, timeoutMs);
|
||||
|
||||
return () => {
|
||||
window.clearTimeout(timeoutId);
|
||||
};
|
||||
}, [
|
||||
status.hasConnected,
|
||||
status.nextRetryAt,
|
||||
status.online,
|
||||
status.reconnectAttemptCount,
|
||||
status.reconnectPhase,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
syncConnectionToast(Date.now());
|
||||
}, [status]);
|
||||
}, [nowMs, status]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -382,6 +374,8 @@ function useWebSocketConnectionCoordinatorEffects(status: WsConnectionStatus) {
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function SlowRpcAckToastCoordinator() {
|
||||
|
||||
@@ -13,18 +13,16 @@ const getStateSpy = vi.fn(() => ({ isAtEnd: true }));
|
||||
vi.mock("@legendapp/list/react", async () => {
|
||||
const React = await import("react");
|
||||
|
||||
const LegendList = React.forwardRef(function MockLegendList(
|
||||
props: {
|
||||
data: Array<{ id: string }>;
|
||||
keyExtractor: (item: { id: string }) => string;
|
||||
renderItem: (args: { item: { id: string } }) => React.ReactNode;
|
||||
ListHeaderComponent?: React.ReactNode;
|
||||
ListFooterComponent?: React.ReactNode;
|
||||
},
|
||||
ref: React.ForwardedRef<LegendListRef>,
|
||||
) {
|
||||
function LegendList(props: {
|
||||
data: Array<{ id: string }>;
|
||||
keyExtractor: (item: { id: string }) => string;
|
||||
renderItem: (args: { item: { id: string } }) => React.ReactNode;
|
||||
ListHeaderComponent?: React.ReactNode;
|
||||
ListFooterComponent?: React.ReactNode;
|
||||
ref?: React.Ref<LegendListRef>;
|
||||
}) {
|
||||
React.useImperativeHandle(
|
||||
ref,
|
||||
props.ref,
|
||||
() =>
|
||||
({
|
||||
scrollToEnd: scrollToEndSpy,
|
||||
@@ -41,7 +39,7 @@ vi.mock("@legendapp/list/react", async () => {
|
||||
{props.ListFooterComponent}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return { LegendList };
|
||||
});
|
||||
|
||||
@@ -268,6 +268,59 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
expect(assistantRows[1]?.showCompletionDivider).toBe(true);
|
||||
});
|
||||
|
||||
it("marks only the active assistant turn as streaming for copy controls", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "assistant-one-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
message: {
|
||||
id: "assistant-one" as never,
|
||||
role: "assistant",
|
||||
text: "Earlier response.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
completedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-two-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
message: {
|
||||
id: "assistant-two" as never,
|
||||
role: "assistant",
|
||||
text: "Active response.",
|
||||
turnId: "turn-2" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: "assistant-two-entry",
|
||||
completionSummary: "done",
|
||||
isWorking: false,
|
||||
activeTurnInProgress: true,
|
||||
activeTurnId: "turn-2" as never,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const assistantRows = rows.filter(
|
||||
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
|
||||
row.kind === "message" && row.message.role === "assistant",
|
||||
);
|
||||
|
||||
expect(assistantRows[0]?.assistantCopyStreaming).toBe(false);
|
||||
expect(assistantRows[0]?.completionSummary).toBeNull();
|
||||
expect(assistantRows[1]?.assistantCopyStreaming).toBe(true);
|
||||
expect(assistantRows[1]?.completionSummary).toBe("done");
|
||||
});
|
||||
|
||||
it("projects assistant diff summaries and user revert counts onto the affected rows", () => {
|
||||
const assistantTurnDiffSummary = {
|
||||
turnId: "turn-1" as never,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as Equal from "effect/Equal";
|
||||
import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
|
||||
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
|
||||
import { type MessageId } from "@t3tools/contracts";
|
||||
import { type MessageId, type TurnId } from "@t3tools/contracts";
|
||||
|
||||
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
|
||||
@@ -26,7 +26,9 @@ export type MessagesTimelineRow =
|
||||
message: ChatMessage;
|
||||
durationStart: string;
|
||||
showCompletionDivider: boolean;
|
||||
completionSummary: string | null;
|
||||
showAssistantCopyButton: boolean;
|
||||
assistantCopyStreaming: boolean;
|
||||
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
|
||||
revertTurnCount?: number | undefined;
|
||||
}
|
||||
@@ -111,7 +113,10 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
|
||||
export function deriveMessagesTimelineRows(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
completionDividerBeforeEntryId: string | null;
|
||||
completionSummary?: string | null;
|
||||
isWorking: boolean;
|
||||
activeTurnInProgress?: boolean;
|
||||
activeTurnId?: TurnId | null;
|
||||
activeTurnStartedAt: string | null;
|
||||
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
|
||||
revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
|
||||
@@ -157,6 +162,16 @@ export function deriveMessagesTimelineRows(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
const assistantTurnStillInProgress =
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
input.activeTurnInProgress === true &&
|
||||
input.activeTurnId != null &&
|
||||
timelineEntry.message.turnId === input.activeTurnId;
|
||||
|
||||
const showCompletionDivider =
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
input.completionDividerBeforeEntryId === timelineEntry.id;
|
||||
|
||||
nextRows.push({
|
||||
kind: "message",
|
||||
id: timelineEntry.id,
|
||||
@@ -164,12 +179,12 @@ export function deriveMessagesTimelineRows(input: {
|
||||
message: timelineEntry.message,
|
||||
durationStart:
|
||||
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
|
||||
showCompletionDivider:
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
input.completionDividerBeforeEntryId === timelineEntry.id,
|
||||
showCompletionDivider,
|
||||
completionSummary: showCompletionDivider ? (input.completionSummary ?? null) : null,
|
||||
showAssistantCopyButton:
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
terminalAssistantMessageIds.has(timelineEntry.message.id),
|
||||
assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress,
|
||||
assistantTurnDiffSummary:
|
||||
timelineEntry.message.role === "assistant"
|
||||
? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
|
||||
@@ -232,7 +247,9 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
a.message === bm.message &&
|
||||
a.durationStart === bm.durationStart &&
|
||||
a.showCompletionDivider === bm.showCompletionDivider &&
|
||||
a.completionSummary === bm.completionSummary &&
|
||||
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
|
||||
a.assistantCopyStreaming === bm.assistantCopyStreaming &&
|
||||
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
|
||||
a.revertTurnCount === bm.revertTurnCount
|
||||
);
|
||||
|
||||
@@ -1,32 +1,28 @@
|
||||
import { EnvironmentId, MessageId } from "@t3tools/contracts";
|
||||
import { createRef } from "react";
|
||||
import { createRef, type ReactNode, type Ref } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import type { LegendListRef } from "@legendapp/list/react";
|
||||
|
||||
vi.mock("@legendapp/list/react", async () => {
|
||||
const React = await import("react");
|
||||
const legendListTestId = "legend-list";
|
||||
|
||||
const LegendList = React.forwardRef(function MockLegendList(
|
||||
props: {
|
||||
data: Array<{ id: string }>;
|
||||
keyExtractor: (item: { id: string }) => string;
|
||||
renderItem: (args: { item: { id: string } }) => React.ReactNode;
|
||||
ListHeaderComponent?: React.ReactNode;
|
||||
ListFooterComponent?: React.ReactNode;
|
||||
},
|
||||
_ref: React.ForwardedRef<LegendListRef>,
|
||||
) {
|
||||
return (
|
||||
<div data-testid="legend-list">
|
||||
{props.ListHeaderComponent}
|
||||
{props.data.map((item) => (
|
||||
<div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
|
||||
))}
|
||||
{props.ListFooterComponent}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
const LegendList = (props: {
|
||||
data: Array<{ id: string }>;
|
||||
keyExtractor: (item: { id: string }) => string;
|
||||
renderItem: (args: { item: { id: string } }) => ReactNode;
|
||||
ListHeaderComponent?: ReactNode;
|
||||
ListFooterComponent?: ReactNode;
|
||||
ref?: Ref<LegendListRef>;
|
||||
}) => (
|
||||
<div data-testid={legendListTestId}>
|
||||
{props.ListHeaderComponent}
|
||||
{props.data.map((item) => (
|
||||
<div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
|
||||
))}
|
||||
{props.ListFooterComponent}
|
||||
</div>
|
||||
);
|
||||
|
||||
return { LegendList };
|
||||
});
|
||||
|
||||
@@ -69,7 +69,7 @@ import { SkillInlineText } from "./SkillInlineText";
|
||||
import { formatWorkspaceRelativePath } from "../../filePathDisplay";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Context — shared state consumed by every row component via useContext.
|
||||
// Context — shared state consumed by every row component via Context.
|
||||
// Propagates through LegendList's memo boundaries for shared callbacks and
|
||||
// non-row-scoped state. `nowIso` is intentionally excluded — self-ticking
|
||||
// components (WorkingTimer, LiveElapsed) handle it.
|
||||
@@ -89,11 +89,8 @@ interface TimelineRowSharedState {
|
||||
}
|
||||
|
||||
interface TimelineRowActivityState {
|
||||
activeTurnInProgress: boolean;
|
||||
activeTurnId: TurnId | null;
|
||||
isWorking: boolean;
|
||||
isRevertingCheckpoint: boolean;
|
||||
completionSummary: string | null;
|
||||
}
|
||||
|
||||
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
|
||||
@@ -164,7 +161,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
completionDividerBeforeEntryId,
|
||||
completionSummary,
|
||||
isWorking,
|
||||
activeTurnInProgress,
|
||||
activeTurnId: activeTurnId ?? null,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
revertTurnCountByUserMessageId,
|
||||
@@ -172,7 +172,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
[
|
||||
timelineEntries,
|
||||
completionDividerBeforeEntryId,
|
||||
completionSummary,
|
||||
isWorking,
|
||||
activeTurnInProgress,
|
||||
activeTurnId,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
revertTurnCountByUserMessageId,
|
||||
@@ -233,13 +236,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
);
|
||||
const activityState = useMemo<TimelineRowActivityState>(
|
||||
() => ({
|
||||
activeTurnInProgress,
|
||||
activeTurnId: activeTurnId ?? null,
|
||||
isWorking,
|
||||
isRevertingCheckpoint,
|
||||
completionSummary,
|
||||
}),
|
||||
[activeTurnInProgress, activeTurnId, completionSummary, isRevertingCheckpoint, isWorking],
|
||||
[isRevertingCheckpoint, isWorking],
|
||||
);
|
||||
|
||||
// Stable renderItem — no closure deps. Row components read shared state
|
||||
@@ -264,8 +264,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}
|
||||
|
||||
return (
|
||||
<TimelineRowCtx.Provider value={sharedState}>
|
||||
<TimelineRowActivityCtx.Provider value={activityState}>
|
||||
<TimelineRowCtx value={sharedState}>
|
||||
<TimelineRowActivityCtx value={activityState}>
|
||||
<LegendList<MessagesTimelineRow>
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
@@ -281,8 +281,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
ListHeaderComponent={TIMELINE_LIST_HEADER}
|
||||
ListFooterComponent={TIMELINE_LIST_FOOTER}
|
||||
/>
|
||||
</TimelineRowActivityCtx.Provider>
|
||||
</TimelineRowCtx.Provider>
|
||||
</TimelineRowActivityCtx>
|
||||
</TimelineRowCtx>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -412,7 +412,9 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
|
||||
|
||||
return (
|
||||
<>
|
||||
{row.showCompletionDivider && <AssistantCompletionDivider />}
|
||||
{row.showCompletionDivider && (
|
||||
<AssistantCompletionDivider completionSummary={row.completionSummary} />
|
||||
)}
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ChatMarkdown
|
||||
text={messageText}
|
||||
@@ -449,14 +451,12 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantCompletionDivider() {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
|
||||
function AssistantCompletionDivider({ completionSummary }: { completionSummary: string | null }) {
|
||||
return (
|
||||
<div className="my-3 flex items-center gap-3">
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
|
||||
{activity.completionSummary ? `Response • ${activity.completionSummary}` : "Response"}
|
||||
{completionSummary ? `Response • ${completionSummary}` : "Response"}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
@@ -464,15 +464,10 @@ function AssistantCompletionDivider() {
|
||||
}
|
||||
|
||||
function AssistantCopyButton({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const assistantTurnStillInProgress =
|
||||
activity.activeTurnInProgress &&
|
||||
activity.activeTurnId !== null &&
|
||||
row.message.turnId === activity.activeTurnId;
|
||||
const assistantCopyState = resolveAssistantMessageCopyState({
|
||||
text: row.message.text ?? null,
|
||||
showCopyButton: row.showAssistantCopyButton,
|
||||
streaming: row.message.streaming || assistantTurnStillInProgress,
|
||||
streaming: row.assistantCopyStreaming,
|
||||
});
|
||||
|
||||
if (!assistantCopyState.visible) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
type ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ProviderOptionDescriptor,
|
||||
type ProviderOptionSelection,
|
||||
type ScopedThreadRef,
|
||||
@@ -196,6 +197,7 @@ export function shouldRenderTraitsControls(input: {
|
||||
|
||||
export interface TraitsMenuContentProps {
|
||||
provider: ProviderDriverKind;
|
||||
instanceId?: ProviderInstanceId;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
model: string | null | undefined;
|
||||
prompt: string;
|
||||
@@ -208,6 +210,7 @@ export interface TraitsMenuContentProps {
|
||||
|
||||
export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
provider,
|
||||
instanceId,
|
||||
models,
|
||||
model,
|
||||
prompt,
|
||||
@@ -228,11 +231,12 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
return;
|
||||
}
|
||||
setProviderModelOptions(threadTarget, provider, nextOptions, {
|
||||
...(instanceId ? { instanceId } : {}),
|
||||
model,
|
||||
persistSticky: true,
|
||||
});
|
||||
},
|
||||
[model, persistence, provider, setProviderModelOptions],
|
||||
[instanceId, model, persistence, provider, setProviderModelOptions],
|
||||
);
|
||||
const {
|
||||
descriptors,
|
||||
@@ -343,6 +347,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
|
||||
export const TraitsPicker = memo(function TraitsPicker({
|
||||
provider,
|
||||
instanceId,
|
||||
models,
|
||||
model,
|
||||
prompt,
|
||||
@@ -431,6 +436,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
<MenuPopup align="start">
|
||||
<TraitsMenuContent
|
||||
provider={provider}
|
||||
{...(instanceId ? { instanceId } : {})}
|
||||
models={models}
|
||||
model={model}
|
||||
prompt={prompt}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
type ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ProviderOptionSelection,
|
||||
type ScopedThreadRef,
|
||||
type ServerProviderModel,
|
||||
@@ -35,6 +36,7 @@ export type ComposerProviderState = {
|
||||
|
||||
type TraitsRenderInput = {
|
||||
provider: ProviderDriverKind;
|
||||
instanceId?: ProviderInstanceId;
|
||||
threadRef?: ScopedThreadRef;
|
||||
draftId?: DraftId;
|
||||
model: string;
|
||||
@@ -76,8 +78,17 @@ function renderTraitsControl(
|
||||
Component: typeof TraitsMenuContent | typeof TraitsPicker,
|
||||
input: TraitsRenderInput,
|
||||
): ReactNode {
|
||||
const { provider, threadRef, draftId, model, models, modelOptions, prompt, onPromptChange } =
|
||||
input;
|
||||
const {
|
||||
provider,
|
||||
instanceId,
|
||||
threadRef,
|
||||
draftId,
|
||||
model,
|
||||
models,
|
||||
modelOptions,
|
||||
prompt,
|
||||
onPromptChange,
|
||||
} = input;
|
||||
const hasTarget = threadRef !== undefined || draftId !== undefined;
|
||||
if (
|
||||
!hasTarget ||
|
||||
@@ -88,6 +99,7 @@ function renderTraitsControl(
|
||||
return (
|
||||
<Component
|
||||
provider={provider}
|
||||
{...(instanceId ? { instanceId } : {})}
|
||||
models={models}
|
||||
{...(threadRef ? { threadRef } : {})}
|
||||
{...(draftId ? { draftId } : {})}
|
||||
|
||||
@@ -8,7 +8,11 @@ import {
|
||||
RefreshCwIcon,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useMemo, useState, type ReactNode } from "react";
|
||||
import type { ServerProcessDiagnosticsEntry, ServerProcessSignal } from "@t3tools/contracts";
|
||||
import type {
|
||||
ServerProcessDiagnosticsEntry,
|
||||
ServerProcessResourceHistorySummary,
|
||||
ServerProcessSignal,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
@@ -17,7 +21,10 @@ import { cn } from "../../lib/utils";
|
||||
import { resolveAndPersistPreferredEditor } from "../../editorPreferences";
|
||||
import { formatRelativeTime } from "../../timestampFormat";
|
||||
import { useServerAvailableEditors, useServerObservability } from "../../rpc/serverState";
|
||||
import { useProcessDiagnostics } from "../../lib/processDiagnosticsState";
|
||||
import {
|
||||
useProcessDiagnostics,
|
||||
useProcessResourceHistory,
|
||||
} from "../../lib/processDiagnosticsState";
|
||||
import { useTraceDiagnostics } from "../../lib/traceDiagnosticsState";
|
||||
import { Button } from "../ui/button";
|
||||
import { ScrollArea } from "../ui/scroll-area";
|
||||
@@ -309,7 +316,7 @@ function ProcessNameCell({
|
||||
return (
|
||||
<div
|
||||
className="grid min-w-0 grid-cols-[1.25rem_0.375rem_minmax(0,1fr)] items-center gap-2"
|
||||
style={{ paddingLeft: `${Math.min(process.depth, 8) * 16}px` }}
|
||||
style={{ paddingLeft: `${Math.min(process.depth, 6) * 10}px` }}
|
||||
>
|
||||
{hasChildren ? (
|
||||
<button
|
||||
@@ -324,7 +331,17 @@ function ProcessNameCell({
|
||||
<span className="size-5 shrink-0" aria-hidden="true" />
|
||||
)}
|
||||
<span className="size-1.5 shrink-0 rounded-full bg-emerald-500/80" />
|
||||
<span className="min-w-0 truncate font-medium text-foreground">{name}</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={<span className="min-w-0 truncate font-medium text-foreground">{name}</span>}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-[min(440px,calc(100vw-2rem))] whitespace-normal break-words text-left font-mono text-[11px] leading-relaxed text-wrap"
|
||||
>
|
||||
{process.command}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -422,7 +439,7 @@ function ProcessDiagnosticsTable({
|
||||
chainVerticalScroll
|
||||
scrollFade
|
||||
hideScrollbars
|
||||
className="w-full max-w-full rounded-none border-t border-border/60"
|
||||
className="max-h-[min(64vh,44rem)] w-full max-w-full rounded-none border-t border-border/60"
|
||||
>
|
||||
<table className="w-full min-w-[1040px] table-fixed text-left text-xs">
|
||||
<colgroup>
|
||||
@@ -434,7 +451,7 @@ function ProcessDiagnosticsTable({
|
||||
<col className="w-[11%]" />
|
||||
<col className="w-[6%]" />
|
||||
</colgroup>
|
||||
<thead className="border-b border-border/60 bg-muted/15 text-[11px] uppercase tracking-[0.08em] text-muted-foreground/70">
|
||||
<thead className="sticky top-0 z-10 border-b border-border/60 bg-card text-[11px] uppercase tracking-[0.08em] text-muted-foreground/70">
|
||||
<tr>
|
||||
<th className="px-4 py-2 font-semibold sm:pl-5">Name</th>
|
||||
<th className="px-3 py-2 text-right font-semibold">CPU</th>
|
||||
@@ -442,7 +459,7 @@ function ProcessDiagnosticsTable({
|
||||
<th className="px-3 py-2 font-semibold">Command</th>
|
||||
<th className="px-3 py-2 text-right font-semibold">PID</th>
|
||||
<th className="px-3 py-2 font-semibold">Type</th>
|
||||
<th className="px-2 py-2 text-right font-semibold sm:pr-4">Kill</th>
|
||||
<th className="p-2 text-right font-semibold sm:pr-4">Kill</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/50">
|
||||
@@ -487,7 +504,7 @@ function ProcessDiagnosticsTable({
|
||||
<td className="truncate px-3 py-2 align-middle text-muted-foreground">
|
||||
{formatProcessType(process)}
|
||||
</td>
|
||||
<td className="px-2 py-2 align-middle sm:pr-4">
|
||||
<td className="p-2 align-middle sm:pr-4">
|
||||
<ProcessSignalActions
|
||||
process={process}
|
||||
isSignaling={signalingPid === process.pid}
|
||||
@@ -502,6 +519,238 @@ function ProcessDiagnosticsTable({
|
||||
);
|
||||
}
|
||||
|
||||
const RESOURCE_HISTORY_WINDOWS = [
|
||||
{ label: "5m", windowMs: 5 * 60_000, bucketMs: 30_000 },
|
||||
{ label: "15m", windowMs: 15 * 60_000, bucketMs: 60_000 },
|
||||
{ label: "30m", windowMs: 30 * 60_000, bucketMs: 2 * 60_000 },
|
||||
{ label: "1h", windowMs: 60 * 60_000, bucketMs: 5 * 60_000 },
|
||||
] as const;
|
||||
|
||||
function formatCpuTime(seconds: number): string {
|
||||
if (seconds < 60) return `${seconds.toFixed(seconds >= 10 ? 1 : 2)}s`;
|
||||
const minutes = seconds / 60;
|
||||
if (minutes < 60) return `${minutes.toFixed(minutes >= 10 ? 1 : 2)}m`;
|
||||
return `${(minutes / 60).toFixed(2)}h`;
|
||||
}
|
||||
|
||||
function formatShortProcessName(command: string): string {
|
||||
const name = formatProcessName(command);
|
||||
return name.length > 42 ? `${name.slice(0, 39)}...` : name;
|
||||
}
|
||||
|
||||
function ResourceHistoryProcessNameCell({
|
||||
process,
|
||||
visualDepth,
|
||||
}: {
|
||||
process: ServerProcessResourceHistorySummary;
|
||||
visualDepth: number;
|
||||
}) {
|
||||
const name = formatShortProcessName(process.command);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="grid min-w-0 grid-cols-[1.25rem_0.375rem_minmax(0,1fr)] items-center gap-2"
|
||||
style={{ paddingLeft: `${Math.min(visualDepth, 6) * 10}px` }}
|
||||
aria-label={`${process.isServerRoot ? "Root" : "Child"} process ${name}`}
|
||||
>
|
||||
<span className="size-5 shrink-0" aria-hidden="true" />
|
||||
<span
|
||||
className={cn(
|
||||
"size-1.5 shrink-0 rounded-full",
|
||||
process.isServerRoot ? "bg-amber-500/90" : "bg-emerald-500/80",
|
||||
)}
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={<span className="min-w-0 truncate font-medium text-foreground">{name}</span>}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-[min(440px,calc(100vw-2rem))] whitespace-normal break-words text-left font-mono text-[11px] leading-relaxed text-wrap"
|
||||
>
|
||||
{process.command}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProcessResourceHistoryChart({
|
||||
buckets,
|
||||
}: {
|
||||
buckets: ReadonlyArray<{
|
||||
readonly startedAt: DateTime.Utc;
|
||||
readonly avgCpuPercent: number;
|
||||
readonly maxCpuPercent: number;
|
||||
}>;
|
||||
}) {
|
||||
const maxCpuPercent = Math.max(1, ...buckets.map((bucket) => bucket.maxCpuPercent));
|
||||
|
||||
return (
|
||||
<div className="border-t border-border/60 px-4 py-3 sm:px-5">
|
||||
<div className="flex h-28 items-end gap-1 overflow-hidden rounded-sm bg-muted/10 p-2">
|
||||
{buckets.map((bucket) => {
|
||||
const peakHeight = Math.max(2, (bucket.maxCpuPercent / maxCpuPercent) * 100);
|
||||
const averageHeight = Math.max(2, (bucket.avgCpuPercent / maxCpuPercent) * 100);
|
||||
return (
|
||||
<Tooltip key={DateTime.formatIso(bucket.startedAt)}>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<div className="flex h-full min-w-1 flex-1 items-end">
|
||||
<div
|
||||
className="relative h-full w-full"
|
||||
aria-label={`Average CPU ${bucket.avgCpuPercent.toFixed(1)}%, peak CPU ${bucket.maxCpuPercent.toFixed(1)}%`}
|
||||
>
|
||||
<div
|
||||
className="absolute inset-x-0 bottom-0 rounded-t-sm bg-foreground/15 transition-colors"
|
||||
style={{ height: `${peakHeight}%` }}
|
||||
/>
|
||||
<div
|
||||
className="absolute inset-x-0 bottom-0 rounded-t-sm bg-foreground/60 transition-colors"
|
||||
style={{ height: `${averageHeight}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">
|
||||
Avg {bucket.avgCpuPercent.toFixed(1)}%, peak {bucket.maxCpuPercent.toFixed(1)}%
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ResourceHistoryWindowSelector({
|
||||
selectedWindowMs,
|
||||
onSelect,
|
||||
}: {
|
||||
selectedWindowMs: number;
|
||||
onSelect: (windowMs: number) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center rounded-md border border-border/60 p-0.5">
|
||||
{RESOURCE_HISTORY_WINDOWS.map((option) => (
|
||||
<button
|
||||
key={option.windowMs}
|
||||
type="button"
|
||||
className={cn(
|
||||
"h-6 rounded-sm px-2 text-[11px] font-medium text-muted-foreground hover:text-foreground",
|
||||
selectedWindowMs === option.windowMs && "bg-muted text-foreground",
|
||||
)}
|
||||
onClick={() => onSelect(option.windowMs)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProcessResourceHistoryTable({
|
||||
processes,
|
||||
emptyLabel,
|
||||
}: {
|
||||
processes: ReadonlyArray<ServerProcessResourceHistorySummary>;
|
||||
emptyLabel: string;
|
||||
}) {
|
||||
const shallowestChildDepth = processes.reduce<number | null>((minDepth, process) => {
|
||||
if (process.isServerRoot) return minDepth;
|
||||
return minDepth === null ? process.depth : Math.min(minDepth, process.depth);
|
||||
}, null);
|
||||
|
||||
return (
|
||||
<ScrollArea
|
||||
chainVerticalScroll
|
||||
scrollFade
|
||||
hideScrollbars
|
||||
className="max-h-[min(64vh,44rem)] w-full max-w-full border-t border-border/60"
|
||||
>
|
||||
<table className="w-full min-w-[980px] table-fixed text-left text-xs">
|
||||
<colgroup>
|
||||
<col className="w-[24%]" />
|
||||
<col className="w-[10%]" />
|
||||
<col className="w-[10%]" />
|
||||
<col className="w-[10%]" />
|
||||
<col className="w-[10%]" />
|
||||
<col className="w-[10%]" />
|
||||
<col className="w-[16%]" />
|
||||
<col className="w-[10%]" />
|
||||
</colgroup>
|
||||
<thead className="sticky top-0 z-10 border-b border-border/60 bg-card text-[11px] uppercase tracking-[0.08em] text-muted-foreground/70">
|
||||
<tr>
|
||||
<th className="px-4 py-2 font-semibold sm:pl-5">Process</th>
|
||||
<th className="px-3 py-2 text-right font-semibold">CPU Time</th>
|
||||
<th className="px-3 py-2 text-right font-semibold">Current</th>
|
||||
<th className="px-3 py-2 text-right font-semibold">Average</th>
|
||||
<th className="px-3 py-2 text-right font-semibold">Peak</th>
|
||||
<th className="px-3 py-2 text-right font-semibold">Max Mem</th>
|
||||
<th className="px-3 py-2 font-semibold">Command</th>
|
||||
<th className="px-3 py-2 text-right font-semibold sm:pr-5">PID</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/50">
|
||||
{processes.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-4 py-4 text-xs text-muted-foreground sm:px-5">
|
||||
{emptyLabel}
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
{processes.map((process) => (
|
||||
<tr key={process.processKey} className="hover:bg-muted/20">
|
||||
<td className="px-4 py-2 align-middle sm:pl-5">
|
||||
<ResourceHistoryProcessNameCell
|
||||
process={process}
|
||||
visualDepth={
|
||||
process.isServerRoot || shallowestChildDepth === null
|
||||
? 0
|
||||
: Math.max(1, process.depth - shallowestChildDepth + 1)
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
|
||||
{formatCpuTime(process.cpuSecondsApprox)}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
|
||||
{process.currentCpuPercent.toFixed(1)}%
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
|
||||
{process.avgCpuPercent.toFixed(1)}%
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
|
||||
{process.maxCpuPercent.toFixed(1)}%
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
|
||||
{formatBytes(process.maxRssBytes)}
|
||||
</td>
|
||||
<td className="px-3 py-2 align-middle text-muted-foreground">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={<span className="block truncate">{process.command}</span>}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-[min(440px,calc(100vw-2rem))] whitespace-normal break-words text-left font-mono text-[11px] leading-relaxed text-wrap"
|
||||
>
|
||||
{process.command}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums text-muted-foreground sm:pr-5">
|
||||
{process.pid}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
|
||||
function DiagnosticsLastChecked({ checkedAt }: { checkedAt: DateTime.Utc | null }) {
|
||||
useRelativeTimeTick();
|
||||
const relative = checkedAt ? formatRelativeTime(DateTime.formatIso(checkedAt)) : null;
|
||||
@@ -556,6 +805,10 @@ function DiagnosticsRefreshButton({
|
||||
export function DiagnosticsSettingsPanel() {
|
||||
const observability = useServerObservability();
|
||||
const availableEditors = useServerAvailableEditors();
|
||||
const [resourceWindowMs, setResourceWindowMs] = useState(15 * 60_000);
|
||||
const selectedResourceWindow =
|
||||
RESOURCE_HISTORY_WINDOWS.find((option) => option.windowMs === resourceWindowMs) ??
|
||||
RESOURCE_HISTORY_WINDOWS[1];
|
||||
const { data, error, isPending, refresh } = useTraceDiagnostics();
|
||||
const {
|
||||
data: processData,
|
||||
@@ -563,6 +816,15 @@ export function DiagnosticsSettingsPanel() {
|
||||
isPending: isProcessPending,
|
||||
refresh: refreshProcesses,
|
||||
} = useProcessDiagnostics();
|
||||
const {
|
||||
data: resourceData,
|
||||
error: resourceError,
|
||||
isPending: isResourcePending,
|
||||
refresh: refreshResources,
|
||||
} = useProcessResourceHistory({
|
||||
windowMs: selectedResourceWindow.windowMs,
|
||||
bucketMs: selectedResourceWindow.bucketMs,
|
||||
});
|
||||
const [isOpeningLogsDirectory, setIsOpeningLogsDirectory] = useState(false);
|
||||
const [openLogsDirectoryError, setOpenLogsDirectoryError] = useState<string | null>(null);
|
||||
const [signalingPid, setSignalingPid] = useState<number | null>(null);
|
||||
@@ -643,6 +905,7 @@ export function DiagnosticsSettingsPanel() {
|
||||
);
|
||||
|
||||
const processDiagnosticsError = processData ? Option.getOrNull(processData.error) : null;
|
||||
const processResourceError = resourceData ? Option.getOrNull(resourceData.error) : null;
|
||||
const traceDiagnosticsError = data ? Option.getOrNull(data.error) : null;
|
||||
const traceDiagnosticsPartialFailure = data
|
||||
? Option.getOrElse(data.partialFailure, () => false)
|
||||
@@ -711,6 +974,70 @@ export function DiagnosticsSettingsPanel() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title="Resource History"
|
||||
headerAction={
|
||||
<div className="flex items-center gap-1.5">
|
||||
<ResourceHistoryWindowSelector
|
||||
selectedWindowMs={resourceWindowMs}
|
||||
onSelect={setResourceWindowMs}
|
||||
/>
|
||||
<DiagnosticsLastChecked checkedAt={resourceData?.readAt ?? null} />
|
||||
<DiagnosticsRefreshButton
|
||||
isPending={isResourcePending}
|
||||
label="Refresh resource history"
|
||||
onClick={refreshResources}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<StatsGrid>
|
||||
<StatBlock
|
||||
label="CPU Time"
|
||||
value={resourceData ? formatCpuTime(resourceData.totalCpuSecondsApprox) : "..."}
|
||||
tooltip="Approximate active CPU time for the T3 server root process and its descendants during the selected window. It grows only while sampled processes use CPU and older samples leave as the window moves."
|
||||
/>
|
||||
<StatBlock
|
||||
label="Samples"
|
||||
value={resourceData ? formatCount(resourceData.retainedSampleCount) : "..."}
|
||||
tooltip="In-memory process samples retained by the server. This resets when the server restarts."
|
||||
/>
|
||||
<StatBlock
|
||||
label="Interval"
|
||||
value={resourceData ? formatDuration(resourceData.sampleIntervalMs) : "..."}
|
||||
/>
|
||||
<StatBlock
|
||||
label="Processes"
|
||||
value={resourceData ? formatCount(resourceData.topProcesses.length) : "..."}
|
||||
/>
|
||||
</StatsGrid>
|
||||
{processResourceError || resourceError ? (
|
||||
<div className="space-y-2 border-t border-border/60 px-4 py-3 text-xs text-muted-foreground sm:px-5">
|
||||
{processResourceError ? (
|
||||
<div className="flex items-start gap-2 text-destructive">
|
||||
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
|
||||
<span>{processResourceError.message}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{resourceError ? (
|
||||
<div className="flex items-start gap-2 text-destructive">
|
||||
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
|
||||
<span>{resourceError}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<ProcessResourceHistoryChart buckets={resourceData?.buckets ?? []} />
|
||||
<ProcessResourceHistoryTable
|
||||
processes={resourceData?.topProcesses ?? []}
|
||||
emptyLabel={
|
||||
isResourcePending && resourceData === null
|
||||
? "Collecting process resource samples..."
|
||||
: "No process resource samples found for this window."
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title="Trace Diagnostics"
|
||||
headerAction={
|
||||
|
||||
@@ -29,6 +29,7 @@ import { Button } from "../ui/button";
|
||||
import { Collapsible, CollapsibleContent } from "../ui/collapsible";
|
||||
import { DraftInput } from "../ui/draft-input";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
|
||||
import { ScrollArea } from "../ui/scroll-area";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
@@ -697,8 +698,12 @@ export function ProviderInstanceCard({
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<PopoverPopup side="bottom" align="start" className="w-84">
|
||||
<div className="grid gap-3">
|
||||
<PopoverPopup
|
||||
side="bottom"
|
||||
align="start"
|
||||
className="w-[min(21rem,calc(100vw-1.5rem))] [--popup-width:min(21rem,calc(100vw-1.5rem))]"
|
||||
>
|
||||
<div className="grid min-w-0 gap-3">
|
||||
<div className="grid gap-0.5">
|
||||
<p className="text-[13px] font-semibold leading-tight text-foreground">
|
||||
Update available
|
||||
@@ -735,10 +740,12 @@ export function ProviderInstanceCard({
|
||||
</div>
|
||||
) : null}
|
||||
{updateCommand ? (
|
||||
<div className="flex items-center gap-1 rounded-md border border-border/70 bg-muted/40 py-0.5 pr-0.5 pl-2">
|
||||
<code className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap font-mono text-[11px] text-foreground [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
{updateCommand}
|
||||
</code>
|
||||
<div className="flex min-w-0 items-center gap-1 rounded-md border border-border/70 bg-muted/40 py-0.5 pr-0.5 pl-2">
|
||||
<ScrollArea scrollFade className="h-8 min-w-0 flex-1 rounded-none">
|
||||
<code className="flex h-full w-max items-center whitespace-nowrap pr-3 font-mono text-[11px] text-foreground">
|
||||
{updateCommand}
|
||||
</code>
|
||||
</ScrollArea>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerConfig,
|
||||
type ServerProcessResourceHistoryResult,
|
||||
type ServerProvider,
|
||||
type SourceControlDiscoveryResult,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -236,7 +237,10 @@ function createBaseServerConfig(): ServerConfig {
|
||||
};
|
||||
}
|
||||
|
||||
function createOutdatedProvider(driver: string): ServerProvider {
|
||||
function createOutdatedProvider(
|
||||
driver: string,
|
||||
updateCommand = "npm install -g openai/codex@latest",
|
||||
): ServerProvider {
|
||||
return {
|
||||
instanceId: ProviderInstanceId.make(driver),
|
||||
driver: ProviderDriverKind.make(driver),
|
||||
@@ -255,7 +259,7 @@ function createOutdatedProvider(driver: string): ServerProvider {
|
||||
latestVersion: "1.1.0",
|
||||
message: "Update available.",
|
||||
checkedAt: "2026-05-04T10:00:00.000Z",
|
||||
updateCommand: "npm install -g openai/codex@latest",
|
||||
updateCommand,
|
||||
canUpdate: true,
|
||||
},
|
||||
};
|
||||
@@ -265,6 +269,20 @@ function makeUtc(value: string) {
|
||||
return DateTime.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function createEmptyProcessResourceHistoryResult(): ServerProcessResourceHistoryResult {
|
||||
return {
|
||||
readAt: makeUtc("2036-04-07T00:00:00.000Z"),
|
||||
windowMs: 15 * 60_000,
|
||||
bucketMs: 60_000,
|
||||
sampleIntervalMs: 5_000,
|
||||
retainedSampleCount: 0,
|
||||
totalCpuSecondsApprox: 0,
|
||||
buckets: [],
|
||||
topProcesses: [],
|
||||
error: Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
function makePairingLink(input: {
|
||||
readonly id: string;
|
||||
readonly credential: string;
|
||||
@@ -1062,6 +1080,9 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
processes: [],
|
||||
error: Option.none(),
|
||||
}),
|
||||
getProcessResourceHistory: vi
|
||||
.fn()
|
||||
.mockResolvedValue(createEmptyProcessResourceHistoryResult()),
|
||||
getTraceDiagnostics: vi.fn().mockResolvedValue({
|
||||
traceFilePath: "/repo/project/.t3/traces.jsonl",
|
||||
scannedFilePaths: ["/repo/project/.t3/traces.jsonl"],
|
||||
@@ -1155,6 +1176,47 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps long provider update commands inside the fixed-width popover", async () => {
|
||||
const longUpdateCommand =
|
||||
"npm install -g @anthropic-ai/claude-code@latest --registry=https://registry.npmjs.org --cache=/tmp/t3code-provider-update-cache";
|
||||
|
||||
setServerConfigSnapshot({
|
||||
...createBaseServerConfig(),
|
||||
providers: [createOutdatedProvider("codex", longUpdateCommand)],
|
||||
});
|
||||
|
||||
mounted = await render(
|
||||
<AppAtomRegistryProvider>
|
||||
<ProviderSettingsPanel />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
await page.getByRole("button", { name: "Update available — view details" }).click();
|
||||
await expect.element(page.getByText(longUpdateCommand)).toBeInTheDocument();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const popup = document.querySelector<HTMLElement>('[data-slot="popover-popup"]');
|
||||
const commandCode = Array.from(document.querySelectorAll<HTMLElement>("code")).find(
|
||||
(element) => element.textContent === longUpdateCommand,
|
||||
);
|
||||
const scrollViewport = commandCode?.closest<HTMLElement>(
|
||||
'[data-slot="scroll-area-viewport"]',
|
||||
);
|
||||
|
||||
expect(popup).toBeTruthy();
|
||||
expect(commandCode).toBeTruthy();
|
||||
expect(scrollViewport).toBeTruthy();
|
||||
|
||||
const popupRect = popup!.getBoundingClientRect();
|
||||
const viewportRect = scrollViewport!.getBoundingClientRect();
|
||||
|
||||
expect(popupRect.width).toBeGreaterThan(300);
|
||||
expect(popupRect.width).toBeLessThanOrEqual(337);
|
||||
expect(viewportRect.right).toBeLessThanOrEqual(popupRect.right + 0.5);
|
||||
expect(scrollViewport!.scrollWidth).toBeGreaterThan(scrollViewport!.clientWidth);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("SourceControlSettingsPanel discovery states", () => {
|
||||
|
||||
@@ -22,9 +22,9 @@ function Combobox<Value, Multiple extends boolean | undefined = false>(
|
||||
const chipsRef = React.useRef<Element | null>(null);
|
||||
const value = React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple]);
|
||||
return (
|
||||
<ComboboxContext.Provider value={value}>
|
||||
<ComboboxContext value={value}>
|
||||
<ComboboxPrimitive.Root {...props} />
|
||||
</ComboboxContext.Provider>
|
||||
</ComboboxContext>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ function ComboboxPopup({
|
||||
side?: ComboboxPrimitive.Positioner.Props["side"];
|
||||
anchor?: ComboboxPrimitive.Positioner.Props["anchor"];
|
||||
}) {
|
||||
const { chipsRef } = React.useContext(ComboboxContext);
|
||||
const { chipsRef } = React.use(ComboboxContext);
|
||||
const anchor = anchorProp ?? chipsRef;
|
||||
|
||||
return (
|
||||
@@ -324,7 +324,7 @@ function ComboboxChips({
|
||||
}: ComboboxPrimitive.Chips.Props & {
|
||||
startAddon?: React.ReactNode;
|
||||
}) {
|
||||
const { chipsRef } = React.useContext(ComboboxContext);
|
||||
const { chipsRef } = React.use(ComboboxContext);
|
||||
|
||||
return (
|
||||
<ComboboxPrimitive.Chips
|
||||
|
||||
@@ -25,7 +25,7 @@ export function NumberField({
|
||||
const contextValue = React.useMemo(() => ({ fieldId }), [fieldId]);
|
||||
|
||||
return (
|
||||
<NumberFieldContext.Provider value={contextValue}>
|
||||
<NumberFieldContext value={contextValue}>
|
||||
<NumberFieldPrimitive.Root
|
||||
className={cn("flex w-full flex-col items-start gap-2", className)}
|
||||
data-size={size}
|
||||
@@ -33,7 +33,7 @@ export function NumberField({
|
||||
id={fieldId}
|
||||
{...props}
|
||||
/>
|
||||
</NumberFieldContext.Provider>
|
||||
</NumberFieldContext>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ export function NumberFieldScrubArea({
|
||||
}: NumberFieldPrimitive.ScrubArea.Props & {
|
||||
label: string;
|
||||
}): React.ReactElement {
|
||||
const context = React.useContext(NumberFieldContext);
|
||||
const context = React.use(NumberFieldContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
|
||||
@@ -77,7 +77,7 @@ const SidebarContext = React.createContext<SidebarContextProps | null>(null);
|
||||
const SidebarInstanceContext = React.createContext<SidebarInstanceContextProps | null>(null);
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext);
|
||||
const context = React.use(SidebarContext);
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.");
|
||||
}
|
||||
@@ -148,7 +148,7 @@ function SidebarProvider({
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<SidebarContext value={contextValue}>
|
||||
<div
|
||||
className={cn(
|
||||
"group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
|
||||
@@ -166,7 +166,7 @@ function SidebarProvider({
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</SidebarContext.Provider>
|
||||
</SidebarContext>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -206,7 +206,7 @@ function Sidebar({
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<SidebarInstanceContext.Provider value={instanceContextValue}>
|
||||
<SidebarInstanceContext value={instanceContextValue}>
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
|
||||
@@ -217,13 +217,13 @@ function Sidebar({
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</SidebarInstanceContext.Provider>
|
||||
</SidebarInstanceContext>
|
||||
);
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<SidebarInstanceContext.Provider value={instanceContextValue}>
|
||||
<SidebarInstanceContext value={instanceContextValue}>
|
||||
<Sheet onOpenChange={setOpenMobile} open={openMobile} {...props}>
|
||||
<SheetPopup
|
||||
className={cn(
|
||||
@@ -255,12 +255,12 @@ function Sidebar({
|
||||
</div>
|
||||
</SheetPopup>
|
||||
</Sheet>
|
||||
</SidebarInstanceContext.Provider>
|
||||
</SidebarInstanceContext>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarInstanceContext.Provider value={instanceContextValue}>
|
||||
<SidebarInstanceContext value={instanceContextValue}>
|
||||
<div
|
||||
className="group peer hidden text-sidebar-foreground md:block"
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
@@ -305,7 +305,7 @@ function Sidebar({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SidebarInstanceContext.Provider>
|
||||
</SidebarInstanceContext>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -345,7 +345,7 @@ function SidebarRail({
|
||||
...props
|
||||
}: React.ComponentProps<"button">) {
|
||||
const { open, toggleSidebar } = useSidebar();
|
||||
const sidebarInstance = React.useContext(SidebarInstanceContext);
|
||||
const sidebarInstance = React.use(SidebarInstanceContext);
|
||||
const railRef = React.useRef<HTMLButtonElement | null>(null);
|
||||
const suppressClickRef = React.useRef(false);
|
||||
const resizeStateRef = React.useRef<{
|
||||
@@ -889,7 +889,7 @@ function SidebarMenuSkeleton({
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean;
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
// Random width between 50 to 90%. Intentionally wrapped in useMemo to avoid changing width on every render.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`;
|
||||
}, []);
|
||||
|
||||
@@ -43,7 +43,7 @@ function ToggleGroup({
|
||||
orientation={orientation}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider value={value}>{children}</ToggleGroupContext.Provider>
|
||||
<ToggleGroupContext value={value}>{children}</ToggleGroupContext>
|
||||
</ToggleGroupPrimitive>
|
||||
);
|
||||
}
|
||||
@@ -55,7 +55,7 @@ function Toggle({
|
||||
size,
|
||||
...props
|
||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
const context = React.useContext(ToggleGroupContext);
|
||||
const context = React.use(ToggleGroupContext);
|
||||
|
||||
const resolvedVariant = variant ?? context.variant;
|
||||
const resolvedSize = size ?? context.size;
|
||||
|
||||
@@ -21,6 +21,7 @@ import { createModelSelection } from "@t3tools/shared/model";
|
||||
// `stickyModelSelectionByProvider` maps are keyed by `ProviderInstanceId`
|
||||
// in production; these aliases keep the legacy-key migration tests concise.
|
||||
const CODEX_INSTANCE = ProviderInstanceId.make("codex");
|
||||
const CODEX_SECONDARY_INSTANCE = ProviderInstanceId.make("codex_secondary");
|
||||
const CLAUDE_AGENT_INSTANCE = ProviderInstanceId.make("claudeAgent");
|
||||
const CURSOR_INSTANCE = ProviderInstanceId.make("cursor");
|
||||
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||
@@ -1201,6 +1202,43 @@ describe("composerDraftStore modelSelection", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("stores provider option changes on a selected custom instance", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setProviderModelOptions(
|
||||
threadRef,
|
||||
CODEX_DRIVER,
|
||||
toSelections({ reasoningEffort: "low" }),
|
||||
{
|
||||
instanceId: CODEX_SECONDARY_INSTANCE,
|
||||
model: "gpt-5-codex",
|
||||
persistSticky: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(
|
||||
draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CODEX_SECONDARY_INSTANCE],
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
instanceId: CODEX_SECONDARY_INSTANCE,
|
||||
options: [{ id: "reasoningEffort", value: "low" }],
|
||||
}),
|
||||
);
|
||||
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.activeProvider).toBe(CODEX_SECONDARY_INSTANCE);
|
||||
expect(useComposerDraftStore.getState().stickyActiveProvider).toBe(CODEX_SECONDARY_INSTANCE);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider[CODEX_INSTANCE]).toBe(
|
||||
undefined,
|
||||
);
|
||||
expect(
|
||||
useComposerDraftStore.getState().stickyModelSelectionByProvider[CODEX_SECONDARY_INSTANCE],
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
instanceId: CODEX_SECONDARY_INSTANCE,
|
||||
options: [{ id: "reasoningEffort", value: "low" }],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("updates only the draft when sticky persistence is disabled", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
|
||||
@@ -371,6 +371,7 @@ interface ComposerDraftStoreState {
|
||||
provider: ProviderDriverKind,
|
||||
nextProviderOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined,
|
||||
options?: {
|
||||
instanceId?: ProviderInstanceId | null | undefined;
|
||||
model?: string | null | undefined;
|
||||
persistSticky?: boolean;
|
||||
},
|
||||
@@ -2456,7 +2457,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (normalizedProvider === null) {
|
||||
return;
|
||||
}
|
||||
const instanceKey = defaultInstanceIdForDriver(normalizedProvider);
|
||||
const instanceKey = options?.instanceId ?? defaultInstanceIdForDriver(normalizedProvider);
|
||||
const fallbackModel =
|
||||
normalizeModelSlug(options?.model, normalizedProvider) ??
|
||||
DEFAULT_MODEL_BY_PROVIDER[normalizedProvider] ??
|
||||
@@ -2501,7 +2502,9 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
const { options: _, ...rest } = stickyBase;
|
||||
nextStickyMap[instanceKey] = rest as ModelSelection;
|
||||
}
|
||||
nextStickyActiveProvider = base.activeProvider ?? instanceKey;
|
||||
nextStickyActiveProvider = options.instanceId
|
||||
? instanceKey
|
||||
: (base.activeProvider ?? instanceKey);
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -2514,6 +2517,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
...(options?.instanceId ? { activeProvider: instanceKey } : {}),
|
||||
modelSelectionByProvider: nextMap,
|
||||
};
|
||||
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { createContext, useContext, type MutableRefObject } from "react";
|
||||
import { createContext, use } from "react";
|
||||
import type { ChatComposerHandle } from "./components/chat/ChatComposer";
|
||||
|
||||
export type ComposerHandleRef = MutableRefObject<ChatComposerHandle | null>;
|
||||
export type ComposerHandleRef = React.RefObject<ChatComposerHandle | null>;
|
||||
|
||||
export const ComposerHandleContext = createContext<ComposerHandleRef | null>(null);
|
||||
|
||||
export function useComposerHandleContext(): ComposerHandleRef | null {
|
||||
return useContext(ComposerHandleContext);
|
||||
return use(ComposerHandleContext);
|
||||
}
|
||||
@@ -176,6 +176,7 @@ describe("retainThreadDetailSubscription", () => {
|
||||
},
|
||||
})),
|
||||
},
|
||||
isHeartbeatFresh: vi.fn(() => true),
|
||||
orchestration: {
|
||||
subscribeThread: mockSubscribeThread,
|
||||
},
|
||||
@@ -382,7 +383,7 @@ describe("retainThreadDetailSubscription", () => {
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
|
||||
it("reconnects environment streams when the browser resumes from the background", async () => {
|
||||
it("keeps healthy environment streams connected when the browser resumes from the background", async () => {
|
||||
let visibilityState: DocumentVisibilityState = "visible";
|
||||
const documentTarget = new EventTarget();
|
||||
const windowTarget = new EventTarget();
|
||||
@@ -408,6 +409,57 @@ describe("retainThreadDetailSubscription", () => {
|
||||
documentTarget.dispatchEvent(new Event("visibilitychange"));
|
||||
expect(mockConnectionReconnects[0]).not.toHaveBeenCalled();
|
||||
|
||||
visibilityState = "visible";
|
||||
documentTarget.dispatchEvent(new Event("visibilitychange"));
|
||||
expect(mockConnectionReconnects[0]).not.toHaveBeenCalled();
|
||||
|
||||
stop();
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
|
||||
it("reconnects stale environment streams when the browser resumes from the background", async () => {
|
||||
let visibilityState: DocumentVisibilityState = "visible";
|
||||
const documentTarget = new EventTarget();
|
||||
const windowTarget = new EventTarget();
|
||||
vi.stubGlobal("document", {
|
||||
addEventListener: documentTarget.addEventListener.bind(documentTarget),
|
||||
removeEventListener: documentTarget.removeEventListener.bind(documentTarget),
|
||||
get visibilityState() {
|
||||
return visibilityState;
|
||||
},
|
||||
});
|
||||
vi.stubGlobal("window", {
|
||||
addEventListener: windowTarget.addEventListener.bind(windowTarget),
|
||||
removeEventListener: windowTarget.removeEventListener.bind(windowTarget),
|
||||
});
|
||||
mockCreateWsRpcClient.mockReturnValue({
|
||||
server: {
|
||||
getConfig: vi.fn(async () => ({
|
||||
environment: {
|
||||
environmentId: EnvironmentId.make("env-remote"),
|
||||
label: "Remote env",
|
||||
platform: { os: "darwin", arch: "arm64" },
|
||||
serverVersion: "0.0.0-test",
|
||||
capabilities: { repositoryIdentity: true },
|
||||
},
|
||||
})),
|
||||
},
|
||||
isHeartbeatFresh: vi.fn(() => false),
|
||||
orchestration: {
|
||||
subscribeThread: mockSubscribeThread,
|
||||
},
|
||||
});
|
||||
|
||||
const { resetEnvironmentServiceForTests, startEnvironmentConnectionService } =
|
||||
await import("./service");
|
||||
|
||||
const stop = startEnvironmentConnectionService(new QueryClient());
|
||||
expect(mockConnectionReconnects).toHaveLength(1);
|
||||
|
||||
visibilityState = "hidden";
|
||||
documentTarget.dispatchEvent(new Event("visibilitychange"));
|
||||
expect(mockConnectionReconnects[0]).not.toHaveBeenCalled();
|
||||
|
||||
visibilityState = "visible";
|
||||
documentTarget.dispatchEvent(new Event("visibilitychange"));
|
||||
expect(mockConnectionReconnects[0]).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -1482,9 +1482,12 @@ function reconnectEnvironmentConnectionsAfterBrowserResume(reason: string): void
|
||||
if (now - lastBrowserResumeReconnectAt < BROWSER_RESUME_RECONNECT_COOLDOWN_MS) {
|
||||
return;
|
||||
}
|
||||
lastBrowserResumeReconnectAt = now;
|
||||
|
||||
for (const connection of environmentConnections.values()) {
|
||||
if (connection.client.isHeartbeatFresh()) {
|
||||
continue;
|
||||
}
|
||||
lastBrowserResumeReconnectAt = now;
|
||||
void connection.reconnect().catch((error) => {
|
||||
console.warn("Environment reconnect after browser resume failed", {
|
||||
environmentId: connection.environmentId,
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { ServerProcessDiagnosticsResult } from "@t3tools/contracts";
|
||||
import type {
|
||||
ServerProcessDiagnosticsResult,
|
||||
ServerProcessResourceHistoryResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -11,6 +14,8 @@ import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
|
||||
const PROCESS_DIAGNOSTICS_STALE_TIME_MS = 2_000;
|
||||
const PROCESS_DIAGNOSTICS_IDLE_TTL_MS = 5 * 60_000;
|
||||
const PROCESS_RESOURCE_HISTORY_STALE_TIME_MS = 5_000;
|
||||
const PROCESS_RESOURCE_HISTORY_INPUT_SEPARATOR = ":";
|
||||
|
||||
const processDiagnosticsAtom = Atom.make(
|
||||
Effect.promise(() => ensureLocalApi().server.getProcessDiagnostics()),
|
||||
@@ -23,6 +28,38 @@ const processDiagnosticsAtom = Atom.make(
|
||||
Atom.withLabel("process-diagnostics"),
|
||||
);
|
||||
|
||||
function formatProcessResourceHistoryKey(input: {
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
}): string {
|
||||
return `${input.windowMs}${PROCESS_RESOURCE_HISTORY_INPUT_SEPARATOR}${input.bucketMs}`;
|
||||
}
|
||||
|
||||
function parseProcessResourceHistoryKey(key: string): {
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
} {
|
||||
const [windowMs = "0", bucketMs = "0"] = key.split(PROCESS_RESOURCE_HISTORY_INPUT_SEPARATOR);
|
||||
return {
|
||||
windowMs: Number(windowMs),
|
||||
bucketMs: Number(bucketMs),
|
||||
};
|
||||
}
|
||||
|
||||
const processResourceHistoryAtom = Atom.family((key: string) => {
|
||||
const input = parseProcessResourceHistoryKey(key);
|
||||
return Atom.make(
|
||||
Effect.promise(() => ensureLocalApi().server.getProcessResourceHistory(input)),
|
||||
).pipe(
|
||||
Atom.swr({
|
||||
staleTime: PROCESS_RESOURCE_HISTORY_STALE_TIME_MS,
|
||||
revalidateOnMount: true,
|
||||
}),
|
||||
Atom.setIdleTTL(PROCESS_DIAGNOSTICS_IDLE_TTL_MS),
|
||||
Atom.withLabel(`process-resource-history:${key}`),
|
||||
);
|
||||
});
|
||||
|
||||
export interface ProcessDiagnosticsState {
|
||||
readonly data: ServerProcessDiagnosticsResult | null;
|
||||
readonly error: string | null;
|
||||
@@ -30,6 +67,13 @@ export interface ProcessDiagnosticsState {
|
||||
readonly refresh: () => void;
|
||||
}
|
||||
|
||||
export interface ProcessResourceHistoryState {
|
||||
readonly data: ServerProcessResourceHistoryResult | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly refresh: () => void;
|
||||
}
|
||||
|
||||
function formatProcessDiagnosticsError(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "Failed to load process diagnostics.";
|
||||
}
|
||||
@@ -45,6 +89,17 @@ function readProcessDiagnosticsError(
|
||||
return formatProcessDiagnosticsError(squashed);
|
||||
}
|
||||
|
||||
function readProcessResourceHistoryError(
|
||||
result: AsyncResult.AsyncResult<ServerProcessResourceHistoryResult, unknown>,
|
||||
): string | null {
|
||||
if (result._tag !== "Failure") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const squashed = Cause.squash(result.cause);
|
||||
return formatProcessDiagnosticsError(squashed);
|
||||
}
|
||||
|
||||
export function refreshProcessDiagnostics(): void {
|
||||
appAtomRegistry.refresh(processDiagnosticsAtom);
|
||||
}
|
||||
@@ -63,3 +118,23 @@ export function useProcessDiagnostics(): ProcessDiagnosticsState {
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
|
||||
export function useProcessResourceHistory(input: {
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
}): ProcessResourceHistoryState {
|
||||
const atom = processResourceHistoryAtom(formatProcessResourceHistoryKey(input));
|
||||
const result = useAtomValue(atom);
|
||||
const data = Option.getOrNull(AsyncResult.value(result));
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
appAtomRegistry.refresh(atom);
|
||||
}, [atom]);
|
||||
|
||||
return {
|
||||
data,
|
||||
error: readProcessResourceHistoryError(result),
|
||||
isPending: result.waiting,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -155,6 +155,10 @@ function createBrowserLocalApi(rpcClient?: WsRpcClient): LocalApi {
|
||||
rpcClient
|
||||
? rpcClient.server.getProcessDiagnostics()
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
getProcessResourceHistory: (input) =>
|
||||
rpcClient
|
||||
? rpcClient.server.getProcessResourceHistory(input)
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
signalProcess: (input) =>
|
||||
rpcClient
|
||||
? rpcClient.server.signalProcess(input)
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import type { ReactNode } from "react";
|
||||
import { createElement } from "react";
|
||||
|
||||
export let appAtomRegistry = AtomRegistry.make();
|
||||
|
||||
export function AppAtomRegistryProvider({ children }: { readonly children: ReactNode }) {
|
||||
return <RegistryContext.Provider value={appAtomRegistry}>{children}</RegistryContext.Provider>;
|
||||
export function AppAtomRegistryProvider({ children }: React.PropsWithChildren) {
|
||||
return createElement(RegistryContext.Provider, { value: appAtomRegistry }, children);
|
||||
}
|
||||
|
||||
export function resetAppAtomRegistryForTests() {
|
||||
@@ -56,6 +56,7 @@ interface GitRunStackedActionOptions {
|
||||
export interface WsRpcClient {
|
||||
readonly dispose: () => Promise<void>;
|
||||
readonly reconnect: () => Promise<void>;
|
||||
readonly isHeartbeatFresh: () => boolean;
|
||||
readonly terminal: {
|
||||
readonly open: RpcUnaryMethod<typeof WS_METHODS.terminalOpen>;
|
||||
readonly write: RpcUnaryMethod<typeof WS_METHODS.terminalWrite>;
|
||||
@@ -134,6 +135,9 @@ export interface WsRpcClient {
|
||||
readonly getProcessDiagnostics: RpcUnaryNoArgMethod<
|
||||
typeof WS_METHODS.serverGetProcessDiagnostics
|
||||
>;
|
||||
readonly getProcessResourceHistory: RpcUnaryMethod<
|
||||
typeof WS_METHODS.serverGetProcessResourceHistory
|
||||
>;
|
||||
readonly signalProcess: RpcUnaryMethod<typeof WS_METHODS.serverSignalProcess>;
|
||||
readonly subscribeConfig: RpcStreamMethod<typeof WS_METHODS.subscribeServerConfig>;
|
||||
readonly subscribeLifecycle: RpcStreamMethod<typeof WS_METHODS.subscribeServerLifecycle>;
|
||||
@@ -158,6 +162,7 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
|
||||
resetWsReconnectBackoff();
|
||||
await transport.reconnect();
|
||||
},
|
||||
isHeartbeatFresh: () => transport.isHeartbeatFresh(),
|
||||
terminal: {
|
||||
open: (input) => transport.request((client) => client[WS_METHODS.terminalOpen](input)),
|
||||
write: (input) => transport.request((client) => client[WS_METHODS.terminalWrite](input)),
|
||||
@@ -264,6 +269,12 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
|
||||
transport.request((client) =>
|
||||
client[WS_METHODS.serverGetProcessDiagnostics]({}).pipe(Effect.withTracerEnabled(false)),
|
||||
),
|
||||
getProcessResourceHistory: (input) =>
|
||||
transport.request((client) =>
|
||||
client[WS_METHODS.serverGetProcessResourceHistory](input).pipe(
|
||||
Effect.withTracerEnabled(false),
|
||||
),
|
||||
),
|
||||
signalProcess: (input) =>
|
||||
transport.request((client) =>
|
||||
client[WS_METHODS.serverSignalProcess](input).pipe(Effect.withTracerEnabled(false)),
|
||||
|
||||
@@ -17,9 +17,13 @@
|
||||
},
|
||||
"apps/desktop": {
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/ssh": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
"electron": "41.5.0",
|
||||
"electron-updater": "^6.6.2",
|
||||
@@ -27,13 +31,7 @@
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/ssh": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
@@ -52,7 +50,7 @@
|
||||
},
|
||||
"apps/server": {
|
||||
"name": "t3",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"bin": {
|
||||
"t3": "./dist/bin.mjs",
|
||||
},
|
||||
@@ -60,12 +58,12 @@
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/platform-node-shared": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
@@ -85,7 +83,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.4.1",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
@@ -109,8 +107,8 @@
|
||||
"effect": "catalog:",
|
||||
"lexical": "^0.41.0",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6",
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
@@ -122,12 +120,12 @@
|
||||
"@tailwindcss/vite": "^4.0.0",
|
||||
"@tanstack/router-plugin": "^1.161.0",
|
||||
"@types/babel__core": "^7.20.5",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@types/react": "~19.2.14",
|
||||
"@types/react-dom": "~19.2.3",
|
||||
"@vercel/config": "^0.3.0",
|
||||
"@vitejs/plugin-react": "^6.0.0",
|
||||
"@vitest/browser-playwright": "^4.0.18",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"babel-plugin-react-compiler": "1.0.0",
|
||||
"msw": "2.12.11",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
@@ -154,9 +152,9 @@
|
||||
},
|
||||
"packages/client-runtime": {
|
||||
"name": "@t3tools/client-runtime",
|
||||
"version": "0.0.0-alpha.1",
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -167,14 +165,13 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
},
|
||||
@@ -189,7 +186,6 @@
|
||||
"@effect/openapi-generator": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
},
|
||||
@@ -204,14 +200,12 @@
|
||||
"@effect/openapi-generator": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
},
|
||||
},
|
||||
"packages/shared": {
|
||||
"name": "@t3tools/shared",
|
||||
"version": "0.0.0-alpha.1",
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
@@ -227,7 +221,6 @@
|
||||
},
|
||||
"packages/ssh": {
|
||||
"name": "@t3tools/ssh",
|
||||
"version": "0.0.0-alpha.1",
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
@@ -244,7 +237,6 @@
|
||||
},
|
||||
"packages/tailscale": {
|
||||
"name": "@t3tools/tailscale",
|
||||
"version": "0.0.0-alpha.1",
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
@@ -1012,7 +1004,7 @@
|
||||
|
||||
"babel-dead-code-elimination": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="],
|
||||
|
||||
"babel-plugin-react-compiler": ["babel-plugin-react-compiler@19.0.0-beta-ebf51a3-20250411", "", { "dependencies": { "@babel/types": "^7.26.0" } }, "sha512-q84bNR9JG1crykAlJUt5Ud0/5BUyMFuQww/mrwIQDFBaxsikqBDj3f/FNDsVd2iR26A1HvXKWPEIfgJDv8/V2g=="],
|
||||
"babel-plugin-react-compiler": ["[email protected]", "", { "dependencies": { "@babel/types": "^7.26.0" } }, "sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw=="],
|
||||
|
||||
"bail": ["[email protected]", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
|
||||
|
||||
@@ -1038,8 +1030,6 @@
|
||||
|
||||
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg=="],
|
||||
|
||||
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
|
||||
|
||||
"bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
|
||||
|
||||
"cac": ["[email protected]", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
|
||||
@@ -1126,16 +1116,10 @@
|
||||
|
||||
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
|
||||
|
||||
"default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
|
||||
|
||||
"default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
|
||||
|
||||
"defer-to-connect": ["[email protected]", "", {}, "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg=="],
|
||||
|
||||
"define-data-property": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="],
|
||||
|
||||
"define-lazy-prop": ["[email protected]", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="],
|
||||
|
||||
"define-properties": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
|
||||
|
||||
"defu": ["[email protected]", "", {}, "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg=="],
|
||||
@@ -1664,8 +1648,6 @@
|
||||
|
||||
"oniguruma-to-es": ["[email protected]", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-Zjygswjpsewa0NLTsiizVuMQZbp0MDyM6lIt66OxsF21npUDlzpHi1Mgb/qhQdkb+dWFTzJmFbEWdvZgRho8eQ=="],
|
||||
|
||||
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
|
||||
|
||||
"outvariant": ["[email protected]", "", {}, "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA=="],
|
||||
|
||||
"oxfmt": ["[email protected]", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.40.0", "@oxfmt/binding-android-arm64": "0.40.0", "@oxfmt/binding-darwin-arm64": "0.40.0", "@oxfmt/binding-darwin-x64": "0.40.0", "@oxfmt/binding-freebsd-x64": "0.40.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.40.0", "@oxfmt/binding-linux-arm-musleabihf": "0.40.0", "@oxfmt/binding-linux-arm64-gnu": "0.40.0", "@oxfmt/binding-linux-arm64-musl": "0.40.0", "@oxfmt/binding-linux-ppc64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-musl": "0.40.0", "@oxfmt/binding-linux-s390x-gnu": "0.40.0", "@oxfmt/binding-linux-x64-gnu": "0.40.0", "@oxfmt/binding-linux-x64-musl": "0.40.0", "@oxfmt/binding-openharmony-arm64": "0.40.0", "@oxfmt/binding-win32-arm64-msvc": "0.40.0", "@oxfmt/binding-win32-ia32-msvc": "0.40.0", "@oxfmt/binding-win32-x64-msvc": "0.40.0" }, "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-g0C3I7xUj4b4DcagevM9kgH6+pUHytikxUcn3/VUkvzTNaaXBeyZqb7IBsHwojeXm4mTBEC/aBjBTMVUkZwWUQ=="],
|
||||
@@ -1748,9 +1730,9 @@
|
||||
|
||||
"raw-body": ["[email protected]", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
|
||||
|
||||
"react": ["[email protected].4", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
|
||||
"react": ["[email protected].6", "", {}, "sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q=="],
|
||||
|
||||
"react-dom": ["[email protected].4", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
|
||||
"react-dom": ["[email protected].6", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.6" } }, "sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g=="],
|
||||
|
||||
"react-error-boundary": ["[email protected]", "", { "peerDependencies": { "react": "^18.0.0 || ^19.0.0" } }, "sha512-BrYwPOdXi5mqkk5lw+Uvt0ThHx32rCt3BkukS4X23A2AIWDPSGX6iaWTc0y9TU/mHDA/6qOSGel+B2ERkOvD1w=="],
|
||||
|
||||
@@ -1820,8 +1802,6 @@
|
||||
|
||||
"router": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
|
||||
|
||||
"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
|
||||
|
||||
"safer-buffer": ["[email protected]", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
|
||||
|
||||
"sax": ["[email protected]", "", {}, "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA=="],
|
||||
@@ -2110,8 +2090,6 @@
|
||||
|
||||
"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
|
||||
|
||||
"wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="],
|
||||
|
||||
"xxhash-wasm": ["[email protected]", "", {}, "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA=="],
|
||||
|
||||
"y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"label": "after",
|
||||
"capturedAt": "2026-05-11T16:21:51.199Z",
|
||||
"reactScanEnabled": true,
|
||||
"webSocketConnectionCoordinatorRenderCount": 2,
|
||||
"webSocketConnectionCoordinatorUpdateCount": 1,
|
||||
"totalActualDurationMs": 1.2,
|
||||
"metrics": [
|
||||
{
|
||||
"id": "WebSocketConnectionCoordinator",
|
||||
"phase": "mount",
|
||||
"actualDuration": 1,
|
||||
"startTime": 790.3999999761581,
|
||||
"commitTime": 791.6999999880791
|
||||
},
|
||||
{
|
||||
"id": "WebSocketConnectionCoordinator",
|
||||
"phase": "update",
|
||||
"actualDuration": 0.20000004768371582,
|
||||
"startTime": 811.3999999761581,
|
||||
"commitTime": 811.6000000238419
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
{
|
||||
"label": "before",
|
||||
"capturedAt": "2026-05-11T16:20:08.109Z",
|
||||
"reactScanEnabled": true,
|
||||
"webSocketConnectionCoordinatorRenderCount": 9,
|
||||
"webSocketConnectionCoordinatorUpdateCount": 8,
|
||||
"totalActualDurationMs": 2,
|
||||
"metrics": [
|
||||
{
|
||||
"id": "WebSocketConnectionCoordinator",
|
||||
"phase": "mount",
|
||||
"actualDuration": 0.8999999761581421,
|
||||
"startTime": 665.6000000238419,
|
||||
"commitTime": 666.8999999761581
|
||||
},
|
||||
{
|
||||
"id": "WebSocketConnectionCoordinator",
|
||||
"phase": "update",
|
||||
"actualDuration": 0.30000001192092896,
|
||||
"startTime": 690.6999999880791,
|
||||
"commitTime": 691.1000000238419
|
||||
},
|
||||
{
|
||||
"id": "WebSocketConnectionCoordinator",
|
||||
"phase": "update",
|
||||
"actualDuration": 0.19999998807907104,
|
||||
"startTime": 769.1000000238419,
|
||||
"commitTime": 769.3999999761581
|
||||
},
|
||||
{
|
||||
"id": "WebSocketConnectionCoordinator",
|
||||
"phase": "update",
|
||||
"actualDuration": 0.10000002384185791,
|
||||
"startTime": 1692,
|
||||
"commitTime": 1692.199999988079
|
||||
},
|
||||
{
|
||||
"id": "WebSocketConnectionCoordinator",
|
||||
"phase": "update",
|
||||
"actualDuration": 0.09999996423721313,
|
||||
"startTime": 2691.800000011921,
|
||||
"commitTime": 2691.899999976158
|
||||
},
|
||||
{
|
||||
"id": "WebSocketConnectionCoordinator",
|
||||
"phase": "update",
|
||||
"actualDuration": 0.19999998807907104,
|
||||
"startTime": 3691.800000011921,
|
||||
"commitTime": 3692
|
||||
},
|
||||
{
|
||||
"id": "WebSocketConnectionCoordinator",
|
||||
"phase": "update",
|
||||
"actualDuration": 0.10000002384185791,
|
||||
"startTime": 4691.899999976158,
|
||||
"commitTime": 4692.100000023842
|
||||
},
|
||||
{
|
||||
"id": "WebSocketConnectionCoordinator",
|
||||
"phase": "update",
|
||||
"actualDuration": 0,
|
||||
"startTime": 5691.899999976158,
|
||||
"commitTime": 5691.899999976158
|
||||
},
|
||||
{
|
||||
"id": "WebSocketConnectionCoordinator",
|
||||
"phase": "update",
|
||||
"actualDuration": 0.10000002384185791,
|
||||
"startTime": 6691.899999976158,
|
||||
"commitTime": 6692
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
{
|
||||
"name": "@t3tools/client-runtime",
|
||||
"version": "0.0.0-alpha.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
@@ -15,6 +14,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,78 +1 @@
|
||||
import type {
|
||||
AdvertisedEndpoint,
|
||||
AdvertisedEndpointHostedHttpsCompatibility,
|
||||
AdvertisedEndpointProvider,
|
||||
AdvertisedEndpointReachability,
|
||||
AdvertisedEndpointSource,
|
||||
AdvertisedEndpointStatus,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface CreateAdvertisedEndpointInput {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly provider: AdvertisedEndpointProvider;
|
||||
readonly httpBaseUrl: string;
|
||||
readonly reachability: AdvertisedEndpointReachability;
|
||||
readonly hostedHttpsCompatibility?: AdvertisedEndpointHostedHttpsCompatibility;
|
||||
readonly desktopCompatibility?: "compatible" | "unknown";
|
||||
readonly source: AdvertisedEndpointSource;
|
||||
readonly status?: AdvertisedEndpointStatus;
|
||||
readonly isDefault?: boolean;
|
||||
readonly description?: string;
|
||||
}
|
||||
|
||||
export function normalizeHttpBaseUrl(rawValue: string): string {
|
||||
const url = new URL(rawValue);
|
||||
if (url.protocol === "ws:") {
|
||||
url.protocol = "http:";
|
||||
} else if (url.protocol === "wss:") {
|
||||
url.protocol = "https:";
|
||||
}
|
||||
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
throw new Error(`Endpoint must use HTTP or HTTPS. Received ${url.protocol}`);
|
||||
}
|
||||
|
||||
url.pathname = "/";
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export function deriveWsBaseUrl(httpBaseUrl: string): string {
|
||||
const url = new URL(normalizeHttpBaseUrl(httpBaseUrl));
|
||||
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export function classifyHostedHttpsCompatibility(
|
||||
httpBaseUrl: string,
|
||||
fallback: AdvertisedEndpointHostedHttpsCompatibility = "unknown",
|
||||
): AdvertisedEndpointHostedHttpsCompatibility {
|
||||
const url = new URL(normalizeHttpBaseUrl(httpBaseUrl));
|
||||
if (url.protocol === "http:") {
|
||||
return "mixed-content-blocked";
|
||||
}
|
||||
return fallback === "mixed-content-blocked" ? "unknown" : fallback;
|
||||
}
|
||||
|
||||
export function createAdvertisedEndpoint(input: CreateAdvertisedEndpointInput): AdvertisedEndpoint {
|
||||
const httpBaseUrl = normalizeHttpBaseUrl(input.httpBaseUrl);
|
||||
return {
|
||||
id: input.id,
|
||||
label: input.label,
|
||||
provider: input.provider,
|
||||
httpBaseUrl,
|
||||
wsBaseUrl: deriveWsBaseUrl(httpBaseUrl),
|
||||
reachability: input.reachability,
|
||||
compatibility: {
|
||||
hostedHttpsApp:
|
||||
input.hostedHttpsCompatibility ?? classifyHostedHttpsCompatibility(httpBaseUrl),
|
||||
desktopApp: input.desktopCompatibility ?? "compatible",
|
||||
},
|
||||
source: input.source,
|
||||
status: input.status ?? "available",
|
||||
...(input.isDefault === undefined ? {} : { isDefault: input.isDefault }),
|
||||
...(input.description === undefined ? {} : { description: input.description }),
|
||||
};
|
||||
}
|
||||
export * from "@t3tools/shared/advertisedEndpoint";
|
||||
@@ -1,29 +1,22 @@
|
||||
{
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.23",
|
||||
"version": "0.0.24",
|
||||
"private": true,
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
"./settings": {
|
||||
"types": "./src/settings.ts",
|
||||
"import": "./src/settings.ts",
|
||||
"require": "./src/settings.ts"
|
||||
},
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"import": "./src/index.ts",
|
||||
"require": "./dist/index.cjs"
|
||||
"import": "./src/index.ts"
|
||||
},
|
||||
"./settings": {
|
||||
"types": "./src/settings.ts",
|
||||
"import": "./src/settings.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "tsdown src/index.ts --format esm,cjs --dts --watch --clean",
|
||||
"build": "tsdown src/index.ts --format esm,cjs --dts --clean",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
@@ -33,7 +26,6 @@
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
|
||||
@@ -44,13 +44,16 @@ export const EDITORS = [
|
||||
export const EditorId = Schema.Literals(EDITORS.map((e) => e.id));
|
||||
export type EditorId = typeof EditorId.Type;
|
||||
|
||||
export const OpenInEditorInput = Schema.Struct({
|
||||
export const LaunchEditorInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
editor: EditorId,
|
||||
});
|
||||
export type OpenInEditorInput = typeof OpenInEditorInput.Type;
|
||||
export type LaunchEditorInput = typeof LaunchEditorInput.Type;
|
||||
|
||||
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
export class ExternalLauncherError extends Schema.TaggedErrorClass<ExternalLauncherError>()(
|
||||
"ExternalLauncherError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
@@ -29,6 +29,8 @@ import type { ProviderInstanceId } from "./providerInstance.ts";
|
||||
import type {
|
||||
ServerConfig,
|
||||
ServerProcessDiagnosticsResult,
|
||||
ServerProcessResourceHistoryInput,
|
||||
ServerProcessResourceHistoryResult,
|
||||
ServerProviderUpdateInput,
|
||||
ServerProviderUpdatedPayload,
|
||||
ServerRemoveKeybindingResult,
|
||||
@@ -475,6 +477,9 @@ export interface LocalApi {
|
||||
discoverSourceControl: () => Promise<SourceControlDiscoveryResult>;
|
||||
getTraceDiagnostics: () => Promise<ServerTraceDiagnosticsResult>;
|
||||
getProcessDiagnostics: () => Promise<ServerProcessDiagnosticsResult>;
|
||||
getProcessResourceHistory: (
|
||||
input: ServerProcessResourceHistoryInput,
|
||||
) => Promise<ServerProcessResourceHistoryResult>;
|
||||
signalProcess: (input: ServerSignalProcessInput) => Promise<ServerSignalProcessResult>;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as Rpc from "effect/unstable/rpc/Rpc";
|
||||
import * as RpcGroup from "effect/unstable/rpc/RpcGroup";
|
||||
|
||||
import { OpenError, OpenInEditorInput } from "./editor.ts";
|
||||
import { ExternalLauncherError, LaunchEditorInput } from "./editor.ts";
|
||||
import { AuthAccessStreamEvent } from "./auth.ts";
|
||||
import {
|
||||
FilesystemBrowseInput,
|
||||
@@ -79,6 +79,8 @@ import {
|
||||
ServerProviderUpdatedPayload,
|
||||
ServerTraceDiagnosticsResult,
|
||||
ServerProcessDiagnosticsResult,
|
||||
ServerProcessResourceHistoryInput,
|
||||
ServerProcessResourceHistoryResult,
|
||||
ServerSignalProcessInput,
|
||||
ServerSignalProcessResult,
|
||||
ServerUpsertKeybindingInput,
|
||||
@@ -145,6 +147,7 @@ export const WS_METHODS = {
|
||||
serverDiscoverSourceControl: "server.discoverSourceControl",
|
||||
serverGetTraceDiagnostics: "server.getTraceDiagnostics",
|
||||
serverGetProcessDiagnostics: "server.getProcessDiagnostics",
|
||||
serverGetProcessResourceHistory: "server.getProcessResourceHistory",
|
||||
serverSignalProcess: "server.signalProcess",
|
||||
|
||||
// Source control methods
|
||||
@@ -224,6 +227,14 @@ export const WsServerGetProcessDiagnosticsRpc = Rpc.make(WS_METHODS.serverGetPro
|
||||
success: ServerProcessDiagnosticsResult,
|
||||
});
|
||||
|
||||
export const WsServerGetProcessResourceHistoryRpc = Rpc.make(
|
||||
WS_METHODS.serverGetProcessResourceHistory,
|
||||
{
|
||||
payload: ServerProcessResourceHistoryInput,
|
||||
success: ServerProcessResourceHistoryResult,
|
||||
},
|
||||
);
|
||||
|
||||
export const WsServerSignalProcessRpc = Rpc.make(WS_METHODS.serverSignalProcess, {
|
||||
payload: ServerSignalProcessInput,
|
||||
success: ServerSignalProcessResult,
|
||||
@@ -266,8 +277,8 @@ export const WsProjectsWriteFileRpc = Rpc.make(WS_METHODS.projectsWriteFile, {
|
||||
});
|
||||
|
||||
export const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {
|
||||
payload: OpenInEditorInput,
|
||||
error: OpenError,
|
||||
payload: LaunchEditorInput,
|
||||
error: ExternalLauncherError,
|
||||
});
|
||||
|
||||
export const WsFilesystemBrowseRpc = Rpc.make(WS_METHODS.filesystemBrowse, {
|
||||
@@ -472,6 +483,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerDiscoverSourceControlRpc,
|
||||
WsServerGetTraceDiagnosticsRpc,
|
||||
WsServerGetProcessDiagnosticsRpc,
|
||||
WsServerGetProcessResourceHistoryRpc,
|
||||
WsServerSignalProcessRpc,
|
||||
WsSourceControlLookupRepositoryRpc,
|
||||
WsSourceControlCloneRepositoryRpc,
|
||||
|
||||