Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5af56065a9 | ||
|
|
845d508fb7 | ||
|
|
cb1c5cf683 | ||
|
|
9f819581e6 | ||
|
|
d90df543ed | ||
|
|
d1e85c4e8f | ||
|
|
ea20e80021 | ||
|
|
9e632f5cec | ||
|
|
4120e94598 | ||
|
|
34bb18c8cf | ||
|
|
90eea047a9 | ||
|
|
f92e1e1b06 | ||
|
|
556c42452c | ||
|
|
7e20b23e7e | ||
|
|
b83e9c95e4 |
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
|
||||
|
||||
@@ -18,10 +18,12 @@ release-mock/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
apps/marketing/public/provider-compatibility.v1.json
|
||||
.vitest-*
|
||||
__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,
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"build": "astro build",
|
||||
"build": "bun ../../scripts/mirror-provider-compatibility-map.ts && astro build",
|
||||
"preview": "astro preview",
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
|
||||
|
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,13 +20,13 @@
|
||||
"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:",
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
AuthSessionId,
|
||||
RpcClientId,
|
||||
type HostPowerSnapshot,
|
||||
type ClientActivityReportInput,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as BackgroundPolicy from "./BackgroundPolicy.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
const TEST_NOW = DateTime.makeUnsafe("2026-05-13T00:00:00.000Z");
|
||||
|
||||
const nominalHostPower: HostPowerSnapshot = {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_NOW,
|
||||
};
|
||||
|
||||
const constrainedHostPower: HostPowerSnapshot = {
|
||||
...nominalHostPower,
|
||||
lowPowerMode: "true",
|
||||
stale: false,
|
||||
};
|
||||
|
||||
function makeReport(overrides: Partial<ClientActivityReportInput> = {}): ClientActivityReportInput {
|
||||
return {
|
||||
clientId: "client-1",
|
||||
clientKind: "web",
|
||||
visible: true,
|
||||
focused: true,
|
||||
recentlyInteracted: true,
|
||||
scopes: [{ type: "vcs-status", cwd: "/repo" }],
|
||||
ttlMs: 45_000,
|
||||
observedAt: TEST_NOW,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
hostPower: HostPowerSnapshot,
|
||||
settingsOverrides: Parameters<typeof ServerSettingsService.layerTest>[0] = {},
|
||||
) {
|
||||
const hostLayer = Layer.effect(
|
||||
HostPowerMonitor.HostPowerMonitor,
|
||||
Effect.gen(function* () {
|
||||
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
|
||||
let snapshot = hostPower;
|
||||
return HostPowerMonitor.HostPowerMonitor.of({
|
||||
snapshot: Effect.sync(() => snapshot),
|
||||
report: (next) =>
|
||||
Effect.sync(() => {
|
||||
snapshot = next;
|
||||
}).pipe(Effect.andThen(PubSub.publish(changes, next)), Effect.asVoid),
|
||||
setDemandActive: () => Effect.void,
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
});
|
||||
}),
|
||||
);
|
||||
return BackgroundPolicy.layer.pipe(
|
||||
Layer.provide(Layer.merge(hostLayer, ServerSettingsService.layerTest(settingsOverrides))),
|
||||
);
|
||||
}
|
||||
|
||||
describe("BackgroundPolicy", () => {
|
||||
it.effect("records foreground scoped client demand", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 1);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, true);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/other" }), false);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/other" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect("removes all leases for a disconnected websocket connection", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
yield* policy.removeRpcClient(RpcClientId.make(1));
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 0);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, []);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect("host low power mode disables opportunistic work without dropping scoped demand", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 1);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, false);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(constrainedHostPower))),
|
||||
);
|
||||
|
||||
it.effect("keeps background demand visible while preventing scoped work", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport({ focused: false, visible: false }),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 0);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"performance profile allows background scoped work while a scoped lease is active",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport({ focused: false, visible: false }),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
}).pipe(
|
||||
Effect.provide(makeLayer(nominalHostPower, { backgroundActivityProfile: "performance" })),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("battery saver profile pauses scoped work on battery", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer(
|
||||
{
|
||||
...nominalHostPower,
|
||||
onBattery: "true",
|
||||
stale: false,
|
||||
},
|
||||
{ backgroundActivityProfile: "battery-saver" },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,276 +0,0 @@
|
||||
import {
|
||||
type AuthSessionId,
|
||||
type BackgroundPolicySnapshot,
|
||||
type BackgroundScope,
|
||||
type ClientActivityLease,
|
||||
type ClientActivityReportInput,
|
||||
type HostPowerSnapshot,
|
||||
type RpcClientId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getBackgroundActivityPresetSettings,
|
||||
resolveServerBackgroundActivitySettings,
|
||||
type ResolvedBackgroundActivitySettings,
|
||||
} from "@t3tools/shared/backgroundActivitySettings";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
export interface BackgroundPolicyShape {
|
||||
readonly reportClientActivity: (
|
||||
sessionId: AuthSessionId,
|
||||
rpcClientId: RpcClientId,
|
||||
input: ClientActivityReportInput,
|
||||
) => Effect.Effect<void>;
|
||||
readonly removeRpcClient: (rpcClientId: RpcClientId) => Effect.Effect<void>;
|
||||
readonly reportHostPowerState: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly snapshot: Effect.Effect<BackgroundPolicySnapshot>;
|
||||
readonly streamChanges: Stream.Stream<BackgroundPolicySnapshot>;
|
||||
readonly hasDemand: (scope: BackgroundScope) => Effect.Effect<boolean>;
|
||||
readonly shouldRunScopeWork: (scope: BackgroundScope) => Effect.Effect<boolean>;
|
||||
readonly shouldRunOpportunisticWork: Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
export class BackgroundPolicy extends Context.Service<BackgroundPolicy, BackgroundPolicyShape>()(
|
||||
"t3/background/BackgroundPolicy",
|
||||
) {}
|
||||
|
||||
const DEFAULT_LEASE_TTL_MS = 45_000;
|
||||
const MAX_LEASE_TTL_MS = 120_000;
|
||||
|
||||
function scopeKey(scope: BackgroundScope): string {
|
||||
switch (scope.type) {
|
||||
case "server-config":
|
||||
case "diagnostics":
|
||||
return scope.type;
|
||||
case "provider-status":
|
||||
return scope.instanceId ? `${scope.type}:${scope.instanceId}` : scope.type;
|
||||
case "vcs-status":
|
||||
case "git-refs":
|
||||
return `${scope.type}:${scope.cwd}`;
|
||||
case "thread":
|
||||
return `${scope.type}:${scope.threadId}`;
|
||||
}
|
||||
}
|
||||
|
||||
function isLeaseActive(lease: ClientActivityLease, now: DateTime.Utc): boolean {
|
||||
return DateTime.isGreaterThan(lease.expiresAt, now);
|
||||
}
|
||||
|
||||
function isForegroundLease(lease: ClientActivityLease, now: DateTime.Utc): boolean {
|
||||
return isLeaseActive(lease, now) && lease.visible && lease.focused;
|
||||
}
|
||||
|
||||
function leaseHasScope(lease: ClientActivityLease, scope: BackgroundScope): boolean {
|
||||
const key = scopeKey(scope);
|
||||
return lease.scopes.some((leaseScope) => scopeKey(leaseScope) === key);
|
||||
}
|
||||
|
||||
function hasThermalPressure(hostPower: HostPowerSnapshot): boolean {
|
||||
return hostPower.thermalState === "serious" || hostPower.thermalState === "critical";
|
||||
}
|
||||
|
||||
function isHostConstrained(
|
||||
hostPower: HostPowerSnapshot,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
if (
|
||||
(settings.pauseWhenHostLocked && hostPower.locked === "true") ||
|
||||
hasThermalPressure(hostPower)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (settings.pauseWhenHostLowPower && hostPower.lowPowerMode === "true") return true;
|
||||
return settings.pauseWhenOnBattery && hostPower.onBattery === "true";
|
||||
}
|
||||
|
||||
function isClientConstrained(
|
||||
lease: ClientActivityLease,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
if (settings.pauseWhenClientLowPower && lease.lowPowerMode === "true") return true;
|
||||
return settings.pauseWhenOnBattery && lease.batteryState === "unplugged";
|
||||
}
|
||||
|
||||
function leaseMayRunScopedWork(
|
||||
lease: ClientActivityLease,
|
||||
scope: BackgroundScope,
|
||||
now: DateTime.Utc,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
const activeWithScope = isLeaseActive(lease, now) && leaseHasScope(lease, scope);
|
||||
if (!activeWithScope || isClientConstrained(lease, settings)) {
|
||||
return false;
|
||||
}
|
||||
if (settings.profile === "performance") {
|
||||
return true;
|
||||
}
|
||||
return isForegroundLease(lease, now);
|
||||
}
|
||||
|
||||
function computeSnapshot(input: {
|
||||
readonly hostPower: HostPowerSnapshot;
|
||||
readonly leases: ReadonlyMap<string, ClientActivityLease>;
|
||||
readonly now: DateTime.Utc;
|
||||
readonly settings: ResolvedBackgroundActivitySettings;
|
||||
readonly updatedAt: DateTime.Utc;
|
||||
}): BackgroundPolicySnapshot {
|
||||
const activeLeases = [...input.leases.values()].filter((lease) =>
|
||||
isLeaseActive(lease, input.now),
|
||||
);
|
||||
const foregroundLeases = activeLeases.filter((lease) => isForegroundLease(lease, input.now));
|
||||
const activeScopeKeys = new Set<string>();
|
||||
for (const lease of activeLeases) {
|
||||
for (const scope of lease.scopes) {
|
||||
activeScopeKeys.add(scopeKey(scope));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
hostPower: input.hostPower,
|
||||
leases: activeLeases,
|
||||
activeForegroundLeaseCount: foregroundLeases.length,
|
||||
activeScopeKeys: [...activeScopeKeys].toSorted(),
|
||||
shouldRunOpportunisticWork:
|
||||
foregroundLeases.some((lease) => !isClientConstrained(lease, input.settings)) &&
|
||||
!isHostConstrained(input.hostPower, input.settings),
|
||||
updatedAt: input.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("background.policy.make")(function* () {
|
||||
const hostPowerMonitor = yield* HostPowerMonitor.HostPowerMonitor;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const leasesRef = yield* Ref.make(new Map<string, ClientActivityLease>());
|
||||
const changes = yield* PubSub.sliding<BackgroundPolicySnapshot>(1);
|
||||
|
||||
const backgroundActivitySettings = serverSettings.getSettings.pipe(
|
||||
Effect.map(resolveServerBackgroundActivitySettings),
|
||||
Effect.catch(() => Effect.succeed(getBackgroundActivityPresetSettings("balanced"))),
|
||||
);
|
||||
|
||||
const snapshot = Effect.gen(function* () {
|
||||
const [hostPower, leases, now, settings] = yield* Effect.all([
|
||||
hostPowerMonitor.snapshot,
|
||||
Ref.get(leasesRef),
|
||||
DateTime.now,
|
||||
backgroundActivitySettings,
|
||||
]);
|
||||
return computeSnapshot({ hostPower, leases, now, settings, updatedAt: now });
|
||||
});
|
||||
|
||||
const publishSnapshot = snapshot.pipe(
|
||||
Effect.tap((next) => hostPowerMonitor.setDemandActive(next.activeForegroundLeaseCount > 0)),
|
||||
Effect.flatMap((next) => PubSub.publish(changes, next)),
|
||||
);
|
||||
|
||||
const reportClientActivity: BackgroundPolicyShape["reportClientActivity"] = (
|
||||
sessionId,
|
||||
rpcClientId,
|
||||
input,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ttlMs = Math.min(
|
||||
Math.max(input.ttlMs ?? DEFAULT_LEASE_TTL_MS, 1_000),
|
||||
MAX_LEASE_TTL_MS,
|
||||
);
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: ttlMs });
|
||||
const lease: ClientActivityLease = {
|
||||
sessionId,
|
||||
rpcClientId,
|
||||
clientId: input.clientId,
|
||||
clientKind: input.clientKind,
|
||||
visible: input.visible,
|
||||
focused: input.focused,
|
||||
recentlyInteracted: input.recentlyInteracted,
|
||||
...(input.appState !== undefined ? { appState: input.appState } : {}),
|
||||
...(input.lowPowerMode !== undefined ? { lowPowerMode: input.lowPowerMode } : {}),
|
||||
...(input.batteryState !== undefined ? { batteryState: input.batteryState } : {}),
|
||||
...(input.networkType !== undefined ? { networkType: input.networkType } : {}),
|
||||
scopes: input.scopes,
|
||||
updatedAt: now,
|
||||
expiresAt,
|
||||
};
|
||||
yield* Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
next.set(`${rpcClientId}:${input.clientId}`, lease);
|
||||
return next;
|
||||
});
|
||||
yield* publishSnapshot;
|
||||
});
|
||||
|
||||
const removeRpcClient: BackgroundPolicyShape["removeRpcClient"] = (rpcClientId) =>
|
||||
Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
for (const key of next.keys()) {
|
||||
if (key.startsWith(`${rpcClientId}:`)) {
|
||||
next.delete(key);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}).pipe(Effect.andThen(publishSnapshot), Effect.asVoid);
|
||||
|
||||
const hasDemand: BackgroundPolicyShape["hasDemand"] = (scope) =>
|
||||
Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));
|
||||
|
||||
const shouldRunScopeWork: BackgroundPolicyShape["shouldRunScopeWork"] = (scope) =>
|
||||
Effect.gen(function* () {
|
||||
const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);
|
||||
if (isHostConstrained(current.hostPower, settings)) {
|
||||
return false;
|
||||
}
|
||||
return current.leases.some((lease) =>
|
||||
leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),
|
||||
);
|
||||
});
|
||||
|
||||
const shouldRunOpportunisticWork = Effect.map(
|
||||
snapshot,
|
||||
(current) => current.shouldRunOpportunisticWork,
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(hostPowerMonitor.streamChanges, () => publishSnapshot).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.forever(
|
||||
Effect.sleep("15 seconds").pipe(
|
||||
Effect.andThen(
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
yield* Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
for (const [key, lease] of next) {
|
||||
if (!isLeaseActive(lease, now)) {
|
||||
next.delete(key);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
),
|
||||
Effect.andThen(publishSnapshot),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
return BackgroundPolicy.of({
|
||||
reportClientActivity,
|
||||
removeRpcClient,
|
||||
reportHostPowerState: hostPowerMonitor.report,
|
||||
snapshot,
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
hasDemand,
|
||||
shouldRunScopeWork,
|
||||
shouldRunOpportunisticWork,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(BackgroundPolicy, make());
|
||||
@@ -1,209 +0,0 @@
|
||||
import {
|
||||
type BackgroundBooleanState,
|
||||
type HostPowerSnapshot,
|
||||
type HostPowerThermalState,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getBackgroundActivityPresetSettings,
|
||||
resolveServerBackgroundActivitySettings,
|
||||
} from "@t3tools/shared/backgroundActivitySettings";
|
||||
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 PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
|
||||
export interface HostPowerMonitorShape {
|
||||
readonly snapshot: Effect.Effect<HostPowerSnapshot>;
|
||||
readonly report: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly setDemandActive: (active: boolean) => Effect.Effect<void>;
|
||||
readonly streamChanges: Stream.Stream<HostPowerSnapshot>;
|
||||
}
|
||||
|
||||
export class HostPowerMonitor extends Context.Service<HostPowerMonitor, HostPowerMonitorShape>()(
|
||||
"t3/background/HostPowerMonitor",
|
||||
) {}
|
||||
|
||||
const COMMAND_TIMEOUT = Duration.seconds(3);
|
||||
|
||||
export const makeUnknownSnapshot = (
|
||||
source: HostPowerSnapshot["source"],
|
||||
updatedAt: HostPowerSnapshot["updatedAt"],
|
||||
): HostPowerSnapshot => ({
|
||||
source,
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt,
|
||||
});
|
||||
|
||||
function boolState(value: boolean | null): BackgroundBooleanState {
|
||||
if (value === null) return "unknown";
|
||||
return value ? "true" : "false";
|
||||
}
|
||||
|
||||
function parseIdleSeconds(ioregOutput: string): number | null {
|
||||
const match = /"HIDIdleTime"\s*=\s*(\d+)/u.exec(ioregOutput);
|
||||
if (!match) return null;
|
||||
const nanoseconds = Number(match[1]);
|
||||
return Number.isFinite(nanoseconds) ? Math.floor(nanoseconds / 1_000_000_000) : null;
|
||||
}
|
||||
|
||||
function parseOnBattery(pmsetBatteryOutput: string): boolean | null {
|
||||
if (/Now drawing from 'Battery Power'/iu.test(pmsetBatteryOutput)) return true;
|
||||
if (/Now drawing from 'AC Power'/iu.test(pmsetBatteryOutput)) return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseLowPowerMode(pmsetOutput: string): boolean | null {
|
||||
const match = /^\s*lowpowermode\s+([01])\s*$/imu.exec(pmsetOutput);
|
||||
if (!match) return null;
|
||||
return match[1] === "1";
|
||||
}
|
||||
|
||||
function parseThermalState(_output: string): HostPowerThermalState {
|
||||
// The stable shell adapter intentionally does not parse `pmset thermlog`;
|
||||
// native adapters can provide this without depending on human-formatted text.
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function runOptional(
|
||||
runner: ProcessRunner.ProcessRunnerShape,
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) {
|
||||
return runner
|
||||
.run({
|
||||
command,
|
||||
args,
|
||||
timeout: COMMAND_TIMEOUT,
|
||||
timeoutBehavior: "timedOutResult",
|
||||
outputMode: "truncate",
|
||||
maxOutputBytes: 32_000,
|
||||
})
|
||||
.pipe(Effect.option);
|
||||
}
|
||||
|
||||
const readMacShellSnapshot = Effect.fn("background.hostPower.readMacShellSnapshot")(function* () {
|
||||
const runner = yield* ProcessRunner.ProcessRunner;
|
||||
const updatedAt = yield* DateTime.now;
|
||||
const [idleOutput, batteryOutput, pmsetOutput] = yield* Effect.all(
|
||||
[
|
||||
runOptional(runner, "ioreg", ["-c", "IOHIDSystem"]),
|
||||
runOptional(runner, "pmset", ["-g", "batt"]),
|
||||
runOptional(runner, "pmset", ["-g"]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const idleSeconds = idleOutput._tag === "Some" ? parseIdleSeconds(idleOutput.value.stdout) : null;
|
||||
const onBattery =
|
||||
batteryOutput._tag === "Some" ? parseOnBattery(batteryOutput.value.stdout) : null;
|
||||
const lowPowerMode =
|
||||
pmsetOutput._tag === "Some" ? parseLowPowerMode(pmsetOutput.value.stdout) : null;
|
||||
|
||||
return {
|
||||
source: "node-macos-shell",
|
||||
idle: boolState(idleSeconds === null ? null : idleSeconds >= 60),
|
||||
idleSeconds,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: boolState(onBattery),
|
||||
lowPowerMode: boolState(lowPowerMode),
|
||||
thermalState: parseThermalState(""),
|
||||
stale: false,
|
||||
updatedAt,
|
||||
} satisfies HostPowerSnapshot;
|
||||
});
|
||||
|
||||
export const make = Effect.fn("background.hostPower.make")(function* (
|
||||
initialSource: HostPowerSnapshot["source"] = "unknown",
|
||||
) {
|
||||
const initial = makeUnknownSnapshot(initialSource, yield* DateTime.now);
|
||||
const latestRef = yield* Ref.make(initial);
|
||||
const demandActiveRef = yield* Ref.make(false);
|
||||
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
|
||||
|
||||
const report: HostPowerMonitorShape["report"] = (snapshot) =>
|
||||
Ref.set(latestRef, snapshot).pipe(
|
||||
Effect.andThen(PubSub.publish(changes, snapshot)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
return HostPowerMonitor.of({
|
||||
snapshot: Ref.get(latestRef),
|
||||
report,
|
||||
setDemandActive: (active) => Ref.set(demandActiveRef, active),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
});
|
||||
});
|
||||
|
||||
const unknownLayer = Layer.effect(HostPowerMonitor, make("unknown"));
|
||||
const linuxLayer = Layer.effect(HostPowerMonitor, make("node-linux"));
|
||||
const windowsLayer = Layer.effect(HostPowerMonitor, make("node-windows"));
|
||||
|
||||
const macShellLayer = Layer.effect(
|
||||
HostPowerMonitor,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const monitor = yield* make("node-macos-shell");
|
||||
const demandActiveRef = yield* Ref.make(true);
|
||||
const setDemandActive: HostPowerMonitorShape["setDemandActive"] = (active) =>
|
||||
Ref.set(demandActiveRef, active);
|
||||
const getPollInterval = Effect.gen(function* () {
|
||||
const demandActive = yield* Ref.get(demandActiveRef);
|
||||
const settings = yield* serverSettings.getSettings.pipe(
|
||||
Effect.map(resolveServerBackgroundActivitySettings),
|
||||
Effect.catch(() => Effect.succeed(getBackgroundActivityPresetSettings("balanced"))),
|
||||
);
|
||||
return demandActive
|
||||
? settings.hostPowerMonitorActiveInterval
|
||||
: settings.hostPowerMonitorIdleInterval;
|
||||
});
|
||||
const adaptiveMonitor = HostPowerMonitor.of({
|
||||
snapshot: monitor.snapshot,
|
||||
report: monitor.report,
|
||||
setDemandActive,
|
||||
streamChanges: monitor.streamChanges,
|
||||
});
|
||||
yield* readMacShellSnapshot().pipe(
|
||||
Effect.flatMap(adaptiveMonitor.report),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
yield* Effect.forever(
|
||||
getPollInterval.pipe(
|
||||
Effect.flatMap((interval) => Effect.sleep(Duration.max(interval, Duration.seconds(5)))),
|
||||
Effect.andThen(readMacShellSnapshot()),
|
||||
Effect.flatMap(adaptiveMonitor.report),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
return adaptiveMonitor;
|
||||
}),
|
||||
).pipe(Layer.provide(ProcessRunner.layer));
|
||||
|
||||
export const layer = Layer.unwrap(
|
||||
Effect.sync(() => {
|
||||
switch (process.platform) {
|
||||
case "darwin":
|
||||
return macShellLayer;
|
||||
case "linux":
|
||||
return linuxLayer;
|
||||
case "win32":
|
||||
return windowsLayer;
|
||||
default:
|
||||
return unknownLayer;
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -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,299 @@
|
||||
import type {
|
||||
ServerProcessResourceHistoryBucket,
|
||||
ServerProcessResourceHistoryInput,
|
||||
ServerProcessResourceHistoryResult,
|
||||
ServerProcessResourceHistorySummary,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
buildDescendantEntries,
|
||||
isDiagnosticsQueryProcess,
|
||||
type ProcessRow,
|
||||
readProcessRows,
|
||||
} from "./ProcessDiagnostics.ts";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 5_000;
|
||||
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* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
|
||||
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,
|
||||
]);
|
||||
|
||||
|
||||
@@ -24,9 +24,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
|
||||
import {
|
||||
@@ -49,10 +47,12 @@ import {
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import * as ProviderCompatibility from "../ProviderCompatibility.ts";
|
||||
import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
|
||||
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
|
||||
|
||||
function isClaudeNativeCommandPath(commandPath: string): boolean {
|
||||
@@ -77,14 +77,13 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderCompatibility.ProviderCompatibilityService
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
| ServerConfig;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -115,6 +114,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const providerCompatibility = yield* ProviderCompatibility.ProviderCompatibilityService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -174,9 +174,20 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.flatMap((snapshot) =>
|
||||
ProviderCompatibility.enrichProviderSnapshotWithTargetedCompatibilityAdvisory(
|
||||
snapshot,
|
||||
maintenanceCapabilities,
|
||||
),
|
||||
),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.provideService(
|
||||
ProviderCompatibility.ProviderCompatibilityService,
|
||||
providerCompatibility,
|
||||
),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
* @module provider/Drivers/CodexDriver
|
||||
*/
|
||||
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -31,9 +32,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
|
||||
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
|
||||
@@ -47,6 +46,7 @@ import {
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import * as ProviderCompatibility from "../ProviderCompatibility.ts";
|
||||
import {
|
||||
codexContinuationIdentity,
|
||||
materializeCodexShadowHome,
|
||||
@@ -55,6 +55,7 @@ import {
|
||||
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@openai/codex",
|
||||
@@ -68,14 +69,13 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
* registered driver and the runtime satisfies them once.
|
||||
*/
|
||||
export type CodexDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderCompatibility.ProviderCompatibilityService
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
| ServerConfig;
|
||||
|
||||
/**
|
||||
* Stamp instance identity onto a `ServerProvider` snapshot produced by the
|
||||
@@ -111,6 +111,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const providerCompatibility = yield* ProviderCompatibility.ProviderCompatibilityService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const homeLayout = yield* resolveCodexHomeLayout(config);
|
||||
@@ -173,9 +174,20 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.flatMap((snapshot) =>
|
||||
ProviderCompatibility.enrichProviderSnapshotWithTargetedCompatibilityAdvisory(
|
||||
snapshot,
|
||||
maintenanceCapabilities,
|
||||
),
|
||||
),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.provideService(
|
||||
ProviderCompatibility.ProviderCompatibilityService,
|
||||
providerCompatibility,
|
||||
),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
* @module provider/Drivers/CursorDriver
|
||||
*/
|
||||
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -22,8 +23,6 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
|
||||
@@ -46,9 +45,11 @@ import {
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import * as ProviderCompatibility from "../ProviderCompatibility.ts";
|
||||
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
@@ -60,14 +61,13 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
);
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderCompatibility.ProviderCompatibilityService
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
| ServerConfig;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -99,6 +99,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const providerCompatibility = yield* ProviderCompatibility.ProviderCompatibilityService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -152,7 +153,14 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(
|
||||
ProviderCompatibility.ProviderCompatibilityService,
|
||||
providerCompatibility,
|
||||
),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
* @module provider/Drivers/OpenCodeDriver
|
||||
*/
|
||||
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -22,9 +23,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
|
||||
import {
|
||||
@@ -47,9 +46,11 @@ import {
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import * as ProviderCompatibility from "../ProviderCompatibility.ts";
|
||||
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
|
||||
function isOpenCodeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
@@ -72,15 +73,14 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime
|
||||
| Path.Path
|
||||
| ProviderCompatibility.ProviderCompatibilityService
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
| ServerConfig;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -111,6 +111,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const providerCompatibility = yield* ProviderCompatibility.ProviderCompatibilityService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -152,9 +153,20 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.flatMap((snapshot) =>
|
||||
ProviderCompatibility.enrichProviderSnapshotWithTargetedCompatibilityAdvisory(
|
||||
snapshot,
|
||||
maintenanceCapabilities,
|
||||
),
|
||||
),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.provideService(
|
||||
ProviderCompatibility.ProviderCompatibilityService,
|
||||
providerCompatibility,
|
||||
),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "../providerMaintenance.ts";
|
||||
import * as ProviderCompatibility from "../ProviderCompatibility.ts";
|
||||
import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("cursor");
|
||||
@@ -1234,7 +1235,11 @@ export const enrichCursorSnapshot = (input: {
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
|
||||
readonly httpClient: HttpClient.HttpClient;
|
||||
}): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
}): Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | ProviderCompatibility.ProviderCompatibilityService
|
||||
> => {
|
||||
const { settings, snapshot, publishSnapshot } = input;
|
||||
const stampIdentity = input.stampIdentity ?? ((value) => value);
|
||||
|
||||
@@ -1242,6 +1247,12 @@ export const enrichCursorSnapshot = (input: {
|
||||
snapshot,
|
||||
input.maintenanceCapabilities,
|
||||
).pipe(
|
||||
Effect.flatMap((enrichedSnapshot) =>
|
||||
ProviderCompatibility.enrichProviderSnapshotWithTargetedCompatibilityAdvisory(
|
||||
enrichedSnapshot,
|
||||
input.maintenanceCapabilities,
|
||||
),
|
||||
),
|
||||
Effect.provideService(HttpClient.HttpClient, input.httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) =>
|
||||
publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),
|
||||
|
||||
@@ -33,20 +33,17 @@ import {
|
||||
type ProviderInstanceConfigMap,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver } from "../Drivers/CodexDriver.ts";
|
||||
import { CursorDriver } from "../Drivers/CursorDriver.ts";
|
||||
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
|
||||
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import * as ProviderCompatibility from "../ProviderCompatibility.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
|
||||
|
||||
@@ -56,37 +53,9 @@ const TestHttpClientLive = Layer.succeed(
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
|
||||
),
|
||||
);
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(true),
|
||||
shouldRunScopeWork: () => Effect.succeed(true),
|
||||
shouldRunOpportunisticWork: Effect.succeed(true),
|
||||
});
|
||||
const TestProviderCompatibilityLive = ProviderCompatibility.layer.pipe(
|
||||
Layer.provide(TestHttpClientLive),
|
||||
);
|
||||
|
||||
const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
|
||||
enabled: false,
|
||||
@@ -133,9 +102,8 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
prefix: "provider-instance-registry-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(TestProviderCompatibilityLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
@@ -272,9 +240,8 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
prefix: "provider-instance-registry-all-drivers-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(infraLayer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(TestProviderCompatibilityLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
@@ -33,7 +32,6 @@ import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
||||
|
||||
import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
|
||||
import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts";
|
||||
@@ -50,6 +48,7 @@ import { readProviderStatusCache, resolveProviderStatusCachePath } from "../prov
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
|
||||
import * as ProviderCompatibility from "../ProviderCompatibility.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
const decodeServerSettings = Schema.decodeSync(ServerSettings);
|
||||
const encodeServerSettings = Schema.encodeSync(ServerSettings);
|
||||
@@ -66,7 +65,6 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
@@ -74,35 +72,9 @@ const TestHttpClientLive = Layer.succeed(
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
|
||||
),
|
||||
);
|
||||
|
||||
const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(true),
|
||||
shouldRunScopeWork: () => Effect.succeed(true),
|
||||
shouldRunOpportunisticWork: Effect.succeed(true),
|
||||
});
|
||||
const TestProviderCompatibilityLive = ProviderCompatibility.layer.pipe(
|
||||
Layer.provide(TestHttpClientLive),
|
||||
);
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
@@ -767,7 +739,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-merged-persist-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -862,7 +833,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-refresh-failure-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -967,7 +937,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-sync-failure-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -1062,9 +1031,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(TestProviderCompatibilityLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
// NO spawner mock — `ChildProcessSpawner` is supplied by the
|
||||
// outer `NodeServices.layer` on `it.layer(...)` and will
|
||||
// genuinely spawn a subprocess. The missing-binary ENOENT is
|
||||
@@ -1138,6 +1107,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(TestProviderCompatibilityLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
// `it.live` does not inherit layers from the outer `it.layer`
|
||||
@@ -1145,7 +1115,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
// same real `ChildProcessSpawner` + `FileSystem` + `Path`
|
||||
// services that production uses.
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
Scope.provide(scope),
|
||||
@@ -1242,10 +1211,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(TestProviderCompatibilityLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
Scope.provide(scope),
|
||||
@@ -1294,9 +1263,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(TestProviderCompatibilityLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
if (command === "agent") {
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as ProviderCompatibility from "./ProviderCompatibility.ts";
|
||||
import { makeProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
const claudeDriver = ProviderDriverKind.make("claudeAgent");
|
||||
const opencodeDriver = ProviderDriverKind.make("opencode");
|
||||
const cursorDriver = ProviderDriverKind.make("cursor");
|
||||
|
||||
const baseProvider: ServerProvider = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: codexDriver,
|
||||
displayName: "Codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "0.130.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-10T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
const codexNpmUpdateCapabilities = makeProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "npm-global",
|
||||
});
|
||||
|
||||
function jsonHttpClient(
|
||||
responseForUrl: (url: string) => { readonly payload: unknown; readonly status?: number },
|
||||
): HttpClient.HttpClient {
|
||||
return HttpClient.make((request) => {
|
||||
const response = responseForUrl(request.url);
|
||||
return Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
new Response(JSON.stringify(response.payload), {
|
||||
status: response.status ?? 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const provideCompatibility = (
|
||||
responseForUrl: (url: string) => { readonly payload: unknown; readonly status?: number },
|
||||
) =>
|
||||
Effect.provide(
|
||||
ProviderCompatibility.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HttpClient.HttpClient, jsonHttpClient(responseForUrl))),
|
||||
),
|
||||
);
|
||||
|
||||
describe("provider compatibility", () => {
|
||||
it("selects policies by T3 Code version range", () => {
|
||||
const document: ProviderCompatibility.ProviderCompatibilityDocument = {
|
||||
version: 1,
|
||||
policies: [
|
||||
{
|
||||
t3CodeRange: "<0.1.0",
|
||||
driver: codexDriver,
|
||||
recommendedRange: "<0.130.0",
|
||||
recommendedVersion: "0.129.0",
|
||||
ranges: [{ status: "broken", range: ">=0.130.0" }],
|
||||
},
|
||||
{
|
||||
t3CodeRange: ">=0.1.0",
|
||||
driver: codexDriver,
|
||||
recommendedRange: ">=0.130.0",
|
||||
recommendedVersion: "0.130.0",
|
||||
ranges: [{ status: "supported", range: ">=0.130.0" }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(
|
||||
ProviderCompatibility.createProviderCompatibilityAdvisory({
|
||||
driver: codexDriver,
|
||||
currentVersion: "0.130.0",
|
||||
document,
|
||||
t3CodeVersion: "0.0.22",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "broken",
|
||||
recommendedVersion: "0.129.0",
|
||||
});
|
||||
});
|
||||
|
||||
it("adds a targeted compatibility update command when a recommended version is available", () => {
|
||||
const document: ProviderCompatibility.ProviderCompatibilityDocument = {
|
||||
version: 1,
|
||||
policies: [
|
||||
{
|
||||
t3CodeRange: ">=0.0.0",
|
||||
driver: codexDriver,
|
||||
recommendedRange: ">=0.129.0",
|
||||
recommendedVersion: "0.129.0",
|
||||
ranges: [{ status: "broken", range: "<0.129.0" }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(
|
||||
ProviderCompatibility.createProviderCompatibilityAdvisory({
|
||||
driver: codexDriver,
|
||||
currentVersion: "0.128.0",
|
||||
document,
|
||||
maintenanceCapabilities: codexNpmUpdateCapabilities,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "broken",
|
||||
canUpdate: true,
|
||||
updateCommand: "npm install -g @openai/[email protected]",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not warn on disabled providers before their version has been probed", () => {
|
||||
const enriched = ProviderCompatibility.applyBundledProviderCompatibilityAdvisory({
|
||||
snapshot: {
|
||||
...baseProvider,
|
||||
driver: cursorDriver,
|
||||
enabled: false,
|
||||
version: null,
|
||||
status: "disabled",
|
||||
},
|
||||
driver: cursorDriver,
|
||||
currentVersion: null,
|
||||
});
|
||||
|
||||
expect(enriched.compatibilityAdvisory).toBeUndefined();
|
||||
expect(enriched.status).toBe("disabled");
|
||||
});
|
||||
|
||||
it("classifies the bundled compatibility policies for current T3 Code builds", () => {
|
||||
const document: ProviderCompatibility.ProviderCompatibilityDocument = {
|
||||
version: 1,
|
||||
policies: [
|
||||
{
|
||||
t3CodeRange: ">=0.0.0",
|
||||
driver: codexDriver,
|
||||
recommendedRange: ">=0.129.0",
|
||||
recommendedVersion: "0.129.0",
|
||||
ranges: [
|
||||
{ status: "supported", range: ">=0.129.0" },
|
||||
{ status: "broken", range: "<0.129.0" },
|
||||
],
|
||||
},
|
||||
{
|
||||
t3CodeRange: ">=0.0.0",
|
||||
driver: claudeDriver,
|
||||
recommendedRange: ">=0.2.111",
|
||||
recommendedVersion: "0.2.111",
|
||||
ranges: [{ status: "supported", range: ">=0.2.111" }],
|
||||
},
|
||||
{
|
||||
t3CodeRange: ">=0.0.0",
|
||||
driver: opencodeDriver,
|
||||
recommendedRange: ">=1.14.19",
|
||||
recommendedVersion: "1.14.19",
|
||||
ranges: [
|
||||
{ status: "supported", range: ">=1.14.19" },
|
||||
{ status: "broken", range: "<1.14.19" },
|
||||
],
|
||||
},
|
||||
{
|
||||
t3CodeRange: ">=0.0.0",
|
||||
driver: cursorDriver,
|
||||
recommendedRange: ">=2026.05.09",
|
||||
recommendedVersion: "2026.05.09",
|
||||
ranges: [
|
||||
{ status: "supported", range: ">=2026.05.09" },
|
||||
{ status: "unknown", range: "<2026.05.09" },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const classify = (driver: ProviderDriverKind, currentVersion: string) =>
|
||||
ProviderCompatibility.createProviderCompatibilityAdvisory({
|
||||
driver,
|
||||
currentVersion,
|
||||
document,
|
||||
t3CodeVersion: "0.0.22",
|
||||
})?.status;
|
||||
|
||||
expect(classify(codexDriver, "0.129.0")).toBe("supported");
|
||||
expect(classify(codexDriver, "0.128.0")).toBe("broken");
|
||||
expect(classify(claudeDriver, "0.2.111")).toBe("supported");
|
||||
expect(classify(opencodeDriver, "1.14.19")).toBe("supported");
|
||||
expect(classify(opencodeDriver, "1.14.18")).toBe("broken");
|
||||
expect(classify(cursorDriver, "2026.05.09")).toBe("supported");
|
||||
expect(classify(cursorDriver, "2026.05.09-0afadcc")).toBe("supported");
|
||||
expect(classify(cursorDriver, "2026.05.08")).toBe("unknown");
|
||||
});
|
||||
|
||||
it("matches T3 Code nightly versions against their base release policy", () => {
|
||||
const document: ProviderCompatibility.ProviderCompatibilityDocument = {
|
||||
version: 1,
|
||||
policies: [
|
||||
{
|
||||
t3CodeRange: ">=0.0.24",
|
||||
driver: codexDriver,
|
||||
recommendedRange: ">=0.129.0",
|
||||
recommendedVersion: "0.129.0",
|
||||
ranges: [{ status: "supported", range: ">=0.129.0" }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(
|
||||
ProviderCompatibility.createProviderCompatibilityAdvisory({
|
||||
driver: codexDriver,
|
||||
currentVersion: "0.129.0",
|
||||
document,
|
||||
t3CodeVersion: "0.0.24-nightly.20260513.1",
|
||||
})?.status,
|
||||
).toBe("supported");
|
||||
});
|
||||
|
||||
it.effect("enriches snapshots from the remote compatibility map when available", () => {
|
||||
const remoteDocument = {
|
||||
version: 1,
|
||||
policies: [
|
||||
{
|
||||
t3CodeRange: ">=0.0.0",
|
||||
driver: "codex",
|
||||
recommendedRange: "<0.130.0",
|
||||
recommendedVersion: "0.129.0",
|
||||
ranges: [{ status: "broken", range: ">=0.130.0" }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const enriched =
|
||||
yield* ProviderCompatibility.enrichProviderSnapshotWithTargetedCompatibilityAdvisory(
|
||||
baseProvider,
|
||||
codexNpmUpdateCapabilities,
|
||||
).pipe(provideCompatibility(() => ({ payload: remoteDocument })));
|
||||
|
||||
expect(enriched.status).toBe("error");
|
||||
expect(enriched.compatibilityAdvisory).toMatchObject({
|
||||
status: "broken",
|
||||
recommendedVersion: "0.129.0",
|
||||
canUpdate: true,
|
||||
updateCommand: "npm install -g @openai/[email protected]",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("caches remote compatibility documents within the service layer", () => {
|
||||
const remoteDocument = {
|
||||
version: 1,
|
||||
policies: [
|
||||
{
|
||||
t3CodeRange: ">=0.0.0",
|
||||
driver: "codex",
|
||||
recommendedRange: "<0.130.0",
|
||||
recommendedVersion: "0.129.0",
|
||||
ranges: [{ status: "broken", range: ">=0.130.0" }],
|
||||
},
|
||||
],
|
||||
};
|
||||
const requestedUrls: string[] = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* ProviderCompatibility.enrichProviderSnapshotWithCompatibilityAdvisory(baseProvider);
|
||||
yield* ProviderCompatibility.enrichProviderSnapshotWithCompatibilityAdvisory(baseProvider);
|
||||
|
||||
expect(requestedUrls).toEqual([ProviderCompatibility.DEFAULT_PROVIDER_COMPATIBILITY_MAP_URL]);
|
||||
}).pipe(
|
||||
provideCompatibility((url) => {
|
||||
requestedUrls.push(url);
|
||||
return { payload: remoteDocument };
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("falls back from the hosted map to the GitHub raw mirror", () => {
|
||||
const remoteDocument = {
|
||||
version: 1,
|
||||
policies: [
|
||||
{
|
||||
t3CodeRange: ">=0.0.0",
|
||||
driver: "codex",
|
||||
recommendedRange: "<0.130.0",
|
||||
recommendedVersion: "0.129.0",
|
||||
ranges: [{ status: "broken", range: ">=0.130.0" }],
|
||||
},
|
||||
],
|
||||
};
|
||||
const requestedUrls: string[] = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const enriched = yield* ProviderCompatibility.enrichProviderSnapshotWithCompatibilityAdvisory(
|
||||
baseProvider,
|
||||
).pipe(
|
||||
provideCompatibility((url) => {
|
||||
requestedUrls.push(url);
|
||||
return url === ProviderCompatibility.GITHUB_PROVIDER_COMPATIBILITY_MAP_URL
|
||||
? { payload: remoteDocument }
|
||||
: { payload: {}, status: 404 };
|
||||
}),
|
||||
);
|
||||
|
||||
expect(requestedUrls).toEqual([
|
||||
ProviderCompatibility.DEFAULT_PROVIDER_COMPATIBILITY_MAP_URL,
|
||||
ProviderCompatibility.GITHUB_PROVIDER_COMPATIBILITY_MAP_URL,
|
||||
]);
|
||||
expect(enriched.compatibilityAdvisory).toMatchObject({ status: "broken" });
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("falls back to default remote URLs when the env override parses empty", () => {
|
||||
const remoteDocument = {
|
||||
version: 1,
|
||||
policies: [
|
||||
{
|
||||
t3CodeRange: ">=0.0.0",
|
||||
driver: "codex",
|
||||
recommendedRange: "<0.130.0",
|
||||
recommendedVersion: "0.129.0",
|
||||
ranges: [{ status: "broken", range: ">=0.130.0" }],
|
||||
},
|
||||
],
|
||||
};
|
||||
const requestedUrls: string[] = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const previousOverride = process.env.T3_PROVIDER_COMPATIBILITY_MAP_URL;
|
||||
process.env.T3_PROVIDER_COMPATIBILITY_MAP_URL = " , ";
|
||||
const enriched = yield* ProviderCompatibility.enrichProviderSnapshotWithCompatibilityAdvisory(
|
||||
baseProvider,
|
||||
).pipe(
|
||||
provideCompatibility((url) => {
|
||||
requestedUrls.push(url);
|
||||
return url === ProviderCompatibility.DEFAULT_PROVIDER_COMPATIBILITY_MAP_URL
|
||||
? { payload: remoteDocument }
|
||||
: { payload: {}, status: 404 };
|
||||
}),
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
if (previousOverride === undefined) {
|
||||
delete process.env.T3_PROVIDER_COMPATIBILITY_MAP_URL;
|
||||
} else {
|
||||
process.env.T3_PROVIDER_COMPATIBILITY_MAP_URL = previousOverride;
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(requestedUrls).toEqual([ProviderCompatibility.DEFAULT_PROVIDER_COMPATIBILITY_MAP_URL]);
|
||||
expect(enriched.compatibilityAdvisory).toMatchObject({ status: "broken" });
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("lets the remote map relax a bundled compatibility error", () => {
|
||||
const bundledMessage =
|
||||
"This provider harness version 0.130.0 is known to be incompatible with this T3 Code release. Use 0.129.0.";
|
||||
const remoteDocument = {
|
||||
version: 1,
|
||||
policies: [
|
||||
{
|
||||
t3CodeRange: ">=0.0.0",
|
||||
driver: "codex",
|
||||
recommendedRange: ">=0.130.0",
|
||||
recommendedVersion: "0.130.0",
|
||||
ranges: [{ status: "supported", range: ">=0.130.0" }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const enriched = yield* ProviderCompatibility.enrichProviderSnapshotWithCompatibilityAdvisory(
|
||||
{
|
||||
...baseProvider,
|
||||
status: "error",
|
||||
message: bundledMessage,
|
||||
compatibilityAdvisory: {
|
||||
status: "broken",
|
||||
severity: "error",
|
||||
currentVersion: "0.130.0",
|
||||
message: bundledMessage,
|
||||
recommendedRange: "<0.130.0",
|
||||
recommendedVersion: "0.129.0",
|
||||
ranges: [{ status: "broken", range: ">=0.130.0" }],
|
||||
},
|
||||
},
|
||||
).pipe(provideCompatibility(() => ({ payload: remoteDocument })));
|
||||
|
||||
expect(enriched.status).toBe("ready");
|
||||
expect(enriched.message).toBeUndefined();
|
||||
expect(enriched.compatibilityAdvisory).toMatchObject({ status: "supported" });
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("falls back to the bundled map when the remote compatibility fetch fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const enriched = yield* ProviderCompatibility.enrichProviderSnapshotWithCompatibilityAdvisory(
|
||||
{
|
||||
...baseProvider,
|
||||
version: "0.128.0",
|
||||
},
|
||||
).pipe(provideCompatibility(() => ({ payload: {}, status: 404 })));
|
||||
|
||||
expect(enriched.status).toBe("error");
|
||||
expect(enriched.compatibilityAdvisory).toMatchObject({ status: "broken" });
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,413 @@
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
TrimmedNonEmptyString,
|
||||
type ServerProvider,
|
||||
type ServerProviderCompatibilityAdvisory,
|
||||
} from "@t3tools/contracts";
|
||||
import { satisfiesSemverRange } from "@t3tools/shared/semver";
|
||||
import * as Cache from "effect/Cache";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import bundledCompatibilityDocumentJson from "../../../../provider-compatibility.v1.json" with { type: "json" };
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import {
|
||||
makeTargetedProviderUpdateAction,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "./providerMaintenance.ts";
|
||||
|
||||
const T3_CODE_VERSION = packageJson.version;
|
||||
const REMOTE_COMPATIBILITY_CACHE_TTL = Duration.minutes(15);
|
||||
const REMOTE_COMPATIBILITY_TIMEOUT = "2500 millis";
|
||||
const REMOTE_COMPATIBILITY_CACHE_CAPACITY = 8;
|
||||
|
||||
export const DEFAULT_PROVIDER_COMPATIBILITY_MAP_URL =
|
||||
"https://t3.codes/provider-compatibility.v1.json";
|
||||
export const GITHUB_PROVIDER_COMPATIBILITY_MAP_URL =
|
||||
"https://raw.githubusercontent.com/pingdotgg/t3code/main/provider-compatibility.v1.json";
|
||||
export const DEFAULT_PROVIDER_COMPATIBILITY_MAP_URLS = [
|
||||
DEFAULT_PROVIDER_COMPATIBILITY_MAP_URL,
|
||||
GITHUB_PROVIDER_COMPATIBILITY_MAP_URL,
|
||||
] as const;
|
||||
|
||||
const RemoteCompatibilityRange = Schema.Struct({
|
||||
status: Schema.Literals(["unknown", "supported", "graceful", "unsupported", "broken"]),
|
||||
range: TrimmedNonEmptyString,
|
||||
label: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const RemoteCompatibilityPolicy = Schema.Struct({
|
||||
t3CodeRange: TrimmedNonEmptyString,
|
||||
driver: TrimmedNonEmptyString,
|
||||
recommendedRange: Schema.NullOr(TrimmedNonEmptyString),
|
||||
recommendedVersion: Schema.optionalKey(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
ranges: Schema.Array(RemoteCompatibilityRange),
|
||||
});
|
||||
|
||||
const RemoteCompatibilityDocument = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
policies: Schema.Array(RemoteCompatibilityPolicy),
|
||||
});
|
||||
|
||||
export type ProviderCompatibilityDocument = typeof RemoteCompatibilityDocument.Type;
|
||||
|
||||
type ProviderCompatibilitySnapshot = Pick<ServerProvider, "enabled" | "status" | "message"> & {
|
||||
readonly compatibilityAdvisory?: ServerProviderCompatibilityAdvisory | undefined;
|
||||
};
|
||||
|
||||
const decodeCompatibilityDocument = Schema.decodeUnknownEffect(RemoteCompatibilityDocument);
|
||||
|
||||
/**
|
||||
* Repo-root compatibility JSON bundled into the app. Used when the remote map
|
||||
* cannot be fetched or has no matching policy for the current provider/build.
|
||||
*/
|
||||
const bundledProviderCompatibilityDocument = Schema.decodeUnknownSync(RemoteCompatibilityDocument)(
|
||||
bundledCompatibilityDocumentJson,
|
||||
);
|
||||
|
||||
function remoteCompatibilityMapUrls(): ReadonlyArray<string> {
|
||||
const configured = process.env.T3_PROVIDER_COMPATIBILITY_MAP_URL?.trim();
|
||||
if (!configured) {
|
||||
return DEFAULT_PROVIDER_COMPATIBILITY_MAP_URLS;
|
||||
}
|
||||
const urls = configured
|
||||
.split(",")
|
||||
.map((url) => url.trim())
|
||||
.filter((url) => url.length > 0);
|
||||
return urls.length > 0 ? urls : DEFAULT_PROVIDER_COMPATIBILITY_MAP_URLS;
|
||||
}
|
||||
|
||||
function policyMatches(input: {
|
||||
readonly policy: typeof RemoteCompatibilityPolicy.Type;
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly t3CodeVersion: string;
|
||||
}): boolean {
|
||||
return (
|
||||
input.policy.driver === input.driver &&
|
||||
satisfiesSemverRange(input.t3CodeVersion, input.policy.t3CodeRange)
|
||||
);
|
||||
}
|
||||
|
||||
function compatibilityPolicyForDriver(input: {
|
||||
readonly document: typeof RemoteCompatibilityDocument.Type;
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly t3CodeVersion?: string;
|
||||
}): typeof RemoteCompatibilityPolicy.Type | null {
|
||||
const t3CodeVersion = input.t3CodeVersion ?? T3_CODE_VERSION;
|
||||
return (
|
||||
input.document.policies.find((policy) =>
|
||||
policyMatches({ policy, driver: input.driver, t3CodeVersion }),
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
function severityForStatus(
|
||||
status: ServerProviderCompatibilityAdvisory["status"],
|
||||
): ServerProviderCompatibilityAdvisory["severity"] {
|
||||
switch (status) {
|
||||
case "broken":
|
||||
return "error";
|
||||
case "unsupported":
|
||||
case "graceful":
|
||||
return "warning";
|
||||
case "supported":
|
||||
case "unknown":
|
||||
return "info";
|
||||
}
|
||||
}
|
||||
|
||||
function messageForStatus(input: {
|
||||
readonly status: ServerProviderCompatibilityAdvisory["status"];
|
||||
readonly currentVersion: string | null;
|
||||
readonly recommendedRange: string | null;
|
||||
readonly recommendedVersion: string | null;
|
||||
}) {
|
||||
const current = input.currentVersion ? ` ${input.currentVersion}` : "";
|
||||
const recommendedTarget = input.recommendedVersion ?? input.recommendedRange;
|
||||
const recommended = recommendedTarget ? ` Use ${recommendedTarget}.` : "";
|
||||
switch (input.status) {
|
||||
case "broken":
|
||||
return `This provider harness version${current} is known to be incompatible with this T3 Code release.${recommended}`;
|
||||
case "unsupported":
|
||||
return `This provider harness version${current} is outside the compatibility range for this T3 Code release.${recommended}`;
|
||||
case "graceful":
|
||||
return `This provider harness version${current} should still work, but updating is recommended.${recommended}`;
|
||||
case "unknown":
|
||||
return `T3 Code could not determine whether this provider harness version is compatible.${recommended}`;
|
||||
case "supported":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function createProviderCompatibilityAdvisoryFromDocument(input: {
|
||||
readonly document: typeof RemoteCompatibilityDocument.Type;
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly currentVersion: string | null;
|
||||
readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities | undefined;
|
||||
readonly t3CodeVersion?: string;
|
||||
}): ServerProviderCompatibilityAdvisory | undefined {
|
||||
const policy = compatibilityPolicyForDriver({
|
||||
document: input.document,
|
||||
driver: input.driver,
|
||||
...(input.t3CodeVersion ? { t3CodeVersion: input.t3CodeVersion } : {}),
|
||||
});
|
||||
if (!policy) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const currentVersion = input.currentVersion;
|
||||
const matchedRange =
|
||||
currentVersion === null
|
||||
? undefined
|
||||
: policy.ranges.find((range) => satisfiesSemverRange(currentVersion, range.range));
|
||||
const status = matchedRange?.status ?? (currentVersion === null ? "unknown" : "unsupported");
|
||||
const recommendedVersion = policy.recommendedVersion ?? null;
|
||||
const targetedUpdateAction = input.maintenanceCapabilities
|
||||
? makeTargetedProviderUpdateAction(input.maintenanceCapabilities, recommendedVersion)
|
||||
: null;
|
||||
|
||||
return {
|
||||
status,
|
||||
severity: severityForStatus(status),
|
||||
currentVersion: input.currentVersion,
|
||||
message: messageForStatus({
|
||||
status,
|
||||
currentVersion: input.currentVersion,
|
||||
recommendedRange: policy.recommendedRange,
|
||||
recommendedVersion,
|
||||
}),
|
||||
recommendedRange: policy.recommendedRange,
|
||||
recommendedVersion,
|
||||
updateCommand: targetedUpdateAction?.command ?? null,
|
||||
canUpdate: targetedUpdateAction !== null,
|
||||
ranges: [...policy.ranges],
|
||||
};
|
||||
}
|
||||
|
||||
function shouldSkipCompatibilityAdvisory(input: {
|
||||
readonly snapshot: ProviderCompatibilitySnapshot;
|
||||
readonly currentVersion: string | null;
|
||||
}): boolean {
|
||||
return !input.snapshot.enabled && input.currentVersion === null;
|
||||
}
|
||||
|
||||
export function createProviderCompatibilityAdvisory(input: {
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly currentVersion: string | null;
|
||||
readonly document?: typeof RemoteCompatibilityDocument.Type;
|
||||
readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities | undefined;
|
||||
readonly t3CodeVersion?: string;
|
||||
}): ServerProviderCompatibilityAdvisory | undefined {
|
||||
return createProviderCompatibilityAdvisoryFromDocument({
|
||||
document: input.document ?? bundledProviderCompatibilityDocument,
|
||||
driver: input.driver,
|
||||
currentVersion: input.currentVersion,
|
||||
maintenanceCapabilities: input.maintenanceCapabilities,
|
||||
...(input.t3CodeVersion ? { t3CodeVersion: input.t3CodeVersion } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const fetchRemoteCompatibilityDocument = Effect.fn("fetchRemoteCompatibilityDocument")(
|
||||
function* (url: string) {
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
const response = yield* client
|
||||
.execute(
|
||||
HttpClientRequest.get(url).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.setHeader("user-agent", `t3code/${T3_CODE_VERSION}`),
|
||||
),
|
||||
)
|
||||
.pipe(Effect.timeoutOption(REMOTE_COMPATIBILITY_TIMEOUT));
|
||||
|
||||
if (Option.isNone(response)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const httpResponse = response.value;
|
||||
if (httpResponse.status < 200 || httpResponse.status >= 300) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const payload = yield* httpResponse.json.pipe(
|
||||
Effect.flatMap(decodeCompatibilityDocument),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
return payload;
|
||||
},
|
||||
(effect, url) =>
|
||||
effect.pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logWarning("provider compatibility map fetch failed", {
|
||||
cause,
|
||||
url,
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
),
|
||||
);
|
||||
|
||||
export const resolveRemoteProviderCompatibilityDocument = Effect.fn(
|
||||
"resolveRemoteProviderCompatibilityDocument",
|
||||
)(function* () {
|
||||
const compatibility = yield* ProviderCompatibilityService;
|
||||
return yield* compatibility.resolveRemoteDocument;
|
||||
});
|
||||
|
||||
function applyCompatibilityAdvisory<Snapshot extends ProviderCompatibilitySnapshot>(
|
||||
snapshot: Snapshot,
|
||||
compatibilityAdvisory: ServerProviderCompatibilityAdvisory | undefined,
|
||||
): Snapshot {
|
||||
const baseSnapshot = removeExistingCompatibilityAdvisory(snapshot);
|
||||
if (!compatibilityAdvisory) {
|
||||
return baseSnapshot;
|
||||
}
|
||||
|
||||
const compatibilityMessage =
|
||||
compatibilityAdvisory.severity !== "info"
|
||||
? (compatibilityAdvisory.message ?? undefined)
|
||||
: undefined;
|
||||
const status =
|
||||
snapshot.enabled && compatibilityAdvisory.severity === "error"
|
||||
? "error"
|
||||
: snapshot.enabled &&
|
||||
compatibilityAdvisory.severity === "warning" &&
|
||||
baseSnapshot.status === "ready"
|
||||
? "warning"
|
||||
: baseSnapshot.status;
|
||||
|
||||
return {
|
||||
...baseSnapshot,
|
||||
status,
|
||||
...(compatibilityMessage || baseSnapshot.message
|
||||
? { message: compatibilityMessage ?? baseSnapshot.message }
|
||||
: {}),
|
||||
compatibilityAdvisory,
|
||||
} as Snapshot;
|
||||
}
|
||||
|
||||
function removeExistingCompatibilityAdvisory<Snapshot extends ProviderCompatibilitySnapshot>(
|
||||
snapshot: Snapshot,
|
||||
): Snapshot {
|
||||
if (!snapshot.compatibilityAdvisory) {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
const { compatibilityAdvisory: existingCompatibilityAdvisory, ...baseSnapshot } = snapshot;
|
||||
const compatibilityMessage =
|
||||
existingCompatibilityAdvisory.severity !== "info"
|
||||
? (existingCompatibilityAdvisory.message ?? undefined)
|
||||
: undefined;
|
||||
if (compatibilityMessage && baseSnapshot.message === compatibilityMessage) {
|
||||
const { message: _message, ...snapshotWithoutCompatibilityMessage } = baseSnapshot;
|
||||
return {
|
||||
...snapshotWithoutCompatibilityMessage,
|
||||
status: snapshot.enabled ? "ready" : "disabled",
|
||||
} as Snapshot;
|
||||
}
|
||||
return baseSnapshot as Snapshot;
|
||||
}
|
||||
|
||||
export function applyBundledProviderCompatibilityAdvisory<
|
||||
Snapshot extends ProviderCompatibilitySnapshot,
|
||||
>(input: {
|
||||
readonly snapshot: Snapshot;
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly currentVersion: string | null;
|
||||
readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities | undefined;
|
||||
}): Snapshot {
|
||||
if (
|
||||
shouldSkipCompatibilityAdvisory({
|
||||
snapshot: input.snapshot,
|
||||
currentVersion: input.currentVersion,
|
||||
})
|
||||
) {
|
||||
return removeExistingCompatibilityAdvisory(input.snapshot);
|
||||
}
|
||||
|
||||
return applyCompatibilityAdvisory(
|
||||
input.snapshot,
|
||||
createProviderCompatibilityAdvisory({
|
||||
driver: input.driver,
|
||||
currentVersion: input.currentVersion,
|
||||
maintenanceCapabilities: input.maintenanceCapabilities,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const enrichProviderSnapshotWithCompatibilityAdvisory = Effect.fn(
|
||||
"enrichProviderSnapshotWithCompatibilityAdvisory",
|
||||
)(function* (snapshot: ServerProvider) {
|
||||
const compatibility = yield* ProviderCompatibilityService;
|
||||
return yield* compatibility.enrichSnapshot(snapshot);
|
||||
});
|
||||
|
||||
export const enrichProviderSnapshotWithTargetedCompatibilityAdvisory = Effect.fn(
|
||||
"enrichProviderSnapshotWithTargetedCompatibilityAdvisory",
|
||||
)(function* (snapshot: ServerProvider, maintenanceCapabilities: ProviderMaintenanceCapabilities) {
|
||||
const compatibility = yield* ProviderCompatibilityService;
|
||||
return yield* compatibility.enrichSnapshot(snapshot, maintenanceCapabilities);
|
||||
});
|
||||
|
||||
export interface ProviderCompatibilityServiceShape {
|
||||
readonly resolveRemoteDocument: Effect.Effect<typeof RemoteCompatibilityDocument.Type | null>;
|
||||
readonly enrichSnapshot: (
|
||||
snapshot: ServerProvider,
|
||||
maintenanceCapabilities?: ProviderMaintenanceCapabilities | undefined,
|
||||
) => Effect.Effect<ServerProvider>;
|
||||
}
|
||||
|
||||
export class ProviderCompatibilityService extends Context.Service<
|
||||
ProviderCompatibilityService,
|
||||
ProviderCompatibilityServiceShape
|
||||
>()("t3/provider/ProviderCompatibilityService") {}
|
||||
|
||||
export const makeProviderCompatibilityService = Effect.fn("makeProviderCompatibilityService")(
|
||||
function* () {
|
||||
const remoteDocumentCache = yield* Cache.makeWith(fetchRemoteCompatibilityDocument, {
|
||||
capacity: REMOTE_COMPATIBILITY_CACHE_CAPACITY,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? REMOTE_COMPATIBILITY_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
|
||||
const resolveRemoteDocument = Effect.gen(function* () {
|
||||
for (const url of remoteCompatibilityMapUrls()) {
|
||||
const document = yield* Cache.get(remoteDocumentCache, url);
|
||||
if (document) {
|
||||
return document;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
return {
|
||||
resolveRemoteDocument,
|
||||
enrichSnapshot: (snapshot, maintenanceCapabilities) =>
|
||||
resolveRemoteDocument.pipe(
|
||||
Effect.map((remoteDocument) =>
|
||||
shouldSkipCompatibilityAdvisory({
|
||||
snapshot,
|
||||
currentVersion: snapshot.version,
|
||||
})
|
||||
? removeExistingCompatibilityAdvisory(snapshot)
|
||||
: applyCompatibilityAdvisory(
|
||||
snapshot,
|
||||
createProviderCompatibilityAdvisory({
|
||||
driver: snapshot.driver,
|
||||
currentVersion: snapshot.version,
|
||||
maintenanceCapabilities,
|
||||
...(remoteDocument ? { document: remoteDocument } : {}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
} satisfies ProviderCompatibilityServiceShape;
|
||||
},
|
||||
);
|
||||
|
||||
export const layer = Layer.effect(ProviderCompatibilityService, makeProviderCompatibilityService());
|
||||
@@ -1,22 +1,16 @@
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { makeManagedServerProvider } from "./makeManagedServerProvider.ts";
|
||||
|
||||
const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
const fastModeCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
{
|
||||
@@ -93,43 +87,6 @@ const refreshedSnapshotSecond: ServerProvider = {
|
||||
message: "Refreshed provider availability again.",
|
||||
};
|
||||
|
||||
function makeBackgroundPolicyLayer(shouldRunScopeWork: boolean) {
|
||||
return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(shouldRunScopeWork),
|
||||
shouldRunScopeWork: () => Effect.succeed(shouldRunScopeWork),
|
||||
shouldRunOpportunisticWork: Effect.succeed(shouldRunScopeWork),
|
||||
});
|
||||
}
|
||||
|
||||
const BackgroundPolicyAlwaysRunLayer = makeBackgroundPolicyLayer(true);
|
||||
const BackgroundPolicyNeverRunLayer = makeBackgroundPolicyLayer(false);
|
||||
const ServerSettingsTestLayer = ServerSettingsService.layerTest();
|
||||
const AlwaysRunTestLayer = Layer.merge(BackgroundPolicyAlwaysRunLayer, ServerSettingsTestLayer);
|
||||
const NeverRunTestLayer = Layer.merge(BackgroundPolicyNeverRunLayer, ServerSettingsTestLayer);
|
||||
|
||||
const enrichedSnapshotSecond: ServerProvider = {
|
||||
...refreshedSnapshotSecond,
|
||||
checkedAt: "2026-04-10T00:00:04.000Z",
|
||||
@@ -182,38 +139,7 @@ describe("makeManagedServerProvider", () => {
|
||||
assert.deepStrictEqual(latest, refreshedSnapshot);
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
}),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
);
|
||||
|
||||
it.effect("skips periodic provider refreshes without foreground provider-status demand", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const initialCheckDone = yield* Deferred.make<void>();
|
||||
yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
initialSnapshot: () => Effect.succeed(initialSnapshot),
|
||||
checkProvider: Ref.updateAndGet(checkCalls, (count) => count + 1).pipe(
|
||||
Effect.tap((count) =>
|
||||
count === 1
|
||||
? Deferred.succeed(initialCheckDone, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.as(refreshedSnapshot),
|
||||
),
|
||||
refreshInterval: "1 second",
|
||||
});
|
||||
|
||||
yield* Deferred.await(initialCheckDone);
|
||||
yield* TestClock.adjust("1 second");
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.mergeAll(NeverRunTestLayer, TestClock.layer()))),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reruns the provider check when streamed settings change", () =>
|
||||
@@ -258,7 +184,7 @@ describe("makeManagedServerProvider", () => {
|
||||
assert.deepStrictEqual(latest, refreshedSnapshotSecond);
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 2);
|
||||
}),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("streams supplemental snapshot updates after the base provider check completes", () =>
|
||||
@@ -296,7 +222,7 @@ describe("makeManagedServerProvider", () => {
|
||||
assert.deepStrictEqual(updates, [refreshedSnapshot, enrichedSnapshot]);
|
||||
assert.deepStrictEqual(latest, enrichedSnapshot);
|
||||
}),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores stale enrichment callbacks after a newer refresh advances generation", () =>
|
||||
@@ -357,6 +283,6 @@ describe("makeManagedServerProvider", () => {
|
||||
]);
|
||||
assert.deepStrictEqual(latest, enrichedSnapshotSecond);
|
||||
}),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,4 @@
|
||||
import {
|
||||
DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
|
||||
type ServerProvider,
|
||||
ServerSettingsError,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
@@ -14,9 +9,8 @@ import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
interface ProviderSnapshotState {
|
||||
readonly snapshot: ServerProvider;
|
||||
@@ -39,13 +33,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly refreshInterval?: Duration.Input;
|
||||
}): Effect.fn.Return<
|
||||
ServerProviderShape,
|
||||
ServerSettingsError,
|
||||
Scope.Scope | BackgroundPolicy.BackgroundPolicy | ServerSettingsService
|
||||
> {
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
const refreshSemaphore = yield* Semaphore.make(1);
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ServerProvider>(),
|
||||
@@ -146,45 +134,13 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
return yield* applySnapshot(nextSettings, { forceRefresh: true });
|
||||
});
|
||||
|
||||
const hasProviderStatusDemand = Effect.gen(function* () {
|
||||
const state = yield* Ref.get(snapshotStateRef);
|
||||
const instanceId = state.snapshot.instanceId;
|
||||
const [genericDemand, instanceDemand] = yield* Effect.all([
|
||||
backgroundPolicy.shouldRunScopeWork({ type: "provider-status" }),
|
||||
backgroundPolicy.shouldRunScopeWork({ type: "provider-status", instanceId }),
|
||||
]);
|
||||
return genericDemand || instanceDemand;
|
||||
});
|
||||
|
||||
const getRefreshInterval = input.refreshInterval
|
||||
? Effect.succeed(input.refreshInterval)
|
||||
: serverSettings.getSettings.pipe(
|
||||
Effect.map(
|
||||
(settings) =>
|
||||
resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
|
||||
Effect.asVoid(applySnapshot(nextSettings)),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.forever(
|
||||
getRefreshInterval.pipe(
|
||||
Effect.flatMap((refreshInterval) =>
|
||||
Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
|
||||
? Effect.sleep("60 seconds")
|
||||
: Effect.sleep(refreshInterval).pipe(
|
||||
Effect.flatMap(() =>
|
||||
hasProviderStatusDemand.pipe(
|
||||
Effect.flatMap((shouldRefresh) =>
|
||||
shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
|
||||
Effect.flatMap(() => refreshSnapshot()),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
makeTargetedProviderUpdateAction,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "./providerMaintenance.ts";
|
||||
@@ -132,6 +133,24 @@ describe("providerMaintenance", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("targets package install commands that omit an explicit latest suffix", () => {
|
||||
expect(
|
||||
makeTargetedProviderUpdateAction(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
updateExecutable: "vp",
|
||||
updateArgs: ["i", "-g", "@example/package-tool"],
|
||||
updateLockKey: "vite-plus-global",
|
||||
}),
|
||||
"1.2.3",
|
||||
),
|
||||
).toMatchObject({
|
||||
command: "vp i -g @example/[email protected]",
|
||||
args: ["i", "-g", "@example/[email protected]"],
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to vite-plus updates when the resolved binary lives in vite-plus global bin",
|
||||
() =>
|
||||
|
||||
@@ -108,6 +108,32 @@ export function makeManualOnlyProviderMaintenanceCapabilities(input: {
|
||||
});
|
||||
}
|
||||
|
||||
export function makeTargetedProviderUpdateAction(
|
||||
capabilities: ProviderMaintenanceCapabilities,
|
||||
targetVersion: string | null,
|
||||
): ProviderMaintenanceCommandAction | null {
|
||||
if (!capabilities.update || !capabilities.packageName || !targetVersion) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const versionedPackageArg = `${capabilities.packageName}@latest`;
|
||||
const targetPackageArg = `${capabilities.packageName}@${targetVersion}`;
|
||||
const packageArgIndex = capabilities.update.args.findIndex(
|
||||
(arg) => arg === versionedPackageArg || arg === capabilities.packageName,
|
||||
);
|
||||
if (packageArgIndex < 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const args = [...capabilities.update.args];
|
||||
args[packageArgIndex] = targetPackageArg;
|
||||
return {
|
||||
...capabilities.update,
|
||||
args,
|
||||
command: [capabilities.update.executable, ...args].join(" "),
|
||||
};
|
||||
}
|
||||
|
||||
function makeNpmGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
|
||||
@@ -288,6 +288,36 @@ describe("providerMaintenanceRunner", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("runs a targeted package update when a target version is supplied", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
yield* updater.updateProvider({
|
||||
provider: CODEX_DRIVER,
|
||||
targetVersion: "0.129.0",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "npm",
|
||||
args: ["install", "-g", "@openai/[email protected]"],
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"runs update commands through Effect ChildProcess when no test runner is injected",
|
||||
() => {
|
||||
|
||||
@@ -22,7 +22,10 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ProviderRegistry } from "./Services/ProviderRegistry.ts";
|
||||
import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
|
||||
import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makeTargetedProviderUpdateAction,
|
||||
} from "./providerMaintenance.ts";
|
||||
import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);
|
||||
@@ -46,6 +49,7 @@ export interface ProviderMaintenanceRunnerShape {
|
||||
| {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly instanceId?: ProviderInstanceId | undefined;
|
||||
readonly targetVersion?: string | undefined;
|
||||
},
|
||||
) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
|
||||
}
|
||||
@@ -283,12 +287,15 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
typeof target === "string"
|
||||
? defaultInstanceIdForDriver(provider)
|
||||
: (target.instanceId ?? defaultInstanceIdForDriver(provider));
|
||||
const targetVersion = typeof target === "string" ? undefined : target.targetVersion;
|
||||
const targetKey = `instance:${instanceId}`;
|
||||
const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
|
||||
instanceId,
|
||||
provider,
|
||||
);
|
||||
const update = capabilities.update;
|
||||
const update = targetVersion
|
||||
? makeTargetedProviderUpdateAction(capabilities, targetVersion)
|
||||
: capabilities.update;
|
||||
if (!update) {
|
||||
return yield* new ServerProviderUpdateError({
|
||||
provider,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { ProviderDriverKind, type ModelCapabilities } from "@t3tools/contracts";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import { providerModelsFromSettings } from "./providerSnapshot.ts";
|
||||
import { buildServerProvider, providerModelsFromSettings } from "./providerSnapshot.ts";
|
||||
|
||||
const OPENCODE_CUSTOM_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
@@ -42,3 +42,25 @@ describe("providerModelsFromSettings", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildServerProvider", () => {
|
||||
it("leaves compatibility unset when no bundled policy matches this T3 Code version", () => {
|
||||
const provider = buildServerProvider({
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
presentation: { displayName: "Codex" },
|
||||
enabled: true,
|
||||
checkedAt: "2026-04-10T00:00:00.000Z",
|
||||
models: [],
|
||||
probe: {
|
||||
installed: true,
|
||||
version: "0.128.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
},
|
||||
});
|
||||
|
||||
expect(provider.status).toBe("ready");
|
||||
expect(provider.compatibilityAdvisory).toBeUndefined();
|
||||
expect(provider.message).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { isWindowsCommandNotFound } from "../processRunner.ts";
|
||||
import * as ProviderCompatibility from "./ProviderCompatibility.ts";
|
||||
import { createProviderVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
@@ -208,7 +209,7 @@ export function buildServerProvider(input: {
|
||||
checkedAt: input.checkedAt,
|
||||
})
|
||||
: undefined;
|
||||
return {
|
||||
const snapshot: ServerProviderDraft = {
|
||||
displayName: input.presentation.displayName,
|
||||
...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
|
||||
...(typeof input.presentation.showInteractionModeToggle === "boolean"
|
||||
@@ -226,6 +227,13 @@ export function buildServerProvider(input: {
|
||||
skills: [...(input.skills ?? [])],
|
||||
...(versionAdvisory ? { versionAdvisory } : {}),
|
||||
};
|
||||
return input.driver
|
||||
? ProviderCompatibility.applyBundledProviderCompatibilityAdvisory({
|
||||
snapshot,
|
||||
driver: input.driver,
|
||||
currentVersion: input.probe.version,
|
||||
})
|
||||
: snapshot;
|
||||
}
|
||||
|
||||
export const collectStreamAsString = <E>(
|
||||
|
||||
@@ -53,7 +53,6 @@ import { vi } from "vitest";
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
|
||||
import type { ServerConfigShape } from "./config.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "./config.ts";
|
||||
import { makeRoutesLayer } from "./server.ts";
|
||||
@@ -116,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";
|
||||
|
||||
@@ -565,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: () =>
|
||||
@@ -693,36 +709,6 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.layers?.serverRuntimeStartup,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: false,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(false),
|
||||
shouldRunScopeWork: () => Effect.succeed(false),
|
||||
shouldRunOpportunisticWork: Effect.succeed(false),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ServerEnvironment)({
|
||||
getEnvironmentId: Effect.succeed(testEnvironmentDescriptor.environmentId),
|
||||
|
||||
@@ -3,8 +3,6 @@ import * as Layer from "effect/Layer";
|
||||
import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
|
||||
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
|
||||
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
|
||||
import {
|
||||
attachmentsRouteLayer,
|
||||
otlpTracesProxyRouteLayer,
|
||||
@@ -26,6 +24,7 @@ import { ProviderEventLoggersLive } from "./provider/Layers/ProviderEventLoggers
|
||||
import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts";
|
||||
import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";
|
||||
import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts";
|
||||
import * as ProviderCompatibility from "./provider/ProviderCompatibility.ts";
|
||||
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts";
|
||||
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts";
|
||||
import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
|
||||
@@ -78,6 +77,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 {
|
||||
@@ -104,11 +104,6 @@ const PtyAdapterLive = Layer.unwrap(
|
||||
}),
|
||||
);
|
||||
|
||||
const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
|
||||
Layer.provide(HostPowerMonitor.layer),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
);
|
||||
|
||||
const HttpServerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
@@ -249,7 +244,6 @@ const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
|
||||
|
||||
const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// Core Services
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
@@ -265,6 +259,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// `providerInstances` hydration merges `settings.providers.<kind>`
|
||||
// with explicit `providerInstances` entries on boot.
|
||||
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
|
||||
Layer.provideMerge(ProviderCompatibility.layer),
|
||||
// Shared native/canonical NDJSON writers used by both the per-instance
|
||||
// drivers (native stream, written from inside each `<X>Adapter`) and
|
||||
// `ProviderService` (canonical stream, written after event normalization).
|
||||
@@ -277,6 +272,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// no longer transitively provides it. Exposing it at the runtime level
|
||||
// keeps a single Live for all opencode consumers.
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(WorkspaceLayerLive),
|
||||
Layer.provideMerge(ProjectFaviconResolverLive),
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
@@ -286,8 +282,8 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
|
||||
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
|
||||
// Misc.
|
||||
Layer.provideMerge(BackgroundLayerLive),
|
||||
Layer.provideMerge(ProcessDiagnostics.layer),
|
||||
Layer.provideMerge(ProcessResourceMonitor.layer),
|
||||
Layer.provideMerge(TraceDiagnostics.layer),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ExternalLauncher.layer),
|
||||
|
||||
@@ -460,14 +460,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
backgroundActivity: {
|
||||
schemaVersion: 1,
|
||||
profile: "custom",
|
||||
baseProfile: "balanced",
|
||||
overrides: {
|
||||
automaticGitFetchInterval: 10_000,
|
||||
},
|
||||
},
|
||||
automaticGitFetchInterval: 10_000,
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
|
||||
@@ -135,17 +135,13 @@ export class ServerSettingsService extends Context.Service<
|
||||
Layer.effect(
|
||||
ServerSettingsService,
|
||||
Effect.gen(function* () {
|
||||
const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
|
||||
overrides;
|
||||
const { automaticGitFetchInterval, ...overridesForMerge } = overrides;
|
||||
const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
|
||||
const initialSettings = yield* normalizeServerSettings({
|
||||
...merged,
|
||||
...(automaticGitFetchInterval !== undefined
|
||||
? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
|
||||
: {}),
|
||||
...(providerHealthRefreshInterval !== undefined
|
||||
? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }
|
||||
: {}),
|
||||
});
|
||||
const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
|
||||
|
||||
@@ -219,9 +215,7 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
|
||||
|
||||
// Values under these keys are compared as a whole — never stripped field-by-field.
|
||||
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
|
||||
"backgroundActivity",
|
||||
"automaticGitFetchInterval",
|
||||
"providerHealthRefreshInterval",
|
||||
"textGenerationModelSelection",
|
||||
]);
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { assert, it, describe } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -12,7 +11,6 @@ import * as Path from "effect/Path";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import type {
|
||||
BackgroundScope,
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
@@ -20,11 +18,8 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
const baseLocalStatus: VcsStatusLocalResult = {
|
||||
isRepo: true,
|
||||
sourceControlProvider: {
|
||||
@@ -61,7 +56,6 @@ function makeTestLayer(state: {
|
||||
}) {
|
||||
return VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(makeBackgroundPolicyLayer(() => true)),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
@@ -87,37 +81,6 @@ function makeTestLayer(state: {
|
||||
);
|
||||
}
|
||||
|
||||
function makeBackgroundPolicyLayer(shouldRunScopeWork: (scope: BackgroundScope) => boolean) {
|
||||
return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: false,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(true),
|
||||
shouldRunScopeWork: (scope) => Effect.sync(() => shouldRunScopeWork(scope)),
|
||||
shouldRunOpportunisticWork: Effect.succeed(true),
|
||||
});
|
||||
}
|
||||
|
||||
describe("VcsStatusBroadcaster", () => {
|
||||
it.effect("reuses the cached VCS status across repeated reads", () => {
|
||||
const state = {
|
||||
@@ -233,7 +196,6 @@ describe("VcsStatusBroadcaster", () => {
|
||||
};
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(makeBackgroundPolicyLayer(() => true)),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: (input) =>
|
||||
@@ -348,55 +310,27 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("does not start automatic remote refreshes without foreground client demand", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(makeBackgroundPolicyLayer(() => false)),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
return state.currentRemoteStatus;
|
||||
}),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
} satisfies Partial<GitWorkflowService.GitWorkflowServiceShape>),
|
||||
),
|
||||
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,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
const snapshot = yield* Stream.runHead(
|
||||
broadcaster.streamStatus(
|
||||
{ cwd: "/repo" },
|
||||
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) },
|
||||
),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isSome(snapshot));
|
||||
assert.equal(state.remoteStatusCalls, 0);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
|
||||
@@ -412,7 +346,6 @@ describe("VcsStatusBroadcaster", () => {
|
||||
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(makeBackgroundPolicyLayer(() => true)),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
|
||||
@@ -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";
|
||||
@@ -20,10 +21,11 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
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;
|
||||
@@ -49,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,
|
||||
@@ -82,7 +98,6 @@ export const layer = Layer.effect(
|
||||
VcsStatusBroadcaster,
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<VcsStatusChange>(),
|
||||
@@ -243,41 +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) => {
|
||||
if (Duration.isZero(interval)) {
|
||||
return Effect.void;
|
||||
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 backgroundPolicy
|
||||
.shouldRunScopeWork({ type: "vcs-status", cwd })
|
||||
.pipe(
|
||||
Effect.flatMap((shouldRun) =>
|
||||
shouldRun ? refreshRemoteStatus(cwd).pipe(Effect.asVoid) : Effect.void,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const sleepForConfiguredInterval = automaticRemoteRefreshInterval.pipe(
|
||||
Effect.flatMap((interval) =>
|
||||
Effect.sleep(Duration.isZero(interval) ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL : interval),
|
||||
),
|
||||
);
|
||||
|
||||
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* (
|
||||
|
||||
@@ -28,13 +28,11 @@ import {
|
||||
ProjectWriteFileError,
|
||||
OrchestrationReplayEventsError,
|
||||
FilesystemBrowseError,
|
||||
RpcClientId,
|
||||
ThreadId,
|
||||
type TerminalEvent,
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
|
||||
import { clamp } from "effect/Number";
|
||||
import { HttpRouter, HttpServerRequest } from "effect/unstable/http";
|
||||
import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
|
||||
@@ -67,8 +65,8 @@ import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptR
|
||||
import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
|
||||
import * as BackgroundPolicy from "./background/BackgroundPolicy.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";
|
||||
@@ -183,12 +181,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
|
||||
const serverEnvironment = yield* ServerEnvironment;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const sourceControlDiscovery = yield* SourceControlDiscoveryLayer.SourceControlDiscovery;
|
||||
const automaticGitFetchInterval = serverSettings.getSettings.pipe(
|
||||
Effect.map(
|
||||
(settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval,
|
||||
),
|
||||
Effect.map((settings) => settings.automaticGitFetchInterval),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to read automatic Git fetch interval setting", {
|
||||
detail: cause.message,
|
||||
@@ -199,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()}`);
|
||||
|
||||
@@ -915,30 +911,18 @@ 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",
|
||||
}),
|
||||
[WS_METHODS.serverReportClientActivity]: (input, metadata) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverReportClientActivity,
|
||||
backgroundPolicy.reportClientActivity(
|
||||
currentSessionId,
|
||||
RpcClientId.make(metadata.client.id),
|
||||
input,
|
||||
),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverReportHostPowerState]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverReportHostPowerState,
|
||||
backgroundPolicy.reportHostPowerState(input),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverGetBackgroundPolicy]: (_input) =>
|
||||
observeRpcEffect(WS_METHODS.serverGetBackgroundPolicy, backgroundPolicy.snapshot, {
|
||||
"rpc.aggregate": "server",
|
||||
}),
|
||||
[WS_METHODS.sourceControlLookupRepository]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.sourceControlLookupRepository,
|
||||
@@ -1251,15 +1235,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
}),
|
||||
{ "rpc.aggregate": "auth" },
|
||||
),
|
||||
[WS_METHODS.subscribeBackgroundPolicy]: (_input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.subscribeBackgroundPolicy,
|
||||
Stream.concat(
|
||||
Stream.unwrap(Effect.map(backgroundPolicy.snapshot, Stream.make)),
|
||||
backgroundPolicy.streamChanges,
|
||||
),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -42,7 +42,7 @@ import { useGitStatus } from "~/lib/gitStatusState";
|
||||
import { usePrimaryEnvironmentId } from "../environments/primary";
|
||||
import { readEnvironmentApi } from "../environmentApi";
|
||||
import { isElectron } from "../env";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { ensureLocalApi, readLocalApi } from "../localApi";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import {
|
||||
collapseExpandedComposerCursor,
|
||||
@@ -104,7 +104,14 @@ import { BranchToolbar } from "./BranchToolbar";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
CircleAlertIcon,
|
||||
DownloadIcon,
|
||||
LoaderIcon,
|
||||
TriangleAlertIcon,
|
||||
WifiOffIcon,
|
||||
} from "lucide-react";
|
||||
import { cn, randomUUID } from "~/lib/utils";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
|
||||
@@ -150,7 +157,6 @@ import { ChatHeader } from "./chat/ChatHeader";
|
||||
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
|
||||
import { NoActiveThreadState } from "./NoActiveThreadState";
|
||||
import { resolveEffectiveEnvMode, resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
|
||||
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
|
||||
import {
|
||||
@@ -186,6 +192,11 @@ import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
|
||||
import { retainThreadDetailSubscription } from "../environments/runtime/service";
|
||||
import { RightPanelSheet } from "./RightPanelSheet";
|
||||
import { Button } from "./ui/button";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
|
||||
import {
|
||||
canRunProviderCompatibilityUpdate,
|
||||
getProviderCompatibilityUpdateCommand,
|
||||
} from "./settings/providerStatus";
|
||||
import {
|
||||
buildVersionMismatchDismissalKey,
|
||||
dismissVersionMismatch,
|
||||
@@ -200,6 +211,75 @@ const EMPTY_PROPOSED_PLANS: Thread["proposedPlans"] = [];
|
||||
const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
|
||||
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
|
||||
|
||||
function stripProviderCompatibilityInstallHint(message: string, recommendedVersion: string | null) {
|
||||
if (!recommendedVersion) {
|
||||
return message;
|
||||
}
|
||||
const escapedVersion = recommendedVersion.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
return message.replace(new RegExp(`\\s*Use\\s+${escapedVersion}\\.?\\s*$`, "i"), "").trim();
|
||||
}
|
||||
|
||||
function ProviderCompatibilityBannerAction({
|
||||
providerLabel,
|
||||
recommendedVersion,
|
||||
updateCommand,
|
||||
canRunUpdate,
|
||||
updating,
|
||||
onRunUpdate,
|
||||
}: {
|
||||
readonly providerLabel: string;
|
||||
readonly recommendedVersion: string;
|
||||
readonly updateCommand: string | null;
|
||||
readonly canRunUpdate: boolean;
|
||||
readonly updating: boolean;
|
||||
readonly onRunUpdate: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button type="button" size="xs" variant="outline">
|
||||
Install {recommendedVersion}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<PopoverPopup side="top" align="end" className="w-84">
|
||||
<div className="grid gap-3">
|
||||
<div className="grid gap-0.5">
|
||||
<p className="text-[13px] font-semibold leading-tight text-foreground">
|
||||
Install compatible {providerLabel}
|
||||
</p>
|
||||
<p className="text-xs leading-snug text-muted-foreground">
|
||||
Install provider harness version {recommendedVersion}.
|
||||
</p>
|
||||
</div>
|
||||
{canRunUpdate ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="default"
|
||||
className="w-full"
|
||||
disabled={updating}
|
||||
onClick={onRunUpdate}
|
||||
>
|
||||
{updating ? <LoaderIcon className="animate-spin" /> : <DownloadIcon />}
|
||||
{updating ? "Installing" : "Install now"}
|
||||
</Button>
|
||||
) : null}
|
||||
{updateCommand ? (
|
||||
<div className="rounded-md border border-border/70 bg-muted/40 px-2 py-1.5">
|
||||
<code className="block overflow-x-auto whitespace-nowrap font-mono text-[11px] text-foreground [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
{updateCommand}
|
||||
</code>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
type EnvironmentUnavailableState = {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
@@ -1150,6 +1230,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const [dismissedVersionMismatchKey, setDismissedVersionMismatchKey] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [compatibilityUpdatingProviderId, setCompatibilityUpdatingProviderId] =
|
||||
useState<ProviderInstanceId | null>(null);
|
||||
const versionMismatchDismissed =
|
||||
versionMismatchDismissKey === dismissedVersionMismatchKey ||
|
||||
isVersionMismatchDismissed(versionMismatchDismissKey);
|
||||
@@ -1178,8 +1260,112 @@ export default function ChatView(props: ChatViewProps) {
|
||||
savedEnvironmentRuntimeById,
|
||||
serverConfig?.environment.label,
|
||||
]);
|
||||
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
|
||||
const unlockedSelectedProvider = resolveSelectableProvider(
|
||||
providerStatuses,
|
||||
selectedProviderByThreadId ?? threadProvider ?? ProviderDriverKind.make("codex"),
|
||||
);
|
||||
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
|
||||
// Prefer an instance-id match so a custom Codex instance (e.g.
|
||||
// `codex_personal`) surfaces its own status/message in the banner rather
|
||||
// than the default Codex's. Falls back to first-match-by-kind when no
|
||||
// saved instance id is available or the instance no longer exists.
|
||||
const activeProviderInstanceId =
|
||||
composerActiveProvider ??
|
||||
activeThread?.session?.providerInstanceId ??
|
||||
activeThread?.modelSelection.instanceId ??
|
||||
activeProject?.defaultModelSelection?.instanceId ??
|
||||
null;
|
||||
const activeProviderStatus = useMemo(() => {
|
||||
if (activeProviderInstanceId) {
|
||||
return (
|
||||
providerStatuses.find((status) => status.instanceId === activeProviderInstanceId) ?? null
|
||||
);
|
||||
}
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(selectedProvider);
|
||||
return providerStatuses.find((status) => status.instanceId === defaultInstanceId) ?? null;
|
||||
}, [activeProviderInstanceId, providerStatuses, selectedProvider]);
|
||||
const runActiveProviderCompatibilityUpdate = useCallback(async () => {
|
||||
const provider = activeProviderStatus;
|
||||
const targetVersion = provider?.compatibilityAdvisory?.recommendedVersion ?? null;
|
||||
if (!provider || !targetVersion) {
|
||||
return;
|
||||
}
|
||||
|
||||
setCompatibilityUpdatingProviderId(provider.instanceId);
|
||||
try {
|
||||
await ensureLocalApi().server.updateProvider({
|
||||
provider: provider.driver,
|
||||
instanceId: provider.instanceId,
|
||||
targetVersion,
|
||||
});
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Could not update ${provider.displayName ?? provider.driver}`,
|
||||
description:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "The provider update command could not be started.",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setCompatibilityUpdatingProviderId((current) =>
|
||||
current === provider.instanceId ? null : current,
|
||||
);
|
||||
}
|
||||
}, [activeProviderStatus]);
|
||||
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const items: ComposerBannerStackItem[] = [];
|
||||
if (
|
||||
activeProviderStatus &&
|
||||
activeProviderStatus.status !== "ready" &&
|
||||
activeProviderStatus.status !== "disabled"
|
||||
) {
|
||||
const defaultMessage =
|
||||
activeProviderStatus.status === "error"
|
||||
? "Provider is unavailable."
|
||||
: "Provider needs attention.";
|
||||
const recommendedVersion =
|
||||
activeProviderStatus.compatibilityAdvisory?.recommendedVersion ?? null;
|
||||
const compatibilityUpdateCommand =
|
||||
getProviderCompatibilityUpdateCommand(activeProviderStatus);
|
||||
const canRunCompatibilityUpdate = canRunProviderCompatibilityUpdate(activeProviderStatus);
|
||||
const compatibilityUpdating =
|
||||
compatibilityUpdatingProviderId === activeProviderStatus.instanceId;
|
||||
const hasCompatibilityInstallAction =
|
||||
activeProviderStatus.compatibilityAdvisory?.status !== "supported" &&
|
||||
recommendedVersion !== null &&
|
||||
(canRunCompatibilityUpdate || compatibilityUpdateCommand !== null);
|
||||
const rawMessage = activeProviderStatus.message ?? defaultMessage;
|
||||
const message = hasCompatibilityInstallAction
|
||||
? stripProviderCompatibilityInstallHint(rawMessage, recommendedVersion)
|
||||
: rawMessage;
|
||||
const providerLabel = activeProviderStatus.displayName ?? activeProviderStatus.driver;
|
||||
items.push({
|
||||
id: `provider-status:${activeProviderStatus.instanceId}:${activeProviderStatus.status}`,
|
||||
variant: activeProviderStatus.status === "error" ? "error" : "warning",
|
||||
icon: <CircleAlertIcon />,
|
||||
title: `${providerLabel} provider status`,
|
||||
description: (
|
||||
<span className="line-clamp-3" title={message}>
|
||||
{message}
|
||||
</span>
|
||||
),
|
||||
actions:
|
||||
hasCompatibilityInstallAction && recommendedVersion ? (
|
||||
<ProviderCompatibilityBannerAction
|
||||
providerLabel={providerLabel}
|
||||
recommendedVersion={recommendedVersion}
|
||||
updateCommand={compatibilityUpdateCommand}
|
||||
canRunUpdate={canRunCompatibilityUpdate}
|
||||
updating={compatibilityUpdating}
|
||||
onRunUpdate={() => void runActiveProviderCompatibilityUpdate()}
|
||||
/>
|
||||
) : undefined,
|
||||
});
|
||||
}
|
||||
if (activeEnvironmentUnavailableState) {
|
||||
items.push({
|
||||
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
|
||||
@@ -1248,20 +1434,17 @@ export default function ChatView(props: ChatViewProps) {
|
||||
return items;
|
||||
}, [
|
||||
activeEnvironmentUnavailableState,
|
||||
activeProviderStatus,
|
||||
compatibilityUpdatingProviderId,
|
||||
handleReconnectActiveEnvironment,
|
||||
navigate,
|
||||
reconnectingEnvironmentId,
|
||||
runActiveProviderCompatibilityUpdate,
|
||||
showVersionMismatchBanner,
|
||||
versionMismatch,
|
||||
versionMismatchDismissKey,
|
||||
versionMismatchServerLabel,
|
||||
]);
|
||||
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
|
||||
const unlockedSelectedProvider = resolveSelectableProvider(
|
||||
providerStatuses,
|
||||
selectedProviderByThreadId ?? threadProvider ?? ProviderDriverKind.make("codex"),
|
||||
);
|
||||
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
|
||||
const workLogEntries = useMemo(
|
||||
@@ -1633,24 +1816,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const gitStatusQuery = useGitStatus({ environmentId, cwd: gitCwd });
|
||||
const keybindings = useServerKeybindings();
|
||||
const availableEditors = useServerAvailableEditors();
|
||||
// Prefer an instance-id match so a custom Codex instance (e.g.
|
||||
// `codex_personal`) surfaces its own status/message in the banner rather
|
||||
// than the default Codex's. Falls back to first-match-by-kind when no
|
||||
// saved instance id is available or the instance no longer exists.
|
||||
const activeProviderInstanceId =
|
||||
activeThread?.session?.providerInstanceId ??
|
||||
activeThread?.modelSelection.instanceId ??
|
||||
activeProject?.defaultModelSelection?.instanceId ??
|
||||
null;
|
||||
const activeProviderStatus = useMemo(() => {
|
||||
if (activeProviderInstanceId) {
|
||||
return (
|
||||
providerStatuses.find((status) => status.instanceId === activeProviderInstanceId) ?? null
|
||||
);
|
||||
}
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(selectedProvider);
|
||||
return providerStatuses.find((status) => status.instanceId === defaultInstanceId) ?? null;
|
||||
}, [activeProviderInstanceId, providerStatuses, selectedProvider]);
|
||||
const activeProjectCwd = activeProject?.cwd ?? null;
|
||||
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
|
||||
@@ -3540,8 +3705,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
/>
|
||||
</header>
|
||||
|
||||
{/* Error banner */}
|
||||
<ProviderStatusBanner status={activeProviderStatus} />
|
||||
<ThreadErrorBanner
|
||||
error={activeThread.error}
|
||||
onDismiss={() => setThreadError(activeThread.id, null)}
|
||||
@@ -3607,7 +3770,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>
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -21,6 +21,7 @@ interface ComposerPrimaryActionsProps {
|
||||
isSendBusy: boolean;
|
||||
isConnecting: boolean;
|
||||
isEnvironmentUnavailable: boolean;
|
||||
isProviderUnavailable: boolean;
|
||||
isPreparingWorktree: boolean;
|
||||
hasSendableContent: boolean;
|
||||
preserveComposerFocusOnPointerDown?: boolean;
|
||||
@@ -60,6 +61,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
isSendBusy,
|
||||
isConnecting,
|
||||
isEnvironmentUnavailable,
|
||||
isProviderUnavailable,
|
||||
isPreparingWorktree,
|
||||
hasSendableContent,
|
||||
preserveComposerFocusOnPointerDown = false,
|
||||
@@ -107,6 +109,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
{...pointerFocusProps}
|
||||
disabled={
|
||||
isEnvironmentUnavailable ||
|
||||
isProviderUnavailable ||
|
||||
pendingAction.isResponding ||
|
||||
(pendingAction.isLastQuestion ? !pendingAction.isComplete : !pendingAction.canAdvance)
|
||||
}
|
||||
@@ -146,7 +149,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
size="sm"
|
||||
className={cn("rounded-full", compact ? "h-9 px-3 sm:h-8" : "h-9 px-4 sm:h-8")}
|
||||
{...pointerFocusProps}
|
||||
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
|
||||
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || isProviderUnavailable}
|
||||
>
|
||||
{isConnecting || isSendBusy ? "Sending..." : "Refine"}
|
||||
</Button>
|
||||
@@ -160,7 +163,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
size="sm"
|
||||
className="h-9 rounded-l-full rounded-r-none px-4 sm:h-8"
|
||||
{...pointerFocusProps}
|
||||
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
|
||||
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || isProviderUnavailable}
|
||||
>
|
||||
{isConnecting || isSendBusy ? "Sending..." : "Implement"}
|
||||
</Button>
|
||||
@@ -173,7 +176,9 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
className="h-9 rounded-l-none rounded-r-full border-l-white/12 px-2 sm:h-8"
|
||||
aria-label="Implementation actions"
|
||||
{...pointerFocusProps}
|
||||
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
|
||||
disabled={
|
||||
isSendBusy || isConnecting || isEnvironmentUnavailable || isProviderUnavailable
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
@@ -181,7 +186,9 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end" side="top">
|
||||
<MenuItem
|
||||
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
|
||||
disabled={
|
||||
isSendBusy || isConnecting || isEnvironmentUnavailable || isProviderUnavailable
|
||||
}
|
||||
onClick={() => void onImplementPlanInNewThread()}
|
||||
>
|
||||
Implement in a new thread
|
||||
@@ -197,17 +204,25 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
type="submit"
|
||||
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:pointer-events-none disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
|
||||
{...pointerFocusProps}
|
||||
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || !hasSendableContent}
|
||||
disabled={
|
||||
isSendBusy ||
|
||||
isConnecting ||
|
||||
isEnvironmentUnavailable ||
|
||||
isProviderUnavailable ||
|
||||
!hasSendableContent
|
||||
}
|
||||
aria-label={
|
||||
isEnvironmentUnavailable
|
||||
? "Environment disconnected"
|
||||
: isConnecting
|
||||
? "Connecting"
|
||||
: isPreparingWorktree
|
||||
? "Preparing worktree"
|
||||
: isSendBusy
|
||||
? "Sending"
|
||||
: "Send message"
|
||||
isProviderUnavailable
|
||||
? "Provider unavailable"
|
||||
: isEnvironmentUnavailable
|
||||
? "Environment disconnected"
|
||||
: isConnecting
|
||||
? "Connecting"
|
||||
: isPreparingWorktree
|
||||
? "Preparing worktree"
|
||||
: isSendBusy
|
||||
? "Sending"
|
||||
: "Send message"
|
||||
}
|
||||
>
|
||||
{isConnecting || isSendBusy ? (
|
||||
|
||||
@@ -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 };
|
||||
});
|
||||
|
||||
@@ -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.
|
||||
@@ -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>
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import { type ServerProvider } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
|
||||
import { CircleAlertIcon } from "lucide-react";
|
||||
import { formatProviderDriverKindLabel } from "../../providerModels";
|
||||
|
||||
export const ProviderStatusBanner = memo(function ProviderStatusBanner({
|
||||
status,
|
||||
}: {
|
||||
status: ServerProvider | null;
|
||||
}) {
|
||||
if (!status || status.status === "ready" || status.status === "disabled") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const providerLabel = status.displayName?.trim() || formatProviderDriverKindLabel(status.driver);
|
||||
const defaultMessage =
|
||||
status.status === "error"
|
||||
? `${providerLabel} provider is unavailable.`
|
||||
: `${providerLabel} provider has limited availability.`;
|
||||
const title = `${providerLabel} provider status`;
|
||||
|
||||
return (
|
||||
<div className="pt-3 mx-auto max-w-3xl">
|
||||
<Alert variant={status.status === "error" ? "error" : "warning"}>
|
||||
<CircleAlertIcon />
|
||||
<AlertTitle>{title}</AlertTitle>
|
||||
<AlertDescription className="line-clamp-3" title={status.message ?? defaultMessage}>
|
||||
{status.message ?? defaultMessage}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
import { memo } from "react";
|
||||
import { Alert, AlertAction, AlertDescription } from "../ui/alert";
|
||||
import { CircleAlertIcon, XIcon } from "lucide-react";
|
||||
|
||||
import { Alert, AlertAction, AlertDescription } from "../ui/alert";
|
||||
|
||||
export const ThreadErrorBanner = memo(function ThreadErrorBanner({
|
||||
error,
|
||||
onDismiss,
|
||||
@@ -11,7 +12,7 @@ export const ThreadErrorBanner = memo(function ThreadErrorBanner({
|
||||
}) {
|
||||
if (!error) return null;
|
||||
return (
|
||||
<div className="pt-3 mx-auto max-w-3xl">
|
||||
<div className="mx-auto max-w-3xl pt-3">
|
||||
<Alert variant="error">
|
||||
<CircleAlertIcon />
|
||||
<AlertDescription className="line-clamp-3" title={error}>
|
||||
|
||||
@@ -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={
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
AlertTriangleIcon,
|
||||
ArrowUpCircleIcon,
|
||||
ChevronDownIcon,
|
||||
CopyIcon,
|
||||
@@ -29,6 +30,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";
|
||||
@@ -38,8 +40,10 @@ import { ProviderModelsSection } from "./ProviderModelsSection";
|
||||
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
|
||||
import { RedactedSensitiveText } from "./RedactedSensitiveText";
|
||||
import {
|
||||
getProviderCompatibilityUpdateCommand,
|
||||
getProviderVersionAdvisoryPresentation,
|
||||
PROVIDER_STATUS_STYLES,
|
||||
getProviderCompatibilityAdvisoryPresentation,
|
||||
getProviderSummary,
|
||||
getProviderVersionLabel,
|
||||
type ProviderStatusKey,
|
||||
@@ -55,6 +59,8 @@ const PROVIDER_ACCENT_SWATCHES = [
|
||||
] as const;
|
||||
|
||||
const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
||||
const ADVISORY_ICON_CLUSTER_CLASS = "-my-0.5 inline-flex h-5 shrink-0 items-center gap-2";
|
||||
const ADVISORY_ICON_SLOT_CLASS = "inline-flex size-5 shrink-0 items-center justify-center";
|
||||
|
||||
let environmentVariableDraftId = 0;
|
||||
const nextEnvironmentVariableDraftId = () => `provider-env-${environmentVariableDraftId++}`;
|
||||
@@ -420,6 +426,8 @@ interface ProviderInstanceCardProps {
|
||||
readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
|
||||
readonly onRunUpdate?: (() => void) | undefined;
|
||||
readonly isUpdating?: boolean | undefined;
|
||||
readonly onRunCompatibilityUpdate?: (() => void) | undefined;
|
||||
readonly isCompatibilityUpdating?: boolean | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -464,6 +472,8 @@ export function ProviderInstanceCard({
|
||||
onModelOrderChange,
|
||||
onRunUpdate,
|
||||
isUpdating = false,
|
||||
onRunCompatibilityUpdate,
|
||||
isCompatibilityUpdating = false,
|
||||
}: ProviderInstanceCardProps) {
|
||||
const enabled = instance.enabled ?? true;
|
||||
// The server-reported status wins when present; otherwise fall back to
|
||||
@@ -481,8 +491,13 @@ export function ProviderInstanceCard({
|
||||
: null;
|
||||
const summary = rawSummary;
|
||||
const versionLabel = getProviderVersionLabel(liveProvider?.version);
|
||||
const compatibilityAdvisory = getProviderCompatibilityAdvisoryPresentation(
|
||||
liveProvider?.compatibilityAdvisory,
|
||||
);
|
||||
const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
|
||||
const hasProviderAdvisoryIcons = compatibilityAdvisory !== null || versionAdvisory !== null;
|
||||
const updateCommand = versionAdvisory?.updateCommand ?? null;
|
||||
const compatibilityUpdateCommand = getProviderCompatibilityUpdateCommand(liveProvider);
|
||||
const FallbackIconComponent = driverOption?.icon;
|
||||
const displayName =
|
||||
instance.displayName?.trim() || driverOption?.label || String(instance.driver);
|
||||
@@ -676,95 +691,212 @@ export function ProviderInstanceCard({
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
{titleHeadNode}
|
||||
{versionCodeNode}
|
||||
{versionAdvisory ? (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"size-5 rounded-sm p-0",
|
||||
versionAdvisory.emphasis === "strong"
|
||||
? "text-warning hover:text-warning"
|
||||
: "text-primary hover:text-primary",
|
||||
)}
|
||||
aria-label="Update available — view details"
|
||||
>
|
||||
<ArrowUpCircleIcon className="size-3.5 [animation:bounce_2.4s_ease-in-out_infinite] motion-reduce:animate-none" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<PopoverPopup side="bottom" align="start" className="w-84">
|
||||
<div className="grid gap-3">
|
||||
<div className="grid gap-0.5">
|
||||
<p className="text-[13px] font-semibold leading-tight text-foreground">
|
||||
Update available
|
||||
</p>
|
||||
<p
|
||||
className={cn(
|
||||
"text-xs leading-snug",
|
||||
versionAdvisory.emphasis === "strong"
|
||||
? "text-warning"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
{versionCodeNode || hasProviderAdvisoryIcons ? (
|
||||
<span className={ADVISORY_ICON_CLUSTER_CLASS}>
|
||||
{versionCodeNode}
|
||||
{compatibilityAdvisory ? (
|
||||
<span className={ADVISORY_ICON_SLOT_CLASS}>
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"size-5 rounded-sm p-0",
|
||||
compatibilityAdvisory.emphasis === "strong"
|
||||
? "text-destructive hover:text-destructive"
|
||||
: "text-warning hover:text-warning",
|
||||
)}
|
||||
aria-label={`${compatibilityAdvisory.title} — view details`}
|
||||
>
|
||||
<AlertTriangleIcon className="size-3.5" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<PopoverPopup
|
||||
side="bottom"
|
||||
align="start"
|
||||
className="w-[min(21rem,calc(100vw-1.5rem))] [--popup-width:min(21rem,calc(100vw-1.5rem))]"
|
||||
>
|
||||
{versionAdvisory.detail}
|
||||
</p>
|
||||
</div>
|
||||
{onRunUpdate ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="default"
|
||||
className="w-full"
|
||||
disabled={isUpdating}
|
||||
onClick={onRunUpdate}
|
||||
<div className="grid min-w-0 gap-3">
|
||||
<div className="grid gap-0.5">
|
||||
<p className="text-[13px] font-semibold leading-tight text-foreground">
|
||||
{compatibilityAdvisory.title}
|
||||
</p>
|
||||
<p
|
||||
className={cn(
|
||||
"text-xs leading-snug",
|
||||
compatibilityAdvisory.emphasis === "strong"
|
||||
? "text-destructive"
|
||||
: "text-warning",
|
||||
)}
|
||||
>
|
||||
{compatibilityAdvisory.detail}
|
||||
</p>
|
||||
</div>
|
||||
{onRunCompatibilityUpdate ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="default"
|
||||
className="w-full"
|
||||
disabled={isCompatibilityUpdating}
|
||||
onClick={onRunCompatibilityUpdate}
|
||||
>
|
||||
{isCompatibilityUpdating ? (
|
||||
<LoaderIcon className="animate-spin" />
|
||||
) : (
|
||||
<DownloadIcon />
|
||||
)}
|
||||
{isCompatibilityUpdating ? "Updating" : "Update now"}
|
||||
</Button>
|
||||
) : null}
|
||||
{onRunCompatibilityUpdate && compatibilityUpdateCommand ? (
|
||||
<div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
|
||||
<span aria-hidden className="h-px flex-1 bg-border" />
|
||||
or, update manually using
|
||||
<span aria-hidden className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
) : null}
|
||||
{compatibilityUpdateCommand ? (
|
||||
<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">
|
||||
{compatibilityUpdateCommand}
|
||||
</code>
|
||||
</ScrollArea>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-6 shrink-0 rounded-sm p-0 text-muted-foreground hover:text-foreground"
|
||||
onClick={() =>
|
||||
copyToClipboard(compatibilityUpdateCommand, {
|
||||
providerName: displayName,
|
||||
})
|
||||
}
|
||||
aria-label="Copy compatibility update command"
|
||||
>
|
||||
<CopyIcon className="size-3" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Copy command</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
</span>
|
||||
) : null}
|
||||
{versionAdvisory ? (
|
||||
<span className={ADVISORY_ICON_SLOT_CLASS}>
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"size-5 rounded-sm p-0",
|
||||
versionAdvisory.emphasis === "strong"
|
||||
? "text-warning hover:text-warning"
|
||||
: "text-primary hover:text-primary",
|
||||
)}
|
||||
aria-label="Update available — view details"
|
||||
>
|
||||
<ArrowUpCircleIcon className="size-3.5 [animation:bounce_2.4s_ease-in-out_infinite] motion-reduce:animate-none" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<PopoverPopup
|
||||
side="bottom"
|
||||
align="start"
|
||||
className="w-[min(21rem,calc(100vw-1.5rem))] [--popup-width:min(21rem,calc(100vw-1.5rem))]"
|
||||
>
|
||||
{isUpdating ? <LoaderIcon className="animate-spin" /> : <DownloadIcon />}
|
||||
{isUpdating ? "Updating" : "Update now"}
|
||||
</Button>
|
||||
) : null}
|
||||
{onRunUpdate && updateCommand ? (
|
||||
<div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
|
||||
<span aria-hidden className="h-px flex-1 bg-border" />
|
||||
or, update manually using
|
||||
<span aria-hidden className="h-px flex-1 bg-border" />
|
||||
</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>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-6 shrink-0 rounded-sm p-0 text-muted-foreground hover:text-foreground"
|
||||
onClick={() =>
|
||||
copyToClipboard(updateCommand, {
|
||||
providerName: displayName,
|
||||
})
|
||||
}
|
||||
aria-label="Copy update command"
|
||||
>
|
||||
<CopyIcon className="size-3" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Copy command</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
<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
|
||||
</p>
|
||||
<p
|
||||
className={cn(
|
||||
"text-xs leading-snug",
|
||||
versionAdvisory.emphasis === "strong"
|
||||
? "text-warning"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{versionAdvisory.detail}
|
||||
</p>
|
||||
</div>
|
||||
{onRunUpdate ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="default"
|
||||
className="w-full"
|
||||
disabled={isUpdating}
|
||||
onClick={onRunUpdate}
|
||||
>
|
||||
{isUpdating ? (
|
||||
<LoaderIcon className="animate-spin" />
|
||||
) : (
|
||||
<DownloadIcon />
|
||||
)}
|
||||
{isUpdating ? "Updating" : "Update now"}
|
||||
</Button>
|
||||
) : null}
|
||||
{onRunUpdate && updateCommand ? (
|
||||
<div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
|
||||
<span aria-hidden className="h-px flex-1 bg-border" />
|
||||
or, update manually using
|
||||
<span aria-hidden className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
) : null}
|
||||
{updateCommand ? (
|
||||
<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={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-6 shrink-0 rounded-sm p-0 text-muted-foreground hover:text-foreground"
|
||||
onClick={() =>
|
||||
copyToClipboard(updateCommand, {
|
||||
providerName: displayName,
|
||||
})
|
||||
}
|
||||
aria-label="Copy update command"
|
||||
>
|
||||
<CopyIcon className="size-3" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Copy command</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
) : null}
|
||||
{titleTailNode}
|
||||
</div>
|
||||
|
||||
@@ -13,11 +13,11 @@ import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerConfig,
|
||||
type ServerProcessResourceHistoryResult,
|
||||
type ServerProvider,
|
||||
type SourceControlDiscoveryResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Option from "effect/Option";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -237,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),
|
||||
@@ -256,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,
|
||||
},
|
||||
};
|
||||
@@ -266,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;
|
||||
@@ -744,41 +761,6 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows advanced background activity controls when background intervals are customized", async () => {
|
||||
setServerConfigSnapshot({
|
||||
...createBaseServerConfig(),
|
||||
settings: {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
backgroundActivity: {
|
||||
schemaVersion: 1,
|
||||
profile: "custom",
|
||||
baseProfile: "balanced",
|
||||
overrides: {
|
||||
automaticGitFetchInterval: Duration.seconds(15),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
mounted = await renderWithTestRouter(
|
||||
<AppAtomRegistryProvider>
|
||||
<GeneralSettingsPanel />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
await expect.element(page.getByText("Advanced", { exact: true })).toBeInTheDocument();
|
||||
|
||||
await page.getByRole("button", { name: "Configure advanced background activity" }).click();
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Background Activity" });
|
||||
await expect.element(dialog).toBeInTheDocument();
|
||||
await expect.element(dialog.getByText("Shared policy")).toBeInTheDocument();
|
||||
await expect.element(dialog.getByText("Git fetch interval")).toBeInTheDocument();
|
||||
await expect.element(dialog.getByText("Provider health interval")).toBeInTheDocument();
|
||||
await expect.element(dialog.getByText("Host power monitor")).toBeInTheDocument();
|
||||
await expect.element(dialog.getByText("Idle host monitor")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("creates and shows a pairing link when network access is enabled", async () => {
|
||||
window.desktopBridge = createDesktopBridgeStub({
|
||||
serverExposureState: {
|
||||
@@ -1098,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"],
|
||||
@@ -1191,6 +1176,104 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
});
|
||||
});
|
||||
|
||||
it("runs targeted compatibility updates from the provider card", async () => {
|
||||
const updateProvider = vi.fn<LocalApi["server"]["updateProvider"]>().mockResolvedValue({
|
||||
providers: [],
|
||||
});
|
||||
window.nativeApi = {
|
||||
persistence: {
|
||||
getClientSettings: vi.fn().mockResolvedValue(null),
|
||||
setClientSettings: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
server: {
|
||||
updateProvider,
|
||||
},
|
||||
} as unknown as LocalApi;
|
||||
const incompatibleProvider: ServerProvider = {
|
||||
...createOutdatedProvider("codex"),
|
||||
version: "0.128.0",
|
||||
status: "error",
|
||||
message:
|
||||
"This provider harness version 0.128.0 is known to be incompatible with this T3 Code release. Use 0.129.0.",
|
||||
compatibilityAdvisory: {
|
||||
status: "broken",
|
||||
severity: "error",
|
||||
currentVersion: "0.128.0",
|
||||
message:
|
||||
"This provider harness version 0.128.0 is known to be incompatible with this T3 Code release. Use 0.129.0.",
|
||||
recommendedRange: ">=0.129.0",
|
||||
recommendedVersion: "0.129.0",
|
||||
ranges: [{ status: "broken", range: "<0.129.0" }],
|
||||
},
|
||||
};
|
||||
|
||||
setServerConfigSnapshot({
|
||||
...createBaseServerConfig(),
|
||||
providers: [incompatibleProvider],
|
||||
});
|
||||
|
||||
mounted = await render(
|
||||
<AppAtomRegistryProvider>
|
||||
<ProviderSettingsPanel />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
await page
|
||||
.getByRole("button", { name: "Incompatible provider version — view details" })
|
||||
.click();
|
||||
await expect
|
||||
.element(page.getByText("npm install -g @openai/[email protected]"))
|
||||
.toBeInTheDocument();
|
||||
await page.getByRole("button", { name: "Update now" }).click();
|
||||
|
||||
expect(updateProvider).toHaveBeenCalledWith({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
targetVersion: "0.129.0",
|
||||
});
|
||||
});
|
||||
|
||||
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", () => {
|
||||
|
||||
@@ -1,32 +1,19 @@
|
||||
import {
|
||||
ArchiveIcon,
|
||||
ArchiveX,
|
||||
LoaderIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
SettingsIcon,
|
||||
} from "lucide-react";
|
||||
import { ArchiveIcon, ArchiveX, LoaderIcon, PlusIcon, RefreshCwIcon } from "lucide-react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
type BackgroundActivityProfile,
|
||||
type BackgroundActivitySettings,
|
||||
type DesktopUpdateChannel,
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceConfig,
|
||||
type ProviderInstanceId,
|
||||
type ScopedThreadRef,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import {
|
||||
getBackgroundActivityBaseProfile,
|
||||
getBackgroundActivityPresetSettings,
|
||||
resolveServerBackgroundActivitySettings,
|
||||
} from "@t3tools/shared/backgroundActivitySettings";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Equal from "effect/Equal";
|
||||
@@ -63,23 +50,7 @@ import { selectProjectsAcrossEnvironments, useStore } from "../../store";
|
||||
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
|
||||
import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
import { DraftInput } from "../ui/draft-input";
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldDecrement,
|
||||
NumberFieldGroup,
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
} from "../ui/number-field";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
@@ -93,6 +64,10 @@ import {
|
||||
type ProviderUpdateCandidate,
|
||||
} from "../ProviderUpdateLaunchNotification.logic";
|
||||
import { ProviderInstanceCard } from "./ProviderInstanceCard";
|
||||
import {
|
||||
canRunProviderCompatibilityUpdate,
|
||||
getProviderCompatibilityUpdateCommand,
|
||||
} from "./providerStatus";
|
||||
import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
|
||||
import {
|
||||
buildProviderInstanceUpdatePatch,
|
||||
@@ -105,12 +80,6 @@ import {
|
||||
SettingsSection,
|
||||
useRelativeTimeTick,
|
||||
} from "./settingsLayout";
|
||||
import {
|
||||
BackgroundPolicyTooltip as PolicyTooltip,
|
||||
backgroundActivityOverrideSettings,
|
||||
durationToSeconds,
|
||||
normalizeIntervalSeconds,
|
||||
} from "./backgroundActivityUtils";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
import { useServerObservability, useServerProviders } from "../../rpc/serverState";
|
||||
|
||||
@@ -135,68 +104,7 @@ const TIMESTAMP_FORMAT_LABELS = {
|
||||
"24-hour": "24-hour",
|
||||
} as const;
|
||||
|
||||
const BACKGROUND_ACTIVITY_PROFILE_LABELS: Record<BackgroundActivityProfile, string> = {
|
||||
balanced: "Balanced",
|
||||
performance: "Performance",
|
||||
"battery-saver": "Battery saver",
|
||||
};
|
||||
|
||||
type BackgroundActivityProfileOption = BackgroundActivityProfile | "advanced";
|
||||
|
||||
const BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS: Record<BackgroundActivityProfileOption, string> = {
|
||||
...BACKGROUND_ACTIVITY_PROFILE_LABELS,
|
||||
advanced: "Advanced",
|
||||
};
|
||||
|
||||
const BACKGROUND_ACTIVITY_PROFILE_DESCRIPTIONS: Record<BackgroundActivityProfile, string> = {
|
||||
balanced:
|
||||
"Pauses background probes when clients are idle, the host is locked, or low power mode is active.",
|
||||
performance: "Allows scoped background probes while any subscribed client remains connected.",
|
||||
"battery-saver": "Also pauses background probes when the host or client is on battery.",
|
||||
};
|
||||
|
||||
const ADVANCED_BACKGROUND_ACTIVITY_DESCRIPTION =
|
||||
"Uses custom background intervals with the selected shared power policy.";
|
||||
|
||||
const PROVIDER_HEALTH_INTERVAL_STEP_SECONDS = 30;
|
||||
const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const BACKGROUND_ACTIVITY_BOOLEAN_OVERRIDES: ReadonlyArray<{
|
||||
readonly key:
|
||||
| "pauseWhenHostLocked"
|
||||
| "pauseWhenHostLowPower"
|
||||
| "pauseWhenClientLowPower"
|
||||
| "pauseWhenOnBattery";
|
||||
readonly label: string;
|
||||
}> = [
|
||||
{ key: "pauseWhenHostLocked", label: "Pause when host is locked" },
|
||||
{ key: "pauseWhenHostLowPower", label: "Pause on host low power" },
|
||||
{ key: "pauseWhenClientLowPower", label: "Pause on client low power" },
|
||||
{ key: "pauseWhenOnBattery", label: "Pause on battery" },
|
||||
];
|
||||
|
||||
function resolveBackgroundActivityProfileOption(settings: {
|
||||
readonly backgroundActivity: BackgroundActivitySettings;
|
||||
}): BackgroundActivityProfileOption {
|
||||
return settings.backgroundActivity.profile === "custom"
|
||||
? "advanced"
|
||||
: settings.backgroundActivity.profile;
|
||||
}
|
||||
|
||||
function resetBackgroundActivitySettings() {
|
||||
return {
|
||||
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
|
||||
};
|
||||
}
|
||||
|
||||
function backgroundActivityProfileSettings(profile: BackgroundActivityProfile) {
|
||||
return {
|
||||
backgroundActivity: {
|
||||
schemaVersion: 1 as const,
|
||||
profile,
|
||||
overrides: {},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function withoutProviderInstanceKey<V>(
|
||||
record: Readonly<Record<ProviderInstanceId, V>> | undefined,
|
||||
@@ -505,8 +413,9 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming
|
||||
? ["Assistant output"]
|
||||
: []),
|
||||
...(!Equal.equals(settings.backgroundActivity, DEFAULT_UNIFIED_SETTINGS.backgroundActivity)
|
||||
? ["Background activity"]
|
||||
...(Duration.toMillis(settings.automaticGitFetchInterval) !==
|
||||
Duration.toMillis(DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval)
|
||||
? ["Automatic Git fetch interval"]
|
||||
: []),
|
||||
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
|
||||
? ["New thread mode"]
|
||||
@@ -531,7 +440,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.diffIgnoreWhitespace,
|
||||
settings.diffWordWrap,
|
||||
settings.backgroundActivity,
|
||||
settings.automaticGitFetchInterval,
|
||||
settings.enableAssistantStreaming,
|
||||
settings.sidebarThreadPreviewCount,
|
||||
settings.timestampFormat,
|
||||
@@ -557,7 +466,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
|
||||
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
|
||||
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
|
||||
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
|
||||
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
|
||||
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
|
||||
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
|
||||
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
|
||||
@@ -573,255 +482,10 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
};
|
||||
}
|
||||
|
||||
function BackgroundActivityAdvancedDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
readonly open: boolean;
|
||||
readonly onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
|
||||
const activeProfile = getBackgroundActivityBaseProfile(settings.backgroundActivity);
|
||||
const automaticGitFetchIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.automaticGitFetchInterval,
|
||||
);
|
||||
const providerHealthRefreshIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.providerHealthRefreshInterval,
|
||||
);
|
||||
const hostPowerMonitorActiveIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.hostPowerMonitorActiveInterval,
|
||||
);
|
||||
const hostPowerMonitorIdleIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.hostPowerMonitorIdleInterval,
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Background Activity</DialogTitle>
|
||||
<DialogDescription>
|
||||
Tune the shared power policy and the background intervals that feed it.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-0 px-6 pb-5">
|
||||
<div className="overflow-hidden rounded-xl border bg-card text-card-foreground">
|
||||
<div className="flex flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="text-sm font-medium">Shared policy</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
Controls whether background work may run after a subscribed interval fires.
|
||||
</p>
|
||||
</div>
|
||||
<Select
|
||||
value={activeProfile}
|
||||
onValueChange={(value) => {
|
||||
if (
|
||||
value === "balanced" ||
|
||||
value === "performance" ||
|
||||
value === "battery-saver"
|
||||
) {
|
||||
updateSettings(backgroundActivityProfileSettings(value));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-40" aria-label="Shared background policy">
|
||||
<SelectValue>{BACKGROUND_ACTIVITY_PROFILE_LABELS[activeProfile]}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
<SelectItem hideIndicator value="balanced">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS.balanced}
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="performance">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS.performance}
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="battery-saver">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS["battery-saver"]}
|
||||
</SelectItem>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="text-sm font-medium">Git fetch interval</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
Refresh remote branch status in the background.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<NumberField
|
||||
value={automaticGitFetchIntervalSeconds}
|
||||
min={0}
|
||||
step={5}
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
automaticGitFetchInterval: Duration.seconds(
|
||||
normalizeIntervalSeconds(value),
|
||||
),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement aria-label="Decrease Git fetch interval" />
|
||||
<NumberFieldInput aria-label="Git fetch interval in seconds" />
|
||||
<NumberFieldIncrement aria-label="Increase Git fetch interval" />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
<span className="text-xs text-muted-foreground">seconds</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="text-sm font-medium">Provider health interval</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
Refresh provider availability, versions, auth state, and model metadata.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<NumberField
|
||||
value={providerHealthRefreshIntervalSeconds}
|
||||
min={0}
|
||||
step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
providerHealthRefreshInterval: Duration.seconds(
|
||||
normalizeIntervalSeconds(value),
|
||||
),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement aria-label="Decrease provider health interval" />
|
||||
<NumberFieldInput aria-label="Provider health interval in seconds" />
|
||||
<NumberFieldIncrement aria-label="Increase provider health interval" />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
<span className="text-xs text-muted-foreground">seconds</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="text-sm font-medium">Host power monitor</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
Poll host power state while clients are active.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<NumberField
|
||||
value={hostPowerMonitorActiveIntervalSeconds}
|
||||
min={5}
|
||||
step={5}
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
hostPowerMonitorActiveInterval: Duration.seconds(
|
||||
normalizeIntervalSeconds(value),
|
||||
),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement aria-label="Decrease active host power interval" />
|
||||
<NumberFieldInput aria-label="Active host power interval in seconds" />
|
||||
<NumberFieldIncrement aria-label="Increase active host power interval" />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
<span className="text-xs text-muted-foreground">seconds</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="text-sm font-medium">Idle host monitor</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
Poll host power state when no foreground client is active.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<NumberField
|
||||
value={hostPowerMonitorIdleIntervalSeconds}
|
||||
min={5}
|
||||
step={30}
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
hostPowerMonitorIdleInterval: Duration.seconds(
|
||||
normalizeIntervalSeconds(value),
|
||||
),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement aria-label="Decrease idle host power interval" />
|
||||
<NumberFieldInput aria-label="Idle host power interval in seconds" />
|
||||
<NumberFieldIncrement aria-label="Increase idle host power interval" />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
<span className="text-xs text-muted-foreground">seconds</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-0 border-t sm:grid-cols-2">
|
||||
{BACKGROUND_ACTIVITY_BOOLEAN_OVERRIDES.map(({ key, label }) => (
|
||||
<label
|
||||
key={key}
|
||||
className="flex items-center justify-between gap-3 border-b px-4 py-3 last:border-b-0 sm:border-r sm:even:border-r-0"
|
||||
>
|
||||
<span className="text-sm font-medium">{label}</span>
|
||||
<Switch
|
||||
checked={resolvedBackgroundActivity[key]}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
[key]: Boolean(checked),
|
||||
}),
|
||||
)
|
||||
}
|
||||
aria-label={label}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</DialogPanel>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => updateSettings(resetBackgroundActivitySettings())}
|
||||
>
|
||||
Reset all
|
||||
</Button>
|
||||
<Button onClick={() => onOpenChange(false)}>Done</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function GeneralSettingsPanel() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const [backgroundActivityDialogOpen, setBackgroundActivityDialogOpen] = useState(false);
|
||||
const observability = useServerObservability();
|
||||
const serverProviders = useServerProviders();
|
||||
const diagnosticsDescription = formatDiagnosticsDescription({
|
||||
@@ -854,21 +518,6 @@ export function GeneralSettingsPanel() {
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
|
||||
const activeBackgroundActivityProfile = getBackgroundActivityBaseProfile(
|
||||
settings.backgroundActivity,
|
||||
);
|
||||
const backgroundActivityProfileOption = resolveBackgroundActivityProfileOption(settings);
|
||||
const backgroundActivityDescription =
|
||||
backgroundActivityProfileOption === "advanced"
|
||||
? `${ADVANCED_BACKGROUND_ACTIVITY_DESCRIPTION} Current shared policy: ${
|
||||
BACKGROUND_ACTIVITY_PROFILE_LABELS[activeBackgroundActivityProfile]
|
||||
}.`
|
||||
: BACKGROUND_ACTIVITY_PROFILE_DESCRIPTIONS[resolvedBackgroundActivity.profile];
|
||||
const canResetBackgroundActivity = !Equal.equals(
|
||||
settings.backgroundActivity,
|
||||
DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
@@ -1025,88 +674,6 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title={
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
Background activity
|
||||
<PolicyTooltip>
|
||||
This shared policy gates background work such as Git refreshes and provider health
|
||||
probes after their individual intervals elapse.
|
||||
</PolicyTooltip>
|
||||
</span>
|
||||
}
|
||||
description={backgroundActivityDescription}
|
||||
resetAction={
|
||||
canResetBackgroundActivity ? (
|
||||
<SettingResetButton
|
||||
label="background activity"
|
||||
onClick={() => updateSettings(resetBackgroundActivitySettings())}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<>
|
||||
<Select
|
||||
value={backgroundActivityProfileOption}
|
||||
onValueChange={(value) => {
|
||||
if (value === "advanced") {
|
||||
setBackgroundActivityDialogOpen(true);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
value === "balanced" ||
|
||||
value === "performance" ||
|
||||
value === "battery-saver"
|
||||
) {
|
||||
updateSettings(backgroundActivityProfileSettings(value));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-40" aria-label="Background activity profile">
|
||||
<SelectValue>
|
||||
{BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS[backgroundActivityProfileOption]}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
<SelectItem hideIndicator value="balanced">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS.balanced}
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="performance">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS.performance}
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="battery-saver">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS["battery-saver"]}
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="advanced">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS.advanced}
|
||||
</SelectItem>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
{backgroundActivityProfileOption === "advanced" ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="outline"
|
||||
aria-label="Configure advanced background activity"
|
||||
onClick={() => setBackgroundActivityDialogOpen(true)}
|
||||
>
|
||||
<SettingsIcon className="size-4" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Configure background activity</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<BackgroundActivityAdvancedDialog
|
||||
open={backgroundActivityDialogOpen}
|
||||
onOpenChange={setBackgroundActivityDialogOpen}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Auto-open task panel"
|
||||
description="Open the right-side plan and task panel automatically when steps appear."
|
||||
@@ -1382,14 +949,6 @@ export function ProviderSettingsPanel() {
|
||||
);
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
|
||||
const providerHealthPreset = getBackgroundActivityPresetSettings(
|
||||
getBackgroundActivityBaseProfile(settings.backgroundActivity),
|
||||
).providerHealthRefreshInterval;
|
||||
const providerHealthRefreshIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.providerHealthRefreshInterval,
|
||||
);
|
||||
const defaultProviderHealthRefreshIntervalSeconds = durationToSeconds(providerHealthPreset);
|
||||
const lastCheckedAt =
|
||||
serverProviders.length > 0
|
||||
? serverProviders.reduce(
|
||||
@@ -1456,6 +1015,55 @@ export function ProviderSettingsPanel() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const runProviderCompatibilityUpdate = useCallback(async (provider: ServerProvider) => {
|
||||
const targetVersion = provider.compatibilityAdvisory?.recommendedVersion ?? null;
|
||||
if (!targetVersion) {
|
||||
return;
|
||||
}
|
||||
|
||||
let started = false;
|
||||
setUpdatingProviderDrivers((previous) => {
|
||||
if (previous.has(provider.driver)) {
|
||||
return previous;
|
||||
}
|
||||
started = true;
|
||||
const next = new Set(previous);
|
||||
next.add(provider.driver);
|
||||
return next;
|
||||
});
|
||||
if (!started) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureLocalApi().server.updateProvider({
|
||||
provider: provider.driver,
|
||||
instanceId: provider.instanceId,
|
||||
targetVersion,
|
||||
});
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Could not update ${PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver}`,
|
||||
description:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "The provider update command could not be started.",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setUpdatingProviderDrivers((previous) => {
|
||||
if (!previous.has(provider.driver)) {
|
||||
return previous;
|
||||
}
|
||||
const next = new Set(previous);
|
||||
next.delete(provider.driver);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
interface InstanceRow {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly instance: ProviderInstanceConfig;
|
||||
@@ -1669,61 +1277,6 @@ export function ProviderSettingsPanel() {
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<SettingsRow
|
||||
title={
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
Health check interval
|
||||
<PolicyTooltip>
|
||||
This interval is configured here, then the shared Background activity policy decides
|
||||
whether provider probes may run when the timer fires. Custom intervals appear as
|
||||
Advanced in General settings.
|
||||
</PolicyTooltip>
|
||||
</span>
|
||||
}
|
||||
description="Refresh provider availability, versions, auth state, and model metadata in the background. Set this to 0 seconds to rely on manual refreshes."
|
||||
resetAction={
|
||||
providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
|
||||
<SettingResetButton
|
||||
label="provider health check interval"
|
||||
onClick={() =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
providerHealthRefreshInterval: undefined,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<NumberField
|
||||
value={providerHealthRefreshIntervalSeconds}
|
||||
min={0}
|
||||
step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
providerHealthRefreshInterval: Duration.seconds(
|
||||
normalizeIntervalSeconds(value),
|
||||
),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement aria-label="Decrease provider health check interval" />
|
||||
<NumberFieldInput aria-label="Provider health check interval in seconds" />
|
||||
<NumberFieldIncrement aria-label="Increase provider health check interval" />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
<span className="text-xs text-muted-foreground">seconds</span>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
{rows.map((row) => {
|
||||
const driverOption = getDriverOption(row.driver);
|
||||
const liveProvider = serverProviders.find(
|
||||
@@ -1746,6 +1299,22 @@ export function ProviderSettingsPanel() {
|
||||
updateCandidate !== undefined &&
|
||||
canOneClickUpdateProviderCandidate(updateCandidate, serverProviders) &&
|
||||
!updatingProviderDrivers.has(updateCandidate.driver);
|
||||
const compatibilityUpdateCommand = getProviderCompatibilityUpdateCommand(liveProvider);
|
||||
const showInlineCompatibilityUpdateButton =
|
||||
canRunProviderCompatibilityUpdate(liveProvider) &&
|
||||
compatibilityUpdateCommand !== null &&
|
||||
Boolean(liveProvider?.compatibilityAdvisory?.recommendedVersion);
|
||||
const isCompatibilityUpdateRunning =
|
||||
liveProvider !== undefined &&
|
||||
(updatingProviderDrivers.has(liveProvider.driver) ||
|
||||
serverProviders.some(
|
||||
(provider) =>
|
||||
provider.driver === liveProvider.driver && isProviderUpdateActive(provider),
|
||||
));
|
||||
const canRunInlineCompatibilityUpdate =
|
||||
showInlineCompatibilityUpdateButton &&
|
||||
liveProvider !== undefined &&
|
||||
!updatingProviderDrivers.has(liveProvider.driver);
|
||||
const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
|
||||
hiddenModels: [],
|
||||
modelOrder: [],
|
||||
@@ -1819,6 +1388,19 @@ export function ProviderSettingsPanel() {
|
||||
: undefined
|
||||
}
|
||||
isUpdating={showInlineUpdateButton ? isDriverUpdateRunning : undefined}
|
||||
onRunCompatibilityUpdate={
|
||||
showInlineCompatibilityUpdateButton && liveProvider
|
||||
? () => {
|
||||
if (!canRunInlineCompatibilityUpdate) {
|
||||
return;
|
||||
}
|
||||
void runProviderCompatibilityUpdate(liveProvider);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
isCompatibilityUpdating={
|
||||
showInlineCompatibilityUpdateButton ? isCompatibilityUpdateRunning : undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -10,11 +10,7 @@ import type {
|
||||
VcsDriverKind,
|
||||
VcsDiscoveryItem,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getBackgroundActivityBaseProfile,
|
||||
getBackgroundActivityPresetSettings,
|
||||
resolveServerBackgroundActivitySettings,
|
||||
} from "@t3tools/shared/backgroundActivitySettings";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
|
||||
import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
|
||||
import { cn } from "../../lib/utils";
|
||||
@@ -54,12 +50,6 @@ import {
|
||||
} from "../Icons";
|
||||
import { RedactedSensitiveText } from "./RedactedSensitiveText";
|
||||
import { SettingResetButton, SettingsPageContainer, SettingsSection } from "./settingsLayout";
|
||||
import {
|
||||
BackgroundPolicyTooltip,
|
||||
backgroundActivityOverrideSettings,
|
||||
durationToSeconds,
|
||||
normalizeIntervalSeconds as normalizeFetchIntervalSeconds,
|
||||
} from "./backgroundActivityUtils";
|
||||
|
||||
const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
|
||||
versionControlSystems: [],
|
||||
@@ -81,6 +71,17 @@ const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
|
||||
const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
|
||||
const GIT_FETCH_INTERVAL_STEP_SECONDS = 5;
|
||||
|
||||
function durationToSeconds(duration: Duration.Duration): number {
|
||||
return Math.round(Duration.toMillis(duration) / 1_000);
|
||||
}
|
||||
|
||||
function normalizeFetchIntervalSeconds(value: number | null): number {
|
||||
if (value === null || !Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
return Math.max(0, Math.round(value));
|
||||
}
|
||||
|
||||
function optionLabel(value: Option.Option<string>): string | null {
|
||||
return Option.getOrNull(value);
|
||||
}
|
||||
@@ -290,16 +291,11 @@ function DiscoveryItemRow({
|
||||
}
|
||||
|
||||
function GitFetchIntervalSettings() {
|
||||
const settings = useSettings();
|
||||
const automaticGitFetchInterval = useSettings((settings) => settings.automaticGitFetchInterval);
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
|
||||
const automaticGitFetchIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.automaticGitFetchInterval,
|
||||
);
|
||||
const automaticGitFetchIntervalSeconds = durationToSeconds(automaticGitFetchInterval);
|
||||
const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
|
||||
getBackgroundActivityPresetSettings(
|
||||
getBackgroundActivityBaseProfile(settings.backgroundActivity),
|
||||
).automaticGitFetchInterval,
|
||||
DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
|
||||
);
|
||||
const canResetFetchInterval =
|
||||
automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
|
||||
@@ -310,11 +306,6 @@ function GitFetchIntervalSettings() {
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="flex min-w-0 items-center gap-1">
|
||||
<span className="text-xs font-medium text-foreground">Fetch interval</span>
|
||||
<BackgroundPolicyTooltip>
|
||||
This interval is configured for Git only. The shared Background activity policy still
|
||||
decides whether Git refreshes may run when the timer fires. Custom intervals appear as
|
||||
Advanced in General settings.
|
||||
</BackgroundPolicyTooltip>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex size-5 shrink-0 items-center justify-center transition-opacity",
|
||||
@@ -326,11 +317,9 @@ function GitFetchIntervalSettings() {
|
||||
<SettingResetButton
|
||||
label="fetch interval"
|
||||
onClick={() =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
automaticGitFetchInterval: undefined,
|
||||
}),
|
||||
)
|
||||
updateSettings({
|
||||
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
@@ -349,11 +338,9 @@ function GitFetchIntervalSettings() {
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
|
||||
}),
|
||||
)
|
||||
updateSettings({
|
||||
automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
|
||||
})
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import { InfoIcon } from "lucide-react";
|
||||
import * as Duration from "effect/Duration";
|
||||
import type { BackgroundActivitySettings } from "@t3tools/contracts";
|
||||
import { getBackgroundActivityBaseProfile } from "@t3tools/shared/backgroundActivitySettings";
|
||||
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
export type BackgroundActivityOverridePatch = Partial<{
|
||||
[K in keyof BackgroundActivitySettings["overrides"]]:
|
||||
| BackgroundActivitySettings["overrides"][K]
|
||||
| undefined;
|
||||
}>;
|
||||
|
||||
export function durationToSeconds(duration: Duration.Duration): number {
|
||||
return Math.round(Duration.toMillis(duration) / 1_000);
|
||||
}
|
||||
|
||||
export function normalizeIntervalSeconds(value: number | null): number {
|
||||
if (value === null || !Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
return Math.max(0, Math.round(value));
|
||||
}
|
||||
|
||||
export function backgroundActivityOverrideSettings(
|
||||
current: BackgroundActivitySettings,
|
||||
overrides: BackgroundActivityOverridePatch,
|
||||
) {
|
||||
const nextOverrides: BackgroundActivityOverridePatch = {
|
||||
...current.overrides,
|
||||
...overrides,
|
||||
};
|
||||
for (const [key, value] of Object.entries(nextOverrides)) {
|
||||
if (value === undefined) {
|
||||
delete nextOverrides[key as keyof typeof nextOverrides];
|
||||
}
|
||||
}
|
||||
return {
|
||||
backgroundActivity: {
|
||||
schemaVersion: 1 as const,
|
||||
profile: "custom" as const,
|
||||
baseProfile: getBackgroundActivityBaseProfile(current),
|
||||
overrides: nextOverrides as BackgroundActivitySettings["overrides"],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function BackgroundPolicyTooltip({ children }: { readonly children: string }) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex size-5 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground"
|
||||
aria-label="Background policy details"
|
||||
>
|
||||
<InfoIcon className="size-3.5" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-72">
|
||||
{children}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getProviderCompatibilityAdvisoryPresentation,
|
||||
getProviderCompatibilityUpdateCommand,
|
||||
} from "./providerStatus";
|
||||
|
||||
describe("getProviderCompatibilityAdvisoryPresentation", () => {
|
||||
it("hides supported compatibility advisories", () => {
|
||||
expect(
|
||||
getProviderCompatibilityAdvisoryPresentation({
|
||||
status: "supported",
|
||||
severity: "info",
|
||||
currentVersion: "0.129.0",
|
||||
message: null,
|
||||
recommendedRange: ">=0.129.0",
|
||||
ranges: [],
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("presents broken compatibility advisories strongly", () => {
|
||||
expect(
|
||||
getProviderCompatibilityAdvisoryPresentation({
|
||||
status: "broken",
|
||||
severity: "error",
|
||||
currentVersion: "0.128.0",
|
||||
message: "Known incompatible.",
|
||||
recommendedRange: ">=0.129.0",
|
||||
ranges: [],
|
||||
}),
|
||||
).toEqual({
|
||||
title: "Incompatible provider version",
|
||||
detail: "Known incompatible.",
|
||||
updateCommand: null,
|
||||
canUpdate: false,
|
||||
emphasis: "strong",
|
||||
});
|
||||
});
|
||||
|
||||
it("derives targeted compatibility update commands from package install commands", () => {
|
||||
expect(
|
||||
getProviderCompatibilityUpdateCommand({
|
||||
compatibilityAdvisory: {
|
||||
status: "broken",
|
||||
severity: "error",
|
||||
currentVersion: "0.128.0",
|
||||
message: "Known incompatible.",
|
||||
recommendedRange: ">=0.129.0",
|
||||
recommendedVersion: "0.129.0",
|
||||
ranges: [],
|
||||
},
|
||||
versionAdvisory: {
|
||||
status: "behind_latest",
|
||||
currentVersion: "0.128.0",
|
||||
latestVersion: "0.130.0",
|
||||
checkedAt: "2026-05-13T00:00:00.000Z",
|
||||
message: "Update available.",
|
||||
updateCommand: "vp i -g @openai/codex",
|
||||
canUpdate: true,
|
||||
},
|
||||
}),
|
||||
).toBe("vp i -g @openai/[email protected]");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { ServerProvider, ServerProviderVersionAdvisory } from "@t3tools/contracts";
|
||||
import type {
|
||||
ServerProvider,
|
||||
ServerProviderCompatibilityAdvisory,
|
||||
ServerProviderVersionAdvisory,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* Visual treatment for each server-reported provider status. Centralized so
|
||||
@@ -115,3 +119,85 @@ export function getProviderVersionAdvisoryPresentation(
|
||||
emphasis: "normal" as const,
|
||||
};
|
||||
}
|
||||
|
||||
function makeTargetedUpdateCommand(input: {
|
||||
readonly updateCommand: string | null | undefined;
|
||||
readonly recommendedVersion: string | null | undefined;
|
||||
}): string | null {
|
||||
if (!input.updateCommand || !input.recommendedVersion) {
|
||||
return null;
|
||||
}
|
||||
if (!input.updateCommand.includes("@latest")) {
|
||||
const packageNameMatch = input.updateCommand.match(
|
||||
/(?:^|\s)(@[^\s]+\/[^\s@]+|[^\s@]+)(?=\s*$)/,
|
||||
);
|
||||
if (!packageNameMatch?.[1]) {
|
||||
return null;
|
||||
}
|
||||
return input.updateCommand.replace(
|
||||
packageNameMatch[1],
|
||||
`${packageNameMatch[1]}@${input.recommendedVersion}`,
|
||||
);
|
||||
}
|
||||
return input.updateCommand.replace("@latest", `@${input.recommendedVersion}`);
|
||||
}
|
||||
|
||||
export function getProviderCompatibilityUpdateCommand(
|
||||
provider: Pick<ServerProvider, "compatibilityAdvisory" | "versionAdvisory"> | null | undefined,
|
||||
): string | null {
|
||||
const compatibilityAdvisory = provider?.compatibilityAdvisory;
|
||||
if (!compatibilityAdvisory || compatibilityAdvisory.status === "supported") {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
compatibilityAdvisory.updateCommand ??
|
||||
makeTargetedUpdateCommand({
|
||||
updateCommand: provider.versionAdvisory?.updateCommand,
|
||||
recommendedVersion: compatibilityAdvisory.recommendedVersion,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function canRunProviderCompatibilityUpdate(
|
||||
provider: Pick<ServerProvider, "compatibilityAdvisory" | "versionAdvisory"> | null | undefined,
|
||||
): boolean {
|
||||
const compatibilityAdvisory = provider?.compatibilityAdvisory;
|
||||
if (!compatibilityAdvisory || compatibilityAdvisory.status === "supported") {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
compatibilityAdvisory.canUpdate === true ||
|
||||
(provider?.versionAdvisory?.canUpdate === true &&
|
||||
getProviderCompatibilityUpdateCommand(provider) !== null)
|
||||
);
|
||||
}
|
||||
|
||||
export function getProviderCompatibilityAdvisoryPresentation(
|
||||
advisory: ServerProviderCompatibilityAdvisory | undefined,
|
||||
): {
|
||||
readonly title: string;
|
||||
readonly detail: string;
|
||||
readonly updateCommand: string | null;
|
||||
readonly canUpdate: boolean;
|
||||
readonly emphasis: "normal" | "strong";
|
||||
} | null {
|
||||
if (!advisory || advisory.status === "supported") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const recommendedTarget = advisory.recommendedVersion ?? advisory.recommendedRange;
|
||||
const recommended = recommendedTarget ? ` Recommended: ${recommendedTarget}.` : "";
|
||||
const fallback =
|
||||
advisory.status === "unknown"
|
||||
? `Compatibility unknown.${recommended}`
|
||||
: `This provider harness is outside the supported range.${recommended}`;
|
||||
|
||||
return {
|
||||
title:
|
||||
advisory.status === "broken" ? "Incompatible provider version" : "Provider version warning",
|
||||
detail: advisory.message ?? fallback,
|
||||
updateCommand: advisory.updateCommand ?? null,
|
||||
canUpdate: advisory.canUpdate === true,
|
||||
emphasis: advisory.severity === "error" ? "strong" : "normal",
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
|
||||